Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

web-ui: in-document panes with a byte-budgeted transcript, plus the stacked UX and steering fixes (#175)

Regan Bell5eb3393315b4
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index be031e14b..08d0b2a46 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -1073,6 +1073,16 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {
return relay(res, r);
}
+ if (method === "GET" && /^\/api\/sessions\/[^/]+\/entries\/\d+$/.test(path)) {
+ const [, , , rawId, , seq] = path.split("/");
+ const id = decodeURIComponent(rawId!);
+ const r = await coreFetch(
+ "GET",
+ `/v1/sessions/${encodeURIComponent(id)}/entries/${seq}?viewer=${encodeURIComponent(user)}`,
+ );
+ return relay(res, r);
+ }
+
if (method === "GET" && path.startsWith("/api/sessions/")) {
const id = decodeURIComponent(path.slice("/api/sessions/".length));
const qs = new URLSearchParams({ viewer: user });
@@ -1413,7 +1423,10 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (!threadRef.startsWith(`web:${user}:`)) {
const sessionId = typeof record.sessionId === "string" ? record.sessionId : "";
const visible = sessionId
- ? await coreFetch("GET", `/v1/sessions/${encodeURIComponent(sessionId)}?viewer=${encodeURIComponent(user)}`)
+ ? await coreFetch(
+ "GET",
+ `/v1/sessions/${encodeURIComponent(sessionId)}?viewer=${encodeURIComponent(user)}&tailTurns=1`,
+ )
: null;
if (visible?.status !== 200) return json(res, 404, { error: "not_found" });
}
diff --git a/plugins/web-ui/src/ambient-policy.ts b/plugins/web-ui/src/ambient-policy.ts
index bb19509c8..27e70e6dc 100644
--- a/plugins/web-ui/src/ambient-policy.ts
+++ b/plugins/web-ui/src/ambient-policy.ts
@@ -1,6 +1,7 @@
import { html, nothing, type TemplateResult } from "lit";
import { api } from "./core-bridge";
import { errMessage } from "../../chassis/src/errors";
+import { fieldSelect } from "./ui";
export const BOT_MODES = ["ignore", "rollup", "action", "user"] as const;
export type BotMode = (typeof BOT_MODES)[number];
@@ -153,22 +154,28 @@ const BOT_MODE_LABELS: Record<BotMode, string> = {
user: "Treat like a person",
};
+function ambientValue(enabled: boolean | null): string {
+ if (enabled === null) return "default";
+ return enabled ? "on" : "off";
+}
+
function botRow(b: BotPolicyView, i: number): TemplateResult {
return html`
<div class="ambient-bot-row">
<span class="ambient-bot-name">${b.name}</span>
- <select
- class="ambient-bot-mode"
- aria-label=${`Handling for ${b.name}`}
- ?disabled=${ambientPolicyState.saving}
- @change=${(e: Event) => {
- const mode = (e.currentTarget as HTMLSelectElement).value as BotMode;
+ ${fieldSelect({
+ className: "ambient-bot-mode",
+ compact: true,
+ ariaLabel: `Handling for ${b.name}`,
+ disabled: ambientPolicyState.saving,
+ value: b.mode,
+ onChange: (value) => {
+ const mode = value as BotMode;
ambientPolicyState.bots = ambientPolicyState.bots.map((x, j) => (j === i ? { ...x, mode } : x));
markDirty();
- }}
- >
- ${BOT_MODES.map((m) => html`<option value=${m} ?selected=${m === b.mode}>${BOT_MODE_LABELS[m]}</option>`)}
- </select>
+ },
+ options: BOT_MODES.map((m) => html`<option value=${m}>${BOT_MODE_LABELS[m]}</option>`),
+ })}
${
b.mode === "rollup"
? html`<label class="ambient-bot-hours"
@@ -226,78 +233,78 @@ export function ambientPolicySection(scopeId: string): TemplateResult | typeof n
<p class="context-panel-copy">Choose what this project should notice and act on.</p>
</div>
</div>
- <label class="ambient-field" for="ambient-enabled">
- <span class="ambient-field-label">Ambient behavior</span>
- <span class="ambient-policy-hint"
- >When off, the agent never acts on overheard messages here — it only responds to direct @mentions. Default: on
- only when standing orders (or an action-mode bot) are set below — otherwise mention-only.</span
- >
- </label>
- <select
- id="ambient-enabled"
- class="ambient-enabled-select"
- data-focus-key="ambient-enabled"
- ?disabled=${ambientPolicyState.saving}
- @change=${(e: Event) => {
- const v = (e.currentTarget as HTMLSelectElement).value;
- ambientPolicyState.ambientEnabled = v === "default" ? null : v === "on";
- markDirty();
- }}
- >
- <option value="default" ?selected=${ambientPolicyState.ambientEnabled === null}>
- Default (on when standing orders are set)
- </option>
- <option value="on" ?selected=${ambientPolicyState.ambientEnabled === true}>On</option>
- <option value="off" ?selected=${ambientPolicyState.ambientEnabled === false}>Off</option>
- </select>
- <label class="ambient-field" for="ambient-orders">
- <span class="ambient-field-label">Standing orders</span>
- <span class="ambient-policy-hint" id="ambient-orders-hint"
- >Plain-language guidance for proactive work. Leave empty to respond only when addressed.</span
- >
- </label>
- <textarea
- id="ambient-orders"
- data-focus-key="ambient-orders"
- class="ambient-orders"
- rows="4"
- aria-describedby="ambient-orders-hint"
- placeholder="For example: Flag anything that could delay the launch."
- .value=${ambientPolicyState.orders}
- ?disabled=${ambientPolicyState.saving}
- @input=${(e: InputEvent) => {
- ambientPolicyState.orders = (e.currentTarget as HTMLTextAreaElement).value;
- markDirty();
- }}
- ></textarea>
- <div class="ambient-field-heading">
- <h3>Automated posters</h3>
- <p class="ambient-policy-hint">Control how messages from bots and integrations wake the agent.</p>
+ <div class="ambient-group">
+ <label class="ambient-field-label" for="ambient-enabled">Ambient behavior</label>
+ ${fieldSelect({
+ id: "ambient-enabled",
+ className: "ambient-enabled-select",
+ focusKey: "ambient-enabled",
+ describedBy: "ambient-enabled-hint",
+ disabled: ambientPolicyState.saving,
+ value: ambientValue(ambientPolicyState.ambientEnabled),
+ onChange: (v) => {
+ ambientPolicyState.ambientEnabled = v === "default" ? null : v === "on";
+ markDirty();
+ },
+ options: [
+ html`<option value="default">Default (on when standing orders are set)</option>`,
+ html`<option value="on">On</option>`,
+ html`<option value="off">Off</option>`,
+ ],
+ })}
+ <p class="ambient-policy-hint" id="ambient-enabled-hint">
+ When off, the agent never acts on overheard messages here — it only responds to direct @mentions. Default: on
+ only when standing orders (or an action-mode bot) are set below — otherwise mention-only.
+ </p>
</div>
- ${ambientPolicyState.bots.length ? html`<div class="ambient-bot-list">${ambientPolicyState.bots.map((b, i) => botRow(b, i))}</div>` : html`<div class="empty compact">No bots added. All bot posts are treated as activity.</div>`}
- <form
- class="ambient-bot-add"
- @submit=${(e: SubmitEvent) => {
- e.preventDefault();
- addBot();
- }}
- >
- <input
- data-focus-key="ambient-bot-name"
- type="text"
- maxlength="120"
- aria-label="Bot name"
- required
- placeholder="Bot name"
- .value=${ambientPolicyState.newBotName}
+ <div class="ambient-group">
+ <label class="ambient-field-label" for="ambient-orders">Standing orders</label>
+ <textarea
+ id="ambient-orders"
+ data-focus-key="ambient-orders"
+ class="ambient-orders"
+ rows="4"
+ aria-describedby="ambient-orders-hint"
+ placeholder="For example: Flag anything that could delay the launch."
+ .value=${ambientPolicyState.orders}
?disabled=${ambientPolicyState.saving}
@input=${(e: InputEvent) => {
- ambientPolicyState.newBotName = (e.currentTarget as HTMLInputElement).value;
- redraw();
+ ambientPolicyState.orders = (e.currentTarget as HTMLTextAreaElement).value;
+ markDirty();
}}
- />
- <button class="btn" type="submit" ?disabled=${ambientPolicyState.saving}>Add bot</button>
- </form>
+ ></textarea>
+ <p class="ambient-policy-hint" id="ambient-orders-hint">
+ Plain-language guidance for proactive work. Leave empty to respond only when addressed.
+ </p>
+ </div>
+ <div class="ambient-group">
+ <h3 class="ambient-field-label">Automated posters</h3>
+ <p class="ambient-policy-hint">Control how messages from bots and integrations wake the agent.</p>
+ ${ambientPolicyState.bots.length ? html`<div class="ambient-bot-list">${ambientPolicyState.bots.map((b, i) => botRow(b, i))}</div>` : html`<div class="empty compact">No bots added. All bot posts are treated as activity.</div>`}
+ <form
+ class="ambient-bot-add"
+ @submit=${(e: SubmitEvent) => {
+ e.preventDefault();
+ addBot();
+ }}
+ >
+ <input
+ data-focus-key="ambient-bot-name"
+ type="text"
+ maxlength="120"
+ aria-label="Bot name"
+ required
+ placeholder="Bot name"
+ .value=${ambientPolicyState.newBotName}
+ ?disabled=${ambientPolicyState.saving}
+ @input=${(e: InputEvent) => {
+ ambientPolicyState.newBotName = (e.currentTarget as HTMLInputElement).value;
+ redraw();
+ }}
+ />
+ <button class="btn" type="submit" ?disabled=${ambientPolicyState.saving}>Add bot</button>
+ </form>
+ </div>
<div class="ambient-policy-actions">
<button
class="btn primary"
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 44a3c1826..9a4d275a0 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -34,8 +34,12 @@ import {
import {
activeRunForThread,
api,
+ createRunSlot,
+ hasLiveRun,
+ signalLiveRun,
attachPendingApprovals,
entriesToMessages,
+ fetchEntry,
fetchTranscript,
forkCutSeq,
forkSession,
@@ -44,7 +48,6 @@ import {
makeRunResumeStreamFn,
runApprovalTurn,
sharedContextLabel,
- subscribeDeliveries,
TAIL_TURNS,
type ApprovalDecision,
type AssistantWork,
@@ -63,15 +66,7 @@ import {
import { buildTimeline, toolRowKind, type TimelineItem, type ToolPayload, type ToolRowModel } from "./timeline";
import { CONNECTOR_NAMES, connectorLinksIn, stripConnectorLinks, type ConnectorLink } from "./connector-link";
import { deepLinkPath, UI_BASE } from "./deep-link";
-import {
- currentDensity,
- embedMode,
- onDensityChange,
- onRelayedDelivery,
- postPaneState,
- requestPaneExpand,
-} from "./embed";
-import { exitSplitIfActive, relayDeliveryToPanes } from "./split";
+import type { ChatSurface, ConvCtx } from "./conv-types";
import { errMessage, swallow } from "../../chassis/src/errors";
import { showStateError } from "./error-banner";
import { escapeLoneDollars } from "./markdown-dollars";
@@ -94,279 +89,307 @@ import {
sessionSlackUrl,
surfaceOf,
} from "./sessions";
-import { applySessionState, backgroundLabel, clearWorking, conversationBackground, markWorking } from "./session-list";
+import { backgroundLabel, clearWorking, conversationBackground, markWorking } from "./session-list";
import { liveTurnThreadRef } from "./working-dot";
-import {
- carryModelPick,
- composerForm,
- composerState,
- currentModelOption,
- focusComposerEnd,
- onDragEnter,
- onDragLeave,
- onDragOver,
- onDrop,
- refreshRuntimeSelection,
- resetComposer,
- resizeComposer,
-} from "./composer";
import { newChatDraftKey, saveDraft, storedDraft } from "./drafts";
installMarkdownSanitizer();
-export const chatState = {
- agent: null as Agent | null,
- host: null as HTMLElement | null,
- threadRef: null as string | null,
- sessionId: null as string | null,
- scopeId: null as string | null,
- contextName: null as string | null,
- rememberedThreadRef: null as string | null,
- rememberedSessionId: null as string | null,
- rememberedScopeId: null as string | null,
- rememberedContextName: null as string | null,
- liveWork: null as WorkBlock | null,
- pendingSend: null as string | null,
- normalStreamFn: null as Agent["streamFn"] | null,
- onWork: null as ((work: WorkBlock) => void) | null,
- resolvingApprovals: new Set<string>(),
- transcriptAnchorSeq: null as number | null,
- earlierCount: 0,
- loadingEarlier: false,
-};
-
-let workTicker: ReturnType<typeof setInterval> | null = null;
-let revealedTailLen = 0;
const detachedAgents = new WeakSet<Agent>();
-let liveWorkExpanded = false;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
-
-export function notePendingSessionOnSend(): void {
- if (!chatState.threadRef || chatState.sessionId !== null) return;
- const existing = sessionsState.list.find((s) => s.id && s.threadRef === chatState.threadRef);
- if (existing) {
- if (chatState.agent) adoptActiveSessionFromList(chatState.agent);
- return;
- }
- addPendingSession(chatState.threadRef, chatState.scopeId, chatState.contextName);
+interface SettledRowKey {
+ index: number;
+ activity: WorkBlock["activity"] | undefined;
+ status: WorkBlock["status"] | undefined;
+ stale: boolean | undefined;
+ deliveredFiles: unknown;
+ stopReason: unknown;
+ errorMessage: unknown;
+ approvalDecision: unknown;
+ forkable: boolean;
+ tpl: TemplateResult | typeof nothing;
}
+const settledRowCache = new WeakMap<object, SettledRowKey>();
+const connectedConnectors = new Set<string>();
+const redrawHooks = new Set<() => void>();
+let proactiveOpenerStarted = false;
-let readOnlyView: { id: string; threadRef: string; session: CoreSession } | null = null;
-
-export function teardownActiveChat(): void {
- readOnlyView = null;
- preserveOutgoingWorkingDot(null);
- detachActiveAgent();
- chatState.agent = null;
- clearLiveWork();
- resetBackgroundPanel();
- chatState.host = null;
- chatState.threadRef = null;
- chatState.sessionId = null;
- chatState.scopeId = null;
- chatState.contextName = null;
- chatState.normalStreamFn = null;
- chatState.onWork = null;
- chatState.resolvingApprovals.clear();
- chatState.transcriptAnchorSeq = null;
- chatState.earlierCount = 0;
- chatState.loadingEarlier = false;
-}
+export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
-export function resetChatState(): void {
- teardownActiveChat();
- proactiveOpenerStarted = false;
- chatState.rememberedThreadRef = null;
- chatState.rememberedSessionId = null;
- chatState.rememberedScopeId = null;
- chatState.rememberedContextName = null;
- connectedConnectors.clear();
-}
+export function markConnectorConnected(provider: string): void {
+ if (!provider) return;
+ connectedConnectors.add(provider);
+ for (const hook of redrawHooks) hook();
+}
+
+export function createChatSurface(ctx: ConvCtx): ChatSurface {
+ const runSlot = createRunSlot();
+
+ const chatState = {
+ agent: null as Agent | null,
+ host: null as HTMLElement | null,
+ threadRef: null as string | null,
+ sessionId: null as string | null,
+ scopeId: null as string | null,
+ contextName: null as string | null,
+ rememberedThreadRef: null as string | null,
+ rememberedSessionId: null as string | null,
+ rememberedScopeId: null as string | null,
+ rememberedContextName: null as string | null,
+ liveWork: null as WorkBlock | null,
+ pendingSend: null as string | null,
+ normalStreamFn: null as Agent["streamFn"] | null,
+ onWork: null as ((work: WorkBlock) => void) | null,
+ resolvingApprovals: new Set<string>(),
+ transcriptAnchorSeq: null as number | null,
+ earlierCount: 0,
+ loadingEarlier: false,
+ };
-export function newChat(context?: { scopeId: string; name: string | null }): string {
- appState.currentView = "chats";
- renderSidebarTop();
- const user = appState.me?.user ?? "anon";
- const threadRef = `web:${user}:${crypto.randomUUID()}`;
- const carried = storedDraft(newChatDraftKey(user));
- if (carried) saveDraft(threadRef, carried);
- resetComposer();
- mountContinuable(threadRef, null, context?.scopeId ?? null, [], context?.name ?? null);
- renderList();
- focusComposerEnd();
- return threadRef;
-}
+ let workTicker: ReturnType<typeof setInterval> | null = null;
+ let revealedTailLen = 0;
+ let liveWorkExpanded = false;
-function preserveOutgoingWorkingDot(nextThreadRef: string | null): void {
- const live = liveTurnThreadRef({
- mountedThreadRef: chatState.threadRef,
- isStreaming: Boolean(chatState.agent?.state.isStreaming),
- pendingSend: chatState.pendingSend,
- });
- if (!live || live === nextThreadRef) return;
- sessionsState.list = markWorking(sessionsState.list, live);
-}
+ function notePendingSessionOnSend(): void {
+ if (!chatState.threadRef || chatState.sessionId !== null) return;
+ const existing = sessionsState.list.find((s) => s.id && s.threadRef === chatState.threadRef);
+ if (existing) {
+ if (chatState.agent) adoptActiveSessionFromList(chatState.agent);
+ return;
+ }
+ addPendingSession(chatState.threadRef, chatState.scopeId, chatState.contextName);
+ }
-function detachActiveAgent(): void {
- if (!chatState.agent) return;
- detachedAgents.add(chatState.agent);
- chatState.agent.abort();
-}
+ let readOnlyView: { id: string; threadRef: string; session: CoreSession; anchorSeq: number | null } | null = null;
+
+ function teardownActiveChat(): void {
+ readOnlyView = null;
+ preserveOutgoingWorkingDot(null);
+ detachActiveAgent();
+ chatState.agent = null;
+ clearLiveWork();
+ resetBackgroundPanel();
+ chatState.host = null;
+ chatState.threadRef = null;
+ chatState.sessionId = null;
+ chatState.scopeId = null;
+ chatState.contextName = null;
+ chatState.normalStreamFn = null;
+ chatState.onWork = null;
+ chatState.resolvingApprovals.clear();
+ chatState.transcriptAnchorSeq = null;
+ chatState.earlierCount = 0;
+ chatState.loadingEarlier = false;
+ }
-export function mountContinuable(
- threadRef: string,
- sessionId: string | null,
- scopeId: string | null,
- messages: ReturnType<typeof entriesToMessages>,
- contextName: string | null = null,
-): void {
- if (!appState.mainEl) return;
- exitSplitIfActive();
- readOnlyView = null;
- preserveOutgoingWorkingDot(threadRef);
- detachActiveAgent();
- resetComposer();
- chatState.threadRef = threadRef;
- chatState.sessionId = sessionId;
- chatState.scopeId = scopeId;
- chatState.contextName = contextName;
- chatState.rememberedThreadRef = threadRef;
- chatState.rememberedSessionId = sessionId;
- chatState.rememberedScopeId = scopeId;
- chatState.rememberedContextName = contextName;
- composerState.draft = storedDraft(threadRef);
- syncUrlFromState();
- chatState.transcriptAnchorSeq = null;
- chatState.earlierCount = 0;
- chatState.loadingEarlier = false;
- chatState.host = document.createElement("div");
- chatState.host.className = "custom-chat";
-
- const model = currentModelOption().model;
- const defaultThinkingLevel = defaultEffortForModel(model);
- const agent = new Agent({
- initialState: {
- systemPrompt: "",
- model,
- ...(defaultThinkingLevel === "low" ? { thinkingLevel: "low" as const } : {}),
- messages,
- tools: [],
- },
- convertToLlm: (messages) => import("@earendil-works/pi-web-ui").then((m) => m.defaultConvertToLlm(messages)),
- });
- chatState.agent = agent;
- clearLiveWork();
- resetBackgroundPanel();
- chatState.resolvingApprovals.clear();
- const onWork = observeLiveWork(agent);
- const normalStreamFn = makeCoreStreamFn(threadRef, agent, currentTurnOptions, onWork);
- agent.streamFn = normalStreamFn;
- chatState.normalStreamFn = normalStreamFn;
- chatState.onWork = onWork;
- void refreshRuntimeSelection(scopeId, agent);
-
- agent.subscribe((e) => {
- scheduleStreamDraw(agent);
- if (agent === chatState.agent && (agent.state.isStreaming || e.type === "agent_end")) chatState.pendingSend = null;
- if (e.type === "agent_end" && !detachedAgents.has(agent))
- sessionsState.list = clearWorking(sessionsState.list, threadRef);
+ function resetChatState(): void {
+ teardownActiveChat();
+ proactiveOpenerStarted = false;
+ chatState.rememberedThreadRef = null;
+ chatState.rememberedSessionId = null;
+ chatState.rememberedScopeId = null;
+ chatState.rememberedContextName = null;
+ connectedConnectors.clear();
+ }
+
+ function newChat(context?: { scopeId: string; name: string | null }): string {
+ appState.currentView = "chats";
+ renderSidebarTop();
+ const user = appState.me?.user ?? "anon";
+ const threadRef = `web:${user}:${crypto.randomUUID()}`;
+ const carried = storedDraft(newChatDraftKey(user));
+ if (carried) saveDraft(threadRef, carried);
+ ctx.composer.resetComposer();
+ mountContinuable(threadRef, null, context?.scopeId ?? null, [], context?.name ?? null);
renderList();
- if (e.type !== "agent_end") return;
- void agent.waitForIdle().then(async () => {
- if (agent === chatState.agent) clearLiveWork();
- const wasUnsaved = agent === chatState.agent && chatState.sessionId === null;
- try {
- await refreshSessions({ silent: true });
- } catch {
- void 0;
+ ctx.composer.focusComposerEnd();
+ return threadRef;
+ }
+
+ function preserveOutgoingWorkingDot(nextThreadRef: string | null): void {
+ const live = liveTurnThreadRef({
+ mountedThreadRef: chatState.threadRef,
+ isStreaming: Boolean(chatState.agent?.state.isStreaming),
+ pendingSend: chatState.pendingSend,
+ });
+ if (!live || live === nextThreadRef) return;
+ sessionsState.list = markWorking(sessionsState.list, live);
+ }
+
+ function detachActiveAgent(): void {
+ if (!chatState.agent) return;
+ detachedAgents.add(chatState.agent);
+ chatState.agent.abort();
+ }
+
+ function mountContinuable(
+ threadRef: string,
+ sessionId: string | null,
+ scopeId: string | null,
+ messages: ReturnType<typeof entriesToMessages>,
+ contextName: string | null = null,
+ ): void {
+ const container = ctx.claimContainer();
+ if (!container) return;
+ readOnlyView = null;
+ preserveOutgoingWorkingDot(threadRef);
+ detachActiveAgent();
+ ctx.composer.resetComposer();
+ chatState.threadRef = threadRef;
+ chatState.sessionId = sessionId;
+ chatState.scopeId = scopeId;
+ chatState.contextName = contextName;
+ chatState.rememberedThreadRef = threadRef;
+ chatState.rememberedSessionId = sessionId;
+ chatState.rememberedScopeId = scopeId;
+ chatState.rememberedContextName = contextName;
+ ctx.composer.state.draft = storedDraft(threadRef);
+ syncLocation();
+ chatState.transcriptAnchorSeq = null;
+ chatState.earlierCount = 0;
+ chatState.loadingEarlier = false;
+ chatState.host = document.createElement("div");
+ chatState.host.className = "custom-chat";
+
+ const model = ctx.composer.currentModelOption().model;
+ const defaultThinkingLevel = defaultEffortForModel(model);
+ const agent = new Agent({
+ initialState: {
+ systemPrompt: "",
+ model,
+ ...(defaultThinkingLevel === "low" ? { thinkingLevel: "low" as const } : {}),
+ messages,
+ tools: [],
+ },
+ convertToLlm: (messages) => import("@earendil-works/pi-web-ui").then((m) => m.defaultConvertToLlm(messages)),
+ });
+ chatState.agent = agent;
+ clearLiveWork();
+ resetBackgroundPanel();
+ chatState.resolvingApprovals.clear();
+ const onWork = observeLiveWork(agent);
+ const normalStreamFn = makeCoreStreamFn(threadRef, agent, currentTurnOptions, onWork, runSlot);
+ agent.streamFn = normalStreamFn;
+ chatState.normalStreamFn = normalStreamFn;
+ chatState.onWork = onWork;
+ void ctx.composer.refreshRuntimeSelection(scopeId, agent);
+
+ let listedWorking = false;
+ let titlePollStarted = false;
+ agent.subscribe((e) => {
+ if (!titlePollStarted && agent.state.isStreaming) {
+ // The server generates a title at the START of the first turn; poll for
+ // it right away instead of waiting for the turn to end, so long
+ // tool-heavy first turns don't leave the chat unnamed in the sidebar.
+ titlePollStarted = true;
+ const row = sessionsState.list.find((r) => r.threadRef === threadRef);
+ if (!row?.title?.trim()) void settleNewSessionTitle(agent, threadRef);
}
- if (!detachedAgents.has(agent)) {
+ scheduleStreamDraw(agent);
+ if (agent === chatState.agent && (agent.state.isStreaming || e.type === "agent_end"))
+ chatState.pendingSend = null;
+ if (e.type === "agent_end" && !detachedAgents.has(agent))
sessionsState.list = clearWorking(sessionsState.list, threadRef);
+ const working = agent.state.isStreaming || chatState.pendingSend !== null;
+ if (working !== listedWorking || e.type === "agent_end") {
+ listedWorking = working;
renderList();
}
- if (agent !== chatState.agent) return;
- adoptActiveSessionFromList(agent);
- await refreshTranscriptFromEntries(agent);
- if (wasUnsaved && chatState.sessionId) void settleNewSessionTitle(agent, chatState.sessionId);
+ if (e.type !== "agent_end") return;
+ void agent.waitForIdle().then(async () => {
+ if (agent === chatState.agent) clearLiveWork();
+ const wasUnsaved = agent === chatState.agent && chatState.sessionId === null;
+ try {
+ await refreshSessions({ silent: true });
+ } catch {
+ void 0;
+ }
+ if (!detachedAgents.has(agent)) {
+ sessionsState.list = clearWorking(sessionsState.list, threadRef);
+ renderList();
+ }
+ if (agent !== chatState.agent) return;
+ adoptActiveSessionFromList(agent);
+ await refreshTranscriptFromEntries(agent);
+ if (wasUnsaved && chatState.sessionId) void settleNewSessionTitle(agent, threadRef);
+ });
});
- });
-
- stickToBottom = true;
- appState.mainEl.replaceChildren(chatState.host);
- const opening = startProactiveOpenerIfNew(agent, threadRef, normalStreamFn, onWork, sessionId, scopeId, messages);
- drawActiveChat(agent, { forceScroll: true });
- focusComposerEnd();
- ensureDeliveryStream();
- if (!opening) void resumeTrackedRun(agent, threadRef, normalStreamFn, onWork);
- consumeBackgroundPanelRequest();
-}
-let proactiveOpenerStarted = false;
+ stickToBottom = true;
+ container.replaceChildren(chatState.host);
+ const opening = startProactiveOpenerIfNew(agent, threadRef, normalStreamFn, onWork, sessionId, scopeId, messages);
+ drawActiveChat(agent, { forceScroll: true });
+ ctx.composer.focusComposerEnd();
+ ctx.ensureDeliveryStream();
+ if (!opening) void resumeTrackedRun(agent, threadRef, normalStreamFn, onWork);
+ consumeBackgroundPanelRequest();
+ }
-function startProactiveOpenerIfNew(
- agent: Agent,
- threadRef: string,
- normalStreamFn: Agent["streamFn"],
- onWork: (work: WorkBlock) => void,
- sessionId: string | null,
- scopeId: string | null,
- messages: ReturnType<typeof entriesToMessages>,
-): boolean {
- if (embedMode) return false;
- if (proactiveOpenerStarted || sessionId !== null || scopeId !== null || messages.length > 0) return false;
- if (!sessionsState.loaded) return false;
- if (sessionsState.list.some((s) => s.id)) return false;
- proactiveOpenerStarted = true;
- agent.state.messages = [{ role: "user", content: "", opener: true } as unknown as AgentMessage];
- agent.streamFn = makeOpenerStreamFn(threadRef, agent, currentTurnOptions, onWork);
- void (async () => {
- try {
- await agent.continue();
- } catch (err) {
- if (agent === chatState.agent) composerState.error = errMessage(err, "Could not start the conversation.");
- } finally {
- if (agent === chatState.agent) {
- agent.streamFn = normalStreamFn;
- const last = agent.state.messages[agent.state.messages.length - 1] as AssistantMessage | undefined;
- if (
- last?.role === "assistant" &&
- (last.stopReason === "error" || last.stopReason === "aborted") &&
- !messageText(last).trim()
- ) {
- agent.state.messages = [];
+ function startProactiveOpenerIfNew(
+ agent: Agent,
+ threadRef: string,
+ normalStreamFn: Agent["streamFn"],
+ onWork: (work: WorkBlock) => void,
+ sessionId: string | null,
+ scopeId: string | null,
+ messages: ReturnType<typeof entriesToMessages>,
+ ): boolean {
+ if (ctx.pane) return false;
+ if (proactiveOpenerStarted || sessionId !== null || scopeId !== null || messages.length > 0) return false;
+ if (!sessionsState.loaded) return false;
+ if (sessionsState.list.some((s) => s.id)) return false;
+ proactiveOpenerStarted = true;
+ agent.state.messages = [{ role: "user", content: "", opener: true } as unknown as AgentMessage];
+ agent.streamFn = makeOpenerStreamFn(threadRef, agent, currentTurnOptions, onWork, runSlot);
+ void (async () => {
+ try {
+ await agent.continue();
+ } catch (err) {
+ if (agent === chatState.agent) ctx.composer.state.error = errMessage(err, "Could not start the conversation.");
+ } finally {
+ if (agent === chatState.agent) {
+ agent.streamFn = normalStreamFn;
+ const last = agent.state.messages[agent.state.messages.length - 1] as AssistantMessage | undefined;
+ if (
+ last?.role === "assistant" &&
+ (last.stopReason === "error" || last.stopReason === "aborted") &&
+ !messageText(last).trim()
+ ) {
+ agent.state.messages = [];
+ }
+ drawActiveChat(agent);
}
- drawActiveChat(agent);
}
- }
- })();
- return true;
-}
+ })();
+ return true;
+ }
-function currentTurnOptions(): TurnOptions {
- const { harnessId: harness } = currentModelOption();
- return {
- ...(harnessSupportsEffort(harness) ? { effortLevel: composerState.effortLevel } : {}),
- ...(harnessSupportsFastMode(harness) && typeof composerState.fastMode === "boolean"
- ? { fastMode: composerState.fastMode }
- : {}),
- harness,
- scopeId: chatState.scopeId,
- channelName: chatState.contextName,
- };
-}
+ function currentTurnOptions(): TurnOptions {
+ const { harnessId: harness } = ctx.composer.currentModelOption();
+ return {
+ ...(harnessSupportsEffort(harness) ? { effortLevel: ctx.composer.state.effortLevel } : {}),
+ ...(harnessSupportsFastMode(harness) && typeof ctx.composer.state.fastMode === "boolean"
+ ? { fastMode: ctx.composer.state.fastMode }
+ : {}),
+ harness,
+ scopeId: chatState.scopeId,
+ channelName: chatState.contextName,
+ };
+ }
-let deliveryStreamOpen = false;
-export function ensureDeliveryStream(): void {
- if (deliveryStreamOpen) return;
- deliveryStreamOpen = true;
- const onNudge = (threadRef: string): void => {
- if (!embedMode) void refreshSessions({ silent: true });
+ function onDelivery(threadRef: string): void {
const ro = readOnlyView;
if (ro && threadRef === ro.threadRef) {
- void api<{ entries: SessionEntry[] }>(`/api/sessions/${encodeURIComponent(ro.id)}`)
- .then((r) => {
- if (readOnlyView?.id === ro.id)
- mountReadOnly(readOnlyView.session, entriesToMessages(r.entries ?? [], transcriptModel()));
+ void fetchTranscript(ro.id, ro.anchorSeq !== null ? { sinceSeq: ro.anchorSeq } : { tailTurns: TAIL_TURNS })
+ .then((page) => {
+ if (readOnlyView?.id !== ro.id) return;
+ const earlier = page.earlierEntries ?? 0;
+ mountReadOnly(
+ readOnlyView.session,
+ entriesToMessages(page.entries ?? [], transcriptModel()),
+ earlier,
+ earlier > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ );
})
.catch(() => {});
return;
@@ -374,1552 +397,1613 @@ export function ensureDeliveryStream(): void {
const agent = chatState.agent;
if (!agent || threadRef !== chatState.threadRef || agent.state.isStreaming) return;
void refreshTranscriptFromEntries(agent);
- };
- if (embedMode) {
- onRelayedDelivery(onNudge);
- } else {
- subscribeDeliveries(
- (threadRef) => {
- relayDeliveryToPanes(threadRef);
- onNudge(threadRef);
- },
- (event) => {
- const { list, matched } = applySessionState(sessionsState.list, event);
- if (matched) {
- sessionsState.list = list;
- renderList();
- } else {
- void refreshSessions({ silent: true });
- }
- },
- () => void refreshSessions({ silent: true }),
- );
}
- if (typeof document !== "undefined") {
- document.addEventListener("visibilitychange", () => {
- if (document.visibilityState !== "visible") return;
- const agent = chatState.agent;
- if (!agent || agent.state.isStreaming || !chatState.threadRef || !chatState.normalStreamFn || !chatState.onWork)
- return;
- void resumeTrackedRun(agent, chatState.threadRef, chatState.normalStreamFn, chatState.onWork);
- });
+
+ function resumeIfIdle(): void {
+ const agent = chatState.agent;
+ if (!agent || agent.state.isStreaming || !chatState.threadRef || !chatState.normalStreamFn || !chatState.onWork)
+ return;
+ void resumeTrackedRun(agent, chatState.threadRef, chatState.normalStreamFn, chatState.onWork);
}
-}
-async function approveCommand(agent: Agent, decision: ApprovalDecision): Promise<void> {
- if (agent !== chatState.agent || !chatState.threadRef || agent.state.isStreaming) return;
- if (chatState.resolvingApprovals.size > 0) return;
- chatState.resolvingApprovals.add(decision.requestId);
- composerState.error = "";
- drawActiveChat(agent);
- try {
- await runApprovalTurn(chatState.threadRef, agent, decision, currentTurnOptions, chatState.onWork ?? undefined);
- } catch (err) {
- if (agent === chatState.agent) {
- composerState.error = err instanceof Error ? err.message : "Could not send the approval.";
- drawActiveChat(agent);
- }
- } finally {
- chatState.resolvingApprovals.delete(decision.requestId);
- if (agent === chatState.agent) {
- clearLiveWork();
- try {
- await refreshSessions({ silent: true });
- } catch {
- void 0;
+ function syncLocation(): void {
+ if (ctx.ownsUrl) syncUrlFromState();
+ else postCurrentPaneState();
+ }
+
+ function redrawForConnector(): void {
+ if (chatState.agent) drawActiveChat();
+ }
+
+ function dispose(): void {
+ redrawHooks.delete(redrawForConnector);
+ teardownActiveChat();
+ }
+
+ async function approveCommand(agent: Agent, decision: ApprovalDecision): Promise<void> {
+ if (agent !== chatState.agent || !chatState.threadRef || agent.state.isStreaming) return;
+ if (chatState.resolvingApprovals.size > 0) return;
+ chatState.resolvingApprovals.add(decision.requestId);
+ ctx.composer.state.error = "";
+ drawActiveChat(agent);
+ try {
+ await runApprovalTurn(
+ chatState.threadRef,
+ agent,
+ decision,
+ currentTurnOptions,
+ chatState.onWork ?? undefined,
+ undefined,
+ runSlot,
+ );
+ } catch (err) {
+ if (agent === chatState.agent) {
+ ctx.composer.state.error = err instanceof Error ? err.message : "Could not send the approval.";
+ drawActiveChat(agent);
+ }
+ } finally {
+ chatState.resolvingApprovals.delete(decision.requestId);
+ if (agent === chatState.agent) {
+ clearLiveWork();
+ try {
+ await refreshSessions({ silent: true });
+ } catch {
+ void 0;
+ }
+ await refreshTranscriptFromEntries(agent);
}
- await refreshTranscriptFromEntries(agent);
}
}
-}
-export function resolveCommandApproval(decision: ApprovalDecision): void {
- const agent = chatState.agent;
- if (agent) void approveCommand(agent, decision);
-}
+ function resolveCommandApproval(decision: ApprovalDecision): void {
+ const agent = chatState.agent;
+ if (agent) void approveCommand(agent, decision);
+ }
-export function activePendingApprovals(): PendingApproval[] {
- const agent = chatState.agent;
- if (!agent || agent.state.isStreaming) return [];
- const byId = new Map<string, PendingApproval>();
- for (const m of agent.state.messages) {
- if ((m as { role?: string }).role !== "assistant") continue;
- for (const approval of (m as AssistantWork).work?.pendingApprovals ?? []) {
- byId.set(approval.requestId, approval);
+ function activePendingApprovals(): PendingApproval[] {
+ const agent = chatState.agent;
+ if (!agent || agent.state.isStreaming) return [];
+ const byId = new Map<string, PendingApproval>();
+ for (const m of agent.state.messages) {
+ if ((m as { role?: string }).role !== "assistant") continue;
+ for (const approval of (m as AssistantWork).work?.pendingApprovals ?? []) {
+ byId.set(approval.requestId, approval);
+ }
}
+ return [...byId.values()];
}
- return [...byId.values()];
-}
-export function hasUnresolvedApproval(): boolean {
- return activePendingApprovals().length > 0;
-}
+ function hasUnresolvedApproval(): boolean {
+ return activePendingApprovals().length > 0;
+ }
-async function refreshTranscriptFromEntries(agent: Agent): Promise<void> {
- const sessionId = chatState.sessionId;
- if (!sessionId || agent !== chatState.agent || agent.state.isStreaming) return drawActiveChat(agent);
- const last = agent.state.messages[agent.state.messages.length - 1] as { stopReason?: string } | undefined;
- if (last?.stopReason === "error" || last?.stopReason === "aborted") return drawActiveChat(agent);
- try {
- const anchor = chatState.transcriptAnchorSeq;
- const page = await fetchTranscript(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);
- if (agent !== chatState.agent || agent.state.isStreaming) return;
- const messages = entriesToMessages(page.entries ?? [], transcriptModel());
+ async function refreshTranscriptFromEntries(agent: Agent): Promise<void> {
+ const sessionId = chatState.sessionId;
+ if (!sessionId || agent !== chatState.agent || agent.state.isStreaming) return drawActiveChat(agent);
+ const last = agent.state.messages[agent.state.messages.length - 1] as { stopReason?: string } | undefined;
+ if (last?.stopReason === "error" || last?.stopReason === "aborted") return drawActiveChat(agent);
try {
- const r = await api<{ approvals: PendingApproval[] }>(`/api/sessions/${encodeURIComponent(sessionId)}/approvals`);
- attachPendingApprovals(messages, r.approvals ?? [], transcriptModel());
+ const anchor = chatState.transcriptAnchorSeq;
+ const page = await fetchTranscript(sessionId, anchor !== null ? { sinceSeq: anchor } : undefined);
+ if (agent !== chatState.agent || agent.state.isStreaming) return;
+ const messages = entriesToMessages(page.entries ?? [], transcriptModel());
+ try {
+ const r = await api<{ approvals: PendingApproval[] }>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/approvals`,
+ );
+ attachPendingApprovals(messages, r.approvals ?? [], transcriptModel());
+ } catch {
+ void 0;
+ }
+ if (agent !== chatState.agent || agent.state.isStreaming) return;
+ agent.state.messages = messages;
+ chatState.earlierCount = page.earlierEntries ?? 0;
+ chatState.transcriptAnchorSeq = chatState.earlierCount > 0 ? (page.entries?.[0]?.seq ?? null) : null;
} catch {
void 0;
}
- if (agent !== chatState.agent || agent.state.isStreaming) return;
- agent.state.messages = messages;
- chatState.earlierCount = page.earlierEntries ?? 0;
- if (chatState.earlierCount === 0) chatState.transcriptAnchorSeq = null;
- } catch {
- void 0;
- }
- drawActiveChat(agent);
-}
-
-function observeLiveWork(agent: Agent): (work: WorkBlock) => void {
- return (work: WorkBlock) => {
- if (agent !== chatState.agent) return;
- chatState.liveWork = work;
- syncWorkTicker();
drawActiveChat(agent);
- };
-}
-
-async function resumeTrackedRun(
- agent: Agent,
- threadRef: string,
- normalStreamFn: Agent["streamFn"],
- onWork: (work: WorkBlock) => void,
-): Promise<boolean> {
- if (!agent.state.messages.length) return false;
- let activeRun: Awaited<ReturnType<typeof activeRunForThread>>;
- try {
- activeRun = await activeRunForThread(threadRef);
- } catch {
- return false;
- }
- if (!activeRun || agent !== chatState.agent || appState.currentView !== "chats" || agent.state.isStreaming)
- return false;
- const msgs = agent.state.messages.slice();
- while (msgs.length && (msgs[msgs.length - 1] as { role?: string }).role === "assistant") msgs.pop();
- if (!msgs.length) return false;
- agent.state.messages = msgs;
- agent.streamFn = makeRunResumeStreamFn(activeRun.runId, activeRun.run, onWork);
- try {
- await agent.continue();
- } catch (err) {
- if (agent === chatState.agent)
- composerState.error = err instanceof Error ? err.message : "Could not reconnect to the running task.";
- } finally {
- if (agent === chatState.agent) {
- agent.streamFn = normalStreamFn;
- await refreshTranscriptFromEntries(agent);
- }
}
- return true;
-}
-
-function adoptActiveSessionFromList(agent: Agent): void {
- if (agent !== chatState.agent || chatState.sessionId !== null || chatState.threadRef === null) return;
- const match = sessionsState.list.find((s) => s.id && s.threadRef === chatState.threadRef);
- if (!match) return;
- chatState.sessionId = match.id;
- chatState.scopeId = match.scopeId;
- if (match.channelName) chatState.contextName = match.channelName;
- chatState.rememberedSessionId = match.id;
- chatState.rememberedScopeId = match.scopeId;
- chatState.rememberedContextName = chatState.contextName;
- syncUrlFromState();
- renderList();
- drawActiveChat(agent);
-}
-
-export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
-export function postCurrentPaneState(): void {
- if (!embedMode) return;
- const live = liveTurnThreadRef({
- mountedThreadRef: chatState.threadRef,
- isStreaming: Boolean(chatState.agent?.state.isStreaming),
- pendingSend: chatState.pendingSend,
- });
- postPaneState({
- threadRef: chatState.threadRef ?? chatState.rememberedThreadRef,
- sessionId: chatState.sessionId ?? chatState.rememberedSessionId,
- working: live !== null,
- });
-}
+ function observeLiveWork(agent: Agent): (work: WorkBlock) => void {
+ return (work: WorkBlock) => {
+ if (agent !== chatState.agent) return;
+ chatState.liveWork = work;
+ syncWorkTicker();
+ drawActiveChat(agent);
+ };
+ }
-async function settleNewSessionTitle(agent: Agent, sessionId: string): Promise<void> {
- const titled = (): boolean => {
- const s = sessionsState.list.find((row) => row.id === sessionId);
- return Boolean(s?.title && s.title.trim());
- };
- if (titled()) return;
- for (const delay of [600, 1200, 2400, 4000]) {
- await sleep(delay);
- if (agent !== chatState.agent || chatState.sessionId !== sessionId) return;
+ async function resumeTrackedRun(
+ agent: Agent,
+ threadRef: string,
+ normalStreamFn: Agent["streamFn"],
+ onWork: (work: WorkBlock) => void,
+ ): Promise<boolean> {
+ if (!agent.state.messages.length) return false;
+ let activeRun: Awaited<ReturnType<typeof activeRunForThread>>;
try {
- await refreshSessions({ silent: true });
+ activeRun = await activeRunForThread(threadRef);
} catch {
- void 0;
+ return false;
}
- if (titled()) return;
+ if (!activeRun || agent !== chatState.agent || appState.currentView !== "chats" || agent.state.isStreaming)
+ return false;
+ // Pull the transcript before attaching so the turn's triggering user message
+ // (written by core, not by this tab) is on screen while the run streams.
+ await refreshTranscriptFromEntries(agent);
+ if (agent !== chatState.agent || agent.state.isStreaming) return false;
+ const msgs = agent.state.messages.slice();
+ const popped: AgentMessage[] = [];
+ while (msgs.length && (msgs[msgs.length - 1] as { role?: string }).role === "assistant")
+ popped.unshift(msgs.pop()!);
+ if (!msgs.length) return false;
+ agent.state.messages = msgs;
+ // Seed the resumed stream with the assistant text we just removed so the
+ // model's already-visible words (e.g. its opening ack) don't blink out
+ // while we re-attach to the live run.
+ const seedText = popped
+ .map((m) => messageText(m).trim())
+ .filter(Boolean)
+ .join("\n\n");
+ agent.streamFn = makeRunResumeStreamFn(activeRun.runId, activeRun.run, onWork, runSlot, seedText);
+ try {
+ await agent.continue();
+ } catch (err) {
+ if (agent === chatState.agent)
+ ctx.composer.state.error = err instanceof Error ? err.message : "Could not reconnect to the running task.";
+ } finally {
+ if (agent === chatState.agent) {
+ agent.streamFn = normalStreamFn;
+ await refreshTranscriptFromEntries(agent);
+ }
+ }
+ return true;
}
-}
-export function mountLoadingPane(): void {
- if (!appState.mainEl || appState.currentView !== "chats") return;
- const host = document.createElement("div");
- host.className = "custom-chat";
- render(
- html`<div class="custom-chat-shell">
- <div class="chat-loading"><span class="spinner"></span></div>
- </div>`,
- host,
- );
- appState.mainEl.replaceChildren(host);
-}
+ function adoptActiveSessionFromList(agent: Agent): void {
+ if (agent !== chatState.agent || chatState.sessionId !== null || chatState.threadRef === null) return;
+ const match = sessionsState.list.find((s) => s.id && s.threadRef === chatState.threadRef);
+ if (!match) return;
+ chatState.sessionId = match.id;
+ chatState.scopeId = match.scopeId;
+ if (match.channelName) chatState.contextName = match.channelName;
+ chatState.rememberedSessionId = match.id;
+ chatState.rememberedScopeId = match.scopeId;
+ chatState.rememberedContextName = chatState.contextName;
+ syncLocation();
+ renderList();
+ drawActiveChat(agent);
+ }
+
+ function postCurrentPaneState(): void {
+ if (!ctx.pane) return;
+ const live = liveTurnThreadRef({
+ mountedThreadRef: chatState.threadRef,
+ isStreaming: Boolean(chatState.agent?.state.isStreaming),
+ pendingSend: chatState.pendingSend,
+ });
+ ctx.onState?.({
+ threadRef: chatState.threadRef ?? chatState.rememberedThreadRef,
+ sessionId: chatState.sessionId ?? chatState.rememberedSessionId,
+ working: live !== null,
+ });
+ }
+
+ async function settleNewSessionTitle(agent: Agent, threadRef: string): Promise<void> {
+ const titled = (): boolean => {
+ const s = sessionsState.list.find((row) => row.threadRef === threadRef);
+ return Boolean(s?.title && s.title.trim());
+ };
+ if (titled()) return;
+ for (const delay of [1200, 1800, 2400, 3600, 4800, 6400, 8000, 8000]) {
+ await sleep(delay);
+ if (agent !== chatState.agent || chatState.threadRef !== threadRef) return;
+ try {
+ await refreshSessions({ silent: true });
+ } catch {
+ void 0;
+ }
+ if (titled()) return;
+ }
+ }
-export function mountReadOnly(
- s: CoreSession,
- messages: ReturnType<typeof entriesToMessages>,
- earlierCount = 0,
- anchorSeq: number | null = null,
-): void {
- if (!appState.mainEl) return;
- exitSplitIfActive();
- preserveOutgoingWorkingDot(s.threadRef);
- detachActiveAgent();
- chatState.agent = null;
- clearLiveWork();
- chatState.host = null;
- resetComposer();
- chatState.threadRef = null;
- chatState.sessionId = s.id;
- chatState.scopeId = s.scopeId;
- syncUrlFromState();
-
- resetBackgroundPanel();
- const host = document.createElement("div");
- host.className = "custom-chat readonly-chat";
- const draw = () =>
+ function mountLoadingPane(): void {
+ const container = ctx.container();
+ if (!container || !ctx.visible()) return;
+ const host = document.createElement("div");
+ host.className = "custom-chat";
render(
- html`
- <div class="custom-chat-shell">
- ${chatHeader(groupDmTitle(s), surfaceOf(s), true)}
- <div class="readonly-banner">
- ${
- surfaceOf(s) === "slack"
- ? html`This conversation lives in Slack. Replies happen
- there.${
- sessionSlackUrl(s)
- ? html` <a
- class="readonly-banner-link"
- href=${sessionSlackUrl(s)!}
- target="_blank"
- rel="noreferrer"
- >Open in Slack</a
- >`
- : nothing
- }`
- : "This conversation is read-only here."
- }
- </div>
- ${backgroundActivityStrip()}
- <section class="chat-scroll readonly-scroll">
- <div class="message-stack">
+ html`<div class="custom-chat-shell">
+ <div class="chat-loading"><span class="spinner"></span></div>
+ </div>`,
+ host,
+ );
+ container.replaceChildren(host);
+ }
+
+ function mountReadOnly(
+ s: CoreSession,
+ messages: ReturnType<typeof entriesToMessages>,
+ earlierCount = 0,
+ anchorSeq: number | null = null,
+ ): void {
+ const container = ctx.claimContainer();
+ if (!container) return;
+ preserveOutgoingWorkingDot(s.threadRef);
+ detachActiveAgent();
+ chatState.agent = null;
+ clearLiveWork();
+ chatState.host = null;
+ ctx.composer.resetComposer();
+ chatState.threadRef = null;
+ chatState.sessionId = s.id;
+ chatState.scopeId = s.scopeId;
+ syncLocation();
+
+ resetBackgroundPanel();
+ const host = document.createElement("div");
+ host.className = "custom-chat readonly-chat";
+ const draw = () =>
+ render(
+ html`
+ <div class="custom-chat-shell">
+ ${chatHeader(groupDmTitle(s), surfaceOf(s), true)}
+ <div class="readonly-banner">
${
- earlierCount > 0
- ? html`<div class="earlier-messages">
- <button
- class="earlier-messages-btn"
- @click=${async (e: Event) => {
- const btn = e.currentTarget as HTMLButtonElement;
- btn.disabled = true;
- btn.textContent = "Loading earlier messages\u2026";
- try {
- const page = await fetchTranscript(
- s.id,
- anchorSeq !== null ? { beforeSeq: anchorSeq, tailTurns: TAIL_TURNS } : undefined,
- );
- if (chatState.sessionId !== s.id) return;
- const scroller = appState.mainEl?.querySelector<HTMLElement>(".chat-scroll");
- const priorHeight = scroller?.scrollHeight ?? 0;
- const priorTop = scroller?.scrollTop ?? 0;
- const remaining = page.earlierEntries ?? 0;
- mountReadOnly(
- s,
- [...entriesToMessages(page.entries ?? [], transcriptModel()), ...messages],
- remaining,
- remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null,
- );
- requestAnimationFrame(() => {
- const scrollerNow = appState.mainEl?.querySelector<HTMLElement>(".chat-scroll");
- if (!scrollerNow) return;
- scrollerNow.scrollTop = priorTop + (scrollerNow.scrollHeight - priorHeight);
- });
- } catch {
- btn.disabled = false;
- btn.textContent = "Show earlier messages";
- }
- }}
- >
- Show earlier messages
- </button>
- </div>`
- : nothing
+ surfaceOf(s) === "slack"
+ ? html`This conversation lives in Slack. Replies happen
+ there.${
+ sessionSlackUrl(s)
+ ? html` <a
+ class="readonly-banner-link"
+ href=${sessionSlackUrl(s)!}
+ target="_blank"
+ rel="noreferrer"
+ >Open in Slack</a
+ >`
+ : nothing
+ }`
+ : "This conversation is read-only here."
}
- ${messages.length ? messages.map((m, i) => chatMessage(m, i)) : html`<div class="empty compact">No readable messages in this conversation.</div>`}
</div>
- </section>
- </div>
- `,
- host,
- );
- readonlyRedraw = draw;
- draw();
- appState.mainEl.replaceChildren(host);
- readOnlyView = { id: s.id, threadRef: s.threadRef, session: s };
- ensureDeliveryStream();
- consumeBackgroundPanelRequest();
-}
+ ${backgroundActivityStrip()}
+ <section class="chat-scroll readonly-scroll">
+ <div class="message-stack">
+ ${
+ earlierCount > 0
+ ? html`<div class="earlier-messages">
+ <button
+ class="earlier-messages-btn"
+ @click=${async (e: Event) => {
+ const btn = e.currentTarget as HTMLButtonElement;
+ btn.disabled = true;
+ btn.textContent = "Loading earlier messages\u2026";
+ try {
+ const page = await fetchTranscript(
+ s.id,
+ anchorSeq !== null ? { beforeSeq: anchorSeq, tailTurns: TAIL_TURNS } : undefined,
+ );
+ if (chatState.sessionId !== s.id) return;
+ const scroller = container?.querySelector<HTMLElement>(".chat-scroll");
+ const priorHeight = scroller?.scrollHeight ?? 0;
+ const priorTop = scroller?.scrollTop ?? 0;
+ const remaining = page.earlierEntries ?? 0;
+ mountReadOnly(
+ s,
+ [...entriesToMessages(page.entries ?? [], transcriptModel()), ...messages],
+ remaining,
+ remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null,
+ );
+ requestAnimationFrame(() => {
+ const scrollerNow = container?.querySelector<HTMLElement>(".chat-scroll");
+ if (!scrollerNow) return;
+ scrollerNow.scrollTop = priorTop + (scrollerNow.scrollHeight - priorHeight);
+ });
+ } catch {
+ btn.disabled = false;
+ btn.textContent = "Show earlier messages";
+ }
+ }}
+ >
+ Show earlier messages
+ </button>
+ </div>`
+ : nothing
+ }
+ ${messages.length ? messages.map((m, i) => chatMessage(m, i)) : html`<div class="empty compact">No readable messages in this conversation.</div>`}
+ </div>
+ </section>
+ </div>
+ `,
+ host,
+ );
+ readonlyRedraw = draw;
+ draw();
+ container.replaceChildren(host);
+ readOnlyView = { id: s.id, threadRef: s.threadRef, session: s, anchorSeq };
+ ctx.ensureDeliveryStream();
+ consumeBackgroundPanelRequest();
+ }
-function welcomeGreeting(): TemplateResult {
- return html`
- <article class="message-row assistant-row welcome-greeting">
- <div class="assistant-body">
- <div class="streaming-text">
- ${markdown(
- "Hi — I'm your AI teammate 👋\n\n" +
- "I run tasks on a computer of my own and work across your connected tools — Slack, Google Workspace, GitHub, Linear, and the open web — and I remember what we work on together.\n\n" +
- "Want to get set up? Tell me your name and what you're working on, and I'll take it from there — or just ask me anything to dive straight in.",
- )}
+ function welcomeGreeting(): TemplateResult {
+ return html`
+ <article class="message-row assistant-row welcome-greeting">
+ <div class="assistant-body">
+ <div class="streaming-text">
+ ${markdown(
+ "Hi — I'm your AI teammate 👋\n\n" +
+ "I run tasks on a computer of my own and work across your connected tools — Slack, Google Workspace, GitHub, Linear, and the open web — and I remember what we work on together.\n\n" +
+ "Want to get set up? Tell me your name and what you're working on, and I'll take it from there — or just ask me anything to dive straight in.",
+ )}
+ </div>
</div>
- </div>
- </article>
- `;
-}
+ </article>
+ `;
+ }
-export function setTranscriptWindow(anchorSeq: number | null, earlierCount: number): void {
- chatState.transcriptAnchorSeq = earlierCount > 0 ? anchorSeq : null;
- chatState.earlierCount = earlierCount;
- if (chatState.agent) drawActiveChat(chatState.agent);
-}
+ function setTranscriptWindow(anchorSeq: number | null, earlierCount: number): void {
+ chatState.transcriptAnchorSeq = earlierCount > 0 ? anchorSeq : null;
+ chatState.earlierCount = earlierCount;
+ if (chatState.agent) drawActiveChat(chatState.agent);
+ }
-function earlierNotice(agent: Agent): TemplateResult {
- return html`<div class="earlier-messages">
- <button
- class="earlier-messages-btn"
- ?disabled=${chatState.loadingEarlier || agent.state.isStreaming}
- @click=${() => void loadEarlierMessages()}
- >
- ${chatState.loadingEarlier ? "Loading earlier messages…" : "Show earlier messages"}
- </button>
- </div>`;
-}
+ function earlierNotice(agent: Agent): TemplateResult {
+ return html`<div class="earlier-messages">
+ <button
+ class="earlier-messages-btn"
+ ?disabled=${chatState.loadingEarlier || agent.state.isStreaming}
+ @click=${() => void loadEarlierMessages()}
+ >
+ ${chatState.loadingEarlier ? "Loading earlier messages…" : "Show earlier messages"}
+ </button>
+ </div>`;
+ }
-async function loadEarlierMessages(): Promise<void> {
- const agent = chatState.agent;
- const sessionId = chatState.sessionId;
- const anchor = chatState.transcriptAnchorSeq;
- if (!agent || !sessionId || anchor === null || chatState.loadingEarlier || agent.state.isStreaming) return;
- chatState.loadingEarlier = true;
- drawActiveChat(agent);
- try {
- const page = await fetchTranscript(sessionId, { beforeSeq: anchor, tailTurns: TAIL_TURNS });
- if (agent !== chatState.agent || agent.state.isStreaming) return;
- const earlierMessages = entriesToMessages(page.entries ?? [], transcriptModel());
- const scroller = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
- const priorHeight = scroller?.scrollHeight ?? 0;
- const priorTop = scroller?.scrollTop ?? 0;
- agent.state.messages = [...earlierMessages, ...agent.state.messages];
- const remaining = page.earlierEntries ?? 0;
- chatState.transcriptAnchorSeq = remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null;
- chatState.earlierCount = remaining;
- chatState.loadingEarlier = false;
+ async function loadEarlierMessages(): Promise<void> {
+ const agent = chatState.agent;
+ const sessionId = chatState.sessionId;
+ const anchor = chatState.transcriptAnchorSeq;
+ if (!agent || !sessionId || anchor === null || chatState.loadingEarlier || agent.state.isStreaming) return;
+ chatState.loadingEarlier = true;
drawActiveChat(agent);
- requestAnimationFrame(() => {
- const scrollerNow = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
- if (!scrollerNow) return;
- const prev = scrollerNow.style.scrollBehavior;
- scrollerNow.style.scrollBehavior = "auto";
- scrollerNow.scrollTop = priorTop + (scrollerNow.scrollHeight - priorHeight);
- scrollerNow.style.scrollBehavior = prev;
- });
- } catch {
- void 0;
- } finally {
- if (chatState.loadingEarlier) {
+ try {
+ const page = await fetchTranscript(sessionId, { beforeSeq: anchor, tailTurns: TAIL_TURNS });
+ if (agent !== chatState.agent || agent.state.isStreaming) return;
+ const earlierMessages = entriesToMessages(page.entries ?? [], transcriptModel());
+ const scroller = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
+ const priorHeight = scroller?.scrollHeight ?? 0;
+ const priorTop = scroller?.scrollTop ?? 0;
+ agent.state.messages = [...earlierMessages, ...agent.state.messages];
+ const remaining = page.earlierEntries ?? 0;
+ chatState.transcriptAnchorSeq = remaining > 0 ? (page.entries?.[0]?.seq ?? null) : null;
+ chatState.earlierCount = remaining;
chatState.loadingEarlier = false;
- if (agent === chatState.agent) drawActiveChat(agent);
+ drawActiveChat(agent);
+ requestAnimationFrame(() => {
+ const scrollerNow = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
+ if (!scrollerNow) return;
+ const prev = scrollerNow.style.scrollBehavior;
+ scrollerNow.style.scrollBehavior = "auto";
+ scrollerNow.scrollTop = priorTop + (scrollerNow.scrollHeight - priorHeight);
+ scrollerNow.style.scrollBehavior = prev;
+ });
+ } catch {
+ void 0;
+ } finally {
+ if (chatState.loadingEarlier) {
+ chatState.loadingEarlier = false;
+ if (agent === chatState.agent) drawActiveChat(agent);
+ }
}
}
-}
-let streamDrawScheduled = false;
-let streamDrawAgent: Agent | null = null;
-function scheduleStreamDraw(agent: Agent): void {
- streamDrawAgent = agent;
- if (streamDrawScheduled) return;
- streamDrawScheduled = true;
- requestAnimationFrame(() => {
- streamDrawScheduled = false;
- const target = streamDrawAgent;
- streamDrawAgent = null;
- if (target) drawActiveChat(target);
- });
-}
+ let streamDrawScheduled = false;
+ let streamDrawAgent: Agent | null = null;
+ function scheduleStreamDraw(agent: Agent): void {
+ streamDrawAgent = agent;
+ if (streamDrawScheduled) return;
+ streamDrawScheduled = true;
+ requestAnimationFrame(() => {
+ streamDrawScheduled = false;
+ const target = streamDrawAgent;
+ streamDrawAgent = null;
+ if (target) drawActiveChat(target);
+ });
+ }
-function paneGlance(agent: Agent, messages: AgentMessage[], tier: "card" | "strip"): TemplateResult {
- const now = paneNowLine(agent);
- const last = [...messages].reverse().find((m) => m.role === "assistant" && messageText(m).trim());
- const snippet = last ? messageText(last).trim() : "";
- if (tier === "strip") {
+ function paneGlance(agent: Agent, messages: AgentMessage[], tier: "card" | "strip"): TemplateResult {
+ const now = paneNowLine(agent);
+ const last = [...messages].reverse().find((m) => m.role === "assistant" && messageText(m).trim());
+ const snippet = last ? messageText(last).trim() : "";
+ if (tier === "strip") {
+ return html`
+ <button type="button" class="pane-strip" title="Expand this pane" @click=${() => ctx.onExpand?.()}>
+ <span class="pane-strip-text">${now ?? snippet}</span>
+ ${icon(Maximize2, 13)}
+ </button>
+ `;
+ }
return html`
- <button type="button" class="pane-strip" title="Expand this pane" @click=${() => requestPaneExpand()}>
- <span class="pane-strip-text">${now ?? snippet}</span>
- ${icon(Maximize2, 13)}
- </button>
+ <section class="pane-card" aria-live="polite">
+ ${now ? html`<div class="pane-card-now"><span class="pane-card-now-label">Now</span><span class="pane-card-now-text">${now}</span></div>` : nothing}
+ ${snippet ? html`<div class="pane-card-last">${snippet}</div>` : nothing}
+ </section>
`;
}
- return html`
- <section class="pane-card" aria-live="polite">
- ${now ? html`<div class="pane-card-now"><span class="pane-card-now-label">Now</span><span class="pane-card-now-text">${now}</span></div>` : nothing}
- ${snippet ? html`<div class="pane-card-last">${snippet}</div>` : nothing}
- </section>
- `;
-}
-function paneNowLine(agent: Agent): string | null {
- if (activePendingApprovals().length) return "Needs your approval";
- if (agent.state.isStreaming || chatState.resolvingApprovals.size > 0) {
- const work = chatState.liveWork ?? { status: "thinking", activity: [] };
- const summary = liveWorkSummary(work);
- if (!summary) return "Thinking…";
- return summary.detail ? `${summary.label} — ${summary.detail}` : summary.label;
+ function paneNowLine(agent: Agent): string | null {
+ if (activePendingApprovals().length) return "Needs your approval";
+ if (agent.state.isStreaming || chatState.resolvingApprovals.size > 0) {
+ const work = chatState.liveWork ?? { status: "thinking", activity: [] };
+ const summary = liveWorkSummary(work);
+ if (!summary) return "Thinking…";
+ return summary.detail ? `${summary.label} — ${summary.detail}` : summary.label;
+ }
+ return null;
}
- return null;
-}
-onDensityChange(() => drawActiveChat());
+ ctx.onDensityChange(() => drawActiveChat());
-export function drawActiveChat(agent = chatState.agent, opts: { forceScroll?: boolean } = {}): void {
- if (!agent || agent !== chatState.agent || !chatState.host || appState.currentView !== "chats") return;
- const messages = visibleMessages(agent);
- const isNewUser = sessionsState.list.filter((s) => s.id).length === 0;
- let messageContent: Array<TemplateResult | typeof nothing> | TemplateResult | typeof nothing = nothing;
- if (messages.length) {
- messageContent = messages.map((m, i) =>
- settledChatMessage(m, i, agent.state.isStreaming && m === agent.state.streamingMessage),
+ function drawActiveChat(agent = chatState.agent, opts: { forceScroll?: boolean } = {}): void {
+ if (!agent || agent !== chatState.agent || !chatState.host || appState.currentView !== "chats") return;
+ const messages = visibleMessages(agent);
+ const isNewUser = sessionsState.list.filter((s) => s.id).length === 0;
+ let messageContent: Array<TemplateResult | typeof nothing> | TemplateResult | typeof nothing = nothing;
+ if (messages.length) {
+ messageContent = messages.map((m, i) =>
+ settledChatMessage(m, i, agent.state.isStreaming && m === agent.state.streamingMessage),
+ );
+ } else if (isNewUser) {
+ messageContent = welcomeGreeting();
+ }
+ const tier = ctx.density();
+ const glanceTier = tier === "card" || tier === "strip" ? tier : null;
+ render(
+ html`
+ <div
+ class="custom-chat-shell ${ctx.composer.state.dragging ? "dragging" : ""}"
+ @dragenter=${(e: DragEvent) => ctx.composer.onDragEnter(e)}
+ @dragover=${(e: DragEvent) => ctx.composer.onDragOver(e)}
+ @dragleave=${(e: DragEvent) => ctx.composer.onDragLeave(e)}
+ @drop=${(e: DragEvent) => void ctx.composer.onDrop(e, agent)}
+ >
+ ${
+ ctx.composer.state.dragging
+ ? html`<div class="drop-overlay">
+ <div class="drop-overlay-card">${icon(Files, 30)}<span>Drop files or folders to attach</span></div>
+ </div>`
+ : nothing
+ }
+ ${contextBanner()}
+ ${
+ glanceTier
+ ? paneGlance(agent, messages, glanceTier)
+ : html`<section class="chat-scroll" @scroll=${onTranscriptScroll}>
+ <div class="message-stack ${messages.length ? "" : "empty-stack"}">
+ ${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing} ${messageContent}
+ ${showStateError(messages, agent.state.errorMessage) ? html`<div class="composer-error inline">${agent.state.errorMessage}</div>` : nothing}
+ </div>
+ </section>`
+ }
+ <div class="chat-bottom-dock">
+ ${backgroundActivityStrip()} ${liveWorkDock(agent)} ${ctx.composer.composerForm(agent)}
+ </div>
+ </div>
+ `,
+ chatState.host,
);
- } else if (isNewUser) {
- messageContent = welcomeGreeting();
- }
- const tier = currentDensity();
- const glanceTier = tier === "card" || tier === "strip" ? tier : null;
- render(
- html`
- <div
- class="custom-chat-shell ${composerState.dragging ? "dragging" : ""}"
- @dragenter=${(e: DragEvent) => onDragEnter(e)}
- @dragover=${(e: DragEvent) => onDragOver(e)}
- @dragleave=${(e: DragEvent) => onDragLeave(e)}
- @drop=${(e: DragEvent) => void onDrop(e, agent)}
- >
- ${
- composerState.dragging
- ? html`<div class="drop-overlay">
- <div class="drop-overlay-card">${icon(Files, 30)}<span>Drop files or folders to attach</span></div>
- </div>`
- : nothing
- }
- ${contextBanner()}
- ${
- glanceTier
- ? paneGlance(agent, messages, glanceTier)
- : html`<section class="chat-scroll" @scroll=${onTranscriptScroll}>
- <div class="message-stack ${messages.length ? "" : "empty-stack"}">
- ${chatState.earlierCount > 0 ? earlierNotice(agent) : nothing} ${messageContent}
- ${showStateError(messages, agent.state.errorMessage) ? html`<div class="composer-error inline">${agent.state.errorMessage}</div>` : nothing}
- </div>
- </section>`
- }
- <div class="chat-bottom-dock">${backgroundActivityStrip()} ${liveWorkDock(agent)} ${composerForm(agent)}</div>
- </div>
- `,
- chatState.host,
- );
- decorateStreamingTail();
- resizeComposer();
- scrollTranscript(opts.forceScroll);
- postCurrentPaneState();
-}
-
-function decorateStreamingTail(): void {
- const blocks = chatState.host?.querySelectorAll<HTMLElement>(".streaming-text.live-stream markdown-block");
- const block = blocks?.length ? blocks[blocks.length - 1] : undefined;
- if (!block) {
- revealedTailLen = 0;
- return;
- }
- if (reduceMotion.matches) return;
- const fullLen = (block.textContent ?? "").replace(/\s+$/u, "").length;
- const grown = fullLen - revealedTailLen;
- revealedTailLen = fullLen;
- if (grown <= 0 || grown > 240) return;
- const last = lastTextNode(block);
- if (!last || !last.textContent) return;
- const visibleEnd = last.textContent.replace(/\s+$/u, "").length;
- const n = Math.min(grown, visibleEnd);
- if (n <= 0) return;
- const tail = last.splitText(visibleEnd - n);
- if (tail.textContent && tail.textContent.length > n) tail.splitText(n);
- const parent = tail.parentNode;
- if (!parent) return;
- const span = document.createElement("span");
- span.className = "tok-in";
- parent.insertBefore(span, tail);
- span.appendChild(tail);
-}
+ decorateStreamingTail();
+ ctx.composer.resizeComposer();
+ scrollTranscript(opts.forceScroll);
+ postCurrentPaneState();
+ }
-function lastTextNode(el: Node): Text | null {
- for (let i = el.childNodes.length - 1; i >= 0; i--) {
- const child = el.childNodes[i]!;
- if (child.nodeType === Node.TEXT_NODE && /\S/u.test(child.textContent ?? "")) return child as Text;
- const deep = lastTextNode(child);
- if (deep) return deep;
+ function decorateStreamingTail(): void {
+ const blocks = chatState.host?.querySelectorAll<HTMLElement>(".streaming-text.live-stream markdown-block");
+ const block = blocks?.length ? blocks[blocks.length - 1] : undefined;
+ if (!block) {
+ revealedTailLen = 0;
+ return;
+ }
+ if (reduceMotion.matches) return;
+ const fullLen = (block.textContent ?? "").replace(/\s+$/u, "").length;
+ const grown = fullLen - revealedTailLen;
+ revealedTailLen = fullLen;
+ if (grown <= 0 || grown > 240) return;
+ const last = lastTextNode(block);
+ if (!last || !last.textContent) return;
+ const visibleEnd = last.textContent.replace(/\s+$/u, "").length;
+ const n = Math.min(grown, visibleEnd);
+ if (n <= 0) return;
+ const tail = last.splitText(visibleEnd - n);
+ if (tail.textContent && tail.textContent.length > n) tail.splitText(n);
+ const parent = tail.parentNode;
+ if (!parent) return;
+ const span = document.createElement("span");
+ span.className = "tok-in";
+ parent.insertBefore(span, tail);
+ span.appendChild(tail);
}
- return null;
-}
-function contextBanner(): TemplateResult | typeof nothing {
- const label = sharedContextLabel(chatState.scopeId, chatState.contextName);
- if (!label) return nothing;
- const glyph = chatState.scopeId?.startsWith("group:") ? Users : Hash;
- return html`<div
- class="context-banner"
- title="This chat runs in the ${label} context — the agent works with that context's files and memory, separate from your personal context."
- >
- ${icon(glyph, 13)}<span><strong>${label}</strong> context</span>
- </div>`;
-}
+ function lastTextNode(el: Node): Text | null {
+ for (let i = el.childNodes.length - 1; i >= 0; i--) {
+ const child = el.childNodes[i]!;
+ if (child.nodeType === Node.TEXT_NODE && /\S/u.test(child.textContent ?? "")) return child as Text;
+ const deep = lastTextNode(child);
+ if (deep) return deep;
+ }
+ return null;
+ }
-function chatHeader(title: string | TemplateResult, detail: string, readOnly: boolean): TemplateResult {
- return html`
- <header class="chat-topbar">
- <div class="chat-heading">
- <div class="chat-title">${title}</div>
- <div class="chat-subtitle">${readOnly ? "Read-only" : detail}</div>
- </div>
- <div class="topbar-actions">
- ${
- chatState.sessionId && can("admin")
- ? html`<a
- class="icon-btn subtle"
- title="View session log (admin)"
- href=${adminSessionLogUrl(chatState.sessionId, chatState.scopeId ?? `org:${appState.me?.org ?? ""}`)}
- target="_blank"
- rel="noreferrer"
- >${icon(ScrollText, 17)}</a
- >`
- : nothing
- }
- <button
- class="icon-btn subtle"
- title="Refresh conversations"
- @click=${() => void refreshSessions({ refreshContexts: true })}
- >
- ${icon(RefreshCw, 17)}
- </button>
- </div>
- </header>
- `;
-}
-
-function visibleMessages(agent: Agent): AgentMessage[] {
- const out = [...agent.state.messages];
- if (agent.state.streamingMessage) out.push(agent.state.streamingMessage);
- return out;
-}
-
-interface SettledRowKey {
- index: number;
- activity: WorkBlock["activity"] | undefined;
- status: WorkBlock["status"] | undefined;
- stale: boolean | undefined;
- deliveredFiles: unknown;
- stopReason: unknown;
- errorMessage: unknown;
- approvalDecision: unknown;
- forkable: boolean;
- tpl: TemplateResult | typeof nothing;
-}
-const settledRowCache = new WeakMap<object, SettledRowKey>();
-
-function settledChatMessage(
- message: AgentMessage,
- index: number,
- isStreaming: boolean,
-): TemplateResult | typeof nothing {
- const msg = message as AssistantWork & { stopReason?: string; errorMessage?: string; approvalDecision?: string };
- const work = msg.work;
- const cacheable =
- !isStreaming &&
- (!work || ((work.status === "complete" || work.status === "failed") && !work.pendingApprovals?.length));
- if (!cacheable) return chatMessage(message, index, isStreaming);
- const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
- const hit = settledRowCache.get(message as object);
- if (
- hit &&
- hit.index === index &&
- hit.activity === work?.activity &&
- hit.status === work?.status &&
- hit.stale === work?.stale &&
- hit.deliveredFiles === msg.deliveredFiles &&
- hit.stopReason === msg.stopReason &&
- hit.errorMessage === msg.errorMessage &&
- hit.approvalDecision === msg.approvalDecision &&
- hit.forkable === forkable
- ) {
- return hit.tpl;
- }
- const tpl = chatMessage(message, index, isStreaming);
- settledRowCache.set(message as object, {
- index,
- activity: work?.activity,
- status: work?.status,
- stale: work?.stale,
- deliveredFiles: msg.deliveredFiles,
- stopReason: msg.stopReason,
- errorMessage: msg.errorMessage,
- approvalDecision: msg.approvalDecision,
- forkable,
- tpl,
- });
- return tpl;
-}
+ function contextBanner(): TemplateResult | typeof nothing {
+ const label = sharedContextLabel(chatState.scopeId, chatState.contextName);
+ if (!label) return nothing;
+ const glyph = chatState.scopeId?.startsWith("group:") ? Users : Hash;
+ return html`<div
+ class="context-banner"
+ title="This chat runs in the ${label} context — the agent works with that context's files and memory, separate from your personal context."
+ >
+ ${icon(glyph, 13)}<span><strong>${label}</strong> context</span>
+ </div>`;
+ }
-function chatMessage(message: AgentMessage, index: number, isStreaming = false): TemplateResult | typeof nothing {
- if ((message as { opener?: boolean }).opener) return nothing;
- const role = (message as { role?: string }).role;
- if (role === "user" || role === "user-with-attachments") {
- const attachments = ((message as UserMessageWithAttachments).attachments ?? []) as UserAttachmentView[];
- const steered = Boolean((message as { steered?: boolean }).steered);
+ function chatHeader(title: string | TemplateResult, detail: string, readOnly: boolean): TemplateResult {
return html`
- <article class="message-row user-row ${steered ? "steered-row" : ""}" data-index=${index}>
- ${steered ? html`<div class="steer-label">↪ steered the running task</div>` : nothing}
- <div class="message-bubble user-bubble">
- ${markdown(messageText(message))}
- ${attachments.length ? html`<div class="message-files">${attachments.map(userAttachmentBadge)}</div>` : nothing}
+ <header class="chat-topbar">
+ <div class="chat-heading">
+ <div class="chat-title">${title}</div>
+ <div class="chat-subtitle">${readOnly ? "Read-only" : detail}</div>
</div>
- ${messageMeta(message, index)}
- </article>
- `;
- }
- if (role === "assistant") {
- const msg = message as AssistantMessage;
- const work = isStreaming ? null : (msg as AssistantWork).work;
- const text = messageText(msg).trim();
- const hasText = Boolean(text);
- const showWork = shouldShowApprovalWork(msg, work, text) && shouldShowWork(work, hasText);
- const deliveredFiles = (msg as AssistantWork).deliveredFiles;
- const hasVisibleContent =
- showWork ||
- hasText ||
- Boolean(deliveredFiles?.length) ||
- msg.content.some((chunk) => chunk.type === "thinking" && chunk.thinking.trim());
- if (!hasVisibleContent && msg.stopReason !== "error" && msg.stopReason !== "aborted") return nothing;
- return html`
- <article class="message-row assistant-row ${isStreaming ? "streaming" : ""}" data-index=${index}>
- <div class="assistant-body">
- ${showWork ? workBlock(work, isStreaming) : nothing} ${assistantContent(msg, isStreaming, showWork)}
- ${assistantFileList(deliveredFiles)}
- ${msg.stopReason === "error" && msg.errorMessage ? html`<div class="composer-error inline">${msg.errorMessage}</div>` : nothing}
- ${msg.stopReason === "aborted" ? html`<div class="stopped-note">${icon(Ban, 13)}<span>Stopped</span></div>` : nothing}
- ${isStreaming ? nothing : messageMeta(msg, index)}
+ <div class="topbar-actions">
+ ${
+ chatState.sessionId && can("admin")
+ ? html`<a
+ class="icon-btn subtle"
+ title="View session log (admin)"
+ href=${adminSessionLogUrl(chatState.sessionId, chatState.scopeId ?? `org:${appState.me?.org ?? ""}`)}
+ target="_blank"
+ rel="noreferrer"
+ >${icon(ScrollText, 17)}</a
+ >`
+ : nothing
+ }
+ <button
+ class="icon-btn subtle"
+ title="Refresh conversations"
+ @click=${() => void refreshSessions({ refreshContexts: true })}
+ >
+ ${icon(RefreshCw, 17)}
+ </button>
</div>
- </article>
+ </header>
`;
}
- return nothing;
-}
-function messageMeta(message: AgentMessage, index: number): TemplateResult | typeof nothing {
- const text = messageText(message).trim();
- const ts = (message as { timestamp?: number }).timestamp;
- if (!text && ts === undefined) return nothing;
- const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
- return html`
- <div class="message-meta">
- ${ts !== undefined ? html`<span class="message-time">${formatClock(ts)}</span>` : nothing}
- ${
- text
- ? html`<button
- class="msg-copy"
- type="button"
- title="Copy"
- aria-label="Copy message"
- @click=${(e: Event) => void copyMessage(text, e.currentTarget as HTMLButtonElement)}
- >
- ${icon(Copy, 13)}
- </button>`
- : nothing
- }
- ${
- forkable
- ? html`<button
- class="msg-copy msg-fork"
- type="button"
- title="Fork conversation from here"
- aria-label="Fork conversation from here"
- @click=${() => void forkFromMessage(index)}
- >
- ${icon(GitFork, 13)}
- </button>`
- : nothing
- }
- </div>
- `;
-}
+ function visibleMessages(agent: Agent): AgentMessage[] {
+ const out = [...agent.state.messages];
+ if (agent.state.streamingMessage) out.push(agent.state.streamingMessage);
+ return out;
+ }
-async function forkFromMessage(index: number): Promise<void> {
- const agent = chatState.agent;
- const sessionId = chatState.sessionId;
- const sourceThreadRef = chatState.threadRef;
- if (!agent || !sessionId) return;
- const messages = agent.state.messages as Array<{ role?: string }>;
- const target = messages[index];
- if (!target) return;
- const isUser = target.role === "user" || target.role === "user-with-attachments";
- let userOrdinal = 0;
- for (let i = 0; i <= index; i++) {
- const role = messages[i]?.role;
- if (role === "user" || role === "user-with-attachments") userOrdinal++;
- }
- try {
- const { entries } = await api<{ entries: SessionEntry[] }>(`/api/sessions/${encodeURIComponent(sessionId)}`);
- const anchor = chatState.transcriptAnchorSeq;
- if (anchor !== null) userOrdinal += userMessagesBefore(entries ?? [], anchor);
- const upToSeq = forkCutSeq(entries ?? [], userOrdinal, isUser);
- const forked = await forkSession(sessionId, upToSeq);
- carryModelPick(sourceThreadRef, forked.session.threadRef);
- mountContinuable(
- forked.session.threadRef,
- forked.session.id,
- forked.session.scopeId,
- entriesToMessages(forked.entries ?? [], transcriptModel()),
- forked.session.channelName ?? null,
- );
- await refreshSessions({ silent: true });
- renderList();
- } catch (err) {
- composerState.error = errMessage(err, "Could not fork the conversation.");
- drawActiveChat();
+ function settledChatMessage(
+ message: AgentMessage,
+ index: number,
+ isStreaming: boolean,
+ ): TemplateResult | typeof nothing {
+ const msg = message as AssistantWork & { stopReason?: string; errorMessage?: string; approvalDecision?: string };
+ const work = msg.work;
+ const cacheable =
+ !isStreaming &&
+ (!work || ((work.status === "complete" || work.status === "failed") && !work.pendingApprovals?.length));
+ if (!cacheable) return chatMessage(message, index, isStreaming);
+ const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
+ const hit = settledRowCache.get(message as object);
+ if (
+ hit &&
+ hit.index === index &&
+ hit.activity === work?.activity &&
+ hit.status === work?.status &&
+ hit.stale === work?.stale &&
+ hit.deliveredFiles === msg.deliveredFiles &&
+ hit.stopReason === msg.stopReason &&
+ hit.errorMessage === msg.errorMessage &&
+ hit.approvalDecision === msg.approvalDecision &&
+ hit.forkable === forkable
+ ) {
+ return hit.tpl;
+ }
+ const tpl = chatMessage(message, index, isStreaming);
+ settledRowCache.set(message as object, {
+ index,
+ activity: work?.activity,
+ status: work?.status,
+ stale: work?.stale,
+ deliveredFiles: msg.deliveredFiles,
+ stopReason: msg.stopReason,
+ errorMessage: msg.errorMessage,
+ approvalDecision: msg.approvalDecision,
+ forkable,
+ tpl,
+ });
+ return tpl;
}
-}
-function formatClock(ms: number): string {
- try {
- return new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
- } catch {
- return "";
+ function chatMessage(message: AgentMessage, index: number, isStreaming = false): TemplateResult | typeof nothing {
+ if ((message as { opener?: boolean }).opener) return nothing;
+ const role = (message as { role?: string }).role;
+ if (role === "user" || role === "user-with-attachments") {
+ const attachments = ((message as UserMessageWithAttachments).attachments ?? []) as UserAttachmentView[];
+ const steered = Boolean((message as { steered?: boolean }).steered);
+ return html`
+ <article class="message-row user-row ${steered ? "steered-row" : ""}" data-index=${index}>
+ ${steered ? html`<div class="steer-label">↪ steered the running task</div>` : nothing}
+ <div class="message-bubble user-bubble">
+ ${markdown(messageText(message))}
+ ${attachments.length ? html`<div class="message-files">${attachments.map(userAttachmentBadge)}</div>` : nothing}
+ </div>
+ ${messageMeta(message, index)}
+ </article>
+ `;
+ }
+ if (role === "assistant") {
+ const msg = message as AssistantMessage;
+ const work = isStreaming ? null : (msg as AssistantWork).work;
+ const text = messageText(msg).trim();
+ const hasText = Boolean(text);
+ const showWork = shouldShowApprovalWork(msg, work, text) && shouldShowWork(work, hasText);
+ const deliveredFiles = (msg as AssistantWork).deliveredFiles;
+ const hasVisibleContent =
+ showWork ||
+ hasText ||
+ Boolean(deliveredFiles?.length) ||
+ msg.content.some((chunk) => chunk.type === "thinking" && chunk.thinking.trim());
+ if (!hasVisibleContent && msg.stopReason !== "error" && msg.stopReason !== "aborted") return nothing;
+ return html`
+ <article class="message-row assistant-row ${isStreaming ? "streaming" : ""}" data-index=${index}>
+ <div class="assistant-body">
+ ${showWork ? workBlock(work, isStreaming) : nothing} ${assistantContent(msg, isStreaming, showWork)}
+ ${assistantFileList(deliveredFiles)}
+ ${msg.stopReason === "error" && msg.errorMessage ? html`<div class="composer-error inline">${msg.errorMessage}</div>` : nothing}
+ ${msg.stopReason === "aborted" ? html`<div class="stopped-note">${icon(Ban, 13)}<span>Stopped</span></div>` : nothing}
+ ${isStreaming ? nothing : messageMeta(msg, index)}
+ </div>
+ </article>
+ `;
+ }
+ return nothing;
}
-}
-async function copyMessage(text: string, btn: HTMLButtonElement): Promise<void> {
- try {
- await navigator.clipboard.writeText(text);
- } catch {
- return;
- }
- btn.classList.add("copied");
- btn.replaceChildren(icon(Check, 13));
- setTimeout(() => {
- if (!btn.isConnected) return;
- btn.classList.remove("copied");
- btn.replaceChildren(icon(Copy, 13));
- }, 1200);
-}
+ function messageMeta(message: AgentMessage, index: number): TemplateResult | typeof nothing {
+ const text = messageText(message).trim();
+ const ts = (message as { timestamp?: number }).timestamp;
+ if (!text && ts === undefined) return nothing;
+ const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
+ return html`
+ <div class="message-meta">
+ ${ts !== undefined ? html`<span class="message-time">${formatClock(ts)}</span>` : nothing}
+ ${
+ text
+ ? html`<button
+ class="msg-copy"
+ type="button"
+ title="Copy"
+ aria-label="Copy message"
+ @click=${(e: Event) => void copyMessage(text, e.currentTarget as HTMLButtonElement)}
+ >
+ ${icon(Copy, 13)}
+ </button>`
+ : nothing
+ }
+ ${
+ forkable
+ ? html`<button
+ class="msg-copy msg-fork"
+ type="button"
+ title="Fork conversation from here"
+ aria-label="Fork conversation from here"
+ @click=${() => void forkFromMessage(index)}
+ >
+ ${icon(GitFork, 13)}
+ </button>`
+ : nothing
+ }
+ </div>
+ `;
+ }
-const connectedConnectors = new Set<string>();
+ async function forkFromMessage(index: number): Promise<void> {
+ const agent = chatState.agent;
+ const sessionId = chatState.sessionId;
+ const sourceThreadRef = chatState.threadRef;
+ if (!agent || !sessionId) return;
+ const messages = agent.state.messages as Array<{ role?: string }>;
+ const target = messages[index];
+ if (!target) return;
+ const isUser = target.role === "user" || target.role === "user-with-attachments";
+ let userOrdinal = 0;
+ for (let i = 0; i <= index; i++) {
+ const role = messages[i]?.role;
+ if (role === "user" || role === "user-with-attachments") userOrdinal++;
+ }
+ try {
+ const { entries } = await api<{ entries: SessionEntry[] }>(`/api/sessions/${encodeURIComponent(sessionId)}`);
+ const anchor = chatState.transcriptAnchorSeq;
+ if (anchor !== null) userOrdinal += userMessagesBefore(entries ?? [], anchor);
+ const upToSeq = forkCutSeq(entries ?? [], userOrdinal, isUser);
+ const forked = await forkSession(sessionId, upToSeq);
+ ctx.composer.carryModelPick(sourceThreadRef, forked.session.threadRef);
+ mountContinuable(
+ forked.session.threadRef,
+ forked.session.id,
+ forked.session.scopeId,
+ entriesToMessages(forked.entries ?? [], transcriptModel()),
+ forked.session.channelName ?? null,
+ );
+ await refreshSessions({ silent: true });
+ renderList();
+ } catch (err) {
+ ctx.composer.state.error = errMessage(err, "Could not fork the conversation.");
+ drawActiveChat();
+ }
+ }
-export function markConnectorConnected(provider: string): void {
- if (!provider) return;
- connectedConnectors.add(provider);
- if (chatState.agent) drawActiveChat();
-}
+ function formatClock(ms: number): string {
+ try {
+ return new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
+ } catch {
+ return "";
+ }
+ }
-function withReturnTo(url: string): string {
- const returnTo = deepLinkPath(UI_BASE, "chats", chatState.sessionId);
- const sep = url.includes("?") ? "&" : "?";
- return `${url}${sep}returnTo=${encodeURIComponent(returnTo)}`;
-}
+ async function copyMessage(text: string, btn: HTMLButtonElement): Promise<void> {
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ return;
+ }
+ btn.classList.add("copied");
+ btn.replaceChildren(icon(Check, 13));
+ setTimeout(() => {
+ if (!btn.isConnected) return;
+ btn.classList.remove("copied");
+ btn.replaceChildren(icon(Copy, 13));
+ }, 1200);
+ }
-function connectorWidget(link: ConnectorLink): TemplateResult {
- const name =
- CONNECTOR_NAMES[link.provider] ??
- (link.provider ? link.provider[0]!.toUpperCase() + link.provider.slice(1) : "your account");
- if (link.provider && connectedConnectors.has(link.provider)) {
- return html`<div class="connector-widget connected" role="status">
- <span class="connector-widget-icon">${icon(Check, 18)}</span>
+ function withReturnTo(url: string): string {
+ const returnTo = deepLinkPath(UI_BASE, "chats", chatState.sessionId);
+ const sep = url.includes("?") ? "&" : "?";
+ return `${url}${sep}returnTo=${encodeURIComponent(returnTo)}`;
+ }
+
+ function connectorWidget(link: ConnectorLink): TemplateResult {
+ const name =
+ CONNECTOR_NAMES[link.provider] ??
+ (link.provider ? link.provider[0]!.toUpperCase() + link.provider.slice(1) : "your account");
+ if (link.provider && connectedConnectors.has(link.provider)) {
+ return html`<div class="connector-widget connected" role="status">
+ <span class="connector-widget-icon">${icon(Check, 18)}</span>
+ <span class="connector-widget-text"
+ ><strong>Connected ${name}</strong><small>Authorized — its tools work here now</small></span
+ >
+ </div>`;
+ }
+ return html`<a class="connector-widget" href=${withReturnTo(link.url)} target="_blank" rel="noreferrer">
+ <span class="connector-widget-icon">${icon(Plug, 18)}</span>
<span class="connector-widget-text"
- ><strong>Connected ${name}</strong><small>Authorized — its tools work here now</small></span
+ ><strong>Connect ${name}</strong><small>Authorize access in a new tab</small></span
>
- </div>`;
+ ${icon(ChevronRight, 16)}
+ </a>`;
}
- return html`<a class="connector-widget" href=${withReturnTo(link.url)} target="_blank" rel="noreferrer">
- <span class="connector-widget-icon">${icon(Plug, 18)}</span>
- <span class="connector-widget-text"
- ><strong>Connect ${name}</strong><small>Authorize access in a new tab</small></span
- >
- ${icon(ChevronRight, 16)}
- </a>`;
-}
-function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {
- const parts: TemplateResult[] = [];
- for (const chunk of message.content) {
- if (chunk.type === "text" && chunk.text.trim()) {
- const links = connectorLinksIn(chunk.text, location.origin);
- const body = links.length ? stripConnectorLinks(chunk.text) : chunk.text;
- if (body.trim())
+ function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {
+ const parts: TemplateResult[] = [];
+ for (const chunk of message.content) {
+ if (chunk.type === "text" && chunk.text.trim()) {
+ const links = connectorLinksIn(chunk.text, location.origin);
+ const body = links.length ? stripConnectorLinks(chunk.text) : chunk.text;
+ if (body.trim())
+ parts.push(
+ html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}">
+ ${isStreaming ? streamingMarkdown(body) : markdown(body)}
+ </div>`,
+ );
+ for (const link of links) parts.push(connectorWidget(link));
+ }
+ if (chunk.type === "thinking" && chunk.thinking.trim()) {
parts.push(
- html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}">
- ${isStreaming ? streamingMarkdown(body) : markdown(body)}
- </div>`,
+ html`<details class="thinking">
+ <summary>${sheenLabel("Thinking", isStreaming)}</summary>
+ ${markdown(chunk.thinking)}
+ </details>`,
);
- for (const link of links) parts.push(connectorWidget(link));
- }
- if (chunk.type === "thinking" && chunk.thinking.trim()) {
- parts.push(
- html`<details class="thinking">
- <summary>${sheenLabel("Thinking", isStreaming)}</summary>
- ${markdown(chunk.thinking)}
- </details>`,
- );
+ }
}
+ if (parts.length === 0 && message.stopReason !== "error" && message.stopReason !== "aborted" && !hasWork)
+ parts.push(typingRow());
+ return parts;
}
- if (parts.length === 0 && message.stopReason !== "error" && message.stopReason !== "aborted" && !hasWork)
- parts.push(typingRow());
- return parts;
-}
-function assistantFileList(files: DeliveredFile[] | undefined): TemplateResult | typeof nothing {
- if (!files?.length) return nothing;
- return html`<div class="message-files">${files.map((f) => deliveredFileBadge(f))}</div>`;
-}
+ function assistantFileList(files: DeliveredFile[] | undefined): TemplateResult | typeof nothing {
+ if (!files?.length) return nothing;
+ return html`<div class="message-files">${files.map((f) => deliveredFileBadge(f))}</div>`;
+ }
-function markdown(text: string): TemplateResult {
- return html`<markdown-block .content=${escapeLoneDollars(text)}></markdown-block>`;
-}
+ function markdown(text: string): TemplateResult {
+ return html`<markdown-block .content=${escapeLoneDollars(text)}></markdown-block>`;
+ }
-let escapedSegs: string[] = [];
-let escapedSrc: string[] = [];
-function streamingMarkdown(text: string): TemplateResult {
- const { segments, tail } = splitStreamingMarkdown(text);
- if (segments.length < escapedSrc.length) {
- escapedSrc = [];
- escapedSegs = [];
- }
- for (let i = 0; i < segments.length; i++) {
- const seg = segments[i] ?? "";
- if (escapedSrc[i] !== seg) {
- escapedSrc[i] = seg;
- escapedSegs[i] = escapeLoneDollars(seg);
+ let escapedSegs: string[] = [];
+ let escapedSrc: string[] = [];
+ function streamingMarkdown(text: string): TemplateResult {
+ const { segments, tail } = splitStreamingMarkdown(text);
+ if (segments.length < escapedSrc.length) {
+ escapedSrc = [];
+ escapedSegs = [];
}
+ for (let i = 0; i < segments.length; i++) {
+ const seg = segments[i] ?? "";
+ if (escapedSrc[i] !== seg) {
+ escapedSrc[i] = seg;
+ escapedSegs[i] = escapeLoneDollars(seg);
+ }
+ }
+ escapedSrc.length = segments.length;
+ escapedSegs.length = segments.length;
+ return html`${escapedSegs.map((seg) => html`<markdown-block .content=${seg}></markdown-block>`)}<markdown-block
+ class="stream-tail"
+ .content=${escapeLoneDollars(tail)}
+ ></markdown-block>`;
}
- escapedSrc.length = segments.length;
- escapedSegs.length = segments.length;
- return html`${escapedSegs.map((seg) => html`<markdown-block .content=${seg}></markdown-block>`)}<markdown-block
- class="stream-tail"
- .content=${escapeLoneDollars(tail)}
- ></markdown-block>`;
-}
-function messageText(message: AgentMessage): string {
- const content = (message as { content?: unknown }).content;
- if (typeof content === "string") return content;
- if (Array.isArray(content)) {
- return content
- .filter((c): c is TextContent => Boolean(c) && typeof c === "object" && (c as { type?: string }).type === "text")
- .map((c) => c.text ?? "")
- .join("\n");
+ function messageText(message: AgentMessage): string {
+ const content = (message as { content?: unknown }).content;
+ if (typeof content === "string") return content;
+ if (Array.isArray(content)) {
+ return content
+ .filter(
+ (c): c is TextContent => Boolean(c) && typeof c === "object" && (c as { type?: string }).type === "text",
+ )
+ .map((c) => c.text ?? "")
+ .join("\n");
+ }
+ return "";
}
- return "";
-}
-function typingRow(): TemplateResult {
- return html`<div class="thinking-placeholder">${sheenLabel("Thinking", true)}</div>`;
-}
+ function typingRow(): TemplateResult {
+ return html`<div class="thinking-placeholder">${sheenLabel("Thinking", true)}</div>`;
+ }
-function syncWorkTicker(): void {
- const active = chatState.liveWork?.status === "working" && !chatState.liveWork.stale;
- if (active && !workTicker) {
- workTicker = setInterval(() => drawActiveChat(), 1000);
- } else if (!active && workTicker) {
- clearInterval(workTicker);
- workTicker = null;
+ function syncWorkTicker(): void {
+ const active = chatState.liveWork?.status === "working" && !chatState.liveWork.stale;
+ if (active && !workTicker) {
+ workTicker = setInterval(() => drawActiveChat(), 1000);
+ } else if (!active && workTicker) {
+ clearInterval(workTicker);
+ workTicker = null;
+ }
}
-}
-function clearLiveWork(): void {
- chatState.liveWork = null;
- chatState.pendingSend = null;
- syncWorkTicker();
-}
+ function clearLiveWork(): void {
+ chatState.liveWork = null;
+ chatState.pendingSend = null;
+ syncWorkTicker();
+ }
-function shouldShowWork(work: WorkBlock | null | undefined, hasText: boolean): work is WorkBlock {
- if (!work) return false;
- if (work.activity.length > 0) return true;
- if (work.pendingApprovals?.length) return true;
- return work.status === "thinking" && !hasText;
-}
+ function shouldShowWork(work: WorkBlock | null | undefined, hasText: boolean): work is WorkBlock {
+ if (!work) return false;
+ if (work.activity.length > 0) return true;
+ if (work.pendingApprovals?.length) return true;
+ return work.status === "thinking" && !hasText;
+ }
-function shouldShowApprovalWork(message: AssistantMessage, work: WorkBlock | null | undefined, text: string): boolean {
- if ((message as AssistantWork & { approvalDecision?: "denied" }).approvalDecision === "denied") return false;
- if (text === "Denied." && work?.activity.some((a) => a.type === "tool_call" || a.type === "approval_request"))
- return false;
- return true;
-}
+ function shouldShowApprovalWork(
+ message: AssistantMessage,
+ work: WorkBlock | null | undefined,
+ text: string,
+ ): boolean {
+ if ((message as AssistantWork & { approvalDecision?: "denied" }).approvalDecision === "denied") return false;
+ if (text === "Denied." && work?.activity.some((a) => a.type === "tool_call" || a.type === "approval_request"))
+ return false;
+ return true;
+ }
-let readonlyRedraw: (() => void) | null = null;
-
-const bgPanel = {
- requested: null as { sessionId: string | null; threadRef: string | null } | null,
- open: false,
- loading: false,
- error: "",
- detail: null as SessionBackgroundView | null,
- openJob: null as string | null,
- output: new Map<string, { text: string; cursor: number; state: "running" | "exited"; exitCode?: number }>(),
- timer: null as ReturnType<typeof setInterval> | null,
- fetchSeq: 0,
- epoch: 0,
-};
-
-export function requestBackgroundPanel(sessionId: string | null, threadRef: string | null): void {
- const mounted = sessionId ? sessionId === chatState.sessionId : threadRef === chatState.threadRef;
- if (mounted) {
- openBackgroundPanel();
- return;
- }
- bgPanel.requested = { sessionId, threadRef };
-}
+ let readonlyRedraw: (() => void) | null = null;
+
+ const bgPanel = {
+ requested: null as { sessionId: string | null; threadRef: string | null } | null,
+ open: false,
+ loading: false,
+ error: "",
+ detail: null as SessionBackgroundView | null,
+ openJob: null as string | null,
+ output: new Map<string, { text: string; cursor: number; state: "running" | "exited"; exitCode?: number }>(),
+ timer: null as ReturnType<typeof setInterval> | null,
+ fetchSeq: 0,
+ epoch: 0,
+ };
-function resetBackgroundPanel(): void {
- if (bgPanel.timer) clearInterval(bgPanel.timer);
- bgPanel.timer = null;
- bgPanel.open = false;
- bgPanel.loading = false;
- bgPanel.error = "";
- bgPanel.detail = null;
- bgPanel.openJob = null;
- bgPanel.output.clear();
- bgPanel.fetchSeq++;
- bgPanel.epoch++;
- readonlyRedraw = null;
-}
+ function requestBackgroundPanel(sessionId: string | null, threadRef: string | null): void {
+ const mounted = sessionId ? sessionId === chatState.sessionId : threadRef === chatState.threadRef;
+ if (mounted) {
+ openBackgroundPanel();
+ return;
+ }
+ bgPanel.requested = { sessionId, threadRef };
+ }
-function consumeBackgroundPanelRequest(): void {
- const req = bgPanel.requested;
- bgPanel.requested = null;
- if (!req) return;
- const matches = req.sessionId ? req.sessionId === chatState.sessionId : req.threadRef === chatState.threadRef;
- if (matches) openBackgroundPanel();
-}
+ function resetBackgroundPanel(): void {
+ if (bgPanel.timer) clearInterval(bgPanel.timer);
+ bgPanel.timer = null;
+ bgPanel.open = false;
+ bgPanel.loading = false;
+ bgPanel.error = "";
+ bgPanel.detail = null;
+ bgPanel.openJob = null;
+ bgPanel.output.clear();
+ bgPanel.fetchSeq++;
+ bgPanel.epoch++;
+ readonlyRedraw = null;
+ }
-function openBackgroundPanel(): void {
- if (bgPanel.open) return;
- bgPanel.open = true;
- void refreshBackgroundDetail();
- bgPanel.timer = setInterval(() => void backgroundPanelTick(), 2_500);
- redrawBackgroundPanel();
-}
+ function consumeBackgroundPanelRequest(): void {
+ const req = bgPanel.requested;
+ bgPanel.requested = null;
+ if (!req) return;
+ const matches = req.sessionId ? req.sessionId === chatState.sessionId : req.threadRef === chatState.threadRef;
+ if (matches) openBackgroundPanel();
+ }
-function closeBackgroundPanel(): void {
- if (bgPanel.timer) clearInterval(bgPanel.timer);
- bgPanel.timer = null;
- bgPanel.open = false;
- bgPanel.openJob = null;
- redrawBackgroundPanel();
-}
+ function openBackgroundPanel(): void {
+ if (bgPanel.open) return;
+ bgPanel.open = true;
+ void refreshBackgroundDetail();
+ bgPanel.timer = setInterval(() => void backgroundPanelTick(), 2_500);
+ redrawBackgroundPanel();
+ }
-function toggleBackgroundPanel(): void {
- if (bgPanel.open) closeBackgroundPanel();
- else openBackgroundPanel();
-}
+ function closeBackgroundPanel(): void {
+ if (bgPanel.timer) clearInterval(bgPanel.timer);
+ bgPanel.timer = null;
+ bgPanel.open = false;
+ bgPanel.openJob = null;
+ redrawBackgroundPanel();
+ }
-function redrawBackgroundPanel(): void {
- if (readonlyRedraw) readonlyRedraw();
- else drawActiveChat();
-}
+ function toggleBackgroundPanel(): void {
+ if (bgPanel.open) closeBackgroundPanel();
+ else openBackgroundPanel();
+ }
-async function refreshBackgroundDetail(): Promise<void> {
- const id = chatState.sessionId;
- if (!id) {
- bgPanel.detail = { jobs: [], watches: [] };
- return;
- }
- const seq = ++bgPanel.fetchSeq;
- bgPanel.loading = !bgPanel.detail;
- try {
- const d = await api<SessionBackgroundView>(`/api/sessions/${encodeURIComponent(id)}/background`);
- if (seq !== bgPanel.fetchSeq) return;
- bgPanel.detail = d;
- bgPanel.error = "";
- } catch (e) {
- if (seq !== bgPanel.fetchSeq) return;
- bgPanel.error = errMessage(e, "Failed to load background activity.");
- } finally {
- if (seq === bgPanel.fetchSeq) {
- bgPanel.loading = false;
- redrawBackgroundPanel();
+ function redrawBackgroundPanel(): void {
+ if (readonlyRedraw) readonlyRedraw();
+ else drawActiveChat();
+ }
+
+ async function refreshBackgroundDetail(): Promise<void> {
+ const id = chatState.sessionId;
+ if (!id) {
+ bgPanel.detail = { jobs: [], watches: [] };
+ return;
+ }
+ const seq = ++bgPanel.fetchSeq;
+ bgPanel.loading = !bgPanel.detail;
+ try {
+ const d = await api<SessionBackgroundView>(`/api/sessions/${encodeURIComponent(id)}/background`);
+ if (seq !== bgPanel.fetchSeq) return;
+ bgPanel.detail = d;
+ bgPanel.error = "";
+ } catch (e) {
+ if (seq !== bgPanel.fetchSeq) return;
+ bgPanel.error = errMessage(e, "Failed to load background activity.");
+ } finally {
+ if (seq === bgPanel.fetchSeq) {
+ bgPanel.loading = false;
+ redrawBackgroundPanel();
+ }
}
}
-}
-async function backgroundPanelTick(): Promise<void> {
- await refreshBackgroundDetail();
- if (bgPanel.openJob) await pollJobOutput(bgPanel.openJob);
- const d = bgPanel.detail;
- if (d) {
- const row = sessionsState.list.find((r) =>
- chatState.sessionId ? r.id === chatState.sessionId : r.threadRef === chatState.threadRef,
- );
- if (row && ((row.backgroundJobs ?? 0) !== d.jobs.length || (row.watches ?? 0) !== d.watches.length)) {
- await refreshSessions({ silent: true });
- redrawBackgroundPanel();
+ async function backgroundPanelTick(): Promise<void> {
+ await refreshBackgroundDetail();
+ if (bgPanel.openJob) await pollJobOutput(bgPanel.openJob);
+ const d = bgPanel.detail;
+ if (d) {
+ const row = sessionsState.list.find((r) =>
+ chatState.sessionId ? r.id === chatState.sessionId : r.threadRef === chatState.threadRef,
+ );
+ if (row && ((row.backgroundJobs ?? 0) !== d.jobs.length || (row.watches ?? 0) !== d.watches.length)) {
+ await refreshSessions({ silent: true });
+ redrawBackgroundPanel();
+ }
}
}
-}
-function toggleJobOutput(processId: string): void {
- bgPanel.openJob = bgPanel.openJob === processId ? null : processId;
- if (bgPanel.openJob && !bgPanel.output.has(processId)) void pollJobOutput(processId);
- redrawBackgroundPanel();
-}
+ function toggleJobOutput(processId: string): void {
+ bgPanel.openJob = bgPanel.openJob === processId ? null : processId;
+ if (bgPanel.openJob && !bgPanel.output.has(processId)) void pollJobOutput(processId);
+ redrawBackgroundPanel();
+ }
-async function pollJobOutput(processId: string): Promise<void> {
- const id = chatState.sessionId;
- if (!id) return;
- const epoch = bgPanel.epoch;
- const prev = bgPanel.output.get(processId);
- let text = prev?.text ?? "";
- let cursor = prev?.cursor ?? 0;
- let state: "running" | "exited" = prev?.state ?? "running";
- let exitCode = prev?.exitCode;
- try {
- for (let i = 0; i < 8; i++) {
- const read = await api<SessionBackgroundOutput>(
- `/api/sessions/${encodeURIComponent(id)}/background/${encodeURIComponent(processId)}/output?sinceCursor=${cursor}`,
- );
- cursor = read.cursor;
- text = (text + read.chunk).slice(-16_384);
- state = read.state;
- exitCode = read.exitCode;
- if (read.chunk.length < 60_000) break;
+ async function pollJobOutput(processId: string): Promise<void> {
+ const id = chatState.sessionId;
+ if (!id) return;
+ const epoch = bgPanel.epoch;
+ const prev = bgPanel.output.get(processId);
+ let text = prev?.text ?? "";
+ let cursor = prev?.cursor ?? 0;
+ let state: "running" | "exited" = prev?.state ?? "running";
+ let exitCode = prev?.exitCode;
+ try {
+ for (let i = 0; i < 8; i++) {
+ const read = await api<SessionBackgroundOutput>(
+ `/api/sessions/${encodeURIComponent(id)}/background/${encodeURIComponent(processId)}/output?sinceCursor=${cursor}`,
+ );
+ cursor = read.cursor;
+ text = (text + read.chunk).slice(-16_384);
+ state = read.state;
+ exitCode = read.exitCode;
+ if (read.chunk.length < 60_000) break;
+ }
+ if (epoch !== bgPanel.epoch) return;
+ bgPanel.output.set(processId, { text, cursor, state, ...(exitCode !== undefined ? { exitCode } : {}) });
+ } catch (e) {
+ swallow("web-ui: background job output read", e);
}
if (epoch !== bgPanel.epoch) return;
- bgPanel.output.set(processId, { text, cursor, state, ...(exitCode !== undefined ? { exitCode } : {}) });
- } catch (e) {
- swallow("web-ui: background job output read", e);
+ redrawBackgroundPanel();
}
- if (epoch !== bgPanel.epoch) return;
- redrawBackgroundPanel();
-}
-
-function timeLeft(expiresAt: number): string {
- const mins = Math.round((expiresAt - Date.now()) / 60_000);
- if (mins <= 0) return "expiring";
- if (mins < 60) return `${mins}m left`;
- return `${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m left`;
-}
-function backgroundActivityStrip(): TemplateResult | typeof nothing {
- const row = conversationBackground(sessionsState.list, chatState.sessionId, chatState.threadRef);
- const live =
- bgPanel.open && bgPanel.detail ? backgroundLabel(bgPanel.detail.jobs.length, bgPanel.detail.watches.length) : null;
- const label = (live ?? row)?.label;
- if (!label && !bgPanel.open) return nothing;
- return html`
- <section class="bg-activity ${bgPanel.open ? "expanded" : ""}">
- <button
- type="button"
- class="bg-activity-strip"
- aria-expanded=${String(bgPanel.open)}
- title=${bgPanel.open ? "Hide background activity" : "Work continuing on the agent's computer — click to inspect"}
- @click=${toggleBackgroundPanel}
- >
- ${icon(Activity, 13)}<span class="bg-activity-label">${label ?? "Background activity"}</span>
- <span class="bg-activity-toggle">${icon(ChevronRight, 14)}</span>
- </button>
- ${bgPanel.open ? backgroundPanelBody() : nothing}
- </section>
- `;
-}
+ function timeLeft(expiresAt: number): string {
+ const mins = Math.round((expiresAt - Date.now()) / 60_000);
+ if (mins <= 0) return "expiring";
+ if (mins < 60) return `${mins}m left`;
+ return `${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m left`;
+ }
-function backgroundPanelBody(): TemplateResult {
- const d = bgPanel.detail;
- const empty = d && d.jobs.length === 0 && d.watches.length === 0;
- return html`<div class="bg-panel" role="region" aria-label="Background activity">
- ${bgPanel.error ? html`<div class="bg-panel-note">${bgPanel.error}</div>` : nothing}
- ${!d && bgPanel.loading ? html`<div class="bg-panel-note">Loading…</div>` : nothing}
- ${empty && !bgPanel.error ? html`<div class="bg-panel-note">Nothing running here anymore.</div>` : nothing}
- ${d ? d.jobs.map((j) => backgroundJobRow(j)) : nothing} ${d ? d.watches.map((w) => backgroundWatchRow(w)) : nothing}
- </div>`;
-}
+ function backgroundActivityStrip(): TemplateResult | typeof nothing {
+ const row = conversationBackground(sessionsState.list, chatState.sessionId, chatState.threadRef);
+ const live =
+ bgPanel.open && bgPanel.detail
+ ? backgroundLabel(bgPanel.detail.jobs.length, bgPanel.detail.watches.length)
+ : null;
+ const label = (live ?? row)?.label;
+ if (!label && !bgPanel.open) return nothing;
+ return html`
+ <section class="bg-activity ${bgPanel.open ? "expanded" : ""}">
+ <button
+ type="button"
+ class="bg-activity-strip"
+ aria-expanded=${String(bgPanel.open)}
+ title=${bgPanel.open ? "Hide background activity" : "Work continuing on the agent's computer — click to inspect"}
+ @click=${toggleBackgroundPanel}
+ >
+ ${icon(Activity, 13)}<span class="bg-activity-label">${label ?? "Background activity"}</span>
+ <span class="bg-activity-toggle">${icon(ChevronRight, 14)}</span>
+ </button>
+ ${bgPanel.open ? backgroundPanelBody() : nothing}
+ </section>
+ `;
+ }
-function backgroundJobRow(j: SessionBackgroundView["jobs"][number]): TemplateResult {
- const open = bgPanel.openJob === j.processId;
- const out = bgPanel.output.get(j.processId);
- const status =
- out?.state === "exited" ? `exited${out.exitCode !== undefined ? ` (${out.exitCode})` : ""}` : timeLeft(j.expiresAt);
- return html`
- <div class="bg-row ${open ? "open" : ""}">
- <button
- type="button"
- class="bg-row-head"
- aria-expanded=${String(open)}
- title=${open ? "Hide output" : "Show live output"}
- @click=${() => toggleJobOutput(j.processId)}
- >
- ${icon(Terminal, 13)}
- <code class="bg-row-cmd">${j.command}</code>
- <span class="bg-row-meta">started ${relTime(j.startedAt)} · ${status}</span>
- <span class="bg-row-toggle">${icon(ChevronRight, 13)}</span>
- </button>
- ${open ? html`<pre class="bg-row-output">${out ? out.text || "(no output yet)" : "Loading output…"}</pre>` : nothing}
- </div>
- `;
-}
+ function backgroundPanelBody(): TemplateResult {
+ const d = bgPanel.detail;
+ const empty = d && d.jobs.length === 0 && d.watches.length === 0;
+ return html`<div class="bg-panel" role="region" aria-label="Background activity">
+ ${bgPanel.error ? html`<div class="bg-panel-note">${bgPanel.error}</div>` : nothing}
+ ${!d && bgPanel.loading ? html`<div class="bg-panel-note">Loading…</div>` : nothing}
+ ${empty && !bgPanel.error ? html`<div class="bg-panel-note">Nothing running here anymore.</div>` : nothing}
+ ${d ? d.jobs.map((j) => backgroundJobRow(j)) : nothing}
+ ${d ? d.watches.map((w) => backgroundWatchRow(w)) : nothing}
+ </div>`;
+ }
-function backgroundWatchRow(w: SessionBackgroundView["watches"][number]): TemplateResult {
- const what = w.pattern ? `output matching /${w.pattern}/` : "any new output";
- const note = w.instructions?.trim();
- return html`
- <div class="bg-row watch">
- <div class="bg-row-head static">
- ${icon(Radar, 13)}
- <span class="bg-row-cmd">Watch — wakes on ${what}${note ? ` · “${note}”` : ""}</span>
- <span class="bg-row-meta"
- >armed ${relTime(w.createdAt)}${w.lastFiredAt ? ` · last fired ${relTime(w.lastFiredAt)}` : ""} ·
- ${timeLeft(w.expiresAt)}</span
+ function backgroundJobRow(j: SessionBackgroundView["jobs"][number]): TemplateResult {
+ const open = bgPanel.openJob === j.processId;
+ const out = bgPanel.output.get(j.processId);
+ const status =
+ out?.state === "exited"
+ ? `exited${out.exitCode !== undefined ? ` (${out.exitCode})` : ""}`
+ : timeLeft(j.expiresAt);
+ return html`
+ <div class="bg-row ${open ? "open" : ""}">
+ <button
+ type="button"
+ class="bg-row-head"
+ aria-expanded=${String(open)}
+ title=${open ? "Hide output" : "Show live output"}
+ @click=${() => toggleJobOutput(j.processId)}
>
+ ${icon(Terminal, 13)}
+ <code class="bg-row-cmd">${j.command}</code>
+ <span class="bg-row-meta">started ${relTime(j.startedAt)} · ${status}</span>
+ <span class="bg-row-toggle">${icon(ChevronRight, 13)}</span>
+ </button>
+ ${open ? html`<pre class="bg-row-output">${out ? out.text || "(no output yet)" : "Loading output…"}</pre>` : nothing}
</div>
- </div>
- `;
-}
+ `;
+ }
-function liveWorkDock(agent: Agent): TemplateResult | typeof nothing {
- if (!agent.state.isStreaming && chatState.resolvingApprovals.size === 0) return nothing;
- const work = chatState.liveWork ?? { status: "thinking", activity: [] };
- if (work.status !== "thinking" && work.status !== "working") return nothing;
- const summary = liveWorkSummary(work);
- const expandable = Boolean(summary?.detail);
- const expanded = expandable && liveWorkExpanded;
- let title = "";
- if (expandable) title = liveWorkExpanded ? "Show less" : "Show more";
- return html`
- <section class="live-work-dock ${expanded ? "expanded" : ""}" aria-live="polite">
- <button
- type="button"
- class="live-work-line ${expandable ? "" : "static"}"
- ?disabled=${!expandable}
- aria-expanded=${expandable ? String(liveWorkExpanded) : nothing}
- title=${title}
- @click=${toggleLiveWorkExpanded}
- >
- ${summary ? html`<span class="tool-icon">${icon(summary.icon, 15)}</span>` : nothing}
- <span class="live-work-label"
- >${summary ? summary.label : sheenLabel(`Thinking${usedToolsSuffix(work)}`, true)}</span
+ function backgroundWatchRow(w: SessionBackgroundView["watches"][number]): TemplateResult {
+ const what = w.pattern ? `output matching /${w.pattern}/` : "any new output";
+ const note = w.instructions?.trim();
+ return html`
+ <div class="bg-row watch">
+ <div class="bg-row-head static">
+ ${icon(Radar, 13)}
+ <span class="bg-row-cmd">Watch — wakes on ${what}${note ? ` · “${note}”` : ""}</span>
+ <span class="bg-row-meta"
+ >armed ${relTime(w.createdAt)}${w.lastFiredAt ? ` · last fired ${relTime(w.lastFiredAt)}` : ""} ·
+ ${timeLeft(w.expiresAt)}</span
+ >
+ </div>
+ </div>
+ `;
+ }
+
+ function liveWorkDock(agent: Agent): TemplateResult | typeof nothing {
+ if (!agent.state.isStreaming && chatState.resolvingApprovals.size === 0) return nothing;
+ const work = chatState.liveWork ?? { status: "thinking", activity: [] };
+ if (work.status !== "thinking" && work.status !== "working") return nothing;
+ const summary = liveWorkSummary(work);
+ const expandable = Boolean(summary?.detail);
+ const expanded = expandable && liveWorkExpanded;
+ let title = "";
+ if (expandable) title = liveWorkExpanded ? "Show less" : "Show more";
+ return html`
+ <section class="live-work-dock ${expanded ? "expanded" : ""}" aria-live="polite">
+ <button
+ type="button"
+ class="live-work-line ${expandable ? "" : "static"}"
+ ?disabled=${!expandable}
+ aria-expanded=${expandable ? String(liveWorkExpanded) : nothing}
+ title=${title}
+ @click=${toggleLiveWorkExpanded}
>
- ${summary?.detail ? html`<span class="live-work-detail">${summary.detail}</span>` : nothing}
- ${expandable ? html`<span class="live-work-toggle">${icon(ChevronRight, 14)}</span>` : nothing}
- </button>
- </section>
- `;
-}
+ ${summary ? html`<span class="tool-icon">${icon(summary.icon, 15)}</span>` : nothing}
+ <span class="live-work-label"
+ >${summary ? summary.label : sheenLabel(`Thinking${usedToolsSuffix(work)}`, true)}</span
+ >
+ ${summary?.detail ? html`<span class="live-work-detail">${summary.detail}</span>` : nothing}
+ ${expandable ? html`<span class="live-work-toggle">${icon(ChevronRight, 14)}</span>` : nothing}
+ </button>
+ </section>
+ `;
+ }
-function toggleLiveWorkExpanded(): void {
- liveWorkExpanded = !liveWorkExpanded;
- drawActiveChat();
-}
+ function toggleLiveWorkExpanded(): void {
+ liveWorkExpanded = !liveWorkExpanded;
+ drawActiveChat();
+ }
-function liveWorkSummary(work: WorkBlock): { icon: IconNode; label: string; detail: string } | null {
- if (work.stale) {
+ function liveWorkSummary(work: WorkBlock): { icon: IconNode; label: string; detail: string } | null {
+ if (work.stale) {
+ const active = activeToolRow(work);
+ const call = (active?.call?.payload ?? {}) as ToolPayload;
+ const tool = call.tool ?? "";
+ const verb = active ? (TOOL_META[tool] ?? UNKNOWN_TOOL).active : null;
+ return {
+ icon: RefreshCw,
+ label: verb ? `${verb} interrupted — resuming…` : "Interrupted — resuming…",
+ detail: active ? toolDetail(tool, call, (active.result?.payload ?? {}) as ToolPayload) : "",
+ };
+ }
const active = activeToolRow(work);
- const call = (active?.call?.payload ?? {}) as ToolPayload;
- const tool = call.tool ?? "";
- const verb = active ? (TOOL_META[tool] ?? UNKNOWN_TOOL).active : null;
+ return active ? activeToolSummary(active, work) : null;
+ }
+
+ function activeToolRow(work: WorkBlock): ToolRowModel | null {
+ const timeline = buildTimeline(work);
+ for (let i = timeline.length - 1; i >= 0; i--) {
+ const item = timeline[i]!;
+ if (item.kind === "tool" && toolRowKind(item.row, work.status) === "running") return item.row;
+ }
+ return null;
+ }
+
+ function activeToolSummary(row: ToolRowModel, work: WorkBlock): { icon: IconNode; label: string; detail: string } {
+ const call = (row.call?.payload ?? {}) as ToolPayload;
+ const result = (row.result?.payload ?? {}) as ToolPayload;
+ const tool = call.tool ?? result.tool ?? "unknown";
+ const meta = TOOL_META[tool] ?? UNKNOWN_TOOL;
+ const secs = elapsedSeconds(row.call?.createdAt) || workSeconds(work);
return {
- icon: RefreshCw,
- label: verb ? `${verb} interrupted — resuming…` : "Interrupted — resuming…",
- detail: active ? toolDetail(tool, call, (active.result?.payload ?? {}) as ToolPayload) : "",
+ icon: meta.icon,
+ label: secs > 0 ? `${meta.active} for ${secs}s` : meta.active,
+ detail: toolDetail(tool, call, result),
};
}
- const active = activeToolRow(work);
- return active ? activeToolSummary(active, work) : null;
-}
-function activeToolRow(work: WorkBlock): ToolRowModel | null {
- const timeline = buildTimeline(work);
- for (let i = timeline.length - 1; i >= 0; i--) {
- const item = timeline[i]!;
- if (item.kind === "tool" && toolRowKind(item.row, work.status) === "running") return item.row;
+ function elapsedSeconds(startedAt: number | null | undefined): number {
+ if (typeof startedAt !== "number" || startedAt <= 0) return 0;
+ return Math.max(0, Math.round((Date.now() - startedAt) / 1000));
}
- return null;
-}
-function activeToolSummary(row: ToolRowModel, work: WorkBlock): { icon: IconNode; label: string; detail: string } {
- const call = (row.call?.payload ?? {}) as ToolPayload;
- const result = (row.result?.payload ?? {}) as ToolPayload;
- const tool = call.tool ?? result.tool ?? "unknown";
- const meta = TOOL_META[tool] ?? UNKNOWN_TOOL;
- const secs = elapsedSeconds(row.call?.createdAt) || workSeconds(work);
- return {
- icon: meta.icon,
- label: secs > 0 ? `${meta.active} for ${secs}s` : meta.active,
- detail: toolDetail(tool, call, result),
- };
-}
+ function workSeconds(work: WorkBlock): number {
+ if (work.startedAt == null) return 0;
+ const end = work.finishedAt ?? Date.now();
+ return Math.max(0, Math.round((end - work.startedAt) / 1000));
+ }
-function elapsedSeconds(startedAt: number | null | undefined): number {
- if (typeof startedAt !== "number" || startedAt <= 0) return 0;
- return Math.max(0, Math.round((Date.now() - startedAt) / 1000));
-}
+ function usedToolsSuffix(work: WorkBlock): string {
+ const n = work.activity.filter((a) => a.type === "tool_call").length;
+ return n > 0 ? ` (used ${n} tool${n === 1 ? "" : "s"})` : "";
+ }
-function workSeconds(work: WorkBlock): number {
- if (work.startedAt == null) return 0;
- const end = work.finishedAt ?? Date.now();
- return Math.max(0, Math.round((end - work.startedAt) / 1000));
-}
+ function workLabel(work: WorkBlock): string {
+ if (work.stale && (work.status === "thinking" || work.status === "working")) return "Interrupted — resuming…";
+ if (work.status === "thinking") return "Thinking";
+ const secs = workSeconds(work);
+ return work.status === "working" ? `Working for ${secs}s` : `Worked for ${secs}s`;
+ }
-function usedToolsSuffix(work: WorkBlock): string {
- const n = work.activity.filter((a) => a.type === "tool_call").length;
- return n > 0 ? ` (used ${n} tool${n === 1 ? "" : "s"})` : "";
-}
+ function workBlock(work: WorkBlock, isStreaming: boolean): TemplateResult {
+ if (work.status === "thinking" && !work.activity.length) {
+ return html`<div class="work work-thinking">
+ <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>
+ </div>`;
+ }
+ const timeline = buildTimeline(work);
+ const rows = timeline.length
+ ? html`<div class="work-rows">${timeline.map((it) => renderTimelineItem(it, work))}</div>`
+ : nothing;
+ const body = html`<div class="work-divider"></div>
+ ${rows}`;
+ if (isStreaming || work.status === "working" || work.status === "thinking") {
+ return html`<div class="work work-working">
+ <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>
+ ${body}
+ </div>`;
+ }
+ const openFolds = !!work.pendingApprovals?.length;
+ const parts: TemplateResult[] = [];
+ let seg: TimelineItem[] = [];
+ const flushSeg = (): void => {
+ if (!seg.length) return;
+ const items = seg;
+ seg = [];
+ parts.push(
+ html`<details class="work-fold" ?open=${openFolds}>
+ <summary class="work-head">${segmentSummaryLabel(items, work)}${icon(ChevronRight, 14)}</summary>
+ <div class="work-divider"></div>
+ <div class="work-rows">${items.map((it) => renderTimelineItem(it, work))}</div>
+ </details>`,
+ );
+ };
+ for (const it of timeline) {
+ const demoted = it.kind === "text" && (it.activity.payload as { demoted?: boolean } | null)?.demoted === true;
+ if (it.kind === "text" && !demoted) {
+ flushSeg();
+ const text = ((it.activity.payload as { text?: string } | null)?.text ?? "").trim();
+ if (text) parts.push(html`<div class="work-said">${markdown(text)}</div>`);
+ } else {
+ seg.push(it);
+ }
+ }
+ flushSeg();
+ return html`<div class="work work-${work.status}">${parts}</div>`;
+ }
-function workLabel(work: WorkBlock): string {
- if (work.stale && (work.status === "thinking" || work.status === "working")) return "Interrupted — resuming…";
- if (work.status === "thinking") return "Thinking";
- const secs = workSeconds(work);
- return work.status === "working" ? `Working for ${secs}s` : `Worked for ${secs}s`;
-}
+ function segmentSummaryLabel(items: TimelineItem[], work: WorkBlock): string {
+ const tools = items.filter((it) => it.kind === "tool").length;
+ if (tools > 0) return `${tools} tool call${tools === 1 ? "" : "s"}`;
+ const secs = workSeconds(work);
+ return work.status === "failed" ? `Failed after ${secs}s` : `Worked for ${secs}s`;
+ }
-function workBlock(work: WorkBlock, isStreaming: boolean): TemplateResult {
- if (work.status === "thinking" && !work.activity.length) {
- return html`<div class="work work-thinking">
- <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>
- </div>`;
+ function approvalSummaryView(a: PendingApproval, expanded = false): TemplateResult {
+ const summary = firstLine(a.command, 80);
+ const truncated = a.command.includes("\n") || a.command.length > 80;
+ return html`
+ <div class="approval-head">
+ <span class="approval-title">Approval needed</span>
+ ${a.reason ? html`<span class="approval-reason-badge">${a.reason}</span>` : nothing}
+ </div>
+ ${a.summary ? html`<div class="approval-summary-line">${a.summary}</div>` : nothing}
+ ${a.purpose ? html`<div class="approval-why"><span class="approval-why-label">Why</span>${a.purpose}</div>` : nothing}
+ ${
+ expanded
+ ? html`<code class="approval-cmd approval-cmd-full">${a.command}</code>`
+ : html`<code class="approval-summary" title=${a.command}>${summary}</code>`
+ }
+ ${
+ a.matched
+ ? html`<div class="approval-match">
+ <span class="approval-match-label">Triggered by</span
+ ><code class="approval-match-snippet">${a.matched}</code>
+ </div>`
+ : nothing
+ }
+ ${
+ !expanded && truncated
+ ? html`<details class="approval-full">
+ <summary>Show full command</summary>
+ <code class="approval-cmd">${a.command}</code>
+ </details>`
+ : nothing
+ }
+ `;
}
- const timeline = buildTimeline(work);
- const rows = timeline.length
- ? html`<div class="work-rows">
- ${timeline.map((it) => renderTimelineItem(it, work.status, work.stale === true))}
- </div>`
- : nothing;
- const body = html`<div class="work-divider"></div>
- ${rows}`;
- if (isStreaming || work.status === "working" || work.status === "thinking") {
- return html`<div class="work work-working">
- <div class="work-head">${sheenLabel(workLabel(work), isStreaming)}</div>
- ${body}
+
+ function approvalMarker(a: PendingApproval): TemplateResult {
+ return html`<div class="approval-card inline-approval-marker">
+ <div class="approval-text">${approvalSummaryView(a)}</div>
</div>`;
}
- const openFolds = !!work.pendingApprovals?.length;
- const parts: TemplateResult[] = [];
- let seg: TimelineItem[] = [];
- const flushSeg = (): void => {
- if (!seg.length) return;
- const items = seg;
- seg = [];
- parts.push(
- html`<details class="work-fold" ?open=${openFolds}>
- <summary class="work-head">${segmentSummaryLabel(items, work)}${icon(ChevronRight, 14)}</summary>
- <div class="work-divider"></div>
- <div class="work-rows">${items.map((it) => renderTimelineItem(it, work.status, work.stale === true))}</div>
- </details>`,
- );
- };
- for (const it of timeline) {
- const demoted = it.kind === "text" && (it.activity.payload as { demoted?: boolean } | null)?.demoted === true;
- if (it.kind === "text" && !demoted) {
- flushSeg();
- const text = ((it.activity.payload as { text?: string } | null)?.text ?? "").trim();
- if (text) parts.push(html`<div class="work-said">${markdown(text)}</div>`);
- } else {
- seg.push(it);
- }
- }
- flushSeg();
- return html`<div class="work work-${work.status}">${parts}</div>`;
-}
-function segmentSummaryLabel(items: TimelineItem[], work: WorkBlock): string {
- const tools = items.filter((it) => it.kind === "tool").length;
- if (tools > 0) return `${tools} tool call${tools === 1 ? "" : "s"}`;
- const secs = workSeconds(work);
- return work.status === "failed" ? `Failed after ${secs}s` : `Worked for ${secs}s`;
-}
-
-export function approvalSummaryView(a: PendingApproval, expanded = false): TemplateResult {
- const summary = firstLine(a.command, 80);
- const truncated = a.command.includes("\n") || a.command.length > 80;
- return html`
- <div class="approval-head">
- <span class="approval-title">Approval needed</span>
- ${a.reason ? html`<span class="approval-reason-badge">${a.reason}</span>` : nothing}
- </div>
- ${a.summary ? html`<div class="approval-summary-line">${a.summary}</div>` : nothing}
- ${a.purpose ? html`<div class="approval-why"><span class="approval-why-label">Why</span>${a.purpose}</div>` : nothing}
- ${
- expanded
- ? html`<code class="approval-cmd approval-cmd-full">${a.command}</code>`
- : html`<code class="approval-summary" title=${a.command}>${summary}</code>`
- }
- ${
- a.matched
- ? html`<div class="approval-match">
- <span class="approval-match-label">Triggered by</span
- ><code class="approval-match-snippet">${a.matched}</code>
- </div>`
- : nothing
- }
- ${
- !expanded && truncated
- ? html`<details class="approval-full">
- <summary>Show full command</summary>
- <code class="approval-cmd">${a.command}</code>
- </details>`
- : nothing
- }
- `;
-}
-
-function approvalMarker(a: PendingApproval): TemplateResult {
- return html`<div class="approval-card inline-approval-marker">
- <div class="approval-text">${approvalSummaryView(a)}</div>
- </div>`;
-}
+ function sheenLabel(label: string, active: boolean): TemplateResult {
+ return html`<span class="sheen-label ${active ? "thinking-sheen" : ""}" data-sheen=${active ? label : ""}
+ >${label}</span
+ >`;
+ }
-function sheenLabel(label: string, active: boolean): TemplateResult {
- return html`<span class="sheen-label ${active ? "thinking-sheen" : ""}" data-sheen=${active ? label : ""}
- >${label}</span
- >`;
-}
+ function renderTimelineItem(item: TimelineItem, work: WorkBlock): TemplateResult {
+ const status = work.status;
+ const stale = work.stale === true;
+ if (item.kind === "thinking") return thinkingRow(item.activity);
+ if (item.kind === "text") return messageRow(item.activity);
+ if (item.kind === "approval") return approvalMarker(item.approval);
+ return toolRow(item.row, work, status, stale);
+ }
-function renderTimelineItem(item: TimelineItem, status: WorkBlock["status"], stale = false): TemplateResult {
- if (item.kind === "thinking") return thinkingRow(item.activity);
- if (item.kind === "text") return messageRow(item.activity);
- if (item.kind === "approval") return approvalMarker(item.approval);
- return toolRow(item.row, status, stale);
-}
+ function thinkingRow(activity: ToolActivity): TemplateResult {
+ const text = (activity.payload as { thinking?: string } | null)?.thinking ?? "";
+ return html`<div class="thinking">${markdown(text)}</div>`;
+ }
-function thinkingRow(activity: ToolActivity): TemplateResult {
- const text = (activity.payload as { thinking?: string } | null)?.thinking ?? "";
- return html`<div class="thinking">${markdown(text)}</div>`;
-}
+ function messageRow(activity: ToolActivity): TemplateResult {
+ const text = (activity.payload as { text?: string } | null)?.text ?? "";
+ return html`<div class="work-message">${markdown(text)}</div>`;
+ }
-function messageRow(activity: ToolActivity): TemplateResult {
- const text = (activity.payload as { text?: string } | null)?.text ?? "";
- return html`<div class="work-message">${markdown(text)}</div>`;
-}
+ const TOOL_META: Record<string, { icon: IconNode; active: string; done: string; attempted: string }> = {
+ execute: { icon: Terminal, active: "Running command", done: "Ran command", attempted: "Tried command" },
+ read: { icon: FileText, active: "Reading file", done: "Read file", attempted: "Tried reading file" },
+ write: { icon: Pencil, active: "Writing file", done: "Wrote file", attempted: "Tried writing file" },
+ publish: { icon: Rocket, active: "Publishing", done: "Published", attempted: "Tried publishing" },
+ recall: { icon: Brain, active: "Searching memory", done: "Searched memory", attempted: "Tried searching memory" },
+ memory: { icon: Brain, active: "Using memory", done: "Used memory", attempted: "Tried using memory" },
+ history: {
+ icon: ScrollText,
+ active: "Searching history",
+ done: "Searched history",
+ attempted: "Tried searching history",
+ },
+ background: {
+ icon: Terminal,
+ active: "Managing process",
+ done: "Managed process",
+ attempted: "Tried managing process",
+ },
+ };
+ const UNKNOWN_TOOL = { icon: Wrench, active: "Working", done: "Finished step", attempted: "Tried step" };
-const TOOL_META: Record<string, { icon: IconNode; active: string; done: string; attempted: string }> = {
- execute: { icon: Terminal, active: "Running command", done: "Ran command", attempted: "Tried command" },
- read: { icon: FileText, active: "Reading file", done: "Read file", attempted: "Tried reading file" },
- write: { icon: Pencil, active: "Writing file", done: "Wrote file", attempted: "Tried writing file" },
- publish: { icon: Rocket, active: "Publishing", done: "Published", attempted: "Tried publishing" },
- recall: { icon: Brain, active: "Searching memory", done: "Searched memory", attempted: "Tried searching memory" },
- memory: { icon: Brain, active: "Using memory", done: "Used memory", attempted: "Tried using memory" },
- history: {
- icon: ScrollText,
- active: "Searching history",
- done: "Searched history",
- attempted: "Tried searching history",
- },
- background: {
- icon: Terminal,
- active: "Managing process",
- done: "Managed process",
- attempted: "Tried managing process",
- },
-};
-const UNKNOWN_TOOL = { icon: Wrench, active: "Working", done: "Finished step", attempted: "Tried step" };
-
-function firstLine(s: string, max = 72): string {
- const line = s.split("\n")[0] ?? "";
- return line.length > max ? `${line.slice(0, max - 1)}…` : line;
-}
+ function firstLine(s: string, max = 72): string {
+ const line = s.split("\n")[0] ?? "";
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
+ }
-function toolDetail(tool: string, call: ToolPayload, result: ToolPayload): string {
- switch (tool) {
- case "execute":
- return call.command ? firstLine(call.command) : "";
- case "read":
- return call.path ?? result.path ?? "";
- case "write": {
- const path = call.path ?? result.path ?? "";
- const bytes = result.bytes ?? call.bytes;
- return bytes !== undefined ? `${path} · ${formatBytes(bytes)}` : path;
- }
- case "publish":
- return result.url ?? result.name ?? call.name ?? "";
- case "recall":
- case "history": {
- const q = call.query ?? result.query ?? "";
- return result.count !== undefined ? `${q} · ${result.count} result${result.count === 1 ? "" : "s"}` : q;
- }
- case "memory": {
- const action = call.action ?? result.action ?? "";
- const q = call.query ?? result.query ?? "";
- let detail = q;
- if (result.count !== undefined) {
- detail = `${q} · ${result.count} result${result.count === 1 ? "" : "s"}`;
- } else if (result.added !== undefined) {
- detail = `${result.added} saved`;
+ function toolDetail(tool: string, call: ToolPayload, result: ToolPayload): string {
+ switch (tool) {
+ case "execute":
+ return call.command ? firstLine(call.command) : "";
+ case "read":
+ return call.path ?? result.path ?? "";
+ case "write": {
+ const path = call.path ?? result.path ?? "";
+ const bytes = result.bytes ?? call.bytes;
+ return bytes !== undefined ? `${path} · ${formatBytes(bytes)}` : path;
+ }
+ case "publish":
+ return result.url ?? result.name ?? call.name ?? "";
+ case "recall":
+ case "history": {
+ const q = call.query ?? result.query ?? "";
+ return result.count !== undefined ? `${q} · ${result.count} result${result.count === 1 ? "" : "s"}` : q;
+ }
+ case "memory": {
+ const action = call.action ?? result.action ?? "";
+ const q = call.query ?? result.query ?? "";
+ let detail = q;
+ if (result.count !== undefined) {
+ detail = `${q} · ${result.count} result${result.count === 1 ? "" : "s"}`;
+ } else if (result.added !== undefined) {
+ detail = `${result.added} saved`;
+ }
+ return [action, detail].filter(Boolean).join(" ");
}
- return [action, detail].filter(Boolean).join(" ");
+ case "background": {
+ const action = call.action ?? result.action ?? "";
+ const target = call.command ? firstLine(call.command, 48) : (call.process_id ?? call.monitor_id ?? "");
+ return [action, target].filter(Boolean).join(" ");
+ }
+ default:
+ return "";
}
- case "background": {
- const action = call.action ?? result.action ?? "";
- const target = call.command ? firstLine(call.command, 48) : (call.process_id ?? call.monitor_id ?? "");
- return [action, target].filter(Boolean).join(" ");
+ }
+
+ function toolRow(row: ToolRowModel, work: WorkBlock, status: WorkBlock["status"], stale = false): TemplateResult {
+ if (row.approval) {
+ const p = (row.approval.payload ?? {}) as ToolPayload;
+ return html`<div class="tool-row tool-approval">
+ <span class="tool-icon">${icon(Wrench, 15)}</span>
+ <span class="tool-label"
+ >Approval
+ needed${p.reason ? html` <span class="tool-detail">${firstLine(p.reason, 90)}</span>` : nothing}</span
+ >
+ </div>`;
}
- default:
- return "";
+ const call = (row.call?.payload ?? {}) as ToolPayload;
+ const result = (row.result?.payload ?? {}) as ToolPayload;
+ const tool = call.tool ?? result.tool ?? "unknown";
+ const meta = TOOL_META[tool] ?? UNKNOWN_TOOL;
+ const kind = toolRowKind(row, status);
+ let label = meta.attempted;
+ if (kind === "approval") label = "Approval needed";
+ else if (kind === "running") label = stale ? `${meta.active} — interrupted` : meta.active;
+ else if (kind === "ok") label = meta.done;
+ let why = "";
+ if (kind === "approval") why = firstLine(result.reason ?? "", 90);
+ else if (kind === "failed") why = firstLine(result.error ?? result.reason ?? "", 90);
+ const base = kind === "approval" ? "" : toolDetail(tool, call, result);
+ const attempts = row.attempts && row.attempts > 1 ? `${row.attempts} attempts` : "";
+ const detail = [base, why, attempts].filter(Boolean).join(" · ");
+ const classes = ["tool-row", `tool-${kind}`].join(" ");
+ const head = html`<span class="tool-icon">${icon(meta.icon, 15)}</span>
+ <span class="tool-label">${label}${detail ? html` <span class="tool-detail">${detail}</span>` : nothing}</span>`;
+ if (tool === "execute" && row.result && (result.stdout || result.stderr)) {
+ return html`<details class="${classes} tool-expandable">
+ <summary class="tool-summary">${head}${icon(ChevronRight, 14)}</summary>
+ ${execOutputCard(result, work, row.result ?? null)}
+ </details>`;
+ }
+ return html`<div class="${classes}">${head}</div>`;
}
-}
-function toolRow(row: ToolRowModel, status: WorkBlock["status"], stale = false): TemplateResult {
- if (row.approval) {
- const p = (row.approval.payload ?? {}) as ToolPayload;
- return html`<div class="tool-row tool-approval">
- <span class="tool-icon">${icon(Wrench, 15)}</span>
- <span class="tool-label"
- >Approval needed${p.reason ? html` <span class="tool-detail">${firstLine(p.reason, 90)}</span>` : nothing}</span
- >
+ function execOutputCard(result: ToolPayload, work: WorkBlock, activity: ToolActivity | null): TemplateResult {
+ const out = [result.stdout ?? "", result.stderr ? `[stderr]\n${result.stderr}` : ""].filter(Boolean).join("\n");
+ return html`<div class="code-card">
+ <div class="code-card-head"><span class="code-card-lang">bash</span></div>
+ <pre class="code-card-body">${out}</pre>
+ <div class="code-card-foot">
+ exit ${result.code ?? 0}${result.timedOut ? " · timed out" : ""}
+ ${
+ activity?.truncated
+ ? html`<button class="show-full-btn" type="button" @click=${() => void loadFullEntry(work, activity)}>
+ Show full output
+ </button>`
+ : nothing
+ }
+ </div>
</div>`;
}
- const call = (row.call?.payload ?? {}) as ToolPayload;
- const result = (row.result?.payload ?? {}) as ToolPayload;
- const tool = call.tool ?? result.tool ?? "unknown";
- const meta = TOOL_META[tool] ?? UNKNOWN_TOOL;
- const kind = toolRowKind(row, status);
- let label = meta.attempted;
- if (kind === "approval") label = "Approval needed";
- else if (kind === "running") label = stale ? `${meta.active} — interrupted` : meta.active;
- else if (kind === "ok") label = meta.done;
- let why = "";
- if (kind === "approval") why = firstLine(result.reason ?? "", 90);
- else if (kind === "failed") why = firstLine(result.error ?? result.reason ?? "", 90);
- const base = kind === "approval" ? "" : toolDetail(tool, call, result);
- const attempts = row.attempts && row.attempts > 1 ? `${row.attempts} attempts` : "";
- const detail = [base, why, attempts].filter(Boolean).join(" · ");
- const classes = ["tool-row", `tool-${kind}`].join(" ");
- const head = html`<span class="tool-icon">${icon(meta.icon, 15)}</span>
- <span class="tool-label">${label}${detail ? html` <span class="tool-detail">${detail}</span>` : nothing}</span>`;
- if (tool === "execute" && row.result && (result.stdout || result.stderr)) {
- return html`<details class="${classes} tool-expandable">
- <summary class="tool-summary">${head}${icon(ChevronRight, 14)}</summary>
- ${execOutputCard(result)}
- </details>`;
- }
- return html`<div class="${classes}">${head}</div>`;
-}
-function execOutputCard(result: ToolPayload): TemplateResult {
- const out = [result.stdout ?? "", result.stderr ? `[stderr]\n${result.stderr}` : ""].filter(Boolean).join("\n");
- return html`<div class="code-card">
- <div class="code-card-head"><span class="code-card-lang">bash</span></div>
- <pre class="code-card-body">${out}</pre>
- <div class="code-card-foot">exit ${result.code ?? 0}${result.timedOut ? " · timed out" : ""}</div>
- </div>`;
-}
+ function redrawTranscript(): void {
+ if (readonlyRedraw) readonlyRedraw();
+ else drawActiveChat();
+ }
-function chipBadge(glyph: IconNode, name: string, size?: number, href?: string, download = false): TemplateResult {
- const inner = html`${icon(glyph, 14)}<span>${name}</span>${typeof size === "number" ? html`<small>${formatBytes(size)}</small>` : nothing}`;
- if (!href) return html`<span class="file-chip">${inner}</span>`;
- return download
- ? html`<a class="file-chip" href=${href} download=${name}>${inner}</a>`
- : html`<a class="file-chip" href=${href} target="_blank" rel="noreferrer">${inner}</a>`;
-}
+ async function loadFullEntry(work: WorkBlock, activity: ToolActivity): Promise<void> {
+ const sessionId = chatState.sessionId;
+ if (!sessionId || !activity.truncated) return;
+ try {
+ const full = await fetchEntry(sessionId, activity.seq);
+ work.activity = work.activity.map((a) =>
+ a === activity ? { ...a, payload: full.payload, truncated: false } : a,
+ );
+ } catch (err) {
+ ctx.composer.state.error = errMessage(err, "Couldn't load the full output.");
+ }
+ redrawTranscript();
+ }
-function fileChip(name: string, size?: number, href?: string): TemplateResult {
- return chipBadge(Paperclip, name, size, href);
-}
+ function chipBadge(glyph: IconNode, name: string, size?: number, href?: string, download = false): TemplateResult {
+ const inner = html`${icon(glyph, 14)}<span>${name}</span>${typeof size === "number" ? html`<small>${formatBytes(size)}</small>` : nothing}`;
+ if (!href) return html`<span class="file-chip">${inner}</span>`;
+ return download
+ ? html`<a class="file-chip" href=${href} download=${name}>${inner}</a>`
+ : html`<a class="file-chip" href=${href} target="_blank" rel="noreferrer">${inner}</a>`;
+ }
-function imageChip(name: string, size?: number, href?: string): TemplateResult {
- return chipBadge(FileImage, name, size, href, true);
-}
+ function fileChip(name: string, size?: number, href?: string): TemplateResult {
+ return chipBadge(Paperclip, name, size, href);
+ }
-interface UserAttachmentView {
- fileName: string;
- mimeType?: string;
- size?: number;
- content?: string;
- artifactId?: string;
-}
+ function imageChip(name: string, size?: number, href?: string): TemplateResult {
+ return chipBadge(FileImage, name, size, href, true);
+ }
-function userAttachmentBadge(a: UserAttachmentView): TemplateResult {
- const artifactHref = a.artifactId ? withBase(`/api/files/${encodeURIComponent(a.artifactId)}/content`) : undefined;
- if (a.mimeType?.startsWith("image/")) {
- let src = artifactHref;
- if (!src && a.content) {
- src = a.content.startsWith("data:") ? a.content : `data:${a.mimeType};base64,${a.content}`;
- }
- if (src && !browserRenderableImage(a.mimeType)) return imageChip(a.fileName, a.size, src);
- if (src) {
- const img = html`<img src=${src} alt=${a.fileName} loading="lazy" />`;
- return artifactHref
- ? html`<a class="file-image" href=${artifactHref} target="_blank" rel="noreferrer" title=${a.fileName}
- >${img}</a
- >`
- : html`<span class="file-image" title=${a.fileName}>${img}</span>`;
+ interface UserAttachmentView {
+ fileName: string;
+ mimeType?: string;
+ size?: number;
+ content?: string;
+ artifactId?: string;
+ }
+
+ function userAttachmentBadge(a: UserAttachmentView): TemplateResult {
+ const artifactHref = a.artifactId ? withBase(`/api/files/${encodeURIComponent(a.artifactId)}/content`) : undefined;
+ if (a.mimeType?.startsWith("image/")) {
+ let src = artifactHref;
+ if (!src && a.content) {
+ src = a.content.startsWith("data:") ? a.content : `data:${a.mimeType};base64,${a.content}`;
+ }
+ if (src && !browserRenderableImage(a.mimeType)) return imageChip(a.fileName, a.size, src);
+ if (src) {
+ const img = html`<img src=${src} alt=${a.fileName} loading="lazy" />`;
+ return artifactHref
+ ? html`<a class="file-image" href=${artifactHref} target="_blank" rel="noreferrer" title=${a.fileName}
+ >${img}</a
+ >`
+ : html`<span class="file-image" title=${a.fileName}>${img}</span>`;
+ }
}
+ return fileChip(a.fileName, a.size, artifactHref);
}
- return fileChip(a.fileName, a.size, artifactHref);
-}
-function deliveredFileBadge(file: DeliveredFile): TemplateResult {
- if (!file.artifactId) return fileChip(file.name, file.sizeBytes);
- const href = withBase(`/api/files/${encodeURIComponent(file.artifactId)}/content`);
- if (file.mimetype?.startsWith("image/")) {
- if (!browserRenderableImage(file.mimetype)) return imageChip(file.name, file.sizeBytes, href);
- return html`<a class="file-image" href=${href} target="_blank" rel="noreferrer" title=${file.name}
- ><img src=${href} alt=${file.name} loading="lazy"
- /></a>`;
+ function deliveredFileBadge(file: DeliveredFile): TemplateResult {
+ if (!file.artifactId) return fileChip(file.name, file.sizeBytes);
+ const href = withBase(`/api/files/${encodeURIComponent(file.artifactId)}/content`);
+ if (file.mimetype?.startsWith("image/")) {
+ if (!browserRenderableImage(file.mimetype)) return imageChip(file.name, file.sizeBytes, href);
+ return html`<a class="file-image" href=${href} target="_blank" rel="noreferrer" title=${file.name}
+ ><img src=${href} alt=${file.name} loading="lazy"
+ /></a>`;
+ }
+ return fileChip(file.name, file.sizeBytes, href);
}
- return fileChip(file.name, file.sizeBytes, href);
-}
-let stickToBottom = true;
+ let stickToBottom = true;
-function onTranscriptScroll(e: Event): void {
- const s = e.currentTarget as HTMLElement;
- stickToBottom = s.scrollHeight - s.scrollTop - s.clientHeight <= 120;
-}
+ function onTranscriptScroll(e: Event): void {
+ const s = e.currentTarget as HTMLElement;
+ stickToBottom = s.scrollHeight - s.scrollTop - s.clientHeight <= 120;
+ }
-function scrollTranscript(force = false): void {
- const scroller = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
- if (!scroller) return;
- if (!force && !stickToBottom) return;
- requestAnimationFrame(() => {
- if (force) {
- const prev = scroller.style.scrollBehavior;
- scroller.style.scrollBehavior = "auto";
+ function scrollTranscript(force = false): void {
+ const scroller = chatState.host?.querySelector<HTMLElement>(".chat-scroll");
+ if (!scroller) return;
+ if (!force && !stickToBottom) return;
+ requestAnimationFrame(() => {
+ if (force) {
+ const prev = scroller.style.scrollBehavior;
+ scroller.style.scrollBehavior = "auto";
+ scroller.scrollTop = scroller.scrollHeight;
+ requestAnimationFrame(() => {
+ scroller.style.scrollBehavior = prev;
+ });
+ return;
+ }
scroller.scrollTop = scroller.scrollHeight;
- requestAnimationFrame(() => {
- scroller.style.scrollBehavior = prev;
- });
- return;
- }
- scroller.scrollTop = scroller.scrollHeight;
- });
+ });
+ }
+
+ redrawHooks.add(redrawForConnector);
+
+ return {
+ state: chatState,
+ hasLiveRun: () => hasLiveRun(runSlot),
+ signalLiveRun: (kind, text) => signalLiveRun(runSlot, kind, text),
+ newChat,
+ teardown: teardownActiveChat,
+ resetChatState,
+ mountContinuable,
+ mountReadOnly,
+ mountLoadingPane,
+ drawActiveChat,
+ setTranscriptWindow,
+ requestBackgroundPanel,
+ activePendingApprovals,
+ hasUnresolvedApproval,
+ resolveCommandApproval,
+ approvalSummaryView,
+ notePendingSessionOnSend,
+ syncPaneState: postCurrentPaneState,
+ onDelivery,
+ resumeIfIdle,
+ redraw: () => drawActiveChat(),
+ dispose,
+ };
}
diff --git a/plugins/web-ui/src/composer.ts b/plugins/web-ui/src/composer.ts
index 03fe4fe5a..52612bd33 100644
--- a/plugins/web-ui/src/composer.ts
+++ b/plugins/web-ui/src/composer.ts
@@ -21,8 +21,6 @@ import {
import {
api,
fetchRuntimeConfig,
- hasLiveRun,
- signalLiveRun,
updateRuntimeConfig,
type ApprovalDecision,
type PendingApproval,
@@ -30,7 +28,6 @@ import {
} from "./core-bridge";
import { errMessage, swallow } from "../../chassis/src/errors";
import { icon } from "./ui";
-import { embedMode } from "./embed";
import {
EFFORT_LEVELS,
applyRuntimeOptions,
@@ -47,15 +44,7 @@ import {
type ModelOptionValue,
} from "./model-options";
import { modelSupportsFastMode, setFastModeModelIds } from "./pi-models";
-import {
- activePendingApprovals,
- approvalSummaryView,
- chatState,
- drawActiveChat,
- hasUnresolvedApproval,
- notePendingSessionOnSend,
- resolveCommandApproval,
-} from "./chat";
+import type { ComposerSurface, ConvCtx } from "./conv-types";
import { bumpSessionActivity, dropPendingSession, renderList } from "./sessions";
import { adminSessionLogUrl, appState, can } from "./shell";
import { base64ToText, bytesToBase64, insertIntoDraft, pasteChipLabel } from "./paste-text";
@@ -85,8 +74,17 @@ function loadThreadPicks(): Map<string, ModelOptionValue> {
}
let threadModelPicks = loadThreadPicks();
-let activeRuntimeConfig: RuntimeConfig | null = null;
-let runtimeRequest = 0;
+let seededRuntime: { scopeId: string | null; config: RuntimeConfig } | null = null;
+
+export function seedRuntimeConfig(scopeId: string | null, config: RuntimeConfig): void {
+ seededRuntime = { scopeId: runtimeScopeKey(scopeId), config };
+}
+
+function runtimeScopeKey(scopeId: string | null): string | null {
+ if (scopeId) return scopeId;
+ const user = appState.me?.user;
+ return user ? `personal:${user}` : null;
+}
if (typeof window !== "undefined") {
window.addEventListener("storage", (e) => {
@@ -109,8 +107,8 @@ export function carryModelPick(fromThreadRef: string | null, toThreadRef: string
if (pick) rememberThreadPick(toThreadRef, pick);
}
-function modelOptionFor(value: ModelOptionValue): ModelOption {
- const options = getModelOptions();
+function modelOptionFor(value: ModelOptionValue, scopeKey?: string | null): ModelOption {
+ const options = getModelOptions(scopeKey);
return (
options.find((option) => option.value === value) ??
options.find((option) => option.value === defaultModelValue()) ??
@@ -147,24 +145,6 @@ function persistPreference(key: string, value: string): void {
}
}
-function isUnsentNewChat(): boolean {
- return (
- chatState.sessionId === null &&
- !(chatState.agent?.state.messages ?? []).some((m) => !(m as { opener?: boolean }).opener)
- );
-}
-
-function persistDraft(): void {
- if (!chatState.threadRef) return;
- saveDraft(chatState.threadRef, composerState.draft);
- if (isUnsentNewChat()) saveDraft(newChatDraftKey(appState.me?.user), composerState.draft);
-}
-
-function clearActiveDraft(): void {
- if (chatState.threadRef) clearDraft(chatState.threadRef);
- if (chatState.sessionId === null) clearDraft(newChatDraftKey(appState.me?.user));
-}
-
export interface SkillItem {
id?: string;
name: string;
@@ -189,93 +169,17 @@ interface SkillMatch {
end: number;
}
-export const composerState = {
- draft: "",
- attachments: [] as Attachment[],
- error: "",
- processingFiles: false,
- dragging: false,
- openMenu: null as ComposerMenu | null,
- skillsCache: null as SkillItem[] | null,
- slashDismissed: false,
- effortLevel: loadStoredEffort(defaultEffortForModel(modelOptionFor(defaultModelValue()).model)),
- fastMode: loadStoredFastMode(),
- pasteView: null as { id: string; text: string; initial: string; dirty: boolean } | null,
-};
-
-const pastedTextIds = new Set<string>();
-
-let dragDepth = 0;
-let skillsLoading = false;
-let slashActiveIndex = 0;
-let fastModeCharging = false;
-let orgFastModeDefault = false;
-
-function effectiveFastMode(): boolean {
- return composerState.fastMode ?? orgFastModeDefault;
-}
-let fastModeChargeTimer: ReturnType<typeof setTimeout> | null = null;
-
-export function resetComposer(): void {
- composerState.draft = "";
- composerState.attachments = [];
- composerState.pasteView = null;
- pastedTextIds.clear();
- composerState.error = "";
- composerState.processingFiles = false;
- composerState.openMenu = null;
- slashActiveIndex = 0;
- composerState.slashDismissed = false;
-}
+let skillsCache: SkillItem[] | null = null;
-export function currentModelOption(): ModelOption {
- const picked = chatState.threadRef ? threadModelPicks.get(chatState.threadRef) : undefined;
- return modelOptionFor(picked ?? defaultModelValue());
+export function clearSkillsCache(): void {
+ skillsCache = null;
}
-export async function refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void> {
- const request = ++runtimeRequest;
- activeRuntimeConfig = null;
- composerState.error = "";
- drawActiveChat(agent);
- const config = await fetchRuntimeConfig(scopeId);
- if (request !== runtimeRequest) return;
- if (!config) {
- composerState.error = "Could not load runtime settings.";
- drawActiveChat(agent);
- return;
- }
- activeRuntimeConfig = config;
- setFastModeModelIds(config.fastModeModelIds);
- orgFastModeDefault = config.interactiveFastMode === true;
- applyRuntimeOptions(config.approvedHarnesses, config.modelsByHarness, config.effective, config.modelCatalog);
- if (agent && (!chatState.threadRef || !threadModelPicks.has(chatState.threadRef)))
- agent.state.model = currentModelOption().model;
- drawActiveChat(agent);
- if (pendingComposerFocus) focusComposerEnd();
-}
+const SLASH_TOKEN = /(^|\s)\/([a-zA-Z0-9_-]*)$/;
-async function changeScopeRuntime(
- change: { harnessId?: string; modelId?: string; inherit?: boolean; keep?: boolean },
- agent: Agent,
-): Promise<void> {
- const request = ++runtimeRequest;
- const scopeId = chatState.scopeId;
- try {
- const config = await updateRuntimeConfig(scopeId, change);
- if (request !== runtimeRequest || scopeId !== chatState.scopeId) return;
- activeRuntimeConfig = config;
- setFastModeModelIds(config.fastModeModelIds);
- orgFastModeDefault = config.interactiveFastMode === true;
- applyRuntimeOptions(config.approvedHarnesses, config.modelsByHarness, config.effective, config.modelCatalog);
- if (!chatState.threadRef || !threadModelPicks.has(chatState.threadRef))
- agent.state.model = currentModelOption().model;
- composerState.error = "";
- } catch (e) {
- if (request !== runtimeRequest || scopeId !== chatState.scopeId) return;
- composerState.error = errMessage(e, "Could not update the scope default.");
- }
- drawActiveChat(agent);
+export function slashQuery(draft: string): string | null {
+ const m = SLASH_TOKEN.exec(draft);
+ return m ? (m[2] ?? "") : null;
}
export function resyncModelSelection(): void {
@@ -284,1080 +188,1334 @@ export function resyncModelSelection(): void {
} catch {
void 0;
}
- composerState.effortLevel = loadStoredEffort(defaultEffortForModel(currentModelOption().model));
}
-export function composerForm(agent: Agent): TemplateResult {
- const selectedModel = currentModelOption();
- const effortAvailable = harnessSupportsEffort(selectedModel.harnessId);
- const fastSupported = harnessSupportsFastMode(selectedModel.harnessId);
- const fastAvailable = fastSupported && modelSupportsFastMode(selectedModel.model.id);
- const fastOn = fastAvailable && effectiveFastMode();
- const fastCharging = fastModeCharging && fastOn;
- let fastTitle = "Fast mode is only available on Opus models";
- if (fastAvailable) fastTitle = fastOn ? "Fast mode active" : "Fast mode";
- const approvalPauses = activePendingApprovals();
- const runtimePending = activeRuntimeConfig === null;
- const modelToggled = !runtimePending && selectedModel.value !== defaultModelValue();
- const inputBlocked = runtimePending || chatState.resolvingApprovals.size > 0 || approvalPauses.length > 0;
- const attachingDisabled = inputBlocked || agent.state.isStreaming;
- let placeholder = "Ask anything";
- if (inputBlocked) placeholder = runtimePending ? "Loading runtime…" : "Approve or deny to continue";
- else if (agent.state.isStreaming) placeholder = "Steer the running task…";
- let composerNotice: TemplateResult | typeof nothing = nothing;
- if (composerState.processingFiles) {
- composerNotice = html`<div class="composer-note">Preparing files...</div>`;
- } else if (!approvalPauses.length && runtimePending) {
- composerNotice = html`<div class="composer-error">
- ${composerState.error || "Loading runtime settings…"}
- ${composerState.error ? html`<button type="button" @click=${() => void refreshRuntimeSelection(chatState.scopeId, agent)}>Retry</button>` : nothing}
- </div>`;
- } else if (composerState.error) {
- composerNotice = html`<div class="composer-error">${composerState.error}</div>`;
- }
- return html`
- <form class="composer-wrap" @submit=${(e: Event) => submitComposer(e, agent)}>
- ${slashMenu(agent)}
- ${
- activeRuntimeConfig?.upgradeAvailable
- ? html`<div class="runtime-upgrade">
- <span
- >The org now recommends
- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).harnessLabel}
- ·
- ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).buttonLabel}.</span
- >
- <button
- type="button"
- @click=${() => changeScopeRuntime({ harnessId: activeRuntimeConfig!.orgDefault.harnessId, modelId: activeRuntimeConfig!.orgDefault.modelId }, agent)}
- >
- Upgrade
- </button>
- <button type="button" @click=${() => changeScopeRuntime({ keep: true }, agent)}>Keep mine</button>
- <button type="button" @click=${() => changeScopeRuntime({ inherit: true }, agent)}>
- Inherit future defaults
- </button>
- </div>`
- : nothing
- }
- ${
- composerState.attachments.length
- ? html`
- <div class="attachment-strip">
- ${composerState.attachments.map(
- (a) => html`
- <span class="file-chip">
- ${
- pastedTextIds.has(a.id)
- ? html`
- <button
- type="button"
- class="chip-open"
- title="View pasted text"
- @click=${() => openPasteView(a.id, agent)}
- >
- ${icon(FileText, 14)}
- <span>${pasteChipLabel(a.extractedText?.length ?? 0)}</span>
- </button>
- `
- : html`${icon(Paperclip, 14)}<span>${a.fileName}</span>`
- }
- <button type="button" class="chip-x" title="Remove" @click=${() => removeAttachment(a.id, agent)}>
- ${icon(X, 13)}
- </button>
- </span>
- `,
- )}
- </div>
- `
- : nothing
- }
- ${
- approvalPauses.length
- ? composerApprovalPanel(approvalPauses)
- : html`
- <textarea
- class="composer-input"
- rows="1"
- placeholder=${placeholder}
- ?disabled=${inputBlocked}
- .value=${live(composerState.draft)}
- @input=${(e: InputEvent) => onDraftInput(e, agent)}
- @keydown=${(e: KeyboardEvent) => onComposerKeydown(e, agent)}
- @paste=${(e: ClipboardEvent) => void onComposerPaste(e, agent)}
- ></textarea>
- `
- }
- <div class="composer-toolbar">
- <div class="composer-left">
- ${
- !embedMode && chatState.sessionId && can("admin")
- ? html`<a
- class="icon-btn"
- title="View session log (admin)"
- href=${adminSessionLogUrl(chatState.sessionId, chatState.scopeId ?? `org:${appState.me?.org ?? ""}`)}
- target="_blank"
- rel="noreferrer"
- >${icon(ScrollText, 18)}</a
- >`
- : nothing
- }
- <input
- class="file-input"
- type="file"
- multiple
- hidden
- ?disabled=${attachingDisabled}
- @change=${(e: Event) => void onFilesSelected(e, agent)}
- />
- <button
- class="icon-btn"
- type="button"
- title="Attach files"
- ?disabled=${attachingDisabled}
- @click=${() => pickFiles()}
- >
- ${icon(Paperclip, 18)}
- </button>
- ${
- embedMode
- ? nothing
- : html`
- ${
- effortAvailable
- ? menuControl({
- kind: "effort",
- glyph: Brain,
- label: effortLabel(composerState.effortLevel),
- title: "Effort",
- selected: composerState.effortLevel,
- options: EFFORT_LEVELS,
- disabled: inputBlocked,
- onSelect: (value: string) => selectEffort(value as EffortLevel, agent),
- })
- : nothing
- }
- ${
- fastSupported
- ? html`<button
- class="fast-toggle ${fastOn ? "active" : ""} ${fastCharging ? "charging" : ""} ${fastAvailable ? "" : "unavailable"}"
- type="button"
- title=${fastTitle}
- aria-label=${fastTitle}
- aria-pressed=${fastOn ? "true" : "false"}
- aria-disabled=${fastAvailable ? "false" : "true"}
- ?disabled=${inputBlocked}
- @click=${() => toggleFastMode(agent)}
- >
- ${icon(Zap, 15)}
- <span class="fast-label">Fast</span>
- </button>`
- : nothing
- }
- `
- }
- </div>
- <div class="composer-right">
- ${
- embedMode
- ? settingsControl(agent, selectedModel, inputBlocked)
- : html`
- ${
- modelToggled
- ? html`<button
- class="runtime-default-btn"
- type="button"
- aria-label="Make default"
- data-mobile-label="Default"
- title="Use this harness and model as the default for this scope"
- ?disabled=${inputBlocked}
- @click=${() => changeScopeRuntime({ harnessId: selectedModel.harnessId, modelId: selectedModel.model.id }, agent)}
- >
- Make default
- </button>`
- : nothing
- }
- ${
- modelToggled && activeRuntimeConfig?.scopeOverride
- ? html`<button
- class="runtime-default-btn"
- type="button"
- aria-label="Use org default"
- data-mobile-label="Org default"
- ?disabled=${inputBlocked}
- @click=${() => changeScopeRuntime({ inherit: true }, agent)}
- >
- Use org default
- </button>`
- : nothing
- }
- ${menuControl({
- kind: "model",
- label: selectedModel.buttonLabel,
- title: "Model",
- selected: selectedModel.value,
- align: "right",
- options: getModelOptionsForHarness(selectedModel.harnessId).map((option) => ({
- value: option.value,
- label: option.label,
- })),
- disabled: inputBlocked,
- onSelect: (value: string) => selectModel(value, agent),
- })}
- ${menuControl({
- kind: "harness",
- label: selectedModel.harnessLabel,
- title: "Harness",
- selected: selectedModel.harnessId,
- align: "right",
- options: getHarnessOptions(),
- disabled: inputBlocked,
- onSelect: (value: string) => selectHarness(value, agent),
- })}
- `
- }
- ${sendControls(agent)}
- </div>
- </div>
- ${composerNotice}
- </form>
- ${pasteViewDialog(agent)}
- `;
-}
+export function createComposerSurface(ctx: ConvCtx): ComposerSurface {
+ let activeRuntimeConfig: RuntimeConfig | null = null;
+ let runtimeRequest = 0;
-function pasteViewDialog(agent: Agent): TemplateResult | typeof nothing {
- const view = composerState.pasteView;
- if (!view) return nothing;
- return html`
- <div
- class="project-dialog-backdrop"
- @click=${(e: MouseEvent) => e.target === e.currentTarget && closePasteView(agent)}
- @keydown=${(e: KeyboardEvent) => e.key === "Escape" && closePasteView(agent)}
- >
- <div class="project-dialog paste-dialog" role="dialog" aria-modal="true" aria-labelledby="paste-dialog-title">
- <div class="project-dialog-head">
- <div><h2 id="paste-dialog-title">Pasted text</h2></div>
- <button class="chip-x" type="button" aria-label="Close" title="Close" @click=${() => closePasteView(agent)}>
- ${icon(X, 16)}
- </button>
- </div>
- <textarea
- class="paste-dialog-text"
- @input=${(e: InputEvent) => {
- view.text = (e.currentTarget as HTMLTextAreaElement).value;
- view.dirty = true;
- }}
- >
-${view.initial}</textarea>
- <div class="project-dialog-actions">
- <button class="btn" type="button" @click=${() => removeAttachment(view.id, agent)}>Remove</button>
- <button class="btn" type="button" @click=${() => insertPasteIntoDraft(agent)}>Insert into message</button>
- <button class="btn primary" type="button" @click=${() => closePasteView(agent)}>Done</button>
- </div>
- </div>
- </div>
- `;
-}
+ function isUnsentNewChat(): boolean {
+ return (
+ ctx.chat.state.sessionId === null &&
+ !(ctx.chat.state.agent?.state.messages ?? []).some((m) => !(m as { opener?: boolean }).opener)
+ );
+ }
-function openPasteView(id: string, agent: Agent): void {
- const attachment = composerState.attachments.find((a) => a.id === id);
- if (!attachment) return;
- const text = attachment.extractedText ?? base64ToText(attachment.content);
- composerState.pasteView = { id, text, initial: text, dirty: false };
- drawActiveChat(agent);
- requestAnimationFrame(() => chatState.host?.querySelector<HTMLTextAreaElement>(".paste-dialog-text")?.focus());
-}
+ function persistDraft(): void {
+ if (!ctx.chat.state.threadRef) return;
+ saveDraft(ctx.chat.state.threadRef, composerState.draft);
+ if (isUnsentNewChat()) saveDraft(newChatDraftKey(appState.me?.user), composerState.draft);
+ }
-function closePasteView(agent: Agent): void {
- const view = composerState.pasteView;
- if (!view) return;
- const attachment = composerState.attachments.find((a) => a.id === view.id);
- if (attachment && view.dirty) {
- const bytes = new TextEncoder().encode(view.text);
- attachment.content = bytesToBase64(bytes);
- attachment.size = bytes.length;
- attachment.extractedText = view.text;
- }
- composerState.pasteView = null;
- drawActiveChat(agent);
-}
+ function clearActiveDraft(): void {
+ if (ctx.chat.state.threadRef) clearDraft(ctx.chat.state.threadRef);
+ if (ctx.chat.state.sessionId === null) clearDraft(newChatDraftKey(appState.me?.user));
+ }
-function insertPasteIntoDraft(agent: Agent): void {
- const view = composerState.pasteView;
- if (!view) return;
- const ta = chatState.host?.querySelector<HTMLTextAreaElement>(".composer-input");
- const { draft, cursor } = insertIntoDraft(composerState.draft, view.text, ta ? ta.selectionStart : null);
- composerState.draft = draft;
- persistDraft();
- composerState.pasteView = null;
- removeAttachment(view.id, agent);
- resizeComposer();
- requestAnimationFrame(() => {
- const input = chatState.host?.querySelector<HTMLTextAreaElement>(".composer-input");
- if (!input) return;
- input.focus();
- input.setSelectionRange(cursor, cursor);
- });
-}
+ const composerState = {
+ draft: "",
+ attachments: [] as Attachment[],
+ error: "",
+ processingFiles: false,
+ dragging: false,
+ openMenu: null as ComposerMenu | null,
+ slashDismissed: false,
+ effortLevel: loadStoredEffort(defaultEffortForModel(modelOptionFor(defaultModelValue()).model)),
+ fastMode: loadStoredFastMode(),
+ pasteView: null as { id: string; text: string; initial: string; dirty: boolean } | null,
+ };
-function sendControls(agent: Agent): TemplateResult {
- if (!agent.state.isStreaming) {
- return html`<button class="send-btn" type="submit" title="Send" ?disabled=${!composerCanSend()}>
- ${icon(ArrowUp, 17)}
- </button>`;
- }
- const canSteer = Boolean(composerState.draft.trim());
- return html`
- <button class="stop-btn" type="button" title="Stop" aria-label="Stop" @click=${() => stopStreaming(agent)}>
- ${icon(Square, 16)}
- </button>
- <button
- class="send-btn"
- type="submit"
- title="Steer the running task"
- aria-label="Steer the running task"
- ?disabled=${!canSteer}
- >
- ${icon(ArrowUp, 17)}
- </button>
- `;
-}
+ const pastedTextIds = new Set<string>();
-function composerApprovalPanel(approvals: PendingApproval[]): TemplateResult {
- const busy = chatState.resolvingApprovals.size > 0;
- const decide = (decision: ApprovalDecision): void => {
- if (!busy) resolveCommandApproval(decision);
- };
- return html`<div class="composer-approval-panel" role="group" aria-label="Command approval">
- ${approvals.map(
- (a) =>
- html`<div class="composer-approval">
- <div class="composer-approval-copy">${approvalSummaryView(a, true)}</div>
- <div class="approval-actions">
- <button
- class="approval-btn deny"
- type="button"
- ?disabled=${busy}
- @click=${() => decide({ requestId: a.requestId, approved: false })}
- >
- Deny
+ let dragDepth = 0;
+ let skillsLoading = false;
+ let slashActiveIndex = 0;
+ let fastModeCharging = false;
+ let orgFastModeDefault = false;
+ let fastModeChargeTimer: ReturnType<typeof setTimeout> | null = null;
+
+ function effectiveFastMode(): boolean {
+ return composerState.fastMode ?? orgFastModeDefault;
+ }
+
+ function resetComposer(): void {
+ composerState.draft = "";
+ composerState.attachments = [];
+ composerState.pasteView = null;
+ pastedTextIds.clear();
+ composerState.error = "";
+ composerState.processingFiles = false;
+ composerState.openMenu = null;
+ slashActiveIndex = 0;
+ composerState.slashDismissed = false;
+ }
+
+ function scopeKey(): string | null {
+ return runtimeScopeKey(ctx.chat.state.scopeId);
+ }
+
+ function currentModelOption(): ModelOption {
+ const picked = ctx.chat.state.threadRef ? threadModelPicks.get(ctx.chat.state.threadRef) : undefined;
+ return modelOptionFor(picked ?? defaultModelValue(scopeKey()), scopeKey());
+ }
+
+ async function refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void> {
+ const request = ++runtimeRequest;
+ const scopeKey = runtimeScopeKey(scopeId);
+ const seeded = scopeKey !== null && seededRuntime?.scopeId === scopeKey ? seededRuntime.config : null;
+ if (seeded) {
+ applySelectedRuntime(seeded, agent);
+ return;
+ }
+ activeRuntimeConfig = null;
+ composerState.error = "";
+ ctx.chat.drawActiveChat(agent);
+ const config = await fetchRuntimeConfig(scopeId);
+ if (request !== runtimeRequest) return;
+ if (!config) {
+ composerState.error = "Could not load runtime settings.";
+ ctx.chat.drawActiveChat(agent);
+ return;
+ }
+ applySelectedRuntime(config, agent);
+ }
+
+ function applySelectedRuntime(config: RuntimeConfig, agent?: Agent): void {
+ activeRuntimeConfig = config;
+ composerState.error = "";
+ setFastModeModelIds(scopeKey(), config.fastModeModelIds);
+ orgFastModeDefault = config.interactiveFastMode === true;
+ applyRuntimeOptions(
+ scopeKey(),
+ config.approvedHarnesses,
+ config.modelsByHarness,
+ config.effective,
+ config.modelCatalog,
+ );
+ if (agent && (!ctx.chat.state.threadRef || !threadModelPicks.has(ctx.chat.state.threadRef)))
+ agent.state.model = currentModelOption().model;
+ ctx.chat.drawActiveChat(agent);
+ if (pendingComposerFocus) focusComposerEnd();
+ }
+
+ async function changeScopeRuntime(
+ change: { harnessId?: string; modelId?: string; inherit?: boolean; keep?: boolean },
+ agent: Agent,
+ ): Promise<void> {
+ const request = ++runtimeRequest;
+ const scopeId = ctx.chat.state.scopeId;
+ try {
+ const config = await updateRuntimeConfig(scopeId, change);
+ if (request !== runtimeRequest || scopeId !== ctx.chat.state.scopeId) return;
+ seededRuntime = null;
+ activeRuntimeConfig = config;
+ setFastModeModelIds(scopeKey(), config.fastModeModelIds);
+ orgFastModeDefault = config.interactiveFastMode === true;
+ applyRuntimeOptions(
+ scopeKey(),
+ config.approvedHarnesses,
+ config.modelsByHarness,
+ config.effective,
+ config.modelCatalog,
+ );
+ if (!ctx.chat.state.threadRef || !threadModelPicks.has(ctx.chat.state.threadRef))
+ agent.state.model = currentModelOption().model;
+ composerState.error = "";
+ } catch (e) {
+ if (request !== runtimeRequest || scopeId !== ctx.chat.state.scopeId) return;
+ composerState.error = errMessage(e, "Could not update the scope default.");
+ }
+ ctx.chat.drawActiveChat(agent);
+ }
+
+ function composerForm(agent: Agent): TemplateResult {
+ const selectedModel = currentModelOption();
+ const effortAvailable = harnessSupportsEffort(selectedModel.harnessId);
+ const fastSupported = harnessSupportsFastMode(selectedModel.harnessId);
+ const fastAvailable = fastSupported && modelSupportsFastMode(scopeKey(), selectedModel.model.id);
+ const fastOn = fastAvailable && effectiveFastMode();
+ const fastCharging = fastModeCharging && fastOn;
+ let fastTitle = "Fast mode is only available on Opus models";
+ if (fastAvailable) fastTitle = fastOn ? "Fast mode active" : "Fast mode";
+ const approvalPauses = ctx.chat.activePendingApprovals();
+ const runtimePending = activeRuntimeConfig === null;
+ const modelToggled = !runtimePending && selectedModel.value !== defaultModelValue(scopeKey());
+ const inputBlocked = runtimePending || ctx.chat.state.resolvingApprovals.size > 0 || approvalPauses.length > 0;
+ const attachingDisabled = inputBlocked;
+ let placeholder = "Ask anything";
+ if (inputBlocked) placeholder = runtimePending ? "Loading runtime…" : "Approve or deny to continue";
+ else if (agent.state.isStreaming) placeholder = "Steer the running task…";
+ let composerNotice: TemplateResult | typeof nothing = nothing;
+ if (composerState.processingFiles) {
+ composerNotice = html`<div class="composer-note">Preparing files...</div>`;
+ } else if (!approvalPauses.length && runtimePending) {
+ composerNotice = composerState.error
+ ? html`<div class="composer-error">
+ ${composerState.error}
+ <button type="button" @click=${() => void refreshRuntimeSelection(ctx.chat.state.scopeId, agent)}>
+ Retry
</button>
+ </div>`
+ : html`<div class="composer-note">Loading runtime settings…</div>`;
+ } else if (composerState.error) {
+ composerNotice = html`<div class="composer-error">${composerState.error}</div>`;
+ }
+ return html`
+ <form class="composer-wrap" @submit=${(e: Event) => submitComposer(e, agent)}>
+ ${slashMenu(agent)}
+ ${
+ activeRuntimeConfig?.upgradeAvailable
+ ? html`<div class="runtime-upgrade">
+ <span
+ >The org now recommends
+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).harnessLabel}
+ ·
+ ${modelOptionFor(`${activeRuntimeConfig.orgDefault.harnessId}:${activeRuntimeConfig.orgDefault.modelId}`).buttonLabel}.</span
+ >
+ <button
+ type="button"
+ @click=${() => changeScopeRuntime({ harnessId: activeRuntimeConfig!.orgDefault.harnessId, modelId: activeRuntimeConfig!.orgDefault.modelId }, agent)}
+ >
+ Upgrade
+ </button>
+ <button type="button" @click=${() => changeScopeRuntime({ keep: true }, agent)}>Keep mine</button>
+ <button type="button" @click=${() => changeScopeRuntime({ inherit: true }, agent)}>
+ Inherit future defaults
+ </button>
+ </div>`
+ : nothing
+ }
+ ${
+ composerState.attachments.length
+ ? html`
+ <div class="attachment-strip">
+ ${composerState.attachments.map(
+ (a) => html`
+ <span class="file-chip">
+ ${
+ pastedTextIds.has(a.id)
+ ? html`
+ <button
+ type="button"
+ class="chip-open"
+ title="View pasted text"
+ @click=${() => openPasteView(a.id, agent)}
+ >
+ ${icon(FileText, 14)}
+ <span>${pasteChipLabel(a.extractedText?.length ?? 0)}</span>
+ </button>
+ `
+ : html`${icon(Paperclip, 14)}<span>${a.fileName}</span>`
+ }
+ <button
+ type="button"
+ class="chip-x"
+ title="Remove"
+ @click=${() => removeAttachment(a.id, agent)}
+ >
+ ${icon(X, 13)}
+ </button>
+ </span>
+ `,
+ )}
+ </div>
+ `
+ : nothing
+ }
+ ${
+ approvalPauses.length
+ ? composerApprovalPanel(approvalPauses)
+ : html`
+ <textarea
+ class="composer-input"
+ rows="1"
+ placeholder=${placeholder}
+ ?disabled=${inputBlocked}
+ .value=${live(composerState.draft)}
+ @input=${(e: InputEvent) => onDraftInput(e, agent)}
+ @keydown=${(e: KeyboardEvent) => onComposerKeydown(e, agent)}
+ @paste=${(e: ClipboardEvent) => void onComposerPaste(e, agent)}
+ ></textarea>
+ `
+ }
+ <div class="composer-toolbar">
+ <div class="composer-left">
+ ${
+ !ctx.pane && ctx.chat.state.sessionId && can("admin")
+ ? html`<a
+ class="icon-btn"
+ title="View session log (admin)"
+ href=${adminSessionLogUrl(ctx.chat.state.sessionId, ctx.chat.state.scopeId ?? `org:${appState.me?.org ?? ""}`)}
+ target="_blank"
+ rel="noreferrer"
+ >${icon(ScrollText, 18)}</a
+ >`
+ : nothing
+ }
+ <input
+ class="file-input"
+ type="file"
+ multiple
+ hidden
+ ?disabled=${attachingDisabled}
+ @change=${(e: Event) => void onFilesSelected(e, agent)}
+ />
<button
- class="approval-btn"
+ class="icon-btn"
type="button"
- ?disabled=${busy}
- @click=${() => decide({ requestId: a.requestId, approved: true, scope: "once" })}
+ title="Attach files"
+ ?disabled=${attachingDisabled}
+ @click=${() => pickFiles()}
>
- Allow once
+ ${icon(Paperclip, 18)}
</button>
${
- a.grantModes?.session === false
+ ctx.pane
? nothing
- : html`<button
- class="approval-btn primary"
- type="button"
- ?disabled=${busy}
- @click=${() => decide({ requestId: a.requestId, approved: true, scope: "session" })}
- >
- Allow for session
- </button>`
+ : html`
+ ${
+ effortAvailable
+ ? menuControl({
+ kind: "effort",
+ glyph: Brain,
+ label: effortLabel(composerState.effortLevel),
+ title: "Effort",
+ selected: composerState.effortLevel,
+ options: EFFORT_LEVELS,
+ disabled: inputBlocked,
+ onSelect: (value: string) => selectEffort(value as EffortLevel, agent),
+ })
+ : nothing
+ }
+ ${
+ fastSupported
+ ? html`<button
+ class="fast-toggle ${fastOn ? "active" : ""} ${fastCharging ? "charging" : ""} ${fastAvailable ? "" : "unavailable"}"
+ type="button"
+ title=${fastTitle}
+ aria-label=${fastTitle}
+ aria-pressed=${fastOn ? "true" : "false"}
+ aria-disabled=${fastAvailable ? "false" : "true"}
+ ?disabled=${inputBlocked}
+ @click=${() => toggleFastMode(agent)}
+ >
+ ${icon(Zap, 15)}
+ <span class="fast-label">Fast</span>
+ </button>`
+ : nothing
+ }
+ `
}
+ </div>
+ <div class="composer-right">
${
- a.grantModes?.always === false
- ? nothing
- : html`<button
- class="approval-btn"
- type="button"
- ?disabled=${busy}
- @click=${() => decide({ requestId: a.requestId, approved: true, scope: "always" })}
- >
- Allow always
- </button>`
+ ctx.pane
+ ? settingsControl(agent, selectedModel, inputBlocked)
+ : html`
+ ${
+ modelToggled
+ ? html`<button
+ class="runtime-default-btn"
+ type="button"
+ aria-label="Make default"
+ data-mobile-label="Default"
+ title="Use this harness and model as the default for this scope"
+ ?disabled=${inputBlocked}
+ @click=${() => changeScopeRuntime({ harnessId: selectedModel.harnessId, modelId: selectedModel.model.id }, agent)}
+ >
+ Make default
+ </button>`
+ : nothing
+ }
+ ${
+ modelToggled && activeRuntimeConfig?.scopeOverride
+ ? html`<button
+ class="runtime-default-btn"
+ type="button"
+ aria-label="Use org default"
+ data-mobile-label="Org default"
+ ?disabled=${inputBlocked}
+ @click=${() => changeScopeRuntime({ inherit: true }, agent)}
+ >
+ Use org default
+ </button>`
+ : nothing
+ }
+ ${menuControl({
+ kind: "model",
+ label: selectedModel.buttonLabel,
+ title: "Model",
+ selected: selectedModel.value,
+ align: "right",
+ options: getModelOptionsForHarness(selectedModel.harnessId, scopeKey()).map((option) => ({
+ value: option.value,
+ label: option.label,
+ })),
+ disabled: inputBlocked,
+ onSelect: (value: string) => selectModel(value, agent),
+ })}
+ ${menuControl({
+ kind: "harness",
+ label: selectedModel.harnessLabel,
+ title: "Harness",
+ selected: selectedModel.harnessId,
+ align: "right",
+ options: getHarnessOptions(scopeKey()),
+ disabled: inputBlocked,
+ onSelect: (value: string) => selectHarness(value, agent),
+ })}
+ `
}
+ ${sendControls(agent)}
</div>
- </div>`,
- )}
- </div>`;
-}
+ </div>
+ ${composerNotice}
+ </form>
+ ${pasteViewDialog(agent)}
+ `;
+ }
-function settingsControl(agent: Agent, selected: ModelOption, disabled: boolean): TemplateResult {
- const open = composerState.openMenu === "settings";
- const fastAvailable = harnessSupportsFastMode(selected.harnessId) && modelSupportsFastMode(selected.model.id);
- const fastOn = fastAvailable && effectiveFastMode();
- const summary = `${selected.buttonLabel} · ${effortLabel(composerState.effortLevel)}${fastOn ? " · Fast" : ""}`;
- return html`
- <div class="menu-control settings-control ${open ? "open" : ""}" data-align="right">
- <button
- class="menu-button settings-button"
- type="button"
- title="Session settings — ${summary}"
- aria-label="Session settings — ${summary}"
- aria-haspopup="menu"
- aria-expanded=${open ? "true" : "false"}
- aria-controls="composer-settings-menu"
- ?disabled=${disabled}
- @click=${(e: Event) => toggleComposerMenu(e, "settings")}
+ function pasteViewDialog(agent: Agent): TemplateResult | typeof nothing {
+ const view = composerState.pasteView;
+ if (!view) return nothing;
+ return html`
+ <div
+ class="project-dialog-backdrop"
+ @click=${(e: MouseEvent) => e.target === e.currentTarget && closePasteView(agent)}
+ @keydown=${(e: KeyboardEvent) => e.key === "Escape" && closePasteView(agent)}
>
- ${icon(SlidersHorizontal, 16)}
+ <div class="project-dialog paste-dialog" role="dialog" aria-modal="true" aria-labelledby="paste-dialog-title">
+ <div class="project-dialog-head">
+ <div><h2 id="paste-dialog-title">Pasted text</h2></div>
+ <button class="chip-x" type="button" aria-label="Close" title="Close" @click=${() => closePasteView(agent)}>
+ ${icon(X, 16)}
+ </button>
+ </div>
+ <textarea
+ class="paste-dialog-text"
+ @input=${(e: InputEvent) => {
+ view.text = (e.currentTarget as HTMLTextAreaElement).value;
+ view.dirty = true;
+ }}
+ >
+ ${view.initial}</textarea>
+ <div class="project-dialog-actions">
+ <button class="btn" type="button" @click=${() => removeAttachment(view.id, agent)}>Remove</button>
+ <button class="btn" type="button" @click=${() => insertPasteIntoDraft(agent)}>Insert into message</button>
+ <button class="btn primary" type="button" @click=${() => closePasteView(agent)}>Done</button>
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
+ function openPasteView(id: string, agent: Agent): void {
+ const attachment = composerState.attachments.find((a) => a.id === id);
+ if (!attachment) return;
+ const text = attachment.extractedText ?? base64ToText(attachment.content);
+ composerState.pasteView = { id, text, initial: text, dirty: false };
+ ctx.chat.drawActiveChat(agent);
+ requestAnimationFrame(() => ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".paste-dialog-text")?.focus());
+ }
+
+ function closePasteView(agent: Agent): void {
+ const view = composerState.pasteView;
+ if (!view) return;
+ const attachment = composerState.attachments.find((a) => a.id === view.id);
+ if (attachment && view.dirty) {
+ const bytes = new TextEncoder().encode(view.text);
+ attachment.content = bytesToBase64(bytes);
+ attachment.size = bytes.length;
+ attachment.extractedText = view.text;
+ }
+ composerState.pasteView = null;
+ ctx.chat.drawActiveChat(agent);
+ }
+
+ function insertPasteIntoDraft(agent: Agent): void {
+ const view = composerState.pasteView;
+ if (!view) return;
+ const ta = ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".composer-input");
+ const { draft, cursor } = insertIntoDraft(composerState.draft, view.text, ta ? ta.selectionStart : null);
+ composerState.draft = draft;
+ persistDraft();
+ composerState.pasteView = null;
+ removeAttachment(view.id, agent);
+ resizeComposer();
+ requestAnimationFrame(() => {
+ const input = ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".composer-input");
+ if (!input) return;
+ input.focus();
+ input.setSelectionRange(cursor, cursor);
+ });
+ }
+
+ function sendControls(agent: Agent): TemplateResult {
+ if (!agent.state.isStreaming) {
+ return html`<button class="send-btn" type="submit" title="Send" ?disabled=${!composerCanSend()}>
+ ${icon(ArrowUp, 17)}
+ </button>`;
+ }
+ const canSteer = Boolean(composerState.draft.trim());
+ const steerTitle = composerState.attachments.length
+ ? "Steer the running task (attachments stay for your next message)"
+ : "Steer the running task";
+ return html`
+ <button class="stop-btn" type="button" title="Stop" aria-label="Stop" @click=${() => stopStreaming(agent)}>
+ ${icon(Square, 16)}
+ </button>
+ <button class="send-btn" type="submit" title=${steerTitle} aria-label=${steerTitle} ?disabled=${!canSteer}>
+ ${icon(ArrowUp, 17)}
</button>
- ${
- open && !disabled
- ? html`
- <div
- class="menu-popover settings-popover"
- id="composer-settings-menu"
- role="menu"
- @click=${(e: Event) => e.stopPropagation()}
+ `;
+ }
+
+ function composerApprovalPanel(approvals: PendingApproval[]): TemplateResult {
+ const busy = ctx.chat.state.resolvingApprovals.size > 0;
+ const decide = (decision: ApprovalDecision): void => {
+ if (!busy) ctx.chat.resolveCommandApproval(decision);
+ };
+ return html`<div class="composer-approval-panel" role="group" aria-label="Command approval">
+ ${approvals.map(
+ (a) =>
+ html`<div class="composer-approval">
+ <div class="composer-approval-copy">${ctx.chat.approvalSummaryView(a, true)}</div>
+ <div class="approval-actions">
+ <button
+ class="approval-btn deny"
+ type="button"
+ ?disabled=${busy}
+ @click=${() => decide({ requestId: a.requestId, approved: false })}
+ >
+ Deny
+ </button>
+ <button
+ class="approval-btn"
+ type="button"
+ ?disabled=${busy}
+ @click=${() => decide({ requestId: a.requestId, approved: true, scope: "once" })}
>
- <div class="menu-title">Model</div>
- ${getModelOptionsForHarness(selected.harnessId).map(
- (option) => html`
- <button
- class="menu-option ${option.value === selected.value ? "active" : ""}"
+ Allow once
+ </button>
+ ${
+ a.grantModes?.session === false
+ ? nothing
+ : html`<button
+ class="approval-btn primary"
type="button"
- role="menuitemradio"
- aria-checked=${option.value === selected.value ? "true" : "false"}
- @click=${() => selectModel(option.value, agent)}
+ ?disabled=${busy}
+ @click=${() => decide({ requestId: a.requestId, approved: true, scope: "session" })}
>
- <span class="menu-option-copy">
- <span class="menu-option-label">${option.label}</span>
- </span>
- ${option.value === selected.value ? icon(Check, 15) : nothing}
- </button>
- `,
- )}
- <div class="menu-title">Harness</div>
- <div class="settings-seg" role="group" aria-label="Harness">
- ${getHarnessOptions().map(
+ Allow for session
+ </button>`
+ }
+ ${
+ a.grantModes?.always === false
+ ? nothing
+ : html`<button
+ class="approval-btn"
+ type="button"
+ ?disabled=${busy}
+ @click=${() => decide({ requestId: a.requestId, approved: true, scope: "always" })}
+ >
+ Allow always
+ </button>`
+ }
+ </div>
+ </div>`,
+ )}
+ </div>`;
+ }
+
+ function settingsControl(agent: Agent, selected: ModelOption, disabled: boolean): TemplateResult {
+ const open = composerState.openMenu === "settings";
+ const fastAvailable =
+ harnessSupportsFastMode(selected.harnessId) && modelSupportsFastMode(scopeKey(), selected.model.id);
+ const fastOn = fastAvailable && effectiveFastMode();
+ const summary = `${selected.buttonLabel} · ${effortLabel(composerState.effortLevel)}${fastOn ? " · Fast" : ""}`;
+ return html`
+ <div class="menu-control settings-control ${open ? "open" : ""}" data-align="right">
+ <button
+ class="menu-button settings-button"
+ type="button"
+ title="Session settings — ${summary}"
+ aria-label="Session settings — ${summary}"
+ aria-haspopup="menu"
+ aria-expanded=${open ? "true" : "false"}
+ aria-controls="composer-settings-menu"
+ ?disabled=${disabled}
+ @click=${(e: Event) => toggleComposerMenu(e, "settings")}
+ >
+ ${icon(SlidersHorizontal, 16)}
+ </button>
+ ${
+ open && !disabled
+ ? html`
+ <div
+ class="menu-popover settings-popover"
+ id="composer-settings-menu"
+ role="menu"
+ @click=${(e: Event) => e.stopPropagation()}
+ >
+ <div class="menu-title">Model</div>
+ ${getModelOptionsForHarness(selected.harnessId, scopeKey()).map(
(option) => html`
<button
- class="settings-chip ${option.value === selected.harnessId ? "active" : ""}"
+ class="menu-option ${option.value === selected.value ? "active" : ""}"
type="button"
- aria-pressed=${option.value === selected.harnessId ? "true" : "false"}
- @click=${() => selectHarness(option.value, agent)}
+ role="menuitemradio"
+ aria-checked=${option.value === selected.value ? "true" : "false"}
+ @click=${() => selectModel(option.value, agent)}
>
- ${option.label}
+ <span class="menu-option-copy">
+ <span class="menu-option-label">${option.label}</span>
+ </span>
+ ${option.value === selected.value ? icon(Check, 15) : nothing}
</button>
`,
)}
- </div>
- ${
- harnessSupportsEffort(selected.harnessId)
- ? html`
- <div class="menu-title">Effort</div>
- <div class="settings-seg" role="group" aria-label="Effort">
- ${EFFORT_LEVELS.map(
- (option) => html`
- <button
- class="settings-chip ${option.value === composerState.effortLevel ? "active" : ""}"
- type="button"
- aria-pressed=${option.value === composerState.effortLevel ? "true" : "false"}
- @click=${() => selectEffort(option.value, agent)}
- >
- ${option.label}
- </button>
- `,
- )}
- </div>
- `
- : nothing
- }
- ${
- fastAvailable
- ? html`
+ <div class="menu-title">Harness</div>
+ <div class="settings-seg" role="group" aria-label="Harness">
+ ${getHarnessOptions(scopeKey()).map(
+ (option) => html`
<button
- class="menu-option ${fastOn ? "active" : ""}"
+ class="settings-chip ${option.value === selected.harnessId ? "active" : ""}"
type="button"
- role="menuitemcheckbox"
- aria-checked=${fastOn ? "true" : "false"}
- @click=${() => toggleFastMode(agent)}
+ aria-pressed=${option.value === selected.harnessId ? "true" : "false"}
+ @click=${() => selectHarness(option.value, agent)}
>
- <span class="menu-option-copy">
- <span class="menu-option-label">${icon(Zap, 13)} Fast mode</span>
- </span>
- ${fastOn ? icon(Check, 15) : nothing}
+ ${option.label}
</button>
- `
- : nothing
- }
- </div>
- `
- : nothing
- }
- </div>
- `;
-}
-
-function menuControl(args: {
- kind: ComposerMenu;
- glyph?: IconNode;
- label: string;
- title: string;
- selected: string;
- options: Array<{ value: string; label: string }>;
- disabled?: boolean;
- align?: "left" | "right";
- onSelect: (value: string) => void;
-}): TemplateResult {
- const open = composerState.openMenu === args.kind;
- const menuId = `composer-${args.kind}-menu`;
- let controlClass = "";
- if (args.kind === "model") controlClass = "model-control";
- else if (args.kind === "harness") controlClass = "harness-control";
- return html`
- <div class="menu-control ${controlClass}" data-align=${args.align ?? "left"}>
- <button
- class="menu-button"
- type="button"
- title=${args.title}
- aria-haspopup="menu"
- aria-expanded=${open ? "true" : "false"}
- aria-controls=${menuId}
- ?disabled=${args.disabled}
- @click=${(e: Event) => toggleComposerMenu(e, args.kind)}
- >
- ${args.glyph ? icon(args.glyph, 16) : nothing}
- <span class="menu-label">${args.label}</span>
- ${icon(ChevronDown, 14)}
- </button>
- ${
- open && !args.disabled
- ? html`
- <div class="menu-popover" id=${menuId} role="menu" @click=${(e: Event) => e.stopPropagation()}>
- <div class="menu-title">${args.title}</div>
- ${args.options.map(
- (option) => html`
- <button
- class="menu-option ${option.value === args.selected ? "active" : ""}"
- type="button"
- role="menuitemradio"
- aria-checked=${option.value === args.selected ? "true" : "false"}
- @click=${() => args.onSelect(option.value)}
- >
- <span class="menu-option-copy">
- <span class="menu-option-label">${option.label}</span>
- </span>
- ${option.value === args.selected ? icon(Check, 15) : nothing}
- </button>
- `,
- )}
- </div>
- `
- : nothing
- }
- </div>
- `;
-}
-
-function toggleComposerMenu(e: Event, kind: ComposerMenu): void {
- e.stopPropagation();
- composerState.openMenu = composerState.openMenu === kind ? null : kind;
- drawActiveChat();
-}
-
-const SLASH_TOKEN = /(^|\s)\/([a-zA-Z0-9_-]*)$/;
+ `,
+ )}
+ </div>
+ ${
+ harnessSupportsEffort(selected.harnessId)
+ ? html`
+ <div class="menu-title">Effort</div>
+ <div class="settings-seg" role="group" aria-label="Effort">
+ ${EFFORT_LEVELS.map(
+ (option) => html`
+ <button
+ class="settings-chip ${option.value === composerState.effortLevel ? "active" : ""}"
+ type="button"
+ aria-pressed=${option.value === composerState.effortLevel ? "true" : "false"}
+ @click=${() => selectEffort(option.value, agent)}
+ >
+ ${option.label}
+ </button>
+ `,
+ )}
+ </div>
+ `
+ : nothing
+ }
+ ${
+ fastAvailable
+ ? html`
+ <button
+ class="menu-option ${fastOn ? "active" : ""}"
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked=${fastOn ? "true" : "false"}
+ @click=${() => toggleFastMode(agent)}
+ >
+ <span class="menu-option-copy">
+ <span class="menu-option-label">${icon(Zap, 13)} Fast mode</span>
+ </span>
+ ${fastOn ? icon(Check, 15) : nothing}
+ </button>
+ `
+ : nothing
+ }
+ </div>
+ `
+ : nothing
+ }
+ </div>
+ `;
+ }
-export function slashQuery(draft: string): string | null {
- const m = draft.match(SLASH_TOKEN);
- return m ? (m[2] ?? "") : null;
-}
+ function menuControl(args: {
+ kind: ComposerMenu;
+ glyph?: IconNode;
+ label: string;
+ title: string;
+ selected: string;
+ options: Array<{ value: string; label: string }>;
+ disabled?: boolean;
+ align?: "left" | "right";
+ onSelect: (value: string) => void;
+ }): TemplateResult {
+ const open = composerState.openMenu === args.kind;
+ const menuId = `composer-${args.kind}-menu`;
+ let controlClass = "";
+ if (args.kind === "model") controlClass = "model-control";
+ else if (args.kind === "harness") controlClass = "harness-control";
+ return html`
+ <div class="menu-control ${controlClass}" data-align=${args.align ?? "left"}>
+ <button
+ class="menu-button"
+ type="button"
+ title=${args.title}
+ aria-haspopup="menu"
+ aria-expanded=${open ? "true" : "false"}
+ aria-controls=${menuId}
+ ?disabled=${args.disabled}
+ @click=${(e: Event) => toggleComposerMenu(e, args.kind)}
+ >
+ ${args.glyph ? icon(args.glyph, 16) : nothing}
+ <span class="menu-label">${args.label}</span>
+ ${icon(ChevronDown, 14)}
+ </button>
+ ${
+ open && !args.disabled
+ ? html`
+ <div class="menu-popover" id=${menuId} role="menu" @click=${(e: Event) => e.stopPropagation()}>
+ <div class="menu-title">${args.title}</div>
+ ${args.options.map(
+ (option) => html`
+ <button
+ class="menu-option ${option.value === args.selected ? "active" : ""}"
+ type="button"
+ role="menuitemradio"
+ aria-checked=${option.value === args.selected ? "true" : "false"}
+ @click=${() => args.onSelect(option.value)}
+ >
+ <span class="menu-option-copy">
+ <span class="menu-option-label">${option.label}</span>
+ </span>
+ ${option.value === args.selected ? icon(Check, 15) : nothing}
+ </button>
+ `,
+ )}
+ </div>
+ `
+ : nothing
+ }
+ </div>
+ `;
+ }
-function matchSkills(query: string, skills: SkillItem[]): SkillMatch[] {
- const q = query.toLowerCase();
- if (!q) return skills.map((skill) => ({ skill, start: -1, end: -1 }));
- const out: SkillMatch[] = [];
- for (const skill of skills) {
- const at = skill.name.toLowerCase().indexOf(q);
- if (at >= 0) out.push({ skill, start: at, end: at + q.length });
+ function toggleComposerMenu(e: Event, kind: ComposerMenu): void {
+ e.stopPropagation();
+ composerState.openMenu = composerState.openMenu === kind ? null : kind;
+ ctx.chat.drawActiveChat();
}
- return out.sort((a, b) => a.start - b.start || a.skill.name.localeCompare(b.skill.name));
-}
-function currentSlashMenu(): { open: boolean; loading: boolean; matches: SkillMatch[] } {
- const query = slashQuery(composerState.draft);
- if (query === null || composerState.slashDismissed) return { open: false, loading: false, matches: [] };
- const loading = skillsLoading;
- const matches = composerState.skillsCache ? matchSkills(query, composerState.skillsCache) : [];
- return { open: loading || matches.length > 0, loading, matches };
-}
+ function matchSkills(query: string, skills: SkillItem[]): SkillMatch[] {
+ const q = query.toLowerCase();
+ if (!q) return skills.map((skill) => ({ skill, start: -1, end: -1 }));
+ const out: SkillMatch[] = [];
+ for (const skill of skills) {
+ const at = skill.name.toLowerCase().indexOf(q);
+ if (at >= 0) out.push({ skill, start: at, end: at + q.length });
+ }
+ return out.sort((a, b) => a.start - b.start || a.skill.name.localeCompare(b.skill.name));
+ }
-function clampedActive(matchCount: number): number {
- return Math.max(0, Math.min(slashActiveIndex, matchCount - 1));
-}
+ function currentSlashMenu(): { open: boolean; loading: boolean; matches: SkillMatch[] } {
+ const query = slashQuery(composerState.draft);
+ if (query === null || composerState.slashDismissed) return { open: false, loading: false, matches: [] };
+ const loading = skillsLoading;
+ const matches = skillsCache ? matchSkills(query, skillsCache) : [];
+ return { open: loading || matches.length > 0, loading, matches };
+ }
-async function loadSkills(agent: Agent): Promise<void> {
- if (skillsLoading || composerState.skillsCache !== null) return;
- skillsLoading = true;
- drawActiveChat(agent);
- try {
- const r = await api<{ skills: SkillItem[] }>("/api/skills");
- composerState.skillsCache = r.skills ?? [];
- } catch {
- composerState.skillsCache = null;
- } finally {
- skillsLoading = false;
- if (agent === chatState.agent) drawActiveChat(agent);
+ function clampedActive(matchCount: number): number {
+ return Math.max(0, Math.min(slashActiveIndex, matchCount - 1));
}
-}
-function acceptSkill(skill: SkillItem, agent: Agent): void {
- composerState.draft = composerState.draft.replace(SLASH_TOKEN, (_m, pre: string) => `${pre}/${skill.name} `);
- persistDraft();
- slashActiveIndex = 0;
- composerState.slashDismissed = false;
- drawActiveChat(agent);
- focusComposerEnd();
-}
+ async function loadSkills(agent: Agent): Promise<void> {
+ if (skillsLoading || skillsCache !== null) return;
+ skillsLoading = true;
+ ctx.chat.drawActiveChat(agent);
+ try {
+ const r = await api<{ skills: SkillItem[] }>("/api/skills");
+ skillsCache = r.skills ?? [];
+ } catch {
+ skillsCache = null;
+ } finally {
+ skillsLoading = false;
+ if (agent === ctx.chat.state.agent) ctx.chat.drawActiveChat(agent);
+ }
+ }
-let pendingComposerFocus = false;
+ function acceptSkill(skill: SkillItem, agent: Agent): void {
+ composerState.draft = composerState.draft.replace(SLASH_TOKEN, (_m, pre: string) => `${pre}/${skill.name} `);
+ persistDraft();
+ slashActiveIndex = 0;
+ composerState.slashDismissed = false;
+ ctx.chat.drawActiveChat(agent);
+ focusComposerEnd();
+ }
-export function focusComposerEnd(): void {
- requestAnimationFrame(() => {
- const ta = chatState.host?.querySelector<HTMLTextAreaElement>(".composer-input");
- if (!ta) return;
- if (ta.disabled) {
- pendingComposerFocus = true;
- return;
- }
- pendingComposerFocus = false;
- ta.focus();
- ta.setSelectionRange(ta.value.length, ta.value.length);
- });
-}
+ let pendingComposerFocus = false;
-function closeSlashMenu(agent: Agent): void {
- composerState.slashDismissed = true;
- drawActiveChat(agent);
-}
+ function focusComposerEnd(): void {
+ requestAnimationFrame(() => {
+ const ta = ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".composer-input");
+ if (!ta) return;
+ if (ta.disabled) {
+ pendingComposerFocus = true;
+ return;
+ }
+ pendingComposerFocus = false;
+ ta.focus();
+ ta.setSelectionRange(ta.value.length, ta.value.length);
+ });
+ }
-function slashMenu(agent: Agent): TemplateResult | typeof nothing {
- const slash = currentSlashMenu();
- if (!slash.open) return nothing;
- if (slash.loading && slash.matches.length === 0) {
- return html`<div class="slash-popover">
- <div class="menu-title">Skills</div>
- <div class="slash-empty">Loading skills…</div>
- </div>`;
+ function closeSlashMenu(agent: Agent): void {
+ composerState.slashDismissed = true;
+ ctx.chat.drawActiveChat(agent);
}
- const active = clampedActive(slash.matches.length);
- return html`
- <div class="slash-popover" role="listbox" aria-label="Skills">
- <div class="menu-title">Skills</div>
- ${slash.matches.map((m, i) => slashRow(m, i === active, agent))}
- </div>
- `;
-}
-function slashRow(m: SkillMatch, active: boolean, agent: Agent): TemplateResult {
- return html`
- <button
- type="button"
- role="option"
- aria-selected=${active ? "true" : "false"}
- class="slash-option ${active ? "active" : ""}"
- title=${m.skill.description}
- @mousedown=${(e: Event) => e.preventDefault()}
- @click=${() => acceptSkill(m.skill, agent)}
- >
- <span class="slash-icon">${icon(Box, 16)}</span>
- <span class="slash-name">${highlightName(m)}</span>
- <span class="slash-desc">${m.skill.description}</span>
- <span class="slash-scope">${scopeBadge(m.skill.scope)}</span>
- </button>
- `;
-}
+ function slashMenu(agent: Agent): TemplateResult | typeof nothing {
+ const slash = currentSlashMenu();
+ if (!slash.open) return nothing;
+ if (slash.loading && slash.matches.length === 0) {
+ return html`<div class="slash-popover">
+ <div class="menu-title">Skills</div>
+ <div class="slash-empty">Loading skills…</div>
+ </div>`;
+ }
+ const active = clampedActive(slash.matches.length);
+ return html`
+ <div class="slash-popover" role="listbox" aria-label="Skills">
+ <div class="menu-title">Skills</div>
+ ${slash.matches.map((m, i) => slashRow(m, i === active, agent))}
+ </div>
+ `;
+ }
-function highlightName(m: SkillMatch): TemplateResult {
- const { name } = m.skill;
- if (m.start < 0 || m.end <= m.start) return html`${name}`;
- return html`${name.slice(0, m.start)}<b>${name.slice(m.start, m.end)}</b>${name.slice(m.end)}`;
-}
+ function slashRow(m: SkillMatch, active: boolean, agent: Agent): TemplateResult {
+ return html`
+ <button
+ type="button"
+ role="option"
+ aria-selected=${active ? "true" : "false"}
+ class="slash-option ${active ? "active" : ""}"
+ title=${m.skill.description}
+ @mousedown=${(e: Event) => e.preventDefault()}
+ @click=${() => acceptSkill(m.skill, agent)}
+ >
+ <span class="slash-icon">${icon(Box, 16)}</span>
+ <span class="slash-name">${highlightName(m)}</span>
+ <span class="slash-desc">${m.skill.description}</span>
+ <span class="slash-scope">${scopeBadge(m.skill.scope)}</span>
+ </button>
+ `;
+ }
-function scopeBadge(scope: string): string {
- return scope ? scope.charAt(0).toUpperCase() + scope.slice(1) : "";
-}
+ function highlightName(m: SkillMatch): TemplateResult {
+ const { name } = m.skill;
+ if (m.start < 0 || m.end <= m.start) return html`${name}`;
+ return html`${name.slice(0, m.start)}<b>${name.slice(m.start, m.end)}</b>${name.slice(m.end)}`;
+ }
-function submitComposer(e: Event, agent: Agent): void {
- e.preventDefault();
- void sendPrompt(agent);
-}
+ function scopeBadge(scope: string): string {
+ return scope ? scope.charAt(0).toUpperCase() + scope.slice(1) : "";
+ }
-function onDraftInput(e: InputEvent, agent: Agent): void {
- composerState.draft = (e.currentTarget as HTMLTextAreaElement).value;
- persistDraft();
- const hadError = Boolean(composerState.error);
- composerState.error = "";
- composerState.slashDismissed = false;
- slashActiveIndex = 0;
- const armed = slashQuery(composerState.draft) !== null;
- if (armed && composerState.skillsCache === null && !skillsLoading) void loadSkills(agent);
- const popoverShown = Boolean(chatState.host?.querySelector(".slash-popover"));
- if (armed || popoverShown || hadError) {
- drawActiveChat(agent);
- return;
- }
- syncComposerControls(agent);
- resizeComposer();
-}
+ function submitComposer(e: Event, agent: Agent): void {
+ e.preventDefault();
+ void sendPrompt(agent);
+ }
-function composerCanSend(): boolean {
- return (
- Boolean(composerState.draft.trim() || composerState.attachments.length) &&
- !composerState.processingFiles &&
- activeRuntimeConfig !== null &&
- chatState.resolvingApprovals.size === 0 &&
- !hasUnresolvedApproval()
- );
-}
+ function onDraftInput(e: InputEvent, agent: Agent): void {
+ composerState.draft = (e.currentTarget as HTMLTextAreaElement).value;
+ persistDraft();
+ const hadError = Boolean(composerState.error);
+ composerState.error = "";
+ composerState.slashDismissed = false;
+ slashActiveIndex = 0;
+ const armed = slashQuery(composerState.draft) !== null;
+ if (armed && skillsCache === null && !skillsLoading) void loadSkills(agent);
+ const popoverShown = Boolean(ctx.chat.state.host?.querySelector(".slash-popover"));
+ if (armed || popoverShown || hadError) {
+ ctx.chat.drawActiveChat(agent);
+ return;
+ }
+ syncComposerControls(agent);
+ resizeComposer();
+ }
-function syncComposerControls(agent: Agent): void {
- if (!chatState.host || agent !== chatState.agent) return;
- const send = chatState.host.querySelector<HTMLButtonElement>(".send-btn");
- if (send) send.disabled = agent.state.isStreaming ? !composerState.draft.trim() : !composerCanSend();
-}
+ function composerCanSend(): boolean {
+ return (
+ Boolean(composerState.draft.trim() || composerState.attachments.length) &&
+ !composerState.processingFiles &&
+ activeRuntimeConfig !== null &&
+ ctx.chat.state.resolvingApprovals.size === 0 &&
+ !ctx.chat.hasUnresolvedApproval()
+ );
+ }
-function clearComposerDom(agent: Agent): void {
- if (!chatState.host || agent !== chatState.agent) return;
- const input = chatState.host.querySelector<HTMLTextAreaElement>(".composer-input");
- if (input) {
- input.value = "";
- input.style.height = "auto";
- input.style.overflowY = "hidden";
- input.scrollTop = 0;
+ function syncComposerControls(agent: Agent): void {
+ if (!ctx.chat.state.host || agent !== ctx.chat.state.agent) return;
+ const send = ctx.chat.state.host.querySelector<HTMLButtonElement>(".send-btn");
+ if (send) send.disabled = agent.state.isStreaming ? !composerState.draft.trim() : !composerCanSend();
}
- const send = chatState.host.querySelector<HTMLButtonElement>(".send-btn");
- if (send) send.disabled = true;
-}
-function onComposerKeydown(e: KeyboardEvent, agent: Agent): void {
- const slash = currentSlashMenu();
- if (slash.open) {
- if (e.key === "Escape") {
- e.preventDefault();
- return closeSlashMenu(agent);
+ function clearComposerDom(agent: Agent): void {
+ if (!ctx.chat.state.host || agent !== ctx.chat.state.agent) return;
+ const input = ctx.chat.state.host.querySelector<HTMLTextAreaElement>(".composer-input");
+ if (input) {
+ input.value = "";
+ input.style.height = "auto";
+ input.style.overflowY = "hidden";
+ input.scrollTop = 0;
}
- if (slash.matches.length) {
- const count = slash.matches.length;
- if (e.key === "ArrowDown") {
- e.preventDefault();
- slashActiveIndex = (clampedActive(count) + 1) % count;
- return drawActiveChat(agent);
- }
- if (e.key === "ArrowUp") {
+ const send = ctx.chat.state.host.querySelector<HTMLButtonElement>(".send-btn");
+ if (send) send.disabled = true;
+ }
+
+ function onComposerKeydown(e: KeyboardEvent, agent: Agent): void {
+ const slash = currentSlashMenu();
+ if (slash.open) {
+ if (e.key === "Escape") {
e.preventDefault();
- slashActiveIndex = (clampedActive(count) - 1 + count) % count;
- return drawActiveChat(agent);
+ return closeSlashMenu(agent);
}
- if (!e.shiftKey && (e.key === "Enter" || e.key === "Tab")) {
+ if (slash.matches.length) {
+ const count = slash.matches.length;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ slashActiveIndex = (clampedActive(count) + 1) % count;
+ return ctx.chat.drawActiveChat(agent);
+ }
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ slashActiveIndex = (clampedActive(count) - 1 + count) % count;
+ return ctx.chat.drawActiveChat(agent);
+ }
+ if (!e.shiftKey && (e.key === "Enter" || e.key === "Tab")) {
+ e.preventDefault();
+ return acceptSkill(slash.matches[clampedActive(count)]!.skill, agent);
+ }
+ } else if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
- return acceptSkill(slash.matches[clampedActive(count)]!.skill, agent);
+ return;
}
- } else if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
+ }
+ if (e.key !== "Enter" || e.shiftKey) return;
+ e.preventDefault();
+ void sendPrompt(agent);
+ }
+
+ function stopStreaming(agent: Agent): void {
+ void ctx.chat.signalLiveRun("abort").catch((e) => swallow("web-ui: abort signal", e));
+ agent.abort();
+ }
+
+ async function sendSteer(agent: Agent): Promise<void> {
+ const text = composerState.draft.trim();
+ if (!text) return;
+ if (ctx.chat.state.threadRef) bumpSessionActivity(ctx.chat.state.threadRef);
+ clearActiveDraft();
+ composerState.draft = "";
+ composerState.error = "";
+ agent.state.messages.push({
+ role: "user",
+ content: text,
+ timestamp: Date.now(),
+ steered: true,
+ } as unknown as AgentMessage);
+ ctx.chat.drawActiveChat(agent);
+ clearComposerDom(agent);
+ if (!ctx.chat.hasLiveRun()) {
+ // The turn is between run states: submitted but /api/turn hasn't returned the
+ // run id yet, or the stream is tearing down. Dropping the message here is a
+ // silent no-op the user reads as a dead composer — hold it and deliver when
+ // the run slot settles (steer the live run, or resend as an ordinary prompt).
+ steerWhenLive(agent, text, 0);
return;
}
+ await deliverSteer(agent, text);
}
- if (e.key !== "Enter" || e.shiftKey) return;
- e.preventDefault();
- void sendPrompt(agent);
-}
-function stopStreaming(agent: Agent): void {
- void signalLiveRun("abort").catch((e) => swallow("web-ui: abort signal", e));
- agent.abort();
-}
+ async function deliverSteer(agent: Agent, text: string): Promise<void> {
+ try {
+ const outcome = await ctx.chat.signalLiveRun("steer", text);
+ if (!outcome.ok) recoverEndedRunSteer(agent, text, outcome);
+ } catch (err) {
+ composerState.error = errMessage(err, "Could not steer the running task.");
+ ctx.chat.drawActiveChat(agent);
+ }
+ }
-async function sendSteer(agent: Agent): Promise<void> {
- const text = composerState.draft.trim();
- if (!text || !hasLiveRun()) return;
- if (chatState.threadRef) bumpSessionActivity(chatState.threadRef);
- clearActiveDraft();
- composerState.draft = "";
- composerState.error = "";
- agent.state.messages.push({
- role: "user",
- content: text,
- timestamp: Date.now(),
- steered: true,
- } as unknown as AgentMessage);
- drawActiveChat(agent);
- clearComposerDom(agent);
- try {
- await signalLiveRun("steer", text);
- } catch (err) {
- composerState.error = errMessage(err, "Could not steer the running task.");
- drawActiveChat(agent);
+ function steerWhenLive(agent: Agent, text: string, attempt: number): void {
+ if (agent !== ctx.chat.state.agent) return;
+ if (ctx.chat.hasLiveRun()) {
+ void deliverSteer(agent, text);
+ return;
+ }
+ if (!agent.state.isStreaming) {
+ // The run ended without the slot ever going live — recover exactly like a
+ // steer that raced the run's end: resend the text as an ordinary prompt.
+ recoverEndedRunSteer(agent, text, {});
+ return;
+ }
+ if (attempt < 40) {
+ window.setTimeout(() => steerWhenLive(agent, text, attempt + 1), 250);
+ return;
+ }
+ const last = agent.state.messages[agent.state.messages.length - 1] as
+ { role?: string; content?: unknown } | undefined;
+ if (last?.role === "user" && last.content === text) agent.state.messages.pop();
+ // Don't clobber anything typed while the message was held: put the held text
+ // back in front of the newer draft instead of overwriting it.
+ composerState.draft = composerState.draft.trim() ? `${text}\n\n${composerState.draft}` : text;
+ composerState.error = "Could not deliver the message — the running task never settled. It is back in the composer.";
+ ctx.chat.drawActiveChat(agent);
}
-}
-async function sendPrompt(agent: Agent): Promise<void> {
- if (composerState.processingFiles) return;
- if (!activeRuntimeConfig && !agent.state.isStreaming) return;
- if (composerState.pasteView) closePasteView(agent);
- if (chatState.resolvingApprovals.size > 0) return;
- if (hasUnresolvedApproval()) return;
- if (agent.state.isStreaming) return sendSteer(agent);
- const text = composerState.draft.trim();
- if (!text && composerState.attachments.length === 0) return;
- if (chatState.threadRef) {
- bumpSessionActivity(chatState.threadRef);
- chatState.pendingSend = chatState.threadRef;
- renderList();
- }
- const attachments = composerState.attachments;
- notePendingSessionOnSend();
- clearActiveDraft();
- resetComposer();
- drawActiveChat(agent);
- clearComposerDom(agent);
- try {
- if (attachments.length) {
- await agent.prompt({ role: "user-with-attachments", content: text, attachments, timestamp: Date.now() });
- } else {
- await agent.prompt(text);
+ // The run ended before the steer landed (the client believed it was still live).
+ // Core either replayed the text as a fresh turn (`replayed`) or never stored it.
+ // Either way the message must not silently vanish: detach from the stale stream,
+ // then attach to the replay run — or resend the text as an ordinary prompt.
+ function recoverEndedRunSteer(agent: Agent, text: string, outcome: { replayed?: boolean }): void {
+ agent.abort();
+ if (outcome.replayed) {
+ const last = agent.state.messages[agent.state.messages.length - 1] as
+ { role?: string; content?: unknown; steered?: boolean } | undefined;
+ // It is now an ordinary user turn in the transcript, not a mid-run steer.
+ if (last?.role === "user" && last.content === text && last.steered) delete last.steered;
+ ctx.chat.drawActiveChat(agent);
+ attachWhenIdle(agent, 0);
+ return;
}
- } catch (err) {
- chatState.pendingSend = null;
- if (chatState.threadRef && chatState.sessionId === null) dropPendingSession(chatState.threadRef);
- renderList();
- composerState.error = errMessage(err, "Could not send message.");
- drawActiveChat(agent);
+ const last = agent.state.messages[agent.state.messages.length - 1] as
+ { role?: string; content?: unknown } | undefined;
+ if (last?.role === "user" && last.content === text) agent.state.messages.pop();
+ composerState.draft = text;
+ ctx.chat.drawActiveChat(agent);
+ resendWhenIdle(agent, text, 0);
}
-}
-const LARGE_PASTE_CHARS = 2000;
+ function attachWhenIdle(agent: Agent, attempt: number): void {
+ if (agent !== ctx.chat.state.agent) return;
+ if (agent.state.isStreaming) {
+ if (attempt < 20) window.setTimeout(() => attachWhenIdle(agent, attempt + 1), 250);
+ return;
+ }
+ ctx.chat.resumeIfIdle();
+ }
-async function onComposerPaste(e: ClipboardEvent, agent: Agent): Promise<void> {
- const data = e.clipboardData;
- if (!data) return;
- const files = Array.from(data.items)
- .filter((item) => item.kind === "file")
- .map((item) => item.getAsFile())
- .filter((file): file is File => file !== null);
- if (files.length) {
- e.preventDefault();
- await addFiles(files, agent);
- return;
- }
- const text = data.getData("text/plain");
- if (text.length <= LARGE_PASTE_CHARS) return;
- if (
- hasUnresolvedApproval() ||
- chatState.resolvingApprovals.size > 0 ||
- agent.state.isStreaming ||
- composerState.processingFiles
- )
- return;
- e.preventDefault();
- const names = new Set(composerState.attachments.map((a) => a.fileName));
- let n = 1;
- while (names.has(n === 1 ? "pasted-text.txt" : `pasted-text-${n}.txt`)) n++;
- const bytes = new TextEncoder().encode(text);
- const attachment: Attachment = {
- id: `paste_${Date.now()}_${Math.random()}`,
- type: "document",
- fileName: n === 1 ? "pasted-text.txt" : `pasted-text-${n}.txt`,
- mimeType: "text/plain",
- size: bytes.length,
- content: bytesToBase64(bytes),
- extractedText: text,
- };
- pastedTextIds.add(attachment.id);
- composerState.attachments = [...composerState.attachments, attachment];
- drawActiveChat(agent);
-}
+ function resendWhenIdle(agent: Agent, text: string, attempt: number): void {
+ if (agent !== ctx.chat.state.agent) return;
+ if (agent.state.isStreaming) {
+ if (attempt < 20) window.setTimeout(() => resendWhenIdle(agent, text, attempt + 1), 250);
+ else {
+ composerState.error =
+ "Could not deliver the message — the running task ended mid-send. It is back in the composer.";
+ ctx.chat.drawActiveChat(agent);
+ }
+ return;
+ }
+ if (composerState.draft === text) void sendPrompt(agent);
+ }
-async function onFilesSelected(e: Event, agent: Agent): Promise<void> {
- const input = e.currentTarget as HTMLInputElement;
- const files = Array.from(input.files ?? []);
- input.value = "";
- await addFiles(files, agent);
-}
+ async function sendPrompt(agent: Agent): Promise<void> {
+ if (composerState.processingFiles) return;
+ if (!activeRuntimeConfig && !agent.state.isStreaming) return;
+ if (composerState.pasteView) closePasteView(agent);
+ if (ctx.chat.state.resolvingApprovals.size > 0) return;
+ if (ctx.chat.hasUnresolvedApproval()) return;
+ if (agent.state.isStreaming) return sendSteer(agent);
+ const text = composerState.draft.trim();
+ if (!text && composerState.attachments.length === 0) return;
+ if (ctx.chat.state.threadRef) {
+ bumpSessionActivity(ctx.chat.state.threadRef);
+ ctx.chat.state.pendingSend = ctx.chat.state.threadRef;
+ renderList();
+ }
+ const attachments = composerState.attachments;
+ ctx.chat.notePendingSessionOnSend();
+ clearActiveDraft();
+ resetComposer();
+ ctx.chat.drawActiveChat(agent);
+ clearComposerDom(agent);
+ try {
+ if (attachments.length) {
+ await agent.prompt({ role: "user-with-attachments", content: text, attachments, timestamp: Date.now() });
+ } else {
+ await agent.prompt(text);
+ }
+ } catch (err) {
+ ctx.chat.state.pendingSend = null;
+ if (ctx.chat.state.threadRef && ctx.chat.state.sessionId === null) dropPendingSession(ctx.chat.state.threadRef);
+ renderList();
+ composerState.error = errMessage(err, "Could not send message.");
+ ctx.chat.drawActiveChat(agent);
+ }
+ }
-async function fileToBase64(file: File): Promise<string> {
- return bytesToBase64(new Uint8Array(await file.arrayBuffer()));
-}
+ const LARGE_PASTE_CHARS = 2000;
-async function loadAnyAttachment(file: File): Promise<Attachment> {
- try {
- const { loadAttachment } = await import("@earendil-works/pi-web-ui");
- return await loadAttachment(file);
- } catch {
- return {
- id: `${file.name}_${Date.now()}_${Math.random()}`,
+ async function onComposerPaste(e: ClipboardEvent, agent: Agent): Promise<void> {
+ const data = e.clipboardData;
+ if (!data) return;
+ const files = Array.from(data.items)
+ .filter((item) => item.kind === "file")
+ .map((item) => item.getAsFile())
+ .filter((file): file is File => file !== null);
+ if (files.length) {
+ e.preventDefault();
+ await addFiles(files, agent);
+ return;
+ }
+ const text = data.getData("text/plain");
+ if (text.length <= LARGE_PASTE_CHARS) return;
+ if (ctx.chat.hasUnresolvedApproval() || ctx.chat.state.resolvingApprovals.size > 0 || composerState.processingFiles)
+ return;
+ e.preventDefault();
+ const names = new Set(composerState.attachments.map((a) => a.fileName));
+ let n = 1;
+ while (names.has(n === 1 ? "pasted-text.txt" : `pasted-text-${n}.txt`)) n++;
+ const bytes = new TextEncoder().encode(text);
+ const attachment: Attachment = {
+ id: `paste_${Date.now()}_${Math.random()}`,
type: "document",
- fileName: file.name,
- mimeType: file.type || "application/octet-stream",
- size: file.size,
- content: await fileToBase64(file),
+ fileName: n === 1 ? "pasted-text.txt" : `pasted-text-${n}.txt`,
+ mimeType: "text/plain",
+ size: bytes.length,
+ content: bytesToBase64(bytes),
+ extractedText: text,
};
+ pastedTextIds.add(attachment.id);
+ composerState.attachments = [...composerState.attachments, attachment];
+ ctx.chat.drawActiveChat(agent);
}
-}
-async function addFiles(files: File[], agent: Agent, folders: DropEntryLike[] = []): Promise<void> {
- if (
- (!files.length && !folders.length) ||
- hasUnresolvedApproval() ||
- chatState.resolvingApprovals.size > 0 ||
- agent.state.isStreaming
- )
- return;
- if (composerState.processingFiles) {
- composerState.error = "Still preparing the previous drop — try again in a moment.";
- drawActiveChat(agent);
- return;
- }
- composerState.processingFiles = true;
- composerState.error = "";
- drawActiveChat(agent);
- try {
- const zipped: File[] = [];
- for (const folder of folders) zipped.push(await folderToZipFile(folder));
- const loaded = await Promise.all([...files, ...zipped].map((file) => loadAnyAttachment(file)));
- composerState.attachments = [...composerState.attachments, ...loaded];
- } catch (err) {
- if (err instanceof FolderDropError) composerState.error = err.message;
- else if (isFolderReadError(err))
- composerState.error =
- "That drop included a folder this browser can't read — zip it and drop the archive instead.";
- else composerState.error = errMessage(err, "Could not attach that file.");
- } finally {
- composerState.processingFiles = false;
- drawActiveChat(agent);
+ async function onFilesSelected(e: Event, agent: Agent): Promise<void> {
+ const input = e.currentTarget as HTMLInputElement;
+ const files = Array.from(input.files ?? []);
+ input.value = "";
+ await addFiles(files, agent);
}
-}
-function dragHasFiles(e: DragEvent): boolean {
- const types = e.dataTransfer?.types;
- return types ? Array.from(types).includes("Files") : false;
-}
+ async function fileToBase64(file: File): Promise<string> {
+ return bytesToBase64(new Uint8Array(await file.arrayBuffer()));
+ }
-export function onDragEnter(e: DragEvent): void {
- if (!dragHasFiles(e)) return;
- e.preventDefault();
- dragDepth += 1;
- if (!composerState.dragging) {
- composerState.dragging = true;
- drawActiveChat();
+ async function loadAnyAttachment(file: File): Promise<Attachment> {
+ try {
+ const { loadAttachment } = await import("@earendil-works/pi-web-ui");
+ return await loadAttachment(file);
+ } catch {
+ return {
+ id: `${file.name}_${Date.now()}_${Math.random()}`,
+ type: "document",
+ fileName: file.name,
+ mimeType: file.type || "application/octet-stream",
+ size: file.size,
+ content: await fileToBase64(file),
+ };
+ }
}
-}
-export function onDragOver(e: DragEvent): void {
- if (!dragHasFiles(e)) return;
- e.preventDefault();
- if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
-}
+ async function addFiles(files: File[], agent: Agent, folders: DropEntryLike[] = []): Promise<void> {
+ if (
+ (!files.length && !folders.length) ||
+ ctx.chat.hasUnresolvedApproval() ||
+ ctx.chat.state.resolvingApprovals.size > 0
+ )
+ return;
+ if (composerState.processingFiles) {
+ composerState.error = "Still preparing the previous drop — try again in a moment.";
+ ctx.chat.drawActiveChat(agent);
+ return;
+ }
+ composerState.processingFiles = true;
+ composerState.error = "";
+ ctx.chat.drawActiveChat(agent);
+ try {
+ const zipped: File[] = [];
+ for (const folder of folders) zipped.push(await folderToZipFile(folder));
+ const loaded = await Promise.all([...files, ...zipped].map((file) => loadAnyAttachment(file)));
+ composerState.attachments = [...composerState.attachments, ...loaded];
+ } catch (err) {
+ if (err instanceof FolderDropError) composerState.error = err.message;
+ else if (isFolderReadError(err))
+ composerState.error =
+ "That drop included a folder this browser can't read — zip it and drop the archive instead.";
+ else composerState.error = errMessage(err, "Could not attach that file.");
+ } finally {
+ composerState.processingFiles = false;
+ ctx.chat.drawActiveChat(agent);
+ }
+ }
-export function onDragLeave(e: DragEvent): void {
- if (!dragHasFiles(e)) return;
- e.preventDefault();
- dragDepth = Math.max(0, dragDepth - 1);
- if (dragDepth === 0 && composerState.dragging) {
- composerState.dragging = false;
- drawActiveChat();
+ function dragHasFiles(e: DragEvent): boolean {
+ const types = e.dataTransfer?.types;
+ return types ? Array.from(types).includes("Files") : false;
}
-}
-export async function onDrop(e: DragEvent, agent: Agent): Promise<void> {
- if (!dragHasFiles(e)) return;
- e.preventDefault();
- dragDepth = 0;
- composerState.dragging = false;
- const { files, folders } = splitDropItems(Array.from(e.dataTransfer?.items ?? []));
- if (!files.length && !folders.length) files.push(...Array.from(e.dataTransfer?.files ?? []));
- drawActiveChat(agent);
- await addFiles(files, agent, folders);
-}
+ function onDragEnter(e: DragEvent): void {
+ if (!dragHasFiles(e)) return;
+ e.preventDefault();
+ dragDepth += 1;
+ if (!composerState.dragging) {
+ composerState.dragging = true;
+ ctx.chat.drawActiveChat();
+ }
+ }
-function pickFiles(): void {
- if (hasUnresolvedApproval() || chatState.resolvingApprovals.size > 0 || chatState.agent?.state.isStreaming) return;
- chatState.host?.querySelector<HTMLInputElement>(".file-input")?.click();
-}
+ function onDragOver(e: DragEvent): void {
+ if (!dragHasFiles(e)) return;
+ e.preventDefault();
+ if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
+ }
-function removeAttachment(id: string, agent: Agent): void {
- composerState.attachments = composerState.attachments.filter((a) => a.id !== id);
- pastedTextIds.delete(id);
- if (composerState.pasteView?.id === id) composerState.pasteView = null;
- drawActiveChat(agent);
-}
+ function onDragLeave(e: DragEvent): void {
+ if (!dragHasFiles(e)) return;
+ e.preventDefault();
+ dragDepth = Math.max(0, dragDepth - 1);
+ if (dragDepth === 0 && composerState.dragging) {
+ composerState.dragging = false;
+ ctx.chat.drawActiveChat();
+ }
+ }
-function selectModel(value: string, agent: Agent): void {
- const option = getModelOptions().find((candidate) => candidate.value === value);
- if (!option) return;
- const previousDefaultEffort = defaultEffortForModel(currentModelOption().model);
- if (chatState.threadRef) rememberThreadPick(chatState.threadRef, option.value);
- agent.state.model = option.model;
- if (composerState.effortLevel === previousDefaultEffort) {
- composerState.effortLevel = defaultEffortForModel(option.model);
- persistPreference(EFFORT_STORAGE_KEY, composerState.effortLevel);
- }
- if (composerState.openMenu !== "settings") composerState.openMenu = null;
- drawActiveChat(agent);
-}
+ async function onDrop(e: DragEvent, agent: Agent): Promise<void> {
+ if (!dragHasFiles(e)) return;
+ e.preventDefault();
+ dragDepth = 0;
+ composerState.dragging = false;
+ const { files, folders } = splitDropItems(Array.from(e.dataTransfer?.items ?? []));
+ if (!files.length && !folders.length) files.push(...Array.from(e.dataTransfer?.files ?? []));
+ ctx.chat.drawActiveChat(agent);
+ await addFiles(files, agent, folders);
+ }
-function selectHarness(harnessId: string, agent: Agent): void {
- const current = currentModelOption();
- const options = getModelOptionsForHarness(harnessId);
- const option = options.find((candidate) => candidate.model.id === current.model.id) ?? options[0];
- if (option) selectModel(option.value, agent);
-}
+ function pickFiles(): void {
+ if (ctx.chat.hasUnresolvedApproval() || ctx.chat.state.resolvingApprovals.size > 0) return;
+ ctx.chat.state.host?.querySelector<HTMLInputElement>(".file-input")?.click();
+ }
-function selectEffort(level: EffortLevel, agent: Agent): void {
- composerState.effortLevel = level;
- persistPreference(EFFORT_STORAGE_KEY, level);
- if (composerState.openMenu !== "settings") composerState.openMenu = null;
- drawActiveChat(agent);
-}
+ function removeAttachment(id: string, agent: Agent): void {
+ composerState.attachments = composerState.attachments.filter((a) => a.id !== id);
+ pastedTextIds.delete(id);
+ if (composerState.pasteView?.id === id) composerState.pasteView = null;
+ ctx.chat.drawActiveChat(agent);
+ }
-function toggleFastMode(agent: Agent): void {
- if (hasUnresolvedApproval() || chatState.resolvingApprovals.size > 0) return;
- if (!modelSupportsFastMode(currentModelOption().model.id)) return;
- composerState.fastMode = !effectiveFastMode();
- persistPreference(FAST_MODE_STORAGE_KEY, composerState.fastMode ? "1" : "0");
- if (fastModeChargeTimer) {
- clearTimeout(fastModeChargeTimer);
- fastModeChargeTimer = null;
- }
- fastModeCharging = composerState.fastMode === true;
- drawActiveChat(agent);
- if (fastModeCharging) {
- fastModeChargeTimer = setTimeout(() => {
- fastModeCharging = false;
- fastModeChargeTimer = null;
- if (agent === chatState.agent) drawActiveChat(agent);
- }, 760);
+ function selectModel(value: string, agent: Agent): void {
+ const option = getModelOptions(scopeKey()).find((candidate) => candidate.value === value);
+ if (!option) return;
+ const previousDefaultEffort = defaultEffortForModel(currentModelOption().model);
+ if (ctx.chat.state.threadRef) rememberThreadPick(ctx.chat.state.threadRef, option.value);
+ agent.state.model = option.model;
+ if (composerState.effortLevel === previousDefaultEffort) {
+ composerState.effortLevel = defaultEffortForModel(option.model);
+ persistPreference(EFFORT_STORAGE_KEY, composerState.effortLevel);
+ }
+ if (composerState.openMenu !== "settings") composerState.openMenu = null;
+ ctx.chat.drawActiveChat(agent);
+ }
+
+ function selectHarness(harnessId: string, agent: Agent): void {
+ const current = currentModelOption();
+ const options = getModelOptionsForHarness(harnessId, scopeKey());
+ const option = options.find((candidate) => candidate.model.id === current.model.id) ?? options[0];
+ if (option) selectModel(option.value, agent);
}
-}
-let autosizedTa: HTMLTextAreaElement | null = null;
-let autosizedValue: string | null = null;
-let autosizeObserver: ResizeObserver | null = null;
+ function selectEffort(level: EffortLevel, agent: Agent): void {
+ composerState.effortLevel = level;
+ persistPreference(EFFORT_STORAGE_KEY, level);
+ if (composerState.openMenu !== "settings") composerState.openMenu = null;
+ ctx.chat.drawActiveChat(agent);
+ }
+
+ function toggleFastMode(agent: Agent): void {
+ if (ctx.chat.hasUnresolvedApproval() || ctx.chat.state.resolvingApprovals.size > 0) return;
+ if (!modelSupportsFastMode(scopeKey(), currentModelOption().model.id)) return;
+ composerState.fastMode = !effectiveFastMode();
+ persistPreference(FAST_MODE_STORAGE_KEY, composerState.fastMode ? "1" : "0");
+ if (fastModeChargeTimer) {
+ clearTimeout(fastModeChargeTimer);
+ fastModeChargeTimer = null;
+ }
+ fastModeCharging = composerState.fastMode === true;
+ ctx.chat.drawActiveChat(agent);
+ if (fastModeCharging) {
+ fastModeChargeTimer = setTimeout(() => {
+ fastModeCharging = false;
+ fastModeChargeTimer = null;
+ if (agent === ctx.chat.state.agent) ctx.chat.drawActiveChat(agent);
+ }, 760);
+ }
+ }
-export function resizeComposer(): void {
- requestAnimationFrame(() => {
- const ta = chatState.host?.querySelector<HTMLTextAreaElement>(".composer-input");
- if (!ta) return;
- if (autosizedTa !== ta && typeof ResizeObserver !== "undefined") {
- autosizeObserver ??= new ResizeObserver(() => {
+ let autosizedTa: HTMLTextAreaElement | null = null;
+ let autosizedValue: string | null = null;
+ let autosizeObserver: ResizeObserver | null = null;
+
+ function resizeComposer(): void {
+ requestAnimationFrame(() => {
+ const ta = ctx.chat.state.host?.querySelector<HTMLTextAreaElement>(".composer-input");
+ if (!ta) return;
+ if (autosizedTa !== ta && typeof ResizeObserver !== "undefined") {
+ autosizeObserver ??= new ResizeObserver(() => {
+ autosizedValue = null;
+ resizeComposer();
+ });
+ if (autosizedTa) autosizeObserver.unobserve(autosizedTa);
+ autosizeObserver.observe(ta);
+ autosizedTa = ta;
autosizedValue = null;
- resizeComposer();
- });
- if (autosizedTa) autosizeObserver.unobserve(autosizedTa);
- autosizeObserver.observe(ta);
- autosizedTa = ta;
- autosizedValue = null;
+ }
+ if (ta.value === autosizedValue) return;
+ autosizedValue = ta.value;
+ ta.style.height = "auto";
+ const cap = parseFloat(getComputedStyle(ta).maxHeight) || 180;
+ const content = ta.scrollHeight;
+ ta.style.height = `${Math.min(cap, Math.max(ctx.pane ? 0 : 48, content))}px`;
+ if (content > cap) {
+ ta.style.overflowY = "auto";
+ } else {
+ ta.style.overflowY = "hidden";
+ ta.scrollTop = 0;
+ }
+ });
+ }
+
+ function closeMenus(): boolean {
+ let changed = false;
+ if (composerState.openMenu) {
+ composerState.openMenu = null;
+ changed = true;
}
- if (ta.value === autosizedValue) return;
- autosizedValue = ta.value;
- ta.style.height = "auto";
- const cap = parseFloat(getComputedStyle(ta).maxHeight) || 180;
- const content = ta.scrollHeight;
- ta.style.height = `${Math.min(cap, Math.max(embedMode ? 0 : 48, content))}px`;
- if (content > cap) {
- ta.style.overflowY = "auto";
- } else {
- ta.style.overflowY = "hidden";
- ta.scrollTop = 0;
+ if (!composerState.slashDismissed && slashQuery(composerState.draft) !== null) {
+ composerState.slashDismissed = true;
+ changed = true;
}
- });
+ return changed;
+ }
+
+ function dispose(): void {
+ autosizeObserver?.disconnect();
+ autosizeObserver = null;
+ autosizedTa = null;
+ if (fastModeChargeTimer !== null) clearTimeout(fastModeChargeTimer);
+ }
+
+ return {
+ state: composerState,
+ composerForm,
+ resetComposer,
+ focusComposerEnd,
+ resizeComposer,
+ currentModelOption,
+ carryModelPick,
+ refreshRuntimeSelection,
+ onDragEnter,
+ onDragOver,
+ onDragLeave,
+ onDrop,
+ closeMenus,
+ dispose,
+ };
}
diff --git a/plugins/web-ui/src/connectors.ts b/plugins/web-ui/src/connectors.ts
index f22d149fc..d1780550c 100644
--- a/plugins/web-ui/src/connectors.ts
+++ b/plugins/web-ui/src/connectors.ts
@@ -256,9 +256,12 @@ function addCredentialCard(): TemplateResult {
return html`<section class="kc-add-card" aria-labelledby="kc-add-title">
<div class="kc-panel-head">
<div>
- <span class="kc-eyebrow">Secure drop</span>
+ <span class="kc-eyebrow">New credential</span>
<h2 id="kc-add-title">Add a credential</h2>
- <p>The secret goes directly to your encrypted keychain. It never enters chat or this page.</p>
+ <p>
+ Describe the credential here, then paste the secret itself on a private one-time page. It goes straight to
+ your encrypted keychain — it is never shown in chat or stored on this page.
+ </p>
</div>
<div class="kc-panel-icon">${icon(LockKeyhole, 20)}</div>
</div>
@@ -266,10 +269,11 @@ function addCredentialCard(): TemplateResult {
secureDropUrl
? html`
<div class="kc-success" role="status">
- <strong>Secure form ready</strong><span>Open it in a new tab to enter the credential.</span>
+ <strong>Your one-time page is ready</strong><span>Open it in a new tab and paste the secret there.</span>
</div>
<div class="kc-form-actions">
- <a class="btn primary" href=${secureDropUrl} target="_blank" rel="noopener noreferrer">Open secure form</a
+ <a class="btn primary" href=${secureDropUrl} target="_blank" rel="noopener noreferrer"
+ >Open the one-time page</a
><button
class="btn"
type="button"
@@ -340,7 +344,7 @@ function addCredentialCard(): TemplateResult {
?disabled=${keychainOperations.dropInFlight}
@click=${() => void createDrop()}
>
- ${keychainOperations.dropInFlight ? "Creating…" : "Create secure form"}
+ ${keychainOperations.dropInFlight ? "Preparing…" : "Continue"}
</button>
</div>
`
@@ -489,17 +493,6 @@ function drawConnectors(loading = false): void {
</div>
</div>
<div class="kc-hero-actions">
- <button
- class="btn primary"
- type="button"
- @click=${() => {
- addingCredential = { service: "", envKey: "", purpose: "" };
- secureDropUrl = null;
- drawConnectors();
- }}
- >
- ${icon(Plus, 16)} Add credential
- </button>
<button
class="pane-refresh"
type="button"
@@ -512,6 +505,17 @@ function drawConnectors(loading = false): void {
>
${icon(RefreshCw, 17)}
</button>
+ <button
+ class="btn primary"
+ type="button"
+ @click=${() => {
+ addingCredential = { service: "", envKey: "", purpose: "" };
+ secureDropUrl = null;
+ drawConnectors();
+ }}
+ >
+ ${icon(Plus, 16)} Add credential
+ </button>
</div>
</header>
<div class="kc-summary" aria-label="Keychain summary">
@@ -552,7 +556,7 @@ function drawConnectors(loading = false): void {
<h2 id="kc-credentials-title">Stored credentials</h2>
<span>${keychainCredentials.length}</span>
</div>
- <p>API keys, tokens, and files added through a one-time secure form.</p>
+ <p>API keys, tokens, and files you added through the one-time page.</p>
</div>
<div class="kc-resource-list">
${
@@ -727,12 +731,12 @@ async function createDrop(): Promise<void> {
body: JSON.stringify(submittedDraft),
});
if (!keychainOperations.isCurrentEpoch(stateEpoch)) return;
- if (!result.url) throw new Error("No secure form URL was returned.");
+ if (!result.url) throw new Error("No one-time page URL was returned.");
secureDropUrl = result.url;
- connectorNotice = "Secure credential form ready.";
+ connectorNotice = "Your one-time page is ready.";
} catch (e) {
if (!keychainOperations.isCurrentEpoch(stateEpoch)) return;
- connectorNotice = errMessage(e, "Could not create the secure form.");
+ connectorNotice = errMessage(e, "Could not create the one-time page.");
} finally {
if (keychainOperations.isCurrentEpoch(stateEpoch)) {
keychainOperations.finishDrop(stateEpoch);
diff --git a/plugins/web-ui/src/context-model.ts b/plugins/web-ui/src/context-model.ts
new file mode 100644
index 000000000..0b4655753
--- /dev/null
+++ b/plugins/web-ui/src/context-model.ts
@@ -0,0 +1,162 @@
+import { html, nothing, type TemplateResult } from "lit";
+import { fetchRuntimeConfig, updateRuntimeConfig, type RuntimeConfig } from "./core-bridge";
+import { runtimeModelOptions, type ModelOption } from "./model-options";
+import { fieldSelect } from "./ui";
+import { errMessage } from "../../chassis/src/errors";
+
+const INHERIT = "";
+
+export const contextModelState = {
+ scope: null as string | null,
+ loading: false,
+ saving: false,
+ config: null as RuntimeConfig | null,
+ notice: "",
+ noticeKind: "" as "" | "saved" | "error",
+};
+
+let loadSeq = 0;
+let redraw: () => void = () => {};
+
+export function resetContextModel(): void {
+ loadSeq += 1;
+ contextModelState.scope = null;
+ contextModelState.loading = false;
+ contextModelState.saving = false;
+ contextModelState.config = null;
+ contextModelState.notice = "";
+ contextModelState.noticeKind = "";
+}
+
+export async function loadContextModel(scopeId: string, onChange: () => void): Promise<void> {
+ redraw = onChange;
+ if (contextModelState.scope === scopeId) return;
+ resetContextModel();
+ const seq = ++loadSeq;
+ contextModelState.scope = scopeId;
+ contextModelState.loading = true;
+ const config = await fetchRuntimeConfig(scopeId);
+ if (seq !== loadSeq) return;
+ contextModelState.config = config;
+ contextModelState.loading = false;
+ if (!config) {
+ contextModelState.notice = "Couldn't load this project's model.";
+ contextModelState.noticeKind = "error";
+ }
+ redraw();
+}
+
+function optionsFor(config: RuntimeConfig): ModelOption[] {
+ return runtimeModelOptions(config.approvedHarnesses, config.modelsByHarness, config.modelCatalog);
+}
+
+function optionLabel(option: ModelOption, multiHarness: boolean): string {
+ return multiHarness ? `${option.harnessLabel} · ${option.label}` : option.label;
+}
+
+function labelForRuntime(config: RuntimeConfig, runtime: { harnessId: string; modelId: string }): string {
+ const options = optionsFor(config);
+ const multiHarness = new Set(options.map((o) => o.harnessId)).size > 1;
+ const match = options.find((o) => o.value === `${runtime.harnessId}:${runtime.modelId}`);
+ return match ? optionLabel(match, multiHarness) : runtime.modelId;
+}
+
+function selectedValue(config: RuntimeConfig): string {
+ return config.scopeOverride ? `${config.scopeOverride.harnessId}:${config.scopeOverride.modelId}` : INHERIT;
+}
+
+async function choose(scope: string, value: string): Promise<void> {
+ if (contextModelState.saving) return;
+ const seq = loadSeq;
+ contextModelState.saving = true;
+ contextModelState.notice = "";
+ contextModelState.noticeKind = "";
+ redraw();
+ try {
+ const sep = value.indexOf(":");
+ const config = await updateRuntimeConfig(
+ scope,
+ value === INHERIT ? { inherit: true } : { harnessId: value.slice(0, sep), modelId: value.slice(sep + 1) },
+ );
+ if (seq !== loadSeq) return;
+ contextModelState.config = config;
+ contextModelState.notice = `Saved — new conversations here run on ${labelForRuntime(config, config.effective)}.`;
+ contextModelState.noticeKind = "saved";
+ } catch (e) {
+ if (seq !== loadSeq) return;
+ contextModelState.notice = errMessage(e, "Couldn't change the model — try again.");
+ contextModelState.noticeKind = "error";
+ } finally {
+ if (seq === loadSeq) {
+ contextModelState.saving = false;
+ redraw();
+ }
+ }
+}
+
+export function contextModelSection(scopeId: string): TemplateResult | typeof nothing {
+ if (contextModelState.scope !== scopeId) return nothing;
+ if (contextModelState.loading)
+ return html`<section class="context-panel context-model" aria-labelledby="context-model-title">
+ <h2 class="context-panel-title" id="context-model-title">Model</h2>
+ <div class="context-panel-loading">Loading…</div>
+ </section>`;
+ const config = contextModelState.config;
+ if (!config)
+ return html`<section class="context-panel context-model" aria-labelledby="context-model-title">
+ <h2 class="context-panel-title" id="context-model-title">Model</h2>
+ <span class="context-model-status error" aria-live="polite">${contextModelState.notice}</span>
+ </section>`;
+ const options = optionsFor(config);
+ const multiHarness = new Set(options.map((o) => o.harnessId)).size > 1;
+ const selected = selectedValue(config);
+ const stalePin = selected !== INHERIT && !options.some((o) => o.value === selected);
+ const isSlack = scopeId.startsWith("channel:");
+ return html`
+ <section class="context-panel context-model" aria-labelledby="context-model-title">
+ <div class="context-panel-heading">
+ <div>
+ <h2 class="context-panel-title" id="context-model-title">Model</h2>
+ <p class="context-panel-copy">The model every conversation here starts on.</p>
+ </div>
+ </div>
+ ${fieldSelect({
+ id: "context-model-select",
+ className: "context-model-select",
+ focusKey: "context-model",
+ ariaLabel: "Default model for this project",
+ disabled: contextModelState.saving,
+ value: selected,
+ onChange: (value) => void choose(scopeId, value),
+ options: [
+ html`<option value=${INHERIT}>Org default (${labelForRuntime(config, config.orgDefault)})</option>`,
+ ...options.map((o) => html`<option value=${o.value}>${optionLabel(o, multiHarness)}</option>`),
+ ...(stalePin
+ ? [
+ html`<option value=${selected}>
+ ${labelForRuntime(config, config.scopeOverride!)} — no longer offered
+ </option>`,
+ ]
+ : []),
+ ],
+ })}
+ <p class="context-model-hint">
+ ${
+ selected === INHERIT
+ ? "Following the org default — it changes when the org's does."
+ : "Pinned for this project. Anyone in a chat can still pick a different model for that conversation."
+ }
+ ${isSlack ? " The channel description in Slack names this model." : ""}
+ </p>
+ ${
+ contextModelState.notice
+ ? html`<span
+ class=${`context-model-status ${contextModelState.noticeKind === "error" ? "error" : ""}`}
+ aria-live="polite"
+ >${contextModelState.notice}</span
+ >`
+ : nothing
+ }
+ </section>
+ `;
+}
diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.ts
index 5790af3cb..b008063e9 100644
--- a/plugins/web-ui/src/contexts.ts
+++ b/plugins/web-ui/src/contexts.ts
@@ -29,15 +29,16 @@ import {
} from "./core-bridge";
import { UI_BASE } from "./deep-link";
import { errMessage } from "../../chassis/src/errors";
-import { actionSnippet, closeFormMenus, formatBytes, icon, initials, relTime, toggleFormMenu } from "./ui";
+import { actionSnippet, closeFormMenus, fieldSelect, formatBytes, icon, initials, relTime, toggleFormMenu } from "./ui";
import { appState, renderSidebarTop, replacePanePreservingFocus, switchView, syncUrlFromState } from "./shell";
-import { newChat } from "./chat";
+import { mainConversation } from "./conversations";
import { groupDmTitle, openSession, refreshSessions, sessionsState, slackLogo, surfaceOf } from "./sessions";
import { activityOf } from "./session-list";
import type { CronView } from "./crons";
import { cronRunSummary, cronRunSummaryTitle, cronScheduleSummary } from "./cron-format";
import { restoreDialogFocus } from "./dialog-focus";
-import { ambientPolicyApplies, ambientPolicySection, loadAmbientPolicy, resetAmbientPolicy } from "./ambient-policy";
+import { ambientPolicySection, loadAmbientPolicy, resetAmbientPolicy } from "./ambient-policy";
+import { contextModelSection, loadContextModel, resetContextModel } from "./context-model";
interface ScopeFile {
id: string;
@@ -180,6 +181,7 @@ export async function renderContexts(): Promise<void> {
) {
void loadScopeResources(contextsState.selected);
void loadAmbientPolicy(contextsState.selected, drawContexts);
+ void loadContextModel(contextsState.selected, drawContexts);
}
drawContexts();
}
@@ -224,6 +226,18 @@ export function personalScopeId(): string | null {
return contextsState.list.find((c) => c.kind === "personal")?.scopeId ?? null;
}
+export function resolveProjectScope(contexts: readonly CoreContext[], slug: string): string | null {
+ if (slug.startsWith("channel:") || slug.startsWith("group:")) {
+ return contexts.some((context) => context.scopeId === slug) ? slug : null;
+ }
+ const normalized = slug.toLowerCase();
+ const matches = contexts.filter((context) => {
+ const match = /^personal:([^@]+)@/.exec(context.scopeId);
+ return match?.[1]?.toLowerCase() === normalized;
+ });
+ return matches.length === 1 ? matches[0]!.scopeId : null;
+}
+
function metaForScope(scopeId: string | null, fallbackName?: string | null): { title: string; glyph: IconNode } {
const c = scopeId ? contextsState.list.find((x) => x.scopeId === scopeId) : undefined;
if (c) {
@@ -364,18 +378,15 @@ function gridTpl(): TemplateResult {
}}
/></label>
<label class="list-select"
- ><span>Show</span
- ><select
- .value=${contextsWorkspaceFilter}
- @change=${(event: Event) => {
- contextsWorkspaceFilter = (event.currentTarget as HTMLSelectElement)
- .value as typeof contextsWorkspaceFilter;
+ ><span>Show</span>${fieldSelect({
+ compact: true,
+ value: contextsWorkspaceFilter,
+ onChange: (value) => {
+ contextsWorkspaceFilter = value as typeof contextsWorkspaceFilter;
drawContexts();
- }}
- >
- <option value="active">Active only</option>
- <option value="all">Everything</option>
- </select></label
+ },
+ options: [html`<option value="active">Active only</option>`, html`<option value="all">Everything</option>`],
+ })}</label
>
</div>
${status ? html`<div class="status">${status}</div>` : nothing} ${projectList}
@@ -407,7 +418,6 @@ function contextCard(c: CoreContext): TemplateResult {
function detailTpl(c: CoreContext): TemplateResult {
const { title, sub, glyph } = contextMeta(c);
const sessions = sessionsIn(c.scopeId);
- const hasSettings = Boolean(c.project) || ambientPolicyApplies(c.scopeId);
const completelyEmpty = sessions.length === 0 && scopeResourcesEmpty(c.scopeId);
return html`
<div class="context-detail">
@@ -438,7 +448,7 @@ function detailTpl(c: CoreContext): TemplateResult {
</button>
</div>
</div>
- <div class=${`context-workspace ${hasSettings ? "has-settings" : ""}`}>
+ <div class="context-workspace has-settings">
<div class="context-workspace-main">
${
completelyEmpty
@@ -468,13 +478,10 @@ function detailTpl(c: CoreContext): TemplateResult {
`
}
</div>
- ${
- hasSettings
- ? html`<aside class="context-settings" aria-label=${c.project ? "Project settings" : "Context settings"}>
- ${c.project ? projectMembersSection(c) : nothing} ${ambientPolicySection(c.scopeId)}
- </aside>`
- : nothing
- }
+ <aside class="context-settings" aria-label=${c.project ? "Project settings" : "Context settings"}>
+ ${c.project ? projectMembersSection(c) : nothing} ${contextModelSection(c.scopeId)}
+ ${ambientPolicySection(c.scopeId)}
+ </aside>
</div>
</div>
`;
@@ -1195,16 +1202,18 @@ function selectContext(scopeId: string | null): void {
contextsState.resourcesNotice = "";
contextsState.resourcesLoading = false;
resetAmbientPolicy();
+ resetContextModel();
syncUrlFromState();
drawContexts();
if (scopeId) {
void loadScopeResources(scopeId);
void loadAmbientPolicy(scopeId, drawContexts);
+ void loadContextModel(scopeId, drawContexts);
}
}
function startChatIn(c: CoreContext): void {
- newChat(c.kind === "personal" ? undefined : { scopeId: c.scopeId, name: c.name });
+ mainConversation().newChat(c.kind === "personal" ? undefined : { scopeId: c.scopeId, name: c.name });
}
async function openFromContext(s: CoreSession): Promise<void> {
diff --git a/plugins/web-ui/src/conv-types.ts b/plugins/web-ui/src/conv-types.ts
new file mode 100644
index 000000000..d9c1fffea
--- /dev/null
+++ b/plugins/web-ui/src/conv-types.ts
@@ -0,0 +1,119 @@
+import type { Agent } from "@earendil-works/pi-agent-core";
+import type { TemplateResult } from "lit";
+import type { DensityTier } from "./density";
+import type { Attachment } from "@earendil-works/pi-web-ui";
+import type { ApprovalDecision, CoreSession, PendingApproval, entriesToMessages } from "./core-bridge";
+import type { EffortLevel, ModelOption } from "./model-options";
+import type { ComposerMenu } from "./composer";
+
+interface PaneState {
+ threadRef: string | null;
+ sessionId: string | null;
+ working: boolean;
+}
+
+export interface ConvHost {
+ pane: boolean;
+ ownsUrl: boolean;
+ container(): HTMLElement | null;
+ claimContainer(): HTMLElement | null;
+ visible(): boolean;
+ density(): DensityTier;
+ onDensityChange(handler: () => void): void;
+ ensureDeliveryStream(): void;
+ onState?(state: PaneState): void;
+ onExpand?(): void;
+}
+
+export interface ConvCtx extends ConvHost {
+ chat: ChatSurface;
+ composer: ComposerSurface;
+}
+
+interface ChatState {
+ agent: Agent | null;
+ host: HTMLElement | null;
+ threadRef: string | null;
+ sessionId: string | null;
+ scopeId: string | null;
+ contextName: string | null;
+ rememberedThreadRef: string | null;
+ rememberedSessionId: string | null;
+ rememberedScopeId: string | null;
+ rememberedContextName: string | null;
+ pendingSend: string | null;
+ resolvingApprovals: Set<string>;
+ transcriptAnchorSeq: number | null;
+ earlierCount: number;
+ loadingEarlier: boolean;
+}
+
+export interface ChatSurface {
+ state: ChatState;
+ hasLiveRun(): boolean;
+ signalLiveRun(kind: "abort" | "steer", text?: string): Promise<import("./core-bridge").SignalOutcome>;
+ newChat(context?: { scopeId: string; name: string | null }): string;
+ teardown(): void;
+ resetChatState(): void;
+ mountContinuable(
+ threadRef: string,
+ sessionId: string | null,
+ scopeId: string | null,
+ messages: ReturnType<typeof entriesToMessages>,
+ contextName?: string | null,
+ ): void;
+ mountReadOnly(
+ s: CoreSession,
+ messages: ReturnType<typeof entriesToMessages>,
+ earlierCount?: number,
+ anchorSeq?: number | null,
+ ): void;
+ mountLoadingPane(): void;
+ drawActiveChat(agent?: Agent | null, opts?: { forceScroll?: boolean }): void;
+ setTranscriptWindow(anchorSeq: number | null, earlierCount: number): void;
+ requestBackgroundPanel(sessionId: string | null, threadRef: string | null): void;
+ activePendingApprovals(): PendingApproval[];
+ hasUnresolvedApproval(): boolean;
+ resolveCommandApproval(decision: ApprovalDecision): void;
+ approvalSummaryView(a: PendingApproval, expanded?: boolean): TemplateResult;
+ notePendingSessionOnSend(): void;
+ syncPaneState(): void;
+ onDelivery(threadRef: string): void;
+ resumeIfIdle(): void;
+ redraw(): void;
+ dispose(): void;
+}
+
+interface ComposerState {
+ draft: string;
+ attachments: Attachment[];
+ error: string;
+ processingFiles: boolean;
+ dragging: boolean;
+ openMenu: ComposerMenu | null;
+ slashDismissed: boolean;
+ effortLevel: EffortLevel;
+ fastMode: boolean | undefined;
+ pasteView: { id: string; text: string; initial: string; dirty: boolean } | null;
+}
+
+export interface ComposerSurface {
+ state: ComposerState;
+ composerForm(agent: Agent): TemplateResult;
+ resetComposer(): void;
+ focusComposerEnd(): void;
+ resizeComposer(): void;
+ currentModelOption(): ModelOption;
+ carryModelPick(fromThreadRef: string | null, toThreadRef: string): void;
+ refreshRuntimeSelection(scopeId: string | null, agent?: Agent): Promise<void>;
+ onDragEnter(e: DragEvent): void;
+ onDragOver(e: DragEvent): void;
+ onDragLeave(e: DragEvent): void;
+ onDrop(e: DragEvent, agent: Agent): Promise<void>;
+ closeMenus(): boolean;
+ dispose(): void;
+}
+
+export interface Conversation extends ChatSurface {
+ composer: ComposerSurface;
+}
diff --git a/plugins/web-ui/src/conversations.ts b/plugins/web-ui/src/conversations.ts
new file mode 100644
index 000000000..1e8f21dda
--- /dev/null
+++ b/plugins/web-ui/src/conversations.ts
@@ -0,0 +1,92 @@
+import { createChatSurface } from "./chat";
+import { createComposerSurface } from "./composer";
+import { densityTierFor, type DensityTier } from "./density";
+import { subscribeDeliveries } from "./core-bridge";
+import { applySessionState } from "./session-list";
+import { refreshSessions, renderList, sessionsState } from "./sessions";
+import { appState } from "./shell-state";
+import type { Conversation, ConvCtx, ConvHost } from "./conv-types";
+
+const live = new Set<Conversation>();
+let main: Conversation | null = null;
+
+export function createConversation(host: ConvHost): Conversation {
+ const ctx = { ...host } as ConvCtx;
+ ctx.chat = createChatSurface(ctx);
+ ctx.composer = createComposerSurface(ctx);
+ const conv = ctx.chat as Conversation;
+ conv.composer = ctx.composer;
+ live.add(conv);
+ return conv;
+}
+
+export function disposeConversation(conv: Conversation): void {
+ live.delete(conv);
+ if (main === conv) main = null;
+ conv.composer.dispose();
+ conv.dispose();
+}
+
+export function allConversations(): Conversation[] {
+ return [...live];
+}
+
+export function mainConversation(): Conversation {
+ main ??= createConversation({
+ pane: false,
+ ownsUrl: true,
+ container: () => appState.mainEl,
+ claimContainer: () => {
+ exitCanvas();
+ return appState.mainEl;
+ },
+ visible: () => appState.currentView === "chats",
+ density: () => "full" as DensityTier,
+ onDensityChange: () => {},
+ ensureDeliveryStream,
+ });
+ return main;
+}
+
+export function paneDensity(el: HTMLElement): DensityTier {
+ const r = el.getBoundingClientRect();
+ return densityTierFor(r.width || el.clientWidth, r.height || el.clientHeight);
+}
+
+let exitCanvas: () => void = () => {};
+
+export function onExitCanvas(fn: () => void): void {
+ exitCanvas = fn;
+}
+
+let deliveryStreamOpen = false;
+
+export function ensureDeliveryStream(): void {
+ if (deliveryStreamOpen) return;
+ deliveryStreamOpen = true;
+ subscribeDeliveries(
+ (threadRef) => {
+ void refreshSessions({ silent: true });
+ for (const conv of live) conv.onDelivery(threadRef);
+ },
+ (event) => {
+ const { list, matched } = applySessionState(sessionsState.list, event);
+ if (matched) {
+ sessionsState.list = list;
+ renderList();
+ } else {
+ void refreshSessions({ silent: true });
+ }
+ // A run can start server-side for an open conversation without this tab asking
+ // for it (a steer replayed as a fresh turn after its run ended, a cron wake, a
+ // message from another surface). Attach the open view instead of waiting for a
+ // visibilitychange, so the new turn — and its triggering message — show up live.
+ if (event.state === "working") for (const conv of live) conv.resumeIfIdle();
+ },
+ () => void refreshSessions({ silent: true }),
+ );
+ document.addEventListener("visibilitychange", () => {
+ if (document.visibilityState !== "visible") return;
+ for (const conv of live) conv.resumeIfIdle();
+ });
+}
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index d06e0e767..9f6a55b15 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -189,6 +189,13 @@ export async function fetchTranscript(
return api<TranscriptPage>(`/api/sessions/${encodeURIComponent(id)}${suffix}`);
}
+export async function fetchEntry(sessionId: string, seq: number): Promise<SessionEntry> {
+ const r = await api<{ entry: SessionEntry }>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/entries/${encodeURIComponent(String(seq))}`,
+ );
+ return r.entry;
+}
+
export async function regenerateTitle(id: string): Promise<{ title: string | null }> {
return api<{ title: string | null }>(`/api/sessions/${encodeURIComponent(id)}/title`, { method: "POST" });
}
@@ -209,6 +216,7 @@ export interface SessionEntry {
createdAt: number;
seq?: number;
parentSeq?: number | null;
+ truncated?: boolean;
}
export interface ToolActivity {
@@ -217,6 +225,7 @@ export interface ToolActivity {
type: "tool_call" | "tool_result" | "approval_request" | "approval_resolved" | "thinking" | "text";
payload: unknown;
createdAt: number;
+ truncated?: boolean;
}
type WorkStatus = "thinking" | "working" | "complete" | "failed";
export interface WorkBlock {
@@ -354,10 +363,12 @@ async function toCoreAttachment(a: PiAttachment): Promise<CoreAttachment> {
export class ApiError extends Error {
status: number;
- constructor(message: string, status: number) {
+ body: unknown;
+ constructor(message: string, status: number, body?: unknown) {
super(message);
this.name = "ApiError";
this.status = status;
+ this.body = body;
}
}
@@ -391,7 +402,7 @@ export async function api<T = unknown>(path: string, init?: RequestInit): Promis
(body as { error?: string; message?: string })?.message ??
(body as { error?: string })?.error ??
`HTTP ${r.status}`;
- throw new ApiError(msg, r.status);
+ throw new ApiError(msg, r.status, body);
}
return body as T;
}
@@ -431,19 +442,43 @@ export async function updateRuntimeConfig(
export type WorkObserver = (work: WorkBlock) => void;
-let liveRun: { runId: string } | null = null;
+export interface RunSlot {
+ runId: string | null;
+}
+
+export function createRunSlot(): RunSlot {
+ return { runId: null };
+}
-export function hasLiveRun(): boolean {
- return liveRun !== null;
+export function hasLiveRun(slot: RunSlot): boolean {
+ return slot.runId !== null;
}
-export async function signalLiveRun(kind: "abort" | "steer", text?: string): Promise<void> {
- const run = liveRun;
+export type SignalOutcome = { ok: true } | { ok: false; reason: string; replayed?: boolean };
+
+export async function signalLiveRun(slot: RunSlot, kind: "abort" | "steer", text?: string): Promise<SignalOutcome> {
+ const run = slot.runId !== null ? { runId: slot.runId } : null;
if (!run) throw new Error("No active run to signal.");
- await api(runPath(run.runId, "/signal"), {
- method: "POST",
- body: JSON.stringify({ kind, ...(text !== undefined ? { text } : {}) }),
- });
+ try {
+ await api(runPath(run.runId, "/signal"), {
+ method: "POST",
+ body: JSON.stringify({ kind, ...(text !== undefined ? { text } : {}) }),
+ });
+ return { ok: true };
+ } catch (err) {
+ // The run ended before (or as) the signal arrived. For a steer, core replays the
+ // text as a fresh turn when it can; surface that outcome instead of failing so the
+ // caller can attach to the replay run or resend, rather than dropping the message.
+ if (err instanceof ApiError && (err.status === 409 || err.status === 404)) {
+ const body = (err.body ?? {}) as { reason?: string; replayed?: boolean };
+ return {
+ ok: false,
+ reason: body.reason ?? (err.status === 404 ? "not_found" : "terminal"),
+ ...(body.replayed ? { replayed: true } : {}),
+ };
+ }
+ throw err;
+ }
}
export function makeCoreStreamFn(
@@ -451,6 +486,7 @@ export function makeCoreStreamFn(
agent: Agent,
getTurnOptions?: () => TurnOptions,
onWork?: WorkObserver,
+ slot?: RunSlot,
): StreamFn {
const fn = (
model: Model<Api>,
@@ -458,7 +494,7 @@ export function makeCoreStreamFn(
options?: { signal?: AbortSignal },
): AssistantMessageEventStream => {
const stream = createAssistantMessageEventStream();
- void drive(stream, model, threadRef, agent, getTurnOptions, options?.signal, onWork);
+ void drive(stream, model, threadRef, agent, getTurnOptions, options?.signal, onWork, undefined, false, slot);
return stream;
};
return fn as unknown as StreamFn;
@@ -470,14 +506,20 @@ export async function activeRunForThread(threadRef: string): Promise<ActiveRun |
return r.runId && r.run ? { runId: r.runId, run: r.run } : null;
}
-export function makeRunResumeStreamFn(runId: string, initialRun?: RunPoll, onWork?: WorkObserver): StreamFn {
+export function makeRunResumeStreamFn(
+ runId: string,
+ initialRun?: RunPoll,
+ onWork?: WorkObserver,
+ slot?: RunSlot,
+ seedText?: string,
+): StreamFn {
const fn = (
model: Model<Api>,
_context: Context,
options?: { signal?: AbortSignal },
): AssistantMessageEventStream => {
const stream = createAssistantMessageEventStream();
- void resumeDrive(stream, model, runId, initialRun, options?.signal, onWork);
+ void resumeDrive(stream, model, runId, initialRun, options?.signal, onWork, slot, seedText);
return stream;
};
return fn as unknown as StreamFn;
@@ -490,9 +532,10 @@ export async function runApprovalTurn(
getTurnOptions: (() => TurnOptions) | undefined,
onWork: WorkObserver | undefined,
signal?: AbortSignal,
+ slot?: RunSlot,
): Promise<void> {
const stream = createAssistantMessageEventStream();
- await drive(stream, agent.state.model, threadRef, agent, getTurnOptions, signal, onWork, decision);
+ await drive(stream, agent.state.model, threadRef, agent, getTurnOptions, signal, onWork, decision, false, slot);
const outcome = await stream.result();
if (outcome.stopReason === "error") throw new Error(outcome.errorMessage || "Could not send the approval.");
}
@@ -502,6 +545,7 @@ export function makeOpenerStreamFn(
agent: Agent,
getTurnOptions: (() => TurnOptions) | undefined,
onWork: WorkObserver | undefined,
+ slot?: RunSlot,
): StreamFn {
const fn = (
model: Model<Api>,
@@ -509,7 +553,7 @@ export function makeOpenerStreamFn(
options?: { signal?: AbortSignal },
): AssistantMessageEventStream => {
const stream = createAssistantMessageEventStream();
- void drive(stream, model, threadRef, agent, getTurnOptions, options?.signal, onWork, undefined, true);
+ void drive(stream, model, threadRef, agent, getTurnOptions, options?.signal, onWork, undefined, true, slot);
return stream;
};
return fn as unknown as StreamFn;
@@ -525,6 +569,7 @@ async function drive(
onWork?: WorkObserver,
approval?: ApprovalDecision,
opener?: boolean,
+ slot?: RunSlot,
): Promise<void> {
const partial = baseAssistant(model);
const work: WorkBlock = { status: "thinking", activity: [] };
@@ -564,7 +609,7 @@ async function drive(
});
if (submit.runId) {
- await followRun(stream, partial, submit.runId, signal, notify);
+ await followRun(stream, partial, submit.runId, signal, notify, undefined, slot);
return;
}
@@ -587,6 +632,8 @@ async function resumeDrive(
initialRun?: RunPoll,
signal?: AbortSignal,
onWork?: WorkObserver,
+ slot?: RunSlot,
+ seedText?: string,
): Promise<void> {
const partial = baseAssistant(model);
const work: WorkBlock = { status: "thinking", activity: [] };
@@ -597,8 +644,13 @@ async function resumeDrive(
stream.push({ type: "start", partial });
stream.push({ type: "text_start", contentIndex: 0, partial });
const st: Acc = { acc: "", lastProgressAt: now() };
+ // Keep any assistant text the transcript already showed for this in-flight
+ // run visible: seed the accumulator with it so attaching the live stream
+ // never blanks text the person has already read. The server's own partial
+ // (when longer) simply replaces it via the normal delta path.
+ if (seedText?.trim()) pushDelta(stream, partial, st, seedText);
if (initialRun && applyRun(stream, partial, st, initialRun, notify) === "terminal") return;
- await followRun(stream, partial, runId, signal, notify, st);
+ await followRun(stream, partial, runId, signal, notify, st, slot);
} catch (e) {
work.status = "failed";
work.finishedAt = Date.now();
@@ -614,8 +666,9 @@ async function followRun(
signal?: AbortSignal,
notify?: () => void,
st: Acc = { acc: "", lastProgressAt: now() },
+ slot?: RunSlot,
): Promise<void> {
- liveRun = { runId };
+ if (slot) slot.runId = runId;
try {
if (signal?.aborted) return abortStream(stream, partial);
const viaSse = await streamRunViaSse(stream, partial, runId, st, signal, notify);
@@ -623,7 +676,7 @@ async function followRun(
if (signal?.aborted) return abortStream(stream, partial);
return await pollRun(stream, partial, runId, st, signal, notify);
} finally {
- if (liveRun?.runId === runId) liveRun = null;
+ if (slot?.runId === runId) slot.runId = null;
}
}
@@ -1110,6 +1163,7 @@ export function entriesToMessages(entries: SessionEntry[], model: Model<Api>): A
type: e.type as ToolActivity["type"],
payload: e.payload,
createdAt: e.createdAt,
+ ...(e.truncated ? { truncated: true } : {}),
};
if (e.type === "tool_call") {
const postText = postCallText(e.payload);
diff --git a/plugins/web-ui/src/crons.ts b/plugins/web-ui/src/crons.ts
index 738ebd47b..e9fc8d2cd 100644
--- a/plugins/web-ui/src/crons.ts
+++ b/plugins/web-ui/src/crons.ts
@@ -6,7 +6,8 @@ import { icon } from "./ui";
import { listBackLink, listPageTpl } from "./list-page";
import { ensureContexts, scopeChip } from "./contexts";
import { appState } from "./shell";
-import { chatState, newChat } from "./chat";
+import { mainConversation } from "./conversations";
+import { deepLinkPath, UI_BASE } from "./deep-link";
import {
cronNextFire,
cronRunSummary,
@@ -67,11 +68,33 @@ const cronRuns = new Map<string, CronRunView[]>();
const cronRunsLoading = new Set<string>();
let cronDialog: { kind: "rename" | "delete"; cron: CronView } | null = null;
let activeCronId: string | null = null;
+let pendingCronId: string | null = null;
export function resetActiveCron(): void {
cronsScope = null;
}
+export function openCronById(id: string): void {
+ pendingCronId = id;
+}
+
+function syncCronUrl(cronId: string | null, push = false): void {
+ if (appState.currentView !== "crons") return;
+ const next = deepLinkPath(UI_BASE, "crons", null, null, cronId);
+ if (`${location.pathname}${location.search}` === next) return;
+ if (push) history.pushState(null, "", next);
+ else history.replaceState(null, "", next);
+}
+
+export function routeCronsHistory(cronId: string | null): void {
+ if (appState.currentView !== "crons") return;
+ const cron = cronId
+ ? (cronList.find((c) => c.id === cronId) ?? visibleCronList.find((c) => c.id === cronId))
+ : undefined;
+ if (cron) openCron(cron);
+ else drawCronsPage();
+}
+
async function refreshCrons(opts: { showLoading?: boolean } = {}): Promise<boolean> {
const seq = ++cronRefreshSeq;
if (opts.showLoading) {
@@ -165,13 +188,25 @@ export async function renderCronsPage(): Promise<void> {
if (appState.currentView !== "crons") return;
await ensureContexts();
drawCronsPage();
- await refreshCrons({ showLoading: cronList.length === 0 && visibleCronList.length === 0 });
- if (appState.currentView === "crons") drawCronsPage();
+ const loaded = await refreshCrons({ showLoading: cronList.length === 0 && visibleCronList.length === 0 });
+ const wanted = pendingCronId;
+ pendingCronId = null;
+ if (appState.currentView !== "crons") return;
+ if (!loaded) return drawCronsPage();
+ const cron = wanted
+ ? (cronList.find((c) => c.id === wanted) ?? visibleCronList.find((c) => c.id === wanted))
+ : undefined;
+ if (wanted && !cron) {
+ cronActionNotice = "That cron wasn't found, or you don't have access to it.";
+ }
+ if (cron) openCron(cron);
+ else drawCronsPage();
}
function drawCronsPage(): void {
if (appState.currentView !== "crons" || !appState.mainEl) return;
activeCronId = null;
+ syncCronUrl(null);
if (!cronsPageHost || cronsPageHost.parentElement !== appState.mainEl) {
cronsPageHost = document.createElement("div");
cronsPageHost.className = "pane crons-page";
@@ -194,6 +229,10 @@ function drawCronsPage(): void {
const counts: Record<CronTab, number> = { yours: yours.length, shared: shared.length, archived: archived.length };
const rows: TemplateResult[] = [];
+ if (cronActionNotice) {
+ rows.push(html`<div class="action-notice">${cronActionNotice}</div>`);
+ cronActionNotice = "";
+ }
if (all.length) rows.push(cronTabs(counts));
if (cronTab === "yours") {
rows.push(...yoursEnabled.map(({ c }) => cronPageRow(c, true)));
@@ -297,14 +336,22 @@ function cronPageRow(c: CronView, mine: boolean): TemplateResult {
const meta = `${cronScheduleSummary(c)} · ${cronRunSummary(c)}`;
return html`
<div class="list-row cron-row cron-${status}">
- <button class="cron-row-main" type="button" @click=${() => openCron(c)}>
+ <a
+ class="cron-row-main"
+ href=${deepLinkPath(UI_BASE, "crons", null, null, c.id)}
+ @click=${(event: MouseEvent) => {
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
+ event.preventDefault();
+ openCron(c, { push: true });
+ }}
+ >
<span class="list-row-title cron-title-line"><span>${cronTitle(c)}</span></span>
${preview ? html`<span class="cron-preview">${preview}</span>` : nothing}
<span class="list-row-meta">
${isPersonalScope(c) ? nothing : scopeChip(c.ownerScopeId, c.scopeName ?? null)}
<span class="cron-meta-line" title=${cronRunSummaryTitle(c)}>${meta}</span>
</span>
- </button>
+ </a>
${canManageCron(c, mine) ? cronRowActions(c) : nothing}
</div>
`;
@@ -381,9 +428,10 @@ function cronRowActions(c: CronView): TemplateResult {
`;
}
-function openCron(c: CronView): void {
+function openCron(c: CronView, opts: { push?: boolean } = {}): void {
if (!appState.mainEl) return;
activeCronId = c.id;
+ syncCronUrl(c.id, opts.push);
const mine = cronList.some((x) => x.id === c.id);
const manageable = canManageCron(c, mine);
const notice = cronActionNotice;
@@ -516,18 +564,21 @@ function cronRunHistory(c: CronView): TemplateResult {
return html` <div class="field">
${heading}
<div class="cron-run-list">
- ${[...runs].reverse().map(
- (run) =>
- html` <div class="cron-run-row">
- <div>
- <span class="badge">${run.status ?? "completed"}</span>
- <span>${new Date(run.firedAt).toLocaleString()}</span>
- </div>
- ${run.note ? html`<div class="cron-run-error">${run.note}</div>` : nothing}
- ${run.reply ? html`<div class="cron-run-reply">${clipWords(run.reply, 180)}</div>` : nothing}
- ${run.sessionId ? html`<a href=${`${location.pathname}?session=${encodeURIComponent(run.sessionId)}`}>Open worklog</a>` : nothing}
- </div>`,
- )}
+ ${[...runs].reverse().map((run) => {
+ const detail = run.note ?? (run.reply ? clipWords(run.reply, 120) : "");
+ return html` <div class="cron-run-row">
+ <span class="badge">${run.status ?? "completed"}</span>
+ <span class="cron-run-time">${new Date(run.firedAt).toLocaleString()}</span>
+ <span class=${run.note ? "cron-run-detail cron-run-error" : "cron-run-detail"} title=${detail}>
+ ${detail}
+ </span>
+ ${
+ run.sessionId
+ ? html`<a class="cron-run-link" href=${deepLinkPath(UI_BASE, "chats", run.sessionId)}>Worklog</a>`
+ : nothing
+ }
+ </div>`;
+ })}
</div>
</div>`;
}
@@ -693,8 +744,9 @@ async function saveCronEdit(event: SubmitEvent, c: CronView): Promise<void> {
function editCronWithAgent(c: CronView): void {
cronDialog = null;
- newChat();
- void chatState.agent?.prompt(
+ const conv = mainConversation();
+ conv.newChat();
+ void conv.state.agent?.prompt(
`Help me edit cron ${c.id} ("${cronTitle(c)}"). Its current schedule is ${cronScheduleSummary(c)}. Ask what I want changed, then update its task, schedule, timezone, destination, or run mode as requested.`,
);
}
@@ -780,8 +832,9 @@ function onCreateCron(e: Event): void {
if (errSlot) errSlot.textContent = "Describe the cron you want.";
return;
}
- newChat();
- void chatState.agent?.prompt(
+ const conv = mainConversation();
+ conv.newChat();
+ void conv.state.agent?.prompt(
`Set up a cron for me: ${text}\n\n(Sent from the web UI's New-cron pane — create it now with your scheduling API, use a calendar schedule with timezone for daily/weekly/monthly timing, give it a 2-5 word title naming what the cron is for and distinctive in a list, like "Gmail unread digest" or "GitLab CI watch" — not the command and not a generic word, and confirm what you created.)`,
);
}
diff --git a/plugins/web-ui/src/deep-link.ts b/plugins/web-ui/src/deep-link.ts
index b02f24393..659ec3bc4 100644
--- a/plugins/web-ui/src/deep-link.ts
+++ b/plugins/web-ui/src/deep-link.ts
@@ -8,33 +8,52 @@ export function deepLinkPath(
view: string,
sessionId: string | null,
contextScope?: string | null,
+ itemId?: string | null,
): string {
const b = base.replace(/\/$/, "");
- if (view === "contexts" && contextScope) return `${b}/contexts?scope=${encodeURIComponent(contextScope)}`;
- if (view !== "chats") return `${b}/${encodeURIComponent(view)}`;
+ if (view === "contexts" && contextScope) {
+ if (itemId) throw new Error("the contexts view is addressed by scope, not by item id");
+ return `${b}/contexts?scope=${encodeURIComponent(contextScope)}`;
+ }
+ if (view !== "chats") return `${b}/${encodeURIComponent(view)}${itemId ? `/${encodeURIComponent(itemId)}` : ""}`;
+ if (itemId) throw new Error("the chats view is addressed by session, not by item id");
return `${b}/${sessionId ? `?session=${encodeURIComponent(sessionId)}` : ""}`;
}
+function decodeSegment(seg: string): string | null {
+ if (!seg) return null;
+ try {
+ return decodeURIComponent(seg);
+ } catch {
+ return null;
+ }
+}
+
export function parseDeepLink(
base: string,
pathname: string,
search: string,
-): { view: string | null; session: string | null } {
+): { view: string | null; session: string | null; item: string | null } {
const params = new URLSearchParams(search);
const b = base.replace(/\/$/, "");
const rel = pathname.startsWith(b) ? pathname.slice(b.length) : pathname;
- const seg = rel.replace(/^\/+/, "").split("/")[0] ?? "";
- let fromPath: string | null = null;
- if (seg) {
- try {
- fromPath = decodeURIComponent(seg);
- } catch {
- fromPath = null;
- }
+ const segments = rel.replace(/^\/+/, "").split("/");
+ const pathView = decodeSegment(segments[0] ?? "");
+ const projectKind = segments[1] === "channel" || segments[1] === "group" ? segments[1] : null;
+ let projectItem: string | null = null;
+ if (pathView === "projects") {
+ projectItem = projectKind ? decodeSegment(segments[2] ?? "") : decodeSegment(segments[1] ?? "");
}
- const requestedView = params.get("view") ?? fromPath;
+ const requestedView = params.get("view") ?? (pathView === "projects" ? "contexts" : pathView);
const view = requestedView === "connectors" ? "keychain" : requestedView;
- return { view, session: params.get("session") };
+ return {
+ view,
+ session: params.get("session"),
+ item:
+ pathView === "projects" && projectKind && projectItem
+ ? `${projectKind}:${projectItem}`
+ : (projectItem ?? decodeSegment(segments[1] ?? "")),
+ };
}
export function sessionLink(origin: string, base: string, sessionId: string): string {
diff --git a/plugins/web-ui/src/deploy-view.ts b/plugins/web-ui/src/deploy-view.ts
index d0d28af0a..9c4025233 100644
--- a/plugins/web-ui/src/deploy-view.ts
+++ b/plugins/web-ui/src/deploy-view.ts
@@ -94,7 +94,7 @@ export function deploymentTab(d: DeploymentView, viewer: string | undefined): De
export function deploymentTabEmptyMessage(tab: DeploymentTab): string {
if (tab === "shared") return "No apps shared with you.";
if (tab === "archived") return "Nothing archived.";
- return "No apps in Yours.";
+ return "No apps of your own yet.";
}
export function filterDeployments(
diff --git a/plugins/web-ui/src/deploys.ts b/plugins/web-ui/src/deploys.ts
index 32cff531b..1eba4f8c9 100644
--- a/plugins/web-ui/src/deploys.ts
+++ b/plugins/web-ui/src/deploys.ts
@@ -3,12 +3,11 @@ import { live } from "lit/directives/live.js";
import { Archive, Check, Copy, ExternalLink, MoreHorizontal, Pencil, RotateCcw, X } from "lucide";
import { api, withBase } from "./core-bridge";
import { errMessage } from "../../chassis/src/errors";
-import { copyText, icon, relTime } from "./ui";
+import { copyText, fieldSelect, icon, relTime } from "./ui";
import { listBackLink, listPageTpl } from "./list-page";
import { contextsState, ensureContexts, scopeChip } from "./contexts";
import { appState } from "./shell";
-import { chatState, drawActiveChat, newChat } from "./chat";
-import { composerState, focusComposerEnd } from "./composer";
+import { mainConversation } from "./conversations";
import { focusDialogCancel, restoreDialogFocus, trapDialogFocus } from "./dialog-focus";
import {
withDeploymentDetailNotice,
@@ -161,7 +160,7 @@ function deploymentRow(d: DeploymentView): TemplateResult {
<span class="list-row-meta deploy-row-meta">
${contextScope ? scopeChip(contextScope) : nothing}
<span>${ownerLabel(d)}</span>
- ${permissionBadge(d)}
+ ${canManage(d) ? permissionBadge(d) : nothing}
<span>${versionLabel(d)}</span>
<span>${deployedLabel(d)}</span>
</span>
@@ -306,19 +305,20 @@ function drawDeploysPage(): void {
onRefresh: () => void renderDeploys(),
action: { label: "Deploy with Agent", onClick: deployWithAgent },
controls: html`<label class="deploy-sort"
- ><span>Sort</span
- ><select
- aria-label="Sort apps"
- .value=${deploySort}
- @change=${(event: Event) => {
- deploySort = (event.currentTarget as HTMLSelectElement).value as DeploymentSort;
+ ><span>Sort</span>${fieldSelect({
+ compact: true,
+ ariaLabel: "Sort apps",
+ value: deploySort,
+ onChange: (value) => {
+ deploySort = value as DeploymentSort;
drawDeploysPage();
- }}
- >
- <option value="newest">Newest</option>
- <option value="name">Name</option>
- <option value="status">Status</option>
- </select></label
+ },
+ options: [
+ html`<option value="newest">Newest</option>`,
+ html`<option value="name">Name</option>`,
+ html`<option value="status">Status</option>`,
+ ],
+ })}</label
>`,
search: {
value: deployQuery,
@@ -844,10 +844,11 @@ async function openLiveEdit(d: DeploymentView, button: HTMLButtonElement): Promi
}
function deployWithAgent(): void {
- newChat();
- composerState.draft = "Deploy an app for me. ";
- drawActiveChat(chatState.agent);
- focusComposerEnd();
+ const conv = mainConversation();
+ conv.newChat();
+ conv.composer.state.draft = "Deploy an app for me. ";
+ conv.drawActiveChat(conv.state.agent);
+ conv.composer.focusComposerEnd();
}
async function refreshDeployments(): Promise<"updated" | "failed" | "superseded"> {
diff --git a/plugins/web-ui/src/embed.ts b/plugins/web-ui/src/embed.ts
deleted file mode 100644
index 5833e71b0..000000000
--- a/plugins/web-ui/src/embed.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { densityTierFor, type DensityTier } from "./density";
-
-export const PANE_STATE_MSG = "webui:pane-state";
-export const PANE_DELIVERY_MSG = "webui:pane-delivery";
-export const PANE_FOCUS_MSG = "webui:pane-focus";
-export const PANE_EXPAND_MSG = "webui:pane-expand";
-export const PANE_COLLAPSE_MSG = "webui:pane-collapse";
-
-export interface PaneStateMsg {
- type: typeof PANE_STATE_MSG;
- threadRef: string | null;
- sessionId: string | null;
- working: boolean;
-}
-
-export const embedMode: boolean = (() => {
- try {
- return new URLSearchParams(location.search).get("embed") === "1" && window.parent !== window;
- } catch {
- return false;
- }
-})();
-
-let densityTier: DensityTier = embedMode ? densityTierFor(window.innerWidth, window.innerHeight) : "full";
-const densityHandlers: Array<() => void> = [];
-
-export function currentDensity(): DensityTier {
- return densityTier;
-}
-
-export function onDensityChange(handler: () => void): void {
- densityHandlers.push(handler);
-}
-
-if (embedMode) {
- document.documentElement.dataset.density = densityTier;
- window.addEventListener("resize", () => {
- const next = densityTierFor(window.innerWidth, window.innerHeight);
- if (next === densityTier) return;
- densityTier = next;
- document.documentElement.dataset.density = next;
- for (const handler of densityHandlers) handler();
- });
-}
-
-let lastPosted = "";
-
-export function postPaneState(state: Omit<PaneStateMsg, "type">): void {
- if (!embedMode) return;
- const key = `${state.threadRef}|${state.sessionId}|${state.working}`;
- if (key === lastPosted) return;
- lastPosted = key;
- try {
- window.parent.postMessage({ type: PANE_STATE_MSG, ...state } satisfies PaneStateMsg, location.origin);
- } catch {
- void 0;
- }
-}
-
-export function requestPaneExpand(): void {
- if (!embedMode) return;
- try {
- window.parent.postMessage({ type: PANE_EXPAND_MSG }, location.origin);
- } catch {
- void 0;
- }
-}
-
-if (embedMode) {
- window.addEventListener("focus", () => {
- try {
- window.parent.postMessage({ type: PANE_FOCUS_MSG }, location.origin);
- } catch {
- void 0;
- }
- });
- window.addEventListener(
- "keydown",
- (e) => {
- if (e.key !== "Escape" || e.defaultPrevented) return;
- if (document.querySelector('[role="dialog"], .menu-popover, .slash-popover, .session-menu-popover')) return;
- try {
- window.parent.postMessage({ type: PANE_COLLAPSE_MSG }, location.origin);
- } catch {
- void 0;
- }
- },
- true,
- );
-}
-
-export function onRelayedDelivery(handler: (threadRef: string) => void): void {
- if (!embedMode) return;
- window.addEventListener("message", (e: MessageEvent) => {
- if (e.origin !== location.origin || e.source !== window.parent) return;
- const d = e.data as { type?: string; threadRef?: string };
- if (d?.type === PANE_DELIVERY_MSG && typeof d.threadRef === "string" && d.threadRef) handler(d.threadRef);
- });
-}
diff --git a/plugins/web-ui/src/files.ts b/plugins/web-ui/src/files.ts
index 36f1f6c1e..2fc996b90 100644
--- a/plugins/web-ui/src/files.ts
+++ b/plugins/web-ui/src/files.ts
@@ -2,7 +2,7 @@ import { html, nothing, render } from "lit";
import { File, Image, Upload } from "lucide";
import { api, reportSigninRequired, type SigninRequired, withBase } from "./core-bridge";
import { errMessage } from "../../chassis/src/errors";
-import { browserRenderableImage, formatBytes, icon, relTime } from "./ui";
+import { browserRenderableImage, fieldSelect, formatBytes, icon, relTime } from "./ui";
import { contextsState, ensureContexts, personalScopeId, scopeChip, scopeFilterControl } from "./contexts";
import { appState } from "./shell";
import { fileListNeedsAllPages } from "./file-list";
@@ -56,10 +56,12 @@ function selectControl(
onChange: (value: string) => void,
) {
return html`<label class="list-select"
- ><span>${label}</span
- ><select .value=${value} @change=${(e: Event) => onChange((e.currentTarget as HTMLSelectElement).value)}>
- ${options.map(([v, text]) => html`<option value=${v}>${text}</option>`)}
- </select></label
+ ><span>${label}</span>${fieldSelect({
+ compact: true,
+ value,
+ onChange,
+ options: options.map(([v, text]) => html`<option value=${v}>${text}</option>`),
+ })}</label
>`;
}
diff --git a/plugins/web-ui/src/main.ts b/plugins/web-ui/src/main.ts
index 0aa64e6bd..e5f0e3dc0 100644
--- a/plugins/web-ui/src/main.ts
+++ b/plugins/web-ui/src/main.ts
@@ -2,46 +2,39 @@ import "dockview-core/dist/styles/dockview.css";
import "./shell.css";
import { bootSafely } from "./shell";
import { closeFormMenus } from "./ui";
-import { drawActiveChat } from "./chat";
-import { composerState, slashQuery } from "./composer";
+import { allConversations } from "./conversations";
import { closeOpenSessionMenu, renderList, sessionsState } from "./sessions";
import { closeDeployMenu } from "./deploys";
+function closeComposerMenus(keepOpenWithin: Element | null): boolean {
+ let changed = false;
+ for (const conv of allConversations()) {
+ if (keepOpenWithin && conv.state.host?.contains(keepOpenWithin)) continue;
+ if (!conv.composer.closeMenus()) continue;
+ changed = true;
+ conv.redraw();
+ }
+ return changed;
+}
+
document.addEventListener("click", (e) => {
const target = e.target as Element | null;
- let redrawChat = false;
- if (composerState.openMenu && !target?.closest(".menu-control")) {
- composerState.openMenu = null;
- redrawChat = true;
- }
- if (!composerState.slashDismissed && slashQuery(composerState.draft) !== null && !target?.closest(".composer-wrap")) {
- composerState.slashDismissed = true;
- redrawChat = true;
- }
+ const inside = target?.closest(".menu-control, .composer-wrap") ?? null;
+ closeComposerMenus(inside);
if (!target?.closest(".form-menu-control")) closeFormMenus();
if (sessionsState.openMenuId && !target?.closest(".session-menu")) {
sessionsState.openMenuId = null;
renderList();
}
closeDeployMenu(target);
- if (redrawChat) drawActiveChat();
});
document.addEventListener("keydown", (e) => {
if (e.key !== "Escape") return;
- let changed = false;
- if (composerState.openMenu) {
- composerState.openMenu = null;
- changed = true;
- }
- if (!composerState.slashDismissed && slashQuery(composerState.draft) !== null) {
- composerState.slashDismissed = true;
- changed = true;
- }
+ closeComposerMenus(null);
closeOpenSessionMenu();
- changed = closeDeployMenu(null, true) || changed;
- changed = closeFormMenus() || changed;
- if (changed) drawActiveChat();
+ closeDeployMenu(null, true);
+ closeFormMenus();
});
void bootSafely();
diff --git a/plugins/web-ui/src/model-options.ts b/plugins/web-ui/src/model-options.ts
index 3a6f4a4dc..5ee2c799f 100644
--- a/plugins/web-ui/src/model-options.ts
+++ b/plugins/web-ui/src/model-options.ts
@@ -115,50 +115,77 @@ function buildOptions(
return harnessId === "pi" ? buildOptions(DEFAULT_PICKER_MODEL_IDS, "pi", qualified, catalog) : [];
}
-let activeModelOptions: ModelOption[] = buildOptions(DEFAULT_PICKER_MODEL_IDS);
-let defaultRuntimeValue: string | null = null;
+interface RuntimeOptions {
+ options: ModelOption[];
+ defaultValue: string | null;
+}
+
+const FALLBACK: RuntimeOptions = { options: buildOptions(DEFAULT_PICKER_MODEL_IDS), defaultValue: null };
+const byScope = new Map<string, RuntimeOptions>();
+let lastApplied: RuntimeOptions = FALLBACK;
+
+function runtimeFor(scopeKey?: string | null): RuntimeOptions {
+ if (scopeKey === undefined) return lastApplied;
+ return (scopeKey !== null ? byScope.get(scopeKey) : undefined) ?? lastApplied;
+}
-export function getModelOptions(): ModelOption[] {
- return activeModelOptions;
+export function getModelOptions(scopeKey?: string | null): ModelOption[] {
+ return runtimeFor(scopeKey).options;
}
-export function getHarnessOptions(): Array<{ value: string; label: string }> {
- return [...new Map(activeModelOptions.map((option) => [option.harnessId, option.harnessLabel])).entries()].map(
+export function getHarnessOptions(scopeKey?: string | null): Array<{ value: string; label: string }> {
+ const options = runtimeFor(scopeKey).options;
+ return [...new Map(options.map((option) => [option.harnessId, option.harnessLabel])).entries()].map(
([value, label]) => ({ value, label }),
);
}
-export function getModelOptionsForHarness(harnessId: string): ModelOption[] {
- return activeModelOptions.filter((option) => option.harnessId === harnessId);
+export function getModelOptionsForHarness(harnessId: string, scopeKey?: string | null): ModelOption[] {
+ return runtimeFor(scopeKey).options.filter((option) => option.harnessId === harnessId);
}
export function applyPickerModelIds(ids: readonly string[] | null | undefined, baseModelId?: string | null): void {
- activeModelOptions = buildOptions(ids && ids.length ? ids : DEFAULT_PICKER_MODEL_IDS);
- defaultRuntimeValue = baseModelId ?? null;
+ lastApplied = {
+ options: buildOptions(ids && ids.length ? ids : DEFAULT_PICKER_MODEL_IDS),
+ defaultValue: baseModelId ?? null,
+ };
}
-export function applyRuntimeOptions(
+export function runtimeModelOptions(
approvedHarnesses: readonly string[],
modelsByHarness: Readonly<Record<string, readonly string[]>>,
- effective: { harnessId: string; modelId: string },
catalog: Readonly<Record<string, { name: string; provider: string }>> = {},
-): void {
- activeModelOptions = approvedHarnesses.flatMap((harnessId) => {
+): ModelOption[] {
+ const options = approvedHarnesses.flatMap((harnessId) => {
const configured = buildOptions(modelsByHarness[harnessId] ?? [], harnessId, true, catalog);
return configured.length
? configured
: buildOptions(defaultModelIdsForHarness(harnessId), harnessId, true, catalog);
});
- if (!activeModelOptions.length) activeModelOptions = buildOptions(DEFAULT_PICKER_MODEL_IDS);
- defaultRuntimeValue = `${effective.harnessId}:${effective.modelId}`;
+ return options.length ? options : buildOptions(DEFAULT_PICKER_MODEL_IDS);
+}
+
+export function applyRuntimeOptions(
+ scopeKey: string | null,
+ approvedHarnesses: readonly string[],
+ modelsByHarness: Readonly<Record<string, readonly string[]>>,
+ effective: { harnessId: string; modelId: string },
+ catalog: Readonly<Record<string, { name: string; provider: string }>> = {},
+): void {
+ const options = runtimeModelOptions(approvedHarnesses, modelsByHarness, catalog);
+ const applied = { options, defaultValue: `${effective.harnessId}:${effective.modelId}` };
+ lastApplied = applied;
+ if (scopeKey !== null) byScope.set(scopeKey, applied);
}
-export function defaultModelValue(): ModelOptionValue {
- return activeModelOptions.find((o) => o.value === defaultRuntimeValue)?.value ?? activeModelOptions[0].value;
+export function defaultModelValue(scopeKey?: string | null): ModelOptionValue {
+ const { options, defaultValue } = runtimeFor(scopeKey);
+ return options.find((o) => o.value === defaultValue)?.value ?? options[0]!.value;
}
-export function transcriptModel(): Model<Api> {
- return (activeModelOptions.find((o) => o.value === defaultRuntimeValue) ?? activeModelOptions[0]).model;
+export function transcriptModel(scopeKey?: string | null): Model<Api> {
+ const { options, defaultValue } = runtimeFor(scopeKey);
+ return (options.find((o) => o.value === defaultValue) ?? options[0]!).model;
}
export type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max" | "ultracode" | "auto";
diff --git a/plugins/web-ui/src/pane-focus.ts b/plugins/web-ui/src/pane-focus.ts
index 511ee71ad..2bbec4a49 100644
--- a/plugins/web-ui/src/pane-focus.ts
+++ b/plugins/web-ui/src/pane-focus.ts
@@ -1,33 +1,51 @@
+type Selection = { start: number | null; end: number | null; direction: "forward" | "backward" | "none" | null };
+
+function isTextControl(
+ view: (Window & typeof globalThis) | null,
+ element: Element | null,
+): element is HTMLInputElement {
+ return Boolean(
+ view && element && (element instanceof view.HTMLInputElement || element instanceof view.HTMLTextAreaElement),
+ );
+}
+
+function readSelection(view: (Window & typeof globalThis) | null, element: Element | null): Selection | null {
+ if (!isTextControl(view, element)) return null;
+ return { start: element.selectionStart, end: element.selectionEnd, direction: element.selectionDirection };
+}
+
+function applySelection(
+ view: (Window & typeof globalThis) | null,
+ element: HTMLElement,
+ selection: Selection | null,
+): void {
+ if (!selection || selection.start === null || selection.end === null) return;
+ if (!isTextControl(view, element)) return;
+ element.setSelectionRange(selection.start, selection.end, selection.direction ?? undefined);
+}
+
export function replaceChildrenPreservingFocus(container: HTMLElement, host: HTMLElement): void {
const view = container.ownerDocument.defaultView;
const active = container.contains(container.ownerDocument.activeElement)
? (container.ownerDocument.activeElement as HTMLElement)
: null;
const key = active?.dataset.focusKey;
- const textControl = Boolean(
- view && active && (active instanceof view.HTMLInputElement || active instanceof view.HTMLTextAreaElement),
- );
- const selection = textControl
- ? {
- start: (active as HTMLInputElement).selectionStart,
- end: (active as HTMLInputElement).selectionEnd,
- direction: (active as HTMLInputElement).selectionDirection,
- }
- : null;
+ const selection = readSelection(view, active);
container.replaceChildren(host);
if (!key) return;
const next = [...container.querySelectorAll<HTMLElement>("[data-focus-key]")].find(
(element) => element.dataset.focusKey === key,
);
next?.focus();
- if (
- view &&
- next &&
- selection &&
- (next instanceof view.HTMLInputElement || next instanceof view.HTMLTextAreaElement) &&
- selection.start !== null &&
- selection.end !== null
- ) {
- next.setSelectionRange(selection.start, selection.end, selection.direction ?? undefined);
- }
+ if (next) applySelection(view, next, selection);
+}
+
+export function preservingFocus(doc: Document, mutate: () => void): void {
+ const view = doc.defaultView;
+ const active = doc.activeElement as HTMLElement | null;
+ const selection = readSelection(view, active);
+ mutate();
+ if (!active || doc.activeElement === active || !active.isConnected) return;
+ active.focus();
+ applySelection(view, active, selection);
}
diff --git a/plugins/web-ui/src/pi-models.ts b/plugins/web-ui/src/pi-models.ts
index 38593441d..ca2128a3a 100644
--- a/plugins/web-ui/src/pi-models.ts
+++ b/plugins/web-ui/src/pi-models.ts
@@ -41,12 +41,15 @@ function cloneModel(model: PiModel, id: string, name: string): PiModel {
return { ...structuredClone(model), id, name };
}
-let fastModeModelIds = new Set<string>();
+const fastModeByScope = new Map<string, Set<string>>();
+let lastFastModeIds = new Set<string>();
-export function setFastModeModelIds(ids: readonly string[] | undefined): void {
- fastModeModelIds = new Set(ids ?? []);
+export function setFastModeModelIds(scopeKey: string | null, ids: readonly string[] | undefined): void {
+ lastFastModeIds = new Set(ids ?? []);
+ if (scopeKey !== null) fastModeByScope.set(scopeKey, lastFastModeIds);
}
-export function modelSupportsFastMode(modelId: string | undefined): boolean {
- return !!modelId && fastModeModelIds.has(modelId);
+export function modelSupportsFastMode(scopeKey: string | null, modelId: string | undefined): boolean {
+ const ids = (scopeKey !== null ? fastModeByScope.get(scopeKey) : undefined) ?? lastFastModeIds;
+ return !!modelId && ids.has(modelId);
}
diff --git a/plugins/web-ui/src/session-list.ts b/plugins/web-ui/src/session-list.ts
index 125931bf5..6bc352d7f 100644
--- a/plugins/web-ui/src/session-list.ts
+++ b/plugins/web-ui/src/session-list.ts
@@ -149,19 +149,23 @@ export function applySessionState(
export interface RowIndicators {
working: boolean;
awaiting: boolean;
- background: { count: number; label: string } | null;
+ background: { jobs: number; watches: number; label: string } | null;
}
-export function backgroundLabel(jobs: number, watches: number): { count: number; label: string } | null {
+export function backgroundLabel(
+ jobs: number,
+ watches: number,
+): { jobs: number; watches: number; label: string } | null {
const parts: string[] = [];
if (jobs > 0) parts.push(`${jobs} background job${jobs === 1 ? "" : "s"} running`);
if (watches > 0) parts.push(`${watches} watch${watches === 1 ? "" : "es"} armed`);
- return parts.length ? { count: jobs + watches, label: parts.join(" · ") } : null;
+ return parts.length ? { jobs, watches, label: parts.join(" · ") } : null;
}
-export function rowIndicators(s: CoreSession, liveThreadRef: string | null): RowIndicators {
+export function rowIndicators(s: CoreSession, liveThreads: ReadonlySet<string> | string | null): RowIndicators {
+ const live = typeof liveThreads === "string" ? new Set([liveThreads]) : (liveThreads ?? new Set<string>());
return {
- working: Boolean(s.working) || (Boolean(s.threadRef) && s.threadRef === liveThreadRef),
+ working: Boolean(s.working) || (Boolean(s.threadRef) && live.has(s.threadRef)),
awaiting: Boolean(s.awaitingInput),
background: backgroundLabel(s.backgroundJobs ?? 0, s.watches ?? 0),
};
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index a60919be3..bd8f6fd7b 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -3,11 +3,12 @@ import { live } from "lit/directives/live.js";
import { ref } from "lit/directives/ref.js";
import { repeat } from "lit/directives/repeat.js";
import {
- Activity,
Archive,
+ Binoculars,
ArchiveRestore,
ChevronDown,
ChevronRight,
+ Cog,
EllipsisVertical,
Folder,
Hash,
@@ -55,8 +56,9 @@ import {
type RecentItem,
type ChatBrowseStatus,
} from "./session-list";
+import { hideTooltip, showTooltip } from "./tooltip";
import { errMessage } from "../../chassis/src/errors";
-import { copyText, icon, relTime } from "./ui";
+import { copyText, fieldSelect, icon, relTime } from "./ui";
import { listPageTpl } from "./list-page";
import {
contextsState,
@@ -69,15 +71,8 @@ import {
import { groupDmLabel, groupDmText } from "./group-dm-label";
import { transcriptModel } from "./model-options";
import { appState, closeSidebarOnNarrowView, renderSidebarTop, showMainEmpty } from "./shell";
-import {
- chatState,
- mountContinuable,
- mountLoadingPane,
- mountReadOnly,
- newChat,
- requestBackgroundPanel,
- setTranscriptWindow,
-} from "./chat";
+import { allConversations, mainConversation } from "./conversations";
+import type { Conversation } from "./conv-types";
import {
addBlankPane,
beginSessionDrag,
@@ -390,7 +385,7 @@ function startProjectChat(event: Event, scopeId: string, name: string | null): v
closeSidebarOnNarrowView();
sessionsState.collapsedProjectScopes.delete(scopeId);
if (addBlankPane(scopeId)) return;
- addPendingSession(newChat({ scopeId, name }), scopeId, name);
+ addPendingSession(mainConversation().newChat({ scopeId, name }), scopeId, name);
}
function projectMenuPopover(item: Extract<RecentItem, { kind: "project" }>): TemplateResult {
@@ -455,7 +450,7 @@ export async function renderChatsPage(): Promise<void> {
export function drawChatsPage(): void {
if (appState.currentView !== "chats" || !appState.mainEl || splitState.active) return;
- chatState.host = null;
+ mainConversation().state.host = null;
if (!chatsPageHost || chatsPageHost.parentElement !== appState.mainEl) {
chatsPageHost = document.createElement("div");
chatsPageHost.className = "pane chats-page";
@@ -483,7 +478,7 @@ export function drawChatsPage(): void {
drawChatsPage();
},
onRefresh: () => void renderChatsPage(),
- action: { label: "New chat", onClick: () => newChat() },
+ action: { label: "New chat", onClick: () => mainConversation().newChat() },
search: {
value: chatsPageQuery,
placeholder: "Search chats…",
@@ -519,18 +514,19 @@ export function drawChatsPage(): void {
)}
</div>
<label class="list-select"
- ><span>Surface</span
- ><select
- .value=${chatsPageSurface}
- @change=${(e: Event) => {
- chatsPageSurface = (e.currentTarget as HTMLSelectElement).value as typeof chatsPageSurface;
+ ><span>Surface</span>${fieldSelect({
+ compact: true,
+ value: chatsPageSurface,
+ onChange: (value) => {
+ chatsPageSurface = value as typeof chatsPageSurface;
drawChatsPage();
- }}
- >
- <option value="all">All surfaces</option>
- <option value="web">Web</option>
- <option value="slack">Slack</option>
- </select></label
+ },
+ options: [
+ html`<option value="all">All surfaces</option>`,
+ html`<option value="web">Web</option>`,
+ html`<option value="slack">Slack</option>`,
+ ],
+ })}</label
>
</div>`,
rows,
@@ -554,20 +550,25 @@ export const syncWorkingPulse = (el?: Element): void => {
else requestAnimationFrame(pin);
};
-function liveThread(): string | null {
- return liveTurnThreadRef({
- mountedThreadRef: chatState.threadRef,
- isStreaming: Boolean(chatState.agent?.state.isStreaming),
- pendingSend: chatState.pendingSend,
- });
+function liveThreads(): ReadonlySet<string> {
+ const live = new Set<string>();
+ for (const conv of allConversations()) {
+ const ref = liveTurnThreadRef({
+ mountedThreadRef: conv.state.threadRef,
+ isStreaming: Boolean(conv.state.agent?.state.isStreaming),
+ pendingSend: conv.state.pendingSend,
+ });
+ if (ref) live.add(ref);
+ }
+ return live;
}
function sessionWorking(s: CoreSession): boolean {
- return rowIndicators(s, liveThread()).working;
+ return rowIndicators(s, liveThreads()).working;
}
function statusMarks(s: CoreSession): TemplateResult {
- const ind = rowIndicators(s, liveThread());
+ const ind = rowIndicators(s, liveThreads());
return html`${ind.working ? html`<span class="working-dot" ${ref(syncWorkingPulse)} title="Agent is working" aria-label="Agent is working"></span>` : nothing}${
ind.awaiting
? html`<span class="awaiting-dot" title="Waiting for your reply" aria-label="Waiting for your reply"></span>`
@@ -578,11 +579,17 @@ function statusMarks(s: CoreSession): TemplateResult {
class="bg-chip"
role="button"
tabindex="0"
- title="${ind.background.label} — click to inspect"
aria-label="${ind.background.label} — click to inspect"
+ @mouseenter=${(e: Event) =>
+ showTooltip(e.currentTarget as Element, `${ind.background!.label} — click to inspect`)}
+ @mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}
+ @focus=${(e: Event) => showTooltip(e.currentTarget as Element, `${ind.background!.label} — click to inspect`)}
+ @blur=${(e: Event) => hideTooltip(e.currentTarget as Element)}
@click=${(e: Event) => openBackgroundInspector(e, s)}
@keydown=${(e: KeyboardEvent) => (e.key === "Enter" || e.key === " ") && openBackgroundInspector(e, s)}
- >${icon(Activity, 11)}${ind.background.count}</span
+ >${ind.background.jobs > 0 ? icon(Cog, 11) : nothing}${
+ ind.background.watches > 0 ? icon(Binoculars, 11) : nothing
+ }</span
>`
: nothing
}`;
@@ -591,17 +598,15 @@ function statusMarks(s: CoreSession): TemplateResult {
function openBackgroundInspector(e: Event, s: CoreSession): void {
e.stopPropagation();
e.preventDefault();
- requestBackgroundPanel(s.id || null, s.threadRef);
+ mainConversation().requestBackgroundPanel(s.id || null, s.threadRef);
void openSession(s);
}
function isActiveRow(s: CoreSession): boolean {
if (splitState.active) return Boolean(s.id) && sessionInCanvas(s.id);
if (sessionsState.openingKey) return Boolean(s.id) && s.id === sessionsState.openingKey;
- return Boolean(
- (chatState.sessionId && s.id === chatState.sessionId) ||
- (chatState.threadRef && s.threadRef === chatState.threadRef),
- );
+ const main = mainConversation().state;
+ return Boolean((main.sessionId && s.id === main.sessionId) || (main.threadRef && s.threadRef === main.threadRef));
}
function chatPageRow(s: CoreSession): TemplateResult {
@@ -785,6 +790,11 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
@dragstart=${(e: DragEvent) => onSessionDragStart(e, s)}
@dragend=${() => endSessionDrag()}
@click=${() => openSession(s)}
+ @dblclick=${(e: Event) => {
+ if (!saved) return;
+ e.preventDefault();
+ startRename(s);
+ }}
>
<div class="title" aria-live="polite">
${statusMarks(s)}${surfaceGlyph(s)}${readOnly ? html`<span class="ro-lock" title="Read-only">${icon(Lock, 12)}</span>` : nothing}<span
@@ -796,6 +806,18 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {
${
saved
? html`<div class="session-menu">
+ <button
+ class="session-menu-btn session-archive-btn"
+ type="button"
+ title=${s.archived ? "Unarchive" : "Archive"}
+ aria-label=${`${s.archived ? "Unarchive" : "Archive"} ${sessionTitle(s)}`}
+ @click=${(e: Event) => {
+ e.stopPropagation();
+ setArchived(s, !s.archived);
+ }}
+ >
+ ${s.archived ? icon(ArchiveRestore, 15) : icon(Archive, 15)}
+ </button>
<button
class="session-menu-btn"
data-menu-id=${s.id}
@@ -1103,6 +1125,13 @@ async function persistSessionPatch(
}
}
+let listSettled: (() => void) | null = null;
+const listReady = new Promise<void>((resolve) => (listSettled = resolve));
+
+export function sessionsReady(): Promise<void> {
+ return sessionsState.loaded ? Promise.resolve() : listReady;
+}
+
export async function refreshSessions(
opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean } = {},
): Promise<boolean> {
@@ -1125,6 +1154,8 @@ export async function refreshSessions(
if (!opts.silent) sessionsNotice = errMessage(e, "Failed to load conversations.");
return false;
} finally {
+ listSettled?.();
+ listSettled = null;
if (seq === sessionRefreshSeq) {
sessionsLoading = false;
renderList();
@@ -1136,22 +1167,33 @@ export async function openSession(s: CoreSession, entriesPrefetch?: Promise<Tran
if (splitInterceptsOpen(s)) return;
closeSidebarOnNarrowView();
if (projectName(s.scopeId) && sessionsState.collapsedProjectScopes.delete(s.scopeId)) renderList();
+ return openSessionInto(mainConversation(), s, entriesPrefetch);
+}
+
+export async function openSessionInto(
+ conv: Conversation,
+ s: CoreSession,
+ entriesPrefetch?: Promise<TranscriptPage | null>,
+): Promise<void> {
+ const tracked = conv === mainConversation();
if (!s.id) {
- if (chatState.threadRef !== s.threadRef) {
- mountContinuable(s.threadRef, null, s.scopeId || null, [], s.channelName ?? null);
+ if (conv.state.threadRef !== s.threadRef) {
+ conv.mountContinuable(s.threadRef, null, s.scopeId || null, [], s.channelName ?? null);
renderList();
}
return;
}
- if (s.id === chatState.sessionId) return;
+ if (s.id === conv.state.sessionId) return;
void refreshSessions({ silent: true });
- sessionsState.openingKey = s.id;
const opening = s.id;
- renderList();
+ if (tracked) {
+ sessionsState.openingKey = opening;
+ renderList();
+ }
const skeletonTimer = window.setTimeout(() => {
- if (sessionsState.openingKey === opening) mountLoadingPane();
+ if (!tracked || sessionsState.openingKey === opening) conv.mountLoadingPane();
}, 140);
const fetchEntries = (): Promise<TranscriptPage | null> =>
@@ -1165,11 +1207,13 @@ export async function openSession(s: CoreSession, entriesPrefetch?: Promise<Tran
]);
window.clearTimeout(skeletonTimer);
- if (sessionsState.openingKey !== opening) return;
- sessionsState.openingKey = null;
+ if (tracked) {
+ if (sessionsState.openingKey !== opening) return;
+ sessionsState.openingKey = null;
+ }
if (!entriesRes) {
- showMainEmpty("Couldn't load this conversation. Check your connection and click it again.");
+ if (tracked) showMainEmpty("Couldn't load this conversation. Check your connection and click it again.");
renderList();
return;
}
@@ -1179,10 +1223,10 @@ export async function openSession(s: CoreSession, entriesPrefetch?: Promise<Tran
const anchorSeq = entriesRes.entries?.[0]?.seq ?? null;
if (continuable) {
attachPendingApprovals(messages, approvalsRes?.approvals ?? [], transcriptModel());
- mountContinuable(s.threadRef, s.id, s.scopeId, messages, s.channelName ?? null);
- setTranscriptWindow(anchorSeq, earlier);
+ conv.mountContinuable(s.threadRef, s.id, s.scopeId, messages, s.channelName ?? null);
+ conv.setTranscriptWindow(anchorSeq, earlier);
} else {
- mountReadOnly(s, messages, earlier, anchorSeq);
+ conv.mountReadOnly(s, messages, earlier, anchorSeq);
}
renderList();
}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 1b30ad5a8..481762f00 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -71,13 +71,37 @@ body.resizing-sidebar .sidebar {
.sidebar > :not(.brand) {
min-width: calc(var(--sidebar-w) - 16px);
}
-.layout.sidebar-closed .sidebar > :not(.brand),
+.layout.sidebar-closed .sidebar > :not(.brand):not(#sidebar-top),
.layout.sidebar-closed .brand-lockup {
/* Untransitioned on purpose: the hide must be instant so nothing in the closed rail
stays focusable or exposed to assistive tech while the width animates shut. */
opacity: 0;
visibility: hidden;
}
+/* Collapsed, the nav stays in the rail as icon-only buttons (tooltips carry the
+ labels), so the rail keeps navigation instead of becoming a dead strip. */
+.layout.sidebar-closed #sidebar-top {
+ min-width: 0;
+ /* Short viewports: the rail's icons scroll rather than clip out of reach. */
+ min-height: 0;
+ overflow-y: auto;
+}
+.layout.sidebar-closed #sidebar-top .new-chat span,
+.layout.sidebar-closed #sidebar-top .navrow span,
+.layout.sidebar-closed #sidebar-top .nav-section-toggle,
+.layout.sidebar-closed #sidebar-top .section-label {
+ display: none;
+}
+.layout.sidebar-closed #sidebar-top .nav-group.collapsed {
+ /* The Browse group may be folded; the rail always shows its icons. */
+ grid-template-rows: 1fr;
+}
+.layout.sidebar-closed #sidebar-top .new-chat,
+.layout.sidebar-closed #sidebar-top .navrow {
+ justify-content: center;
+ gap: 0;
+ padding-inline: 0;
+}
.layout.sidebar-closed .brand {
padding-inline: 0;
gap: 0;
@@ -752,6 +776,9 @@ body.resizing-sidebar {
position: absolute;
top: 50%;
right: 6px;
+ display: flex;
+ align-items: center;
+ gap: 2px;
margin-top: -13px;
}
@@ -894,6 +921,8 @@ body.resizing-sidebar {
border-top: 1px solid var(--border);
}
.user-pill {
+ cursor: default;
+ user-select: none;
display: flex;
align-items: center;
gap: 9px;
@@ -1739,6 +1768,22 @@ body.resizing-sidebar {
padding: 0 12px 12px;
font-size: 13px;
color: var(--muted-foreground);
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.show-full-btn {
+ border: 1px solid var(--border, #d0d0d0);
+ border-radius: 999px;
+ background: var(--bg, #fff);
+ color: var(--muted-fg, #666);
+ font-size: 12px;
+ padding: 3px 10px;
+ cursor: pointer;
+}
+.show-full-btn:hover {
+ border-color: var(--fg, #333);
+ color: var(--fg, #333);
}
.chat-bottom-dock {
@@ -1748,7 +1793,7 @@ body.resizing-sidebar {
.bg-chip {
display: inline-flex;
align-items: center;
- gap: 2px;
+ gap: 3px;
flex: 0 0 auto;
margin-right: 6px;
padding: 0 5px;
@@ -2568,6 +2613,10 @@ body.resizing-sidebar {
}
.btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
font: inherit;
font-size: 13px;
padding: 7px 13px;
@@ -2918,6 +2967,14 @@ body.resizing-sidebar {
font-size: 14px;
box-sizing: border-box;
}
+.skill-form-page .field-select {
+ display: flex;
+}
+.skill-form-page .field-select > select {
+ min-height: 43px;
+ padding: 10px 36px 10px 11px;
+ font-size: 14px;
+}
.skill-form-page .skill-body-input {
min-height: 320px;
}
@@ -3094,7 +3151,7 @@ body.resizing-sidebar {
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
}
.skill-filter-fields .list-select,
- .skill-filter-fields select {
+ .skill-filter-fields .field-select {
min-width: 0;
width: 100%;
}
@@ -4242,7 +4299,7 @@ body.resizing-sidebar {
.cron-run-list {
display: grid;
- gap: 8px;
+ gap: 0;
}
.cron-run-heading {
@@ -4258,22 +4315,40 @@ body.resizing-sidebar {
}
.cron-run-row {
- display: grid;
- gap: 5px;
- padding: 10px 12px;
- border: 1px solid var(--border);
- border-radius: 8px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 0;
+ border-bottom: 1px solid color-mix(in srgb, var(--border) 65%, transparent);
font-size: 12px;
+ white-space: nowrap;
}
-.cron-run-error {
- color: var(--destructive, #b42318);
+.cron-run-row:last-child {
+ border-bottom: 0;
}
-.cron-run-reply {
+.cron-run-time {
+ font-variant-numeric: tabular-nums;
color: var(--muted-foreground);
}
+.cron-run-detail {
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: var(--muted-foreground);
+}
+
+.cron-run-link {
+ margin-left: auto;
+}
+
+.cron-run-error {
+ color: var(--destructive, #b42318);
+}
+
.action-notice {
padding: 9px 11px;
border-radius: 8px;
@@ -4339,16 +4414,6 @@ body.resizing-sidebar {
font-size: 11px;
font-weight: 600;
}
-.list-select select {
- min-height: 34px;
- padding: 0 28px 0 9px;
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- background: var(--background);
- color: var(--foreground);
- font: inherit;
- font-size: 12px;
-}
.resource-tabs {
width: min(960px, 100%);
margin: 16px auto 0;
@@ -4902,6 +4967,9 @@ body.resizing-sidebar {
background: color-mix(in srgb, var(--foreground) 28%, transparent);
}
.project-dialog {
+ /* Tailwind's preflight zeroes every margin, which strips the UA centering from
+ modal dialogs — restore it so showModal() opens centered, not top-left. */
+ margin: auto;
width: min(440px, 100%);
max-height: calc(100vh - var(--dialog-pad-top) - var(--dialog-pad-bottom));
max-height: calc(100dvh - var(--dialog-pad-top) - var(--dialog-pad-bottom));
@@ -5340,15 +5408,6 @@ body.resizing-sidebar {
color: var(--muted-foreground);
font-size: 12px;
}
-.deploy-sort select {
- height: 32px;
- padding: 0 24px 0 8px;
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- background: var(--background);
- color: var(--foreground);
- font: inherit;
-}
.deploy-row-main {
min-width: 0;
display: grid;
@@ -5737,6 +5796,7 @@ body.resizing-sidebar {
cursor: default;
}
.cron-row-main {
+ text-decoration: none;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
grid-template-areas:
@@ -5911,7 +5971,80 @@ body.resizing-sidebar {
flex-shrink: 0;
opacity: 0.85;
}
-
+.field-select {
+ position: relative;
+ min-width: 0;
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ color: var(--foreground);
+}
+.field-select > select {
+ min-width: 0;
+ width: 100%;
+ min-height: 34px;
+ box-sizing: border-box;
+ padding: 0 36px 0 10px;
+ appearance: none;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ outline: 0;
+ background: var(--background);
+ color: inherit;
+ font: inherit;
+ font-size: 13px;
+ text-overflow: ellipsis;
+}
+.field-select > .icon {
+ position: absolute;
+ right: 12px;
+ opacity: 0.55;
+ pointer-events: none;
+}
+.field-select.compact > select {
+ min-height: 30px;
+ padding-right: 32px;
+ font-size: 12.5px;
+}
+.field-select.compact > .icon {
+ right: 10px;
+}
+.field-select > select:hover:not(:disabled) {
+ border-color: color-mix(in srgb, var(--foreground) 30%, var(--border));
+}
+.field-select > select:focus-visible {
+ border-color: var(--foreground);
+ outline: 2px solid color-mix(in srgb, var(--foreground) 65%, transparent);
+ outline-offset: 2px;
+}
+.field-select:has(> select:disabled) {
+ opacity: 0.55;
+}
+.field-select > select:disabled {
+ cursor: not-allowed;
+}
+.context-model {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.context-model-select {
+ align-self: flex-start;
+ min-width: min(260px, 100%);
+}
+.context-model-hint {
+ margin: 0;
+ color: var(--muted-foreground);
+ font-size: 12px;
+ line-height: 1.45;
+}
+.context-model-status {
+ color: var(--muted-foreground);
+ font-size: 12px;
+}
+.context-model-status.error {
+ color: var(--destructive, #c0392b);
+}
.ambient-policy {
display: flex;
flex-direction: column;
@@ -5922,30 +6055,28 @@ body.resizing-sidebar {
font-size: 12px;
line-height: 1.45;
}
-.ambient-field {
+.ambient-group {
display: flex;
flex-direction: column;
- gap: 3px;
+ gap: 6px;
+}
+.ambient-group + .ambient-group {
+ margin-top: 4px;
+ padding-top: 14px;
+ border-top: 1px solid var(--border);
}
.ambient-enabled-select {
align-self: flex-start;
- margin-bottom: 8px;
+ min-width: min(300px, 100%);
}
-.ambient-field-label,
-.ambient-field-heading h3 {
+.ambient-field-label {
color: var(--foreground);
font-size: 12.5px;
font-weight: 600;
}
-.ambient-field-heading {
- margin-top: 6px;
-}
-.ambient-field-heading h3 {
+h3.ambient-field-label {
margin: 0;
}
-.ambient-field-heading p {
- margin: 3px 0 0;
-}
.ambient-orders {
width: 100%;
min-height: 112px;
@@ -5962,7 +6093,6 @@ body.resizing-sidebar {
line-height: 1.5;
}
.ambient-orders:focus-visible,
-.ambient-bot-mode:focus-visible,
.ambient-bot-hours input:focus-visible,
.ambient-bot-add input:focus-visible {
border-color: var(--foreground);
@@ -5992,7 +6122,6 @@ body.resizing-sidebar {
white-space: nowrap;
font-size: 13px;
}
-.ambient-bot-mode,
.ambient-bot-hours input,
.ambient-bot-add input {
box-sizing: border-box;
@@ -6005,8 +6134,7 @@ body.resizing-sidebar {
font-size: 12.5px;
}
.ambient-bot-mode {
- max-width: 160px;
- padding: 5px 7px;
+ max-width: 150px;
}
.ambient-bot-hours {
display: inline-flex;
@@ -6039,7 +6167,9 @@ body.resizing-sidebar {
display: flex;
align-items: center;
gap: 10px;
- padding-top: 2px;
+ margin-top: 4px;
+ padding-top: 14px;
+ border-top: 1px solid var(--border);
}
.ambient-policy-status {
color: var(--muted-foreground);
@@ -6359,14 +6489,15 @@ body.resizing-sidebar {
height: 100%;
}
-.split-pane-frame {
- display: block;
+.split-pane-chat {
+ display: flex;
+ flex-direction: column;
width: 100%;
height: 100%;
- border: 0;
+ overflow: hidden;
}
-.split-canvas.resizing .split-pane-frame {
+.split-canvas.resizing .split-pane-chat {
pointer-events: none;
}
@@ -6522,31 +6653,27 @@ body.resizing-sidebar {
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18);
}
-.embed-layout .main {
- height: 100%;
-}
-
-html[data-density="compact"] .chat-scroll {
+[data-density="compact"] .chat-scroll {
padding: 14px 14px 18px;
}
-html[data-density="compact"] .message-stack {
+[data-density="compact"] .message-stack {
gap: 10px;
font-size: 13.5px;
}
-html[data-density="compact"] .live-work-detail {
+[data-density="compact"] .live-work-detail {
display: none;
}
-html[data-density="card"] .context-banner,
-html[data-density="strip"] .context-banner,
-html[data-density="card"] .live-work-dock,
-html[data-density="strip"] .live-work-dock {
+[data-density="card"] .context-banner,
+[data-density="strip"] .context-banner,
+[data-density="card"] .live-work-dock,
+[data-density="strip"] .live-work-dock {
display: none;
}
-html[data-density="strip"] .chat-bottom-dock {
+[data-density="strip"] .chat-bottom-dock {
display: none;
}
-.embed-layout .composer-wrap {
+[data-density] .composer-wrap {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
@@ -6556,31 +6683,31 @@ html[data-density="strip"] .chat-bottom-dock {
padding: 6px 8px;
border-radius: 16px;
}
-.embed-layout .composer-input {
+[data-density] .composer-input {
flex: 1 1 120px;
min-height: 0;
max-height: 120px;
padding: 6px 6px 7px;
}
-.embed-layout .composer-toolbar {
+[data-density] .composer-toolbar {
display: contents;
}
-.embed-layout .composer-left,
-.embed-layout .composer-right {
+[data-density] .composer-left,
+[data-density] .composer-right {
width: auto;
}
-.embed-layout .composer-toolbar .icon-btn,
-.embed-layout .composer-toolbar .menu-button,
-.embed-layout .composer-toolbar .send-btn {
+[data-density] .composer-toolbar .icon-btn,
+[data-density] .composer-toolbar .menu-button,
+[data-density] .composer-toolbar .send-btn {
width: 34px;
height: 34px;
min-height: 34px;
}
-.embed-layout .runtime-upgrade,
-.embed-layout .attachment-strip,
-.embed-layout .composer-approval-panel,
-.embed-layout .composer-note,
-.embed-layout .composer-error {
+[data-density] .runtime-upgrade,
+[data-density] .attachment-strip,
+[data-density] .composer-approval-panel,
+[data-density] .composer-note,
+[data-density] .composer-error {
flex-basis: 100%;
}
.pane-card {
@@ -6680,3 +6807,24 @@ html[data-density="strip"] .chat-bottom-dock {
color: var(--primary, #6366f1);
background: color-mix(in srgb, var(--primary, #6366f1) 8%, var(--background));
}
+
+/* Floating tooltip (ours — never the browser's native title bubble). */
+.qm-tooltip {
+ position: fixed;
+ z-index: 4000;
+ max-width: 320px;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 11.5px;
+ line-height: 1.35;
+ color: var(--background, #fff);
+ background: color-mix(in srgb, var(--foreground) 92%, transparent);
+ box-shadow: 0 2px 8px rgb(0 0 0 / 0.18);
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 0.1s ease;
+ white-space: nowrap;
+}
+.qm-tooltip.visible {
+ opacity: 1;
+}
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index 776d3135a..ff4ce9a68 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -29,19 +29,11 @@ import {
import { applyRuntimeOptions } from "./model-options";
import { errMessage, swallow } from "../../chassis/src/errors";
import { brandMark, brandName, icon, initials } from "./ui";
-import {
- chatState,
- markConnectorConnected,
- mountContinuable,
- newChat,
- postCurrentPaneState,
- resetChatState,
- teardownActiveChat,
-} from "./chat";
-import { composerState, resetComposer, resyncModelSelection } from "./composer";
+import { markConnectorConnected } from "./chat";
+import { clearSkillsCache, resyncModelSelection, seedRuntimeConfig } from "./composer";
+import { ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";
import { clearAllDrafts, saveDraft, storedDraft } from "./drafts";
import { deepLinkPath, parseDeepLink, UI_BASE } from "./deep-link";
-import { embedMode } from "./embed";
import {
addBlankPane,
canvasToast,
@@ -49,6 +41,7 @@ import {
exitSplitIfActive,
loadPersistedSplit,
mountRestoredCanvas,
+ restoredCanvasNeedsSessionList,
splitState,
} from "./split";
import { activityOf } from "./session-list";
@@ -63,13 +56,13 @@ import {
sessionsState,
toggleWebOnly,
} from "./sessions";
-import { renderCronsPage, resetActiveCron } from "./crons";
+import { openCronById, renderCronsPage, resetActiveCron, routeCronsHistory } from "./crons";
import { renderFiles } from "./files";
import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";
import { renderDeploys } from "./deploys";
import { renderMemory, resetMemoryState } from "./memory";
import { renderSkills } from "./skills";
-import { contextsState, ensureContexts, renderContexts, resetContextsState } from "./contexts";
+import { contextsState, ensureContexts, renderContexts, resetContextsState, resolveProjectScope } from "./contexts";
import { appState, isView, type AuthMode, type Me, type View } from "./shell-state";
import { trapDialogFocus } from "./dialog-focus";
export { appState, can, type Me, type View } from "./shell-state";
@@ -82,6 +75,8 @@ setSigninRequiredHandler((detail) => {
renderAuthGate(gateFor(authMode, detail.reason));
});
+onExitCanvas(() => exitSplitIfActive());
+
export const ADMIN_BASE = (() => {
const base = ((import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/").replace(/\/$/, "");
return base ? base.replace(/\/[^/]+$/, "/admin") : "/admin";
@@ -94,14 +89,7 @@ export function adminSessionLogUrl(sessionId: string, scopeId: string): string {
}
export function syncUrlFromState(): void {
- if (embedMode) {
- postCurrentPaneState();
- if (parseDeepLink(UI_BASE, location.pathname, location.search).view === "app-edit") return;
- const sessionId = chatState.sessionId ?? chatState.rememberedSessionId;
- const next = sessionId ? `${deepLinkPath(UI_BASE, "chats", sessionId)}&embed=1` : `${UI_BASE}/?embed=1`;
- if (`${location.pathname}${location.search}` !== next) history.replaceState(null, "", next);
- return;
- }
+ const chatState = mainConversation().state;
const sessionId = splitState.active ? null : (chatState.sessionId ?? chatState.rememberedSessionId);
const next = deepLinkPath(UI_BASE, appState.currentView, sessionId, contextsState.selected);
if (`${location.pathname}${location.search}` !== next) history.replaceState(null, "", next);
@@ -204,14 +192,15 @@ export async function signOut(): Promise<void> {
}
appState.me = null;
clearAllDrafts();
- resetChatState();
+ exitSplitIfActive();
+ mainConversation().resetChatState();
resetSessionsState();
appState.currentView = "chats";
- composerState.skillsCache = null;
+ clearSkillsCache();
resetMemoryState();
resetContextsState();
resetKeychainState();
- resetComposer();
+ mainConversation().composer.resetComposer();
if (!portal) {
renderAuthGate({ kind: "dev" });
return;
@@ -427,19 +416,6 @@ function gateFor(mode: AuthMode, reason: "unauthenticated" | "not_allowed" | und
}
export function mountShell(): void {
- if (embedMode) {
- render(
- html`<div class="layout embed-layout">
- <section class="main" id="main"><div class="empty">Loading…</div></section>
- </div>`,
- appEl as HTMLElement,
- );
- appState.topEl = null;
- appState.listEl = null;
- appState.mainEl = (appEl as HTMLElement).querySelector("#main");
- shellMounted = true;
- return;
- }
applySavedSidebarWidth();
const impersonatedBy = appState.me?.impersonatedBy ?? null;
let banner: TemplateResult | null = null;
@@ -472,7 +448,7 @@ export function mountShell(): void {
<a class="icon-btn subtle" href=${ADMIN_HOME_URL} title="Back to admin" aria-label="Back to admin"
>${icon(ArrowLeft, 17)}</a
>
- <theme-toggle></theme-toggle>
+ <theme-toggle .includeSystem=${true} title="Color scheme: light / dark / system"></theme-toggle>
<button class="icon-btn subtle" title="Sign out" aria-label="Sign out" @click=${signOut}>
${icon(LogOut, 17)}
</button>
@@ -507,7 +483,12 @@ export function mountShell(): void {
export function renderSidebarTop(): void {
if (!appState.topEl) return;
const navRow = (v: View, glyph: IconNode, label: string) =>
- html`<button class="navrow ${appState.currentView === v ? "active" : ""}" type="button" data-view=${v}>
+ html`<button
+ class="navrow ${appState.currentView === v ? "active" : ""}"
+ type="button"
+ data-view=${v}
+ title=${label}
+ >
${icon(glyph, 17)}<span>${label}</span>
</button>`;
const navGroup = (id: string, title: string, open: boolean, toggle: () => void, rows: TemplateResult) => html`
@@ -530,9 +511,10 @@ export function renderSidebarTop(): void {
html`
<button
class="new-chat"
+ title=${splitState.active ? "New session" : "New chat"}
@click=${() => {
closeSidebarOnNarrowView();
- if (!addBlankPane()) newChat();
+ if (!addBlankPane()) mainConversation().newChat();
}}
>
${icon(ICON.newChat, 17)}<span>${splitState.active ? "New session" : "New chat"}</span>
@@ -596,8 +578,8 @@ export function switchView(v: View): void {
sessionsState.openMenuId = null;
sessionsState.renamingId = null;
if (v !== "chats") {
- teardownActiveChat();
- resetComposer();
+ mainConversation().teardown();
+ mainConversation().composer.resetComposer();
}
renderSidebarTop();
syncUrlFromState();
@@ -666,7 +648,7 @@ function refreshActiveView(v: View): void {
export function showMainEmpty(text: string): void {
exitSplitIfActive();
- chatState.host = null;
+ mainConversation().state.host = null;
if (appState.mainEl)
appState.mainEl.replaceChildren(
Object.assign(document.createElement("div"), { className: "empty", textContent: text }),
@@ -772,8 +754,15 @@ export function replacePanePreservingFocus(host: HTMLElement): void {
replaceChildrenPreservingFocus(appState.mainEl, host);
}
+window.addEventListener("popstate", () => {
+ if (appState.currentView !== "crons") return;
+ const { view, item } = parseDeepLink(UI_BASE, location.pathname, location.search);
+ if (view !== "crons") return;
+ routeCronsHistory(item);
+});
+
window.addEventListener("focus", () => {
- if (!appState.me || embedMode) return;
+ if (!appState.me) return;
if (appState.currentView === "contexts") void renderContexts();
else if (appState.currentView === "chats") void refreshSessions({ silent: true, refreshContexts: true });
});
@@ -794,7 +783,7 @@ function openAppEditChat(slug: string): void {
return;
}
if (!storedDraft(threadRef)) saveDraft(threadRef, `Update my deployed app "${slug}": `);
- mountContinuable(threadRef, null, null, []);
+ mainConversation().mountContinuable(threadRef, null, null, []);
renderList();
}
@@ -829,27 +818,39 @@ export async function boot(): Promise<void> {
appState.me = (await r.json()) as Me;
authMode = appState.me.mode ?? "portal";
clearPortalAttempt();
- const runtimeConfig = await fetchRuntimeConfig(`personal:${appState.me.user}`);
- if (runtimeConfig)
+ const personalScope = `personal:${appState.me.user}`;
+ const runtimeConfig = await fetchRuntimeConfig(personalScope);
+ if (runtimeConfig) {
applyRuntimeOptions(
+ personalScope,
runtimeConfig.approvedHarnesses,
runtimeConfig.modelsByHarness,
runtimeConfig.effective,
runtimeConfig.modelCatalog,
);
+ seedRuntimeConfig(personalScope, runtimeConfig);
+ }
resyncModelSelection();
mountShell();
+ ensureDeliveryStream();
warmDeferredChunks();
loadPersistedSplit();
const params = new URLSearchParams(location.search);
- const { view: wanted, session: wantedSession } = parseDeepLink(UI_BASE, location.pathname, location.search);
+ const {
+ view: wanted,
+ session: wantedSession,
+ item: wantedItem,
+ } = parseDeepLink(UI_BASE, location.pathname, location.search);
const connectedProvider = params.get("status") === "connected" ? params.get("connector") : null;
if (connectedProvider) markConnectorConnected(connectedProvider);
const viewIntent = isView(wanted) && wanted !== "chats";
const entriesPrefetch =
wantedSession && !viewIntent ? fetchTranscript(wantedSession, { tailTurns: TAIL_TURNS }).catch(() => null) : null;
+ const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;
+ if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas();
+
await refreshSessions({ showLoading: true });
if (wanted === "app-edit") {
@@ -862,19 +863,6 @@ export async function boot(): Promise<void> {
return;
}
- if (embedMode) {
- if (wantedSession) {
- const match = sessionsState.list.find((s) => s.id === wantedSession);
- if (match) await openSession(match, entriesPrefetch ?? undefined);
- else showMainEmpty("That conversation wasn't found, or you don't have access to it.");
- } else {
- const scope = params.get("scope");
- const context = scope ? (await ensureContexts()).find((c) => c.scopeId === scope) : undefined;
- newChat(context ? { scopeId: context.scopeId, name: context.name ?? null } : undefined);
- }
- return;
- }
-
if (wanted === "keychain") {
const provider = params.get("connector");
const status = params.get("status");
@@ -882,9 +870,11 @@ export async function boot(): Promise<void> {
switchView("keychain");
} else if (viewIntent) {
if (wanted === "contexts" || wanted === "files" || wanted === "deploys") {
- const scope = params.get("scope");
+ const scope =
+ params.get("scope") ?? (wantedItem ? resolveProjectScope(await ensureContexts(), wantedItem) : null);
if (scope) contextsState.selected = scope;
}
+ if (wanted === "crons" && wantedItem) openCronById(wantedItem);
switchView(wanted as View);
} else if (wantedSession) {
const match = sessionsState.list.find((s) => s.id === wantedSession);
@@ -902,7 +892,7 @@ export async function boot(): Promise<void> {
const recent = [...sessionsState.list].sort((a, b) => activityOf(b) - activityOf(a))[0]!;
exitSplitIfActive();
await openSession(recent);
- } else if (!mountRestoredCanvas()) {
- newChat();
+ } else if (!mountRestoredCanvas() && !mainConversation().state.threadRef) {
+ mainConversation().newChat();
}
}
diff --git a/plugins/web-ui/src/skills.ts b/plugins/web-ui/src/skills.ts
index 575db34ef..1840feda4 100644
--- a/plugins/web-ui/src/skills.ts
+++ b/plugins/web-ui/src/skills.ts
@@ -3,7 +3,7 @@ import { Box } from "lucide";
import { api, type CoreContext } from "./core-bridge";
import type { SkillItem } from "./composer";
import { errMessage } from "../../chassis/src/errors";
-import { icon } from "./ui";
+import { fieldSelect, icon } from "./ui";
import { appState } from "./shell";
import { skillActions } from "./skill-actions";
import {
@@ -381,18 +381,17 @@ function creatorPane() {
</label>
<label class="skill-field">
<span>Available to</span>
- <select
- class="skill-desc-input"
- .value=${c.scopeId}
- ?disabled=${creatingSaving}
- @change=${(ev: Event) => {
- c.scopeId = (ev.target as HTMLSelectElement).value;
+ ${fieldSelect({
+ className: "skill-scope-select",
+ value: c.scopeId,
+ disabled: creatingSaving,
+ onChange: (value) => {
+ c.scopeId = value;
c.review = null;
drawSkills();
- }}
- >
- ${createScopes.map((scope) => html`<option value=${scope.scopeId}>${scope.name}</option>`)}
- </select>
+ },
+ options: createScopes.map((scope) => html`<option value=${scope.scopeId}>${scope.name}</option>`),
+ })}
<small class="card-meta">Everyone in a shared context can invoke and edit this skill.</small>
</label>
<label class="skill-field">
@@ -537,38 +536,40 @@ function drawSkills(loading = false): void {
</div>
<div class="skill-filter-fields">
<label class="list-select"
- ><span>Scope</span
- ><select
- aria-label="Filter skills by scope"
- .value=${scopeFilter}
- @change=${(e: Event) => {
- scopeFilter = (e.currentTarget as HTMLSelectElement).value;
+ ><span>Scope</span>${fieldSelect({
+ compact: true,
+ ariaLabel: "Filter skills by scope",
+ value: scopeFilter,
+ onChange: (value) => {
+ scopeFilter = value;
drawSkills();
- }}
- >
- <option value="all">All scopes</option>
- <option value="personal">Personal</option>
- <option value="channel">Channel</option>
- <option value="group">Project / group</option>
- <option value="team">Team</option>
- <option value="org">Organization</option>
- </select></label
+ },
+ options: [
+ html`<option value="all">All scopes</option>`,
+ html`<option value="personal">Personal</option>`,
+ html`<option value="channel">Channel</option>`,
+ html`<option value="group">Project / group</option>`,
+ html`<option value="team">Team</option>`,
+ html`<option value="org">Organization</option>`,
+ ],
+ })}</label
>
<label class="list-select"
- ><span>Source</span
- ><select
- aria-label="Filter skills by source"
- .value=${sourceFilter}
- @change=${(e: Event) => {
- sourceFilter = (e.currentTarget as HTMLSelectElement).value;
+ ><span>Source</span>${fieldSelect({
+ compact: true,
+ ariaLabel: "Filter skills by source",
+ value: sourceFilter,
+ onChange: (value) => {
+ sourceFilter = value;
drawSkills();
- }}
- >
- <option value="all">All sources</option>
- <option value="native">Created here</option>
- <option value="pack">Skill packs</option>
- <option value="overrides">Overrides</option>
- </select></label
+ },
+ options: [
+ html`<option value="all">All sources</option>`,
+ html`<option value="native">Created here</option>`,
+ html`<option value="pack">Skill packs</option>`,
+ html`<option value="overrides">Overrides</option>`,
+ ],
+ })}</label
>
</div>
</div>
diff --git a/plugins/web-ui/src/split-layout.ts b/plugins/web-ui/src/split-layout.ts
index 2f18127e6..fb5e661c9 100644
--- a/plugins/web-ui/src/split-layout.ts
+++ b/plugins/web-ui/src/split-layout.ts
@@ -53,3 +53,23 @@ export function dropAddsTile(drop: { edge: boolean; wholeTile: boolean; sourceTi
if (!drop.edge || drop.wholeTile) return false;
return drop.sourceTilePanes !== 1;
}
+
+export function layoutNeedsSessionList(layout: unknown): boolean {
+ const panels = (layout as { panels?: unknown } | null)?.panels;
+ if (!panels || typeof panels !== "object") return true;
+ return Object.values(panels as Record<string, unknown>).some((panel) => {
+ const params = (panel as { params?: unknown } | null)?.params as PaneSeedLike | undefined;
+ return paneNeedsSessionList(params ?? {});
+ });
+}
+
+interface PaneSeedLike {
+ sessionId?: unknown;
+ threadRef?: unknown;
+}
+
+export function paneNeedsSessionList(p: PaneSeedLike): boolean {
+ const hasSession = typeof p.sessionId === "string" && p.sessionId !== "";
+ const hasThread = typeof p.threadRef === "string" && p.threadRef !== "";
+ return !hasSession && hasThread;
+}
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index c6c01b5ee..90b8fecd3 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -1,6 +1,6 @@
import { html, nothing, render, type TemplateResult } from "lit";
import { ref } from "lit/directives/ref.js";
-import { Activity, Expand, Maximize2, Plus, Shrink, X } from "lucide";
+import { Binoculars, Cog, Expand, Maximize2, Plus, Shrink, X } from "lucide";
import {
createDockview,
type DockviewApi,
@@ -15,31 +15,44 @@ import {
type SerializedDockview,
type TabPartInitParameters,
} from "dockview-core";
-import {
- embedMode,
- PANE_COLLAPSE_MSG,
- PANE_DELIVERY_MSG,
- PANE_EXPAND_MSG,
- PANE_FOCUS_MSG,
- PANE_STATE_MSG,
-} from "./embed";
import {
dropAddsTile,
MAX_PANES,
MAX_TILES,
serializedTileCount,
v1PaneSeeds,
+ layoutNeedsSessionList,
+ paneNeedsSessionList,
type DropEdge,
type PaneSeed,
type SplitEdge,
} from "./split-layout";
-import { deepLinkPath, UI_BASE } from "./deep-link";
+import { preservingFocus } from "./pane-focus";
+import { hideTooltip, showTooltip } from "./tooltip";
import { icon } from "./ui";
+import { contextsState } from "./contexts";
+import type { DensityTier } from "./density";
import { appState } from "./shell-state";
import { renderSidebarTop, switchView, syncUrlFromState } from "./shell";
-import { chatState, ensureDeliveryStream, newChat, sleep, teardownActiveChat } from "./chat";
-import { composerState, resetComposer } from "./composer";
-import { openSession, refreshSessions, renderList, sessionsState, sessionTitle, syncWorkingPulse } from "./sessions";
+import { sleep } from "./chat";
+import {
+ createConversation,
+ disposeConversation,
+ ensureDeliveryStream,
+ mainConversation,
+ paneDensity,
+} from "./conversations";
+import type { Conversation } from "./conv-types";
+import {
+ openSession,
+ openSessionInto,
+ refreshSessions,
+ sessionsReady,
+ renderList,
+ sessionsState,
+ sessionTitle,
+ syncWorkingPulse,
+} from "./sessions";
import { conversationBackground, type RowIndicators } from "./session-list";
import type { CoreSession } from "./core-bridge";
@@ -63,7 +76,6 @@ let dockApi: DockviewApi | null = null;
let toastEl: HTMLElement | null = null;
let lastLayout: SerializedDockview | null = null;
let pendingSeed: PendingSeed | null = null;
-const paneWorking = new Map<string, boolean>();
const paneContents = new Map<string, PaneContent>();
const paneTabs = new Set<PaneTab>();
const groupActions = new Set<GroupActions>();
@@ -109,7 +121,6 @@ function buildDock(): DockviewApi {
createTabComponent: () => new PaneTab(),
createRightHeaderActionComponent: () => new GroupActions(),
singleTabMode: "fullwidth",
- defaultRenderer: "always",
disableFloatingGroups: true,
});
const inner = dockEl.querySelector(":scope > .dv-dockview") as HTMLElement | null;
@@ -188,7 +199,7 @@ function ensureCanvas(): boolean {
canvasHost = document.createElement("div");
canvasHost.className = "split-canvas";
appState.mainEl.replaceChildren(canvasHost);
- chatState.host = null;
+ mainConversation().state.host = null;
dockApi = buildDock();
const seed = pendingSeed;
pendingSeed = null;
@@ -259,8 +270,8 @@ function largestGroupPanel(api: DockviewApi): { panel: IDockviewPanel; wide: boo
}
function activateCanvas(first: PaneParams, second: PaneParams, edge: SplitEdge): void {
- teardownActiveChat();
- resetComposer();
+ mainConversation().teardown();
+ mainConversation().composer.resetComposer();
splitState.active = true;
lastLayout = null;
pendingSeed = null;
@@ -288,13 +299,11 @@ export function exitSplitIfActive(): void {
persist();
disposeDock();
canvasHost = null;
- paneWorking.clear();
headerSignature = "";
renderSidebarTop();
}
export function loadPersistedSplit(): void {
- if (embedMode) return;
let raw: unknown;
try {
raw = JSON.parse(localStorage.getItem(STORE_KEY) ?? "null");
@@ -318,7 +327,14 @@ export function loadPersistedSplit(): void {
splitState.active = true;
}
+export function restoredCanvasNeedsSessionList(): boolean {
+ if (!pendingSeed) return false;
+ if (pendingSeed.kind === "v1") return pendingSeed.seeds.some((seed) => paneNeedsSessionList(seed));
+ return layoutNeedsSessionList(pendingSeed.layout);
+}
+
export function mountRestoredCanvas(): boolean {
+ if (splitState.active && (dockApi?.panels.length ?? 0) > 0) return true;
if (!splitState.active || (!pendingSeed && !lastLayout)) return false;
if (!ensureCanvas()) {
splitState.active = false;
@@ -370,7 +386,6 @@ function openInPane(paneId: string, sessionId: string, threadRef: string): void
if (!target) return;
const fresh = addPane({ sessionId, threadRef }, { referencePanel: target.id, direction: "within" });
dockApi.removePanel(target);
- paneWorking.delete(target.id);
fresh.api.setActive();
persist();
}
@@ -425,7 +440,6 @@ function closePanels(panels: IDockviewPanel[]): void {
if (!dockApi) return;
for (const p of panels) {
dockApi.removePanel(p);
- paneWorking.delete(p.id);
}
reconcileAfterClose();
}
@@ -434,7 +448,7 @@ function reconcileAfterClose(): void {
const rest = dockApi?.panels ?? [];
if (rest.length === 0) {
exitSplitIfActive();
- newChat();
+ mainConversation().newChat();
return;
}
if (rest.length === 1) {
@@ -444,7 +458,7 @@ function reconcileAfterClose(): void {
void maximizePane(params);
} else {
exitSplitIfActive();
- newChat();
+ mainConversation().newChat();
}
return;
}
@@ -475,7 +489,9 @@ async function maximizePane(params: PaneParams): Promise<void> {
}
function focusPane(paneId: string): void {
- dockApi?.getPanel(paneId)?.api.setActive();
+ const panel = dockApi?.getPanel(paneId);
+ if (!panel || panel.api.isActive) return;
+ preservingFocus(document, () => panel.api.setActive());
}
export function canvasToast(msg: string): void {
@@ -555,11 +571,13 @@ function paneZoneAct(paneId: string): (edge: DropEdge) => () => void {
}
function currentChatParams(): PaneParams | null {
+ const conv = mainConversation();
+ const chatState = conv.state;
if (!chatState.host) return null;
if (chatState.sessionId)
return { sessionId: chatState.sessionId, ...(chatState.threadRef ? { threadRef: chatState.threadRef } : {}) };
const untouched =
- !chatState.pendingSend && !composerState.draft.trim() && (chatState.agent?.state.messages.length ?? 0) === 0;
+ !chatState.pendingSend && !conv.composer.state.draft.trim() && (chatState.agent?.state.messages.length ?? 0) === 0;
return untouched ? {} : null;
}
@@ -571,7 +589,7 @@ function showSingleDropOverlay(): void {
if (!drag) return;
const session = sessionsState.list.find((s) => s.id === drag.sessionId);
const current = edge === "center" ? null : currentChatParams();
- if (edge === "center" || chatState.sessionId === drag.sessionId || !current) {
+ if (edge === "center" || mainConversation().state.sessionId === drag.sessionId || !current) {
if (session) void openSession(session);
return;
}
@@ -625,7 +643,10 @@ function paneTitle(panel: IDockviewPanel): string {
}
function paneIsWorking(panel: IDockviewPanel): boolean {
- return paneWorking.get(panel.id) === true || Boolean(paneSession(panel)?.working);
+ const conv = paneContents.get(panel.id)?.conversation;
+ const agent = conv?.state.agent;
+ if (agent?.state.isStreaming || (conv && conv.state.pendingSend !== null)) return true;
+ return Boolean(paneSession(panel)?.working);
}
function paneAwaitsInput(panel: IDockviewPanel): boolean {
@@ -637,49 +658,113 @@ function paneBackground(panel: IDockviewPanel): RowIndicators["background"] {
return conversationBackground(sessionsState.list, sessionId ?? null, threadRef ?? null);
}
-function paneSrc(params: PaneParams): string {
- const sessionId =
- params.sessionId ??
- (params.threadRef ? (sessionsState.list.find((s) => s.threadRef === params.threadRef)?.id ?? null) : null);
- if (sessionId) return `${deepLinkPath(UI_BASE, "chats", sessionId)}&embed=1`;
- const scope = params.scopeId ? `&scope=${encodeURIComponent(params.scopeId)}` : "";
- return `${UI_BASE}/?embed=1${scope}`;
-}
-
class PaneContent implements IContentRenderer {
readonly element: HTMLElement;
- private readonly frame: HTMLIFrameElement;
+ readonly conversation: Conversation;
+ private readonly chatEl: HTMLElement;
private readonly zonesEl: HTMLElement;
+ private readonly resize: ResizeObserver;
private panelId = "";
private panel: IDockviewPanel | null = null;
+ private params: PaneParams = {};
+ private density: DensityTier = "full";
+ private loaded = false;
+ private disposed = false;
+ private redrawOnResize: Array<() => void> = [];
constructor() {
this.element = document.createElement("div");
this.element.className = "split-pane-content";
- this.frame = document.createElement("iframe");
- this.frame.className = "split-pane-frame";
- this.frame.setAttribute("allow", "clipboard-read; clipboard-write");
+ this.chatEl = document.createElement("div");
+ this.chatEl.className = "split-pane-chat";
this.zonesEl = document.createElement("div");
this.zonesEl.className = "split-zones";
- this.element.append(this.frame, this.zonesEl);
+ this.element.append(this.chatEl, this.zonesEl);
+ this.conversation = createConversation({
+ pane: true,
+ ownsUrl: false,
+ container: () => this.chatEl,
+ claimContainer: () => this.chatEl,
+ visible: () => splitState.active && appState.currentView === "chats",
+ density: () => this.density,
+ onDensityChange: (handler) => this.redrawOnResize.push(handler),
+ ensureDeliveryStream,
+ onState: (paneState) => {
+ notePaneSession(this.panelId, paneState.sessionId, paneState.threadRef);
+ refreshHeaders();
+ },
+ onExpand: () => {
+ const panel = dockApi?.getPanel(this.panelId);
+ if (panel && !panel.api.isMaximized()) panel.api.maximize();
+ },
+ });
+ this.element.addEventListener("focusin", () => focusPane(this.panelId));
+ this.resize = new ResizeObserver(() => this.syncDensity());
}
init(p: GroupPanelPartInitParameters): void {
this.panelId = p.api.id;
this.panel = p.containerApi.getPanel(p.api.id) ?? null;
- this.frame.dataset.paneId = this.panelId;
- this.frame.title = this.panel ? paneTitle(this.panel) : "Conversation pane";
- this.frame.src = paneSrc((p.params ?? {}) as PaneParams);
+ this.params = (p.params ?? {}) as PaneParams;
+ this.element.dataset.paneId = this.panelId;
paneContents.set(this.panelId, this);
+ this.resize.observe(this.element);
this.syncZones();
+ p.api.onDidDimensionsChange(() => this.syncDensity());
+ p.api.onDidVisibilityChange((e) => {
+ if (e.isVisible) void this.load();
+ });
+ if (p.api.isVisible) void this.load();
}
- update(): void {
+ private syncDensity(): void {
+ this.element.dataset.density = this.density = paneDensity(this.element);
+ for (const handler of this.redrawOnResize) handler();
+ }
+
+ private async load(): Promise<void> {
+ if (this.loaded || this.disposed) return;
+ this.loaded = true;
+ this.syncDensity();
+ const { sessionId, threadRef, scopeId } = this.params;
+ const wanted =
+ sessionId ?? (threadRef ? (sessionsState.list.find((s) => s.threadRef === threadRef)?.id ?? null) : null);
+ if (!wanted) {
+ const context = scopeId ? contextsState.list.find((c) => c.scopeId === scopeId) : undefined;
+ this.conversation.newChat(context ? { scopeId: context.scopeId, name: context.name ?? null } : undefined);
+ return;
+ }
+ this.conversation.mountLoadingPane();
+ let session = sessionsState.list.find((s) => s.id === wanted);
+ if (!session) {
+ await sessionsReady();
+ if (this.disposed) return;
+ session = sessionsState.list.find((s) => s.id === wanted);
+ }
+ if (!session) {
+ await refreshSessions({ silent: true });
+ if (this.disposed) return;
+ session = sessionsState.list.find((s) => s.id === wanted);
+ }
+ if (!session) {
+ this.conversation.mountReadOnly(
+ { id: wanted, threadRef: threadRef ?? "", scopeId: "", title: "" } as CoreSession,
+ [],
+ );
+ return;
+ }
+ await openSessionInto(this.conversation, session);
+ if (this.disposed) return;
+ refreshHeaders();
+ }
+
+ update(p: { params: Record<string, unknown> }): void {
+ this.params = (p.params ?? {}) as PaneParams;
this.syncTitle();
}
syncTitle(): void {
- if (this.panel) this.frame.title = paneTitle(this.panel);
+ if (this.panel) this.element.title = paneTitle(this.panel);
}
syncZones(): void {
@@ -687,7 +772,10 @@ class PaneContent implements IContentRenderer {
}
dispose(): void {
+ this.disposed = true;
+ this.resize.disconnect();
paneContents.delete(this.panelId);
+ disposeConversation(this.conversation);
}
}
@@ -728,8 +816,14 @@ class PaneTab implements ITabRenderer {
${awaiting ? html`<span class="awaiting-dot" title="Waiting for your reply" aria-label="Waiting for your reply"></span>` : nothing}
${
background
- ? html`<span class="bg-chip" title=${background.label} aria-label=${background.label}
- >${icon(Activity, 11)}${background.count}</span
+ ? html`<span
+ class="bg-chip"
+ aria-label=${background.label}
+ @mouseenter=${(e: Event) => showTooltip(e.currentTarget as Element, background.label)}
+ @mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}
+ >${background.jobs > 0 ? icon(Cog, 11) : nothing}${
+ background.watches > 0 ? icon(Binoculars, 11) : nothing
+ }</span
>`
: nothing
}
@@ -837,61 +931,19 @@ class GroupActions implements IHeaderActionsRenderer {
}
}
-export function relayDeliveryToPanes(threadRef: string): void {
- if (!splitState.active || !canvasHost) return;
- for (const frame of canvasHost.querySelectorAll<HTMLIFrameElement>("iframe.split-pane-frame")) {
- frame.contentWindow?.postMessage({ type: PANE_DELIVERY_MSG, threadRef }, location.origin);
- }
-}
-
-window.addEventListener("message", (e: MessageEvent) => {
- if (e.origin !== location.origin || !splitState.active || !canvasHost || !dockApi) return;
- const d = e.data as { type?: string; threadRef?: unknown; sessionId?: unknown; working?: unknown } | null;
- if (
- d?.type !== PANE_STATE_MSG &&
- d?.type !== PANE_FOCUS_MSG &&
- d?.type !== PANE_EXPAND_MSG &&
- d?.type !== PANE_COLLAPSE_MSG
- )
- return;
- const frames = canvasHost.querySelectorAll<HTMLIFrameElement>("iframe.split-pane-frame");
- const frame = [...frames].find((f) => f.contentWindow === e.source);
- const paneId = frame?.dataset.paneId;
- if (!paneId) return;
- if (d.type === PANE_FOCUS_MSG) {
- focusPane(paneId);
- return;
- }
- if (d.type === PANE_EXPAND_MSG) {
- const expanding = dockApi.getPanel(paneId);
- if (expanding && !expanding.api.isMaximized()) expanding.api.maximize();
- return;
- }
- if (d.type === PANE_COLLAPSE_MSG) {
- if (dockApi.hasMaximizedGroup()) dockApi.exitMaximizedGroup();
- return;
- }
- const panel = dockApi.getPanel(paneId);
+function notePaneSession(paneId: string, sessionId: string | null, threadRef: string | null): void {
+ const panel = dockApi?.getPanel(paneId);
if (!panel) return;
- const wasWorking = paneWorking.get(paneId) === true;
- const working = d.working === true;
- paneWorking.set(paneId, working);
const params = panelParams(panel);
- const postedSession = typeof d.sessionId === "string" && d.sessionId ? d.sessionId : null;
- const postedThread = typeof d.threadRef === "string" && d.threadRef ? d.threadRef : null;
- if (!params.sessionId && (postedSession || (postedThread && postedThread !== params.threadRef))) {
- panel.api.updateParameters({
- ...(postedSession ? { sessionId: postedSession } : {}),
- ...(postedThread ? { threadRef: postedThread } : {}),
- });
- persist();
- if (postedSession) void settlePaneTitle(postedSession);
- } else if (wasWorking && !working && params.sessionId) {
- const settledId = params.sessionId;
- void settlePoll([0, 2000, 5000], () => sessionsState.list.find((s) => s.id === settledId)?.working !== true);
- }
+ if (params.sessionId || (!sessionId && (!threadRef || threadRef === params.threadRef))) return;
+ panel.api.updateParameters({
+ ...(sessionId ? { sessionId } : {}),
+ ...(threadRef ? { threadRef } : {}),
+ });
+ persist();
+ if (sessionId) void settlePaneTitle(sessionId);
refreshHeaders();
-});
+}
async function settlePaneTitle(sessionId: string): Promise<void> {
const titled = (): boolean => Boolean(sessionsState.list.find((s) => s.id === sessionId)?.title?.trim());
@@ -911,12 +963,6 @@ async function settlePoll(delays: number[], done: () => boolean): Promise<void>
}
}
-window.addEventListener("blur", () => {
- if (!splitState.active) return;
- const el = document.activeElement;
- if (el instanceof HTMLIFrameElement && el.dataset.paneId) focusPane(el.dataset.paneId);
-});
-
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && splitState.active && dockApi?.hasMaximizedGroup()) dockApi.exitMaximizedGroup();
});
diff --git a/plugins/web-ui/src/tooltip.ts b/plugins/web-ui/src/tooltip.ts
new file mode 100644
index 000000000..54e4b53bf
--- /dev/null
+++ b/plugins/web-ui/src/tooltip.ts
@@ -0,0 +1,39 @@
+/** Lightweight floating tooltip — our own styled element, never the browser's
+ * native `title` bubble. Anchored above the target, clamped to the viewport,
+ * appended to <body> so list-row overflow clipping can't hide it. */
+
+let tipEl: HTMLDivElement | null = null;
+let anchor: Element | null = null;
+
+function ensureEl(): HTMLDivElement {
+ if (!tipEl) {
+ tipEl = document.createElement("div");
+ tipEl.className = "qm-tooltip";
+ tipEl.setAttribute("role", "tooltip");
+ document.body.appendChild(tipEl);
+ }
+ return tipEl;
+}
+
+export function showTooltip(target: Element, text: string): void {
+ if (!text) return;
+ anchor = target;
+ const el = ensureEl();
+ el.textContent = text;
+ el.classList.add("visible");
+ // Measure after content is set.
+ const r = target.getBoundingClientRect();
+ const tr = el.getBoundingClientRect();
+ let left = r.left + r.width / 2 - tr.width / 2;
+ left = Math.max(6, Math.min(left, window.innerWidth - tr.width - 6));
+ let top = r.top - tr.height - 7;
+ if (top < 6) top = r.bottom + 7; // no room above — flip below
+ el.style.left = `${Math.round(left)}px`;
+ el.style.top = `${Math.round(top)}px`;
+}
+
+export function hideTooltip(target?: Element): void {
+ if (target && anchor && target !== anchor) return;
+ anchor = null;
+ tipEl?.classList.remove("visible");
+}
diff --git a/plugins/web-ui/src/ui.ts b/plugins/web-ui/src/ui.ts
index 515ae9c66..00d92c274 100644
--- a/plugins/web-ui/src/ui.ts
+++ b/plugins/web-ui/src/ui.ts
@@ -1,5 +1,5 @@
-import { html, type TemplateResult } from "lit";
-import { createElement, type IconNode } from "lucide";
+import { html, nothing, type TemplateResult } from "lit";
+import { ChevronDown, createElement, type IconNode } from "lucide";
export function brandName(): string {
if (typeof document === "undefined") return "QM";
@@ -22,6 +22,36 @@ export function icon(node: IconNode, size = 18): SVGElement {
return el;
}
+export function fieldSelect(props: {
+ options: TemplateResult | TemplateResult[];
+ onChange: (value: string, event: Event) => void;
+ value?: string;
+ id?: string;
+ ariaLabel?: string;
+ describedBy?: string;
+ focusKey?: string;
+ disabled?: boolean;
+ compact?: boolean;
+ className?: string;
+}): TemplateResult {
+ return html`<span
+ class=${`field-select${props.compact ? " compact" : ""}${props.className ? ` ${props.className}` : ""}`}
+ >
+ <select
+ id=${props.id ?? nothing}
+ aria-label=${props.ariaLabel ?? nothing}
+ aria-describedby=${props.describedBy ?? nothing}
+ data-focus-key=${props.focusKey ?? nothing}
+ .value=${props.value ?? nothing}
+ ?disabled=${props.disabled ?? false}
+ @change=${(e: Event) => props.onChange((e.currentTarget as HTMLSelectElement).value, e)}
+ >
+ ${props.options}
+ </select>
+ ${icon(ChevronDown, 16)}
+ </span>`;
+}
+
export function initials(s: string): string {
const base = (s.split("@")[0] || s).trim();
const parts = base.split(/[.\-_ ]+/).filter(Boolean);
diff --git a/plugins/web-ui/test/ambient-policy-source.test.ts b/plugins/web-ui/test/ambient-policy-source.test.ts
index d7aaad0cd..c145aa49a 100644
--- a/plugins/web-ui/test/ambient-policy-source.test.ts
+++ b/plugins/web-ui/test/ambient-policy-source.test.ts
@@ -19,12 +19,31 @@ test("policy edits redraw immediately and preserve focused text controls", () =>
test("policy controls use product language and persistent accessible labels", () => {
for (const label of ["Ignore", "Batch updates", "Act immediately", "Treat like a person"])
assert.match(policy, new RegExp(label));
- assert.match(policy, /<label class="ambient-field" for="ambient-orders">/);
+ assert.match(policy, /<label class="ambient-field-label" for="ambient-orders">/);
assert.match(policy, /aria-describedby="ambient-orders-hint"/);
+ assert.match(policy, /describedBy: "ambient-enabled-hint"/);
assert.match(policy, /aria-label="Bot name"/);
assert.match(policy, /required/);
});
+test("a field reads label, then control, then the prose explaining it", () => {
+ for (const [id, control] of [
+ ["ambient-enabled", "fieldSelect({"],
+ ["ambient-orders", "<textarea"],
+ ]) {
+ const group = policy.match(new RegExp(`<label class="ambient-field-label" for="${id}">[^]*?</div>`))?.[0] ?? "";
+ assert.ok(group, `${id} sits in its own group`);
+ const controlIndex = group.indexOf(control!);
+ assert.ok(controlIndex >= 0, `${id}'s control is present in its group`);
+ assert.ok(controlIndex < group.indexOf(`id="${id}-hint"`), `${id}'s control comes before its hint`);
+ }
+});
+
+test("both policy dropdowns come from the shared one, not hand-rolled markup", () => {
+ assert.equal((policy.match(/fieldSelect\(\{/g) ?? []).length, 2);
+ assert.doesNotMatch(policy, /<select/);
+});
+
test("policy styles use the shell theme contract", () => {
const start = css.indexOf(".ambient-policy {");
const end = css.indexOf("\n.main {", start);
diff --git a/plugins/web-ui/test/composer-no-scrollbar.test.ts b/plugins/web-ui/test/composer-no-scrollbar.test.ts
index 4e9c035df..480d1d0f0 100644
--- a/plugins/web-ui/test/composer-no-scrollbar.test.ts
+++ b/plugins/web-ui/test/composer-no-scrollbar.test.ts
@@ -11,7 +11,7 @@ test("composer input rests overflow-hidden below the height cap", () => {
});
test("resizeComposer opens scrolling only past the cap and pins scrollTop under it", () => {
- const fn = composer.match(/export function resizeComposer\(\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
+ const fn = composer.match(/function resizeComposer\(\): void \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
assert.match(
fn,
/const cap = parseFloat\(getComputedStyle\(ta\)\.maxHeight\) \|\| 180;/,
@@ -24,7 +24,7 @@ test("resizeComposer opens scrolling only past the cap and pins scrollTop under
});
test("the send-clear path resets overflow and scroll before the input is seen empty", () => {
- const fn = composer.match(/function clearComposerDom\(agent: Agent\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
+ const fn = composer.match(/function clearComposerDom\(agent: Agent\): void \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
assert.match(fn, /overflowY = "hidden"/, "clearing must close the scroller synchronously");
assert.match(fn, /scrollTop = 0/, "clearing must drop the clamped scroll offset");
});
diff --git a/plugins/web-ui/test/composer-source.test.ts b/plugins/web-ui/test/composer-source.test.ts
index 504aeb25a..dd98e9b93 100644
--- a/plugins/web-ui/test/composer-source.test.ts
+++ b/plugins/web-ui/test/composer-source.test.ts
@@ -5,7 +5,10 @@ import test from "node:test";
const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
test("scope-default buttons render only after the model selection is toggled off the default", () => {
- assert.match(composer, /const modelToggled = !runtimePending && selectedModel\.value !== defaultModelValue\(\)/);
+ assert.match(
+ composer,
+ /const modelToggled = !runtimePending && selectedModel\.value !== defaultModelValue\(scopeKey\(\)\)/,
+ );
assert.match(composer, /\$\{\s*modelToggled\s*\? html`[\s\S]{0,800}?>\s*Make default\s*<\/button>/);
assert.match(composer, /\$\{\s*modelToggled && activeRuntimeConfig\?\.scopeOverride/);
});
@@ -31,3 +34,39 @@ test("composer-right keeps its control order: make default, use org default, mod
assert.ok(model < harness, "the model picker should precede the harness picker");
assert.ok(harness < send, "the harness picker should precede the send controls");
});
+
+test("attaching files is allowed while a turn is streaming", () => {
+ // The attach button and drop/paste paths must not gate on isStreaming —
+ // only on runtime readiness and pending approvals.
+ assert.match(composer, /const attachingDisabled = inputBlocked;/);
+ assert.doesNotMatch(composer, /attachingDisabled = inputBlocked \|\| agent\.state\.isStreaming/);
+ // pickFiles, addFiles, and the large-paste path no longer check isStreaming.
+ const guards = composer.match(/isStreaming/g) ?? [];
+ const pickFiles = composer.slice(
+ composer.indexOf("function pickFiles"),
+ composer.indexOf("function removeAttachment"),
+ );
+ assert.doesNotMatch(pickFiles, /isStreaming/);
+ const addFiles = composer.slice(
+ composer.indexOf("async function addFiles"),
+ composer.indexOf("function dragHasFiles"),
+ );
+ assert.doesNotMatch(addFiles, /isStreaming/);
+ assert.ok(guards.length > 0, "streaming still gates steer/send routing");
+});
+
+test("steering with pending attachments explains they ride the next message", () => {
+ assert.match(composer, /attachments stay for your next message/);
+});
+
+test("a steer whose run already ended is recovered, never silently dropped", () => {
+ // sendSteer must inspect the signal outcome and route a failed steer through recovery.
+ assert.match(composer, /const outcome = await ctx\.chat\.signalLiveRun\("steer", text\);/);
+ assert.match(composer, /if \(!outcome\.ok\) recoverEndedRunSteer\(agent, text, outcome\);/);
+ // Replayed by core → detach from the stale stream and attach to the fresh run.
+ assert.match(composer, /function recoverEndedRunSteer\(/);
+ assert.match(composer, /attachWhenIdle\(agent, 0\);/);
+ // Not stored anywhere → the text goes back through a normal send.
+ assert.match(composer, /resendWhenIdle\(agent, text, 0\);/);
+ assert.match(composer, /if \(composerState\.draft === text\) void sendPrompt\(agent\);/);
+});
diff --git a/plugins/web-ui/test/context-model-source.test.ts b/plugins/web-ui/test/context-model-source.test.ts
new file mode 100644
index 000000000..0d1a6fc1b
--- /dev/null
+++ b/plugins/web-ui/test/context-model-source.test.ts
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const panel = readFileSync(new URL("../src/context-model.ts", import.meta.url), "utf8");
+const contexts = readFileSync(new URL("../src/contexts.ts", import.meta.url), "utf8");
+const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
+
+test("the scope's model panel writes through the same endpoint the composer's default does", () => {
+ assert.match(panel, /updateRuntimeConfig\(\s*scope,/);
+ assert.match(panel, /\{ inherit: true \}/);
+ assert.match(panel, /\{ harnessId: value\.slice\(0, sep\), modelId: value\.slice\(sep \+ 1\) \}/);
+ assert.doesNotMatch(panel, /applyRuntimeOptions/);
+});
+
+test("the panel offers inheriting the org default and names what is serving now", () => {
+ assert.match(panel, /Org default \(\$\{labelForRuntime\(config, config\.orgDefault\)\}\)/);
+ assert.match(panel, /!options\.some\(\(o\) => o\.value === selected\)/);
+ assert.match(panel, /no longer offered/);
+ assert.match(panel, /Saved — new conversations here run on/);
+ assert.match(panel, /The channel description in Slack names this model\./);
+});
+
+test("the panel is labelled, focus-keyed, and disabled while saving", () => {
+ assert.match(panel, /ariaLabel: "Default model for this project"/);
+ assert.match(panel, /focusKey: "context-model"/);
+ assert.match(panel, /disabled: contextModelState\.saving/);
+ assert.match(panel, /aria-live="polite"/);
+});
+
+test("every context loads and resets its model setting with the page", () => {
+ assert.match(contexts, /loadContextModel\(contextsState\.selected, drawContexts\)/);
+ assert.match(contexts, /resetContextModel\(\)/);
+ assert.match(contexts, /<aside class="context-settings"[^]*?contextModelSection\(c\.scopeId\)/);
+});
+
+test("model panel styles use the shell theme contract", () => {
+ const block = css.slice(css.indexOf(".context-model {"), css.indexOf("\n.ambient-policy {"));
+ assert.match(block, /color: var\(--muted-foreground\)/);
+ assert.match(block, /color: var\(--destructive/);
+ assert.doesNotMatch(block, /#[0-9a-f]{6}(?![^)]*\))/i);
+});
diff --git a/plugins/web-ui/test/core-wire-contract.ts b/plugins/web-ui/test/core-wire-contract.ts
index ca82c78a6..886638a85 100644
--- a/plugins/web-ui/test/core-wire-contract.ts
+++ b/plugins/web-ui/test/core-wire-contract.ts
@@ -1,4 +1,5 @@
-import type { Session, SessionEntry as CoreSessionEntry } from "../../../src/types.ts";
+import type { Session } from "../../../src/types.ts";
+import type { TranscriptEntry as CoreSessionEntry } from "../../../src/sessions/session-store.ts";
import type { ContextSummary, ProjectView } from "../../../src/api/app.ts";
import type { CoreContext, CoreProject, CoreSession, SessionEntry } from "../src/core-bridge.ts";
diff --git a/plugins/web-ui/test/crons-deep-link.test.ts b/plugins/web-ui/test/crons-deep-link.test.ts
new file mode 100644
index 000000000..da567ba77
--- /dev/null
+++ b/plugins/web-ui/test/crons-deep-link.test.ts
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const source = readFileSync(new URL("../src/crons.ts", import.meta.url), "utf8");
+const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");
+
+test("a run's worklog link addresses the chats view, not the page it was rendered on", () => {
+ assert.match(source, /class="cron-run-link" href=\$\{deepLinkPath\(UI_BASE, "chats", run\.sessionId\)\}/);
+ assert.doesNotMatch(source, /location\.pathname\}\?session=/);
+});
+
+test("a cron row is a real link to its own path", () => {
+ assert.match(source, /<a\s+class="cron-row-main"\s+href=\$\{deepLinkPath\(UI_BASE, "crons", null, null, c\.id\)\}/);
+});
+
+test("modified clicks fall through to the browser so open-in-tab and save-link still work", () => {
+ assert.match(source, /event\.metaKey \|\| event\.ctrlKey \|\| event\.shiftKey \|\| event\.altKey \|\| event\.button/);
+});
+
+test("opening a cron from the list pushes history, so Back returns to the list", () => {
+ assert.match(source, /openCron\(c, \{ push: true \}\)/);
+ assert.match(source, /if \(push\) history\.pushState\(null, "", next\);\s+else history\.replaceState/);
+ assert.match(shell, /addEventListener\("popstate"[\s\S]*?routeCronsHistory\(item\)/);
+});
+
+test("a failed load is never reported as a missing cron", () => {
+ assert.match(source, /const loaded = await refreshCrons/);
+ assert.match(source, /if \(!loaded\) return drawCronsPage\(\);/);
+ const body = source.slice(source.indexOf("export async function renderCronsPage"));
+ assert.ok(body.indexOf("if (!loaded)") < body.indexOf("wasn't found"));
+});
+
+test("a pending deep-linked cron is consumed even when the view changed mid-load", () => {
+ const body = source.slice(source.indexOf("export async function renderCronsPage"));
+ const consume = body.indexOf("pendingCronId = null");
+ const guard = body.indexOf('appState.currentView !== "crons") return', body.indexOf("await refreshCrons"));
+ assert.ok(consume !== -1 && guard !== -1 && consume < guard);
+});
diff --git a/plugins/web-ui/test/deep-link.test.ts b/plugins/web-ui/test/deep-link.test.ts
index 4bddc4faf..94003cba7 100644
--- a/plugins/web-ui/test/deep-link.test.ts
+++ b/plugins/web-ui/test/deep-link.test.ts
@@ -30,26 +30,64 @@ test("session ids are URI-encoded", () => {
});
test("parseDeepLink reads the view from the path", () => {
- assert.deepEqual(parseDeepLink("", "/crons", ""), { view: "crons", session: null });
- assert.deepEqual(parseDeepLink("/web-ui/", "/web-ui/crons", ""), { view: "crons", session: null });
- assert.deepEqual(parseDeepLink("", "/", "?session=s1"), { view: null, session: "s1" });
+ assert.deepEqual(parseDeepLink("", "/crons", ""), { view: "crons", session: null, item: null });
+ assert.deepEqual(parseDeepLink("/web-ui/", "/web-ui/crons", ""), { view: "crons", session: null, item: null });
+ assert.deepEqual(parseDeepLink("", "/", "?session=s1"), { view: null, session: "s1", item: null });
+});
+
+test("project paths open the contexts view with a resolvable project identifier", () => {
+ assert.deepEqual(parseDeepLink("", "/projects/atlas", ""), {
+ view: "contexts",
+ session: null,
+ item: "atlas",
+ });
+ assert.deepEqual(parseDeepLink("/web-ui/", "/web-ui/projects/channel/C0123", ""), {
+ view: "contexts",
+ session: null,
+ item: "channel:C0123",
+ });
+ assert.deepEqual(parseDeepLink("", "/projects/group/G9ABC", ""), {
+ view: "contexts",
+ session: null,
+ item: "group:G9ABC",
+ });
});
test("parseDeepLink degrades a malformed percent-escape to no view instead of throwing", () => {
- assert.deepEqual(parseDeepLink("", "/%E0%A4%A", ""), { view: null, session: null });
+ assert.deepEqual(parseDeepLink("", "/%E0%A4%A", ""), { view: null, session: null, item: null });
});
test("parseDeepLink still honors legacy ?view= links", () => {
- assert.deepEqual(parseDeepLink("", "/", "?view=crons"), { view: "crons", session: null });
+ assert.deepEqual(parseDeepLink("", "/", "?view=crons"), { view: "crons", session: null, item: null });
assert.deepEqual(parseDeepLink("/web-ui/", "/web-ui/", "?view=contexts&scope=channel:C1"), {
view: "contexts",
session: null,
+ item: null,
});
});
test("legacy connectors links resolve to the keychain view", () => {
- assert.deepEqual(parseDeepLink("", "/connectors", ""), { view: "keychain", session: null });
- assert.deepEqual(parseDeepLink("", "/", "?view=connectors"), { view: "keychain", session: null });
+ assert.deepEqual(parseDeepLink("", "/connectors", ""), { view: "keychain", session: null, item: null });
+ assert.deepEqual(parseDeepLink("", "/", "?view=connectors"), { view: "keychain", session: null, item: null });
+});
+
+test("a cron is addressed by /crons/<id>", () => {
+ assert.equal(deepLinkPath("", "crons", null, null, "abc 1"), "/crons/abc%201");
+ assert.deepEqual(parseDeepLink("", "/crons/abc%201", ""), { view: "crons", session: null, item: "abc 1" });
+ assert.deepEqual(parseDeepLink("/web-ui/", "/web-ui/crons/c1", ""), {
+ view: "crons",
+ session: null,
+ item: "c1",
+ });
+});
+
+test("an item id is rejected for views that are not addressed that way", () => {
+ assert.throws(() => deepLinkPath("", "chats", "s1", null, "x"));
+ assert.throws(() => deepLinkPath("", "contexts", null, "channel:C1", "x"));
+});
+
+test("only the first two path segments are addressed", () => {
+ assert.deepEqual(parseDeepLink("", "/crons/a/b", ""), { view: "crons", session: null, item: "a" });
});
test("sessionLink builds an absolute link under the serving base", () => {
diff --git a/plugins/web-ui/test/deploy-view.test.ts b/plugins/web-ui/test/deploy-view.test.ts
index 3622c9a93..df60323fb 100644
--- a/plugins/web-ui/test/deploy-view.test.ts
+++ b/plugins/web-ui/test/deploy-view.test.ts
@@ -126,7 +126,7 @@ test("the empty Yours message stays tab-local when a manageable transfer is Shar
permission: "write",
});
assert.equal(deploymentTab(transferred, "[email protected]"), "shared");
- assert.equal(deploymentTabEmptyMessage("yours"), "No apps in Yours.");
+ assert.equal(deploymentTabEmptyMessage("yours"), "No apps of your own yet.");
});
test("management actions fail closed when permission is missing or unknown", () => {
diff --git a/plugins/web-ui/test/deploys-source.test.ts b/plugins/web-ui/test/deploys-source.test.ts
index 4a5df7e16..e1f5a5ae9 100644
--- a/plugins/web-ui/test/deploys-source.test.ts
+++ b/plugins/web-ui/test/deploys-source.test.ts
@@ -63,4 +63,6 @@ test("the empty Yours tab does not imply the account has no deployments", () =>
const source = readFileSync(new URL("../src/deploys.ts", import.meta.url), "utf8");
assert.match(source, /deploymentTabEmptyMessage\(deployTab\)/);
assert.doesNotMatch(source, /No deployments yet\./);
+ const messages = readFileSync(new URL("../src/deploy-view.ts", import.meta.url), "utf8");
+ assert.doesNotMatch(messages, /You have no apps\./);
});
diff --git a/plugins/web-ui/test/field-select-source.test.ts b/plugins/web-ui/test/field-select-source.test.ts
new file mode 100644
index 000000000..2041f0229
--- /dev/null
+++ b/plugins/web-ui/test/field-select-source.test.ts
@@ -0,0 +1,43 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { readdirSync } from "node:fs";
+import test from "node:test";
+
+const srcDir = new URL("../src/", import.meta.url);
+const ui = readFileSync(new URL("ui.ts", srcDir), "utf8");
+const css = readFileSync(new URL("shell.css", srcDir), "utf8");
+
+test("the shell has exactly one dropdown, and it is a real select", () => {
+ const offenders = readdirSync(srcDir)
+ .filter((f) => f.endsWith(".ts"))
+ .filter((f) => readFileSync(new URL(f, srcDir), "utf8").includes("<select"));
+ assert.deepEqual(offenders, ["ui.ts"], "every dropdown goes through fieldSelect()");
+ assert.match(ui, /<select/);
+ assert.match(ui, /icon\(ChevronDown, 16\)/);
+});
+
+test("the dropdown keeps the accessible name, focus key and disabled state its callers pass", () => {
+ for (const attr of [
+ /id=\$\{props\.id \?\? nothing\}/,
+ /aria-label=\$\{props\.ariaLabel \?\? nothing\}/,
+ /aria-describedby=\$\{props\.describedBy \?\? nothing\}/,
+ /data-focus-key=\$\{props\.focusKey \?\? nothing\}/,
+ /\?disabled=\$\{props\.disabled \?\? false\}/,
+ ])
+ assert.match(ui, attr);
+});
+
+test("the chevron is inset from the edge, not pinned to it", () => {
+ const block = css.slice(css.indexOf(".field-select {"), css.indexOf(".field-select.compact > select"));
+ assert.match(block, /appearance: none/);
+ assert.match(block, /padding: 0 36px 0 10px/);
+ assert.match(block, /right: 12px/);
+ assert.match(block, /pointer-events: none/);
+});
+
+test("no page keeps its own select chrome now that one rule owns it", () => {
+ for (const dead of [".list-select select {", ".deploy-sort select {", ".ambient-enabled-select {\n align-self"])
+ assert.ok(!css.includes(dead) || dead.includes("align-self"), `${dead} should be gone`);
+ assert.doesNotMatch(css, /\.list-select select \{/);
+ assert.doesNotMatch(css, /\.deploy-sort select \{/);
+});
diff --git a/plugins/web-ui/test/layout-thrash.test.ts b/plugins/web-ui/test/layout-thrash.test.ts
index a6aaa7122..062723d55 100644
--- a/plugins/web-ui/test/layout-thrash.test.ts
+++ b/plugins/web-ui/test/layout-thrash.test.ts
@@ -6,7 +6,7 @@ const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "u
const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
test("resizeComposer skips the forced-reflow measure pass when the draft value is unchanged", () => {
- const fn = composer.match(/export function resizeComposer\(\): void \{[\s\S]*?\n\}/)?.[0] ?? "";
+ const fn = composer.match(/function resizeComposer\(\): void \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
const skip = fn.indexOf("if (ta.value === autosizedValue) return;");
const measure = fn.indexOf('ta.style.height = "auto"');
assert.ok(skip >= 0, "the value memo must gate the measure pass");
diff --git a/plugins/web-ui/test/model-options.test.ts b/plugins/web-ui/test/model-options.test.ts
index 4c3ba486a..329b6453b 100644
--- a/plugins/web-ui/test/model-options.test.ts
+++ b/plugins/web-ui/test/model-options.test.ts
@@ -9,7 +9,9 @@ import {
getModelOptionsForHarness,
harnessSupportsEffort,
harnessSupportsFastMode,
+ runtimeModelOptions,
} from "../src/model-options.ts";
+import { modelSupportsFastMode, setFastModeModelIds } from "../src/pi-models.ts";
test("the built-in picker includes Fable alongside Opus/Sonnet/Haiku", () => {
applyPickerModelIds(null);
@@ -56,6 +58,7 @@ test("the Codex picker can render and select the OpenAI model", () => {
test("runtime options qualify harness/model pairs and select the effective pair", () => {
applyRuntimeOptions(
+ null,
["pi", "codex"],
{ pi: ["claude-opus-4-8"], codex: ["gpt-5.6-sol"] },
{ harnessId: "codex", modelId: "gpt-5.6-sol" },
@@ -80,6 +83,7 @@ test("runtime options qualify harness/model pairs and select the effective pair"
test("runtime options preserve a fetched OpenRouter model as the selected web turn model", () => {
applyRuntimeOptions(
+ null,
["pi"],
{ pi: ["anthropic/claude-sonnet-4.5"] },
{ harnessId: "pi", modelId: "anthropic/claude-sonnet-4.5" },
@@ -94,6 +98,7 @@ test("runtime options preserve a fetched OpenRouter model as the selected web tu
test("runtime options hide retired persisted model ids", () => {
applyRuntimeOptions(
+ null,
["claude", "codex"],
{
claude: ["claude-fable-5", "claude-sonnet-4-6", "claude-sonnet-5"],
@@ -123,7 +128,7 @@ test("harness-only turn controls are exposed only where the adapter supports the
});
test("an all-retired list falls back within the approved harness", () => {
- applyRuntimeOptions(["codex"], { codex: ["gpt-5.5"] }, { harnessId: "codex", modelId: "gpt-5.5" });
+ applyRuntimeOptions(null, ["codex"], { codex: ["gpt-5.5"] }, { harnessId: "codex", modelId: "gpt-5.5" });
assert.deepEqual(getHarnessOptions(), [{ value: "codex", label: "Codex" }]);
assert.deepEqual(
getModelOptionsForHarness("codex").map((o) => o.label),
@@ -153,3 +158,42 @@ test("duplicate ids are de-duped, preserving first occurrence order", () => {
);
applyPickerModelIds(null);
});
+
+test("two panes on different scopes keep their own picker, default, and fast-mode set", () => {
+ applyRuntimeOptions("personal:me", ["pi"], { pi: ["claude-opus-5"] }, { harnessId: "pi", modelId: "claude-opus-5" });
+ setFastModeModelIds("personal:me", ["claude-opus-5"]);
+ applyRuntimeOptions(
+ "group:team",
+ ["codex"],
+ { codex: ["gpt-5.6-sol"] },
+ { harnessId: "codex", modelId: "gpt-5.6-sol" },
+ );
+ setFastModeModelIds("group:team", []);
+
+ assert.equal(
+ defaultModelValue("personal:me"),
+ "pi:claude-opus-5",
+ "the later scope must not capture the earlier one",
+ );
+ assert.equal(defaultModelValue("group:team"), "codex:gpt-5.6-sol");
+ assert.deepEqual(
+ getModelOptions("personal:me").map((o) => o.value),
+ ["pi:claude-opus-5"],
+ );
+ assert.equal(modelSupportsFastMode("personal:me", "claude-opus-5"), true);
+ assert.equal(modelSupportsFastMode("group:team", "claude-opus-5"), false);
+});
+
+test("a scope's own model list is derived without disturbing the active picker", () => {
+ applyPickerModelIds(["claude-opus-4-8"], "claude-opus-4-8");
+ const scoped = runtimeModelOptions(["pi", "codex"], { pi: ["claude-sonnet-5"], codex: ["gpt-5.6-sol"] });
+ assert.deepEqual(
+ scoped.map((o) => o.value),
+ ["pi:claude-sonnet-5", "codex:gpt-5.6-sol"],
+ );
+ assert.deepEqual(
+ getModelOptions().map((o) => o.value),
+ ["claude-opus-4-8"],
+ "reading a scope's options never re-points the composer's picker",
+ );
+});
diff --git a/plugins/web-ui/test/openrouter-turn.test.ts b/plugins/web-ui/test/openrouter-turn.test.ts
index 56b1488f0..00e936ed0 100644
--- a/plugins/web-ui/test/openrouter-turn.test.ts
+++ b/plugins/web-ui/test/openrouter-turn.test.ts
@@ -13,6 +13,7 @@ afterEach(() => {
test("a web turn submits the fetched OpenRouter model selected by runtime config", async () => {
applyRuntimeOptions(
+ null,
["pi"],
{ pi: ["anthropic/claude-sonnet-4.5"] },
{ harnessId: "pi", modelId: "anthropic/claude-sonnet-4.5" },
diff --git a/plugins/web-ui/test/pane-composer-source.test.ts b/plugins/web-ui/test/pane-composer-source.test.ts
index 21cf27de9..110710a23 100644
--- a/plugins/web-ui/test/pane-composer-source.test.ts
+++ b/plugins/web-ui/test/pane-composer-source.test.ts
@@ -5,19 +5,20 @@ import test from "node:test";
const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
-test("pane composer collapses to a single line in embed mode", () => {
- assert.match(css, /\.embed-layout \.composer-wrap \{[^}]*display: flex;/);
- assert.match(css, /\.embed-layout \.composer-toolbar \{\s*display: contents;/);
- assert.match(css, /\.embed-layout \.composer-input \{[^}]*min-height: 0;/);
- assert.match(composer, /Math\.max\(embedMode \? 0 : 48, content\)/);
+test("pane composer collapses to a single line — keyed off the pane, not a whole-document layout class", () => {
+ assert.doesNotMatch(css, /\.embed-layout/, "panes are elements now, not framed documents");
+ assert.match(css, /\[data-density\] \.composer-wrap \{[^}]*display: flex;/);
+ assert.match(css, /\[data-density\] \.composer-toolbar \{\s*display: contents;/);
+ assert.match(css, /\[data-density\] \.composer-input \{[^}]*min-height: 0;/);
+ assert.match(composer, /Math\.max\(ctx\.pane \? 0 : 48, content\)/);
});
test("phone touch layout cannot inflate a pane's composer controls", () => {
assert.match(
css,
- /\.embed-layout \.composer-toolbar \.icon-btn,\s*\.embed-layout \.composer-toolbar \.menu-button,\s*\.embed-layout \.composer-toolbar \.send-btn \{\s*width: 34px;\s*height: 34px;\s*min-height: 34px;/,
+ /\[data-density\] \.composer-toolbar \.icon-btn,\s*\[data-density\] \.composer-toolbar \.menu-button,\s*\[data-density\] \.composer-toolbar \.send-btn \{\s*width: 34px;\s*height: 34px;\s*min-height: 34px;/,
);
- assert.match(css, /\.embed-layout \.composer-left,\s*\.embed-layout \.composer-right \{\s*width: auto;/);
+ assert.match(css, /\[data-density\] \.composer-left,\s*\[data-density\] \.composer-right \{\s*width: auto;/);
});
test("pane settings control is visible without hover", () => {
diff --git a/plugins/web-ui/test/pane-focus.test.ts b/plugins/web-ui/test/pane-focus.test.ts
index 2dbfc70ee..f23985290 100644
--- a/plugins/web-ui/test/pane-focus.test.ts
+++ b/plugins/web-ui/test/pane-focus.test.ts
@@ -1,7 +1,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { JSDOM } from "jsdom";
-import { replaceChildrenPreservingFocus } from "../src/pane-focus.ts";
+import { readFileSync } from "node:fs";
+import { preservingFocus, replaceChildrenPreservingFocus } from "../src/pane-focus.ts";
test("re-rendered pane inputs keep focus and caret across multi-character typing", () => {
const dom = new JSDOM('<main><div><input data-focus-key="search" value="a"></div></main>');
@@ -20,3 +21,29 @@ test("re-rendered pane inputs keep focus and caret across multi-character typing
next.setSelectionRange(value.length, value.length);
}
});
+
+test("activating a pane cannot cost the composer its focus or caret", () => {
+ const dom = new JSDOM('<div class="dock"><div class="pane"><textarea>hi</textarea></div></div>');
+ const doc = dom.window.document;
+ const dock = doc.querySelector(".dock") as HTMLElement;
+ const pane = doc.querySelector(".pane") as HTMLElement;
+ const ta = doc.querySelector("textarea")!;
+ ta.focus();
+ ta.setSelectionRange(1, 1);
+
+ preservingFocus(doc, () => {
+ pane.remove();
+ dock.appendChild(pane);
+ });
+
+ assert.equal(doc.activeElement, ta);
+ assert.equal(ta.selectionStart, 1);
+});
+
+test("a pane focusin never re-activates the pane it is already in", () => {
+ const split = readFileSync(new URL("../src/split.ts", import.meta.url), "utf8");
+ const focusPane = split.match(/function focusPane\([\s\S]*?\n\}/)?.[0] ?? "";
+ assert.ok(focusPane, "focusPane not found");
+ assert.match(focusPane, /if \(!panel \|\| panel\.api\.isActive\) return;/, "re-activation remounts the pane");
+ assert.match(focusPane, /preservingFocus\(document, \(\) => panel\.api\.setActive\(\)\)/, "activation drops focus");
+});
diff --git a/plugins/web-ui/test/pi-models.test.ts b/plugins/web-ui/test/pi-models.test.ts
index a033097c8..8f586d466 100644
--- a/plugins/web-ui/test/pi-models.test.ts
+++ b/plugins/web-ui/test/pi-models.test.ts
@@ -31,12 +31,12 @@ test("models this pi-ai build lacks are cloned from a template of their own prov
});
test("fast-mode support is fed from core's runtime config, not a hardcoded client copy", () => {
- setFastModeModelIds([]);
- assert.equal(modelSupportsFastMode("claude-opus-4-8"), false);
-
- setFastModeModelIds(["claude-opus-4-8", "claude-opus-4-7"]);
- assert.equal(modelSupportsFastMode("claude-opus-4-8"), true);
- assert.equal(modelSupportsFastMode("claude-sonnet-4-6"), false);
- assert.equal(modelSupportsFastMode("claude-haiku-4-5"), false);
- assert.equal(modelSupportsFastMode(undefined), false);
+ setFastModeModelIds(null, []);
+ assert.equal(modelSupportsFastMode(null, "claude-opus-4-8"), false);
+
+ setFastModeModelIds(null, ["claude-opus-4-8", "claude-opus-4-7"]);
+ assert.equal(modelSupportsFastMode(null, "claude-opus-4-8"), true);
+ assert.equal(modelSupportsFastMode(null, "claude-sonnet-4-6"), false);
+ assert.equal(modelSupportsFastMode(null, "claude-haiku-4-5"), false);
+ assert.equal(modelSupportsFastMode(null, undefined), false);
});
diff --git a/plugins/web-ui/test/responsive-source.test.ts b/plugins/web-ui/test/responsive-source.test.ts
index f1a850c05..837318df3 100644
--- a/plugins/web-ui/test/responsive-source.test.ts
+++ b/plugins/web-ui/test/responsive-source.test.ts
@@ -23,7 +23,7 @@ test("mobile sidebar is modal, dismissible, and sized for touch", () => {
assert.match(shell, /main\.inert = modal/);
assert.match(
css,
- /\.layout\.sidebar-closed \.sidebar > :not\(\.brand\),\s*\.layout\.sidebar-closed \.brand-lockup \{[^}]*opacity: 0;\s*visibility: hidden;/,
+ /\.layout\.sidebar-closed \.sidebar > :not\(\.brand\):not\(#sidebar-top\),\s*\.layout\.sidebar-closed \.brand-lockup \{[^}]*opacity: 0;\s*visibility: hidden;/,
);
assert.match(shell, /sidebar\.setAttribute\("role", modal \? "dialog" : "navigation"\)/);
assert.match(
diff --git a/plugins/web-ui/test/runtime-config-handoff.test.ts b/plugins/web-ui/test/runtime-config-handoff.test.ts
new file mode 100644
index 000000000..5b1d49b75
--- /dev/null
+++ b/plugins/web-ui/test/runtime-config-handoff.test.ts
@@ -0,0 +1,74 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
+const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");
+const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");
+
+test("boot hands its runtime config to the composer instead of dropping it", () => {
+ assert.match(shell, /const personalScope = `personal:\$\{appState\.me\.user\}`;/);
+ assert.match(shell, /seedRuntimeConfig\(personalScope, runtimeConfig\);/);
+ const fetchAt = shell.indexOf("await fetchRuntimeConfig(personalScope)");
+ const seedAt = shell.indexOf("seedRuntimeConfig(personalScope, runtimeConfig)");
+ assert.ok(fetchAt > 0 && seedAt > fetchAt, "boot must seed the config it just fetched");
+});
+
+test("the first mount in the seeded scope renders from it — no blanking, no second fetch", () => {
+ const fn = composer.slice(
+ composer.indexOf("async function refreshRuntimeSelection"),
+ composer.indexOf("function applySelectedRuntime"),
+ );
+ assert.ok(fn, "refreshRuntimeSelection not found");
+ const seedRead = fn.indexOf("seededRuntime?.scopeId === scopeKey");
+ const blank = fn.indexOf("activeRuntimeConfig = null");
+ const fetchCall = fn.indexOf("await fetchRuntimeConfig(scopeId)");
+ assert.ok(seedRead > 0, "the seeded config must be consulted");
+ assert.ok(seedRead < blank, "consult the seed BEFORE blanking the composer");
+ assert.ok(seedRead < fetchCall, "consult the seed BEFORE refetching");
+ assert.match(fn, /if \(seeded\) \{\s*applySelectedRuntime\(seeded, agent\);\s*return;\s*\}/);
+ assert.match(fn, /seededRuntime\?\.scopeId === scopeKey \? seededRuntime\.config : null/);
+ assert.match(fn, /const scopeKey = runtimeScopeKey\(scopeId\);/);
+ assert.doesNotMatch(fn, /seededRuntime = null;/, "every pane booting on the seeded scope may read the seed");
+ const change = composer.slice(composer.indexOf("async function changeScopeRuntime"));
+ assert.match(
+ change.slice(0, change.indexOf("\n }")),
+ /seededRuntime = null;/,
+ "changing the scope default is what retires the boot seed",
+ );
+});
+
+test("a still-loading composer is not painted as a failure", () => {
+ const branch = composer.slice(
+ composer.indexOf("} else if (!approvalPauses.length && runtimePending) {"),
+ composer.indexOf("} else if (composerState.error) {"),
+ );
+ assert.ok(branch, "the runtime-pending branch not found");
+ assert.match(branch, /composerState\.error\s*\?/, "the branch must split on a real error");
+ assert.match(branch, /class="composer-note">Loading runtime settings…/, "loading is a note");
+ const loadingAt = branch.indexOf("Loading runtime settings…");
+ const errorClassAt = branch.indexOf('class="composer-error"');
+ assert.ok(errorClassAt >= 0 && errorClassAt < loadingAt, "only the real error keeps the error class");
+ assert.ok(
+ !/class="composer-error">[\s\S]{0,80}Loading runtime settings…/.test(branch),
+ "the loading placeholder must not render inside .composer-error",
+ );
+ const retryAt = branch.indexOf("Retry");
+ assert.ok(retryAt >= 0 && retryAt < loadingAt, "Retry stays on the error side");
+});
+
+test(".composer-error is the destructive colour — which is why loading must not use it", () => {
+ assert.match(css, /^\.composer-error \{\n {2}color: var\(--destructive/m);
+});
+
+test("a personal mount passing null still matches the seeded personal scope", () => {
+ const resolver = composer.slice(
+ composer.indexOf("function runtimeScopeKey"),
+ composer.indexOf("function modelOptionFor"),
+ );
+ assert.ok(resolver, "runtimeScopeKey not found");
+ assert.match(resolver, /if \(scopeId\) return scopeId;/, "a named scope is used as-is");
+ assert.match(resolver, /return user \? `personal:\$\{user\}` : null;/, "null resolves to the personal scope");
+ assert.match(composer, /seededRuntime = \{ scopeId: runtimeScopeKey\(scopeId\), config \};/);
+ assert.match(composer, /scopeKey !== null && seededRuntime\?\.scopeId === scopeKey/);
+});
diff --git a/plugins/web-ui/test/session-list.test.ts b/plugins/web-ui/test/session-list.test.ts
index a37fafb16..bf7899ece 100644
--- a/plugins/web-ui/test/session-list.test.ts
+++ b/plugins/web-ui/test/session-list.test.ts
@@ -363,15 +363,23 @@ test("rowIndicators: awaitingInput maps through", () => {
});
test("backgroundLabel: jobs and watches fold into one chip with a spoken label", () => {
- assert.deepEqual(backgroundLabel(1, 0), { count: 1, label: "1 background job running" });
- assert.deepEqual(backgroundLabel(2, 1), { count: 3, label: "2 background jobs running · 1 watch armed" });
- assert.deepEqual(backgroundLabel(0, 2), { count: 2, label: "2 watches armed" });
+ assert.deepEqual(backgroundLabel(1, 0), { jobs: 1, watches: 0, label: "1 background job running" });
+ assert.deepEqual(backgroundLabel(2, 1), {
+ jobs: 2,
+ watches: 1,
+ label: "2 background jobs running · 1 watch armed",
+ });
+ assert.deepEqual(backgroundLabel(0, 2), { jobs: 0, watches: 2, label: "2 watches armed" });
assert.equal(backgroundLabel(0, 0), null, "nothing running, nothing to say");
});
test("rowIndicators: background counts flow through backgroundLabel — zero counts treated as absent", () => {
const both = rowIndicators({ ...saved("1", "web:u:x"), backgroundJobs: 2, watches: 1 }, null);
- assert.deepEqual(both.background, { count: 3, label: "2 background jobs running · 1 watch armed" });
+ assert.deepEqual(both.background, {
+ jobs: 2,
+ watches: 1,
+ label: "2 background jobs running · 1 watch armed",
+ });
assert.equal(rowIndicators({ ...saved("1", "web:u:x"), backgroundJobs: 0, watches: 0 }, null).background, null);
assert.equal(rowIndicators(saved("1", "web:u:x"), null).background, null);
});
@@ -379,14 +387,15 @@ test("rowIndicators: background counts flow through backgroundLabel — zero cou
test("conversationBackground: resolves the mounted conversation by session id", () => {
const list = [saved("1", "web:u:a"), { ...saved("2", "web:u:b"), backgroundJobs: 2, watches: 1 }];
assert.deepEqual(conversationBackground(list, "2", null), {
- count: 3,
+ jobs: 2,
+ watches: 1,
label: "2 background jobs running · 1 watch armed",
});
});
test("conversationBackground: falls back to threadRef while the conversation is still pending adoption", () => {
const list = [{ ...saved("1", "web:u:a"), watches: 1 }];
- assert.deepEqual(conversationBackground(list, null, "web:u:a"), { count: 1, label: "1 watch armed" });
+ assert.deepEqual(conversationBackground(list, null, "web:u:a"), { jobs: 0, watches: 1, label: "1 watch armed" });
});
test("conversationBackground: null when the conversation has nothing running, or isn't in the list", () => {
diff --git a/plugins/web-ui/test/sidebar-rail-source.test.ts b/plugins/web-ui/test/sidebar-rail-source.test.ts
index 65fc9cd06..04cedafc3 100644
--- a/plugins/web-ui/test/sidebar-rail-source.test.ts
+++ b/plugins/web-ui/test/sidebar-rail-source.test.ts
@@ -19,12 +19,30 @@ test("hidden sidebar innards are out of the focus order and keep their layout wh
assert.match(css, /\.sidebar > :not\(\.brand\) \{\s*min-width: calc\(var\(--sidebar-w\) - 16px\);/);
assert.match(
css,
- /\.layout\.sidebar-closed \.sidebar > :not\(\.brand\),\s*\.layout\.sidebar-closed \.brand-lockup \{[^}]*opacity: 0;\s*visibility: hidden;\s*\}/,
+ /\.layout\.sidebar-closed \.sidebar > :not\(\.brand\):not\(#sidebar-top\),\s*\.layout\.sidebar-closed \.brand-lockup \{[^}]*opacity: 0;\s*visibility: hidden;\s*\}/,
);
assert.doesNotMatch(css, /transition:[^;}]*visibility/);
assert.doesNotMatch(shell, /sidebar\.inert/);
});
+test("the collapsed rail keeps icon-only navigation instead of going empty", () => {
+ assert.match(
+ css,
+ /\.layout\.sidebar-closed #sidebar-top \{\s*min-width: 0;[^}]*min-height: 0;\s*overflow-y: auto;\s*\}/,
+ );
+ assert.match(
+ css,
+ /\.layout\.sidebar-closed #sidebar-top \.new-chat span,\s*\.layout\.sidebar-closed #sidebar-top \.navrow span,\s*\.layout\.sidebar-closed #sidebar-top \.nav-section-toggle,\s*\.layout\.sidebar-closed #sidebar-top \.section-label \{\s*display: none;/,
+ );
+ assert.match(css, /\.layout\.sidebar-closed #sidebar-top \.nav-group\.collapsed \{[^}]*grid-template-rows: 1fr;/);
+ assert.match(
+ css,
+ /\.layout\.sidebar-closed #sidebar-top \.new-chat,\s*\.layout\.sidebar-closed #sidebar-top \.navrow \{\s*justify-content: center;/,
+ );
+ // Icon-only rows need tooltips to carry their labels.
+ assert.match(shell, /class="navrow[^`]*title=\$\{label\}/);
+});
+
test("narrow viewports keep the rail in flow and size it for touch + safe area", () => {
const narrow = css.slice(css.indexOf("@media (max-width: 860px)"));
assert.match(narrow, /--rail-w: calc\(max\(8px, env\(safe-area-inset-left\)\) \+ 52px\)/);
diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.ts
index 5da5d8f02..6a3e92172 100644
--- a/plugins/web-ui/test/split-canvas-entry.test.ts
+++ b/plugins/web-ui/test/split-canvas-entry.test.ts
@@ -6,11 +6,14 @@ const read = (f: string): string => readFileSync(new URL(`../src/${f}`, import.m
const split = read("split.ts");
const sessions = read("sessions.ts");
const shell = read("shell.ts");
+const chat = read("chat.ts");
const layout = read("split-layout.ts");
const css = read("shell.css");
const fn = (src: string, name: string): string => {
- const body = src.match(new RegExp(`^(?:export )?function ${name}\\([\\s\\S]*?\\n\\}`, "m"))?.[0] ?? "";
+ const top = src.match(new RegExp(`^(?:export )?(?:async )?function ${name}\\([\\s\\S]*?\\n\\}`, "m"))?.[0];
+ const nested = src.match(new RegExp(`^ {2}(?:async )?function ${name}\\([\\s\\S]*?\\n {2}\\}`, "m"))?.[0];
+ const body = top ?? nested ?? "";
assert.ok(body, `${name} not found`);
return body;
};
@@ -22,12 +25,15 @@ test("no new-chat affordance can cost the user their canvas", () => {
assert.match(add, /return true;\n\}$/, "having split, the canvas owns the click");
assert.doesNotMatch(add.slice(add.indexOf("splitPane(")), /return false/, "a full canvas must not fall through");
- assert.match(shell, /if \(!addBlankPane\(\)\) newChat\(\);/);
+ assert.match(shell, /if \(!addBlankPane\(\)\) mainConversation\(\)\.newChat\(\);/);
const plus = fn(sessions, "startProjectChat");
const claimed = plus.indexOf("addBlankPane(scopeId)");
assert.ok(claimed > 0, "the project + must offer the click to the canvas");
assert.match(plus.slice(claimed), /^addBlankPane\(scopeId\)\) return;/m, "and bail out when the canvas takes it");
- assert.ok(plus.indexOf("addPendingSession(newChat(") > claimed, "only then may it mount a single chat");
+ assert.ok(
+ plus.indexOf("addPendingSession(mainConversation().newChat(") > claimed,
+ "only then may it mount a single chat",
+ );
assert.match(fn(split, "exitSplitIfActive"), /splitState\.active = false;/);
assert.doesNotMatch(fn(split, "exitSplitIfActive"), /removeItem|lastLayout = null/);
@@ -35,15 +41,29 @@ test("no new-chat affordance can cost the user their canvas", () => {
test("a pane opened from a project's + starts its chat in that project", () => {
assert.match(split, /scopeId\?: string;/, "PaneParams must carry the project");
- const src = fn(split, "paneSrc");
- assert.match(src, /scope=\$\{encodeURIComponent\(params\.scopeId\)\}/);
- assert.match(src, /if \(sessionId\) return/, "an adopted session still wins over the seed scope");
-
- const embed = shell.match(/if \(embedMode\) \{[\s\S]*?\n {4}\}\n {4}return;/)?.[0] ?? "";
- assert.ok(embed, "the embed boot branch not found");
- assert.match(embed, /await ensureContexts\(\)\)\.find\(\(c\) => c\.scopeId === scope\)/);
- assert.doesNotMatch(embed, /newChat\(\{ scopeId: scope/, "the URL's scope must not reach newChat unchecked");
- assert.match(embed, /newChat\(context \? \{ scopeId: context\.scopeId/);
+ const load = split.match(/private async load\(\): Promise<void> \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
+ assert.ok(load, "the pane loader not found");
+ const seeded = load.indexOf("contextsState.list.find((c) => c.scopeId === scopeId)");
+ assert.ok(seeded > 0, "the seed scope must resolve against contexts the viewer can actually use");
+ assert.ok(load.indexOf("if (!wanted)") < seeded, "an adopted session still wins over the seed scope");
+ assert.doesNotMatch(load, /newChat\(\{ scopeId: scopeId/, "an unchecked scope must not reach newChat");
+ assert.match(load, /newChat\(context \? \{ scopeId: context\.scopeId/);
+});
+
+test("a pane is an element in this document — never a second copy of the app", () => {
+ assert.doesNotMatch(split, /iframe/i, "panes must not reload the whole SPA per conversation");
+ assert.doesNotMatch(split, /postMessage/, "same-document panes talk by call, not by message");
+ assert.doesNotMatch(split, /defaultRenderer: "always"/, "a pane behind a tab must cost nothing until shown");
+ assert.match(split, /createConversation\(\{/, "each pane owns a conversation instance");
+ assert.match(split, /disposeConversation\(this\.conversation\)/, "and releases it when the pane closes");
+ const load = split.match(/private async load\(\): Promise<void> \{[\s\S]*?\n {2}\}/)?.[0] ?? "";
+ assert.match(
+ load,
+ /if \(this\.loaded \|\| this\.disposed\) return;/,
+ "a pane loads its transcript once, and never after it closes",
+ );
+ assert.match(load, /if \(this\.disposed\) return;/, "and drops the continuation if the pane closed mid-load");
+ assert.match(split, /onDidVisibilityChange\(\(e\) => \{\s*\n\s*if \(e\.isVisible\) void this\.load\(\);/);
});
test("a conversation dropped on a pane's tab strip joins that pane — and only there", () => {
@@ -94,3 +114,59 @@ test("the tile cap only judges dockview's own panel drags", () => {
assert.ok(bail > 0, "a foreign drag must be waved through");
assert.ok(bail < hold.indexOf("dropAddsTile"), "before the tile arithmetic, not after");
});
+
+test("boot mounts a restored canvas before it awaits the session list", () => {
+ const boot = shell.match(/export async function boot\(\): Promise<void> \{[\s\S]*?\n\}/)?.[0] ?? "";
+ assert.ok(boot, "boot not found");
+ const early = boot.indexOf("if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas();");
+ const listAwait = boot.indexOf("await refreshSessions({ showLoading: true });");
+ assert.ok(early > 0, "boot must offer the canvas its head start");
+ assert.ok(listAwait > 0, "boot still loads the session list");
+ assert.ok(early < listAwait, "the mount must come BEFORE the list fetch the panes never read");
+
+ assert.match(boot, /const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;/);
+
+ assert.match(
+ boot.slice(listAwait),
+ /\} else if \(!mountRestoredCanvas\(\) && !mainConversation\(\)\.state\.threadRef\) \{/,
+ );
+ const mount = fn(split, "mountRestoredCanvas");
+ assert.match(mount, /^ {2}if \(splitState\.active && \(dockApi\?\.panels\.length \?\? 0\) > 0\) return true;/m);
+});
+
+test("boot's fallback never replaces a chat the user mounted during the wait", () => {
+ const boot = shell.match(/export async function boot\(\): Promise<void> \{[\s\S]*?\n\}/)?.[0] ?? "";
+ const listAwait = boot.indexOf("await refreshSessions({ showLoading: true });");
+ const tail = boot.slice(listAwait);
+ assert.match(tail, /\} else if \(!mountRestoredCanvas\(\) && !mainConversation\(\)\.state\.threadRef\) \{/);
+ const guard = tail.indexOf("!mainConversation().state.threadRef");
+ const mint = tail.indexOf("newChat();", guard);
+ assert.ok(guard > 0 && mint > guard, "the guard must gate the mint, not follow it");
+
+ assert.match(chat, /^ {2}function mountContinuable\(/m);
+ assert.match(fn(chat, "mountContinuable"), /chatState\.threadRef = threadRef;/);
+
+ const reconcile = fn(split, "reconcileAfterClose");
+ assert.match(
+ reconcile,
+ /exitSplitIfActive\(\);\s*\n\s*mainConversation\(\)\.newChat\(\);/,
+ "a blank lone survivor mounts a new chat",
+ );
+ assert.match(reconcile, /void maximizePane\(params\);/, "a lone survivor with a session is maximized");
+ assert.match(fn(split, "exitSplitIfActive"), /splitState\.active = false;/);
+});
+
+test("a pane gives the conversation the same height chain the full-screen .main does", () => {
+ // .custom-chat sizes itself with flex: 1 / min-height: 0, so every container it
+ // mounts into must be a flex column of definite height — .main is; the pane
+ // wrapper must be too, or the transcript never scroll-contains and the composer
+ // trails the content instead of pinning to the pane's bottom edge.
+ const main = css.match(/^\.main \{[^}]*\}/m)?.[0] ?? "";
+ assert.match(main, /display: flex;/);
+ assert.match(main, /flex-direction: column;/);
+ const pane = css.match(/^\.split-pane-chat \{[^}]*\}/m)?.[0] ?? "";
+ assert.match(pane, /display: flex;/, "the pane wrapper must be a flex container");
+ assert.match(pane, /flex-direction: column;/, "…a column, like .main");
+ assert.match(pane, /height: 100%;/, "…of definite height");
+ assert.match(pane, /overflow: hidden;/, "…that clips instead of growing the pane");
+});
diff --git a/plugins/web-ui/test/steer-recovery-source.test.ts b/plugins/web-ui/test/steer-recovery-source.test.ts
new file mode 100644
index 000000000..b101dc6c3
--- /dev/null
+++ b/plugins/web-ui/test/steer-recovery-source.test.ts
@@ -0,0 +1,51 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+const bridge = readFileSync(new URL("../src/core-bridge.ts", import.meta.url), "utf8");
+const conversations = readFileSync(new URL("../src/conversations.ts", import.meta.url), "utf8");
+const chat = readFileSync(new URL("../src/chat.ts", import.meta.url), "utf8");
+
+test("signalLiveRun reports a terminal/vanished run as an outcome instead of throwing", () => {
+ assert.match(
+ bridge,
+ /export type SignalOutcome = \{ ok: true \} \| \{ ok: false; reason: string; replayed\?: boolean \};/,
+ );
+ assert.match(bridge, /err\.status === 409 \|\| err\.status === 404/);
+ assert.match(bridge, /\.\.\.\(body\.replayed \? \{ replayed: true \} : \{\}\)/);
+});
+
+test("a server-side run starting for an open conversation attaches the view (working event, not just visibilitychange)", () => {
+ assert.match(conversations, /if \(event\.state === "working"\) for \(const conv of live\) conv\.resumeIfIdle\(\);/);
+});
+
+test("resuming a tracked run pulls the transcript first so the triggering message is on screen", () => {
+ const at = chat.indexOf("async function resumeTrackedRun");
+ assert.ok(at >= 0);
+ const body = chat.slice(at, chat.indexOf("agent.streamFn = makeRunResumeStreamFn", at));
+ assert.match(body, /await refreshTranscriptFromEntries\(agent\);/);
+});
+
+const composer = readFileSync(new URL("../src/composer.ts", import.meta.url), "utf8");
+
+test("a steer typed before the run slot goes live is held and delivered, never dropped", () => {
+ const at = composer.indexOf("async function sendSteer");
+ assert.ok(at >= 0);
+ const body = composer.slice(at, composer.indexOf("async function deliverSteer", at));
+ // the old guard silently returned when the slot had no run id yet
+ assert.doesNotMatch(
+ body,
+ /if \(!text \|\| !ctx\.chat\.hasLiveRun\(\)\) return;/,
+ "steer dropped in the submit window",
+ );
+ assert.match(body, /steerWhenLive\(agent, text, 0\);/);
+});
+
+test("steerWhenLive settles every way a run slot can: live steer, ended resend, timeout restore", () => {
+ const at = composer.indexOf("function steerWhenLive");
+ assert.ok(at >= 0);
+ const body = composer.slice(at, composer.indexOf("// The run ended before the steer landed", at));
+ assert.match(body, /void deliverSteer\(agent, text\);/);
+ assert.match(body, /recoverEndedRunSteer\(agent, text, \{\}\);/);
+ assert.match(body, /composerState\.draft = composerState\.draft\.trim\(\)/);
+});
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.ts
index e121e52ff..21ba292a0 100644
--- a/src/api/app-helpers.ts
+++ b/src/api/app-helpers.ts
@@ -486,6 +486,23 @@ export function createAppHelpers(deps: AppDeps, app: App) {
for (const signal of await deps.signals.takePending(runId)) {
if (signal.kind === "abort") continue;
if (!signal.request) {
+ // A steer sent through /v1/runs/:id/signal carries no TurnRequest. Its text is
+ // still a real user message — re-enqueue it on the run's own request instead of
+ // dropping it, so a steer that raced the run's end is never silently lost.
+ const orphanRun = signal.text?.trim() ? await deps.runs.get(runId) : null;
+ if (orphanRun) {
+ try {
+ const { displayText: _d, attachments: _a, approval: _ap, ...base } = orphanRun.request;
+ const { run: fresh } = await deps.runs.enqueue({
+ sessionId: orphanRun.sessionId,
+ request: { ...base, text: signal.text! },
+ });
+ drained.push({ signal, replayRunId: fresh.id });
+ continue;
+ } catch (err) {
+ swallow(`signals: requestless orphaned-steer replay for run ${runId}`, err);
+ }
+ }
console.warn(
`[signals] orphaned ${signal.kind} for terminal run ${runId} has no stored request — dropped: ${signal.text?.slice(0, 120) ?? ""}`,
);
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index e12f5f8a1..9502a5f7e 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -24,6 +24,7 @@ export function createSessionMethods(
App,
| "getSession"
| "getSessionForViewer"
+ | "getSessionEntryForViewer"
| "listFilesForViewer"
| "uploadFileForViewer"
| "openFileForViewer"
@@ -90,6 +91,15 @@ export function createSessionMethods(
return { session, entries: w.entries, ...(w.earlier > 0 ? { earlierEntries: w.earlier } : {}) };
},
+ async getSessionEntryForViewer(sessionId, principalId, seq) {
+ const session = (await sessionsForViewer(principalId)).find((s) => s.id === sessionId);
+ if (!session) return null;
+ const entry = transcriptEntries(await deps.sessions.visibleEntries(sessionId, principalId)).find(
+ (e) => e.seq === seq,
+ );
+ return entry ? { entry } : null;
+ },
+
listFilesForViewer(principalId, opts, inScope) {
return filesForViewer(principalId, opts, inScope);
},
diff --git a/src/api/app-turn.ts b/src/api/app-turn.ts
index e30f6fb2a..17d835f0e 100644
--- a/src/api/app-turn.ts
+++ b/src/api/app-turn.ts
@@ -502,7 +502,12 @@ export function createTurnMethods(
const after = await deps.runs.get(runId);
if (!after || isTerminal(after.status)) {
await replayOrphanedRunSignals(runId);
- return { accepted: false, reason: "terminal" };
+ if (signal.kind !== "steer") return { accepted: false, reason: "terminal" };
+ // The steer was stored before the run went terminal, so its text is replayed as
+ // a fresh turn (by this drain, the onTerminal hook, or the orphan sweeper —
+ // whoever drains first). Tell the caller so it attaches to the fresh run
+ // instead of treating the message as lost.
+ return { accepted: false, reason: "terminal", replayed: true };
}
return { accepted: true };
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index d6db58d28..cdb801544 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -13,7 +13,7 @@ import type { OutgoingAttachment } from "../types.ts";
import type { Readable } from "node:stream";
import { type FileArtifact, type FileArtifactStore, type ListOwnedOptions } from "../files/file-artifact-store.ts";
import type { IdentityService } from "../identity/identity-service.ts";
-import type { SessionStore } from "../sessions/session-store.ts";
+import type { SessionStore, TranscriptEntry } from "../sessions/session-store.ts";
import { type Sandbox } from "../sandbox/sandbox.ts";
import type { ProcessRegistry } from "../processes/process-registry.ts";
import type { MonitorStore } from "../monitors/monitor-store.ts";
@@ -239,17 +239,26 @@ export interface App {
finishedAt: number | null;
} | null>;
activeRunForThread(threadRef: string, viewer?: string): Promise<{ runId: string } | null>;
- signalRun(runId: string, signal: RunSignal, viewer?: string): Promise<{ accepted: boolean; reason?: string }>;
+ signalRun(
+ runId: string,
+ signal: RunSignal,
+ viewer?: string,
+ ): Promise<{ accepted: boolean; reason?: string; replayed?: boolean }>;
replayOrphanedRunSignals(runId: string): Promise<void>;
getSession(
sessionId: string,
window?: TranscriptWindow,
- ): Promise<{ session: Session; entries: SessionEntry[]; earlierEntries?: number } | null>;
+ ): Promise<{ session: Session; entries: TranscriptEntry[]; earlierEntries?: number } | null>;
getSessionForViewer(
sessionId: string,
principalId: string,
window?: TranscriptWindow,
- ): Promise<{ session: Session; entries: SessionEntry[]; earlierEntries?: number } | null>;
+ ): Promise<{ session: Session; entries: TranscriptEntry[]; earlierEntries?: number } | null>;
+ getSessionEntryForViewer(
+ sessionId: string,
+ principalId: string,
+ seq: number,
+ ): Promise<{ entry: SessionEntry } | null>;
listSessions(principalId: string): Promise<Session[]>;
sessionBackground(sessionId: string, viewer: string): Promise<SessionBackgroundView | null>;
readSessionBackgroundOutput(
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index ad14714b4..7af8045e7 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -20,6 +20,7 @@ import { CONFIG_DEFAULTS } from "../../config.ts";
import { resolveShareTarget as resolveShareTargetGrammar } from "../artifact-share.ts";
import { mintDeployOwnerToken, verifyDeployGitAccess, verifyDeployOwnerToken } from "../../deploy/access-token.ts";
import { EDIT_WIDGET_JS, EDIT_WIDGET_PATH_PREFIX, editWidgetTag } from "../../deploy/edit-widget.ts";
+import { principalDestination } from "../../reach/reach.ts";
import { portalSessionSub } from "../../deploy/viewer-session.ts";
import { proxyHeaders } from "../../util/http-proxy.ts";
@@ -759,6 +760,32 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
if (deps.auditLog?.recordOnce) await deps.auditLog.recordOnce(`reach_denied|${sub}|${slug}|${hour}`, ev);
else deps.auditLog?.record(ev);
}
+ if (reach.status === "denied" && ctx.method === "POST" && pathname === REQUEST_ACCESS_PATH) {
+ const d = await app.getDeployment(slug).catch(() => null);
+ if (!d) {
+ sendJson(res, 404, { error: "not_found" });
+ return true;
+ }
+ // The recipient is the app's owner: the personal home scope if it has one, else whoever created it.
+ const [ownerKind, ownerRef] = String(d.ownerScopeId).split(":", 2);
+ const ownerId = ownerKind === "personal" && ownerRef ? ownerRef : d.createdBy;
+ const label = d.displayName ?? d.name ?? slug;
+ // One request per visitor per app per day — the idempotent outbox absorbs button mashing.
+ const day = Math.floor(Date.now() / 86_400_000);
+ try {
+ await app.enqueueDelivery({
+ destination: principalDestination(ownerId, sub),
+ text:
+ `${sub} is asking for access to your app "${label}" (https://${rawHost}/). ` +
+ `They signed in but the app isn't shared with them. To grant it, share the deployment with personal:${sub}.`,
+ idempotencyKey: `deploy-access-request:${slug}:${sub}:${day}`,
+ });
+ sendJson(res, 200, { ok: true });
+ } catch {
+ sendJson(res, 502, { error: "delivery_failed", message: "the request could not be delivered — try again later" });
+ }
+ return true;
+ }
if (reach.status === "denied" && wantsHtml) {
res.writeHead(403, {
"content-type": "text/html; charset=utf-8",
@@ -786,11 +813,20 @@ p{color:#a3a3a3;margin:0 0 8px}b{color:#fafafa}a{color:#fafafa}</style></head>
<body><div class="card"><h1>${escapeHtml(title)}</h1>${paragraphsHtml}</div></body></html>`;
}
+const REQUEST_ACCESS_PATH = "/__claw__/request-access";
+
function notSharedHtml(sub: string): string {
return gateCardHtml(
"This app hasn't been shared with you",
`<p>You're signed in as <b>${escapeHtml(sub)}</b>, but this app's owner hasn't shared it with you.</p>
-<p>Ask the owner for access, or for the app's share link.</p>`,
+<p>Ask the owner for access, or for the app's share link.</p>
+<p><button id="req" style="margin-top:12px;padding:8px 18px;border-radius:8px;border:1px solid #3f3f3f;
+background:#fafafa;color:#0a0a0a;font:inherit;font-weight:600;cursor:pointer">Request access</button></p>
+<script>document.getElementById("req").addEventListener("click",async function(){
+var b=this;b.disabled=true;b.textContent="Sending\u2026";
+try{var r=await fetch(${JSON.stringify(REQUEST_ACCESS_PATH)},{method:"POST"});
+b.textContent=r.ok?"Request sent \u2713":"Couldn't send \u2014 try again";b.disabled=r.ok;}
+catch(e){b.textContent="Couldn't send \u2014 try again";b.disabled=false;}});</script>`,
);
}
diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.ts
index 922608c21..7310e092f 100644
--- a/src/api/routes/surface.ts
+++ b/src/api/routes/surface.ts
@@ -135,6 +135,20 @@ async function getSession(ctx: ApiCtx): Promise<void> {
return sendJson(res, 200, found);
}
+async function getSessionEntry(ctx: ApiCtx): Promise<void> {
+ const { res, app, url } = ctx;
+ const id = ctx.params.id!;
+ const viewer = url.searchParams.get("viewer");
+ if (!viewer) return sendJson(res, 400, { error: "bad_request", message: "viewer required" });
+ const seq = Number(ctx.params.seq);
+ if (!Number.isInteger(seq) || seq < 0) {
+ return sendJson(res, 400, { error: "bad_request", message: "seq must be a non-negative integer" });
+ }
+ const found = await app.getSessionEntryForViewer(id, viewer, seq);
+ if (!found) return sendJson(res, 404, { error: "not_found" });
+ return sendJson(res, 200, found);
+}
+
async function getAgentConversation(ctx: ApiCtx): Promise<void> {
const { res, app, url, capability } = ctx;
if (!capability) {
@@ -1224,6 +1238,7 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [
auth: "source",
handle: getSessionBackgroundOutput,
},
+ { method: "GET", path: "/v1/sessions/:id/entries/:seq", auth: "source", handle: getSessionEntry },
{ method: "GET", path: "/v1/sessions/:id", auth: "source", handle: getSession },
{ method: "GET", path: "/v1/files/:id/content", auth: "either", handle: getFileContent },
{ method: "POST", path: "/v1/files/upload", auth: "source", handle: uploadFile },
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index 8d5c73282..67f88aa97 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -55,7 +55,8 @@ interface DirectoryPush {
export interface SlackCoreClient {
externalSlackParticipants(): Promise<boolean>;
- effectiveModelName(scope: ScopeId): Promise<string>;
+ surfaceHeaderFacts(scope: ScopeId): Promise<{ agentLabel?: string; modelName: string }>;
+ onScopeModelChanged(listener: (scope: ScopeId) => void): void;
stageBlob(bytes: Uint8Array): Promise<{ blobId: string; sizeBytes: number }>;
readBlob(blobId: string): Promise<Buffer>;
readFileArtifact(artifactId: string, viewerId: string): Promise<Buffer>;
@@ -105,6 +106,11 @@ export interface SlackCoreClientDeps {
pickAckEmoji?(text: string, candidates: readonly string[]): Promise<string | undefined>;
ackPicks?: AckEmojiPickStore;
ackModelId?: () => string | undefined;
+ brandingDefault?: { selfLabel?: string };
+}
+
+function agentLabelFrom(raw: string | undefined): string | undefined {
+ return raw?.replace(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/g, "").slice(0, 40) || undefined;
}
const RUN_FALLBACK_POLL_MS = 1_000;
@@ -122,9 +128,17 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien
return (await deps.config.getExternalSlackParticipantsDurable(orgScope)) === true;
},
- async effectiveModelName(scope) {
- const choice = await resolveRuntimeChoiceDurable(deps.config, orgScope, scope, deps.runtimeFallback);
- return modelDisplayName(choice.modelId);
+ async surfaceHeaderFacts(scope) {
+ const [choice, branding] = await Promise.all([
+ resolveRuntimeChoiceDurable(deps.config, orgScope, scope, deps.runtimeFallback),
+ deps.config.getBrandingDurable(orgScope),
+ ]);
+ const agentLabel = agentLabelFrom(branding?.selfLabel ?? deps.brandingDefault?.selfLabel);
+ return { ...(agentLabel ? { agentLabel } : {}), modelName: modelDisplayName(choice.modelId) };
+ },
+
+ onScopeModelChanged(listener) {
+ deps.config.onRuntimeSelectionChanged((scope) => listener(scope));
},
async stageBlob(bytes) {
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index c50c93edd..2cc5fc156 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -10,6 +10,7 @@ function pat(method: string, template: string, field?: Field): Rule {
const USER_SCOPED: Rule[] = [
pat("GET", "/v1/sessions/:id", { in: "query", name: "viewer" }),
+ pat("GET", "/v1/sessions/:id/entries/:seq", { in: "query", name: "viewer" }),
pat("GET", "/v1/sessions/:id/approvals", { in: "query", name: "viewer" }),
pat("GET", "/v1/sessions/:id/background", { in: "query", name: "viewer" }),
pat("GET", "/v1/sessions/:id/background/:pid/output", { in: "query", name: "viewer" }),
diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.ts
index cba1a0e04..2b0fe16e6 100644
--- a/src/resolution/config-store.ts
+++ b/src/resolution/config-store.ts
@@ -162,6 +162,7 @@ export interface ScopedConfigStore {
acknowledgeRuntimeSelection(id: ScopeId): void;
acknowledgeRuntimeSelectionLatest(id: ScopeId): Promise<void>;
getRuntimeSelectionDurable(id: ScopeId): Promise<ScopedRuntimeSelection | null>;
+ onRuntimeSelectionChanged(listener: (id: ScopeId) => void): void;
getApprovedHarnesses(): string[] | null;
setApprovedHarnesses(ids: string[] | null): void;
getApprovedHarnessesDurable(): Promise<string[] | null>;
@@ -274,6 +275,16 @@ export function createMemoryConfigStore(
pendingWrites.set(key, pending);
void pending.catch(persistWarn(what));
};
+ const runtimeSelectionListeners = new Set<(id: ScopeId) => void>();
+ const noteRuntimeSelectionChanged = (id: ScopeId): void => {
+ for (const listener of runtimeSelectionListeners) {
+ try {
+ listener(id);
+ } catch (e) {
+ console.error("[config] runtime-selection listener failed:", e);
+ }
+ }
+ };
const connectorClients = opts.connectorClients ?? createMemoryMap<StoredConnectorClient>();
const connectorKey = deriveConnectorKey(opts.connectorSecretKey ?? randomBytes(32), "connector-clients");
const connectorMapKey = (id: ScopeId, provider: string) => `${id}|${provider}`;
@@ -631,6 +642,7 @@ export function createMemoryConfigStore(
baseModels.set(id, row);
persist(`model:${id}`, "base model", () => baseModelStore.put(id, row));
}
+ noteRuntimeSelectionChanged(id);
},
getRuntimeSelection(id) {
const row = baseModels.get(id);
@@ -646,6 +658,7 @@ export function createMemoryConfigStore(
if (selection === null) {
baseModels.delete(id);
persist(`model:${id}`, "runtime selection", () => baseModelStore.delete(id));
+ noteRuntimeSelectionChanged(id);
return;
}
const orgRow = baseModels.get(org);
@@ -656,6 +669,7 @@ export function createMemoryConfigStore(
: { scopeId: id, ...selection, orgRevision: orgRow?.revision ?? 0 };
baseModels.set(id, row);
persist(`model:${id}`, "runtime selection", () => baseModelStore.put(id, row));
+ noteRuntimeSelectionChanged(id);
},
async setRuntimeSelectionLatest(id, selection) {
await writeQueue(`model:${id}`, async () => {
@@ -673,6 +687,7 @@ export function createMemoryConfigStore(
await baseModelStore.put(id, row);
baseModels.set(id, row);
});
+ noteRuntimeSelectionChanged(id);
},
acknowledgeRuntimeSelection(id) {
const row = baseModels.get(id);
@@ -692,6 +707,9 @@ export function createMemoryConfigStore(
baseModels.set(id, next);
});
},
+ onRuntimeSelectionChanged(listener) {
+ runtimeSelectionListeners.add(listener);
+ },
getRuntimeSelectionDurable: async (id) => {
const row = await baseModelStore.get(id);
if (!row?.harnessId) return null;
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index ec08712ff..9b5a544d1 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -289,10 +289,78 @@ export function transcriptEntries(entries: readonly SessionEntry[]): SessionEntr
return entries.filter((e) => e.type !== "soul");
}
+export const TRANSCRIPT_BYTE_BUDGET = 400_000;
+export const ENTRY_STRING_BUDGET = 2_000;
+
+export type TranscriptEntry = SessionEntry & { truncated?: true };
+
+const PROJECTED_TYPES: ReadonlySet<EntryType> = new Set<EntryType>(["tool_call", "tool_result"]);
+const WALK_DEPTH = 8;
+
+function shortenStrings(value: unknown, depth: number): { value: unknown; truncated: boolean } {
+ if (typeof value === "string") {
+ return value.length > ENTRY_STRING_BUDGET
+ ? { value: value.slice(0, ENTRY_STRING_BUDGET), truncated: true }
+ : { value, truncated: false };
+ }
+ if (value === null || typeof value !== "object") return { value, truncated: false };
+ if (depth >= WALK_DEPTH) {
+ return payloadBytes(value, depth) > ENTRY_STRING_BUDGET
+ ? { value: null, truncated: true }
+ : { value, truncated: false };
+ }
+ let truncated = false;
+ if (Array.isArray(value)) {
+ const next = value.map((item) => {
+ const walked = shortenStrings(item, depth + 1);
+ truncated ||= walked.truncated;
+ return walked.value;
+ });
+ return truncated ? { value: next, truncated } : { value, truncated };
+ }
+ const next: Record<string, unknown> = {};
+ for (const [key, item] of Object.entries(value)) {
+ const walked = shortenStrings(item, depth + 1);
+ truncated ||= walked.truncated;
+ next[key] = walked.value;
+ }
+ return truncated ? { value: next, truncated } : { value, truncated };
+}
+
+function postsToTheConversation(entry: SessionEntry): boolean {
+ const p = entry.payload as { action?: unknown } | null;
+ return entry.type === "tool_call" && p?.action === "post";
+}
+
+function projectEntry(entry: SessionEntry): TranscriptEntry {
+ if (!PROJECTED_TYPES.has(entry.type) || postsToTheConversation(entry)) return entry;
+ const walked = shortenStrings(entry.payload, 0);
+ return walked.truncated ? { ...entry, payload: walked.value, truncated: true } : entry;
+}
+
+function payloadBytes(value: unknown, depth: number): number {
+ if (typeof value === "string") return value.length + 2;
+ if (value === null || typeof value !== "object") return 8;
+ if (depth >= WALK_DEPTH) {
+ try {
+ return JSON.stringify(value)?.length ?? 8;
+ } catch {
+ return 8;
+ }
+ }
+ let bytes = 2;
+ if (Array.isArray(value)) {
+ for (const item of value) bytes += payloadBytes(item, depth + 1) + 1;
+ return bytes;
+ }
+ for (const [key, item] of Object.entries(value)) bytes += key.length + payloadBytes(item, depth + 1) + 4;
+ return bytes;
+}
+
export function windowedTranscript(
entries: SessionEntry[],
window?: { tailTurns?: number; sinceSeq?: number; beforeSeq?: number },
-): { entries: SessionEntry[]; earlier: number } {
+): { entries: TranscriptEntry[]; earlier: number } {
if (window?.beforeSeq !== undefined) {
const at = entries.findIndex((e) => e.seq >= window.beforeSeq!);
entries = entries.slice(0, at < 0 ? entries.length : at);
@@ -311,7 +379,21 @@ export function windowedTranscript(
}
}
}
- return { entries: cut > 0 ? entries.slice(cut) : entries, earlier: cut };
+ const windowed = (cut > 0 ? entries.slice(cut) : entries).map(projectEntry);
+ if (window === undefined || window.sinceSeq !== undefined) return { entries: windowed, earlier: cut };
+ let spend = 0;
+ let from = windowed.length;
+ while (from > 0) {
+ const bytes = payloadBytes(windowed[from - 1]!.payload, 0);
+ if (spend + bytes > TRANSCRIPT_BYTE_BUDGET && from < windowed.length) break;
+ spend += bytes;
+ from--;
+ }
+ if (from > 0) {
+ const boundary = windowed.findIndex((e, i) => i >= from && e.type === "user");
+ if (boundary > 0) from = boundary;
+ }
+ return { entries: from > 0 ? windowed.slice(from) : windowed, earlier: cut + from };
}
export function isOverheardEntry(e: Pick<SessionEntry, "type" | "payload">): boolean {
diff --git a/src/slack/delivery.ts b/src/slack/delivery.ts
index eca8f3e7a..8f4a2f5cc 100644
--- a/src/slack/delivery.ts
+++ b/src/slack/delivery.ts
@@ -1,6 +1,6 @@
import { errMessage } from "../util/errors.ts";
import { sleep } from "./util.ts";
-import { isExternallyShared, type ChannelMeta } from "./identity.ts";
+import { isExternallyShared, isMpim, type ChannelMeta } from "./identity.ts";
export interface SlackReplyArgs {
channel: string;
@@ -59,6 +59,10 @@ export function slackReplyArgs(
export function scopeSurfaceUrl(webUiPublicUrl: string | undefined, scopeId: string): string | undefined {
const base = (webUiPublicUrl ?? "").trim().replace(/\/+$/, "");
if (!base || !scopeId) return undefined;
+ const personal = /^personal:([^@]+)@/.exec(scopeId);
+ if (personal?.[1] && /^[a-z0-9._-]+$/i.test(personal[1])) return `${base}/projects/${personal[1].toLowerCase()}`;
+ const shared = /^(channel|group):(.+)$/.exec(scopeId);
+ if (shared?.[1] && shared[2]) return `${base}/projects/${shared[1]}/${encodeURIComponent(shared[2])}`;
return `${base}/contexts?scope=${encodeURIComponent(scopeId)}`;
}
@@ -73,11 +77,16 @@ export function channelWelcomeMessage(surfaceUrl: string | undefined): string {
return `Hi! I'm the agent for this channel. Everyone here can see and manage what I'm doing — scheduled jobs, skills, files, and apps — on this channel's shared page: ${surfaceUrl}`;
}
-export function surfaceHeaderText(modelName: string | undefined, projectUrl: string | undefined): string | undefined {
- const model = (modelName ?? "").trim();
+export function surfaceHeaderText(
+ facts: { agentLabel?: string; modelName?: string },
+ projectUrl: string | undefined,
+): string | undefined {
+ const agent = (facts.agentLabel ?? "").trim();
+ const model = (facts.modelName ?? "").trim();
const url = (projectUrl ?? "").trim();
- const parts = [...(model ? [`Model: ${model}`] : []), ...(url ? [url] : [])];
- return parts.length ? parts.join(" · ") : undefined;
+ const modelText = model ? `${agent ? `${agent} is using` : "Using"} ${model} here.` : "";
+ const link = url ? `<${url}|More settings>` : "";
+ return [modelText, link].filter(Boolean).join(" ") || undefined;
}
function unwrapSlackLinks(text: string): string {
@@ -106,7 +115,7 @@ export interface SurfaceHeaderClient {
}
export function createSurfaceHeaderEnsurer(opts: {
- effectiveModelName(scope: string): Promise<string>;
+ headerFacts(scope: string): Promise<{ agentLabel?: string; modelName: string }>;
webUiPublicUrl: string | undefined;
ids: { botUserId: string };
maxTracked?: number;
@@ -114,17 +123,22 @@ export function createSurfaceHeaderEnsurer(opts: {
const maxTracked = opts.maxTracked ?? SURFACE_HEADER_MAX_TRACKED;
const settled = new Map<string, string>();
const inFlight = new Set<string>();
- return (client, channel, scopeId, kind) => {
- if (inFlight.has(channel)) return;
+ const requeued = new Set<string>();
+ return function ensure(client, channel, scopeId, kind) {
+ if (inFlight.has(channel)) {
+ requeued.add(channel);
+ return;
+ }
inFlight.add(channel);
void (async () => {
try {
const desired = surfaceHeaderText(
- await opts.effectiveModelName(scopeId),
+ await opts.headerFacts(scopeId),
scopeSurfaceUrl(opts.webUiPublicUrl, scopeId),
);
if (!desired || settled.get(channel) === desired) return;
const info = (await client.conversations.info({ channel })).channel;
+ if (kind === "channel" && (isExternallyShared(info) || isMpim(info))) return;
const existing = kind === "dm" ? info?.topic : info?.purpose;
if (headerUpdate(existing, opts.ids.botUserId, desired) === "set") {
if (kind === "dm") await client.conversations.setTopic({ channel, topic: desired });
@@ -136,6 +150,7 @@ export function createSurfaceHeaderEnsurer(opts: {
console.error("[slack] surface header ensure failed:", errMessage(err));
} finally {
inFlight.delete(channel);
+ if (requeued.delete(channel)) ensure(client, channel, scopeId, kind);
}
})();
};
diff --git a/src/slack/index.ts b/src/slack/index.ts
index b9fa4d295..6160d6553 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -3,7 +3,7 @@ import bolt from "@slack/bolt";
import { WebClient } from "@slack/web-api";
import { createDeduper, createThreadTracker } from "./lib.ts";
import { installDevIntrospection } from "./dev-introspection.ts";
-import { setDefaultBotIdentity, createSurfaceHeaderEnsurer } from "./delivery.ts";
+import { setDefaultBotIdentity, createSurfaceHeaderEnsurer, type SurfaceHeaderClient } from "./delivery.ts";
import { NO_RETRY, type SlackPluginConfig, normalizeSlackApiUrl, slackPluginConfigFromEnv } from "./config.ts";
import { createCoreBridge } from "./core-bridge.ts";
import { createAckEmojiPicker } from "./ack-emoji.ts";
@@ -130,10 +130,14 @@ export async function startSlackPlugin(
});
const approvals = createApprovals({ core, bridge, directory, threads });
const ensureHeader = createSurfaceHeaderEnsurer({
- effectiveModelName: (scope) => core.effectiveModelName(scope as Parameters<typeof core.effectiveModelName>[0]),
+ headerFacts: (scope) => core.surfaceHeaderFacts(scope as Parameters<typeof core.surfaceHeaderFacts>[0]),
webUiPublicUrl: cfg.webUiPublicUrl,
ids,
});
+ core.onScopeModelChanged((scope) => {
+ const channel = scope.startsWith("channel:") ? scope.slice("channel:".length) : "";
+ if (channel) ensureHeader(app.client as unknown as SurfaceHeaderClient, channel, scope, "channel");
+ });
const handler = createTurnHandler({
bridge,
directory,
diff --git a/src/wiring.ts b/src/wiring.ts
index 684365420..f2a93aded 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1100,6 +1100,7 @@ export function buildApp(
tasks,
ackPicks: ackEmojiPicks,
ackModelId: () => auxiliaryModelForProvider("anthropic"),
+ ...(config.brandingDefault ? { brandingDefault: config.brandingDefault } : {}),
...(harness.models.pickAckEmoji ? { pickAckEmoji: (t, c) => harness.models.pickAckEmoji!(t, c) } : {}),
});
runs.onTerminal((run) => {
diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.ts
index cfe29aa46..0bede0546 100644
--- a/test/deploy-subdomain-signin.test.ts
+++ b/test/deploy-subdomain-signin.test.ts
@@ -73,6 +73,22 @@ function httpGet(
});
}
+function httpPost(
+ port: number,
+ path: string,
+ headers: Record<string, string>,
+): Promise<{ status: number; body: string }> {
+ return new Promise((resolve, reject) => {
+ const req = httpRequest({ host: "localhost", port, path, method: "POST", headers }, (res) => {
+ let body = "";
+ res.on("data", (c) => (body += c));
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));
+ });
+ req.on("error", reject);
+ req.end();
+ });
+}
+
test("subdomain ingress: portal sign-in admits the owner, denies strangers, bounces the signed-out", async () => {
let upstreamCookie: string | undefined = "unset";
let upstreamUrl = "";
@@ -114,6 +130,10 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, boun
files: [],
name: "mysite",
});
+ const deliveries: { destination: unknown; text: string; idempotencyKey: string }[] = [];
+ (app as unknown as Record<string, unknown>).enqueueDelivery = async (input: (typeof deliveries)[number]) => {
+ deliveries.push(input);
+ };
const server = createInsecureTestServer(app, {
deployAppsDomain: "apps.example.com",
deployGateSecret: "gate-secret",
@@ -184,6 +204,31 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, boun
});
assert.equal(strangerXhr.status, 403, "non-HTML denial stays JSON");
+ assert.match(stranger.body, /Request access/, "the denial page offers a request-access button");
+ const asked = await httpPost(port, "/__claw__/request-access", {
+ Host: host,
+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,
+ });
+ assert.equal(asked.status, 200, "a denied visitor can ask the owner for access");
+ const again = await httpPost(port, "/__claw__/request-access", {
+ Host: host,
+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,
+ });
+ assert.equal(again.status, 200, "asking twice is idempotent, not an error");
+ assert.equal(deliveries.length, 2, "both posts enqueue (the outbox dedupes by idempotency key)");
+ assert.equal(deliveries[0]!.idempotencyKey, deliveries[1]!.idempotencyKey, "same visitor+app+day dedupes");
+ assert.match(deliveries[0]!.text, /mallory@example\.com is asking for access/);
+ assert.match(deliveries[0]!.text, /mysite/);
+ assert.deepEqual(deliveries[0]!.destination, {
+ type: "principal",
+ target: "[email protected]",
+ audienceScopeId: "personal:[email protected]",
+ onBehalfOf: "[email protected]",
+ });
+
+ const signedOutAsk = await httpPost(port, "/__claw__/request-access", { Host: host });
+ assert.equal(signedOutAsk.status, 401, "a signed-out visitor cannot send access requests");
+
const forged = await httpGet(port, "/consultants", {
Host: host,
Accept: "text/html",
diff --git a/test/runtime-selection.test.ts b/test/runtime-selection.test.ts
index 1afb3e064..81d92c91a 100644
--- a/test/runtime-selection.test.ts
+++ b/test/runtime-selection.test.ts
@@ -84,3 +84,27 @@ test("runtime resolution reads approvals and selections from shared durable stat
/not approved/,
);
});
+
+test("every write that changes a scope's served model notifies listeners", async () => {
+ const config = createMemoryConfigStore("default-org");
+ const seen: string[] = [];
+ config.onRuntimeSelectionChanged((id) => seen.push(id));
+ config.setApprovedHarnesses(["pi", "codex"]);
+
+ config.setRuntimeSelection(ORG, { harnessId: "pi", modelId: "claude-opus-4-8" });
+ await config.setRuntimeSelectionLatest(PERSONAL, { harnessId: "codex", modelId: "gpt-5.5" });
+ config.setBaseModel(PERSONAL, "gpt-5.6-sol");
+ await config.setRuntimeSelectionLatest(PERSONAL, null);
+ config.acknowledgeRuntimeSelection(PERSONAL);
+ assert.deepEqual(seen, [ORG, PERSONAL, PERSONAL, PERSONAL]);
+});
+
+test("a listener that throws cannot break the write that notified it", async () => {
+ const config = createMemoryConfigStore("default-org");
+ config.onRuntimeSelectionChanged(() => {
+ throw new Error("surface unreachable");
+ });
+ config.setApprovedHarnesses(["pi"]);
+ await config.setRuntimeSelectionLatest(ORG, { harnessId: "pi", modelId: "claude-opus-4-8" });
+ assert.equal((await config.getRuntimeSelectionDurable(ORG))?.modelId, "claude-opus-4-8");
+});
diff --git a/test/slack-delivery.test.ts b/test/slack-delivery.test.ts
index 8f5f25866..5eb0405fc 100644
--- a/test/slack-delivery.test.ts
+++ b/test/slack-delivery.test.ts
@@ -247,9 +247,9 @@ function fakeJoinClient(
};
}
-test("channelSurfaceUrl builds the contexts deep link and degrades when unset", () => {
- assert.equal(channelSurfaceUrl(WEB_BASE, "C123"), `${WEB_BASE}/contexts?scope=channel%3AC123`);
- assert.equal(channelSurfaceUrl("https://x/web-ui/", "C9"), "https://x/web-ui/contexts?scope=channel%3AC9");
+test("channelSurfaceUrl builds the project deep link and degrades when unset", () => {
+ assert.equal(channelSurfaceUrl(WEB_BASE, "C123"), `${WEB_BASE}/projects/channel/C123`);
+ assert.equal(channelSurfaceUrl("https://x/web-ui/", "C9"), "https://x/web-ui/projects/channel/C9");
assert.equal(channelSurfaceUrl(undefined, "C1"), undefined);
assert.equal(channelSurfaceUrl("", "C1"), undefined);
});
@@ -275,7 +275,7 @@ test("onBotJoinedChannel: posts welcome with the deep link and sets the descript
synced++;
},
});
- const expectedUrl = `${WEB_BASE}/contexts?scope=channel%3AC123`;
+ const expectedUrl = `${WEB_BASE}/projects/channel/C123`;
assert.equal(calls.posted.length, 1);
assert.equal(calls.posted[0]!.channel, "C123");
assert.ok(calls.posted[0]!.text.includes(expectedUrl), "welcome message must contain the channel surface deep link");
@@ -391,7 +391,7 @@ test("onBotJoinedChannel: welcomes a normal internal channel and hands the descr
},
ensureHeader: (channel) => ensured.push(channel),
});
- const expectedUrl = `${WEB_BASE}/contexts?scope=channel%3AC123`;
+ const expectedUrl = `${WEB_BASE}/projects/channel/C123`;
assert.equal(calls.posted.length, 1, "welcome lands on a normal internal channel");
assert.ok(calls.posted[0]!.text.includes(expectedUrl), "welcome message contains the project deep link");
assert.deepEqual(ensured, ["C123"], "join triggers exactly one header ensure");
@@ -569,26 +569,37 @@ test("postWithVerify: threaded post verifies via conversations.replies", async (
assert.equal(h.historyCalled, false, "threaded verify reads replies, not history");
});
-test("surfaceHeaderText composes model + project link and degrades gracefully", () => {
+test("surfaceHeaderText names the agent, its model, and the project link — degrading gracefully", () => {
assert.equal(
- surfaceHeaderText("Claude Opus 4.8", "https://claw.acme.dev/contexts?scope=channel%3AC1"),
- "Model: Claude Opus 4.8 · https://claw.acme.dev/contexts?scope=channel%3AC1",
+ surfaceHeaderText(
+ { agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" },
+ "https://claw.acme.dev/projects/channel/C1",
+ ),
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",
);
- assert.equal(surfaceHeaderText("Claude Opus 4.8", undefined), "Model: Claude Opus 4.8");
- assert.equal(surfaceHeaderText(undefined, "https://claw.acme.dev"), "https://claw.acme.dev");
- assert.equal(surfaceHeaderText(" ", " "), undefined);
+ assert.equal(
+ surfaceHeaderText({ agentLabel: "QM", modelName: "Claude Opus 4.8" }, undefined),
+ "QM is using Claude Opus 4.8 here.",
+ );
+ assert.equal(
+ surfaceHeaderText({ modelName: "Claude Opus 4.8" }, undefined),
+ "Using Claude Opus 4.8 here.",
+ "an unbranded deployment keeps the bare model line",
+ );
+ assert.equal(surfaceHeaderText({}, "https://claw.acme.dev"), "<https://claw.acme.dev|More settings>");
+ assert.equal(surfaceHeaderText({ agentLabel: "QM", modelName: " " }, " "), undefined);
});
test("headerUpdate rewrites only an empty or self-authored header", () => {
const BOT = "U0BOT";
- const desired = "Model: Claude Opus 4.8 · https://claw.acme.dev";
+ const desired = "Using Claude Opus 4.8 here. <https://claw.acme.dev|More settings>";
assert.equal(headerUpdate(undefined, BOT, desired), "set");
assert.equal(headerUpdate({ value: "" }, BOT, desired), "set");
assert.equal(headerUpdate({ value: "Model: Claude Sonnet 5", creator: BOT }, BOT, desired), "set");
assert.equal(headerUpdate({ value: desired, creator: BOT }, BOT, desired), "skip");
assert.equal(headerUpdate({ value: "my own notes", creator: "U0HUMAN" }, BOT, desired), "skip");
assert.equal(
- headerUpdate({ value: "Model: Claude Opus 4.8 · <https://claw.acme.dev>", creator: BOT }, BOT, desired),
+ headerUpdate({ value: "Using Claude Opus 4.8 here. <https://claw.acme.dev>", creator: BOT }, BOT, desired),
"skip",
);
});
@@ -620,11 +631,11 @@ function headerHarness(
},
};
const raw = createSurfaceHeaderEnsurer({
- effectiveModelName: async () => model,
+ headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: model }),
webUiPublicUrl: "https://claw.acme.dev",
ids: { botUserId: "U0BOT" },
});
- const scope = kind === "dm" ? "personal:[email protected]" : "channel:C1";
+ const scope = kind === "dm" ? "personal:[email protected]" : "channel:C1";
const ensure = (c: unknown, channel: string) => raw(c as never, channel, scope, kind);
const flush = async (): Promise<void> => {
for (let i = 0; i < 12; i++) await Promise.resolve();
@@ -639,7 +650,7 @@ test("surface header ensurer writes the header once, then goes quiet", async ()
assert.equal(h.calls.set, 1);
assert.equal(
h.read()?.value,
- "Model: Claude Opus 4.8 · https://claw.acme.dev/contexts?scope=personal%3Ajosh%40acme.dev",
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/user.one|More settings>",
);
h.ensure(h.client, "D1");
await h.flush();
@@ -664,28 +675,59 @@ test("surface header ensurer collapses a burst on one channel into a single writ
},
};
const ensure = createSurfaceHeaderEnsurer({
- effectiveModelName: async () => "Claude Opus 4.8",
+ headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),
webUiPublicUrl: "https://claw.acme.dev",
ids: { botUserId: "U0BOT" },
});
- for (let i = 0; i < 5; i++) ensure(client as any, "D1", "personal:[email protected]", "dm");
+ for (let i = 0; i < 5; i++) ensure(client as any, "D1", "personal:[email protected]", "dm");
await new Promise((r) => setTimeout(r, 60));
assert.equal(infos, 1, "the in-flight guard spares the concurrent probes");
assert.equal(sets, 1);
});
+test("a model change during an in-flight ensure is re-run, not dropped", async () => {
+ let model = "Claude Opus 4.8";
+ const purposes: string[] = [];
+ const client = {
+ conversations: {
+ info: async () => {
+ await new Promise((r) => setTimeout(r, 15));
+ return { channel: { purpose: {} } };
+ },
+ setPurpose: async ({ purpose }: { channel: string; purpose: string }) => {
+ purposes.push(purpose);
+ return {};
+ },
+ },
+ };
+ const ensure = createSurfaceHeaderEnsurer({
+ headerFacts: async () => ({ agentLabel: "QM", modelName: model }),
+ webUiPublicUrl: "https://claw.acme.dev",
+ ids: { botUserId: "U0BOT" },
+ });
+ ensure(client as any, "C1", "channel:C1", "channel");
+ model = "Claude Haiku 4.5";
+ ensure(client as any, "C1", "channel:C1", "channel");
+ await new Promise((r) => setTimeout(r, 150));
+ assert.deepEqual(
+ purposes.map((p) => p.split(" <")[0]),
+ ["QM is using Claude Opus 4.8 here.", "QM is using Claude Haiku 4.5 here."],
+ "the change that landed mid-probe still reaches the description",
+ );
+});
+
test("surface header ensurer caps its per-channel memo", async () => {
const client = {
conversations: { info: async () => ({ channel: {} }), setTopic: async () => ({}) },
};
const ensure = createSurfaceHeaderEnsurer({
- effectiveModelName: async () => "Claude Opus 4.8",
+ headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),
webUiPublicUrl: "https://claw.acme.dev",
ids: { botUserId: "U0BOT" },
maxTracked: 3,
});
for (let i = 0; i < 10; i++) {
- ensure(client as any, `D${i}`, "personal:[email protected]", "dm");
+ ensure(client as any, `D${i}`, "personal:[email protected]", "dm");
await new Promise((r) => setTimeout(r, 2));
}
let reprobed = 0;
@@ -698,7 +740,7 @@ test("surface header ensurer caps its per-channel memo", async () => {
setTopic: async () => ({}),
},
};
- ensure(spy as any, "D0", "personal:[email protected]", "dm");
+ ensure(spy as any, "D0", "personal:[email protected]", "dm");
await new Promise((r) => setTimeout(r, 20));
assert.equal(reprobed, 1, "an evicted channel is re-probed, so the map cannot grow forever");
});
@@ -710,11 +752,34 @@ test("surface header ensurer writes a channel's description, not its topic", asy
assert.equal(h.calls.set, 1);
assert.equal(
h.read()?.value,
- "Model: Claude Opus 4.8 · https://claw.acme.dev/contexts?scope=channel%3AC1",
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",
"a channel shows ITS scope's default model and links to ITS project page",
);
});
+test("surface header ensurer writes no channel header where an external member could read it", async () => {
+ for (const shape of [{ is_ext_shared: true }, { is_mpim: true }]) {
+ let sets = 0;
+ const client = {
+ conversations: {
+ info: async () => ({ channel: { ...shape, purpose: {} } }),
+ setPurpose: async () => {
+ sets += 1;
+ return {};
+ },
+ },
+ };
+ const ensure = createSurfaceHeaderEnsurer({
+ headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),
+ webUiPublicUrl: "https://claw.acme.dev",
+ ids: { botUserId: "U0BOT" },
+ });
+ ensure(client as any, "C1", "channel:C1", "channel");
+ await new Promise((r) => setTimeout(r, 30));
+ assert.equal(sets, 0, `a ${JSON.stringify(shape)} conversation is not the bot's to describe`);
+ }
+});
+
test("surface header ensurer never clobbers a human-written channel description", async () => {
const h = headerHarness({ value: "Where we plan the launch", creator: "U0HUMAN" }, "Claude Opus 4.8", "channel");
h.ensure(h.client, "C1");
@@ -724,14 +789,21 @@ test("surface header ensurer never clobbers a human-written channel description"
});
test("scopeSurfaceUrl deep-links each context to its own project page", () => {
+ assert.equal(scopeSurfaceUrl("https://claw.acme.dev/", "channel:C1"), "https://claw.acme.dev/projects/channel/C1");
+ assert.equal(
+ scopeSurfaceUrl("https://claw.acme.dev", "personal:[email protected]"),
+ "https://claw.acme.dev/projects/user.one",
+ );
assert.equal(
- scopeSurfaceUrl("https://claw.acme.dev/", "channel:C1"),
- "https://claw.acme.dev/contexts?scope=channel%3AC1",
+ scopeSurfaceUrl("https://claw.acme.dev", "personal:[email protected]"),
+ "https://claw.acme.dev/projects/user.two",
);
assert.equal(
- scopeSurfaceUrl("https://claw.acme.dev", "personal:[email protected]"),
- "https://claw.acme.dev/contexts?scope=personal%3Ajosh%40acme.dev",
+ scopeSurfaceUrl("https://claw.acme.dev", "personal:[email protected]"),
+ "https://claw.acme.dev/contexts?scope=personal%3Aunsafe%2Bslug%40acme.dev",
);
+ assert.equal(scopeSurfaceUrl("https://claw.acme.dev", "group:G1"), "https://claw.acme.dev/projects/group/G1");
+ assert.equal(scopeSurfaceUrl("https://claw.acme.dev", "team:T1"), "https://claw.acme.dev/contexts?scope=team%3AT1");
assert.equal(scopeSurfaceUrl(undefined, "channel:C1"), undefined);
assert.equal(scopeSurfaceUrl("https://claw.acme.dev", ""), undefined);
});
@@ -746,12 +818,12 @@ test("surface header ensurer never clobbers a human-written topic", async () =>
test("surface header ensurer swallows a Slack failure instead of surfacing it to the turn", async () => {
const ensure = createSurfaceHeaderEnsurer({
- effectiveModelName: async () => {
+ headerFacts: async () => {
throw new Error("core unreachable");
},
webUiPublicUrl: "https://claw.acme.dev",
ids: { botUserId: "U0BOT" },
});
- assert.doesNotThrow(() => ensure({} as any, "D1", "personal:[email protected]", "dm"));
+ assert.doesNotThrow(() => ensure({} as any, "D1", "personal:[email protected]", "dm"));
for (let i = 0; i < 12; i++) await Promise.resolve();
});
diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.ts
index d13b627a5..a5bc2a65a 100644
--- a/test/slack-index.integration.test.ts
+++ b/test/slack-index.integration.test.ts
@@ -198,12 +198,16 @@ class FakeCore implements SlackCoreClient {
readonly polled: string[] = [];
private runGate: Promise<void> | undefined;
private releaseRun: (() => void) | undefined;
+ readonly modelChangeListeners: Array<(scope: any) => void> = [];
async externalSlackParticipants(): Promise<boolean> {
return this.externalParticipants;
}
- async effectiveModelName(): Promise<string> {
- return "Claude Opus 4.8";
+ async surfaceHeaderFacts(): Promise<{ agentLabel?: string; modelName: string }> {
+ return { agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" };
+ }
+ onScopeModelChanged(listener: (scope: any) => void): void {
+ this.modelChangeListeners.push(listener);
}
async stageBlob(bytes: Uint8Array): Promise<{ blobId: string; sizeBytes: number }> {
return { blobId: "blob-1", sizeBytes: bytes.byteLength };
@@ -405,7 +409,8 @@ test("a human's DM sets the conversation header to the serving model + web surfa
assert.deepEqual(f.client.topics, [
{
channel: "D1",
- topic: "Model: Claude Opus 4.8 · https://claw.example.dev/contexts?scope=personal%3AU1",
+ topic:
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/contexts?scope=personal%3AU1|More settings>",
},
]);
await f.app.emitMessage({ channel: "D1", channel_type: "im", user: "U1", text: "again", ts: "100.2" });
@@ -426,7 +431,8 @@ test("a channel's description names the channel's own default model and project
assert.deepEqual(f.client.purposes, [
{
channel: "C1",
- purpose: "Model: Claude Opus 4.8 · https://claw.example.dev/contexts?scope=channel%3AC1",
+ purpose:
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>",
},
]);
assert.deepEqual(f.client.topics, [], "a channel's topic stays the members' own scratch space");
@@ -435,6 +441,27 @@ test("a channel's description names the channel's own default model and project
}
});
+test("a scope's model change rewrites its channel description without waiting for a message", async () => {
+ const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });
+ try {
+ assert.equal(f.core.modelChangeListeners.length, 1, "the plugin subscribes to core's model changes");
+ for (const listener of f.core.modelChangeListeners) listener("channel:C1");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.deepEqual(f.client.purposes, [
+ {
+ channel: "C1",
+ purpose:
+ "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>",
+ },
+ ]);
+ for (const listener of f.core.modelChangeListeners) listener("personal:[email protected]");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.deepEqual(f.client.topics, [], "a DM's topic settles on the person's next message, not on a push");
+ } finally {
+ await f.stop();
+ }
+});
+
test("an external guest's DM never reveals the model or the web surface", async () => {
const f = await fixture({ externalParticipants: true, webUiPublicUrl: "https://claw.example.dev" });
try {
diff --git a/test/transcript-window.test.ts b/test/transcript-window.test.ts
index 190382543..c68034827 100644
--- a/test/transcript-window.test.ts
+++ b/test/transcript-window.test.ts
@@ -8,7 +8,7 @@ import { join } from "node:path";
import type { AddressInfo } from "node:net";
import { createInsecureTestServer } from "../src/api/server.ts";
import { buildApp, type BuiltApp } from "../src/wiring.ts";
-import { windowedTranscript } from "../src/sessions/session-store.ts";
+import { ENTRY_STRING_BUDGET, TRANSCRIPT_BYTE_BUDGET, windowedTranscript } from "../src/sessions/session-store.ts";
import type { SessionEntry } from "../src/types.ts";
import { scopeId } from "../src/types.ts";
import { testConfig } from "./support/test-config.ts";
@@ -123,6 +123,51 @@ test("windowedTranscript: beforeSeq alone truncates; wider-than-history pages re
);
});
+function fat(seq: number, type: SessionEntry["type"], chars: number): SessionEntry {
+ return { ...entry(seq, type), payload: { tool: "execute", output: "x".repeat(chars) } };
+}
+
+test("windowedTranscript: a fat tool payload is previewed, and the entry says so", () => {
+ const log = [entry(0, "user"), fat(1, "tool_call", 50_000), fat(2, "tool_result", 50_000), entry(3, "assistant")];
+ const w = windowedTranscript(log, { tailTurns: 1 });
+ assert.equal(w.entries.length, 4);
+ for (const e of w.entries.filter((x) => x.type === "tool_call" || x.type === "tool_result")) {
+ assert.equal((e.payload as { output: string }).output.length, ENTRY_STRING_BUDGET);
+ assert.equal(e.truncated, true);
+ }
+ assert.equal(w.entries[0]!.truncated, undefined, "a small entry is shipped whole and unmarked");
+});
+
+test("windowedTranscript: conversation text is never truncated — only tool payloads are", () => {
+ const said = "y".repeat(50_000);
+ const log = [
+ { ...entry(0, "user"), payload: { text: said } },
+ { ...entry(1, "assistant"), payload: { text: said } },
+ { ...entry(2, "thinking"), payload: { text: said } },
+ ];
+ for (const e of windowedTranscript(log).entries) {
+ assert.equal((e.payload as { text: string }).text.length, said.length);
+ assert.equal(e.truncated, undefined);
+ }
+});
+
+test("windowedTranscript: the byte budget drops the oldest entries and counts them as earlier", () => {
+ const log = [entry(0, "user")];
+ for (let seq = 1; seq <= 400; seq++) log.push(fat(seq, "tool_result", ENTRY_STRING_BUDGET));
+ const w = windowedTranscript(log, { tailTurns: 99 });
+ const shipped = w.entries.reduce((a, e) => a + JSON.stringify(e.payload).length, 0);
+ assert.ok(shipped <= TRANSCRIPT_BYTE_BUDGET * 1.1, `shipped ${shipped} must respect the budget`);
+ assert.ok(w.entries.length < log.length, "the budget must bite");
+ assert.equal(w.entries.length + w.earlier, log.length, "everything dropped is counted as earlier");
+ assert.equal(w.entries[w.entries.length - 1]!.seq, 400, "the newest end is what survives");
+});
+
+test("windowedTranscript: one entry over budget still ships — a window is never empty", () => {
+ const w = windowedTranscript([fat(0, "user", TRANSCRIPT_BYTE_BUDGET * 2)], { tailTurns: 1 });
+ assert.equal(w.entries.length, 1);
+ assert.equal(w.earlier, 0);
+});
+
function start(): { base: string; built: BuiltApp; close: () => Promise<void> } {
const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "transcript-window-")) }));
const server = createInsecureTestServer(built.app, {
@@ -189,6 +234,19 @@ test("GET /v1/sessions/:id honors tailTurns/sinceSeq and reports earlierEntries"
);
assert.equal(beforeBody.earlierEntries, userSeqs[1], "what remains before this page");
+ const seq = fullBody.entries[0]!.seq;
+ const one = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}/entries/${seq}?viewer=U1`);
+ assert.equal(one.status, 200);
+ const oneBody = (await one.json()) as { entry: SessionEntry };
+ assert.deepEqual(oneBody.entry, fullBody.entries[0], "the whole entry, exactly as stored");
+
+ const missing = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}/entries/99999?viewer=U1`);
+ assert.equal(missing.status, 404, "a seq that isn't in this session");
+ const stranger = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}/entries/${seq}?viewer=U2`);
+ assert.equal(stranger.status, 404, "a viewer who cannot see the session cannot see its entries");
+ const noViewer = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}/entries/${seq}`);
+ assert.equal(noViewer.status, 400, "viewer is required");
+
const bad = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}?viewer=U1&tailTurns=0`);
assert.equal(bad.status, 400, "tailTurns must be a positive integer");
const badSince = await fetch(`${srv.base}/v1/sessions/${encodeURIComponent(sessionId)}?viewer=U1&sinceSeq=-1`);
@@ -199,3 +257,58 @@ test("GET /v1/sessions/:id honors tailTurns/sinceSeq and reports earlierEntries"
await srv.close();
}
});
+
+test("windowedTranscript: an unwindowed read is still whole — fork cutoffs count on it", () => {
+ const log = [entry(0, "user")];
+ for (let seq = 1; seq <= 400; seq++) log.push(fat(seq, "tool_result", ENTRY_STRING_BUDGET * 3));
+ const all = windowedTranscript(log);
+ assert.equal(all.entries.length, log.length, "no window asked for, nothing dropped");
+ assert.equal(all.earlier, 0);
+ assert.equal(all.entries[1]!.truncated, true, "though fat payloads are still previewed");
+});
+
+test("windowedTranscript: the text a post tool call puts in the conversation is never previewed", () => {
+ const said = "z".repeat(50_000);
+ const log = [
+ entry(0, "user"),
+ { ...entry(1, "tool_call"), payload: { tool: "reach", action: "post", text: said, callId: "c1" } },
+ { ...entry(2, "tool_result"), payload: { tool: "reach", callId: "c1", ok: true } },
+ ];
+ const posted = windowedTranscript(log, { tailTurns: 1 }).entries[1]!;
+ assert.equal((posted.payload as { text: string }).text.length, said.length, "the agent's reply is conversation text");
+ assert.equal(posted.truncated, undefined);
+});
+
+test("windowedTranscript: a deeply nested payload cannot smuggle bytes past the budget", () => {
+ const deep = (depth: number, leaf: unknown): unknown => (depth === 0 ? leaf : { nest: deep(depth - 1, leaf) });
+ const log = [entry(0, "user")];
+ for (let seq = 1; seq <= 6; seq++) {
+ log.push({ ...entry(seq, "tool_result"), payload: { tool: "execute", out: deep(12, "q".repeat(300_000)) } });
+ }
+ const w = windowedTranscript(log, { tailTurns: 1 });
+ const shipped = JSON.stringify(w.entries).length;
+ assert.ok(shipped < TRANSCRIPT_BYTE_BUDGET * 2, `a nested subtree must be charged its real size, shipped ${shipped}`);
+});
+
+test("windowedTranscript: the byte cut lands on a turn boundary, so a call keeps its result", () => {
+ const log: SessionEntry[] = [];
+ let seq = 0;
+ const said = (n: number): SessionEntry => ({ ...entry(n, "assistant"), payload: { text: "s".repeat(20_000) } });
+ for (let turn = 0; turn < 40; turn++) {
+ log.push(entry(seq++, "user"));
+ log.push(fat(seq++, "tool_call", ENTRY_STRING_BUDGET * 2));
+ log.push(fat(seq++, "tool_result", ENTRY_STRING_BUDGET * 2));
+ log.push(said(seq++));
+ }
+ const w = windowedTranscript(log, { tailTurns: 99 });
+ assert.ok(w.earlier > 0, "the budget must bite for this to mean anything");
+ assert.equal(w.entries[0]!.type, "user", "a page opens on a turn, never mid-turn");
+});
+
+test("windowedTranscript: a sinceSeq re-read is never trimmed — it refreshes what the client already holds", () => {
+ const log = [entry(0, "user")];
+ for (let seq = 1; seq <= 400; seq++) log.push(fat(seq, "tool_result", ENTRY_STRING_BUDGET * 3));
+ const w = windowedTranscript(log, { sinceSeq: 1 });
+ assert.equal(w.entries.length, log.length - 1, "a refresh that shrinks the window makes read messages vanish");
+ assert.equal(w.earlier, 1);
+});
diff --git a/test/wake-steering.test.ts b/test/wake-steering.test.ts
index 537883577..9c3a70c70 100644
--- a/test/wake-steering.test.ts
+++ b/test/wake-steering.test.ts
@@ -564,7 +564,7 @@ test("orphan replay: a steer unconsumed at run completion replays as a fresh tur
assert.equal((await built.signals.takePending(liveRunId)).length, 0, "the orphaned signal was consumed by the drain");
});
-test("orphan replay: a stale abort and a request-less signal are drained but not replayed", async () => {
+test("orphan replay: a stale abort is drained; a request-less steer replays on the run's own request", async () => {
const built = freshApp();
const channel = "C10";
const root = "1000.1";
@@ -576,8 +576,28 @@ test("orphan replay: a stale abort and a request-less signal are drained but not
await built.app.replayOrphanedRunSignals(liveRunId);
assert.equal((await built.signals.takePending(liveRunId)).length, 0, "drained");
- const runs = await built.runs.list();
- assert.equal(runs.filter((r) => r.sessionId === threadRef).length, 1, "nothing replayable — no fresh turn");
+ const runs = (await built.runs.list()).filter((r) => r.sessionId === threadRef);
+ assert.equal(runs.length, 2, "the abort is dropped; the steer text becomes a fresh turn, never lost");
+ const fresh = runs.find((r) => r.id !== liveRunId);
+ assert.equal(fresh?.request.text, "manual web steer");
+});
+
+test("signalRun: a web steer that races the run's end is replayed and reports the fresh run", async () => {
+ const built = freshApp();
+ const channel = "C14";
+ const root = "1400.1";
+ const first = await built.app.turn(mention("@bot go", channel, root));
+ const liveRunId = first.runId!;
+ completeOnSend(built);
+
+ const raced = await built.app.signalRun(liveRunId, { kind: "steer", text: "did this make it?" });
+ assert.equal(raced.accepted, false);
+ assert.equal(raced.reason, "terminal");
+ assert.equal(raced.replayed, true, "the caller is told the text now rides a fresh run");
+ const fresh = await until(async () =>
+ (await built.runs.list()).find((r) => r.sessionId === `ch:${channel}:${root}` && r.id !== liveRunId),
+ );
+ assert.equal(fresh.request.text, "did this make it?");
});
test("signalRun: a steer already terminal at send is refused up front", async () => {