Files
tern-web/src/lib/api.ts
T
Mateusz PstruchaandClaude Opus 5.5 789b550301
CI / build (push) Successful in 17s
Add Junk, spam actions and infinite scroll
Junk joins the system views; Report spam / Not spam come from the
toolbar, menu and `!`; messages show their spam score as a badge. Rules
gains an Add spam filter preset — score over 5 → Junk, placed first and
stopping later rules — and the editor offers only numeric comparisons
for spam score.

Conversation lists now load older pages. The list previously only ever
showed the newest 50 conversations, leaving older mail unreachable even
though the API returned a cursor. Pages load as the end scrolls into
view, when j walks past the end, or via a Load older button that also
covers keyboard use. Refreshing after an action re-reads as many rows as
were loaded, so a deep scroll doesn't collapse back to one page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 15:32:35 +02:00

297 lines
8.4 KiB
TypeScript

// Thin client for tern-server's REST API (server-architecture-spec.md §4).
// Deliberately minimal for this scaffold phase — just enough to prove the
// two-pane shell can talk to the server once accounts/messages exist.
const SESSION_KEY = 'tern-session-token';
export function getSessionToken(): string | null {
return localStorage.getItem(SESSION_KEY);
}
export function setSessionToken(token: string): void {
localStorage.setItem(SESSION_KEY, token);
}
export function clearSessionToken(): void {
localStorage.removeItem(SESSION_KEY);
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const token = getSessionToken();
const res = await fetch(`/api${path}`, {
...init,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...init?.headers,
},
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? `request failed: ${res.status}`);
}
return res.json() as Promise<T>;
}
export interface Folder {
id: string;
name: string;
/** System folders (Archive, Junk) have a role; the user's own have null. */
role: 'archive' | 'junk' | null;
}
export interface MessageSummary {
id: string;
subject: string | null;
from_addr: string | null;
from_name: string | null;
to_addrs: string[];
cc_addrs: string[];
sent_at: string | null;
thread_id: string;
flags: string[];
/** 'imap' for received mail, 'sent' for mail sent from Tern. */
source: 'imap' | 'sent';
deleted_at: string | null;
/** From the spam filter's headers; null means the filter didn't flag it. */
spam_score: number | null;
}
export interface MessageBody {
message_id: string;
text_body: string | null;
html_body: string | null;
}
/** A message plus its body, as returned by the thread endpoint. */
export interface MessageDetail extends MessageSummary {
body: MessageBody | null;
}
export interface ThreadSummary {
thread_id: string;
subject: string | null;
last_from: string | null;
last_message_at: string | null;
message_count: number;
unread_count: number;
has_attachments: boolean;
tag_ids: string[];
/** In Trash: when this conversation is deleted for good. */
purges_at: string | null;
}
/** Flags are stored in IMAP wire format, so unread is the absence of \Seen. */
export function isUnread(flags: string[]): boolean {
return !flags.includes('\\Seen');
}
export function listFolders(): Promise<Folder[]> {
return request('/folders');
}
/** Which slice of the mailbox a thread list shows. */
export type MailView =
| { kind: 'inbox' }
| { kind: 'all' }
| { kind: 'sent' }
| { kind: 'trash' }
| { kind: 'junk' }
| { kind: 'folder'; id: string }
| { kind: 'tag'; id: string };
/** `cursor` is the opaque `next_cursor` from the previous page; null there means no more pages. */
export function listThreads(view: MailView, cursor?: string, limit?: number): Promise<{
threads: ThreadSummary[];
next_cursor: string | null;
}> {
const query = new URLSearchParams({ view: view.kind });
if (view.kind === 'folder') query.set('folder_id', view.id);
if (view.kind === 'tag') query.set('tag_id', view.id);
if (cursor) query.set('before', cursor);
if (limit) query.set('limit', String(limit));
return request(`/threads?${query}`);
}
export function getThread(threadId: string): Promise<MessageDetail[]> {
return request(`/threads/${threadId}`);
}
/**
* Delta endpoint (§3.8). WebSocket push is a later phase, so the client
* polls this to notice new mail while the tab is open.
*/
export function pollEvents(since: string | null): Promise<{
changed_messages: MessageSummary[];
cursor: string;
}> {
return request(`/events${since ? `?since=${encodeURIComponent(since)}` : ''}`);
}
export async function login(username: string, password: string): Promise<void> {
const res = await request<{ token: string }>('/auth/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
});
setSessionToken(res.token);
}
export interface Account {
id: string;
name: string;
username: string;
email_address: string | null;
display_name: string | null;
}
export type OutboxStatus = 'draft' | 'pending' | 'sending' | 'sent' | 'failed';
export interface OutboxItem {
id: string;
account_id: string;
status: OutboxStatus;
to_addrs: string[];
cc_addrs: string[];
bcc_addrs: string[];
subject: string;
text_body: string;
thread_id: string | null;
attempts: number;
last_error: string | null;
next_attempt_at: string | null;
updated_at: string;
}
export interface ComposeFields {
to: string[];
cc: string[];
bcc: string[];
subject: string;
text_body: string;
}
export function listAccounts(): Promise<Account[]> {
return request('/accounts');
}
export function markThreadRead(threadId: string): Promise<{ messages: number }> {
return request(`/threads/${threadId}/read`, { method: 'POST' });
}
export function listOutbox(): Promise<OutboxItem[]> {
return request('/outbox');
}
export function createOutboxItem(
fields: ComposeFields & {
account_id?: string;
reply_to_message_id?: string;
send: boolean;
},
): Promise<OutboxItem> {
return request('/outbox', { method: 'POST', body: JSON.stringify(fields) });
}
export function updateDraft(id: string, fields: ComposeFields): Promise<OutboxItem> {
return request(`/outbox/${id}`, { method: 'PUT', body: JSON.stringify(fields) });
}
export function sendOutboxItem(id: string): Promise<OutboxItem> {
return request(`/outbox/${id}/send`, { method: 'POST' });
}
export function deleteOutboxItem(id: string): Promise<{ ok: boolean }> {
return request(`/outbox/${id}`, { method: 'DELETE' });
}
export interface Tag {
id: string;
name: string;
color: string | null;
}
/** Same shape as rule actions — manual actions and rules share one applier. */
export type Action =
| { type: 'tag'; tag_id: string }
| { type: 'untag'; tag_id: string }
| { type: 'move'; folder_id: string | null }
| { type: 'archive' }
| { type: 'junk' }
| { type: 'mark_read' }
| { type: 'mark_unread' }
| { type: 'delete' }
| { type: 'restore' };
export type RuleField = 'from' | 'to' | 'cc' | 'recipients' | 'subject' | 'body' | 'header' | 'spam_score';
export type RuleOp = 'contains' | 'equals' | 'matches' | 'exists' | 'greater_than' | 'less_than';
export interface RuleTest {
field: RuleField;
header?: string;
op: RuleOp;
value: string;
negate: boolean;
}
export interface Rule {
id: string;
name: string;
conditions: { match: 'all' | 'any'; tests: RuleTest[] };
actions: Action[];
enabled: boolean;
/** Skip lower-priority rules once this one matches. */
stop_after_match: boolean;
priority: number;
}
export type RuleInput = Omit<Rule, 'id' | 'priority'>;
export function threadActions(threadId: string, actions: Action[]): Promise<{ messages: number }> {
return request(`/threads/${threadId}/actions`, { method: 'POST', body: JSON.stringify({ actions }) });
}
export function listTags(): Promise<Tag[]> {
return request('/tags');
}
export function createTag(name: string, color: string | null): Promise<Tag> {
return request('/tags', { method: 'POST', body: JSON.stringify({ name, color }) });
}
export function deleteTag(id: string): Promise<{ ok: boolean }> {
return request(`/tags/${id}`, { method: 'DELETE' });
}
export function createFolder(name: string): Promise<Folder> {
return request('/folders', { method: 'POST', body: JSON.stringify({ name }) });
}
export function deleteFolder(id: string): Promise<{ ok: boolean }> {
return request(`/folders/${id}`, { method: 'DELETE' });
}
export function listRules(): Promise<Rule[]> {
return request('/rules');
}
export function createRule(rule: RuleInput): Promise<Rule> {
return request('/rules', { method: 'POST', body: JSON.stringify(rule) });
}
export function updateRule(id: string, rule: RuleInput): Promise<Rule> {
return request(`/rules/${id}`, { method: 'PUT', body: JSON.stringify(rule) });
}
export function deleteRule(id: string): Promise<{ ok: boolean }> {
return request(`/rules/${id}`, { method: 'DELETE' });
}
/** Applies a rule to existing mail — what "Run now" does. */
export function runRule(id: string): Promise<{ scanned: number; matched: number }> {
return request(`/rules/${id}/run`, { method: 'POST' });
}
export function reorderRules(ids: string[]): Promise<Rule[]> {
return request('/rules/reorder', { method: 'POST', body: JSON.stringify({ ids }) });
}