Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add Email Archiving, Sent Mail, and a Calendar Tab (#1324)

Eve Bouffard03a793fa03ae
diff --git a/.gitignore b/.gitignore
index 4a1069719..9a7fba0b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
node_modules
data/
+plugins/web-ui/public/*.local.json
*.log
.DS_Store
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index 13125deff..ac9102974 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1496,6 +1496,15 @@ const apiRoutes: readonly WebRoute[] = [
return relayCore(res, "GET", `/v1/loops/inbox?principalId=${encodeURIComponent(user)}`);
},
},
+ {
+ method: "POST",
+ path: "/api/inbox/sent-chat",
+ handle: async ({ req, res, user }) => {
+ if (!isInboxUser(user)) return json(res, 403, { error: "forbidden" });
+ res.setHeader("Cache-Control", "no-store");
+ return relayCore(res, "POST", "/v1/loops/inbox/sent-chat", await readBody(req));
+ },
+ },
{
method: "POST",
path: "/api/inbox/sync-cron",
@@ -2480,6 +2489,29 @@ const apiRoutes: readonly WebRoute[] = [
return relay(res, r);
},
},
+ {
+ method: "GET",
+ path: "/api/inbox/sent/:messageId",
+ handle: async ({ res, user, params }) => {
+ if (!isInboxUser(user)) return json(res, 403, { error: "forbidden" });
+ res.setHeader("Cache-Control", "no-store");
+ return relayCore(res, "GET", `/v1/connectors/gmail/sent/${encodeURIComponent(params.messageId!)}`);
+ },
+ },
+ {
+ method: "GET",
+ path: "/api/inbox/sent",
+ handle: async ({ res, user, url }) => {
+ if (!isInboxUser(user)) return json(res, 403, { error: "forbidden" });
+ const params = new URLSearchParams();
+ for (const key of ["pageToken", "accountType"]) {
+ const value = url.searchParams.get(key);
+ if (value) params.set(key, value);
+ }
+ res.setHeader("Cache-Control", "no-store");
+ return relayCore(res, "GET", `/v1/connectors/gmail/sent?${params}`);
+ },
+ },
{
method: "GET",
path: "/api/loops",
diff --git a/plugins/web-ui/src/calendar.ts b/plugins/web-ui/src/calendar.ts
new file mode 100644
index 000000000..e0e351088
--- /dev/null
+++ b/plugins/web-ui/src/calendar.ts
@@ -0,0 +1,18 @@
+import { html, render } from "lit";
+import { appState, replacePanePreservingFocus } from "./shell";
+
+export function renderCalendar(): void {
+ if (appState.currentView !== "calendar" || !appState.mainEl) return;
+ const host = document.createElement("div");
+ host.className = "pane content-wide-page";
+ render(
+ html`
+ <div class="pane-head">
+ <h1 class="pane-title">Calendar</h1>
+ </div>
+ <div class="empty compact">Coming soon.</div>
+ `,
+ host,
+ );
+ replacePanePreservingFocus(host);
+}
diff --git a/plugins/web-ui/src/document-title.ts b/plugins/web-ui/src/document-title.ts
index 8b54a7f7a..e7cd2e82f 100644
--- a/plugins/web-ui/src/document-title.ts
+++ b/plugins/web-ui/src/document-title.ts
@@ -16,6 +16,7 @@ export const PRODUCT_TITLE = "QM · Web";
const VIEW_TITLES: Record<View, string> = {
chats: "Chats",
inbox: "Inbox",
+ calendar: "Calendar",
contexts: "Projects",
crons: "Crons",
loops: "Loops",
diff --git a/plugins/web-ui/src/draft-review.ts b/plugins/web-ui/src/draft-review.ts
deleted file mode 100644
index 31d63af04..000000000
--- a/plugins/web-ui/src/draft-review.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-import { html, nothing, render, type TemplateResult } from "lit";
-import { CheckCheck, ChevronDown, ChevronRight, Hash, Mail, PenLine } from "lucide";
-import { createConversation, disposeConversation, ensureDeliveryStream } from "./conversations";
-import type { Conversation } from "./conv-types";
-import type { DensityTier } from "./density";
-import {
- attachInboxSurface,
- contextTpl,
- draftEditorTpl,
- handledNoteTpl,
- inboxOpenCount,
- inboxState,
- inboxViewName,
- itemsFor,
- persistDraft,
- refreshInbox,
- selectInboxView,
- type InboxItem,
-} from "./inbox";
-import { openSessionInto, refreshSessions, sessionsReady, sessionsState } from "./sessions";
-import { switchView } from "./shell";
-import { appState, can } from "./shell-state";
-import { registerPaneKind } from "./pane-kinds";
-import { exitSplitIfActive, splitState } from "./split";
-import { icon, relTime } from "./ui";
-
-interface SteerPanel {
- sessionId: string;
- host: HTMLElement;
- conversation: Conversation;
- open: boolean;
- working: boolean;
-}
-
-interface ReviewSurface {
- host: HTMLElement;
- viewId: string;
- density: () => DensityTier;
- tab: "open" | "handled";
- selectedId: string | null;
- steer: SteerPanel | null;
-}
-
-function mountDraftReviewPane(opts: {
- host: HTMLElement;
- viewId: string;
- density: () => DensityTier;
- onDensityChange: (handler: () => void) => void;
-}): { dispose(): void } {
- const surface: ReviewSurface = {
- host: opts.host,
- viewId: opts.viewId,
- density: opts.density,
- tab: "open",
- selectedId: null,
- steer: null,
- };
- opts.host.classList.add("draft-review-pane-host");
- opts.onDensityChange(() => drawSurface(surface));
- const detach = attachInboxSurface({
- redraw: () => drawSurface(surface),
- visible: () => surface.host.isConnected,
- });
- drawSurface(surface);
- void refreshInbox({ ifStaleMs: 30_000, silent: true });
- return {
- dispose() {
- detach();
- dropSteer(surface);
- opts.host.classList.remove("draft-review-pane-host");
- },
- };
-}
-
-function reviewRows(surface: ReviewSurface): InboxItem[] {
- const rows = [...itemsFor(surface.viewId, surface.tab)];
- const at = (i: InboxItem): number =>
- surface.tab === "open" ? i.receivedAt : (i.sentAt ?? i.dismissedAt ?? i.receivedAt);
- return rows.sort((a, b) => at(b) - at(a));
-}
-
-function drawSurface(surface: ReviewSurface): void {
- if (!surface.host.isConnected) return;
- const rows = reviewRows(surface);
- const item = rows.find((i) => i.id === surface.selectedId) ?? rows[0] ?? null;
- surface.selectedId = item?.id ?? null;
- syncSteer(surface, item);
- render(surfaceTpl(surface, rows, item), surface.host);
-}
-
-function pickItem(surface: ReviewSurface, item: InboxItem): void {
- const previous = inboxState.items.find((i) => i.id === surface.selectedId);
- if (previous && previous.id !== item.id) void persistDraft(previous);
- surface.selectedId = item.id;
- drawSurface(surface);
-}
-
-function syncSteer(surface: ReviewSurface, item: InboxItem | null): void {
- const sessionId = item?.status === "open" ? (item.draftSessionId ?? null) : null;
- if (!sessionId) {
- dropSteer(surface);
- return;
- }
- if (surface.steer?.sessionId === sessionId) return;
- dropSteer(surface);
- const host = document.createElement("div");
- host.className = "mini-convo-body";
- host.dataset.density = "compact";
- const steer: SteerPanel = {
- sessionId,
- host,
- conversation: null as unknown as Conversation,
- open: true,
- working: false,
- };
- steer.conversation = createConversation({
- pane: true,
- ownsUrl: false,
- container: () => host,
- claimContainer: () => host,
- visible: () => splitState.active && appState.currentView === "chats" && surface.host.isConnected,
- density: () => "compact" as DensityTier,
- onDensityChange: () => {},
- ensureDeliveryStream,
- onState: (state) => {
- if (steer.working && !state.working) void refreshInbox({ silent: true });
- steer.working = state.working;
- },
- });
- surface.steer = steer;
- void mountSteerSession(surface, steer);
-}
-
-function dropSteer(surface: ReviewSurface): void {
- if (!surface.steer) return;
- disposeConversation(surface.steer.conversation);
- surface.steer = null;
-}
-
-async function mountSteerSession(surface: ReviewSurface, steer: SteerPanel): Promise<void> {
- steer.conversation.mountLoadingPane();
- const find = (): (typeof sessionsState.list)[number] | undefined =>
- sessionsState.list.find((s) => s.id === steer.sessionId);
- let session = find();
- if (!session) {
- await sessionsReady();
- session = find();
- }
- if (!session) {
- try {
- await refreshSessions({ silent: true });
- } catch {
- void 0;
- }
- session = find();
- }
- if (surface.steer !== steer) return;
- if (!session) {
- render(html`<div class="mini-convo-missing">The drafting session isn't available anymore.</div>`, steer.host);
- return;
- }
- await openSessionInto(steer.conversation, session);
-}
-
-function toggleSteer(surface: ReviewSurface): void {
- const steer = surface.steer;
- if (!steer) return;
- steer.open = !steer.open;
- drawSurface(surface);
- if (steer.open) steer.conversation.redraw();
-}
-
-function segTpl(surface: ReviewSurface, open: number, handled: number): TemplateResult {
- const btn = (tab: ReviewSurface["tab"], label: string, count: number): TemplateResult => html`
- <button
- class="rv-seg-btn ${surface.tab === tab ? "on" : ""}"
- type="button"
- role="tab"
- aria-selected=${surface.tab === tab ? "true" : "false"}
- @click=${() => {
- surface.tab = tab;
- drawSurface(surface);
- }}
- >
- <span>${label}</span><span class="rv-seg-count">${count}</span>
- </button>
- `;
- return html`<div class="rv-seg" role="tablist" aria-label="Draft review">
- ${btn("open", "Needs you", open)} ${btn("handled", "Handled", handled)}
- </div>`;
-}
-
-function rowTpl(surface: ReviewSurface, item: InboxItem): TemplateResult {
- const gmail = item.source === "gmail";
- const active = surface.selectedId === item.id;
- return html`
- <button class="rv-row ${active ? "active" : ""}" type="button" @click=${() => pickItem(surface, item)}>
- <span class="rv-glyph">${icon(gmail ? Mail : Hash, 13)}</span>
- <span class="rv-body">
- <span class="rv-l1">
- <span class="rv-from">${gmail ? item.from : (item.slack?.channelLabel ?? item.title)}</span>
- <span class="rv-time"
- >${relTime(
- surface.tab === "open"
- ? item.receivedAt
- : (item.sentAt ?? item.dismissedAt ?? item.repliedAt ?? item.receivedAt),
- )}</span
- >
- </span>
- <span class="rv-l2">${gmail ? item.title : item.from}</span>
- </span>
- ${
- item.status === "open" && item.draft
- ? html`<span class="rv-drafted" title="A reply is drafted and ready">${icon(CheckCheck, 12)}</span>`
- : nothing
- }
- </button>
- `;
-}
-
-function steerTpl(surface: ReviewSurface, item: InboxItem): TemplateResult | typeof nothing {
- const steer = surface.steer;
- if (!steer || steer.sessionId !== item.draftSessionId) return nothing;
- return html`<div class="mini-convo">
- <button
- class="mini-convo-head"
- type="button"
- aria-expanded=${steer.open ? "true" : "false"}
- @click=${() => toggleSteer(surface)}
- >
- <span class="mini-convo-caret">${icon(steer.open ? ChevronDown : ChevronRight, 12)}</span>
- <span class="mini-convo-title">Drafting session</span>
- <span class="mini-convo-sub">steer it and the draft rewrites in place</span>
- <span class="mini-convo-spacer"></span>
- <span class="mini-convo-open">${steer.open ? "Hide" : "Resume"}</span>
- </button>
- ${steer.open ? steer.host : nothing}
- </div>`;
-}
-
-function detailTpl(surface: ReviewSurface, item: InboxItem | null): TemplateResult {
- if (!item) {
- return html`<div class="empty compact rv-empty-detail">
- ${surface.tab === "open" ? "Nothing is waiting on you. Clear water ahead." : "Nothing handled yet."}
- </div>`;
- }
- const gmail = item.source === "gmail";
- return html`
- <div class="rv-detail-head">
- <span class="rv-detail-title">${gmail ? item.title : (item.slack?.channelLabel ?? item.title)}</span>
- <span class="rv-detail-from">${item.from}${item.fromDetail ? ` · ${item.fromDetail}` : ""}</span>
- </div>
- ${contextTpl(item)} ${item.status === "open" ? draftEditorTpl(item) : handledNoteTpl(item)}
- ${item.status === "open" ? steerTpl(surface, item) : nothing}
- `;
-}
-
-function surfaceTpl(surface: ReviewSurface, rows: InboxItem[], item: InboxItem | null): TemplateResult {
- const density = surface.density();
- const compact = density !== "full";
- const open = itemsFor(surface.viewId, "open").length;
- const handled = itemsFor(surface.viewId, "handled").length;
- return html`
- <div class="draft-review-surface ${compact ? "compact" : ""}" data-density=${density}>
- <div class="rv-side">
- ${segTpl(surface, open, handled)}
- <div class="rv-scroll">
- ${
- rows.length
- ? rows.map((row) => rowTpl(surface, row))
- : html`<div class="rv-empty">${surface.tab === "open" ? "Nothing needs you." : "Nothing here yet."}</div>`
- }
- </div>
- </div>
- <div class="rv-main">${detailTpl(surface, item)}</div>
- </div>
- `;
-}
-
-registerPaneKind({
- paramsKey: "draftReview",
- glyph: PenLine,
- title: (id) => (id === "all" ? "Draft review" : `${inboxViewName(id)} drafts`),
- badge: (id) => (can("inbox") ? inboxOpenCount(id) : 0),
- mount: ({ host, id, density, onDensityChange }) => {
- if (!can("inbox")) {
- render(html`<div class="empty compact">This pane kind is not available.</div>`, host);
- return { dispose: () => render(nothing, host) };
- }
- return mountDraftReviewPane({ host, viewId: id, density, onDensityChange });
- },
- maximize: (id) => {
- exitSplitIfActive();
- selectInboxView(id);
- switchView("inbox");
- },
-});
diff --git a/plugins/web-ui/src/inbox.ts b/plugins/web-ui/src/inbox.ts
index 8394e3d19..6760bd68d 100644
--- a/plugins/web-ui/src/inbox.ts
+++ b/plugins/web-ui/src/inbox.ts
@@ -1,5 +1,22 @@
+import {
+ ensureSentMail,
+ openSentEmail,
+ openSentEmailById,
+ isSentMailEmpty,
+ isSentMailLoading,
+ loadSentMail,
+ resetSentMail,
+ resetSelectedSentEmail,
+ selectedSentEmail,
+ sentEmailPageTpl,
+ sentChatTpl,
+ selectedSentChat,
+ updateSentChat,
+ sentMailTpl,
+} from "./sent-mail";
import { html, nothing, render, type TemplateResult } from "lit";
import {
+ Archive,
ArrowUp,
ArrowUpRight,
CheckCheck,
@@ -25,7 +42,7 @@ import { splitMentions } from "./linkify";
import { splitSlackWire } from "./slack-text";
import { listBackLink } from "./list-page";
import { registerPaneKind } from "./pane-kinds";
-import { beginPaneKindDrag, endPaneDrag, exitSplitIfActive, notifyPanesChanged } from "./split";
+import { exitSplitIfActive, notifyPanesChanged } from "./split";
import { tip } from "./tooltip";
import { brandName, icon, initials, relTime, slackMark, workingWave } from "./ui";
@@ -69,6 +86,7 @@ export interface LedgerItem {
}
export interface InboxItem {
+ sentChat?: boolean;
id: string;
loopId: string;
source: InboxSource;
@@ -116,8 +134,22 @@ const VIEWS: InboxView[] = [
{ id: "all", name: "All", sources: ["gmail", "slack"] },
{ id: "gmail", name: "Email", sources: ["gmail"] },
{ id: "slack", name: "Slack", sources: ["slack"] },
+ { id: "sent", name: "Sent", sources: [] },
];
+function isInboxViewId(value: string | null): value is string {
+ return value !== null && VIEWS.some((view) => view.id === value);
+}
+
+function inboxViewIdForSegment(segment: string | null): string | null {
+ if (segment === "email") return "gmail";
+ return isInboxViewId(segment) ? segment : null;
+}
+
+function inboxViewSegment(viewId: string): string {
+ return viewId === "gmail" ? "email" : viewId;
+}
+
export const inboxState = {
items: [] as InboxItem[],
loopId: null as string | null,
@@ -140,6 +172,71 @@ const acting = new Set<string>();
const chatting = new Set<string>();
const chatDrafts = new Map<string, string>();
+let archiveToastHost: HTMLDivElement | null = null;
+let archiveToastTimer: ReturnType<typeof setTimeout> | undefined;
+
+function closeArchiveToast(): void {
+ clearTimeout(archiveToastTimer);
+ archiveToastHost?.remove();
+ archiveToastHost = null;
+}
+
+function showArchiveToast(item: InboxItem): void {
+ closeArchiveToast();
+ const host = document.createElement("div");
+ archiveToastHost = host;
+ document.body.append(host);
+ let busy = false;
+ const schedule = (): void => {
+ clearTimeout(archiveToastTimer);
+ if (!busy && !host.matches(":hover") && !host.contains(document.activeElement)) {
+ archiveToastTimer = setTimeout(() => {
+ if (archiveToastHost === host) closeArchiveToast();
+ }, 8000);
+ }
+ };
+ const draw = (): void => {
+ render(
+ html`<div
+ class="action-toast"
+ role="status"
+ @mouseenter=${() => clearTimeout(archiveToastTimer)}
+ @mouseleave=${schedule}
+ @focusin=${() => clearTimeout(archiveToastTimer)}
+ @focusout=${() => queueMicrotask(schedule)}
+ >
+ ${icon(Archive, 16)}
+ <span>Dismissed from inbox</span>
+ <button
+ type="button"
+ ?disabled=${busy}
+ @click=${async () => {
+ busy = true;
+ clearTimeout(archiveToastTimer);
+ draw();
+ const restored = await setItemStatus(item, "open");
+ if (archiveToastHost !== host) return;
+ if (restored) closeArchiveToast();
+ else {
+ busy = false;
+ draw();
+ schedule();
+ }
+ }}
+ >
+ ${busy ? "Undoing…" : "Undo"}
+ </button>
+ <button class="icon-btn" type="button" aria-label="Dismiss notification" @click=${closeArchiveToast}>
+ ${icon(X, 14)}
+ </button>
+ </div>`,
+ host,
+ );
+ };
+ draw();
+ schedule();
+}
+
let emojiIndexRequested = false;
function ensureEmojiChips(): void {
@@ -159,16 +256,9 @@ interface InboxSurface {
const surfaces = new Set<InboxSurface>();
-const externalSurfaces = new Set<{ redraw: () => void; visible: () => boolean }>();
-
-export function attachInboxSurface(surface: { redraw: () => void; visible: () => boolean }): () => void {
- externalSurfaces.add(surface);
- ensurePolling();
- ensureRealtime();
- return () => externalSurfaces.delete(surface);
-}
-
export function resetInboxState(): void {
+ resetSentMail();
+ closeArchiveToast();
inboxState.items = [];
inboxState.loopId = null;
inboxState.syncCron = null;
@@ -200,7 +290,7 @@ function viewSources(viewId: string): InboxSource[] {
export function itemsFor(viewId: string, status: "open" | "handled"): InboxItem[] {
const sources = viewSources(viewId);
return inboxState.items.filter(
- (i) => sources.includes(i.source) && (status === "open" ? i.status === "open" : i.status !== "open"),
+ (i) => !i.sentChat && sources.includes(i.source) && (status === "open" ? i.status === "open" : i.status !== "open"),
);
}
@@ -240,6 +330,7 @@ export function toInboxItem(entry: LedgerItem): InboxItem {
source,
sourceKey: entry.dedupeKey,
status: resolved,
+ sentChat: payload.sentChat === true,
title: str(payload.title) ?? "",
from: str(payload.from) ?? "",
snippet: str(payload.snippet) ?? "",
@@ -272,7 +363,7 @@ let pollTimer: number | null = null;
function anySurfaceVisible(): boolean {
if (!can("inbox")) return false;
if (appState.currentView === "inbox") return true;
- return [...surfaces].some((s) => s.pane && s.host.isConnected) || [...externalSurfaces].some((s) => s.visible());
+ return [...surfaces].some((s) => s.pane && s.host.isConnected);
}
function ensurePolling(): void {
@@ -302,7 +393,9 @@ export async function refreshInbox(opts: { silent?: boolean; ifStaleMs?: number
const found = await api<{ loop: { id: string } | null; syncCron: InboxSyncCron | null }>("/api/inbox");
inboxState.syncCron = found.syncCron;
inboxState.loopId = found.loop?.id ?? null;
- inboxState.items = inboxState.loopId ? await fetchItems(inboxState.loopId) : [];
+ const localItems = await fetchLocalInboxItems();
+ inboxState.items = localItems.length ? localItems : [];
+ if (!inboxState.items.length && inboxState.loopId) inboxState.items = await fetchItems(inboxState.loopId);
inboxState.loaded = true;
inboxState.error = null;
inboxState.fetchedAt = Date.now();
@@ -323,6 +416,26 @@ async function fetchItems(loopId: string): Promise<InboxItem[]> {
return payload.items.map(toInboxItem);
}
+async function fetchLocalInboxItems(): Promise<InboxItem[]> {
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(location.hostname)) return [];
+ try {
+ const response = await fetch("/inbox-seed.local.json", { cache: "no-store" });
+ if (!response.ok) return [];
+ const payload = (await response.json()) as { items?: unknown };
+ if (!Array.isArray(payload.items)) return [];
+ return payload.items.filter(
+ (item): item is InboxItem =>
+ typeof item === "object" &&
+ item !== null &&
+ typeof (item as InboxItem).id === "string" &&
+ typeof (item as InboxItem).sourceKey === "string" &&
+ ((item as InboxItem).source === "gmail" || (item as InboxItem).source === "slack"),
+ );
+ } catch {
+ return [];
+ }
+}
+
let realtimeWired = false;
const enqueueRealtimeEvent = createInboxEventCoalescer(
@@ -374,6 +487,20 @@ function ensureRealtime(): void {
});
}
+function inboxItemById(id: string): InboxItem | undefined {
+ const sent = selectedSentChat(id);
+ return sent?.id === id ? toInboxItem(sent) : inboxState.items.find((item) => item.id === id);
+}
+
+async function continueSentReply(item: InboxItem): Promise<void> {
+ try {
+ replaceItem(await postAction(item, "reply"));
+ drawAll();
+ } catch (error) {
+ notify(`Couldn't start a reply: ${error instanceof Error ? error.message : error}`);
+ }
+}
+
function replaceItem(next: InboxItem): void {
inboxState.items = inboxState.items.map((i) => (i.id === next.id ? next : i));
}
@@ -408,12 +535,13 @@ function effectiveDraft(item: InboxItem): InboxDraft {
const { basedOnAt: _basedOnAt, ...draft } = edited;
return draft;
}
- return (
- item.draft ?? {
- body: "",
- ...(item.source === "gmail" ? { to: item.gmail?.to ?? [], subject: item.gmail?.subject } : {}),
- }
- );
+ return {
+ body: "",
+ ...(item.source === "gmail"
+ ? { to: item.gmail?.to ?? [], cc: item.gmail?.cc ?? [], subject: item.gmail?.subject }
+ : {}),
+ ...item.draft,
+ };
}
function editDraft(item: InboxItem, patch: Partial<InboxDraft>): void {
@@ -427,7 +555,7 @@ function isDraftConflict(e: unknown): boolean {
async function explainDraftConflict(item: InboxItem, edited: boolean): Promise<void> {
await refetchItem(item);
- const fresh = inboxState.items.find((i) => i.id === item.id);
+ const fresh = inboxItemById(item.id);
const overlay = draftEdits.get(item.id);
if (overlay && fresh?.draftAt !== undefined) draftEdits.set(item.id, { ...overlay, basedOnAt: fresh.draftAt });
const preview = (fresh?.draft?.body ?? "").trim().slice(0, 140);
@@ -438,11 +566,8 @@ async function explainDraftConflict(item: InboxItem, edited: boolean): Promise<v
);
}
-function splitAddresses(raw: string): string[] {
- return raw
- .split(/[,;]/)
- .map((s) => s.trim())
- .filter(Boolean);
+function addressHeaderList(raw: string): string[] {
+ return raw.trim() ? [raw.trim()] : [];
}
function actionPath(item: InboxItem, leaf: "action" | "followup"): string {
@@ -454,6 +579,7 @@ async function refetchItem(item: InboxItem): Promise<void> {
const { item: fresh } = await api<{ item: LedgerItem }>(
`/api/loops/${encodeURIComponent(item.loopId)}/items/${encodeURIComponent(item.id)}`,
);
+ updateSentChat(fresh);
replaceItem(toInboxItem(fresh));
drawAll();
} catch {
@@ -466,6 +592,7 @@ async function postAction(item: InboxItem, kind: string, args?: Record<string, u
method: "POST",
body: JSON.stringify({ kind, ...(args ? { args } : {}) }),
});
+ updateSentChat(next);
return toInboxItem(next);
}
@@ -491,7 +618,7 @@ export function persistDraft(item: InboxItem): Promise<void> {
}
async function persistDraftNow(itemId: string): Promise<void> {
- const item = inboxState.items.find((i) => i.id === itemId);
+ const item = inboxItemById(itemId);
if (!item) return;
const edited = draftEdits.get(item.id);
if (!edited) return;
@@ -539,7 +666,7 @@ async function sendItem(item: InboxItem): Promise<void> {
}
async function sendItemNow(itemId: string): Promise<void> {
- const item = inboxState.items.find((i) => i.id === itemId);
+ const item = inboxItemById(itemId);
if (!item) return;
const edited = draftEdits.get(item.id);
const draft = effectiveDraft(item);
@@ -564,13 +691,17 @@ async function sendItemNow(itemId: string): Promise<void> {
}
}
-export async function setItemStatus(item: InboxItem, status: "open" | "dismissed"): Promise<void> {
- if (acting.has(item.id)) return;
+export async function setItemStatus(item: InboxItem, status: "open" | "dismissed"): Promise<boolean> {
+ if (acting.has(item.id)) return false;
acting.add(item.id);
+ drawAll();
try {
replaceItem(await postAction(item, status === "dismissed" ? "dismiss" : "reopen"));
+ if (status === "dismissed") showArchiveToast(item);
+ return true;
} catch (e) {
notify(`Couldn't update the item: ${e instanceof Error ? e.message : e}`);
+ return false;
} finally {
acting.delete(item.id);
drawAll();
@@ -588,6 +719,7 @@ export async function askAgent(item: InboxItem, message: string): Promise<void>
method: "POST",
body: JSON.stringify({ message: text }),
});
+ updateSentChat(next);
const mapped = toInboxItem(next);
draftEdits.delete(item.id);
replaceItem(mapped);
@@ -785,9 +917,9 @@ export function chatTpl(item: InboxItem): TemplateResult {
${
empty
? html`<div class="inbox-chat-empty">
- <h2 class="inbox-chat-cta">What should I change?</h2>
+ <h2 class="inbox-chat-cta">${item.sentChat ? "Ask about this email" : "What should I change?"}</h2>
<div class="inbox-chat-suggestions">
- ${DRAFT_SUGGESTIONS.map(
+ ${(item.sentChat ? ["Summarize this email", "What should I follow up on?"] : DRAFT_SUGGESTIONS).map(
(prompt) =>
html`<button
class="inbox-chat-suggestion"
@@ -833,7 +965,7 @@ export function chatTpl(item: InboxItem): TemplateResult {
<div class="inbox-chat-actions">
<div class="inbox-chat-suggest">
${
- item.status === "open"
+ item.status === "open" && !item.sentChat
? html`
<button
class="inbox-suggest-chip primary"
@@ -916,7 +1048,7 @@ export function draftEditorTpl(item: InboxItem, opts: { chat?: boolean } = {}):
type="text"
.value=${(draft.to ?? []).join(", ")}
placeholder="[email protected]"
- @input=${(e: Event) => editDraft(item, { to: splitAddresses((e.currentTarget as HTMLInputElement).value) })}
+ @input=${(e: Event) => editDraft(item, { to: addressHeaderList((e.currentTarget as HTMLInputElement).value) })}
@blur=${() => void persistDraft(item)}
/>
</label>
@@ -927,7 +1059,7 @@ export function draftEditorTpl(item: InboxItem, opts: { chat?: boolean } = {}):
<input
type="text"
.value=${(draft.cc ?? []).join(", ")}
- @input=${(e: Event) => editDraft(item, { cc: splitAddresses((e.currentTarget as HTMLInputElement).value) })}
+ @input=${(e: Event) => editDraft(item, { cc: addressHeaderList((e.currentTarget as HTMLInputElement).value) })}
@blur=${() => void persistDraft(item)}
/>
</label>`
@@ -951,7 +1083,7 @@ export function draftEditorTpl(item: InboxItem, opts: { chat?: boolean } = {}):
<textarea
class="inbox-draft-body"
rows=${gmail ? 7 : 3}
- placeholder=${item.draft ? "" : "No draft yet. The next sync writes one, or write your own."}
+ placeholder=${item.draft ? "Write a reply…" : "No draft yet. The next sync writes one, or write your own."}
.value=${draft.body}
@input=${(e: Event) => editDraft(item, { body: (e.currentTarget as HTMLTextAreaElement).value })}
@blur=${() => void persistDraft(item)}
@@ -1025,35 +1157,51 @@ function itemRowTpl(surface: InboxSurface, item: InboxItem): TemplateResult {
const sub = gmail ? item.title : item.from;
return html`
<div class="inbox-item ${expanded ? "expanded" : ""} ${handled ? "handled" : ""} src-${item.source}">
- <button
- class="inbox-item-row"
- type="button"
- aria-expanded=${expandedAttr}
- @click=${() => {
- const previous = surface.selectedId;
- if (previous && previous !== item.id) {
- const prevItem = inboxState.items.find((i) => i.id === previous);
- if (prevItem) void persistDraft(prevItem);
- }
- surface.selectedId = inlineDetail && open ? null : item.id;
- if (!inlineDetail) syncItemUrl(surface.selectedId, true);
- drawAll();
- }}
- >
- <span class="inbox-item-glyph">${sourceGlyph(item.source)}</span>
- <span class="inbox-item-main">
- <span class="inbox-item-top">
- <span class="inbox-item-heading">${heading}</span>
- <span class="inbox-item-sub">${sub}</span>
+ <div class="inbox-item-summary">
+ <button
+ class="inbox-item-row"
+ type="button"
+ aria-expanded=${expandedAttr}
+ @click=${() => {
+ const previous = surface.selectedId;
+ if (previous && previous !== item.id) {
+ const prevItem = inboxState.items.find((i) => i.id === previous);
+ if (prevItem) void persistDraft(prevItem);
+ }
+ surface.selectedId = inlineDetail && open ? null : item.id;
+ if (!inlineDetail) syncInboxUrl(surface.selectedId, true);
+ drawAll();
+ }}
+ >
+ <span class="inbox-item-glyph">${sourceGlyph(item.source)}</span>
+ <span class="inbox-item-main">
+ <span class="inbox-item-top">
+ <span class="inbox-item-heading">${heading}</span>
+ <span class="inbox-item-sub">${sub}</span>
+ </span>
+ <span class="inbox-item-snippet">${slackTextTpl(item, item.snippet, { links: false })}</span>
</span>
- <span class="inbox-item-snippet">${slackTextTpl(item, item.snippet, { links: false })}</span>
- </span>
- <span class="inbox-item-side">
- ${participantsTpl(item)} ${itemSideMark(item, handled)}
- <span class="inbox-item-time" title=${fmtClock(item.receivedAt)}>${relTime(item.receivedAt)}</span>
- ${icon(expanded ? ChevronDown : ChevronRight, 13)}
- </span>
- </button>
+ <span class="inbox-item-side">
+ ${participantsTpl(item)} ${itemSideMark(item, handled)}
+ <span class="inbox-item-time" title=${fmtClock(item.receivedAt)}>${relTime(item.receivedAt)}</span>
+ ${icon(expanded ? ChevronDown : ChevronRight, 13)}
+ </span>
+ </button>
+ ${
+ !handled
+ ? html`<button
+ class="session-menu-btn inbox-item-dismiss"
+ type="button"
+ aria-label=${`Archive ${item.title || heading}`}
+ ${tip("Archive")}
+ ?disabled=${acting.has(item.id)}
+ @click=${() => void setItemStatus(item, "dismissed")}
+ >
+ ${icon(Archive, 13.5)}
+ </button>`
+ : nothing
+ }
+ </div>
${
expanded
? html`<div class="inbox-item-detail">
@@ -1070,31 +1218,57 @@ function syncStatusLabel(cron: InboxSyncCron): string {
return cron.lastFiredAt ? `Synced ${relTime(cron.lastFiredAt)}` : "First sync pending";
}
-function syncLineTpl(): TemplateResult {
+function syncActionTpl(opts: {
+ label: string;
+ busyLabel: string;
+ busy: boolean;
+ tooltip: string;
+ action: () => void;
+}): TemplateResult {
+ return html`<button
+ class="btn inbox-sync-action"
+ type="button"
+ ${tip(opts.tooltip)}
+ ?disabled=${opts.busy}
+ @click=${opts.action}
+ >
+ ${icon(RefreshCw, 13)}<span>${opts.busy ? opts.busyLabel : opts.label}</span>
+ </button>`;
+}
+
+function syncLineTpl(surface: InboxSurface): TemplateResult {
+ if (surface.viewId === "sent") {
+ const busy = isSentMailLoading();
+ return syncActionTpl({
+ label: "Refresh",
+ busyLabel: "Refreshing…",
+ busy,
+ tooltip: "Refresh sent mail",
+ action: () => void loadSentMail(drawAll),
+ });
+ }
const cron = inboxState.syncCron;
if (!cron) {
- return html`<button
- class="btn inbox-sync-setup"
- type="button"
- ${tip("Create the inbox loop and the personal cron that scans your connected apps and drafts replies")}
- ?disabled=${inboxState.syncBusy}
- @click=${() => void setUpSync()}
- >
- ${icon(RefreshCw, 13)}<span>${inboxState.syncBusy ? "Setting up…" : "Set up sync"}</span>
- </button>`;
+ return syncActionTpl({
+ label: "Set up sync",
+ busyLabel: "Setting up…",
+ busy: inboxState.syncBusy,
+ tooltip: "Create the inbox loop and the personal cron that scans your connected apps and drafts replies",
+ action: () => void setUpSync(),
+ });
}
return html`<span class="inbox-sync-line">
- <button
- class="icon-btn subtle compact"
- type="button"
- ${tip("Sync now")}
- aria-label="Sync now"
- ?disabled=${inboxState.syncBusy}
- @click=${() => void syncNow()}
+ ${syncActionTpl({
+ label: "Sync",
+ busyLabel: "Syncing…",
+ busy: inboxState.syncBusy,
+ tooltip: "Sync now",
+ action: () => void syncNow(),
+ })}
+ <span
+ class="inbox-sync-status"
+ ${tip(cron.enabled ? "The sync cron is on" : "The sync cron is paused. Manage it under Crons")}
>
- ${icon(RefreshCw, 14)}
- </button>
- <span ${tip(cron.enabled ? "The sync cron is on" : "The sync cron is paused. Manage it under Crons")}>
${syncStatusLabel(cron)}
</span>
</span>`;
@@ -1111,35 +1285,29 @@ function surfaceTpl(surface: InboxSurface): TemplateResult {
<div class="inbox-chips" role="tablist" aria-label="Inbox views">
${VIEWS.map((v) => {
const count = inboxOpenCount(v.id);
- return html`<button
- class="inbox-chip ${surface.viewId === v.id ? "active" : ""}"
- type="button"
- role="tab"
- aria-selected=${surface.viewId === v.id ? "true" : "false"}
- @click=${() => {
- surface.viewId = v.id;
- if (surface === fullSurface) fullViewId = v.id;
- drawAll();
- }}
- >
- <span>${v.name}</span>${count > 0 ? html`<span class="inbox-chip-count">${count}</span>` : nothing}
- </button>`;
+ const empty =
+ v.id === "sent"
+ ? isSentMailEmpty()
+ : inboxState.loaded &&
+ !inboxState.error &&
+ !inboxState.items.some((item) => v.sources.includes(item.source));
+ const disabled = empty && surface.viewId !== v.id;
+ return html`${v.id === "sent" ? html`<span class="inbox-chip-divider" aria-hidden="true"></span>` : nothing}<button
+ class="inbox-chip ${surface.viewId === v.id ? "active" : ""}"
+ type="button"
+ role="tab"
+ ?disabled=${disabled}
+ aria-selected=${surface.viewId === v.id ? "true" : "false"}
+ @click=${() => {
+ if (surface === fullSurface) selectInboxView(v.id, true);
+ else surface.viewId = v.id;
+ if (v.id === "sent") ensureSentMail(drawAll);
+ drawAll();
+ }}
+ >
+ <span>${v.name}</span>${count > 0 ? html`<span class="inbox-chip-count">${count}</span>` : nothing}
+ </button>`;
})}
- <button
- class="inbox-chip inbox-review-chip"
- type="button"
- draggable="true"
- title="Draft review. Drag into the split canvas to pin it as a pane"
- @dragstart=${(e: DragEvent) => {
- e.dataTransfer?.setData("application/x-webui-draft-review", surface.viewId);
- if (e.dataTransfer) e.dataTransfer.effectAllowed = "copy";
- beginPaneKindDrag("draftReview", surface.viewId);
- }}
- @dragend=${() => endPaneDrag()}
- @click=${() => notify("Drag Draft review into the split canvas to pin it as a pane.")}
- >
- <span>Draft review</span>
- </button>
</div>
`;
const list = html`
@@ -1192,10 +1360,26 @@ function surfaceTpl(surface: InboxSurface): TemplateResult {
return html`
<div class="inbox-surface ${compact ? "compact" : ""}" data-density=${density}>
<div class="inbox-toolbar">
- ${chips} ${surface.pane ? html`<span class="inbox-toolbar-spacer"></span>${syncLineTpl()}` : nothing}
+ ${chips} ${surface.pane ? html`<span class="inbox-toolbar-spacer"></span>${syncLineTpl(surface)}` : nothing}
</div>
${inboxState.notice ? html`<div class="inbox-notice" role="status">${inboxState.notice}</div>` : nothing}
- <div class="inbox-scroll">${list}</div>
+ <div class="inbox-scroll">
+ ${
+ surface.viewId === "sent"
+ ? sentMailTpl(drawAll, (message) => {
+ resetActiveInboxItem();
+ if (surface.pane) {
+ exitSplitIfActive();
+ switchView("inbox");
+ }
+ fullViewId = "sent";
+ if (fullSurface) fullSurface.selectedId = null;
+ syncInboxUrl(message.id, true);
+ void openSentEmail(message, drawAll);
+ })
+ : list
+ }
+ </div>
</div>
`;
}
@@ -1228,6 +1412,24 @@ function itemPageTpl(item: InboxItem): TemplateResult {
`;
}
+function sentDraftTpl(): TemplateResult | undefined {
+ const saved = selectedSentChat();
+ if (!saved) return;
+ const item = toInboxItem(saved);
+ if (item.status !== "open")
+ return html`<div class="inbox-draft">
+ <p>Reply sent.</p>
+ <button class="btn" @click=${() => void continueSentReply(item)}>Write another reply</button>
+ </div>`;
+ return html`${inboxState.notice ? html`<div class="inbox-notice" role="status">${inboxState.notice}</div>` : nothing}${draftEditorTpl(item, { chat: false })}<button
+ class="btn primary"
+ ?disabled=${sending.has(item.id)}
+ @click=${() => void sendItem(item)}
+ >
+ ${sending.has(item.id) ? "Sending…" : "Send reply"}
+ </button>`;
+}
+
function keepingChatLogsPinned(host: HTMLElement, draw: () => void): void {
const logs = () => [...host.querySelectorAll<HTMLElement>(".inbox-chat-log")];
const wasAtBottom = logs().map((el) => el.scrollHeight - el.scrollTop - el.clientHeight < 24);
@@ -1252,7 +1454,7 @@ function drawFull(): void {
if (appState.currentView !== "inbox" || !appState.mainEl) return;
if (!fullSurface || !fullSurface.host.isConnected || fullSurface.host.parentElement !== appState.mainEl) {
const host = document.createElement("div");
- host.className = "pane inbox-page";
+ host.className = "pane inbox-page content-wide-page";
fullSurface = {
host,
viewId: fullViewId,
@@ -1270,24 +1472,35 @@ function drawFull(): void {
pendingItemId = null;
}
const openItem = fullSurface.selectedId ? inboxState.items.find((i) => i.id === fullSurface?.selectedId) : undefined;
- if (fullSurface.selectedId && !openItem && inboxState.loaded) fullSurface.selectedId = null;
- syncItemUrl(fullSurface.selectedId);
+ const openSentEmail = selectedSentEmail();
+ if (fullSurface.selectedId && !openItem && inboxState.loaded) {
+ const sentId = fullSurface.selectedId;
+ fullSurface.selectedId = null;
+ fullViewId = "sent";
+ void openSentEmailById(sentId, drawAll);
+ return;
+ }
+ syncInboxUrl(openSentEmail?.id ?? fullSurface.selectedId);
const host = fullSurface.host;
const surface = fullSurface;
- keepingChatLogsPinned(host, () =>
- render(
- openItem
- ? itemPageTpl(openItem)
- : html`
- <div class="pane-head">
- <h1 class="pane-title">Inbox</h1>
- <div class="pane-head-actions">${syncLineTpl()}</div>
- </div>
- ${surfaceTpl(surface)}
- `,
- host,
- ),
- );
+ let page: TemplateResult | typeof nothing;
+ if (openItem) page = itemPageTpl(openItem);
+ else if (openSentEmail) {
+ page = sentEmailPageTpl(
+ drawAll,
+ sentChatTpl(drawAll, (item) => chatTpl(toInboxItem(item))),
+ sentDraftTpl(),
+ closeInboxItem,
+ );
+ } else
+ page = html`
+ <div class="pane-head">
+ <h1 class="pane-title">Inbox</h1>
+ <div class="pane-head-actions">${syncLineTpl(surface)}</div>
+ </div>
+ ${surfaceTpl(surface)}
+ `;
+ keepingChatLogsPinned(host, () => render(page, host));
sizeAside(host);
sizeChatInputs(host);
}
@@ -1330,15 +1543,18 @@ function sizeChatInputs(host: HTMLElement): void {
for (const box of host.querySelectorAll<HTMLTextAreaElement>(".inbox-chat-input")) autosizeChatInput(box);
}
-function syncItemUrl(itemId: string | null, push = false): void {
+function syncInboxUrl(itemId: string | null, push = false): void {
if (appState.currentView !== "inbox") return;
- const next = deepLinkPath(UI_BASE, "inbox", null, null, itemId);
+ const next = deepLinkPath(UI_BASE, "inbox", null, null, itemId ?? inboxViewSegment(fullViewId));
if (`${location.pathname}${location.search}` === next) return;
if (push) history.pushState(null, "", next);
else history.replaceState(null, "", next);
}
export function resetActiveInboxItem(): void {
+ const sent = selectedSentChat();
+ if (sent) void persistDraft(toInboxItem(sent));
+ resetSelectedSentEmail();
const open = fullSurface?.selectedId;
if (!open || !fullSurface) return;
const item = inboxState.items.find((i) => i.id === open);
@@ -1348,34 +1564,49 @@ export function resetActiveInboxItem(): void {
function closeInboxItem(): void {
resetActiveInboxItem();
- syncItemUrl(null);
- drawAll();
-}
-
-export function routeInboxHistory(itemId: string | null): void {
- if (!fullSurface) return;
- fullSurface.selectedId = itemId;
+ syncInboxUrl(null);
+ if (fullViewId === "sent") ensureSentMail(drawAll);
drawAll();
}
-export function openInboxItemById(itemId: string): void {
- pendingItemId = itemId;
+export function routeInboxHistory(segment: string | null): void {
+ resetActiveInboxItem();
+ const viewId = inboxViewIdForSegment(segment);
+ if (viewId) {
+ fullViewId = viewId;
+ pendingItemId = null;
+ if (fullSurface) {
+ fullSurface.viewId = viewId;
+ fullSurface.selectedId = null;
+ }
+ if (viewId === "sent") ensureSentMail(drawAll);
+ } else {
+ fullViewId = "all";
+ pendingItemId = segment;
+ if (fullSurface) {
+ fullSurface.viewId = "all";
+ fullSurface.selectedId = segment;
+ }
+ }
+ if (appState.currentView === "inbox") drawAll();
}
export function drawAll(): void {
for (const s of surfaces) drawSurface(s);
- for (const s of externalSurfaces) s.redraw();
drawFull();
renderSidebarTop();
notifyPanesChanged();
}
-export function selectInboxView(viewId: string): void {
+export function selectInboxView(viewId: string, push = false): void {
+ resetActiveInboxItem();
+ if (!isInboxViewId(viewId)) viewId = "all";
fullViewId = viewId;
if (fullSurface) {
fullSurface.viewId = viewId;
fullSurface.selectedId = null;
}
+ syncInboxUrl(null, push);
}
export async function renderInbox(): Promise<void> {
diff --git a/plugins/web-ui/src/main.ts b/plugins/web-ui/src/main.ts
index 882f8e680..b7f929c62 100644
--- a/plugins/web-ui/src/main.ts
+++ b/plugins/web-ui/src/main.ts
@@ -1,7 +1,6 @@
import "dockview-core/dist/styles/dockview.css";
import "./shell.css";
import { bootSafely, closeUserMenu } from "./shell";
-import "./draft-review";
import { registerChatSearchHotkey } from "./search";
import { registerSessionJumpHotkeys } from "./session-jump";
import { closeFormMenus } from "./ui";
diff --git a/plugins/web-ui/src/sent-mail.ts b/plugins/web-ui/src/sent-mail.ts
new file mode 100644
index 000000000..fb8dcf81e
--- /dev/null
+++ b/plugins/web-ui/src/sent-mail.ts
@@ -0,0 +1,416 @@
+import { html, nothing, type TemplateResult } from "lit";
+import { ArrowUpRight, ChevronRight, Mail } from "lucide";
+import type { LedgerItem } from "./inbox";
+import { api } from "./core-bridge";
+import { listBackLink } from "./list-page";
+import { icon, initials, relTime } from "./ui";
+
+interface SentThreadMessage {
+ from: string;
+ to: string;
+ cc?: string;
+ sentAt: number;
+ body: string;
+ attachments?: string[];
+}
+
+export interface SentEmail {
+ accountType?: "default" | "personal" | "company";
+ id: string;
+ threadId: string;
+ to: string;
+ subject: string;
+ snippet: string;
+ sentAt: number;
+ conversation?: SentThreadMessage[];
+}
+
+interface SentMailPage {
+ accountType?: SentEmail["accountType"];
+ messages: SentEmail[];
+ nextPageToken?: string;
+ accountEmail: string;
+}
+
+let messages: SentEmail[] = [];
+let nextPageToken: string | undefined;
+let accountEmail = "";
+let loading = false;
+let loaded = false;
+let error = "";
+let generation = 0;
+let selected: SentEmail | null = null;
+let detail:
+ | (SentEmail & {
+ from: string;
+ cc: string;
+ body: string;
+ rfcMessageId?: string;
+ html: boolean;
+ attachments: string[];
+ })
+ | null = null;
+let detailError = "";
+const chatItems = new Map<string, LedgerItem>();
+let chatItemId: string | null = null;
+let chatError = "";
+let detailGeneration = 0;
+
+export async function openSentEmail(message: SentEmail, draw: () => void): Promise<void> {
+ selected = message;
+ chatItemId = null;
+ chatError = "";
+ detail = null;
+ detailError = "";
+ const current = ++detailGeneration;
+ draw();
+ try {
+ const local = await fetchLocalSentMail();
+ const seeded = local?.messages.find((item) => item.id === message.id);
+ const result = seeded
+ ? {
+ ...seeded,
+ from: local!.accountEmail,
+ cc: "",
+ body: `${plainSnippet(seeded.snippet)}\n\nFull message text is not included in this local preview.`,
+ html: false,
+ attachments: [],
+ }
+ : await api<NonNullable<typeof detail>>(
+ `/api/inbox/sent/${encodeURIComponent(message.id)}?${new URLSearchParams({ accountType: message.accountType ?? "default" })}`,
+ );
+ if (current === detailGeneration) {
+ detail = result;
+ selected = { ...message, ...result };
+ if (seeded) accountEmail = local!.accountEmail;
+ draw();
+ await loadSentChat(draw, current);
+ }
+ } catch (cause) {
+ if (current === detailGeneration)
+ detailError = cause instanceof Error ? cause.message : "Couldn't load this email.";
+ } finally {
+ if (current === detailGeneration) draw();
+ }
+}
+
+async function loadSentChat(draw: () => void, current = detailGeneration): Promise<void> {
+ if (!detail) return;
+ chatError = "";
+ draw();
+ try {
+ let text = detail.html ? plainSnippet(detail.body) : detail.body;
+ if (detail.conversation?.length)
+ text = detail.conversation.map((entry) => `${entry.from} to ${entry.to}:\n${entry.body}`).join("\n\n");
+ const result = await api<{ item: LedgerItem }>("/api/inbox/sent-chat", {
+ method: "POST",
+ body: JSON.stringify({
+ accountType: detail.accountType ?? selected?.accountType ?? "default",
+ messageId: detail.id,
+ threadId: detail.threadId,
+ subject: detail.subject,
+ from: detail.from,
+ to: detail.to,
+ cc: detail.cc,
+ rfcMessageId: detail.rfcMessageId,
+ text: text.slice(0, 50000),
+ }),
+ });
+ if (current === detailGeneration) {
+ chatItemId = result.item.id;
+ updateSentChat(result.item);
+ }
+ } catch (cause) {
+ if (current === detailGeneration) chatError = cause instanceof Error ? cause.message : "Couldn't load chat.";
+ } finally {
+ if (current === detailGeneration) draw();
+ }
+}
+
+export function sentChatTpl(draw: () => void, renderChat: (item: LedgerItem) => TemplateResult): TemplateResult {
+ const item = selectedSentChat();
+ if (item) return renderChat(item);
+ return html`<div class="inbox-chat">
+ <h2 class="inbox-chat-cta">Ask about this email</h2>
+ ${chatError ? html`<div role="alert">${chatError}<button class="btn" @click=${() => void loadSentChat(draw)}>Try again</button></div>` : html`<div role="status">Loading chat…</div>`}
+ </div>`;
+}
+
+export function selectedSentChat(id: string | null = chatItemId): LedgerItem | null {
+ return id ? (chatItems.get(id) ?? null) : null;
+}
+
+export function updateSentChat(item: LedgerItem): void {
+ if (chatItemId === item.id || chatItems.has(item.id)) chatItems.set(item.id, item);
+}
+
+export async function openSentEmailById(id: string, draw: () => void): Promise<void> {
+ await openSentEmail(
+ messages.find((message) => message.id === id) ?? {
+ id,
+ threadId: "",
+ to: "",
+ subject: "",
+ snippet: "",
+ sentAt: 0,
+ },
+ draw,
+ );
+}
+
+export function resetSentMail(): void {
+ chatItems.clear();
+ generation++;
+ detailGeneration++;
+ selected = null;
+ chatItemId = null;
+ chatError = "";
+ detail = null;
+ detailError = "";
+ messages = [];
+ nextPageToken = undefined;
+ accountEmail = "";
+ loading = false;
+ loaded = false;
+ error = "";
+}
+
+export async function loadSentMail(draw: () => void, more = false): Promise<void> {
+ if (loading) return;
+ loading = true;
+ error = "";
+ const current = ++generation;
+ const params = new URLSearchParams({ accountType: "default" });
+ if (more && nextPageToken) params.set("pageToken", nextPageToken);
+ draw();
+ try {
+ const local = more ? null : await fetchLocalSentMail();
+ const page = local ?? (await api<SentMailPage>(`/api/inbox/sent?${params}`));
+ if (current !== generation) return;
+ messages = [
+ ...new Map(
+ [
+ ...(more ? messages : []),
+ ...page.messages.map((message) => ({ ...message, accountType: page.accountType ?? ("default" as const) })),
+ ].map((message) => [message.id, message]),
+ ).values(),
+ ].sort((a, b) => b.sentAt - a.sentAt);
+ accountEmail = page.accountEmail;
+ nextPageToken = page.nextPageToken;
+ loaded = true;
+ } catch (cause) {
+ if (current !== generation) return;
+ error = cause instanceof Error ? cause.message : "Couldn't load sent mail. Try again.";
+ } finally {
+ if (current === generation) {
+ loading = false;
+ draw();
+ }
+ }
+}
+
+async function fetchLocalSentMail(): Promise<SentMailPage | null> {
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(location.hostname)) return null;
+ try {
+ const response = await fetch("/sent-seed.local.json", { cache: "no-store" });
+ if (!response.ok) return null;
+ const payload = (await response.json()) as Partial<SentMailPage>;
+ if (typeof payload.accountEmail !== "string" || !Array.isArray(payload.messages)) return null;
+ const messages = payload.messages.filter(
+ (message): message is SentEmail =>
+ typeof message === "object" &&
+ message !== null &&
+ typeof message.id === "string" &&
+ typeof message.threadId === "string" &&
+ typeof message.to === "string" &&
+ typeof message.subject === "string" &&
+ typeof message.snippet === "string" &&
+ typeof message.sentAt === "number" &&
+ (message.conversation === undefined ||
+ (Array.isArray(message.conversation) && message.conversation.every(isSentThreadMessage))),
+ );
+ return messages.length ? { accountEmail: payload.accountEmail, messages } : null;
+ } catch {
+ return null;
+ }
+}
+
+function isSentThreadMessage(message: unknown): message is SentThreadMessage {
+ if (typeof message !== "object" || message === null) return false;
+ const item = message as Partial<SentThreadMessage>;
+ return (
+ typeof item.from === "string" &&
+ typeof item.to === "string" &&
+ (item.cc === undefined || typeof item.cc === "string") &&
+ typeof item.sentAt === "number" &&
+ typeof item.body === "string" &&
+ (item.attachments === undefined ||
+ (Array.isArray(item.attachments) && item.attachments.every((attachment) => typeof attachment === "string")))
+ );
+}
+
+export function isSentMailEmpty(): boolean {
+ return loaded && !loading && !error && messages.length === 0;
+}
+
+export function isSentMailLoading(): boolean {
+ return loading;
+}
+
+export function ensureSentMail(draw: () => void): void {
+ if (!loaded && !loading) void loadSentMail(draw);
+}
+
+export function selectedSentEmail(): SentEmail | null {
+ return selected;
+}
+
+export function resetSelectedSentEmail(): void {
+ detailGeneration++;
+ selected = null;
+ chatItemId = null;
+ chatError = "";
+ detail = null;
+ detailError = "";
+}
+
+function closeSentEmail(draw: () => void): void {
+ resetSelectedSentEmail();
+ ensureSentMail(draw);
+ draw();
+}
+
+function plainSnippet(value: string): string {
+ const doc = new DOMParser().parseFromString(value, "text/html");
+ return doc.body.textContent ?? "";
+}
+
+export function sentMailTpl(
+ draw: () => void,
+ open: (message: SentEmail) => void = (message) => void openSentEmail(message, draw),
+): TemplateResult {
+ return html`
+ ${error ? html`<div class="inbox-notice" role="alert">${error} <button class="btn" ?disabled=${loading} @click=${() => void loadSentMail(draw, Boolean(nextPageToken))}>Try again</button></div>` : nothing}
+ ${!messages.length && !error ? html`<div class="empty compact">${loading ? "Loading sent mail…" : "No sent emails in this account."}</div>` : nothing}
+ <div class="inbox-list">
+ ${messages.map(
+ (message) =>
+ html`<div class="inbox-item src-gmail">
+ <div class="inbox-item-summary">
+ <button
+ class="inbox-item-row inbox-sent-row"
+ type="button"
+ @click=${() => open(message)}
+ aria-label=${`Open sent email: ${message.subject || "No subject"}`}
+ >
+ <span class="inbox-item-glyph">${icon(Mail, 14)}</span>
+ <span class="inbox-item-main">
+ <span class="inbox-item-top"
+ ><span class="inbox-item-heading">To: ${message.to || "Undisclosed recipients"}</span
+ ><span class="inbox-item-sub">${message.subject || "(No subject)"}</span></span
+ >
+ <span class="inbox-item-snippet">${plainSnippet(message.snippet)}</span>
+ </span>
+ <span class="inbox-item-side"
+ ><span class="inbox-item-time" title=${new Date(message.sentAt).toLocaleString()}
+ >${relTime(message.sentAt)}</span
+ >${icon(ChevronRight, 13)}</span
+ >
+ </button>
+ </div>
+ </div>`,
+ )}
+ </div>
+ ${nextPageToken ? html`<button class="btn inbox-sent-more" ?disabled=${loading} @click=${() => void loadSentMail(draw, true)}>${loading ? "Loading…" : "Load more"}</button>` : nothing}
+ `;
+}
+
+function sentMessageTpl(entry: SentThreadMessage): TemplateResult {
+ return html`<div class="inbox-context-msg inbox-sent-message">
+ <span class="inbox-avatar" aria-hidden="true">${initials(entry.from)}</span>
+ <div class="inbox-context-body">
+ <div class="inbox-context-head">
+ <span class="inbox-context-author">${entry.from}</span>
+ <span class="inbox-context-at" title=${new Date(entry.sentAt).toLocaleString()}>${relTime(entry.sentAt)}</span>
+ </div>
+ <div class="inbox-sent-recipients">
+ To: ${entry.to}${entry.cc ? html`<span> · Cc: ${entry.cc}</span>` : nothing}
+ </div>
+ <div class="inbox-context-text">${entry.body || "This email has no text body."}</div>
+ ${
+ entry.attachments?.length
+ ? html`<div class="inbox-sent-attachments">Attachments: ${entry.attachments.join(", ")}</div>`
+ : nothing
+ }
+ </div>
+ </div>`;
+}
+
+export function sentEmailPageTpl(
+ draw: () => void,
+ aside?: TemplateResult,
+ draft?: TemplateResult,
+ close: () => void = () => closeSentEmail(draw),
+): TemplateResult | typeof nothing {
+ if (!selected) return nothing;
+ const message = selected;
+ const body = detail?.html
+ ? plainSnippet(detail.body.replace(/<br\s*\/?>(|\s)|<\/(p|div|tr|li|h[1-6])>/gi, "\n"))
+ : detail?.body;
+ let entries: SentThreadMessage[] = [];
+ if (detail?.conversation?.length) entries = detail.conversation;
+ else if (detail)
+ entries = [
+ {
+ from: detail.from,
+ to: message.to,
+ cc: detail.cc,
+ sentAt: message.sentAt,
+ body: body || "This email has no text body.",
+ attachments: detail.attachments,
+ },
+ ];
+ return html`
+ <div class="pane-head inbox-item-head src-gmail">
+ <div class="inbox-item-head-copy">
+ ${listBackLink("Sent", close)}
+ <h1 class="pane-title">
+ <span class="inbox-item-glyph">${icon(Mail, 18)}</span>
+ <span>To: ${message.to || "Undisclosed recipients"}</span>
+ <span class="inbox-item-head-meta">
+ <span class="inbox-item-state">Sent</span>
+ <span class="inbox-item-time" title=${new Date(message.sentAt).toLocaleString()}
+ >${relTime(message.sentAt)}</span
+ >
+ </span>
+ </h1>
+ <div class="pane-subtitle">${message.subject || "(No subject)"}</div>
+ </div>
+ </div>
+ <div class="inbox-surface inbox-item-surface">
+ <div class="inbox-scroll inbox-item-thread">
+ ${
+ detailError
+ ? html`<div class="inbox-notice" role="alert">
+ ${detailError} <button class="btn" @click=${() => void openSentEmail(message, draw)}>Try again</button>
+ </div>`
+ : nothing
+ }
+ ${!detail && !detailError ? html`<div role="status" class="empty compact">Loading email…</div>` : nothing}
+ ${entries.length ? html`<div class="inbox-context">${entries.map(sentMessageTpl)}</div>` : nothing}
+ ${draft ?? nothing}
+ <div class="inbox-draft-head inbox-sent-actions">
+ <a
+ class="inbox-external-link"
+ href=${`https://mail.google.com/mail/?authuser=${encodeURIComponent(accountEmail)}#sent/${encodeURIComponent(message.threadId)}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ ${icon(ArrowUpRight, 12)}<span>Open in Gmail</span>
+ </a>
+ </div>
+ </div>
+ </div>
+ ${aside ? html`<aside class="inbox-item-aside">${aside}</aside>` : nothing}
+ `;
+}
diff --git a/plugins/web-ui/src/shell-state.ts b/plugins/web-ui/src/shell-state.ts
index 7d0f668d2..d1b963bbf 100644
--- a/plugins/web-ui/src/shell-state.ts
+++ b/plugins/web-ui/src/shell-state.ts
@@ -21,6 +21,7 @@ export interface Me {
const VIEWS = [
"chats",
"inbox",
+ "calendar",
"contexts",
"webhooks",
"crons",
@@ -53,6 +54,6 @@ export function can(key: string): boolean {
export function canView(view: View): boolean {
if (view === "loops") return can("loops");
- if (view === "inbox") return can("inbox");
+ if (view === "inbox" || view === "calendar") return can("inbox");
return true;
}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 5f3f98fb1..11e1c134f 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -22,6 +22,12 @@
--cta: oklch(0.27 0.062 250);
--cta-hover: oklch(0.33 0.07 250);
--cta-foreground: oklch(0.99 0 0);
+ --conversation-hover: color-mix(
+ in srgb,
+ var(--foreground) 4%,
+ color-mix(in srgb, var(--secondary) 42%, var(--background))
+ );
+ --inbox-row-hover: color-mix(in srgb, var(--foreground) 4%, var(--background));
--success: #1a7f37;
--warning: #a66700;
--scrim: oklch(0.145 0 0);
@@ -539,7 +545,7 @@ a.chat-row-open {
padding-right: 90px;
}
.session:hover {
- background: color-mix(in srgb, var(--foreground) 4%, transparent);
+ background: var(--conversation-hover);
}
.session.active {
background: color-mix(in srgb, var(--foreground) 4%, transparent);
@@ -7268,7 +7274,8 @@ a.connector-widget:focus-visible {
font-size: 13.5px;
line-height: 1.5;
}
-.deploy-toast {
+.deploy-toast,
+.action-toast {
position: fixed;
right: 20px;
bottom: 20px;
@@ -7284,11 +7291,13 @@ a.connector-widget:focus-visible {
color: var(--background);
font-size: 13px;
}
-.deploy-toast > span {
+.deploy-toast > span,
+.action-toast > span {
min-width: 0;
flex: 1;
}
-.deploy-toast > button:not(.icon-btn) {
+.deploy-toast > button:not(.icon-btn),
+.action-toast > button:not(.icon-btn) {
border: 0;
background: transparent;
color: inherit;
@@ -7296,7 +7305,8 @@ a.connector-widget:focus-visible {
font-weight: 700;
cursor: pointer;
}
-.deploy-toast .icon-btn {
+.deploy-toast .icon-btn,
+.action-toast .icon-btn {
color: inherit;
}
@media (max-width: 760px) {
@@ -8808,13 +8818,24 @@ h3.ambient-field-label {
.layout.sidebar-closed #sidebar-top .navrow .nav-badge {
display: none;
}
+.content-wide-page {
+ --content-primary-width: 960px;
+ --content-aside-width: 330px;
+ --content-gap: 18px;
+ --content-wide-width: calc(var(--content-primary-width) + var(--content-gap) + var(--content-aside-width));
+}
.inbox-page .inbox-surface {
- width: min(960px, 100%);
+ width: min(var(--content-wide-width), 100%);
height: auto;
margin: 0 auto;
}
+.content-wide-page:not(:has(.inbox-item-aside)) > .pane-head {
+ width: min(var(--content-wide-width), 100%);
+ max-width: none;
+}
.inbox-page .inbox-toolbar {
padding: 8px 0;
+ border-bottom: 0;
}
.inbox-page .inbox-scroll {
overflow: visible;
@@ -8858,10 +8879,21 @@ h3.ambient-field-label {
font-size: 13.5px;
cursor: pointer;
}
-.inbox-chip:hover {
+.inbox-chip:hover:not(:disabled) {
color: var(--foreground);
background: var(--secondary);
}
+.inbox-chip:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+.inbox-chip-divider {
+ width: 1px;
+ height: 14px;
+ margin: 0 5px;
+ background: var(--border);
+ flex: none;
+}
.inbox-chip.active {
color: var(--foreground);
background: color-mix(in srgb, var(--foreground) 12%, transparent);
@@ -8916,10 +8948,43 @@ h3.ambient-field-label {
opacity: 0.75;
}
.inbox-item {
- border-bottom: 1px solid color-mix(in srgb, var(--border) 65%, transparent);
+ position: relative;
}
-.inbox-item:last-child {
- border-bottom: 0;
+.inbox-item:not(:last-child)::after {
+ display: block;
+ height: 1px;
+ margin: 0 12px;
+ background: color-mix(in srgb, var(--border) 65%, transparent);
+ content: "";
+ transition: background 0.12s ease;
+}
+.inbox-item:hover::after,
+.inbox-item:has(+ .inbox-item:hover)::after {
+ background: transparent;
+}
+.inbox-item-summary {
+ display: flex;
+ align-items: center;
+ border-radius: var(--radius-sm);
+ transition: background 0.12s ease;
+}
+.inbox-item-summary .inbox-item-row {
+ flex: 1;
+ min-width: 0;
+}
+.inbox-item-dismiss {
+ flex: none;
+ margin-right: 12px;
+ opacity: 0;
+}
+.inbox-item-summary:hover .inbox-item-dismiss,
+.inbox-item-summary:focus-within .inbox-item-dismiss {
+ opacity: 1;
+}
+@media (hover: none) {
+ .inbox-item-dismiss {
+ opacity: 1;
+ }
}
.inbox-item-row {
display: flex;
@@ -8935,11 +9000,13 @@ h3.ambient-field-label {
text-align: left;
cursor: pointer;
font: inherit;
- transition: background 0.12s ease;
}
-.inbox-item-row:hover,
-.inbox-item.expanded .inbox-item-row {
- background: color-mix(in srgb, var(--foreground) 4%, transparent);
+.inbox-item-summary:hover,
+.inbox-item.expanded .inbox-item-summary {
+ background: var(--inbox-row-hover);
+}
+.inbox-item-summary:has(.inbox-item-dismiss:hover) {
+ background: none;
}
.inbox-item-glyph {
flex: none;
@@ -8992,6 +9059,9 @@ h3.ambient-field-label {
overflow: hidden;
text-overflow: ellipsis;
}
+.src-gmail .inbox-item-snippet {
+ pointer-events: none;
+}
.inbox-item.expanded .inbox-item-snippet {
white-space: normal;
color: var(--foreground);
@@ -9089,6 +9159,7 @@ h3.ambient-field-label {
flex-direction: column;
gap: 14px;
padding-top: 14px;
+ padding-bottom: calc(64px + env(safe-area-inset-bottom));
}
.inbox-item-thread,
.inbox-item-aside {
@@ -9103,7 +9174,7 @@ h3.ambient-field-label {
}
@media (max-width: 900px) {
.inbox-item-aside {
- width: min(960px, 100%);
+ width: min(var(--content-primary-width), 100%);
margin: 14px auto 0;
}
}
@@ -9112,9 +9183,9 @@ h3.ambient-field-label {
.inbox-page:has(.inbox-item-aside) {
display: grid;
- grid-template-columns: minmax(0, 960px) minmax(0, 330px);
+ grid-template-columns: minmax(0, var(--content-primary-width)) minmax(0, var(--content-aside-width));
grid-template-rows: auto 1fr;
- column-gap: 18px;
+ column-gap: var(--content-gap);
justify-content: center;
}
.inbox-page:has(.inbox-item-aside) .pane-head,
@@ -9709,7 +9780,7 @@ h3.ambient-field-label {
.inbox-surface.compact .inbox-item-detail {
padding: 2px 10px 12px;
}
-.inbox-surface.compact .inbox-sync-line span:last-child {
+.inbox-surface.compact .inbox-sync-line > .inbox-sync-status {
display: none;
}
.inbox-surface[data-density="min"] .inbox-item-sub,
@@ -9720,246 +9791,6 @@ h3.ambient-field-label {
.inbox-surface[data-density="min"] .inbox-chip:has(.inbox-chip-count) {
padding-right: 14px;
}
-.draft-review-pane-host {
- overflow: hidden;
-}
-.draft-review-surface {
- flex: 1;
- min-height: 0;
- height: 100%;
- display: grid;
- grid-template-columns: 208px minmax(0, 1fr);
-}
-.draft-review-surface.compact {
- grid-template-columns: 156px minmax(0, 1fr);
-}
-.rv-side {
- border-right: 1px solid var(--border);
- display: flex;
- flex-direction: column;
- min-height: 0;
-}
-.rv-seg {
- display: flex;
- gap: 2px;
- padding: 6px 8px;
- border-bottom: 1px solid var(--border);
- background: var(--background);
-}
-.rv-seg-btn {
- flex: 1;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 4px;
- border: 1px solid transparent;
- background: none;
- color: var(--muted-foreground);
- border-radius: 6px;
- padding: 3px 4px;
- font: inherit;
- font-size: 11px;
- font-weight: 600;
- cursor: pointer;
-}
-.rv-seg-btn:hover {
- color: var(--foreground);
- background: color-mix(in srgb, var(--foreground) 5%, transparent);
-}
-.rv-seg-btn.on {
- color: var(--foreground);
- background: color-mix(in srgb, var(--accent) 12%, transparent);
- border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
-}
-.rv-seg-count {
- font-size: 9.5px;
- opacity: 0.75;
-}
-.rv-scroll {
- flex: 1;
- min-height: 0;
- overflow-y: auto;
- padding-bottom: 12px;
-}
-.rv-row {
- display: flex;
- align-items: flex-start;
- gap: 7px;
- width: 100%;
- padding: 6px 9px;
- border: 0;
- border-left: 2px solid transparent;
- background: none;
- font: inherit;
- text-align: left;
- cursor: pointer;
-}
-.rv-row:hover {
- background: color-mix(in srgb, var(--foreground) 4%, transparent);
-}
-.rv-row.active {
- background: color-mix(in srgb, var(--accent) 9%, transparent);
- border-left-color: var(--accent);
-}
-.rv-glyph {
- flex: none;
- display: inline-flex;
- margin-top: 2px;
- color: var(--muted-foreground);
-}
-.rv-row.active .rv-glyph,
-.rv-row:hover .rv-glyph {
- color: var(--foreground);
-}
-.rv-body {
- flex: 1;
- min-width: 0;
- display: flex;
- flex-direction: column;
-}
-.rv-l1 {
- display: flex;
- align-items: baseline;
- gap: 6px;
- min-width: 0;
-}
-.rv-from {
- font-size: 12.5px;
- font-weight: 600;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.rv-time {
- margin-left: auto;
- flex: none;
- font-size: 10.5px;
- color: var(--muted-foreground);
-}
-.rv-l2 {
- font-size: 11.5px;
- color: var(--muted-foreground);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- line-height: 1.35;
-}
-.rv-drafted {
- flex: none;
- display: inline-flex;
- margin-top: 2px;
- color: var(--accent);
-}
-.rv-empty {
- padding: 8px 11px;
- font-size: 11.5px;
- color: var(--muted-foreground);
-}
-.rv-main {
- min-width: 0;
- overflow-y: auto;
- padding: 14px 16px 24px;
-}
-.rv-empty-detail {
- padding-top: 24px;
-}
-.rv-detail-head {
- display: flex;
- align-items: baseline;
- gap: 10px;
- min-width: 0;
- margin-bottom: 10px;
-}
-.rv-detail-title {
- font-size: 15px;
- font-weight: 650;
- letter-spacing: -0.01em;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.rv-detail-from {
- flex: none;
- font-size: 11.5px;
- color: var(--muted-foreground);
-}
-.draft-review-surface .inbox-draft {
- margin-top: 10px;
-}
-.mini-convo {
- margin-top: 14px;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- overflow: hidden;
-}
-.mini-convo-head {
- display: flex;
- align-items: center;
- gap: 7px;
- width: 100%;
- padding: 7px 11px;
- border: 0;
- background: color-mix(in srgb, var(--foreground) 3%, transparent);
- font: inherit;
- cursor: pointer;
- text-align: left;
-}
-.mini-convo-head:hover {
- background: color-mix(in srgb, var(--foreground) 6%, transparent);
-}
-.mini-convo-caret {
- display: inline-flex;
- color: var(--muted-foreground);
-}
-.mini-convo-title {
- font-size: 12.5px;
- font-weight: 600;
-}
-.mini-convo-sub {
- font-size: 11.5px;
- color: var(--muted-foreground);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.mini-convo-spacer {
- flex: 1;
-}
-.mini-convo-open {
- flex: none;
- font-size: 11.5px;
- color: var(--accent);
- font-weight: 600;
-}
-.mini-convo-body {
- display: flex;
- flex-direction: column;
- max-height: 380px;
- border-top: 1px solid var(--border);
-}
-.mini-convo-body .custom-chat-shell {
- flex: 1;
- min-height: 0;
-}
-.mini-convo-body .chat-scroll {
- --chat-scroll-pad-top: 8px;
- --chat-edge-space: 12px;
- --chat-pad: 12px;
- container-type: normal;
- max-height: 250px;
- padding: var(--chat-scroll-pad-top) var(--chat-pad) var(--chat-scroll-pad-bottom);
-}
-.mini-convo-body .message-stack {
- width: 100%;
-}
-.mini-convo-body .message-stack .user-row:not(:has(~ .user-row)):not(.pin-expanded) .user-bubble > .pin-content {
- max-height: 100px;
-}
-.mini-convo-missing {
- padding: 10px 12px;
- font-size: 12px;
- color: var(--muted-foreground);
-}
.loop-row {
display: flex;
align-items: center;
@@ -12050,3 +11881,27 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {
.subagent-mail-row + .assistant-row {
margin-bottom: 8px;
}
+
+.inbox-sent-row {
+ text-decoration: none;
+}
+.inbox-sent-more {
+ margin: 16px 0;
+}
+.inbox-sent-actions {
+ justify-content: flex-end;
+}
+.inbox-sent-message .inbox-context-text {
+ margin-top: 8px;
+}
+.inbox-sent-recipients {
+ margin-top: 2px;
+ color: var(--muted-foreground);
+ font-size: 11.5px;
+}
+.inbox-sent-attachments {
+ margin-top: 8px;
+ font-size: 11.5px;
+ color: var(--muted-foreground);
+ overflow-wrap: anywhere;
+}
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index f7a250dea..a29de4f96 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -4,6 +4,7 @@ import { html, nothing, render, type TemplateResult } from "lit";
import {
Box,
Brain,
+ CalendarDays,
Clock,
Files,
Folder,
@@ -86,9 +87,9 @@ import { attachTooltip, hideTooltip, tip } from "./tooltip";
import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";
import { openDeployById, renderDeploys } from "./deploys";
import { renderMemory, resetMemoryState } from "./memory";
+import { renderCalendar } from "./calendar";
import {
inboxOpenCount,
- openInboxItemById,
refreshInbox,
renderInbox,
resetActiveInboxItem,
@@ -204,6 +205,7 @@ function resetSidebarWidth(): void {
const ICON = {
newChat: Plus,
inbox: InboxGlyph,
+ calendar: CalendarDays,
chats: MessageSquare,
contexts: Folder,
files: Files,
@@ -613,7 +615,8 @@ export function renderSidebarTop(): void {
render(
html`
<nav class="nav quick-nav" @click=${onNavClick}>
- ${navRow("chats", ICON.home, "Home")} ${can("inbox") ? inboxNavRow() : nothing}
+ ${navRow("chats", ICON.home, "Home")}
+ ${can("inbox") ? html`${inboxNavRow()} ${navRow("calendar", ICON.calendar, "Calendar")}` : nothing}
${actionRow(Search, "Search", () => {
hideTooltip();
openChatSearch();
@@ -694,6 +697,9 @@ export function switchView(v: View): void {
case "inbox":
void renderInbox();
break;
+ case "calendar":
+ renderCalendar();
+ break;
case "webhooks":
void renderWebhooksPage();
break;
@@ -758,6 +764,9 @@ function refreshActiveView(v: View): void {
case "inbox":
void renderInbox();
break;
+ case "calendar":
+ renderCalendar();
+ break;
case "contexts":
void renderContexts();
break;
@@ -1102,9 +1111,9 @@ export async function boot(): Promise<void> {
if (wanted === "deploys" && wantedItem) openDeployById(wantedItem);
if (wanted === "crons" && wantedItem) openCronById(wantedItem);
if (wanted === "webhooks" && wantedItem) openWebhookById(wantedItem);
- if (wanted === "inbox" && wantedItem) openInboxItemById(wantedItem);
if (wanted === "skills" && wantedItem) openSkillById(wantedItem);
switchView(wanted as View);
+ if (wanted === "inbox") routeInboxHistory(wantedItem);
} else if (connectedProvider && sessionsState.list.length) {
const recent = [...sessionsState.list].sort((a, b) => activityOf(b) - activityOf(a))[0]!;
exitSplitIfActive();
diff --git a/plugins/web-ui/test/calendar-view.test.ts b/plugins/web-ui/test/calendar-view.test.ts
new file mode 100644
index 000000000..71fd1399f
--- /dev/null
+++ b/plugins/web-ui/test/calendar-view.test.ts
@@ -0,0 +1,30 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { deepLinkPath, parseDeepLink } from "../src/deep-link.ts";
+import { documentTitle, PRODUCT_TITLE } from "../src/document-title.ts";
+
+const calendar = readFileSync(new URL("../src/calendar.ts", import.meta.url), "utf8");
+const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");
+const shellState = readFileSync(new URL("../src/shell-state.ts", import.meta.url), "utf8");
+
+test("calendar is a first-class empty view directly below Inbox", () => {
+ assert.match(shellState, /"chats",\s*"inbox",\s*"calendar",\s*"contexts"/);
+ assert.match(shell, /inboxNavRow\(\).*navRow\("calendar", ICON\.calendar, "Calendar"\)/s);
+ assert.match(shell, /case "calendar":\s*renderCalendar\(\);/);
+ assert.match(calendar, /host\.className = "pane content-wide-page"/);
+ assert.match(calendar, /<div class="pane-head">/);
+ assert.match(calendar, /<h1 class="pane-title">Calendar<\/h1>/);
+ assert.match(calendar, /Coming soon\./);
+});
+
+test("calendar reuses the Inbox permission gate", () => {
+ assert.match(shell, /can\("inbox"\) \? html`\$\{inboxNavRow\(\)\} \$\{navRow\("calendar"/);
+ assert.match(shellState, /if \(view === "inbox" \|\| view === "calendar"\) return can\("inbox"\);/);
+});
+
+test("calendar has a stable route and document title", () => {
+ assert.equal(deepLinkPath("", "calendar", null), "/calendar");
+ assert.deepEqual(parseDeepLink("", "/calendar", ""), { view: "calendar", session: null, item: null });
+ assert.equal(documentTitle("calendar"), `Calendar · ${PRODUCT_TITLE}`);
+});
diff --git a/plugins/web-ui/test/deep-link.test.ts b/plugins/web-ui/test/deep-link.test.ts
index 50db42d98..ce9845bab 100644
--- a/plugins/web-ui/test/deep-link.test.ts
+++ b/plugins/web-ui/test/deep-link.test.ts
@@ -128,3 +128,15 @@ test("/c/<id> is accepted as an alias for /s/<id> (links shared from Slack)", ()
item: null,
});
});
+
+test("sent and pending email URLs use the same id route shape", () => {
+ for (const base of ["", "/web-ui"]) {
+ const path = deepLinkPath(base, "inbox", null, null, "96e58b52e75bf97f");
+ assert.equal(path, `${base}/inbox/96e58b52e75bf97f`);
+ assert.deepEqual(parseDeepLink(base, path, ""), {
+ view: "inbox",
+ session: null,
+ item: "96e58b52e75bf97f",
+ });
+ }
+});
diff --git a/plugins/web-ui/test/draft-review-pane.test.ts b/plugins/web-ui/test/draft-review-pane.test.ts
deleted file mode 100644
index 8411263bf..000000000
--- a/plugins/web-ui/test/draft-review-pane.test.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-import assert from "node:assert/strict";
-import { test } from "node:test";
-import { JSDOM } from "jsdom";
-import { createServer } from "vite";
-
-const LOOP_ID = "loop-inbox";
-
-const gmailEntry = {
- id: "item-1",
- loopId: LOOP_ID,
- dedupeKey: "gmail:t1",
- state: "held",
- source: "gmail",
- sourcePayload: {
- source: "gmail",
- title: "Renewal terms",
- from: "Dana Silva",
- fromDetail: "[email protected]",
- snippet: "Can you confirm the renewal terms by Friday?",
- receivedAt: Date.now() - 3_600_000,
- gmail: { threadId: "t1", subject: "Renewal terms", to: ["[email protected]"] },
- },
- sourceAt: Date.now() - 3_600_000,
- proposal: {
- data: { to: ["[email protected]"], subject: "Re: Renewal terms", body: "Confirming the terms now." },
- by: "agent",
- at: Date.now(),
- sessionId: "draft-1",
- },
- thread: [],
- updatedAt: Date.now(),
-};
-
-const handledEntry = {
- id: "item-2",
- loopId: LOOP_ID,
- dedupeKey: "slack:c1:1",
- state: "actioned",
- source: "slack",
- sourcePayload: {
- source: "slack",
- title: "deploy question",
- from: "Sam",
- snippet: "Is the deploy done?",
- receivedAt: Date.now() - 7_200_000,
- slack: { channelId: "C1", channelLabel: "#deploys", ts: "1" },
- },
- sourceAt: Date.now() - 7_200_000,
- thread: [],
- actedAt: Date.now() - 3_000_000,
- actionKind: "send",
- updatedAt: Date.now(),
-};
-
-function ledgerResponse(path: string, entries: unknown[]): Response | null {
- if (path.includes("/api/inbox")) return Response.json({ loop: { id: LOOP_ID }, syncCron: null });
- if (path.includes(`/api/loops/${LOOP_ID}/items`)) return Response.json({ items: entries, counts: {} });
- return null;
-}
-
-const draftSession = {
- id: "draft-1",
- type: "dm",
- scopeId: "personal:owner",
- threadRef: "web:owner:thread-1",
- createdAt: Date.now() - 3_500_000,
- title: "Drafting the renewal reply",
-};
-
-test("the draft review pane lists items, edits the draft, and mounts the drafting session as a real conversation", async () => {
- const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main><div id="pane"></div>', {
- url: "http://localhost/web-ui/?view=chats",
- });
- Object.defineProperty(dom.window, "matchMedia", {
- value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
- });
- const globals = {
- window: dom.window,
- document: dom.window.document,
- location: dom.window.location,
- history: dom.window.history,
- localStorage: dom.window.localStorage,
- navigator: dom.window.navigator,
- HTMLElement: dom.window.HTMLElement,
- HTMLInputElement: dom.window.HTMLInputElement,
- HTMLTextAreaElement: dom.window.HTMLTextAreaElement,
- Node: dom.window.Node,
- Event: dom.window.Event,
- MouseEvent: dom.window.MouseEvent,
- InputEvent: dom.window.InputEvent,
- DragEvent: dom.window.Event,
- requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),
- cancelAnimationFrame: clearTimeout,
- getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
- };
- for (const [key, value] of Object.entries(globals))
- Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
-
- globalThis.fetch = async (input) => {
- const path = String(input);
- const ledger = ledgerResponse(path, [gmailEntry, handledEntry]);
- if (ledger) return ledger;
- if (path.includes("/api/sessions/draft-1/approvals")) return Response.json({ approvals: [] });
- if (path.includes("/api/sessions/draft-1")) return Response.json({ session: draftSession, entries: [] });
- if (path.includes("/api/sessions")) return Response.json({ sessions: [draftSession] });
- if (path.includes("/api/contexts")) return Response.json({ contexts: [] });
- if (path.includes("/api/runtime-config"))
- return Response.json({
- scopeId: "personal:owner",
- approvedHarnesses: ["pi"],
- modelsByHarness: { pi: [] },
- modelCatalog: {},
- effective: { harnessId: "pi", modelId: "default" },
- orgDefault: { harnessId: "pi", modelId: "default", revision: 1 },
- scopeOverride: null,
- });
- throw new Error(`Unexpected request: ${path}`);
- };
-
- const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
- try {
- const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");
- const { splitState } = await vite.ssrLoadModule("/src/split.ts");
- const { sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");
- const { paneKindByKey } = await vite.ssrLoadModule("/src/pane-kinds.ts");
- await vite.ssrLoadModule("/src/draft-review.ts");
- appState.me = { user: "owner", org: "acme", permissions: ["inbox"] };
- appState.currentView = "chats";
- splitState.active = true;
- sessionsState.list = [draftSession];
- sessionsState.loaded = true;
-
- const host = document.querySelector<HTMLElement>("#pane")!;
- const pane = paneKindByKey("draftReview")!.mount({
- host,
- id: "all",
- density: () => "full",
- onDensityChange: () => {},
- });
-
- const until = async (ready: () => boolean, what: string): Promise<void> => {
- for (let i = 0; i < 100; i++) {
- if (ready()) return;
- await new Promise((resolve) => setTimeout(resolve, 20));
- }
- assert.fail(`timed out waiting for ${what}`);
- };
-
- await until(() => host.querySelector(".rv-row") !== null, "the item list");
- const segs = [...host.querySelectorAll(".rv-seg-btn")].map((b) => b.textContent?.replace(/\s+/g, "").trim());
- assert.deepEqual(segs, ["Needsyou1", "Handled1"]);
-
- const row = host.querySelector(".rv-row")!;
- assert.match(row.textContent ?? "", /Dana Silva/);
- assert.ok(row.querySelector(".rv-glyph svg"), "the source glyph is an inline lucide icon");
- assert.equal(row.querySelector(".rv-glyph svg")?.getAttribute("stroke"), "currentColor");
-
- const body = host.querySelector<HTMLTextAreaElement>(".inbox-draft-body")!;
- assert.equal(body.value, "Confirming the terms now.");
- const fieldLabels = [...host.querySelectorAll(".inbox-field span")].map((s) => s.textContent);
- assert.ok(fieldLabels.includes("To") && fieldLabels.includes("Subject"), "gmail drafts edit like email");
-
- await until(() => host.querySelector(".mini-convo-head") !== null, "the steering panel head");
- assert.match(host.querySelector(".mini-convo-head")!.textContent ?? "", /Drafting session/);
- await until(
- () => host.querySelector(".mini-convo .custom-chat-shell .chat-scroll") !== null,
- "the real conversation inside the steering panel",
- );
- assert.ok(
- host.querySelector(".mini-convo .custom-chat-shell .message-stack"),
- "the shell's own message stack renders",
- );
- assert.ok(host.querySelector(".mini-convo .composer-wrap"), "the shell's own composer renders");
-
- const handledBtn = [...host.querySelectorAll<HTMLButtonElement>(".rv-seg-btn")].find((b) =>
- (b.textContent ?? "").includes("Handled"),
- )!;
- handledBtn.click();
- await until(() => (host.querySelector(".rv-row")?.textContent ?? "").includes("#deploys"), "the handled list");
- assert.equal(host.querySelector(".mini-convo"), null, "handled items carry no steering panel");
- assert.match(host.querySelector(".inbox-handled-note")?.textContent ?? "", /Reply sent/);
-
- pane.dispose();
- } finally {
- await vite.close();
- dom.window.close();
- }
-});
-
-test("disposing the pane while the drafting session loads never resurrects the conversation", async () => {
- const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main><div id="pane"></div>', {
- url: "http://localhost/web-ui/?view=chats",
- });
- Object.defineProperty(dom.window, "matchMedia", {
- value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
- });
- const globals = {
- window: dom.window,
- document: dom.window.document,
- location: dom.window.location,
- history: dom.window.history,
- localStorage: dom.window.localStorage,
- navigator: dom.window.navigator,
- HTMLElement: dom.window.HTMLElement,
- HTMLInputElement: dom.window.HTMLInputElement,
- HTMLTextAreaElement: dom.window.HTMLTextAreaElement,
- Node: dom.window.Node,
- Event: dom.window.Event,
- MouseEvent: dom.window.MouseEvent,
- InputEvent: dom.window.InputEvent,
- DragEvent: dom.window.Event,
- requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),
- cancelAnimationFrame: clearTimeout,
- getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
- };
- for (const [key, value] of Object.entries(globals))
- Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
-
- let transcriptRequested = false;
- let releaseTranscript = (): void => {};
- const transcriptGate = new Promise<void>((resolve) => {
- releaseTranscript = resolve;
- });
- globalThis.fetch = async (input) => {
- const path = String(input);
- const ledger = ledgerResponse(path, [gmailEntry]);
- if (ledger) return ledger;
- if (path.includes("/api/sessions/draft-1/approvals")) return Response.json({ approvals: [] });
- if (path.includes("/api/sessions/draft-1")) {
- transcriptRequested = true;
- await transcriptGate;
- return Response.json({ session: draftSession, entries: [] });
- }
- if (path.includes("/api/sessions")) return Response.json({ sessions: [draftSession] });
- if (path.includes("/api/contexts")) return Response.json({ contexts: [] });
- if (path.includes("/api/runtime-config"))
- return Response.json({
- scopeId: "personal:owner",
- approvedHarnesses: ["pi"],
- modelsByHarness: { pi: [] },
- modelCatalog: {},
- effective: { harnessId: "pi", modelId: "default" },
- orgDefault: { harnessId: "pi", modelId: "default", revision: 1 },
- scopeOverride: null,
- });
- throw new Error(`Unexpected request: ${path}`);
- };
-
- const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
- try {
- const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");
- const { splitState } = await vite.ssrLoadModule("/src/split.ts");
- const { sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");
- const { allConversations } = await vite.ssrLoadModule("/src/conversations.ts");
- const { paneKindByKey } = await vite.ssrLoadModule("/src/pane-kinds.ts");
- await vite.ssrLoadModule("/src/draft-review.ts");
- appState.me = { user: "owner", org: "acme", permissions: ["inbox"] };
- appState.currentView = "chats";
- splitState.active = true;
- sessionsState.list = [draftSession];
- sessionsState.loaded = true;
-
- const host = document.querySelector<HTMLElement>("#pane")!;
- const pane = paneKindByKey("draftReview")!.mount({
- host,
- id: "all",
- density: () => "full",
- onDensityChange: () => {},
- });
-
- const until = async (ready: () => boolean, what: string): Promise<void> => {
- for (let i = 0; i < 100; i++) {
- if (ready()) return;
- await new Promise((resolve) => setTimeout(resolve, 20));
- }
- assert.fail(`timed out waiting for ${what}`);
- };
-
- await until(() => transcriptRequested, "the transcript request");
- const liveBefore = allConversations().length;
- assert.ok(liveBefore > 0, "the steering conversation is live while loading");
-
- pane.dispose();
- assert.equal(allConversations().length, liveBefore - 1, "disposing the pane releases its conversation");
-
- releaseTranscript();
- await new Promise((resolve) => setTimeout(resolve, 250));
-
- assert.equal(host.querySelector(".mini-convo .message-stack"), null, "no transcript mounts after disposal");
- assert.equal(host.querySelector(".mini-convo .composer-wrap"), null, "no composer mounts after disposal");
- assert.equal(allConversations().length, liveBefore - 1, "nothing re-registers the disposed conversation");
- } finally {
- await vite.close();
- dom.window.close();
- }
-});
diff --git a/plugins/web-ui/test/draft-review-source.test.ts b/plugins/web-ui/test/draft-review-source.test.ts
deleted file mode 100644
index 69addb794..000000000
--- a/plugins/web-ui/test/draft-review-source.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import test from "node:test";
-
-const read = (f: string): string => readFileSync(new URL(`../src/${f}`, import.meta.url), "utf8");
-const dr = read("draft-review.ts");
-const inbox = read("inbox.ts");
-const main = read("main.ts");
-const css = read("shell.css");
-
-test("draft review registers as a pane kind under its own params key", () => {
- assert.match(dr, /registerPaneKind\(\{/);
- assert.match(dr, /paramsKey: "draftReview"/, "saved layouts persist the pane under draftReview");
- assert.match(main, /import "\.\/draft-review";/, "registration must run at boot");
- assert.match(inbox, /beginPaneKindDrag\("draftReview", surface\.viewId\)/, "the inbox toolbar chip starts the drag");
- assert.match(
- dr,
- /badge: \(id\) => \(can\("inbox"\) \? inboxOpenCount\(id\) : 0\)/,
- "the gated tab badge counts what needs you",
- );
-});
-
-test("the steering panel is a real conversation bound to the drafting session", () => {
- assert.match(dr, /createConversation\(\{/, "the panel is the shell's own conversation, not a mock");
- assert.match(dr, /item\.draftSessionId/, "bound to the server-stamped drafting session");
- assert.match(dr, /openSessionInto\(steer\.conversation, session\)/);
- assert.match(dr, /disposeConversation\(surface\.steer\.conversation\)/, "and released when the item changes");
- assert.doesNotMatch(
- dr,
- /message-stack|chat-scroll|user-bubble|steer-label|composer-wrap/,
- "no hand-built chat widget — the conversation renders its own form factor",
- );
-});
-
-test("a finished steer refreshes the inbox so the rewritten draft lands in place", () => {
- assert.match(dr, /if \(steer\.working && !state\.working\) void refreshInbox\(\{ silent: true \}\);/);
-});
-
-test("switching items persists the draft you were editing", () => {
- assert.match(dr, /if \(previous && previous\.id !== item\.id\) void persistDraft\(previous\);/);
-});
-
-test("source glyphs are monochrome line icons painted in currentColor", () => {
- assert.match(dr, /icon\(gmail \? Mail : Hash, 13\)/, "lucide stroke icons inherit the row's own colour");
- assert.doesNotMatch(dr, /<svg|fill="#|icon-mail\.svg|icon-slack\.svg/, "no coloured brand art");
- const glyph = css.match(/\.rv-glyph \{[^}]*\}/)?.[0] ?? "";
- assert.match(glyph, /color: var\(--muted-foreground\);/);
-});
-
-test("the mini conversation scales the shell's chat classes instead of inventing new ones", () => {
- assert.match(css, /\.mini-convo-body \.custom-chat-shell \{/);
- assert.match(css, /\.mini-convo-body \.chat-scroll \{/);
-});
-
-test("a draft review pane keeps the inbox poll alive and redraws with it", () => {
- assert.match(inbox, /export function attachInboxSurface/);
- assert.match(inbox, /\[\.\.\.externalSurfaces\]\.some\(\(s\) => s\.visible\(\)\)/);
- assert.match(dr, /attachInboxSurface\(\{/);
-});
diff --git a/plugins/web-ui/test/inbox-archive-toast.test.ts b/plugins/web-ui/test/inbox-archive-toast.test.ts
new file mode 100644
index 000000000..cf4b82d6f
--- /dev/null
+++ b/plugins/web-ui/test/inbox-archive-toast.test.ts
@@ -0,0 +1,69 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { JSDOM, VirtualConsole } from "jsdom";
+import { createServer } from "vite";
+
+test("dismiss toast undoes the correct item and failed dismissals do not offer undo", async () => {
+ const domErrors: Error[] = [];
+ const virtualConsole = new VirtualConsole();
+ virtualConsole.on("jsdomError", (error) => domErrors.push(error));
+ const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {
+ url: "http://localhost/web-ui/",
+ virtualConsole,
+ });
+ Object.defineProperty(dom.window, "matchMedia", {
+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ });
+ for (const key of ["window", "document", "location", "history", "localStorage", "navigator", "HTMLElement", "Node"])
+ Object.defineProperty(globalThis, key, {
+ configurable: true,
+ value: key === "window" ? dom.window : dom.window[key as keyof typeof dom.window],
+ });
+ Object.defineProperty(globalThis, "getComputedStyle", {
+ configurable: true,
+ value: dom.window.getComputedStyle.bind(dom.window),
+ });
+ const originalFetch = globalThis.fetch;
+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
+ try {
+ await vite.ssrLoadModule("/src/shell.ts");
+ const { setItemStatus, toInboxItem, inboxState, resetInboxState } = await vite.ssrLoadModule("/src/inbox.ts");
+ const entry = {
+ id: "item-1",
+ loopId: "loop-1",
+ state: "held",
+ source: "gmail",
+ sourcePayload: { title: "Example", from: "Sam", snippet: "Hello" },
+ thread: [],
+ };
+ const item = toInboxItem(entry);
+ inboxState.items = [item];
+ const actions: string[] = [];
+ globalThis.fetch = async (_url, options) => {
+ const { kind } = JSON.parse(String(options?.body));
+ actions.push(kind);
+ return Response.json({ item: { ...entry, state: kind === "dismiss" ? "dismissed" : "held" } });
+ };
+ assert.equal(await setItemStatus(item, "dismissed"), true);
+ const toast = document.querySelector(".action-toast")!;
+ assert.match(toast.textContent!, /Dismissed from inbox/);
+ const undo = toast.querySelector<HTMLButtonElement>("button")!;
+ undo.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.deepEqual(actions, ["dismiss", "reopen"]);
+ assert.equal(inboxState.items[0].status, "open");
+ assert.equal(document.querySelector(".action-toast"), null);
+ globalThis.fetch = async () => {
+ throw new Error("Offline");
+ };
+ assert.equal(await setItemStatus(item, "dismissed"), false);
+ assert.equal(document.querySelector(".action-toast"), null);
+ assert.equal(inboxState.items[0].status, "open");
+ resetInboxState();
+ assert.deepEqual(domErrors, []);
+ } finally {
+ globalThis.fetch = originalFetch;
+ await vite.close();
+ dom.window.close();
+ }
+});
diff --git a/plugins/web-ui/test/inbox-sent-navigation.test.ts b/plugins/web-ui/test/inbox-sent-navigation.test.ts
new file mode 100644
index 000000000..619eda401
--- /dev/null
+++ b/plugins/web-ui/test/inbox-sent-navigation.test.ts
@@ -0,0 +1,185 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { JSDOM, VirtualConsole } from "jsdom";
+import { createServer } from "vite";
+import type { LedgerItem } from "../src/inbox.ts";
+
+test("Sent opens from a split pane and retains drafts and queued sends after navigation", async () => {
+ const domErrors: Error[] = [];
+ const virtualConsole = new VirtualConsole();
+ virtualConsole.on("jsdomError", (error) => domErrors.push(error));
+ const dom = new JSDOM('<!doctype html><div id="app"></div><main></main><div id="split"></div>', {
+ url: "https://review.example/",
+ virtualConsole,
+ });
+ Object.defineProperty(dom.window, "matchMedia", {
+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ });
+ for (const key of [
+ "window",
+ "document",
+ "location",
+ "history",
+ "localStorage",
+ "navigator",
+ "HTMLElement",
+ "Node",
+ "DOMParser",
+ ])
+ Object.defineProperty(globalThis, key, {
+ configurable: true,
+ value: key === "window" ? dom.window : dom.window[key as keyof typeof dom.window],
+ });
+ Object.defineProperty(globalThis, "getComputedStyle", {
+ configurable: true,
+ value: dom.window.getComputedStyle.bind(dom.window),
+ });
+ const originalFetch = globalThis.fetch;
+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
+ const waitFor = async (condition: () => boolean): Promise<void> => {
+ for (let i = 0; i < 100 && !condition(); i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.ok(condition());
+ };
+ try {
+ await vite.ssrLoadModule("/src/shell.ts");
+ const inbox = await vite.ssrLoadModule("/src/inbox.ts");
+ const sent = await vite.ssrLoadModule("/src/sent-mail.ts");
+ const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");
+ const { splitState } = await vite.ssrLoadModule("/src/split.ts");
+ const message = {
+ id: "message-1",
+ threadId: "thread-1",
+ to: "Alex",
+ subject: "Subject",
+ snippet: "Sent body",
+ sentAt: 1,
+ };
+ const ledger: LedgerItem = {
+ id: "sent-ledger",
+ loopId: "loop-1",
+ dedupeKey: "sent-chat:thread-1",
+ state: "held",
+ source: "gmail",
+ sourcePayload: {
+ sentChat: true,
+ title: "Subject",
+ from: "Sam",
+ gmail: { threadId: "thread-1", to: ["Alex"], cc: ["Chris"] },
+ },
+ proposal: { data: { body: "" }, by: "human", at: 10 },
+ thread: [],
+ updatedAt: 10,
+ };
+ const actions: Array<{ kind: string; args: { proposal: Record<string, unknown>; expectedProposalAt: number } }> =
+ [];
+ let holdEdit = false;
+ let releaseEdit: (() => void) | undefined;
+ globalThis.fetch = async (input, options) => {
+ const url = String(input);
+ if (url === "/api/inbox") return Response.json({ loop: { id: "loop-1" }, syncCron: null });
+ if (url === "/api/loops/loop-1/items") return Response.json({ items: [] });
+ if (url.startsWith("/api/inbox/sent?"))
+ return Response.json({ messages: [message], accountType: "default", accountEmail: "[email protected]" });
+ if (url.startsWith("/api/inbox/sent/"))
+ return Response.json({ ...message, from: "Sam", cc: "Chris", body: "Sent body", html: false, attachments: [] });
+ if (url === "/api/inbox/sent-chat") {
+ const body = JSON.parse(String(options?.body));
+ assert.equal(body.accountType, "default");
+ assert.equal(body.messageId, message.id);
+ return Response.json({ item: ledger });
+ }
+ if (url.endsWith("/action")) {
+ const action = JSON.parse(String(options?.body));
+ actions.push(action);
+ if (action.kind === "edit") {
+ if (holdEdit)
+ await new Promise<void>((resolve) => {
+ releaseEdit = resolve;
+ });
+ ledger.proposal = { data: action.args.proposal, by: "human", at: ledger.proposal!.at + 1 };
+ }
+ if (action.kind === "send") ledger.state = "actioned";
+ return Response.json({ item: ledger });
+ }
+ return Response.json({});
+ };
+ appState.me = { user: "sam", org: "test", permissions: ["inbox"] };
+ appState.mainEl = document.querySelector("main");
+ appState.currentView = "chats";
+ splitState.active = true;
+ inbox.inboxState.loaded = true;
+ inbox.inboxState.loopId = "loop-1";
+ inbox.inboxState.fetchedAt = Date.now();
+ const pane = document.getElementById("split")!;
+ const mounted = inbox.mountInboxPane({ host: pane, viewId: "all", density: () => "full", onDensityChange() {} });
+ [...pane.querySelectorAll<HTMLButtonElement>('[role="tab"]')]
+ .find((button) => button.textContent!.trim() === "Sent")!
+ .click();
+ await waitFor(() => Boolean(pane.querySelector(".inbox-sent-row")));
+ pane.querySelector<HTMLButtonElement>(".inbox-sent-row")!.click();
+ await waitFor(() => Boolean(document.querySelector("main .inbox-draft-body")));
+ assert.equal(appState.currentView, "inbox");
+ assert.equal(splitState.active, false);
+ assert.match(location.pathname, /\/inbox\/message-1$/);
+ assert.match(document.querySelector("main .inbox-sent-message")!.textContent!, /Sent body/);
+ assert.ok(document.querySelector("main .inbox-chat"));
+ assert.deepEqual(inbox.inboxState.items, []);
+ mounted.dispose();
+ pane.remove();
+
+ const bodyInput = (): HTMLTextAreaElement => document.querySelector(".inbox-draft-body")!;
+ const editBody = (value: string): void => {
+ bodyInput().value = value;
+ bodyInput().dispatchEvent(new dom.window.Event("input"));
+ };
+ const close = (): void => document.querySelector<HTMLButtonElement>(".context-back")!.click();
+ editBody("Save without blur");
+ close();
+ await waitFor(() => ledger.proposal!.data.body === "Save without blur");
+ assert.equal(sent.selectedSentChat(), null);
+ assert.equal(actions.length, 1);
+
+ await sent.openSentEmail(message, inbox.drawAll);
+ editBody("Queued save");
+ bodyInput().dispatchEvent(new dom.window.Event("blur"));
+ inbox.routeInboxHistory("sent");
+ await waitFor(() => ledger.proposal!.data.body === "Queued save");
+ assert.equal(actions.length, 2);
+
+ await sent.openSentEmail(message, inbox.drawAll);
+ editBody("Saving first version");
+ holdEdit = true;
+ bodyInput().dispatchEvent(new dom.window.Event("blur"));
+ await waitFor(() => Boolean(releaseEdit));
+ editBody("Send the latest version");
+ const recipients = '"Doe, Jane" <[email protected]>, Alex <[email protected]>';
+ const headers = document.querySelectorAll<HTMLInputElement>(".inbox-draft-headers input");
+ for (const header of [headers[0]!, headers[1]!]) {
+ header.value = recipients;
+ header.dispatchEvent(new dom.window.Event("input"));
+ }
+ [...document.querySelectorAll<HTMLButtonElement>("button")]
+ .find((button) => button.textContent!.trim() === "Send reply")!
+ .click();
+ inbox.selectInboxView("all");
+ inbox.drawAll();
+ holdEdit = false;
+ releaseEdit!();
+ await waitFor(() => ledger.state === "actioned");
+ assert.deepEqual(
+ actions.map((action) => action.kind),
+ ["edit", "edit", "edit", "send"],
+ );
+ assert.equal(actions.at(-1)!.args.proposal.body, "Send the latest version");
+ assert.equal(actions.at(-1)!.args.expectedProposalAt, ledger.proposal!.at);
+ assert.deepEqual(actions.at(-1)!.args.proposal.to, [recipients]);
+ assert.deepEqual(actions.at(-1)!.args.proposal.cc, [recipients]);
+ await waitFor(() => inbox.inboxState.notice === "Reply sent by email.");
+ inbox.resetInboxState();
+ assert.deepEqual(domErrors, []);
+ } finally {
+ globalThis.fetch = originalFetch;
+ await vite.close();
+ dom.window.close();
+ }
+});
diff --git a/plugins/web-ui/test/inbox-source.test.ts b/plugins/web-ui/test/inbox-source.test.ts
index 659974e12..74fefbe22 100644
--- a/plugins/web-ui/test/inbox-source.test.ts
+++ b/plugins/web-ui/test/inbox-source.test.ts
@@ -8,10 +8,9 @@ const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");
const shellState = readFileSync(new URL("../src/shell-state.ts", import.meta.url), "utf8");
const server = readFileSync(new URL("../server/index.ts", import.meta.url), "utf8");
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
-const draftReview = readFileSync(new URL("../src/draft-review.ts", import.meta.url), "utf8");
test("inbox is a first-class view with a draggable sidebar entry", () => {
- assert.match(shellState, /"chats",\s*"inbox",\s*"contexts"/);
+ assert.match(shellState, /"chats",\s*"inbox",\s*"calendar",\s*"contexts"/);
assert.match(shell, /case "inbox":\s*void renderInbox\(\);/);
assert.match(shell, /data-view="inbox"/);
assert.match(shell, /application\/x-webui-inbox/);
@@ -19,13 +18,11 @@ test("inbox is a first-class view with a draggable sidebar entry", () => {
});
test("inbox access rides the existing permissions plumbing", () => {
- assert.match(shell, /can\("inbox"\) \? inboxNavRow\(\) : nothing/);
- assert.match(shellState, /if \(view === "inbox"\) return can\("inbox"\);/);
+ assert.match(shell, /can\("inbox"\) \? html`\$\{inboxNavRow\(\)\}/);
+ assert.match(shellState, /if \(view === "inbox" \|\| view === "calendar"\) return can\("inbox"\);/);
assert.match(server, /process\.env\.INBOX_USERS/);
assert.match(server, /INBOX_USERS\.has\("all"\) \|\| INBOX_USERS\.has\(principalId\.trim\(\)\.toLowerCase\(\)\)/);
assert.match(server, /if \(isInboxUser\(user\)\) permissions\.push\("inbox"\);/);
- assert.match(draftReview, /if \(!can\("inbox"\)\)/);
- assert.match(draftReview, /can\("inbox"\) \? inboxOpenCount\(id\) : 0/);
assert.match(inbox, /if \(!can\("inbox"\)\) return;/);
});
@@ -49,11 +46,6 @@ test("an inbox drag paints drop zones on every existing pane", () => {
/render\(paneDrag \? paneZonesTpl\(this\.panelId\) : nothing/,
"zones render for any pane drag, inbox included",
);
- assert.match(
- inbox,
- /beginPaneKindDrag\("draftReview", surface\.viewId\)/,
- "draft review enters the shared drag path",
- );
assert.match(shell, /beginPaneKindDrag\("inboxView", "all"\)/, "the sidebar row drags the whole inbox");
assert.doesNotMatch(inbox, /beginPaneKindDrag\("inboxView"/, "view chips are plain tabs, not drag handles");
});
@@ -71,9 +63,10 @@ test("email items edit like an email; slack items like slack", () => {
test("the address keeps naming the open item, even after switchView writes the bare view path", () => {
assert.match(
inbox,
- /if \(fullSurface\.selectedId && !openItem && inboxState\.loaded\) fullSurface\.selectedId = null;\s*(\/\*[\s\S]*?\*\/\s*)?syncItemUrl\(fullSurface\.selectedId\);/,
+ /syncInboxUrl\(openSentEmail\?\.id \?\? fullSurface\.selectedId\);/,
"every draw re-states the URL from the selection it just rendered",
);
+ assert.match(inbox, /void openSentEmailById\(sentId, drawAll\);/, "unknown inbox ids resolve through sent mail");
assert.match(
shell,
/const next = deepLinkPath\(UI_BASE, appState\.currentView, sessionId, contextsState\.selected\);/,
@@ -81,10 +74,23 @@ test("the address keeps naming the open item, even after switchView writes the b
);
const draw = inbox.match(/function drawFull\(\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
assert.match(draw, /pendingItemId/, "a deep link reaches the draw as pendingItemId");
- assert.match(inbox, /function syncItemUrl\(itemId: string \| null, push = false\)/);
+ assert.match(inbox, /function syncInboxUrl\(itemId: string \| null, push = false\)/);
assert.match(inbox, /if \(appState\.currentView !== "inbox"\) return;/, "and never writes from another view");
});
+test("inbox pills own stable routes that survive refresh and history navigation", () => {
+ assert.match(inbox, /itemId \?\? inboxViewSegment\(fullViewId\)/);
+ assert.match(inbox, /if \(segment === "email"\) return "gmail"/);
+ assert.match(inbox, /if \(surface === fullSurface\) selectInboxView\(v\.id, true\)/);
+ assert.match(inbox, /export function routeInboxHistory\(segment: string \| null\)/);
+ assert.match(shell, /if \(wanted === "inbox"\) routeInboxHistory\(wantedItem\)/);
+ assert.match(shell, /else routeInboxHistory\(item\)/);
+});
+
+test("initial inbox selection is restored after the shell resets the active view", () => {
+ assert.match(shell, /switchView\(wanted as View\);\s*if \(wanted === "inbox"\) routeInboxHistory\(wantedItem\);/);
+});
+
test("every draft links back to the session that produced it", () => {
assert.match(inbox, /draftSessionId/);
assert.match(inbox, /deepLinkPath\(UI_BASE, "chats", item.draftSessionId\)/);
@@ -117,6 +123,17 @@ test("the inbox reads the loop's ledger, not a bespoke inbox endpoint", () => {
assert.match(inbox, /const payload = entry\.sourcePayload;/, "source fields are read out of the opaque payload");
});
+test("localhost can overlay private inbox seed data without checking it into source", () => {
+ assert.match(inbox, /fetch\("\/inbox-seed\.local\.json", \{ cache: "no-store" \}\)/);
+ assert.match(
+ inbox,
+ /if \(!\["localhost", "127\.0\.0\.1", "\[::1\]"\]\.includes\(location\.hostname\)\) return \[\];/,
+ );
+ assert.match(inbox, /const localItems = await fetchLocalInboxItems\(\);/);
+ assert.match(inbox, /inboxState\.items = localItems\.length/);
+ assert.match(inbox, /if \(!inboxState\.items\.length && inboxState\.loopId\) inboxState\.items = await fetchItems/);
+});
+
test("each item carries a follow-up chat with the agent", () => {
assert.match(inbox, /export function chatTpl\(item: InboxItem\): TemplateResult/);
assert.match(inbox, /actionPath\(item, "followup"\)/);
@@ -182,6 +199,46 @@ test("the inbox stylesheet exists and scopes to inbox- classes", () => {
assert.match(css, /\.nav-badge \{/);
});
+test("the inbox list spans the same desktop content width as the item detail", () => {
+ assert.match(
+ css,
+ /\.content-wide-page \{[\s\S]*--content-wide-width: calc\(var\(--content-primary-width\) \+ var\(--content-gap\) \+ var\(--content-aside-width\)\);/,
+ );
+ assert.match(css, /\.inbox-page \.inbox-surface \{\s*width: min\(var\(--content-wide-width\), 100%\);/);
+ assert.match(
+ css,
+ /\.content-wide-page:not\(:has\(\.inbox-item-aside\)\) > \.pane-head \{\s*width: min\(var\(--content-wide-width\), 100%\);\s*max-width: none;/,
+ );
+ assert.match(
+ css,
+ /grid-template-columns: minmax\(0, var\(--content-primary-width\)\) minmax\(0, var\(--content-aside-width\)\);/,
+ );
+});
+
+test("inbox item hover behaves like a sidebar conversation hover", () => {
+ assert.match(css, /\.session:hover \{\s*background: var\(--conversation-hover\);/);
+ assert.match(css, /--inbox-row-hover: color-mix\(in srgb, var\(--foreground\) 4%, var\(--background\)\);/);
+ assert.match(css, /\.inbox-item-summary:hover,[\s\S]*?background: var\(--inbox-row-hover\);/);
+ const reveal = css.match(/\.inbox-item-summary:hover \.inbox-item-dismiss,[\s\S]*?\n\}/)?.[0] ?? "";
+ assert.match(reveal, /opacity: 1;/);
+ assert.doesNotMatch(reveal, /background:|color:|pointer-events:/);
+ assert.match(css, /\.inbox-item-summary:has\(\.inbox-item-dismiss:hover\) \{\s*background: none;/);
+});
+
+test("inbox dividers do not collide with rounded hovered rows", () => {
+ assert.match(css, /\.inbox-item:not\(:last-child\)::after \{[\s\S]*?margin: 0 12px;/);
+ assert.match(
+ css,
+ /\.inbox-item:hover::after,\s*\.inbox-item:has\(\+ \.inbox-item:hover\)::after \{\s*background: transparent;/,
+ );
+ assert.doesNotMatch(css, /\.inbox-item \{\s*border-bottom:/);
+ assert.match(css, /\.inbox-page \.inbox-toolbar \{\s*padding: 8px 0;\s*border-bottom: 0;/);
+});
+
+test("clipped email snippets do not trigger a native hover tooltip", () => {
+ assert.match(css, /\.src-gmail \.inbox-item-snippet \{\s*pointer-events: none;/);
+});
+
test("a send refused because the agent redrafted keeps the person's edit and shows the new draft", () => {
assert.match(inbox, /status === 409 && \/draft changed\/i\.test\(e\.message\)/);
assert.match(inbox, /await refetchItem\(item\);/);
@@ -219,3 +276,8 @@ test("conversation messages use the containing view's scroll instead of clipping
assert.match(context, /flex: none;/);
assert.doesNotMatch(context, /max-height:|overflow-y:/);
});
+
+test("single email pages keep bottom breathing room", () => {
+ const surface = css.match(/\.inbox-item-surface \.inbox-scroll \{[^}]*\}/)?.[0] ?? "";
+ assert.match(surface, /padding-bottom: calc\(64px \+ env\(safe-area-inset-bottom\)\);/);
+});
diff --git a/plugins/web-ui/test/inbox-sync-actions.test.ts b/plugins/web-ui/test/inbox-sync-actions.test.ts
new file mode 100644
index 000000000..7ab5da35f
--- /dev/null
+++ b/plugins/web-ui/test/inbox-sync-actions.test.ts
@@ -0,0 +1,16 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(new URL("../src/inbox.ts", import.meta.url), "utf8");
+
+test("inbox sync states use the same labeled action button", () => {
+ assert.match(source, /function syncActionTpl/);
+ assert.match(source, /class="btn inbox-sync-action"/);
+ assert.match(source, /label: "Refresh"/);
+ assert.match(source, /label: "Sync"/);
+ assert.match(source, /label: "Set up sync"/);
+ assert.match(source, /busyLabel: "Refreshing…"/);
+ assert.match(source, /busyLabel: "Syncing…"/);
+ assert.match(source, /busyLabel: "Setting up…"/);
+});
diff --git a/plugins/web-ui/test/nav-returns-to-index.test.ts b/plugins/web-ui/test/nav-returns-to-index.test.ts
index 25bd295f1..e39417edd 100644
--- a/plugins/web-ui/test/nav-returns-to-index.test.ts
+++ b/plugins/web-ui/test/nav-returns-to-index.test.ts
@@ -38,14 +38,11 @@ test("arriving from another view and re-pressing the nav entry share one reset",
}
});
-test("a deep link still wins: the reset clears the selection but never the pending item", () => {
+test("a deep link still wins after the view switch resets its selection", () => {
const reset = inbox.match(/export function resetActiveInboxItem\(\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
assert.match(reset, /fullSurface\.selectedId = null;/);
assert.doesNotMatch(reset, /pendingItemId/);
- assert.match(
- shell,
- /if \(wanted === "inbox" && wantedItem\) openInboxItemById\(wantedItem\);\s*\n\s*.*\n?\s*switchView\(wanted as View\);/,
- );
+ assert.match(shell, /switchView\(wanted as View\);\s*if \(wanted === "inbox"\) routeInboxHistory\(wantedItem\);/);
});
test("closing an item from the page and from the nav both persist the draft first", () => {
diff --git a/plugins/web-ui/test/sent-mail.test.ts b/plugins/web-ui/test/sent-mail.test.ts
new file mode 100644
index 000000000..442fa10c0
--- /dev/null
+++ b/plugins/web-ui/test/sent-mail.test.ts
@@ -0,0 +1,201 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { JSDOM, VirtualConsole } from "jsdom";
+import { createServer } from "vite";
+
+test("sent view pages Gmail messages and opens the matching Google account", async () => {
+ const domErrors: Error[] = [];
+ const virtualConsole = new VirtualConsole();
+ virtualConsole.on("jsdomError", (error) => domErrors.push(error));
+ const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {
+ url: "http://localhost/web-ui/",
+ virtualConsole,
+ });
+ Object.defineProperty(dom.window, "matchMedia", {
+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
+ });
+ for (const key of [
+ "window",
+ "document",
+ "location",
+ "history",
+ "localStorage",
+ "navigator",
+ "HTMLElement",
+ "Node",
+ "DOMParser",
+ ])
+ Object.defineProperty(globalThis, key, {
+ configurable: true,
+ value: key === "window" ? dom.window : dom.window[key as keyof typeof dom.window],
+ });
+ Object.defineProperty(globalThis, "getComputedStyle", {
+ configurable: true,
+ value: dom.window.getComputedStyle.bind(dom.window),
+ });
+ const originalFetch = globalThis.fetch;
+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });
+ try {
+ await vite.ssrLoadModule("/src/shell.ts");
+ const {
+ loadSentMail,
+ sentMailTpl,
+ sentEmailPageTpl,
+ resetSentMail,
+ openSentEmail,
+ openSentEmailById,
+ selectedSentEmail,
+ sentChatTpl,
+ } = await vite.ssrLoadModule("/src/sent-mail.ts");
+ const { html, render } = await vite.ssrLoadModule("lit");
+ const host = document.getElementById("main")!;
+ const draw = () => render(sentMailTpl(draw), host);
+ const urls: string[] = [];
+ globalThis.fetch = async (input) => {
+ urls.push(String(input));
+ if (String(input).endsWith("/sent-seed.local.json")) return new Response(null, { status: 404 });
+ const next = String(input).includes("pageToken=");
+ return Response.json({
+ accountEmail: "[email protected]",
+ messages: [
+ {
+ id: next ? "older" : "newer",
+ threadId: "thread-1",
+ to: "Alex",
+ subject: "Hello",
+ snippet: "A &amp; B",
+ sentAt: next ? 1000 : 2000,
+ },
+ ],
+ ...(next ? {} : { nextPageToken: "cursor" }),
+ });
+ };
+ await loadSentMail(draw);
+ assert.match(host.textContent!, /A & B/);
+ assert.equal(host.querySelector("a"), null);
+ await loadSentMail(draw, true);
+ assert.equal(host.querySelectorAll(".inbox-sent-row").length, 2);
+ const sentRow = host.querySelector(".inbox-sent-row")!;
+ assert.ok(sentRow.closest(".inbox-item")!.classList.contains("src-gmail"));
+ assert.equal(sentRow.querySelector(".inbox-item-glyph svg")!.getAttribute("width"), "14");
+ assert.match(urls.at(-1)!, /accountType=default/);
+ assert.match(urls.at(-1)!, /pageToken=cursor/);
+ assert.equal(host.querySelector(".inbox-sent-more"), null);
+ let chatRequest: Record<string, unknown> = {};
+ globalThis.fetch = async (input, options) => {
+ if (String(input).endsWith("/inbox/sent-chat")) {
+ chatRequest = JSON.parse(String(options?.body));
+ return Response.json({ item: { id: "company-chat", thread: [] } });
+ }
+ if (String(input).endsWith("/sent-seed.local.json")) return new Response(null, { status: 404 });
+ assert.match(String(input), /accountType=company$/);
+ return Response.json({
+ id: "newer",
+ accountType: "company",
+ threadId: "thread-1",
+ from: "Sam",
+ cc: "",
+ body: "Full sent body",
+ html: false,
+ attachments: [],
+ });
+ };
+ await openSentEmail(
+ {
+ id: "newer",
+ accountType: "company",
+ threadId: "thread-1",
+ to: "Alex",
+ subject: "Hello",
+ snippet: "",
+ sentAt: 2000,
+ },
+ draw,
+ );
+ assert.equal(chatRequest.accountType, "company");
+ assert.equal(chatRequest.messageId, "newer");
+ render(sentEmailPageTpl(draw, html`<div class="inbox-chat">Assistant</div>`), host);
+ assert.equal(host.querySelector(".inbox-context-text")!.textContent, "Full sent body");
+ assert.ok(host.querySelector(".pane-head.inbox-item-head"));
+ assert.ok(host.querySelector(".inbox-surface.inbox-item-surface"));
+ assert.equal(host.querySelector(".inbox-item-aside")!.textContent, "Assistant");
+ assert.ok(host.querySelector(".inbox-item-thread > :last-child")!.classList.contains("inbox-sent-actions"));
+ assert.match(host.querySelector("a")!.href, /authuser=sam%40example.com/);
+ (host.querySelector(".context-back") as HTMLButtonElement).click();
+ render(sentMailTpl(draw), host);
+ assert.equal(host.querySelectorAll(".inbox-sent-row").length, 2);
+ resetSentMail();
+ let detailRequest = "";
+ globalThis.fetch = async (input) => {
+ if (String(input).endsWith("/sent-seed.local.json")) return new Response(null, { status: 404 });
+ if (String(input).endsWith("/inbox/sent-chat")) return Response.json({ item: { id: "chat", thread: [] } });
+ detailRequest = String(input);
+ return Response.json({
+ id: "unlisted",
+ threadId: "thread-unlisted",
+ to: "Alex",
+ subject: "Direct link",
+ snippet: "",
+ sentAt: 2000,
+ from: "Sam",
+ cc: "",
+ body: "Loaded without listing",
+ html: false,
+ attachments: [],
+ });
+ };
+ await openSentEmailById("unlisted", draw);
+ assert.match(detailRequest, /\/api\/inbox\/sent\/unlisted\?accountType=default$/);
+ render(sentEmailPageTpl(draw), host);
+ assert.match(host.textContent!, /Direct link/);
+ assert.match(host.textContent!, /Loaded without listing/);
+ assert.equal(selectedSentEmail().id, "unlisted");
+ render(
+ sentEmailPageTpl(
+ draw,
+ sentChatTpl(draw, (item: { id: string }) => html`<div class="verified-chat">Chat ${item.id}</div>`),
+ ),
+ host,
+ );
+ assert.equal(host.querySelector(".inbox-item-aside .verified-chat")!.textContent, "Chat chat");
+ resetSentMail();
+ const seeded = {
+ accountEmail: "[email protected]",
+ messages: [
+ {
+ id: "seeded",
+ threadId: "thread-seeded",
+ to: "Alex",
+ subject: "Seeded thread",
+ snippet: "First message",
+ sentAt: 2000,
+ conversation: [
+ { from: "Sam", to: "Alex", sentAt: 1000, body: "First message" },
+ { from: "Alex", to: "Sam", sentAt: 2000, body: "Second message", attachments: ["mockup.pdf"] },
+ ],
+ },
+ ],
+ };
+ globalThis.fetch = async () => Response.json(seeded);
+ await loadSentMail(draw);
+ await openSentEmail(seeded.messages[0], draw);
+ render(sentEmailPageTpl(draw), host);
+ assert.equal(host.querySelectorAll(".inbox-sent-message").length, 2);
+ assert.match(host.textContent!, /First message/);
+ assert.match(host.textContent!, /Second message/);
+ assert.match(host.textContent!, /mockup\.pdf/);
+ resetSentMail();
+ globalThis.fetch = async () => {
+ throw new Error("Connect Google");
+ };
+ await loadSentMail(draw);
+ assert.match(host.querySelector('[role="alert"]')!.textContent!, /Connect Google/);
+ assert.equal(host.querySelectorAll(".inbox-sent-row").length, 0);
+ resetSentMail();
+ assert.deepEqual(domErrors, []);
+ } finally {
+ globalThis.fetch = originalFetch;
+ await vite.close();
+ dom.window.close();
+ }
+});
diff --git a/plugins/web-ui/test/user-message-cap.test.ts b/plugins/web-ui/test/user-message-cap.test.ts
index 0e17d0e4e..470a45658 100644
--- a/plugins/web-ui/test/user-message-cap.test.ts
+++ b/plugins/web-ui/test/user-message-cap.test.ts
@@ -6,8 +6,6 @@ const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
const shared = readFileSync(new URL("../src/shared-session.ts", import.meta.url), "utf8");
-const pinned = String.raw`\.message-stack\s+\.user-row:not\(:has\(~ \.user-row\)\):not\(\.pin-expanded\)\s+\.user-bubble\s+>\s+\.pin-content`;
-
test("only the collapsed pinned prompt is capped and overflow clips instead of nesting scrollbars", () => {
const bubble =
css.match(
@@ -20,11 +18,8 @@ test("only the collapsed pinned prompt is capped and overflow clips instead of n
assert.doesNotMatch(base, /max-height|flex/);
});
-test("the scroller is the size container the cap measures, except the content-sized mini convo", () => {
+test("the scroller is the size container the cap measures", () => {
assert.match(css, /\n\.chat-scroll \{[^}]*container-type: size;/);
- const mini = css.match(/\n\.mini-convo-body \.chat-scroll \{[^}]*\}/)?.[0] ?? "";
- assert.match(mini, /container-type: normal;/);
- assert.match(css, new RegExp(String.raw`\n\.mini-convo-body\s+${pinned} \{[^}]*max-height: 100px;`));
assert.match(css, /\n\.readonly-chat \.custom-chat-shell \{[^}]*flex-direction: column;/);
assert.match(css, /\n\.readonly-chat \.chat-scroll \{[^}]*flex: 1;/);
assert.doesNotMatch(chat, /--chat-viewport/);
diff --git a/src/api/routes/connectors.ts b/src/api/routes/connectors.ts
index 687e66405..fea4fa8f7 100644
--- a/src/api/routes/connectors.ts
+++ b/src/api/routes/connectors.ts
@@ -1,3 +1,4 @@
+import { GmailReadError, getSentEmail, listSentEmails } from "../../connectors/gmail-sent.ts";
import { orgId as configOrgId } from "../../config.ts";
import {
authorizeUrl,
@@ -501,7 +502,48 @@ export const connectorRawRoutes: ReadonlyArray<Route<BaseCtx>> = [
{ match: (m, p) => m === "GET" && parseOAuthRoute(p)?.action === "callback", auth: "public", handle: oauthCallback },
];
+export async function gmailSent(ctx: ApiCtx): Promise<void> {
+ const principal = ctx.actor?.p;
+ ctx.res.setHeader("Cache-Control", "no-store");
+ if (!principal) return sendJson(ctx.res, 403, { error: "forbidden", message: "Sign in to read sent mail." });
+ const accountType = ctx.url.searchParams.get("accountType") ?? "default";
+ if (!["default", "personal", "company"].includes(accountType))
+ return sendJson(ctx.res, 400, { error: "bad_request" });
+ const pageToken = ctx.url.searchParams.get("pageToken") ?? undefined;
+ if (pageToken && pageToken.length > 2048) return sendJson(ctx.res, 400, { error: "bad_request" });
+ try {
+ const auth = await ctx.deps.connectorTokens?.connectorDerivedAuth(
+ "gmail.googleapis.com",
+ principal,
+ accountType as AccountType,
+ );
+ if (!auth)
+ return sendJson(ctx.res, 409, {
+ error: "not_connected",
+ message: "Connect this Google account in Settings to see sent mail.",
+ });
+ return sendJson(ctx.res, 200, {
+ ...(ctx.params.messageId
+ ? await getSentEmail(auth.accessToken, ctx.params.messageId)
+ : await listSentEmails(auth.accessToken, pageToken)),
+ accountType,
+ });
+ } catch (error) {
+ let status = 502;
+ if (error instanceof GmailReadError) {
+ if ([401, 403].includes(error.status)) status = 409;
+ else if (error.status === 404) status = 404;
+ }
+ return sendJson(ctx.res, status, {
+ error: "gmail_unavailable",
+ message: error instanceof GmailReadError ? error.message : "Couldn't load sent mail from Gmail. Try again.",
+ });
+ }
+}
+
export const connectorRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ { method: "GET", path: "/v1/connectors/gmail/sent/:messageId", auth: "source", handle: gmailSent },
+ { method: "GET", path: "/v1/connectors/gmail/sent", auth: "source", handle: gmailSent },
{ method: "POST", path: "/v1/connectors/oauth/consent/mint", auth: { aud: "oauth-consent" }, handle: consentMint },
{ method: "GET", path: "/v1/connectors/oauth/consent/redeem/:linkId", auth: "source", handle: consentRedeem },
{ match: (m, p) => m === "GET" && parseOAuthRoute(p)?.action === "start", auth: "source", handle: oauthStart },
diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.ts
index 8532bd8ae..31b28bd0c 100644
--- a/src/api/routes/loop-items.ts
+++ b/src/api/routes/loop-items.ts
@@ -7,7 +7,8 @@ import { type ApiCtx, type Route } from "./route.ts";
import { loadAdministrable, loopDeps, actingPrincipal, type LoopServiceDeps } from "./loops.ts";
import { parseScopeId } from "../../types.ts";
import { isLedgerState, ledgerItemView, ledgerState, sortLedgerItems } from "../../loops/ledger-view.ts";
-import type { IngestEntryInput } from "../../loops/item-ledger.ts";
+import { loopItemId, type IngestEntryInput } from "../../loops/item-ledger.ts";
+import { addressList } from "../../loops/sources/adapter.ts";
import { adapterForItem, sourceAdapter } from "../../loops/sources/index.ts";
import {
ensureInboxLoop,
@@ -270,6 +271,13 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
return sendJson(ctx.res, 200, { item: ledgerItemView(next) });
}
+ if (kind === "reply") {
+ if (!ctx.actor?.p || item.sourcePayload?.sentChat !== true) return sendJson(ctx.res, 403, { error: "forbidden" });
+ const next = await deps.items.reopen(item.id, { sentReply: true });
+ if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "a reply is already being drafted" });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next) });
+ }
+
if (kind === "reopen") {
const next = await deps.items.reopen(item.id);
if (!next) return sendJson(ctx.res, 409, { error: "conflict", message: "this item is not dismissed" });
@@ -313,22 +321,34 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
if (adapter?.actions.includes(kind)) {
const tokens = ctx.deps.loopSourceTokens;
if (!tokens) return sendJson(ctx.res, 404, { error: "not_found", message: "connectors are not wired" });
- const slackClient = ctx.deps.loopSlackClient;
- const result = await adapter.act(
- { owner: loop.owner, actor: proposalAuthor, tokens, ...(slackClient ? { slackClient } : {}) },
- item,
- kind,
- args,
- );
- if (!result.ok) {
- if (result.partial) await deps.items.appendThread(item.id, [{ role: "system", text: result.message }]);
- const statusByReason = { not_connected: 409, bad_item: 400, upstream: 502 } as const;
- return sendJson(ctx.res, statusByReason[result.reason], { error: result.reason, message: result.message });
+ const decisionToken = await deps.items.acquireDecision(item.id);
+ if (!decisionToken)
+ return sendJson(ctx.res, 409, { error: "conflict", message: "an action is already in progress" });
+ try {
+ const current = await deps.items.get(item.id);
+ if (!current || ledgerState(current) === "actioned")
+ return sendJson(ctx.res, 409, { error: "already_actioned", message: "this item was already actioned" });
+ if (current.proposal?.at !== item.proposal?.at) return draftChanged();
+ item = current;
+ const slackClient = ctx.deps.loopSlackClient;
+ const result = await adapter.act(
+ { owner: loop.owner, actor: proposalAuthor, tokens, ...(slackClient ? { slackClient } : {}) },
+ item,
+ kind,
+ args,
+ );
+ if (!result.ok) {
+ if (result.partial) await deps.items.appendThread(item.id, [{ role: "system", text: result.message }]);
+ const statusByReason = { not_connected: 409, bad_item: 400, upstream: 502 } as const;
+ return sendJson(ctx.res, statusByReason[result.reason], { error: result.reason, message: result.message });
+ }
+ if (result.payloadPatch) item = (await deps.items.annotate(item.id, result.payloadPatch)) ?? item;
+ if (result.resolves === false) return sendJson(ctx.res, 200, { item: ledgerItemView(item) });
+ const next = await deps.items.recordAction(item.id, { kind, outcome: "actioned", result: result.result });
+ return sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item) });
+ } finally {
+ await deps.items.releaseDecision(item.id, decisionToken);
}
- if (result.payloadPatch) item = (await deps.items.annotate(item.id, result.payloadPatch)) ?? item;
- if (result.resolves === false) return sendJson(ctx.res, 200, { item: ledgerItemView(item) });
- const next = await deps.items.recordAction(item.id, { kind, outcome: "actioned", result: result.result });
- return sendJson(ctx.res, 200, { item: ledgerItemView(next ?? item) });
}
if (!deps.fire) return sendJson(ctx.res, 404, { error: "not_found", message: "loop firing is not wired" });
@@ -401,6 +421,65 @@ async function getInboxLoop(ctx: ApiCtx): Promise<void> {
sendJson(ctx.res, 200, { loop, syncCron: cronSummary(cron) });
}
+export async function ensureSentChat(ctx: ApiCtx): Promise<void> {
+ const owner = ctx.actor?.p;
+ if (!owner) return sendJson(ctx.res, 403, { error: "forbidden" });
+ const deps = loopDeps(ctx);
+ if (!deps) return sendJson(ctx.res, 404, { error: "not_found" });
+ const body = isObj(ctx.body) ? ctx.body : {};
+ const threadId = typeof body.threadId === "string" ? body.threadId.trim() : "";
+ if (!threadId || threadId.length > 200 || jsonSize(body) > MAX_SOURCE_PAYLOAD_BYTES)
+ return sendJson(ctx.res, 400, { error: "bad_request" });
+ const text = (key: string, max: number): string => (typeof body[key] === "string" ? body[key].slice(0, max) : "");
+ const accountType = body.accountType === undefined ? "default" : body.accountType;
+ const to = addressList(body.to === undefined ? [] : [body.to]);
+ const cc = addressList(body.cc === undefined ? [] : [body.cc]);
+ if (
+ typeof accountType !== "string" ||
+ !["default", "personal", "company"].includes(accountType) ||
+ to === null ||
+ cc === null
+ )
+ return sendJson(ctx.res, 400, { error: "bad_request", message: "invalid account or recipient headers" });
+ const payload = {
+ title: text("subject", 300),
+ from: text("from", 500),
+ snippet: text("text", 50000),
+ gmail: {
+ threadId,
+ accountType,
+ messageId: text("messageId", 200),
+ subject: text("subject", 300),
+ to: to ?? [],
+ cc: cc ?? [],
+ rfcMessageId: text("rfcMessageId", 400),
+ },
+ sentChat: true,
+ } as LoopSourcePayload;
+ const loop = await ensureInboxLoop(deps.store, owner);
+ const dedupeKey = accountType === "default" ? `sent-chat:${threadId}` : `sent-chat:${accountType}:${threadId}`;
+ const id = loopItemId(loop.id, dedupeKey);
+ let item = await deps.items.get(id);
+ if (!item) {
+ await deps.items.ingest([
+ {
+ loopId: loop.id,
+ dedupeKey,
+ source: "gmail",
+ summary: text("subject", 300),
+ proposal: { data: { body: "" }, by: "human" },
+ sourcePayload: payload,
+ },
+ ]);
+ item = await deps.items.get(id);
+ }
+ if (!item) return sendJson(ctx.res, 500, { error: "chat_unavailable" });
+ item = (await deps.items.annotate(id, payload, { summary: text("subject", 300) })) ?? item;
+ if (item.actionKind === "sent") item = (await deps.items.reopen(id, { sentReply: true })) ?? item;
+ ctx.res.setHeader("Cache-Control", "no-store");
+ sendJson(ctx.res, 200, { item: ledgerItemView(item) });
+}
+
async function ensureInboxSyncCron(ctx: ApiCtx): Promise<void> {
const deps = loopDeps(ctx);
if (!deps) return sendJson(ctx.res, 404, { error: "not_found", message: "loops are not wired on this deployment" });
@@ -449,6 +528,7 @@ async function ensureInboxSyncCron(ctx: ApiCtx): Promise<void> {
}
export const loopItemRoutes: ReadonlyArray<Route<ApiCtx>> = [
+ { method: "POST", path: "/v1/loops/inbox/sent-chat", auth: "source", handle: ensureSentChat },
{ method: "GET", path: "/v1/loops/inbox", auth: "either", handle: getInboxLoop },
{ method: "POST", path: "/v1/loops/inbox/sync-cron", auth: "source", handle: ensureInboxSyncCron },
{ method: "GET", path: "/v1/loops/:id/items", auth: "either", handle: listItems },
diff --git a/src/connectors/gmail-sent.ts b/src/connectors/gmail-sent.ts
new file mode 100644
index 000000000..212993175
--- /dev/null
+++ b/src/connectors/gmail-sent.ts
@@ -0,0 +1,135 @@
+export interface SentEmail {
+ id: string;
+ threadId: string;
+ to: string;
+ subject: string;
+ snippet: string;
+ sentAt: number;
+}
+
+interface GmailPart {
+ mimeType?: string;
+ filename?: string;
+ body?: { data?: string };
+ headers?: { name: string; value: string }[];
+ parts?: GmailPart[];
+}
+
+interface GmailMessage {
+ id: string;
+ threadId: string;
+ snippet?: string;
+ internalDate?: string;
+ labelIds?: string[];
+ payload?: GmailPart;
+}
+
+export class GmailReadError extends Error {
+ readonly status: number;
+
+ constructor(status: number) {
+ super(
+ status === 401 || status === 403
+ ? "Reconnect Google to read sent mail."
+ : "Couldn't load sent mail from Gmail. Try again.",
+ );
+ this.status = status;
+ }
+}
+
+export async function listSentEmails(
+ token: string,
+ pageToken?: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<{ messages: SentEmail[]; nextPageToken?: string; accountEmail: string }> {
+ const get = async <T>(path: string): Promise<T> => {
+ const response = await fetchImpl(`https://gmail.googleapis.com/gmail/v1/users/me/${path}`, {
+ headers: { authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(15000),
+ });
+ if (!response.ok) throw new GmailReadError(response.status);
+ return response.json() as Promise<T>;
+ };
+ const params = new URLSearchParams({ labelIds: "SENT", maxResults: "25" });
+ if (pageToken) params.set("pageToken", pageToken);
+ const page = await get<{ messages?: { id: string }[]; nextPageToken?: string }>(`messages?${params}`);
+ const profile = await get<{ emailAddress: string }>("profile");
+ const messages: SentEmail[] = [];
+ const ids = page.messages ?? [];
+ for (let i = 0; i < ids.length; i += 5) {
+ const batch = await Promise.all(
+ ids.slice(i, i + 5).map(async ({ id }) => {
+ let message: GmailMessage;
+ try {
+ message = await get<GmailMessage>(
+ `messages/${encodeURIComponent(id)}?format=metadata&metadataHeaders=To&metadataHeaders=Subject`,
+ );
+ } catch (error) {
+ if (error instanceof GmailReadError && error.status === 404) return null;
+ throw error;
+ }
+ const header = (name: string): string =>
+ message.payload?.headers?.find((h) => h.name.toLowerCase() === name)?.value ?? "";
+ return {
+ id: message.id,
+ threadId: message.threadId,
+ to: header("to"),
+ subject: header("subject"),
+ snippet: message.snippet ?? "",
+ sentAt: Number(message.internalDate) || 0,
+ };
+ }),
+ );
+ messages.push(...batch.filter((message): message is SentEmail => message !== null));
+ }
+ messages.sort((a, b) => b.sentAt - a.sentAt);
+ return {
+ messages,
+ accountEmail: profile.emailAddress,
+ ...(page.nextPageToken ? { nextPageToken: page.nextPageToken } : {}),
+ };
+}
+
+export async function getSentEmail(
+ token: string,
+ id: string,
+ fetchImpl: typeof fetch = fetch,
+): Promise<
+ SentEmail & { from: string; cc: string; body: string; rfcMessageId: string; html: boolean; attachments: string[] }
+> {
+ const response = await fetchImpl(
+ `https://gmail.googleapis.com/gmail/v1/users/me/messages/${encodeURIComponent(id)}?format=full`,
+ {
+ headers: { authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(15000),
+ },
+ );
+ if (!response.ok) throw new GmailReadError(response.status);
+ const message = (await response.json()) as GmailMessage;
+ if (!message.labelIds?.includes("SENT")) throw new GmailReadError(404);
+ const header = (name: string): string =>
+ message.payload?.headers?.find((h) => h.name.toLowerCase() === name)?.value ?? "";
+ const parts: GmailPart[] = [];
+ const visit = (part: GmailPart): void => {
+ parts.push(part);
+ for (const child of part.parts ?? []) visit(child);
+ };
+ if (message.payload) visit(message.payload);
+ const content =
+ parts.find((part) => !part.filename && part.mimeType === "text/plain" && part.body?.data) ??
+ parts.find((part) => !part.filename && part.mimeType === "text/html" && part.body?.data);
+ return {
+ id: message.id,
+ threadId: message.threadId,
+ to: header("to"),
+ from: header("from"),
+ cc: header("cc"),
+ rfcMessageId: header("message-id"),
+ subject: header("subject"),
+ snippet: message.snippet ?? "",
+ sentAt: Number(message.internalDate) || 0,
+ body: content?.body?.data ? Buffer.from(content.body.data, "base64url").toString("utf8") : "",
+ html: content?.mimeType === "text/html",
+ attachments: parts.flatMap((part) => (part.filename ? [part.filename] : [])),
+ };
+}
diff --git a/src/loops/item-ledger.ts b/src/loops/item-ledger.ts
index c961a53b7..b2cd83c78 100644
--- a/src/loops/item-ledger.ts
+++ b/src/loops/item-ledger.ts
@@ -60,10 +60,10 @@ export interface LoopItemLedger {
enqueue(input: EnqueueItemInput): Promise<EnqueueResult>;
ingest(entries: IngestEntryInput[]): Promise<IngestOutcome>;
setProposal(id: string, proposal: Omit<LoopProposal, "at">, opts?: { expectedAt?: number }): Promise<LoopItem | null>;
- annotate(id: string, patch: LoopSourcePayload): Promise<LoopItem | null>;
+ annotate(id: string, patch: LoopSourcePayload, opts?: { summary?: string }): Promise<LoopItem | null>;
appendThread(id: string, messages: Array<Omit<LoopThreadMessage, "id" | "at">>): Promise<LoopItem | null>;
recordAction(id: string, input: RecordActionInput): Promise<LoopItem | null>;
- reopen(id: string): Promise<LoopItem | null>;
+ reopen(id: string, opts?: { sentReply?: boolean }): Promise<LoopItem | null>;
prune(loopId: string, options: PruneOptions): Promise<number>;
get(id: string): Promise<LoopItem | null>;
byLoop(loopId: string): Promise<LoopItem[]>;
@@ -266,12 +266,17 @@ export function createLoopItemLedger(
if (applied) emit(after, "proposal");
return applied ? after : null;
},
- async annotate(id, patch) {
+ async annotate(id, patch, opts) {
let applied = false;
const after = await update(id, (item) => {
applied = true;
const now = Date.now();
- return { ...item, sourcePayload: { ...item.sourcePayload, ...patch }, updatedAt: now };
+ return {
+ ...item,
+ sourcePayload: { ...item.sourcePayload, ...patch },
+ ...(opts?.summary !== undefined ? { sourceSummary: opts.summary } : {}),
+ updatedAt: now,
+ };
});
if (applied) emit(after, "annotate");
return applied ? after : null;
@@ -314,15 +319,22 @@ export function createLoopItemLedger(
if (applied) emit(after, "action");
return applied ? after : null;
},
- async reopen(id) {
+ async reopen(id, opts) {
let applied = false;
const after = await update(id, (item) => {
- if (item.status !== "skipped" && item.status !== "failed") return item;
+ const sentReply = opts?.sentReply === true && item.source === "gmail" && item.sourcePayload?.sentChat === true;
+ if (item.status !== "skipped" && item.status !== "failed" && !(sentReply && item.status === "shipped"))
+ return item;
applied = true;
const now = Date.now();
return {
...item,
- status: item.proposal ? "ready" : "queued",
+ status: sentReply || item.proposal ? "ready" : "queued",
+ ...(sentReply
+ ? {
+ proposal: { data: { body: "" }, by: "human" as const, at: Math.max(now, (item.proposal?.at ?? 0) + 1) },
+ }
+ : {}),
actedAt: undefined,
actionKind: undefined,
actionResult: undefined,
diff --git a/src/loops/sources/adapter.ts b/src/loops/sources/adapter.ts
index d487282ba..a8ea0e449 100644
--- a/src/loops/sources/adapter.ts
+++ b/src/loops/sources/adapter.ts
@@ -64,14 +64,19 @@ export function clipOpt(v: unknown, max: number): string | undefined {
return clip(v, max) ?? undefined;
}
-export function addressList(v: unknown, maxEntries = 10): string[] | undefined {
- if (!Array.isArray(v)) return undefined;
+export function addressList(v: unknown): string[] | undefined | null {
+ if (v === undefined) return undefined;
+ if (!Array.isArray(v) || v.length > 100) return null;
const out: string[] = [];
- for (const entry of v.slice(0, maxEntries)) {
- const s = clip(entry, 200);
- if (s) out.push(s);
+ let length = 0;
+ for (const entry of v) {
+ if (typeof entry !== "string" || /[\r\n\0]/.test(entry)) return null;
+ const address = entry.trim();
+ length += address.length;
+ if (length > 8000) return null;
+ if (address) out.push(address);
}
- return out.length ? out : undefined;
+ return out;
}
function httpUrl(v: unknown): string | undefined {
@@ -131,6 +136,7 @@ export function parseReplyDraft(v: unknown): ReplyDraft | null {
if (body === null) return null;
const to = addressList(v.to);
const cc = addressList(v.cc);
+ if (to === null || cc === null) return null;
const subject = clipOpt(v.subject, 300);
return { body, ...(to ? { to } : {}), ...(cc ? { cc } : {}), ...(subject ? { subject } : {}) };
}
diff --git a/src/loops/sources/gmail.ts b/src/loops/sources/gmail.ts
index 99c7321c9..a86ecaacc 100644
--- a/src/loops/sources/gmail.ts
+++ b/src/loops/sources/gmail.ts
@@ -20,6 +20,7 @@ const GMAIL_HOST = "gmail.googleapis.com";
interface GmailMeta {
threadId: string;
+ accountType?: "default" | "personal" | "company";
messageId?: string;
rfcMessageId?: string;
to?: string[];
@@ -31,13 +32,21 @@ function parseGmailMeta(v: unknown): GmailMeta | undefined {
if (!isObj(v)) return undefined;
const threadId = clip(v.threadId, 200);
if (!threadId) return undefined;
+ if (
+ v.accountType !== undefined &&
+ (typeof v.accountType !== "string" || !["default", "personal", "company"].includes(v.accountType))
+ )
+ return undefined;
+ const accountType = v.accountType as GmailMeta["accountType"];
const messageId = clipOpt(v.messageId, 200);
const rfcMessageId = clipOpt(v.rfcMessageId, 400);
const to = addressList(v.to);
const cc = addressList(v.cc);
+ if (to === null || cc === null) return undefined;
const subject = clipOpt(v.subject, 300);
return {
threadId,
+ ...(accountType ? { accountType } : {}),
...(messageId ? { messageId } : {}),
...(rfcMessageId ? { rfcMessageId } : {}),
...(to ? { to } : {}),
@@ -81,7 +90,11 @@ export function replySubject(item: LoopItem, draft: ReplyDraft): string {
export function buildGmailReplyMime(item: LoopItem, draft: ReplyDraft): string | null {
const meta = metaOf(item);
- const to = (draft.to?.length ? draft.to : meta?.to) ?? [];
+ if (!meta) return null;
+ const parsed = parseReplyDraft(draft);
+ if (!parsed) return null;
+ draft = parsed;
+ const to = draft.to ?? meta.to ?? [];
if (to.length === 0) return null;
const cc = draft.cc ?? meta?.cc ?? [];
const rfcId = meta?.rfcMessageId;
@@ -101,13 +114,19 @@ export function buildGmailReplyMime(item: LoopItem, draft: ReplyDraft): string |
async function sendGmail(deps: SourceActionDeps, item: LoopItem, draft: ReplyDraft): Promise<SourceActionResult> {
const fetchImpl = deps.fetchImpl ?? fetch;
- const token = await tokenFor(deps.tokens, GMAIL_HOST, deps.owner);
+ const meta = metaOf(item);
+ if (!meta) return { ok: false, reason: "bad_item", message: "invalid Gmail metadata" };
+ const accountType = meta.accountType ?? (item.sourcePayload?.sentChat === true ? "default" : undefined);
+ const token = accountType
+ ? await deps.tokens.connectorAccessToken(GMAIL_HOST, deps.owner, accountType)
+ : await tokenFor(deps.tokens, GMAIL_HOST, deps.owner);
if (!token) return { ok: false, reason: "not_connected", message: "Google is not connected for this account" };
const mime = buildGmailReplyMime(item, draft);
if (!mime) return { ok: false, reason: "bad_item", message: "no recipient — add a To: address to the draft" };
const threadId = metaOf(item)?.threadId;
const res = await fetchImpl(`https://${GMAIL_HOST}/gmail/v1/users/me/messages/send`, {
method: "POST",
+ signal: AbortSignal.timeout(30000),
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({
raw: Buffer.from(mime, "utf8").toString("base64url"),
@@ -151,7 +170,7 @@ export const gmailAdapter: LoopSourceAdapter = {
},
async act(deps, item, kind, args) {
if (kind !== "send") return { ok: false, reason: "bad_item", message: `gmail items do not support "${kind}"` };
- const draft = parseReplyDraft(args) ?? draftOf(item);
+ const draft = args.body !== undefined ? parseReplyDraft(args) : draftOf(item);
if (!draft || !draft.body.trim()) return { ok: false, reason: "bad_item", message: "the draft is empty" };
try {
return await sendGmail(deps, item, { ...draft, body: draft.body.trim() });
diff --git a/src/loops/sources/slack.ts b/src/loops/sources/slack.ts
index 16ecf1d62..ac98f75c3 100644
--- a/src/loops/sources/slack.ts
+++ b/src/loops/sources/slack.ts
@@ -193,7 +193,7 @@ export const slackAdapter: LoopSourceAdapter = {
}
try {
if (kind === "react") return await reactInSlack(deps, item, args.name);
- const draft = parseReplyDraft(args) ?? draftOf(item);
+ const draft = args.body !== undefined ? parseReplyDraft(args) : draftOf(item);
if (!draft || !draft.body.trim()) return { ok: false, reason: "bad_item", message: "the draft is empty" };
return await sendSlack(deps, item, { ...draft, body: draft.body.trim() });
} catch (err) {
diff --git a/test/gmail-sent-route.test.ts b/test/gmail-sent-route.test.ts
new file mode 100644
index 000000000..bde9b3199
--- /dev/null
+++ b/test/gmail-sent-route.test.ts
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { gmailSent } from "../src/api/routes/connectors.ts";
+import type { ApiCtx } from "../src/api/routes/route.ts";
+
+test("sent mail requires portal identity and ignores a forged principal query", async () => {
+ let status = 0;
+ let requestedPrincipal = "";
+ const ctx = {
+ actor: null,
+ url: new URL("http://localhost/v1/connectors/gmail/sent?principalId=someone-else"),
+ res: {
+ setHeader() {},
+ writeHead(code: number) {
+ status = code;
+ },
+ end() {},
+ },
+ deps: {
+ connectorTokens: {
+ async connectorDerivedAuth(_host: string, principal: string) {
+ requestedPrincipal = principal;
+ return null;
+ },
+ },
+ },
+ } as unknown as ApiCtx;
+ await gmailSent(ctx);
+ assert.equal(status, 403);
+ assert.equal(requestedPrincipal, "");
+ ctx.actor = { p: "signed-in-user" } as ApiCtx["actor"];
+ await gmailSent(ctx);
+ assert.equal(status, 409);
+ assert.equal(requestedPrincipal, "signed-in-user");
+ requestedPrincipal = "";
+ ctx.url.searchParams.set("accountType", "forged");
+ await gmailSent(ctx);
+ assert.equal(status, 400);
+ assert.equal(requestedPrincipal, "");
+});
diff --git a/test/gmail-sent.test.ts b/test/gmail-sent.test.ts
new file mode 100644
index 000000000..54aa278a7
--- /dev/null
+++ b/test/gmail-sent.test.ts
@@ -0,0 +1,68 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { GmailReadError, getSentEmail, listSentEmails } from "../src/connectors/gmail-sent.ts";
+
+test("sent mail reads only SENT messages, paginates, and includes mail sent outside QM", async () => {
+ const calls: URL[] = [];
+ const fakeFetch: typeof fetch = async (input, init) => {
+ const url = new URL(String(input));
+ calls.push(url);
+ assert.equal(new Headers(init?.headers).get("authorization"), "Bearer test-token");
+ if (url.pathname.endsWith("/profile")) return Response.json({ emailAddress: "[email protected]" });
+ if (url.pathname.endsWith("/messages"))
+ return Response.json({ messages: [{ id: "older" }, { id: "newer" }, { id: "deleted" }], nextPageToken: "next" });
+ if (url.pathname.endsWith("/deleted")) return new Response(null, { status: 404 });
+ const id = url.pathname.split("/").at(-1);
+ return Response.json({
+ id,
+ threadId: `thread-${id}`,
+ internalDate: id === "newer" ? "2000" : "1000",
+ snippet: "Hello",
+ payload: {
+ headers: [
+ { name: "To", value: "[email protected]" },
+ { name: "Subject", value: "Outside QM" },
+ ],
+ },
+ });
+ };
+ const result = await listSentEmails("test-token", "cursor", fakeFetch);
+ assert.equal(calls[0]!.searchParams.get("labelIds"), "SENT");
+ assert.equal(calls[0]!.searchParams.get("pageToken"), "cursor");
+ assert.equal(calls[0]!.searchParams.get("maxResults"), "25");
+ assert.deepEqual(
+ result.messages.map((message) => message.id),
+ ["newer", "older"],
+ );
+ assert.equal(result.messages[0]!.to, "[email protected]");
+ assert.equal(result.nextPageToken, "next");
+ assert.equal(result.accountEmail, "[email protected]");
+});
+
+test("Gmail errors do not expose upstream response bodies or tokens", async () => {
+ await assert.rejects(
+ listSentEmails("private-token", undefined, async () => new Response("private upstream response", { status: 403 })),
+ (error: unknown) => error instanceof GmailReadError && error.status === 403 && !error.message.includes("private"),
+ );
+});
+
+test("sent message details decode MIME text and reject non-sent messages", async () => {
+ const payload = {
+ id: "m1",
+ threadId: "t1",
+ labelIds: ["SENT"],
+ payload: {
+ parts: [
+ { mimeType: "text/plain", body: { data: Buffer.from("Full email body").toString("base64url") } },
+ { filename: "report.pdf", mimeType: "application/pdf" },
+ ],
+ },
+ };
+ const result = await getSentEmail("token", "m1", async () => Response.json(payload));
+ assert.equal(result.body, "Full email body");
+ assert.deepEqual(result.attachments, ["report.pdf"]);
+ await assert.rejects(
+ getSentEmail("token", "m1", async () => Response.json({ ...payload, labelIds: ["INBOX"] })),
+ (error: unknown) => error instanceof GmailReadError && error.status === 404,
+ );
+});
diff --git a/test/loop-item-routes.test.ts b/test/loop-item-routes.test.ts
index 3445eafac..13635e9d1 100644
--- a/test/loop-item-routes.test.ts
+++ b/test/loop-item-routes.test.ts
@@ -792,3 +792,14 @@ test("a capability caller's edit is stored as the agent's draft, so its mentions
assert.equal(sent.status, 200, JSON.stringify(sent.body));
assert.equal((w.sent.at(-1)!.body as { text: string }).text, "Everyone @\u200bhere please look");
});
+
+test("concurrent source sends share a durable decision claim", async () => {
+ const w = world();
+ const { loop, item } = await seed(w);
+ const send = () =>
+ call(w, { method: "POST", path: `/v1/loops/${loop.id}/items/${item.id}/action`, body: { kind: "send" } });
+ const outcomes = await Promise.all([send(), send()]);
+ assert.deepEqual(outcomes.map((out) => out.status).sort(), [200, 409]);
+ assert.equal(w.sent.length, 1);
+ assert.equal((await w.loops.items.get(item.id))!.decisionToken, undefined);
+});
diff --git a/test/loop-ledger.test.ts b/test/loop-ledger.test.ts
index f7a98e770..5a85ab5a2 100644
--- a/test/loop-ledger.test.ts
+++ b/test/loop-ledger.test.ts
@@ -354,3 +354,32 @@ test("draft identity ignores key order, as stored JSON does not preserve it", as
assert.equal(after.proposal!.at, at);
assert.equal(after.agentDrafts!.length, 1);
});
+
+test("continuing a sent reply clears the old draft without losing chat or allowing a second reset", async () => {
+ const ledger = createLoopItemLedger();
+ await ledger.ingest([
+ entry({ sourcePayload: { sentChat: true }, proposal: { data: { body: "First reply" }, by: "human" } }),
+ ]);
+ const item = (await ledger.byLoop(LOOP))[0]!;
+ await ledger.appendThread(item.id, [{ role: "human", text: "Help with this thread" }]);
+ await ledger.recordAction(item.id, { kind: "send", outcome: "actioned" });
+ assert.equal(await ledger.reopen(item.id), null);
+ const reply = await ledger.reopen(item.id, { sentReply: true });
+ assert.equal(reply!.proposal!.data.body, "");
+ assert.ok(reply!.proposal!.at > item.proposal!.at);
+ assert.equal(reply!.thread![0]!.text, "Help with this thread");
+ assert.equal(ledgerState(reply!), "held");
+ assert.equal(await ledger.reopen(item.id, { sentReply: true }), null);
+ assert.equal(
+ await ledger.setProposal(
+ item.id,
+ { data: { body: "Stale resend" }, by: "human" },
+ { expectedAt: item.proposal!.at },
+ ),
+ null,
+ );
+ await ledger.ingest([entry({ dedupeKey: "ordinary" })]);
+ const ordinary = (await ledger.byLoop(LOOP)).find((item) => item.sourceKey === "ordinary")!;
+ await ledger.recordAction(ordinary.id, { kind: "send", outcome: "actioned" });
+ assert.equal(await ledger.reopen(ordinary.id, { sentReply: true }), null);
+});
diff --git a/test/loop-source-send.test.ts b/test/loop-source-send.test.ts
index 8b81b884e..43a88cde0 100644
--- a/test/loop-source-send.test.ts
+++ b/test/loop-source-send.test.ts
@@ -374,3 +374,80 @@ test("a mention that fell out of the bounded draft history is still disarmed thr
held.agentMentionKeys = ["!here"];
assert.equal(renderSlackSendText(held, "human kept <!here>"), "human kept @\u200bhere");
});
+
+test("Gmail sends only through the explicitly bound account, including legacy sent chats", async () => {
+ for (const accountType of ["default", "personal", "company", undefined]) {
+ for (const connected of [true, false]) {
+ const requested: (string | undefined)[] = [];
+ let sends = 0;
+ const bound = item("gmail", {
+ sentChat: true,
+ gmail: { threadId: "t", to: ["[email protected]"], ...(accountType ? { accountType } : {}) },
+ });
+ const result = await gmailAdapter.act(
+ {
+ owner: "alice",
+ tokens: {
+ connectorAccessToken: async (_host, _owner, slot) => {
+ requested.push(slot);
+ if (slot !== (accountType ?? "default")) return "wrong-token";
+ return connected ? "bound-token" : null;
+ },
+ },
+ fetchImpl: async (_url, init) => {
+ sends++;
+ assert.equal((init!.headers as Record<string, string>).authorization, "Bearer bound-token");
+ return Response.json({});
+ },
+ },
+ bound,
+ "send",
+ { body: "Hello" },
+ );
+ assert.equal(result.ok, connected);
+ assert.deepEqual(requested, [accountType ?? "default"]);
+ assert.equal(sends, connected ? 1 : 0);
+ }
+ }
+});
+
+test("Gmail drafts preserve recipient lists and reject invalid recipients without falling back", async () => {
+ const addresses = Array.from({ length: 15 }, (_, i) => `person${i}@example.com`);
+ const mime = buildGmailReplyMime(gmailItem, { body: "Hi", to: addresses, cc: [] })!;
+ assert.ok(mime.startsWith(`To: ${addresses.join(", ")}\r\n`));
+ assert.equal(buildGmailReplyMime(gmailItem, { body: "Hi", to: [] }), null);
+ const held = { ...gmailItem, proposal: { data: { body: "Previously saved" }, by: "human" as const, at: 1 } };
+ for (const to of [["x".repeat(8001)], Array(101).fill("[email protected]"), ["[email protected]\nBcc: [email protected]"]]) {
+ assert.equal(gmailAdapter.parseProposal({ body: "Hi", to }), null);
+ const result = await gmailAdapter.act(
+ {
+ owner: "alice",
+ tokens: tokens({ "gmail.googleapis.com": "token" }),
+ fetchImpl: async () => {
+ throw new Error("must not send");
+ },
+ },
+ held,
+ "send",
+ { body: "Hi", to },
+ );
+ assert.equal(result.ok, false);
+ if (!result.ok) assert.equal(result.reason, "bad_item");
+ }
+});
+
+test("Slack rejects an explicit invalid draft instead of sending the saved draft", async () => {
+ const spy = slackSpy();
+ const held = item("slack", slackMeta, { body: "OLD SAVED DRAFT" });
+ for (const invalid of [{ body: "NEW", to: null }, { body: "NEW", cc: ["x".repeat(8001)] }, { body: null }]) {
+ const result = await slackAdapter.act(
+ { owner: "alice", tokens: tokens({ "slack.com": "token" }), slackClient: spy.factory },
+ held,
+ "send",
+ invalid,
+ );
+ assert.equal(result.ok, false);
+ if (!result.ok) assert.equal(result.reason, "bad_item");
+ }
+ assert.equal(spy.calls.length, 0);
+});
diff --git a/test/sent-chat.test.ts b/test/sent-chat.test.ts
new file mode 100644
index 000000000..178a15c49
--- /dev/null
+++ b/test/sent-chat.test.ts
@@ -0,0 +1,188 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { ensureSentChat, loopItemRoutes } from "../src/api/routes/loop-items.ts";
+import { buildGmailReplyMime } from "../src/loops/sources/gmail.ts";
+import { findRoute, run, type ApiCtx } from "../src/api/routes/route.ts";
+import { createLoopStore } from "../src/loops/loop-store.ts";
+import { createLoopItemLedger } from "../src/loops/item-ledger.ts";
+
+test("sent chats are durable, idempotent, and isolated to the signed-in owner", async () => {
+ const store = createLoopStore();
+ const items = createLoopItemLedger();
+ let status = 0;
+ let response: { item: { id: string; loopId: string; state: string; thread: { text: string }[] } };
+ const ctx = {
+ actor: { p: "alice" },
+ url: new URL("http://localhost/?principalId=bob"),
+ body: { threadId: "sent-only-thread", subject: "No inbox match", from: "Alice", text: "The sent email body" },
+ deps: { loops: { store, items } },
+ res: {
+ setHeader() {},
+ writeHead(code: number) {
+ status = code;
+ },
+ end(data: string) {
+ response = JSON.parse(data);
+ },
+ },
+ } as unknown as ApiCtx;
+ await ensureSentChat(ctx);
+ assert.equal(status, 200);
+ const original = response!.item;
+ assert.equal(original.state, "held");
+ assert.equal((await store.get(original.loopId))!.owner, "alice");
+ assert.equal((await items.get(original.id))!.sourcePayload!.snippet, "The sent email body");
+ await items.appendThread(original.id, [{ role: "human", text: "Summarize this" }]);
+ await ensureSentChat(ctx);
+ assert.equal(response!.item.id, original.id);
+ assert.equal(response!.item.thread[0]!.text, "Summarize this");
+ await items.setProposal(original.id, { data: { body: "My unfinished draft" }, by: "human" });
+ const proposal = (await items.get(original.id))!.proposal;
+ ctx.body = {
+ threadId: "sent-only-thread",
+ messageId: "newer-message",
+ subject: "New title",
+ from: "New sender",
+ text: "New context",
+ };
+ await ensureSentChat(ctx);
+ const refreshed = (await items.get(original.id))!;
+ assert.deepEqual(refreshed.proposal, proposal);
+ assert.equal(refreshed.sourcePayload!.snippet, "New context");
+ assert.equal(refreshed.sourcePayload!.from, "New sender");
+ assert.equal(refreshed.sourcePayload!.title, "New title");
+ assert.equal(refreshed.sourceSummary, "New title");
+ assert.equal((refreshed.sourcePayload!.gmail as { messageId: string }).messageId, "newer-message");
+ ctx.body = { ...(ctx.body as object), accountType: "personal" };
+ await ensureSentChat(ctx);
+ assert.notEqual(response!.item.id, original.id);
+ ctx.actor = { p: "bob" } as ApiCtx["actor"];
+ await ensureSentChat(ctx);
+ assert.notEqual(response!.item.id, original.id);
+ assert.equal(response!.item.thread.length, 0);
+ ctx.actor = undefined;
+ await ensureSentChat(ctx);
+ assert.equal(status, 403);
+});
+
+test("a sent email draft saves and sends into the original Gmail thread exactly once", async () => {
+ const store = createLoopStore();
+ const items = createLoopItemLedger();
+ let response: { item: { id: string; loopId: string; proposal?: { at: number; data: { body: string } } } };
+ let status = 0;
+ const ctx = {
+ actor: { p: "alice" },
+ url: new URL("http://localhost/"),
+ body: {
+ threadId: "thread-1",
+ subject: "Project update",
+ from: "Alice",
+ to: "Bob <[email protected]>",
+ cc: "Casey <[email protected]>",
+ rfcMessageId: "<[email protected]>",
+ text: "Original sent message",
+ },
+ deps: { loops: { store, items }, loopSourceTokens: { connectorAccessToken: async () => "test-token" } },
+ app: {
+ membershipControlsScope: async () => false,
+ samePerson: async (a: string, b: string) => a === b,
+ managesScope: async () => false,
+ },
+ res: {
+ setHeader() {},
+ writeHead(code: number) {
+ status = code;
+ },
+ end(data: string) {
+ response = JSON.parse(data);
+ },
+ },
+ } as unknown as ApiCtx;
+ await ensureSentChat(ctx);
+ const { id, loopId } = response!.item;
+ const found = findRoute(loopItemRoutes, "POST", `/v1/loops/${loopId}/items/${id}/action`)!;
+ const action = async (kind: string, args = {}) => {
+ ctx.body = { kind, args };
+ await run(found.route, found.params, ctx);
+ };
+ const draft = {
+ to: ["Bob <[email protected]>"],
+ cc: ["Casey <[email protected]>"],
+ subject: "Project update",
+ body: "Following up",
+ };
+ await action("edit", { proposal: draft });
+ assert.equal(status, 200);
+ assert.equal(response!.item.proposal!.data.body, "Following up");
+ const savedAt = response!.item.proposal!.at;
+ const originalFetch = globalThis.fetch;
+ let sent = 0;
+ globalThis.fetch = async (_url, init) => {
+ sent++;
+ const message = JSON.parse(String(init!.body));
+ assert.equal(message.threadId, "thread-1");
+ const mime = Buffer.from(message.raw, "base64url").toString();
+ assert.match(mime, /To: Bob <[email protected]>/);
+ assert.match(mime, /Cc: Casey <[email protected]>/);
+ assert.match(mime, /In-Reply-To: <[email protected]>/);
+ return Response.json({ id: "sent-reply", threadId: "thread-1" });
+ };
+ try {
+ await action("send", { proposal: draft, expectedProposalAt: savedAt });
+ assert.equal(status, 200);
+ await action("send", { proposal: draft, expectedProposalAt: savedAt });
+ assert.equal(status, 409);
+ assert.equal(sent, 1);
+ await action("reply");
+ assert.equal(status, 200);
+ assert.equal(response!.item.proposal!.data.body, "");
+ await action("send", { proposal: draft, expectedProposalAt: savedAt });
+ assert.equal(status, 409);
+ assert.equal(sent, 1);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("sent chat preserves long quoted recipient headers and rejects oversized input", async () => {
+ const store = createLoopStore();
+ const items = createLoopItemLedger();
+ let status = 0;
+ let id = "";
+ const to = [
+ '"Doe, Jane" <[email protected]>',
+ ...Array.from({ length: 15 }, (_, i) => `Recipient ${i} <recipient${i}@example.com>`),
+ ].join(", ");
+ const cc = '"Smith, Casey" <[email protected]>';
+ const ctx = {
+ actor: { p: "alice" },
+ body: { threadId: "t", to, cc },
+ deps: { loops: { store, items } },
+ res: {
+ setHeader() {},
+ writeHead(code: number) {
+ status = code;
+ },
+ end(data: string) {
+ id = JSON.parse(data).item?.id ?? "";
+ },
+ },
+ } as unknown as ApiCtx;
+ await ensureSentChat(ctx);
+ assert.equal(status, 200);
+ const stored = (await items.get(id))!;
+ const mime = buildGmailReplyMime(stored, { body: "Hello" })!;
+ assert.ok(mime.startsWith(`To: ${to}\r\nCc: ${cc}\r\n`));
+ for (const invalid of [
+ { to: "x".repeat(8001) },
+ { cc: "x".repeat(8001) },
+ { accountType: "forged" },
+ { accountType: ["default"] },
+ ]) {
+ ctx.body = { threadId: "t", ...invalid };
+ await ensureSentChat(ctx);
+ assert.equal(status, 400);
+ assert.deepEqual((await items.get(stored.id))!.sourcePayload, stored.sourcePayload);
+ }
+});