diff --git a/AGENTS.md b/AGENTS.md index a29310c..4046f6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,6 +102,7 @@ open-ended work. The default provider and model come from Settings → Providers | Charts in replies | `chat/visuals.mjs`, `renderPage` in `browser/manager.mjs`, `showVisual` in `bridge.mjs`, `web/src/chat/VisualFrame.tsx`, `web/src/chat/visuals.ts`, `mobile/src/features/chat/VisualCard.tsx`, `mobile/src/ui/BridgeWebView.tsx`, `mobile/src/lib/bridgePage.ts` | T3 Code's `html_preview`/`html_render` on each chat run's `/agent-mcp` (`browser__html_*` through the gateway): the agent previews a self-contained HTML page in the box's Chromium (a PNG, its height, its console), then renders it, which stores it as a chat upload marked `visual` and adds a `visual` part where it was called. The uploads route serves only those uploads as pages, always under `VISUAL_CSP` (sandboxed, opaque origin, scripts from three chart CDNs, no fetch or remote images; a navigation is refused in the preview and closes the dashboard's frame). The dashboard draws it inline in a frame fitted to the height the page reports; the app draws it inline too, in `BridgeWebView`, the app's one WebView for bridge pages, which other screens reuse (only a page on the bridge; the Access token on the first request only, never the bridge secret; a non-persistent data store; no script unless `onHeight`, and the only message read is the height; the source URL loads once, and a reload, even mid-parse, or any page after it closes the view; `lib/bridgePage.ts`), with a full-screen view. A chart loads only its signed upload URL (`visualPagePath`). The in-app browser it used before could not send the Access token, so behind Access it showed the sign-in page (#260). Offered only beside the agent browser (a chart page can carry data out by navigating itself, which is no new way out only for a run that has the browser); never on voice, phone, jobs or totems. `docs/chat.md` → Charts in replies. | | Approvals | `chat/approvals.mjs`, `askApproval` and `/api/chat/approvals` in `bridge.mjs`, `web/src/chat/ApprovalRow.tsx`, `web/src/chat/approvals.ts` | T3 Code's tool approvals for Claude: chat runs pass `--permission-prompt-tool stdio`, so a permission ask arrives as a `can_use_tool` control request; it shows in the reply with Decline / Approve / More (Always allow in this chat, Cancel turn), holds the run's clock, and the decision goes back on stdin. "Always allow" rules are saved on the thread (`allowedTools`) and passed as `--allowedTools` on later runs. A composer message while one waits declines it with those words. `docs/chat.md` → Approvals. | | Approval cards | `chat/inbox-outcome.mjs`, `web/src/chat/InboxCardRow.tsx`, `web/src/chat/inboxCards.ts`, `POST /api/inbox/reply` | An inbox proposal a chat run stages remembers that chat: the run's `/agent-mcp` token reaches the gateway as `TOTEM_RUN_TOKEN` (Codex via `env_vars`), the gateway sends it as `x-totem-run` to `/mcp`, and the stagers write `thread:`/`run:` on the line (reserved meta). An `inbox` part joins the reply as the card, which accepts through the unchanged `/api/inbox/resolve` with the digest and the approval code (no new approval route); `note` on the resolve body goes to the agent. Every resolve updates the card (via the live reply until its final save, which revokes the grant only afterwards); the owner's dashboard decision (never an approval session's) is also sent to the chat as his message marked `inbox`, through `startChatTurn` or, while a reply runs, the queue or a steer per Follow-up behaviour; **a denial without a note starts no run** (it is only added to the thread). Reply sends words and leaves the proposal open. Lines without `thread:` are untouched. `docs/chat.md` → Approval cards. | +| Context window and compaction | `chat/context.mjs`, `chat/compaction.mjs`, `web/src/chat/context.ts` (byte copy in `mobile/src/lib/chat/`), `web/src/chat/ContextMeter.tsx`, `web/src/chat/CompactionMark.tsx` | T3 Code's context meter and compaction rules. A bar in the composer (amber 80%, red 90%, a tick at Claude's compaction point) from the last request's usage: Claude's `assistant` events live, Codex's rollout `token_count` (tailed, since `exec --json` lacks it), OpenCode's last step; never the reply's summed `stats`. The CLIs compact themselves; Totem shows a divider where they did, runs `/compact` on a Claude session as a hidden turn (other accounts get T3's "does not support /compact"), and Settings → Chat › Compact idle threads (`compactIdle`: When you return = a Compact chip and `compactFirst`, which queues the message behind a `/compact`; Before the cache expires = an in-memory timer two minutes before Claude's prompt cache expires; Never) plus Auto-compact after (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`). A compaction turn is never replayed to another account and keeps the session's `through`. `docs/chat.md` → Context window and compaction. | | Running chats | `web/src/chat/RunningChats.tsx`, `web/src/chat/onScreen.ts` | Bottom-right panel of chats answering, finished-but-unread (`needsReply`) or holding a pending approval card ("Waiting on your approval") out of sight, grouped by project and folder, with open, stop, snooze, settle and mark as read; finished replies also toast. "Out of sight" means not open and no row at least half on screen; a new list of chats should give its rows `useRowOnScreen`. `docs/chat.md` → Running chats panel. | | Other chats, for agents | `chat/thread-tools.mjs`, `totem_threads_*` in `bridge.mjs` | `totem_threads_list`/`totem_threads_read` (`threads__*` in the gateway) let an agent list and read the owner's other chats (running, waiting, settled, by project or keyword). `totem_threads_create`/`totem_threads_projects` make a chat in a project or folder (creating the folder if needed), opening with the agent's message and optionally starting a run, deduplicated by `key` (`sourceKey` on the thread); this is how a totem opens a chat per new ticket. Every chat turn with the gateway on is told its own chat id and to use them only when the owner points at another chat or the turn truly needs one (`threadsRule`); keep that restraint in any change. `docs/chat.md` → Other chats. | | Agent browser | `browser/`, `web/src/chat/BrowserPanel.tsx` | A headless Chrome or Chromium (`browser/pick.mjs`: `BROWSER_EXECUTABLE`, installed Chrome, Playwright's full Chromium, a system Chromium, the headless shell last; new headless mode, the user agent without "HeadlessChrome", a 1920×1080 screen; `BROWSER_HEADED=true` for a window on a host with a display) driven by `playwright-core` behind T3 Code's `preview_*` tool names, served to each chat run over a per-run loopback MCP endpoint (`/agent-mcp`). An open panel watches the chat's current tab live over `/api/chat/browser/ws` (`browser/socket.mjs`: CDP screencast while a viewer is there, never waiting on a slow viewer, which keeps only its newest frame; stopped when the last leaves; held input is per tab and per socket (owners), released on a tab switch or when its socket closes, each release bounded to a second; watching never opens or keeps alive a context), and the owner drives it with real input (mouse, drag, wheel, keys with modifiers, IME, paste; `browser/input.mjs`, `web/src/chat/browserInput.ts`), on the socket or `POST /api/chat/browser/input`. Driving is an approval route (low: a session or the approval code, never the bearer alone; the socket takes the code as a subprotocol); the iPhone app shows stills. That is how he signs in for the agent: the agent calls `preview_handoff`, the panel shows Done / Skip, and the call waits on him like `ask_questions` (`browser/handoff.mjs`). **Offered to every dashboard or app chat run** (not voice turns); the prompt has the agent use it only when a request needs it and ask first when unsure (`chat/reach.mjs`). Never give it, or computer use, to the phone path (`limitReach` in `runAgent` enforces it) or to jobs; a totem gets the browser only through its own `browser` switch. | @@ -131,7 +132,9 @@ open-ended work. The default provider and model come from Settings → Providers One deliberate exception: task folders (migration 013) changed every install at once, at the owner's request: venture-tagged tasks move into the same-named chat project once, and the task sheet's rows file themselves into the project its name starts with - unless `TASK_SHEET_FOLDER` says otherwise (`none` keeps them Personal). + unless `TASK_SHEET_FOLDER` says otherwise (`none` keeps them Personal). Another: Compact idle + threads defaults to When you return on every install, as T3 Code does, at the owner's request + (a Compact chip by Send, which Keep turns off for that send). - **Env wins over dashboard settings**, except `AGENT_BACKEND`/`AGENT_MODEL` and the `*_ENABLED`/`*_TIME` job seeds, which only apply before the stored config exists. - **Sibling apps are optional.** The Bushido goal toggle appears only with `BUSHIDO_URL`. diff --git a/bridge.mjs b/bridge.mjs index 0b30007..8b55edc 100644 --- a/bridge.mjs +++ b/bridge.mjs @@ -99,6 +99,8 @@ import { ASK_TOOL, ASK_TOOL_DESCRIPTOR, QUESTION_RULES, DISMISSED_FOR_AGENT, QUE import { DONE_TOOL, DONE_TOOL_DESCRIPTOR, DONE_RULES, DONE_RESULT } from './chat/done.mjs' import { PREVIEW_TOOL, RENDER_TOOL, VISUAL_RULES, visualToolDescriptors, previewVisual, storeVisual, renderedResult, visualToolError } from './chat/visuals.mjs' import { usageTally, addUsage, replyStats } from './chat/stats.mjs' +import { createIdleCompactor } from './chat/compaction.mjs' +import { COMPACT_UNSUPPORTED, DEFAULT_IDLE_COMPACTION, IDLE_COMPACTION_MODES, claudeAutoCompactThreshold, claudeAutoCompactWindow, claudeCompactionEvent, claudeContextUsage, claudeContextWindow, codexCompacted, codexContextUsage, isCompactCommand, normalizeAutoCompactWindow, opencodeContextUsage, reportedClaudeWindows } from './chat/context.mjs' import { memoryFileStats, outsideDir, MEMORY_HEAD_CHARS } from './chat/memory-ref.mjs' import { planHistory, renderTranscript, attachmentBlock, projectBlock, applyEvent, finalizeMessage, fallbackTitle, finalAnswer, failureText } from './chat/turn.mjs' import { listThreads as listOtherThreads, readThread as readOtherThread, threadsRule, findChatPlace, listChatPlaces, projectPath as chatProjectPath } from './chat/thread-tools.mjs' @@ -3139,7 +3141,21 @@ async function readSteerImages(files) { // into a `can_use_tool` control request on stdout. `approve(request, signal)` // resolves the permission result, which goes back on stdin; `allowRules` are the // chat's saved "Always allow" rules. -async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, onText, onSession, onImage, onAgent, signal, model, effort, readOnly, access = null, instance, resume, images = [], browser = null, allowWrite = [], readOnlyPaths = [], allowRules: savedRules = [], approve = null, steering = null, timeoutMs = TIMEOUT } = {}) { +// The context window Claude Code itself reported per model (`result.modelUsage`), +// for models outside the catalog in chat/context.mjs. Learned as runs finish. +const claudeReportedWindows = new Map() + +// Where a Claude account compacts, for the meter's tick (chat/context.mjs): +// Totem's setting, the environment, then the account's own settings.json. +async function claudeCompactWindowFor(account, model) { + const env = { ...process.env, ...instanceEnvironment(account) } + const dir = env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude') + let settings = null + try { settings = JSON.parse(await readFile(join(dir, 'settings.json'), 'utf8')) } catch {} + return claudeAutoCompactWindow({ setting: chatSettings.autoCompactWindow, env, settings, model }) +} + +async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, onText, onSession, onImage, onAgent, onContext, onCompaction, signal, model, effort, readOnly, access = null, instance, resume, images = [], browser = null, allowWrite = [], readOnlyPaths = [], allowRules: savedRules = [], approve = null, steering = null, timeoutMs = TIMEOUT } = {}) { const account = instance || instanceFor('claude') const args = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages'] const m = currentClaudeModel(bareModelId(model) || CLAUDE_MODEL) @@ -3194,6 +3210,19 @@ async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, } let result = '' let sessionId = '' + // How full the context is (chat/context.mjs): each top-level request's usage, + // against the model's window, with Claude's compaction point when one is set. + const compactWindow = onContext ? await claudeCompactWindowFor(account, m) : '' + let requestedAt = 0 + let lastContext = null + let compaction = null // the compaction in progress: { id, startedAt } + const sendContext = (ctx) => { + if (!ctx) return + lastContext = ctx + const { model: _model, ...shown } = ctx + emitSafe(onContext, shown, 'context') + } + const windowFor = (id) => claudeContextWindow(id || m, claudeReportedWindows.get(id || m)) const seenTools = new Set() const toolNames = new Map() // tool_use id → name, to tell a browser snapshot from any other image // Sub-agents launched in the background: their card stays open until Claude @@ -3226,8 +3255,10 @@ async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, .catch((e) => answerControl(requestId, { subtype: 'error', error: String(e?.message || e) })) .finally(() => asking.delete(requestId)) } + // Settings → Chat › Auto-compact after, as T3 passes it (CLAUDE_CODE_AUTO_COMPACT_WINDOW). + const ownWindow = normalizeAutoCompactWindow(chatSettings.autoCompactWindow) return spawnJsonStream(account.cli, args, { - input, label, signal, timeoutMs, holds: browser?.holds, env: { ...instanceEnvironment(account), ...browserCli.env }, + input, label, signal, timeoutMs, holds: browser?.holds, env: { ...instanceEnvironment(account), ...browserCli.env, ...(ownWindow ? { CLAUDE_CODE_AUTO_COMPACT_WINDOW: ownWindow } : {}) }, keepStdin: !!steering, onSpawn: (c) => { child = c @@ -3275,6 +3306,37 @@ async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, } return } + // Compaction, Claude Code's own or a `/compact` (chat/context.mjs). + const comp = claudeCompactionEvent(event) + if (comp) { + if (comp.status === 'running') { + // Claude repeats the status while it works: one divider per compaction (T3). + if (compaction) return + compaction = { id: `cmp-${randomUUID().slice(0, 8)}`, startedAt: Date.now() } + emitSafe(onCompaction, { id: compaction.id, status: 'running', startedAt: compaction.startedAt }, 'compaction') + return + } + const id = compaction?.id || `cmp-${randomUUID().slice(0, 8)}` + // Stopped by us, not failed by Claude (T3 #33291). + const status = comp.status === 'failed' && signal?.aborted ? 'stopped' : comp.status + emitSafe(onCompaction, { id, ...comp, status, endedAt: Date.now(), ...(compaction ? {} : { startedAt: Date.now() }) }, 'compaction') + compaction = null + // The meter drops to what is left at once; the next request refines it. + if (comp.status === 'done' && Number.isFinite(comp.after)) { + const max = windowFor(lastContext?.model) + sendContext({ used: comp.after, ...(max ? { max } : {}), ...(lastContext?.autoCompactAt ? { autoCompactAt: lastContext.autoCompactAt } : {}), at: Date.now() }) + } + return + } + if (event.type === 'system' && event.subtype === 'status' && 'compact_result' in event) return + if (event.type === 'result') { + // The window Claude Code compacts against, for a model outside the catalog. + for (const [id, size] of Object.entries(reportedClaudeWindows(event))) claudeReportedWindows.set(id, size) + if (lastContext && !lastContext.max) { + const max = windowFor(lastContext.model) + if (max) sendContext({ ...lastContext, max, ...(compactWindow && claudeAutoCompactThreshold(compactWindow, max) ? { autoCompactAt: claudeAutoCompactThreshold(compactWindow, max) } : {}) }) + } + } if (event.type === 'result' && typeof event.result === 'string') { if (!steering) { result = event.result; return } // A turn a steer cut short: the run goes on with the steer. @@ -3296,9 +3358,16 @@ async function spawnClaudeStream(text, { label = 'request', onActivity, onTool, } if (event.type === 'stream_event') { const ev = event.event + // The prompt cache's lifetime runs from the request, not the reply's end. + if (ev?.type === 'message_start') requestedAt = Date.now() if (onText && ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && ev.delta.text) onText(ev.delta.text) return } + if (event.type === 'assistant' && onContext && event.message?.usage && event.message.model !== '') { + const id = event.message.model || m + const ctx = claudeContextUsage(event.message.usage, { maxTokens: windowFor(id), autoCompactWindow: compactWindow, requestedAt }) + if (ctx) sendContext({ ...ctx, model: id }) + } if (event.type === 'assistant' && Array.isArray(event.message?.content)) { // Claude Code's display data for connector tools: name, server name, logo. const meta = Array.isArray(event.tool_use_meta) ? event.tool_use_meta : [] @@ -3393,7 +3462,7 @@ function codexActivity(item, phase) { // `resume` continues the thread with `codex exec resume `. That subcommand // has no -C or --sandbox flag, so the sandbox goes in as a config override and // the working directory comes from the spawn's cwd, which is AGENT_CWD anyway. -async function spawnCodexStream(text, { label = 'request', onActivity, onTool, onText, onSession, onImage, onAgent, signal, model, effort, sandbox, access = null, instance, resume, images = [], features = [], extraArgs = [], browser = null, timeoutMs = TIMEOUT } = {}) { +async function spawnCodexStream(text, { label = 'request', onActivity, onTool, onText, onSession, onImage, onAgent, onContext, onCompaction, signal, model, effort, sandbox, access = null, instance, resume, images = [], features = [], extraArgs = [], browser = null, timeoutMs = TIMEOUT } = {}) { const account = instance || instanceFor('codex') // Entries added to the shared home since the last run (a new skill, a new MCP // server in config.toml) only reach this account once they're linked in. @@ -3457,6 +3526,34 @@ async function spawnCodexStream(text, { label = 'request', onActivity, onTool, o } } const startedAt = Date.now() + // How full the context is, and Codex's own compactions (chat/context.mjs): only + // the session's rollout file says, so it is tailed while the turn runs. Lines + // from before this run are earlier turns'. + let contextLog = null + let lastUsed = null + let openCompaction = null + let lastCompactionAt = 0 + const onRolloutRecord = (r) => { + const at = Date.parse(r?.timestamp || '') + // Same machine, same clock: anything stamped before this run began is an earlier turn's. + if (Number.isFinite(at) && at < startedAt) return + const ctx = codexContextUsage(r) + if (ctx) { + lastUsed = ctx.used + emitSafe(onContext, ctx, 'context') + // The first reading after a compaction is what it left. + if (openCompaction) { emitSafe(onCompaction, { id: openCompaction, after: ctx.used }, 'compaction'); openCompaction = null } + return + } + if (codexCompacted(r)) { + const when = Number.isFinite(at) ? at : Date.now() + // The records one compaction writes land within a second of each other. + if (when - lastCompactionAt < 5000) return + lastCompactionAt = when + openCompaction = `cmp-${randomUUID().slice(0, 8)}` + emitSafe(onCompaction, { id: openCompaction, status: 'done', trigger: 'auto', startedAt: when, endedAt: when, ...(lastUsed != null ? { before: lastUsed } : {}) }, 'compaction') + } + } return spawnJsonStream(account.cli, args, { input: text, label, signal, timeoutMs, holds: browser?.holds, env: codexEnv, onEvent: (event) => { @@ -3464,6 +3561,9 @@ async function spawnCodexStream(text, { label = 'request', onActivity, onTool, o if (t === 'thread.started' && event.thread_id) { sessionId = event.thread_id emitSafe(onSession, sessionId, 'session') + if ((onContext || onCompaction) && !contextLog) { + contextLog = watchSessionLog({ provider: 'codex', threadId: sessionId, startedAt, env: codexEnv, log, onRecord: onRolloutRecord, fromEnd: !!resume }) + } return } // A rejected model, a quota block or a server error arrives as an event, not @@ -3523,6 +3623,7 @@ async function spawnCodexStream(text, { label = 'request', onActivity, onTool, o }, }).then(async (res) => { await Promise.all([...childLogs.values()].map((c) => c.watcher.stop().catch(() => {}))) + await contextLog?.stop().catch(() => {}) if (onImage && sessionId) await emitCodexImages(codexEnv.CODEX_HOME || join(homedir(), '.codex'), sessionId, startedAt, onImage) return { ...res, result: lastMessage || [...messages.values()].filter(Boolean).pop() || '', turnError, turnFailed, sessionId } }) @@ -3565,7 +3666,7 @@ function chatToolFromOpenCode(part, phase) { // OpenCode: `run --format json` emits step_start / text / tool / step_finish // events. Each `text` part streams as it grows (keyed by part id), so we diff // against what we've already sent. The reply is the concatenation of text parts. -function spawnOpenCodeStream(text, { label = 'request', onActivity, onTool, onText, onSession, signal, model, instance, resume, images = [], browser = null, timeoutMs = TIMEOUT } = {}) { +function spawnOpenCodeStream(text, { label = 'request', onActivity, onTool, onText, onSession, onContext, signal, model, instance, resume, images = [], browser = null, timeoutMs = TIMEOUT } = {}) { const account = instance || instanceFor('opencode') const args = ['run', '--format', 'json'] const m = bareModelId(model) || OPENCODE_MODEL @@ -3582,6 +3683,9 @@ function spawnOpenCodeStream(text, { label = 'request', onActivity, onTool, onTe onEvent: (event) => { const sid = event.sessionID || event.part?.sessionID if (sid && sid !== sessionId) { sessionId = sid; emitSafe(onSession, sid, 'session') } + // The last step's prompt plus output is what the next request starts from (chat/context.mjs). + const ctx = onContext && opencodeContextUsage(event) + if (ctx) emitSafe(onContext, ctx, 'context') if (event.type === 'text' && event.part) { const id = event.part.id || 'text' const full = event.part.text || '' @@ -8644,7 +8748,13 @@ const threadStore = createThreadStore({ await browserManager.closeSession(thread.id).catch(() => {}) }, }) -const chatRuns = createChatRuns({ log, onEnd: (run) => drainChatQueue(run.threadId, run.outcome || (run.status === 'stopped' ? 'stopped' : 'error')) }) +const chatRuns = createChatRuns({ + log, + onEnd: (run) => drainChatQueue(run.threadId, run.outcome || (run.status === 'stopped' ? 'stopped' : 'error')) + // Compact idle threads → Before the cache expires: the timer for this chat's idle spell. + .then(() => idleCompactor.schedule(run.threadId)) + .catch((e) => log('chat run end handling failed', e?.message || e)), +}) // ---- Agent browser ------------------------------------------------------------ // T3 Code's collaborative browser, for Totem's agents: a headless Chrome or @@ -9451,7 +9561,7 @@ const CHAT_SETTINGS_FILE = join(HERE, 'data', 'chat-settings.json') // A message sent while a reply runs waits its turn (T3 Code's default), except on // an install that had steering before the queue existed: it keeps steering. const DEFAULT_FOLLOW_UP = EXISTING_INSTALL ? 'steer' : 'queue' -const DEFAULT_CHAT_SETTINGS = { titles: { provider: '', model: '', effort: '', off: false }, autoSettleDays: 3, totemsInChat: true, followUp: DEFAULT_FOLLOW_UP } +const DEFAULT_CHAT_SETTINGS = { titles: { provider: '', model: '', effort: '', off: false }, autoSettleDays: 3, totemsInChat: true, followUp: DEFAULT_FOLLOW_UP, autoCompactWindow: '', compactIdle: DEFAULT_IDLE_COMPACTION } let chatSettings = structuredClone(DEFAULT_CHAT_SETTINGS) readFile(CHAT_SETTINGS_FILE, 'utf8').then((raw) => { chatSettings = normalizeChatSettings(JSON.parse(raw)) }).catch(() => {}) @@ -9465,6 +9575,10 @@ function normalizeChatSettings(raw = {}) { totemsInChat: raw.totemsInChat !== false, // What Enter does while a reply runs; Ctrl/⌘+Enter does the other (chat/queue.mjs). followUp: raw.followUp === 'queue' || raw.followUp === 'steer' ? raw.followUp : DEFAULT_FOLLOW_UP, + // Claude's auto-compact window (chat/context.mjs): '' is Claude's own default. + autoCompactWindow: normalizeAutoCompactWindow(raw.autoCompactWindow) ?? '', + // What an idle Claude chat of 200k tokens or more does once its prompt cache goes cold (T3's Compact idle threads). + compactIdle: IDLE_COMPACTION_MODES.includes(raw.compactIdle) ? raw.compactIdle : DEFAULT_IDLE_COMPACTION, } } @@ -9713,6 +9827,18 @@ async function handleChatSend(req, res) { await startChatTurn(body) } catch (e) { if (!e.status) throw e + // The bridge is compacting this idle chat on its own (chat/compaction.mjs): + // his message waits right behind it, and he watches it go. + // Only a plain typed message, and only when nothing was written yet (`busy`). + if (e.code === 'busy' && chatRuns.active(body.threadId)?.idle && !body.regenerate && !body.editMessageId && !body.queuedId && !body.voice) { + try { + await changeChatQueue({ ...body, action: 'add' }) + } catch (q) { + if (!q.status) throw q + return send(res, q.status, { error: q.message }) + } + return streamChatRun(req, res, body.threadId, 0) + } return send(res, e.status, { error: e.message }) } return streamChatRun(req, res, body.threadId, 0) @@ -9723,10 +9849,10 @@ async function handleChatSend(req, res) { * composer (handleChatSend) or from the queue once the reply before it ends * (`queuedId`, chat/queue.mjs). Errors meant for the client carry a `status`. */ -async function startChatTurn(body) { +async function startChatTurn(body, { idle = null } = {}) { const threadId = body.threadId if (!validThreadId(threadId)) throw Object.assign(new Error('missing threadId'), { status: 400 }) - if (chatRuns.active(threadId)) throw Object.assign(new Error('this chat is already answering'), { status: 409 }) + if (chatRuns.active(threadId)) throw Object.assign(new Error('this chat is already answering'), { status: 409, code: 'busy' }) const config = await readProviderConfig() const existing = await threadStore.get(threadId) @@ -9757,6 +9883,15 @@ async function startChatTurn(body) { const assistantId = randomUUID() let userIndex = -1 let userMessage = null + // Compaction (chat/context.mjs). `/compact` as the message compacts the chat's + // session; "Compact and send" (`compactFirst`, T3's onReturn) compacts first + // and queues the message right behind it; `idle` is the bridge compacting an + // idle chat itself (beforeCacheExpires), which must leave its state alone. + const session = existing?.sessions?.[provider] + const compactFirst = !idle && body.compactFirst === true && !body.regenerate && !body.editMessageId && !body.queuedId + && driver === 'claude' && !!session?.id && chatSettings.compactIdle !== 'off' && !isCompactCommand(text) + let compactTrigger = idle || (compactFirst ? 'onReturn' : null) + const quiet = !!idle // One write: drop what a regenerate or an edit replaces, append the turn. const thread = await threadStore.update(threadId, async (t) => { @@ -9781,11 +9916,27 @@ async function startChatTurn(body) { if (m) metas.push({ id: m.id, name: m.name, mime: m.mime, size: m.size, kind: m.kind, ...(m.preview ? { preview: m.preview } : {}) }) } const inbox = inboxMarker(body.inbox) - userMessage = { id: userMessage?.id || randomUUID(), role: 'user', content: text, createdAt: now, ...(metas.length ? { attachments: metas } : {}), ...(voice ? { voice: true } : {}), ...(inbox ? { inbox } : {}) } + if (compactFirst) { + // His message waits at the front of the queue and goes the moment the compaction ends. + t.queue = [{ + id: randomUUID(), text, attachments: [...metas], createdAt: now, + provider: typeof body.provider === 'string' ? body.provider : undefined, + model: typeof body.model === 'string' ? body.model : undefined, + effort: typeof body.effort === 'string' ? body.effort : undefined, + modelSettings: body.modelSettings, + ...(inbox ? { inbox } : {}), + }, ...(t.queue || [])] + text = '/compact' + attachments = [] + metas.length = 0 + } + const compacting = isCompactCommand(text) && !metas.length + if (compacting) compactTrigger ||= 'manual' + userMessage = { id: userMessage?.id || randomUUID(), role: 'user', content: text, createdAt: now, ...(metas.length ? { attachments: metas } : {}), ...(voice ? { voice: true } : {}), ...(inbox && !compactFirst ? { inbox } : {}), ...(compacting ? { command: 'compact' } : {}) } t.messages.push(userMessage) userIndex = t.messages.length - 1 // A message of his own lets a held queue go again once this reply ends (T3 Code). - if (!body.queuedId) delete t.queueHeld + if (!body.queuedId && !quiet) delete t.queueHeld t.messages.push({ id: assistantId, role: 'assistant', content: '', parts: [], status: 'streaming', provider, model: choice.label, createdAt: now, ...(choice.effort ? { effort: choice.effort } : {}), @@ -9796,6 +9947,8 @@ async function startChatTurn(body) { t.provider = provider if (body.modelSettings && typeof body.modelSettings === 'object') t.modelSettings = body.modelSettings if (!t.title) t.title = fallbackTitle(text) || (metas[0]?.name ?? '') + // The bridge compacting an idle chat is not him coming back to it. + if (quiet) return // He answered: the chat no longer waits on him. delete t.needsReply delete t.keepUnread @@ -9840,7 +9993,8 @@ async function startChatTurn(body) { // The task this chat works toward (Chats panel → Tasks), read fresh each turn. const taskCtx = voice ? '' : await linkedTaskContext(thread.taskId).catch(() => '') const contextBlock = `${projectCtx?.text || ''}${taskCtx}${totemCtx}${totemRule}${groupRule ? `${groupRule}\n\n` : ''}${othersRule}` - const needsTitle = !existing?.title || userIndex === 0 + const isCompaction = userMessage.command === 'compact' + const needsTitle = !isCompaction && (!existing?.title || userIndex === 0) const streamLive = streamingEnabled(provider, config) // The browser, computer use and the hour: every dashboard or app chat, never voice. // Cursor and OpenCode reach the browser only through the gateway (browserArgs). @@ -9862,7 +10016,7 @@ async function startChatTurn(body) { const save = (extra) => threadStore.update(threadId, (t) => { const i = t.messages.findIndex((m) => m.id === assistant.id) if (i >= 0) t.messages[i] = structuredClone(assistant) - t.updatedAt = Date.now() + if (!quiet) t.updatedAt = Date.now() extra?.(t) }).catch((e) => log('chat: save failed', e?.message || e)) // A reload mid-run shows the reply so far, not an empty bubble. @@ -10064,6 +10218,35 @@ async function startChatTurn(body) { }, } try { + // `/compact` (chat/context.mjs): the chat's own session summarises itself. + // The reply is only its divider, so it never counts as an answer to read. + if (isCompaction) { + const part = { id: `cmp-${assistant.id.slice(0, 8)}`, trigger: compactTrigger || 'manual' } + const fail = (reason) => forward({ type: 'compaction', compaction: { ...part, status: 'failed', reason, endedAt: Date.now() } }) + const own = thread.sessions?.[provider] + if (driver !== 'claude') { fail(COMPACT_UNSUPPORTED); return } + if (!own?.id) { fail('Not enough messages to compact.'); return } + forward({ type: 'compaction', compaction: { ...part, status: 'running', startedAt: Date.now() } }) + let seen = false + let r + try { + r = await STREAMERS[driver](text, { + label: 'web chat compact', signal, instance: instanceFor(provider), model: choice.model, effort: choice.effort, + resume: own.id, timeoutMs, + onSession: (id) => { sessionId = id }, + onContext: (ctx) => forward({ type: 'context', context: ctx }), + // One divider per compaction turn: Claude's own events settle this turn's part. + onCompaction: (c) => { if (c.status !== 'running') { seen = true; forward({ type: 'compaction', compaction: { ...c, id: part.id, trigger: part.trigger } }) } }, + }).then((res) => { usage = addUsage(usage, res.usage); return res }) + } catch (e) { + if (signal.aborted) { status = 'stopped'; return } + fail(truncate(String(e?.message || e), 300)) + return + } + if (r.stopped) status = 'stopped' + else if (!seen) fail(truncate((r.result || '').trim() || r.stderr?.trim().split('\n').slice(-2).join(' ') || 'Claude did not compact the chat.', 300)) + return + } // A skill command ($morning, /journal, …) runs the skill rather than chatting. const matchedSkill = !body.regenerate && !files.length ? await lookupSkillCommand(text.toLowerCase(), text) : null if (matchedSkill) { @@ -10183,6 +10366,9 @@ async function startChatTurn(body) { }, onAgent: (ev) => forwardAgent(tag && ev.toolId ? { ...ev, toolId: `${ev.toolId}${tag}` } : ev), onSession: (id) => { sessionId = id }, + // How full the context is, and the CLI's own compactions (chat/context.mjs). + onContext: (ctx) => forward({ type: 'context', context: ctx }), + onCompaction: (c) => forward({ type: 'compaction', compaction: c }), onImage: async ({ buffer, mime, name }) => { const ext = (mime.split('/')[1] || 'png').replace('jpeg', 'jpg') const up = await chatUploads.save({ buffer, name: name || `screenshot-${Date.now()}.${ext}`, mime }) @@ -10294,8 +10480,14 @@ async function startChatTurn(body) { // Through this reply only: an inbox outcome recorded while it ran (chat/inbox-outcome.mjs) // comes after it, unseen, and must be replayed next turn. const at = t.messages.findIndex((m) => m.id === assistant.id) - t.sessions = { ...(t.sessions || {}), [provider]: { id: sessionId, through: at >= 0 ? at + 1 : t.messages.length } } + const prior = t.sessions?.[provider] + // A compaction leaves the session where it was in the chat: turns another + // account answered before it are still replayed next time. + const through = isCompaction && prior?.id === sessionId && prior.through < userIndex ? prior.through : at >= 0 ? at + 1 : t.messages.length + t.sessions = { ...(t.sessions || {}), [provider]: { id: sessionId, through } } } + // A compaction is housekeeping: nothing new to read, nothing to wake for. + if (isCompaction) return // Finished (or failed) and now waiting on him, until he replies or marks it read. // A totem's chat posts on a schedule, so it never waits. if (status !== 'stopped' && !t.totemId) t.needsReply = true @@ -10314,8 +10506,9 @@ async function startChatTurn(body) { run.outcome = status push({ type: 'done', message: signMessage(structuredClone(assistant)) }) noteAiUsage(provider) + log(`web chat [${provider}] ${isCompaction ? `compaction (${compactTrigger}) ` : ''}${status} in ${Date.now() - t0}ms`) + if (isCompaction) return recordUse('web', { text, startedAt: t0, ok: status !== 'error', provider }) - log(`web chat [${provider}] ${status} in ${Date.now() - t0}ms`) // Nobody looking at this chat (phone locked, app in the background, another // chat open): tell the phone it's done. Skipped only while someone is on it. if (status !== 'stopped' && !someoneViewing(threadId)) { @@ -10333,6 +10526,9 @@ async function startChatTurn(body) { }, }) + if (idle) run.idle = idle + // Compact and send: his message now waits in the queue (or, refused, went as it was). + if (body.compactFirst) announceQueue(threadId, await threadStore.get(threadId).catch(() => null)) return run } @@ -10430,6 +10626,18 @@ async function changeChatQueue(body) { throw Object.assign(new Error('unknown queue action'), { status: 400 }) } +// Compact idle threads → Before the cache expires (chat/compaction.mjs): after +// every run, a timer two minutes before the chat's prompt cache expires. +const idleCompactor = createIdleCompactor({ + threads: threadStore, + isRunning: (id) => !!chatRuns.active(id), + startTurn: (body, opts) => startChatTurn(body, opts), + mode: () => chatSettings.compactIdle, + driverOf, + enabled: async (provider) => (await readProviderConfig()).enabledProviders.includes(provider), + log, +}) + /** * A run has ended (or the queue changed with nothing running): start the first * queued message, or hold the queue when the run was stopped or failed. A @@ -10800,12 +11008,18 @@ async function handleChatApi(req, res, path) { if (req.method === 'GET' && path === '/api/chat/settings') return send(res, 200, { settings: chatSettings }) if (req.method === 'PUT' && path === '/api/chat/settings') { const body = await readJsonBody(req) + if ('autoCompactWindow' in body && normalizeAutoCompactWindow(body.autoCompactWindow) === null) { + return send(res, 400, { error: 'Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude\'s default.' }) + } const next = normalizeChatSettings({ ...chatSettings, ...body, titles: { ...chatSettings.titles, ...(body.titles || {}) } }) // A Claude model can only be chosen on a Claude account (never Codex). const titles = next.titles if (titles.provider && !(await readProviderConfig()).enabledProviders.includes(titles.provider)) titles.provider = '' if (titles.provider && driverOf(titles.provider) === 'codex' && titles.model && !CODEX_MODEL_ID.test(titles.model)) titles.model = '' + const idleChanged = next.compactIdle !== chatSettings.compactIdle chatSettings = next + // Switched to "Before the cache expires": chats already idle get their timer too. + if (idleChanged) idleCompactor.reschedule().catch((e) => log('idle compaction: reschedule failed', e?.message || e)) await mkdir(dirname(CHAT_SETTINGS_FILE), { recursive: true }) await writeFile(CHAT_SETTINGS_FILE, JSON.stringify(next, null, 2)) return send(res, 200, { settings: next }) diff --git a/chat/compaction-bridge.test.mjs b/chat/compaction-bridge.test.mjs new file mode 100644 index 0000000..f201d60 --- /dev/null +++ b/chat/compaction-bridge.test.mjs @@ -0,0 +1,192 @@ +// Run with: node --test chat/compaction-bridge.test.mjs +// +// Compaction against a real bridge.mjs (chat/context.mjs, docs/chat.md → Context +// window and compaction). The Claude account runs a fake CLI that prints Claude +// Code's stream-json: a reply reports its usage, `/compact` reports a compaction. +// Checks what only the bridge decides: the reading saved on the reply, a +// `/compact` turn resuming the session and keeping it hidden housekeeping, and +// Compact and send putting the message, files and all, right behind it. +// +// The bridge runs from a shadow checkout (a temp dir of symlinks to this repo with +// its own empty data/), on its own port, with no scheduler, and is stopped at the end. + +import test, { before, after } from 'node:test' +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { connect, createServer } from 'node:net' +import { chmodSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, writeFileSync, symlinkSync, rmSync, realpathSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +const REPO = dirname(dirname(fileURLToPath(import.meta.url))) +const SECRET = 'compaction-bridge-test-secret' + +const freePort = () => new Promise((resolve) => { + const server = createServer() + server.listen(0, '127.0.0.1', () => { const { port } = server.address(); server.close(() => resolve(port)) }) +}) +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +const canConnect = (port) => new Promise((resolve) => { + const socket = connect(port, '127.0.0.1') + socket.once('connect', () => { socket.destroy(); resolve(true) }) + socket.once('error', () => resolve(false)) +}) + +// Claude Code 2.1.325's events, trimmed to what the bridge reads. +const FAKE_CLAUDE = `#!/usr/bin/env node +const fs = require('node:fs') +const args = process.argv.slice(2) +const prompt = args[args.indexOf('--') + 1] || '' +fs.appendFileSync(process.env.FAKE_CLAUDE_LOG, JSON.stringify({ args, prompt }) + '\\n') +const out = (e) => process.stdout.write(JSON.stringify({ session_id: 'sess-1', ...e }) + '\\n') +out({ type: 'system', subtype: 'init', model: 'claude-opus-5-5' }) +if (prompt.startsWith('/compact')) { + out({ type: 'system', subtype: 'status', status: 'compacting' }) + out({ type: 'system', subtype: 'status', status: 'compacting' }) + out({ type: 'system', subtype: 'compact_boundary', compact_metadata: { trigger: 'manual', pre_tokens: 251010, post_tokens: 30000 } }) + out({ type: 'system', subtype: 'status', status: null, compact_result: 'success' }) + out({ type: 'result', subtype: 'success', result: '', local_command: 'compact', usage: { input_tokens: 4, output_tokens: 900 } }) +} else { + out({ type: 'stream_event', event: { type: 'message_start' } }) + const usage = { input_tokens: 1000, cache_creation_input_tokens: 250000, cache_read_input_tokens: 0, cache_creation: { ephemeral_1h_input_tokens: 250000, ephemeral_5m_input_tokens: 0 }, output_tokens: 10 } + out({ type: 'assistant', parent_tool_use_id: null, message: { model: 'claude-opus-5-5', content: [{ type: 'text', text: 'ok' }], usage } }) + out({ type: 'result', subtype: 'success', result: 'ok', usage, modelUsage: { 'claude-opus-5-5': { contextWindow: 1000000 } } }) +} +` + +const B = {} +const bearer = { authorization: `Bearer ${SECRET}`, 'content-type': 'application/json' } +const call = async (method, path, body) => { + const r = await fetch(`${B.base}${path}`, { method, headers: bearer, body: body ? JSON.stringify(body) : undefined }) + const text = await r.text() + assert.ok(r.ok, `${method} ${path} ${r.status} ${text}`) + return text +} +const chat = async (body) => { + const text = await call('POST', '/api/chat', { provider: 'claude', ...body }) + return text.split('\n').filter((l) => l.startsWith('data: ')).map((l) => JSON.parse(l.slice(6))) +} +const thread = async (id) => { + const r = JSON.parse(await call('GET', `/api/threads/${id}?turns=50`)) + return r.thread || r +} +const until = async (fn, ms = 15_000) => { + const deadline = Date.now() + ms + for (;;) { + const v = await fn() + if (v) return v + if (Date.now() > deadline) throw new Error('timed out waiting') + await wait(100) + } +} +const invocations = () => readFileSync(B.log, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l)) + +before(async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'totem-compaction-bridge-'))) + for (const entry of readdirSync(REPO)) { + if (entry === 'data' || entry === '.env' || entry === '.git' || entry === 'AGENTS.local.md') continue + symlinkSync(join(REPO, entry), join(root, entry)) + } + B.root = root + mkdirSync(join(root, 'data'), { recursive: true }) + mkdirSync(join(root, 'home')) + writeFileSync(join(root, 'data', 'auth.json'), '{}') + const fake = join(root, 'home', 'fake-claude.cjs') + writeFileSync(fake, FAKE_CLAUDE) + chmodSync(fake, 0o755) + B.log = join(root, 'home', 'fake-claude.log') + writeFileSync(B.log, '') + writeFileSync(join(root, 'data', 'provider-config.json'), JSON.stringify({ + defaultProvider: 'claude', enabledProviders: ['claude'], + instances: { claude: { driver: 'claude', config: { binaryPath: fake } } }, + })) + + const port = await freePort() + B.base = `http://127.0.0.1:${port}` + let output = '' + const child = spawn(process.execPath, ['--preserve-symlinks', '--preserve-symlinks-main', join(root, 'bridge.mjs')], { + cwd: root, + env: { PATH: process.env.PATH, HOME: join(root, 'home'), BRIDGE_PORT: String(port), BRIDGE_SECRET: SECRET, BRIDGE_NO_SCHEDULER: '1', AGENT_CWD: root, FAKE_CLAUDE_LOG: B.log }, + stdio: ['ignore', 'pipe', 'pipe'], + }) + child.stdout.on('data', (d) => { output += d }) + child.stderr.on('data', (d) => { output += d }) + B.output = () => output + B.stop = () => new Promise((resolve) => { + if (child.exitCode !== null) return resolve() + child.once('exit', resolve) + child.kill('SIGTERM') + setTimeout(() => { child.kill('SIGKILL'); resolve() }, 3000) + }) + const deadline = Date.now() + 30_000 + while (!(await canConnect(port))) { + if (child.exitCode !== null) throw new Error(`bridge exited early:\n${output}`) + if (Date.now() > deadline) throw new Error(`bridge never listened:\n${output}`) + await wait(20) + } +}) + +after(async () => { + await B.stop?.() + if (B.root) rmSync(B.root, { recursive: true, force: true }) +}) + +test('a reply keeps how full the context is, and /compact compacts its session as a hidden turn', async () => { + const id = 'ctx-manual' + const first = await chat({ threadId: id, text: 'hello' }) + const reading = first.filter((e) => e.type === 'context').pop()?.context + assert.equal(reading.used, 251010) + assert.equal(reading.max, 1_000_000) + assert.equal(reading.cacheTtlMs, 3_600_000) + + await call('PUT', `/api/threads/${id}`, { needsReply: false }) + const events = await chat({ threadId: id, text: '/compact' }) + const compactions = events.filter((e) => e.type === 'compaction') + assert.deepEqual([...new Set(compactions.map((e) => e.compaction.id))].length, 1, 'one divider, however often Claude says it is compacting') + + const t = await thread(id) + const [, , ask, reply] = t.messages + assert.equal(ask.command, 'compact') + const part = reply.parts.find((p) => p.type === 'compaction') + assert.equal(part.status, 'done') + assert.equal(part.trigger, 'manual') + assert.equal(part.before, 251010) + assert.equal(part.after, 30000) + assert.equal(reply.context.used, 30000) + assert.equal(reply.status, 'done') + assert.deepEqual(t.sessions.claude, { id: 'sess-1', through: 4 }) + + const compactRun = invocations().find((i) => i.prompt === '/compact') + assert.ok(compactRun, 'the CLI was handed /compact as the whole prompt') + assert.equal(compactRun.args[compactRun.args.indexOf('--resume') + 1], 'sess-1') +}) + +test('Compact and send compacts first, then sends the message with its files', async () => { + const id = 'ctx-onreturn' + await chat({ threadId: id, text: 'hello' }) + const up = JSON.parse(await (await fetch(`${B.base}/api/chat/uploads?name=notes.txt&mime=text/plain`, { method: 'POST', headers: { authorization: `Bearer ${SECRET}` }, body: 'the notes' })).text()) + const events = await chat({ threadId: id, text: 'carry on', attachments: [up.id], compactFirst: true }) + const queued = events.find((e) => e.type === 'queue')?.queue?.[0] + assert.equal(queued.text, 'carry on') + assert.equal(queued.attachments?.[0]?.id, up.id, 'the files wait with the words') + + const t = await until(async () => { const x = await thread(id); return x.messages.length === 6 && x.messages[5].status === 'done' ? x : null }) + const [, , ask, compacted, sent, answer] = t.messages + assert.equal(ask.command, 'compact') + assert.equal(compacted.parts.find((p) => p.type === 'compaction').trigger, 'onReturn') + assert.equal(sent.content, 'carry on') + assert.equal(sent.attachments?.[0]?.id, up.id) + assert.equal(answer.content, 'ok') + assert.ok(!t.queue?.length) +}) + +test('/compact on a chat with no session says so instead of running anything', async () => { + const before = invocations().length + await chat({ threadId: 'ctx-empty', text: '/compact' }) + const t = await thread('ctx-empty') + const part = t.messages[1].parts.find((p) => p.type === 'compaction') + assert.equal(part.status, 'failed') + assert.equal(part.reason, 'Not enough messages to compact.') + assert.equal(invocations().length, before) +}) diff --git a/chat/compaction.mjs b/chat/compaction.mjs new file mode 100644 index 0000000..365dc61 --- /dev/null +++ b/chat/compaction.mjs @@ -0,0 +1,58 @@ +// chat/compaction.mjs — Compact idle threads → Before the cache expires (T3 +// Code's IdleCompactionService): two minutes before an idle Claude chat's prompt +// cache expires, the bridge sends it `/compact` itself. When to compact is +// idleCompactionWindow in chat/context.mjs; this is only the timers. +// +// Timers live in memory, so a restart loses them; the chat then offers Compact +// and send instead (When you return). Each firing looks at the chat again: the +// owner may have written, settled or snoozed it since, or switched the account off. + +import { idleCompactionWindow } from './context.mjs' + +/** + * `threads` is the thread store (get, list); `isRunning(id)` whether a reply is + * running; `startTurn(body, { idle })` startChatTurn; `mode()` the setting; + * `enabled(provider)` whether that account is still on. + */ +export function createIdleCompactor({ threads, isRunning, startTurn, mode, driverOf, enabled = async () => true, log = () => {}, now = () => Date.now(), setTimer = setTimeout, clearTimer = clearTimeout }) { + const timers = new Map() + const on = () => mode() === 'beforeCacheExpires' + const windowFor = (t) => idleCompactionWindow(t, { driverOf, now: now(), running: !!t && isRunning(t.id) }) + + function cancel(threadId) { + clearTimer(timers.get(threadId)) + timers.delete(threadId) + } + + async function fire(threadId) { + timers.delete(threadId) + if (!on()) return + const t = await threads.get(threadId).catch(() => null) + if (!windowFor(t) || !(await enabled(t.provider))) return + const last = t.messages[t.messages.length - 1] + log(`idle compaction: compacting ${threadId} before its prompt cache expires`) + await startTurn({ threadId, text: '/compact', provider: t.provider, model: last.model, effort: last.effort, modelSettings: t.modelSettings }, { idle: 'beforeCacheExpires' }) + } + + /** After a run ends: this chat's timer for its idle spell, if it gets one. */ + async function schedule(threadId) { + cancel(threadId) + if (!on()) return + const win = windowFor(await threads.get(threadId).catch(() => null)) + if (!win) return + const timer = setTimer(() => { fire(threadId).catch((e) => log('idle compaction failed', e?.message || e)) }, Math.max(0, win.startMs - now())) + timer?.unref?.() + timers.set(threadId, timer) + } + + /** The setting changed: every recently active chat gets (or loses) its timer. */ + async function reschedule() { + for (const id of [...timers.keys()]) cancel(id) + if (!on()) return + const list = await threads.list().catch(() => []) + // Claude's longest cache lasts an hour; nothing quiet for longer can still be warm. + for (const t of list) if (Number(t.updatedAt) > now() - 2 * 60 * 60_000) await schedule(t.id) + } + + return { schedule, reschedule, fire, pending: () => [...timers.keys()] } +} diff --git a/chat/context.mjs b/chat/context.mjs new file mode 100644 index 0000000..a5294a8 --- /dev/null +++ b/chat/context.mjs @@ -0,0 +1,299 @@ +// chat/context.mjs — how full a chat's context window is, and compacting it. +// +// Ported from T3 Code (pingdotgg/t3code, main of 2026-11-16): the same sources, +// thresholds and idle-compaction rules, mapped onto Totem's CLI runs. +// +// Context fill is the LAST request's prompt plus its output, never a reply's +// billed total (chat/stats.mjs sums every request of a turn, which says nothing +// about how full the window is): +// Claude Code each top-level `assistant` event's message.usage: +// input + cache_creation + cache_read + output +// Codex the rollout file's `token_count` events (`codex exec --json` +// only reports the turn's total): last_token_usage.total_tokens +// over model_context_window +// OpenCode the last step_finish: input + cache.read + cache.write + output +// Cursor its CLI reports no context fill, so no meter +// +// Compaction is the CLI's own: Claude Code and Codex compact a session +// themselves when it fills. Totem shows it (a divider in the reply), drops the +// meter to what is left, and adds T3's two extras for Claude: +// - `/compact` sent as a message compacts the chat's session on demand; +// - idle compaction (Settings → Chat › Compact idle threads): a chat of +// 200k tokens or more whose prompt cache has expired offers "Compact and +// send" (onReturn, the default), or compacts itself two minutes before the +// cache expires (beforeCacheExpires), or never (off). + +/** A message that is a compaction command: `/compact`, optionally with instructions (T3's COMPACT_COMMAND_PATTERN). */ +export const COMPACT_COMMAND = /^\/compact(?:\s|$)/i +export const isCompactCommand = (text) => COMPACT_COMMAND.test(String(text || '').trim()) + +/** T3's words for a provider that cannot compact on demand. */ +export const COMPACT_UNSUPPORTED = 'This provider does not support /compact. Start a new thread to continue with a fresh context.' + +/** + * Context size below which neither the Compact chip nor idle compaction runs: + * Claude Code's own idleCompaction default (it will not go below 100k). Under it + * a cold re-read is cheap, so compacting mostly loses context for little saving. + */ +export const COMPACTION_MIN_TOKENS = 200_000 +/** Idle compaction starts this long before the prompt cache expires, while it is still warm. */ +export const IDLE_COMPACT_LEAD_MS = 2 * 60_000 +/** When the cache lifetime is unknown, how long before a chat counts as gone cold (T3). */ +export const CACHE_TTL_FALLBACK_MS = 70 * 60_000 +/** + * Claude compacts this many tokens short of its auto-compact window: Claude Code + * 2.1.305 reports a 150,000 window as a 117,000 threshold, for every model (T3). + */ +export const CLAUDE_AUTO_COMPACT_RESERVE_TOKENS = 33_000 + +export const IDLE_COMPACTION_MODES = ['onReturn', 'beforeCacheExpires', 'off'] +export const DEFAULT_IDLE_COMPACTION = 'onReturn' + +const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0) +const has = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0 + +/** + * Settings → Chat › Auto-compact after: empty (Claude's default) or a whole + * number from 100,000 to 1,000,000, the same rule as T3's setting. Returns the + * stored string, '' for empty, or null when the value is not allowed. + */ +export function normalizeAutoCompactWindow(raw) { + const s = String(raw ?? '').replace(/[,_\s]/g, '') + if (!s) return '' + return /^(?:[1-9]\d{5}|1000000)$/.test(s) ? s : null +} + +const truthy = (v) => v !== undefined && ['1', 'true', 'yes', 'on'].includes(String(v).trim().toLowerCase()) + +/** + * The auto-compact window a Claude run uses, as T3's resolveAutoCompactWindow + * reads it: none when compaction is off (DISABLE_COMPACT, DISABLE_AUTO_COMPACT, + * autoCompactEnabled:false), else Totem's setting, else the env's + * CLAUDE_CODE_AUTO_COMPACT_WINDOW, else the account's settings.json + * (modelSettings[model].autoCompactWindow, then autoCompactWindow). '' = Claude's + * own default, which reports no threshold. + */ +export function claudeAutoCompactWindow({ setting = '', env = {}, settings = null, model = '' } = {}) { + if (truthy(env.DISABLE_COMPACT) || truthy(env.DISABLE_AUTO_COMPACT)) return '' + if (settings && settings.autoCompactEnabled === false) return '' + const own = normalizeAutoCompactWindow(setting) + if (own) return own + const valid = (v) => (Number.isInteger(Number(v)) && Number(v) >= 100_000 && Number(v) <= 1_000_000 ? String(Number(v)) : '') + const fromEnv = env.CLAUDE_CODE_AUTO_COMPACT_WINDOW !== undefined ? valid(env.CLAUDE_CODE_AUTO_COMPACT_WINDOW) : '' + if (fromEnv) return fromEnv + if (settings && typeof settings === 'object') { + const bare = String(model || '').replace(/\[1m\]$/i, '') + const per = settings.modelSettings?.[bare]?.autoCompactWindow + if (per === 'auto') return '' + return valid(per) || valid(settings.autoCompactWindow) + } + return '' +} + +/** Where Claude compacts, for the meter's tick: the window less its reserve, only when set below the model's window. */ +export function claudeAutoCompactThreshold(window, maxTokens) { + const w = Number(window) + return w > 0 && (!maxTokens || w < maxTokens) ? w - CLAUDE_AUTO_COMPACT_RESERVE_TOKENS : null +} + +// T3 Code's Claude catalog (apps/server/src/provider/model-manifest.json): the +// window Claude Code compacts against, per model. A [1m] suffix picks the 1M +// window on the two models that offer both. +const CLAUDE_WINDOWS = [ + [/^(?:claude-)?(?:fable|opus|sonnet|haiku)$/i, 1_000_000], + [/^claude-fable-5(?:-\d+)?$/i, 1_000_000], + [/^claude-opus-5(?:-\d+)?$/i, 1_000_000], + [/^claude-opus-4-[78]$/i, 1_000_000], + [/^claude-sonnet-5(?:-\d+)?$/i, 1_000_000], + [/^claude-haiku-5-5$/i, 1_000_000], + [/^claude-(?:opus-4-5|haiku-4-5)(?:-\d{8})?$/i, 200_000], +] + +/** + * A Claude model's context window: the catalog first, then the window Claude + * Code itself reported for it (`result.modelUsage[model].contextWindow`), else + * null (tokens shown, no bar). + */ +export function claudeContextWindow(model, reported = null) { + const id = String(model || '').trim() + if (/^claude-(?:opus|sonnet)-4-6(?:-\d{8})?(\[1m\])?$/i.test(id)) return /\[1m\]$/i.test(id) ? 1_000_000 : 200_000 + const bare = id.replace(/\[1m\]$/i, '') + for (const [re, size] of CLAUDE_WINDOWS) if (re.test(bare)) return size + return has(reported) && reported > 0 ? reported : null +} + +/** The window Claude Code reported in a `result` event, by model id. */ +export function reportedClaudeWindows(event) { + const out = {} + const mu = event?.type === 'result' ? event.modelUsage : null + if (!mu || typeof mu !== 'object') return out + for (const [id, u] of Object.entries(mu)) if (has(u?.contextWindow) && u.contextWindow > 0) out[id] = u.contextWindow + return out +} + +/** How long Claude's prompt cache lasts for the request that wrote it, or undefined. */ +export function claudeCacheTtlMs(cacheCreation) { + if (!cacheCreation || typeof cacheCreation !== 'object') return undefined + if (num(cacheCreation.ephemeral_1h_input_tokens) > 0) return 60 * 60_000 + if (num(cacheCreation.ephemeral_5m_input_tokens) > 0) return 5 * 60_000 + return undefined +} + +/** + * One Claude request's usage as context fill, or null for a placeholder (no + * input: not a measurement). `requestedAt` is when the request started + * (`message_start`): the cache lifetime runs from there, not from the reply's end. + */ +export function claudeContextUsage(usage, { maxTokens = null, autoCompactWindow = '', requestedAt = 0, at = Date.now() } = {}) { + if (!usage || typeof usage !== 'object' || !has(usage.input_tokens)) return null + const input = num(usage.input_tokens) + num(usage.cache_creation_input_tokens) + num(usage.cache_read_input_tokens) + if (input <= 0) return null + const output = num(usage.output_tokens) + const ttl = claudeCacheTtlMs(usage.cache_creation) + const threshold = claudeAutoCompactThreshold(autoCompactWindow, maxTokens) + return { + used: input + output, + ...(maxTokens ? { max: maxTokens } : {}), + input, + cached: num(usage.cache_read_input_tokens), + output, + ...(threshold ? { autoCompactAt: threshold } : {}), + ...(ttl ? { cacheTtlMs: ttl } : {}), + ...(ttl && requestedAt ? { cacheExpiresAt: requestedAt + ttl } : {}), + at, + } +} + +/** Codex's `token_count` rollout record as context fill: the last request, never the session total. */ +export function codexContextUsage(record, at = Date.now()) { + const p = record?.type === 'event_msg' ? record.payload : null + if (p?.type !== 'token_count' || !p.info) return null + const last = p.info.last_token_usage + if (!last || !has(last.total_tokens)) return null + const max = num(p.info.model_context_window) + return { + used: last.total_tokens, + ...(max ? { max } : {}), + input: num(last.input_tokens), + cached: num(last.cached_input_tokens), + output: num(last.output_tokens), + at, + } +} + +/** + * Does this Codex rollout record say the session was compacted? Codex 0.167 and + * later write a top-level `compacted` record (and a `ContextCompaction` item); + * 0.142–0.144 wrote an `event_msg` of type `context_compacted` beside it. One + * compaction can produce several of these, so the caller keeps one per moment. + */ +export function codexCompacted(record) { + if (record?.type === 'compacted') return true + const p = record?.type === 'event_msg' ? record.payload : null + return p?.type === 'context_compacted' || (p?.type === 'item_completed' && p.item?.type === 'ContextCompaction') +} + +/** OpenCode's step_finish as context fill: the step's prompt plus output is what the next request starts from. */ +export function opencodeContextUsage(event, at = Date.now()) { + const t = event?.type === 'step_finish' ? event.part?.tokens : null + if (!t || typeof t !== 'object') return null + const input = num(t.input) + num(t.cache?.read) + num(t.cache?.write) + if (input <= 0) return null + const output = num(t.output) + return { used: input + output, input, cached: num(t.cache?.read), output, at } +} + +const USAGE_KEYS = ['used', 'max', 'input', 'cached', 'output', 'autoCompactAt', 'cacheTtlMs', 'cacheExpiresAt', 'at'] + +/** A message's saved context reading, cleaned; null when it holds nothing usable. */ +export function normalizeContextUsage(raw) { + if (!raw || typeof raw !== 'object' || !has(raw.used)) return null + const out = {} + for (const k of USAGE_KEYS) if (has(raw[k])) out[k] = Math.round(raw[k]) + return out +} + +const COMPACTION_STATUSES = new Set(['running', 'done', 'failed', 'stopped']) +const COMPACTION_REASONS = new Set(['manual', 'auto', 'onReturn', 'beforeCacheExpires']) + +/** A `compaction` part, cleaned for the thread file. */ +export function normalizeCompactionPart(p) { + if (!p || typeof p !== 'object' || typeof p.id !== 'string' || !p.id) return null + const out = { + type: 'compaction', + id: p.id.slice(0, 80), + status: COMPACTION_STATUSES.has(p.status) ? p.status : 'done', + trigger: COMPACTION_REASONS.has(p.trigger) ? p.trigger : 'auto', + } + for (const k of ['before', 'after', 'startedAt', 'endedAt']) if (has(p[k])) out[k] = Math.round(p[k]) + if (typeof p.reason === 'string' && p.reason) out.reason = p.reason.slice(0, 300) + return out +} + +/** + * What one Claude `system` event says about compaction: `status: compacting` + * opens it, `compact_boundary` closes it with the tokens before and after, and a + * status line with `compact_result: 'failed'` ends it as failed. Null otherwise. + */ +export function claudeCompactionEvent(event) { + if (event?.type !== 'system') return null + if (event.subtype === 'status' && event.status === 'compacting') return { status: 'running' } + if (event.subtype === 'compact_boundary') { + const m = event.compact_metadata || {} + return { + status: 'done', + trigger: m.trigger === 'manual' ? 'manual' : 'auto', + ...(has(m.pre_tokens) ? { before: m.pre_tokens } : {}), + ...(has(m.post_tokens) ? { after: m.post_tokens } : {}), + } + } + if (event.subtype === 'status' && event.compact_result && event.compact_result !== 'success') { + return { status: 'failed', ...(event.compact_error ? { reason: String(event.compact_error) } : {}) } + } + return null +} + +/** The newest context reading for `provider` among `messages` (newest last), or null. */ +export function latestContext(messages, provider) { + for (let i = (messages?.length || 0) - 1; i >= 0; i--) { + const m = messages[i] + if (m?.role !== 'assistant' || (provider && m.provider !== provider)) continue + if (m.context) return m.context + } + return null +} + +/** Is the user message at `i` a compaction turn (`/compact`, no attachments), whose reply is only its divider? */ +export const isCompactionMessage = (m) => m?.role === 'user' && m.command === 'compact' + +/** + * Should an idle Claude chat compact itself now (Compact idle threads → Before + * the cache expires)? T3's idleCompactionWindow over Totem's thread: returns + * { startMs, endMs } for the window ending when the last request's cache + * expires, or null when it should not. + */ +export function idleCompactionWindow(thread, { driverOf = (p) => p, now = Date.now(), running = false } = {}) { + if (!thread || running) return null + if (thread.kind === 'temporary' || thread.totemId) return null + if (thread.settledOverride === 'settled' || thread.settledAt) return null + if (Number(thread.snoozedUntil) > now) return null + if (thread.queue?.length || thread.queueHeld) return null + const messages = thread.messages || [] + const last = messages[messages.length - 1] + const user = messages[messages.length - 2] + if (last?.role !== 'assistant' || last.status !== 'done' || user?.role !== 'user') return null + // Never compact a compaction, so one idle spell compacts at most once. + if (isCompactionMessage(user)) return null + // Something still waits on the owner in that reply: compaction would swallow it. + if ((last.parts || []).some((p) => (p.type === 'questions' || p.type === 'approval') && p.status === 'pending')) return null + const provider = thread.provider + if (!provider || driverOf(provider) !== 'claude' || last.provider !== provider) return null + const session = thread.sessions?.[provider] + if (!session?.id || session.through !== messages.length) return null + const ctx = last.context + if (!ctx || num(ctx.used) < COMPACTION_MIN_TOKENS) return null + // A request served fully from cache reports no lifetime: unknown, so skip. + const endMs = num(ctx.cacheExpiresAt) + if (!endMs || now >= endMs) return null + return { startMs: endMs - IDLE_COMPACT_LEAD_MS, endMs } +} diff --git a/chat/context.test.mjs b/chat/context.test.mjs new file mode 100644 index 0000000..b4b6cab --- /dev/null +++ b/chat/context.test.mjs @@ -0,0 +1,227 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { + COMPACTION_MIN_TOKENS, IDLE_COMPACT_LEAD_MS, claudeAutoCompactThreshold, codexCompacted, claudeAutoCompactWindow, claudeCacheTtlMs, + claudeCompactionEvent, claudeContextUsage, claudeContextWindow, codexContextUsage, idleCompactionWindow, isCompactCommand, + latestContext, normalizeAutoCompactWindow, opencodeContextUsage, reportedClaudeWindows, +} from './context.mjs' +import { applyEvent, finalizeMessage, renderTranscript } from './turn.mjs' +import { normalizeMessage, threadSummary } from './store.mjs' +import { createIdleCompactor } from './compaction.mjs' + +// Events as Claude Code 2.1.325 and codex-cli 0.169.0 printed them on 2026-11-16 (trimmed). +const CLAUDE_ASSISTANT_USAGE = { input_tokens: 2, cache_creation_input_tokens: 56995, cache_read_input_tokens: 0, cache_creation: { ephemeral_5m_input_tokens: 56995, ephemeral_1h_input_tokens: 0 }, output_tokens: 1 } +const CLAUDE_COMPACTING = { type: 'system', subtype: 'status', status: 'compacting', session_id: 's' } +const CLAUDE_COMPACTED = { type: 'system', subtype: 'status', status: null, compact_result: 'success', session_id: 's' } +const CLAUDE_BOUNDARY = { type: 'system', subtype: 'compact_boundary', session_id: 's', compact_metadata: { trigger: 'manual', pre_tokens: 57001, post_tokens: 19869, cumulative_dropped_tokens: 37132, duration_ms: 6058 } } +const CLAUDE_RESULT = { type: 'result', result: '', modelUsage: { 'claude-haiku-5-5': { inputTokens: 4, contextWindow: 1000000 }, 'claude-new-9': { contextWindow: 400000 } } } +const CODEX_TOKEN_COUNT = { timestamp: '2026-11-16T22:01:53.766Z', type: 'event_msg', payload: { type: 'token_count', info: { total_token_usage: { input_tokens: 90000, cached_input_tokens: 4352, output_tokens: 50, total_tokens: 90050 }, last_token_usage: { input_tokens: 18133, cached_input_tokens: 4352, cache_write_input_tokens: 0, output_tokens: 5, reasoning_output_tokens: 0, total_tokens: 18138 }, model_context_window: 475000 } } } + +test('/compact is a command with or without instructions, never mid-sentence', () => { + assert.ok(isCompactCommand('/compact')) + assert.ok(isCompactCommand(' /COMPACT keep the API decisions')) + assert.ok(!isCompactCommand('/compacted')) + assert.ok(!isCompactCommand('please /compact')) +}) + +test('the auto-compact setting takes T3\'s range only', () => { + assert.equal(normalizeAutoCompactWindow(''), '') + assert.equal(normalizeAutoCompactWindow('150,000'), '150000') + assert.equal(normalizeAutoCompactWindow(1000000), '1000000') + assert.equal(normalizeAutoCompactWindow('99999'), null) + assert.equal(normalizeAutoCompactWindow('1000001'), null) + assert.equal(normalizeAutoCompactWindow('abc'), null) +}) + +test('the compaction window follows T3\'s precedence, and off means no tick', () => { + assert.equal(claudeAutoCompactWindow({ setting: '300000', env: { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '200000' } }), '300000') + assert.equal(claudeAutoCompactWindow({ env: { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '200000' } }), '200000') + assert.equal(claudeAutoCompactWindow({ env: { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '50000' } }), '') + assert.equal(claudeAutoCompactWindow({ settings: { autoCompactWindow: 400000, modelSettings: { 'claude-opus-5-5': { autoCompactWindow: 250000 } } }, model: 'claude-opus-5-5[1m]' }), '250000') + assert.equal(claudeAutoCompactWindow({ settings: { autoCompactWindow: 400000, modelSettings: { 'claude-opus-5-5': { autoCompactWindow: 'auto' } } }, model: 'claude-opus-5-5' }), '') + assert.equal(claudeAutoCompactWindow({ setting: '300000', env: { DISABLE_AUTO_COMPACT: '1' } }), '') + assert.equal(claudeAutoCompactWindow({ setting: '300000', settings: { autoCompactEnabled: false } }), '') + // Claude compacts 33k short of the window, and only below the model's own. + assert.equal(claudeAutoCompactThreshold('150000', 1_000_000), 117_000) + assert.equal(claudeAutoCompactThreshold('1000000', 1_000_000), null) + assert.equal(claudeAutoCompactThreshold('', 1_000_000), null) +}) + +test('Claude windows come from T3\'s catalog, then what Claude Code reported', () => { + assert.equal(claudeContextWindow('claude-opus-5-5'), 1_000_000) + assert.equal(claudeContextWindow('claude-fable-5-2'), 1_000_000) + assert.equal(claudeContextWindow('opus'), 1_000_000) + assert.equal(claudeContextWindow('claude-haiku-4-5-20251001'), 200_000) + assert.equal(claudeContextWindow('claude-sonnet-4-6'), 200_000) + assert.equal(claudeContextWindow('claude-sonnet-4-6[1m]'), 1_000_000) + assert.equal(claudeContextWindow('claude-new-9'), null) + assert.equal(claudeContextWindow('claude-new-9', reportedClaudeWindows(CLAUDE_RESULT)['claude-new-9']), 400_000) +}) + +test('a Claude request is context fill: its whole prompt plus output, with the cache\'s lifetime', () => { + const ctx = claudeContextUsage(CLAUDE_ASSISTANT_USAGE, { maxTokens: 1_000_000, autoCompactWindow: '150000', requestedAt: 1000, at: 2000 }) + assert.deepEqual(ctx, { used: 56998, max: 1_000_000, input: 56997, cached: 0, output: 1, autoCompactAt: 117_000, cacheTtlMs: 300_000, cacheExpiresAt: 301_000, at: 2000 }) + assert.equal(claudeCacheTtlMs({ ephemeral_1h_input_tokens: 5, ephemeral_5m_input_tokens: 9 }), 3_600_000) + // A placeholder with no input is not a measurement. + assert.equal(claudeContextUsage({ input_tokens: 0, output_tokens: 0 }), null) +}) + +test('Codex reads the last request, not the session total; OpenCode its last step', () => { + assert.deepEqual(codexContextUsage(CODEX_TOKEN_COUNT, 5), { used: 18138, max: 475000, input: 18133, cached: 4352, output: 5, at: 5 }) + assert.equal(codexContextUsage({ type: 'event_msg', payload: { type: 'token_count', info: null } }), null) + assert.deepEqual(opencodeContextUsage({ type: 'step_finish', part: { tokens: { input: 900, output: 40, cache: { read: 100, write: 10 } } } }, 7), { used: 1050, input: 1010, cached: 100, output: 40, at: 7 }) +}) + +test('Claude\'s compaction events open and close a divider', () => { + assert.deepEqual(claudeCompactionEvent(CLAUDE_COMPACTING), { status: 'running' }) + assert.deepEqual(claudeCompactionEvent(CLAUDE_BOUNDARY), { status: 'done', trigger: 'manual', before: 57001, after: 19869 }) + assert.equal(claudeCompactionEvent(CLAUDE_COMPACTED), null) + assert.deepEqual(claudeCompactionEvent({ type: 'system', subtype: 'status', compact_result: 'failed', compact_error: 'boom' }), { status: 'failed', reason: 'boom' }) + assert.equal(claudeCompactionEvent({ type: 'system', subtype: 'init' }), null) +}) + +test('the reply folds context readings and compactions, and the thread file keeps them', () => { + const msg = { id: 'a1', role: 'assistant', content: '', parts: [], status: 'streaming', provider: 'claude' } + applyEvent(msg, { type: 'context', context: { used: 400_000, max: 1_000_000, at: 1 } }) + applyEvent(msg, { type: 'compaction', compaction: { id: 'c1', status: 'running', trigger: 'auto' } }, 10) + applyEvent(msg, { type: 'compaction', compaction: { id: 'c1', status: 'done', before: 400_000, after: 40_000 } }, 20) + applyEvent(msg, { type: 'context', context: { used: 40_000, max: 1_000_000, at: 2 } }) + assert.equal(msg.parts.length, 1) + assert.deepEqual(msg.parts[0], { type: 'compaction', id: 'c1', status: 'done', trigger: 'auto', startedAt: 10, before: 400_000, after: 40_000 }) + assert.equal(msg.context.used, 40_000) + finalizeMessage(msg, { status: 'done', finalText: 'ok' }) + const saved = normalizeMessage({ ...msg, context: { ...msg.context, model: 'x', junk: 'y' } }) + assert.deepEqual(saved.context, { used: 40_000, max: 1_000_000, at: 2 }) + assert.equal(saved.parts.find((p) => p.type === 'compaction').after, 40_000) + assert.equal(normalizeMessage({ role: 'user', content: '/compact', command: 'compact' }).command, 'compact') + assert.equal(normalizeMessage({ role: 'user', content: 'hi', command: 'other' }).command, undefined) +}) + +test('a compaction still running when the reply ends is stopped or failed', () => { + const stopped = { role: 'assistant', content: '', parts: [{ type: 'compaction', id: 'c', status: 'running', trigger: 'manual' }] } + finalizeMessage(stopped, { status: 'stopped' }) + assert.equal(stopped.parts[0].status, 'stopped') + const died = { role: 'assistant', content: 'x', parts: [{ type: 'compaction', id: 'c', status: 'running', trigger: 'auto' }] } + finalizeMessage(died, { status: 'done' }) + assert.equal(died.parts[0].status, 'failed') +}) + +test('a compaction turn is never replayed to another account', () => { + const messages = [ + { role: 'user', content: 'plan the trip' }, + { role: 'assistant', content: 'Here is a plan', provider: 'claude' }, + { role: 'user', content: '/compact', command: 'compact' }, + { role: 'assistant', content: '', provider: 'claude', parts: [{ type: 'compaction', id: 'c', status: 'done', trigger: 'manual' }] }, + { role: 'user', content: 'now book it' }, + ] + const out = renderTranscript(messages) + assert.ok(out.includes('plan the trip') && out.includes('now book it')) + assert.ok(!out.includes('/compact')) + assert.ok(!out.includes('(…)'), 'a skipped compaction is not a gap') + // A reply Claude compacted mid-way, that ran tools and said nothing, still hands its steps over. + const midway = renderTranscript([ + { role: 'user', content: 'fix the build' }, + { role: 'assistant', content: '', status: 'stopped', parts: [{ type: 'compaction', id: 'c', status: 'done', trigger: 'auto' }, { type: 'tool', id: 't', title: 'Ran the tests', status: 'done' }] }, + ], { tools: true }) + assert.ok(midway.includes('Ran the tests')) +}) + +test('latestContext reads the newest reading for that account only', () => { + const ms = [ + { role: 'assistant', provider: 'claude', context: { used: 1 } }, + { role: 'assistant', provider: 'codex', context: { used: 2 } }, + { role: 'assistant', provider: 'claude' }, + ] + assert.equal(latestContext(ms, 'claude').used, 1) + assert.equal(latestContext(ms, 'codex').used, 2) + assert.equal(latestContext(ms, 'cursor'), null) +}) + +test('an idle Claude chat compacts two minutes before its cache expires, and only then', () => { + const now = 1_000_000 + const base = () => ({ + id: 't', kind: 'regular', provider: 'claude', + sessions: { claude: { id: 's', through: 2 } }, + messages: [ + { role: 'user', content: 'go' }, + { role: 'assistant', status: 'done', provider: 'claude', context: { used: COMPACTION_MIN_TOKENS, cacheExpiresAt: now + 600_000, at: now } }, + ], + }) + assert.deepEqual(idleCompactionWindow(base(), { now }), { startMs: now + 600_000 - IDLE_COMPACT_LEAD_MS, endMs: now + 600_000 }) + const no = (patch, opts = {}) => assert.equal(idleCompactionWindow(patch(base()), { now, ...opts }), null) + no((t) => t, { running: true }) + no((t) => ({ ...t, settledOverride: 'settled' })) + no((t) => ({ ...t, snoozedUntil: now + 1 })) + no((t) => ({ ...t, totemId: 'x' })) + no((t) => ({ ...t, kind: 'temporary' })) + no((t) => ({ ...t, queue: [{ id: 'q' }] })) + no((t) => ({ ...t, provider: 'codex' }), { driverOf: (p) => p }) + no((t) => { t.messages[1].context.used = COMPACTION_MIN_TOKENS - 1; return t }) + no((t) => { delete t.messages[1].context.cacheExpiresAt; return t }) + no((t) => { t.messages[1].context.cacheExpiresAt = now - 1; return t }) + no((t) => { t.sessions.claude.through = 1; return t }) + no((t) => { t.messages[0] = { role: 'user', content: '/compact', command: 'compact' }; return t }) + no((t) => { t.messages[1].parts = [{ type: 'questions', status: 'pending' }]; return t }) +}) + +test('Codex compactions are read from every rollout shape, old and new', () => { + assert.ok(codexCompacted({ type: 'compacted', payload: { message: '' } })) + assert.ok(codexCompacted({ type: 'event_msg', payload: { type: 'context_compacted' } })) + assert.ok(codexCompacted({ type: 'event_msg', payload: { type: 'item_completed', item: { type: 'ContextCompaction', id: 'x' } } })) + assert.ok(!codexCompacted({ type: 'event_msg', payload: { type: 'item_completed', item: { type: 'AgentMessage' } } })) + assert.ok(!codexCompacted(CODEX_TOKEN_COUNT)) +}) + +test('a chat\'s summary previews the turn before a compaction, not the compaction', () => { + const s = threadSummary({ + id: 't', + messages: [ + { id: 'u1', role: 'user', content: 'plan the trip', createdAt: 1 }, + { id: 'a1', role: 'assistant', content: 'Here is the plan', status: 'done', createdAt: 2 }, + { id: 'u2', role: 'user', content: '/compact', command: 'compact', createdAt: 3 }, + { id: 'a2', role: 'assistant', content: '', status: 'done', createdAt: 4 }, + ], + }) + assert.deepEqual(s.messages.map((m) => m.id), ['a1', 'u2', 'a2']) + assert.equal(s.messages.find((m) => m.id === 'u2').command, 'compact') +}) + +test('the idle compactor sets one timer per idle chat and looks again when it fires', async () => { + const now = 1_000_000 + const chat = { + id: 't', kind: 'regular', provider: 'claude', updatedAt: now, sessions: { claude: { id: 's', through: 2 } }, + messages: [ + { role: 'user', content: 'go' }, + { role: 'assistant', status: 'done', provider: 'claude', model: 'opus', effort: 'high', context: { used: 300_000, cacheExpiresAt: now + 600_000, at: now } }, + ], + } + const timers = [] + const started = [] + let mode = 'beforeCacheExpires' + let enabled = true + const c = createIdleCompactor({ + threads: { get: async () => structuredClone(chat), list: async () => [chat] }, + isRunning: () => false, + startTurn: async (body, opts) => { started.push({ body, opts }) }, + mode: () => mode, + driverOf: (p) => p, + enabled: async () => enabled, + now: () => now, + setTimer: (fn, ms) => { timers.push({ fn, ms }); return timers.length }, + clearTimer: () => {}, + }) + await c.schedule('t') + assert.equal(timers.length, 1) + assert.equal(timers[0].ms, 600_000 - IDLE_COMPACT_LEAD_MS) + enabled = false + await c.fire('t') + assert.equal(started.length, 0, 'not on an account he switched off') + enabled = true + await c.fire('t') + assert.deepEqual(started[0], { body: { threadId: 't', text: '/compact', provider: 'claude', model: 'opus', effort: 'high', modelSettings: undefined }, opts: { idle: 'beforeCacheExpires' } }) + mode = 'onReturn' + await c.schedule('t') + await c.fire('t') + assert.equal(timers.length, 1, 'no timer unless the setting asks for one') + assert.equal(started.length, 1) +}) diff --git a/chat/store.mjs b/chat/store.mjs index 243b22a..b46c7d9 100644 --- a/chat/store.mjs +++ b/chat/store.mjs @@ -19,6 +19,7 @@ import { logoUrl } from './tools.mjs' import { QUEUE_LIMIT } from './queue.mjs' import { APPROVAL_DECISIONS, APPROVAL_STATUSES } from './approvals.mjs' import { inboxMarker, normalizeInboxPart } from './inbox-outcome.mjs' +import { normalizeCompactionPart, normalizeContextUsage } from './context.mjs' export const validThreadId = (id) => typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id) @@ -46,6 +47,8 @@ export function normalizeAttachment(a) { export function normalizePart(p, i = 0) { if (!p || typeof p !== 'object') return null + // The context was compacted here (chat/context.mjs): a divider in the reply. + if (p.type === 'compaction') return normalizeCompactionPart(p) if (p.type === 'text') return typeof p.text === 'string' ? { type: 'text', text: p.text } : null if (p.type === 'image') return validThreadId(p.uploadId) ? { type: 'image', uploadId: p.uploadId, alt: str(p.alt, 200) } : null // A document the agent made this turn (a snapshot in uploads; `path` is where @@ -197,7 +200,12 @@ export function normalizeMessage(m, i = 0) { for (const k of STAT_KEYS) if (typeof m.stats[k] === 'number' && Number.isFinite(m.stats[k]) && m.stats[k] >= 0) stats[k] = m.stats[k] if (Object.keys(stats).length) out.stats = stats } + // How full the context window was after this reply's last request (chat/context.mjs). + const context = normalizeContextUsage(m.context) + if (context) out.context = context } + // `/compact`: a turn that compacts the session, drawn as a divider, never as a message. + if (m.role === 'user' && m.command === 'compact') out.command = 'compact' // A totem's scheduled run, posted to its chat. if (m.run && typeof m.run === 'object') out.run = { trigger: str(m.run.trigger, 20), status: str(m.run.status, 20), notified: m.run.notified === true } if (m.mode && m.mode !== 'chat') out.mode = str(m.mode, 20) @@ -396,7 +404,7 @@ const pendingParts = (m) => (m.parts || []).filter((p) => SUMMARY_PART_TYPES.has function summaryMessage(m) { const out = { id: m.id, role: m.role, content: m.content.length > SUMMARY_TEXT ? `${m.content.slice(0, SUMMARY_TEXT)}…` : m.content, createdAt: m.createdAt } - for (const k of ['status', 'error', 'provider', 'model', 'run', 'mode', 'voice', 'inbox']) if (m[k] !== undefined) out[k] = m[k] + for (const k of ['status', 'error', 'provider', 'model', 'run', 'mode', 'voice', 'inbox', 'command']) if (m[k] !== undefined) out[k] = m[k] if (m.attachments) out.attachments = m.attachments const parts = pendingParts(m) if (parts.length) out.parts = parts @@ -412,11 +420,17 @@ function summaryMessage(m) { */ export function threadSummary(thread) { const { messages = [], ...rest } = thread - let from = messages.length - while (from > 0 && messages.length - from < SUMMARY_TAIL) { - from-- - if (messages[from].role === 'user') break + const turnStart = (end) => { + let at = end + while (at > 0 && messages.length - at < SUMMARY_TAIL) { + at-- + if (messages[at].role === 'user') break + } + return at } + let from = turnStart(messages.length) + // A compaction turn (`/compact`, chat/context.mjs) previews nothing: the turn before it does. + while (from > 0 && messages[from].command === 'compact' && messages.length - from < SUMMARY_TAIL) from = turnStart(from) // A card from an earlier turn can still wait on the owner (a reply leaves a // proposal open): it comes along as a stub, its parts and no text. const waiting = messages.slice(0, from).filter((m) => pendingParts(m).length) diff --git a/chat/subagents.mjs b/chat/subagents.mjs index f15cc8c..0572081 100644 --- a/chat/subagents.mjs +++ b/chat/subagents.mjs @@ -358,6 +358,23 @@ function dateDirs(root, at) { return [...out] } +// A Codex thread's rollout file anywhere under sessions/YYYY/MM/DD, newest day first. +async function findRollout(root, threadId) { + const names = async (dir) => { try { return (await readdir(dir)).filter((n) => /^\d+$/.test(n)).sort().reverse() } catch { return [] } } + for (const y of await names(root)) { + for (const mo of await names(join(root, y))) { + for (const d of await names(join(root, y, mo))) { + const dir = join(root, y, mo, d) + let files = [] + try { files = await readdir(dir) } catch { continue } + const hit = files.find((f) => f.endsWith(`${threadId}.jsonl`)) + if (hit) return join(dir, hit) + } + } + } + return '' +} + async function listJsonl(dir) { try { return (await readdir(dir)).filter((f) => f.endsWith('.jsonl')).map((f) => join(dir, f)) } catch { return [] } } @@ -412,10 +429,11 @@ export function sessionRoots(provider, env = process.env) { /** * Find and tail the session log of an agent started at `startedAt` with * `prompt` (or, for a Codex sub-agent, known by `threadId`). Each new record is - * parsed into steps for `onStep` and facts for `onPatch`. `stop()` reads what is + * parsed into steps for `onStep` and facts for `onPatch`, and handed raw to + * `onRecord`; `fromEnd` skips what the file already held when it was found. `stop()` reads what is * left and stops; it resolves to whether a log was ever found. */ -export function watchSessionLog({ provider, prompt = '', threadId = '', startedAt = Date.now(), env = process.env, onStep, onPatch, log = () => {} }) { +export function watchSessionLog({ provider, prompt = '', threadId = '', startedAt = Date.now(), env = process.env, onStep, onPatch, onRecord, fromEnd = false, log = () => {} }) { const roots = sessionRoots(provider, env) const parse = provider === 'codex' ? codexRolloutSteps : claudeRecordSteps const match = provider === 'codex' ? codexMatch : claudeMatch @@ -427,9 +445,13 @@ export function watchSessionLog({ provider, prompt = '', threadId = '', startedA let stopped = false let timer = null let busy = Promise.resolve() + let deepSearched = false const emitRecords = (records) => { for (const r of records) { + // The raw record too, for a reader of its own (the chat's context meter, chat/context.mjs). + if (onRecord) { try { onRecord(r) } catch (e) { log('session log record handler failed', e?.message || e) } } + if (!onStep && !onPatch) continue const { steps, patch } = parse(r) if (Object.keys(patch).length) onPatch?.(patch) for (const s of steps) onStep?.(s) @@ -439,7 +461,13 @@ export function watchSessionLog({ provider, prompt = '', threadId = '', startedA async function candidates() { if (provider === 'codex') { const files = (await Promise.all(roots.flatMap((r) => dateDirs(r, startedAt)).map(listJsonl))).flat() - return threadId ? files.filter((f) => f.endsWith(`${threadId}.jsonl`)) : files + if (!threadId) return files + const mine = files.filter((f) => f.endsWith(`${threadId}.jsonl`)) + // A resumed thread keeps writing the file it began in, which may be weeks old. + // Searched once: a file that is not there now only ever appears under today. + if (mine.length || deepSearched) return mine + deepSearched = true + return (await Promise.all(roots.map((r) => findRollout(r, threadId)))).filter(Boolean) } // Claude: a project folder gains a file when a session starts in it. const out = [] @@ -487,6 +515,14 @@ export function watchSessionLog({ provider, prompt = '', threadId = '', startedA busy = busy.then(async () => { if (!file) { file = await find() + // A resumed session's file holds every earlier turn: only what comes now is wanted. + if (file && fromEnd) { + // From the start of the line being written, if the end falls mid-line. + const size = (await stat(file).catch(() => null))?.size || 0 + const end = size ? await readSlice(file, Math.max(0, size - 65536), Math.min(size, 65536)) : null + const cut = end ? end.lastIndexOf(10) : -1 + offset = cut >= 0 ? size - end.length + cut + 1 : size + } if (file) { onPatch?.({ log: 'live' }); log(`subagent: tailing ${provider} log ${file}`) } } if (file) await tail() diff --git a/chat/subagents.test.mjs b/chat/subagents.test.mjs index c39ad48..67da501 100644 --- a/chat/subagents.test.mjs +++ b/chat/subagents.test.mjs @@ -178,3 +178,25 @@ test('createCliAgentWatch opens an agent on a delegating command and settles it assert.ok(events.some((e) => e.agent?.log === 'none')) } finally { await home.done() } }) + +test('watchSessionLog fromEnd skips a resumed rollout\'s earlier turns, not a line half-written', async () => { + const home = await tempHome() + try { + // A resumed thread's rollout from weeks ago: found anywhere under sessions/. + const dayDir = join(home.dir, 'sessions', '2026', '01', '02') + await mkdir(dayDir, { recursive: true }) + const file = join(dayDir, 'rollout-2026-01-02T10-00-00-thread-9.jsonl') + const old = { type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { total_tokens: 1 } } } } + const now = { type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { total_tokens: 2 } } } } + const next = { type: 'event_msg', payload: { type: 'token_count', info: { last_token_usage: { total_tokens: 3 } } } } + const half = line(now) + // An earlier turn, then this turn's record caught half-written when the file is found. + await writeFile(file, line({ type: 'session_meta', payload: { id: 'thread-9' } }) + line(old) + half.slice(0, 20)) + const seen = [] + const w = watchSessionLog({ provider: 'codex', threadId: 'thread-9', env: { CODEX_HOME: home.dir }, fromEnd: true, onRecord: (r) => seen.push(r) }) + await new Promise((r) => setTimeout(r, 300)) + await appendFile(file, half.slice(20) + line(next)) + await w.stop() + assert.deepEqual(seen.map((r) => r.payload.info.last_token_usage.total_tokens), [2, 3]) + } finally { await home.done() } +}) diff --git a/chat/turn.mjs b/chat/turn.mjs index b940943..11b9d9f 100644 --- a/chat/turn.mjs +++ b/chat/turn.mjs @@ -79,6 +79,11 @@ function transcriptLine(m, { tools }) { */ export function renderTranscript(messages, { budget = 16_000, heading = 'Conversation so far:', tools = false, keepFirst = false, omitted = null } = {}) { if (!Array.isArray(messages) || !messages.length) return '' + // A `/compact` turn (the command and the reply to it) is housekeeping on one + // account's session: nothing another agent needs. A reply Claude compacted + // mid-way is not one, and keeps its steps. + messages = messages.filter((m, i) => m?.command !== 'compact' && !(m?.role === 'assistant' && messages[i - 1]?.command === 'compact')) + if (!messages.length) return '' const all = messages.map((m) => transcriptLine(m, { tools })) const firstUser = keepFirst ? messages.findIndex((m, i) => m?.role === 'user' && all[i]) : -1 const first = firstUser >= 0 && all[firstUser].length <= budget / 4 ? firstUser : -1 @@ -292,6 +297,21 @@ export function applyEvent(msg, event, now = Date.now()) { msg.parts.push({ type: 'visual', id: v.id, uploadId: v.uploadId, title: v.title || 'Chart', height: v.height || 320 }) break } + case 'context': { + // How full the context window is now (chat/context.mjs): the newest reading wins. + if (event.context && typeof event.context.used === 'number') msg.context = { ...event.context } + break + } + case 'compaction': { + // The session was (or is being) compacted (chat/context.mjs): a divider, + // added where it began and settled in place by id. + const c = event.compaction || {} + if (!c.id) break + const existing = msg.parts.find((p) => p.type === 'compaction' && p.id === c.id) + if (existing) Object.assign(existing, c) + else msg.parts.push({ type: 'compaction', status: 'running', trigger: 'auto', startedAt: now, ...c }) + break + } case 'steer': { // The owner's words mid-reply, kept where they landed among the steps. const st = event.steer || {} @@ -319,6 +339,8 @@ export function finalizeMessage(msg, { status, error, finalText, startedAt, now if (p.type === 'tool' && p.status === 'running') { p.status = status === 'error' ? 'error' : 'done'; p.endedAt = now } // The process that asked is gone, so nothing can answer it now. if (p.type === 'approval' && p.status === 'pending') { p.status = 'expired'; p.decidedAt = now } + // A compaction the run never closed: cut short by Stop, or the CLI died mid-way. + if (p.type === 'compaction' && p.status === 'running') { p.status = status === 'stopped' ? 'stopped' : 'failed'; p.endedAt = now } if (p.type === 'tool' && p.agent?.status === 'running') { p.agent = { ...p.agent, status: status === 'error' ? 'error' : status === 'stopped' ? 'stopped' : 'done', endedAt: now } for (const st of p.agent.steps || []) if (st.status === 'running') st.status = 'done' diff --git a/docs/chat.md b/docs/chat.md index 28941e6..11c9c5a 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -155,6 +155,8 @@ Every event has a `seq`. Viewers replay with `since`. | `visual` | `visual: {id, uploadId, title, height, url}` | The agent showed a chart with `html_render` (a `visual` part, added where it was called, once per id). `url` is signed for viewers and not saved. See Charts in replies. | | `activity` | `text` | The current step, one line. Not persisted. | | `browser` | `tabId`, `url`, `title`, `image` (JPEG data URL), `at` | What the chat's browser shows after a page change. Not persisted; `GET /api/chat/browser?threadId=` returns the latest. | +| `context` | `context: {used, max?, input?, cached?, output?, autoCompactAt?, cacheTtlMs?, cacheExpiresAt?, at}` | How full the context window is after the newest request (Context window and compaction). Kept on the reply as `context`. | +| `compaction` | `compaction: {id, status, trigger, before?, after?, reason?, startedAt?, endedAt?}` | The session was or is being compacted (a `compaction` part, added where it began, settled in place by id). | | `title` | `title`, `icon?` | The AI title (and icon) for a new chat. | | `done` | `message` | The settled assistant message. | | `error` | `text` | The run threw. | @@ -189,6 +191,9 @@ Every event has a `seq`. Viewers replay with `since`. URLs are never stored; `signThread` adds them on the way out. +`context` on a reply is how full the window was after its last request, and a user message with +`command: 'compact'` is a `/compact` turn (Context window and compaction). + `stats` is what the agent CLI reported for the reply, read from its stream by `chat/stats.mjs` (Claude's and Cursor's `result` event, Codex's `turn.completed`, OpenCode's `step_finish`) and summed across a steered or retried run. `input` counts every prompt token, `cached` the part read from @@ -240,6 +245,59 @@ new account. Once another account is picked, a "Handoff with your next message" the composer until that message is sent. Switching while a reply runs leaves that reply on its account; the switch applies to the next message. +## Context window and compaction + +Ported from T3 Code (its context row and Compact idle threads), in `chat/context.mjs` on the +bridge and `web/src/chat/context.ts` (copied byte for byte to `mobile/src/lib/chat/context.ts`). + +**The meter.** After the composer's plus, a thin bar and "45k / 1m" (`ContextMeter.tsx`): amber +from 80%, red from 90%, a tick where Claude compacts when its window is set below the model's; +hover, focus or tap for "Context: 64% used", the exact tokens and "Compacts automatically at +about N tokens." (else "Context compacts automatically when needed."). It reads the newest +`context` of a reply on the account the composer would send on, so after a switch it shows that +account's session, and nothing before the first reading. Fill is the last request's prompt plus +its output, never the reply's billed `stats`: + +| CLI | Read from | Window | +|---|---|---| +| Claude | each top-level `assistant` event's `message.usage` (input + cache creation + cache read + output), live | T3's catalog (`claudeContextWindow`), else `result.modelUsage[model].contextWindow` | +| Codex | the session's rollout file (`token_count`: `last_token_usage.total_tokens`), tailed from where it ended while the turn runs; `codex exec --json` does not carry it | `model_context_window` | +| OpenCode | the last `step_finish` (input + cache + output) | unknown: tokens only | +| Cursor | not reported | no meter | + +**Compaction** is the CLI's own: Claude Code and Codex compact a full session themselves. Totem +shows it where it happened ("Context compacted 967k → 412k tokens", `CompactionMark.tsx`; Claude's +`status: compacting` and `compact_boundary`, Codex's `compacted` record or the older +`context_compacted`), and the meter drops to +what is left. On top of that, as T3 does: + +- **`/compact`** as the message (optionally with instructions, no attachments) resumes the + chat's Claude session with `/compact`. The turn is only its divider: the `/compact` message is + hidden (`command: 'compact'`), it sets no "waiting on you", sends no push, is never replayed to + another account (`renderTranscript`), and keeps the session's `through` when other accounts + answered in between. Other accounts get T3's "This provider does not support /compact. Start a + new thread to continue with a fresh context." (Codex compacts only through its app server, + which Totem does not run.) A message sent while it runs is queued, never steered. +- **Settings → Chat › Compact idle threads** (`compactIdle`), for Claude chats of 200k tokens + or more whose prompt cache has gone cold (1 h or 5 min from the request, as Claude reported; + 70 min when it did not): + - *When you return* (default): the composer shows a Compact chip with the tokens; sending + posts `compactFirst`, and the bridge puts the message at the front of the queue and runs a + `/compact` first (it goes even if the compaction fails, but not if it is stopped). Keep + sends as is, for that send. + - *Before the cache expires (beta)*: two minutes before the cache expires, the bridge sends the + idle chat `/compact` itself (`scheduleIdleCompaction`, after every run ends), not if the chat + is settled, snoozed, temporary, a totem's, has a queue or something pending, or its last turn + was a compaction (`chat/compaction.mjs`; checked again when it fires, and skipped if the + chat's account was switched off). Timers are in memory; a restart loses them and the chip + takes over. It leaves the chat's order, unread state and snooze alone, and a message he + sends meanwhile waits in the queue behind it. + - *Never*. +- **Settings → Chat › Auto-compact after** (`autoCompactWindow`): empty, or 100,000–1,000,000, + passed to Claude as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`. The meter's tick is that less 33,000 + (`CLAUDE_AUTO_COMPACT_RESERVE_TOKENS`); with none set, the account's own `settings.json` or + environment is read the way T3 reads it, and compaction switched off there means no tick. + ## Steering Copied from T3 Code: a message sent while a reply is running either steers it diff --git a/mobile/src/features/chat/ChatScreen.tsx b/mobile/src/features/chat/ChatScreen.tsx index d494751..8d3276c 100644 --- a/mobile/src/features/chat/ChatScreen.tsx +++ b/mobile/src/features/chat/ChatScreen.tsx @@ -40,6 +40,8 @@ import { pendingQuestions } from '../../lib/chat/questions' import { DECLINE_PLACEHOLDER, pendingApproval } from '../../lib/chat/approvals' import { ModelChip } from './ModelPicker' import HandoffMark from './HandoffMark' +import ContextMeter, { CompactChip } from './ContextMeter' +import { compactBeforeSendTokens, contextSnapshot, isCompactionTurn, latestContext } from '../../lib/chat/context' import { providerSwitches } from '../../lib/chat/handoff' import { AccessControl, ThinkingControl, hintFor } from './controls' import UsageChips from './UsageChips' @@ -201,6 +203,18 @@ export default function ChatScreen() { const messages = waiting ? NO_MESSAGES : active?.messages || NO_MESSAGES const empty = !waiting && messages.length === 0 const input = drafts[draftKey] || '' + // Compact idle threads → When you return (lib/chat/context.ts, web ChatView): an + // idle Claude chat whose prompt cache went cold offers to compact before the + // next send. Keep is per send. + const compactIdle = useChat((s) => s.prefs.compactIdle) + const [keepHistory, setKeepHistory] = useState(false) + useEffect(() => { setKeepHistory(false) }, [activeId]) + const compactTokens = active && !waiting ? compactBeforeSendTokens({ + thread: active, provider: choice.provider, claude: providerById(choice.provider)?.driver === 'claude', + setting: compactIdle, text: input, idle: !busy, now: Date.now(), + }) : null + // How full this chat's context is on the account it would send on. + const contextShown = active && !empty ? contextSnapshot(latestContext(messages, choice.provider)) : null useEffect(() => { ensureModels(choice.provider) }, [choice.provider]) // A chat in the list that was opened before its summary arrived: read its window now. useEffect(() => { if (activeId && active && !isLoaded(active) && !page) void loadThread(activeId) }, [activeId, !!active, active && isLoaded(active), !!page]) // eslint-disable-line react-hooks/exhaustive-deps @@ -275,7 +289,8 @@ export default function ChatScreen() { // Every run may use the browser, computer use and the long task budget; the // agent decides, so the app sends neither a mode switch nor a browser flag. function onSend({ text, attachments, mode }: { text: string; attachments: Attachment[]; mode: ChatMode }) { - const id = send({ threadId: activeId, text, attachments, mode, kind, provider: draft.provider, modelSettings: draft.modelSettings, projectId: active ? undefined : project?.id, projectContextOff: !active && !!project && draftContextOff }) + const id = send({ threadId: activeId, text, attachments, mode, kind, provider: draft.provider, modelSettings: draft.modelSettings, projectId: active ? undefined : project?.id, projectContextOff: !active && !!project && draftContextOff, compactFirst: compactTokens != null && !keepHistory }) + setKeepHistory(false) setInput('') if (id !== activeId) { setDraftPick(null) @@ -350,7 +365,9 @@ export default function ChatScreen() { return ok } const onQueue = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : activeId ? queueMessage(activeId, p.text, p.attachments) : false) - const onSteerNow = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : activeId ? steer(activeId, p.text, p.attachments.map((a) => a.id)) : false) + // A `/compact` running cannot take words mid-way: they wait behind it (T3). + const compactingNow = busy && isCompactionTurn(messages[messages.length - 2]) + const onSteerNow = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : !activeId ? false : compactingNow ? queueMessage(activeId, p.text, p.attachments) : steer(activeId, p.text, p.attachments.map((a) => a.id))) const saveQueueEdit = async (p: FollowUpPayload) => { if (!queueEdit) return false const ok = await updateQueue(queueEdit.threadId, { action: 'edit', id: queueEdit.id, text: p.text, attachments: p.attachments.map((a) => a.id) }) @@ -462,6 +479,9 @@ export default function ChatScreen() { const renderItem = (m: ChatMessage, i: number) => { const last = i === messages.length - 1 const moved = switches.get(m.id) + // `/compact` (lib/chat/context.ts): its reply's divider stands for the whole turn. + if (isCompactionTurn(m) && !m.unsent) return moved ? : <> + const compaction = isCompactionTurn(messages[i - 1]) return ( <> {moved ? : null} @@ -483,7 +503,7 @@ export default function ChatScreen() { provider={providerById(m.provider || choice.provider) || providers.find((p) => p.driver === m.provider)} modelName={modelNameFor(m.provider, m.model)} isLast={m.id === lastAssistantId && last} - onRegenerate={!busy && active ? () => regenerate(active.id) : undefined} + onRegenerate={!busy && active && !compaction ? () => regenerate(active.id) : undefined} flash={landed === m.id} /> )} @@ -695,13 +715,22 @@ export default function ChatScreen() { placeholder={waitingApproval ? DECLINE_PLACEHOLDER : temporary ? 'Temporary chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} allowCommands={!temporary} maxUploadBytes={caps?.maxUploadBytes} + compacting={compactTokens != null && !keepHistory} + rightSlot={questionFlow?.answering || queueEdit ? null : ( + <> + {/* A phone's footer holds one of them beside the model: the chip names the tokens itself. */} + {contextShown && (compactTokens == null || busy) ? : null} + {compactTokens != null && !busy ? setKeepHistory((k) => !k)} /> : null} + + )} leftSlot={ <> {/* Answering questions: effort and access make way for the answer buttons. */} {questionFlow?.answering ? null : ( <> - {effortEl} + {/* The meter or the Compact chip takes its room, so the model keeps its name; effort is in the model picker too. */} + {contextShown || (compactTokens != null && !busy) ? null : effortEl} changeModel({ provider: choice.provider, modelSettings: { ...choice.settings, access: v } })} /> )} diff --git a/mobile/src/features/chat/CompactionMark.tsx b/mobile/src/features/chat/CompactionMark.tsx new file mode 100644 index 0000000..350ec4b --- /dev/null +++ b/mobile/src/features/chat/CompactionMark.tsx @@ -0,0 +1,57 @@ +import React, { useEffect } from 'react' +import { StyleSheet, View } from 'react-native' +import Animated, { cancelAnimation, useAnimatedStyle, useReducedMotion, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated' +import { compactionLabel } from '../../lib/chat/context' +import type { CompactionPart } from '../../lib/chat/types' +import { colors } from '../../theme' +import { T } from '../../ui/Text' +import { TI, vc } from './ui' +import { IconAlertCircle, IconArrowRight, IconArrowsDiagonalMinimize2 } from './icons' + +// Where the context was compacted (T3 Code's timeline divider): a rule across the +// log, "Context compacted 412k → 38k tokens", pulsing while it runs and red if it +// failed. The web's web/src/chat/CompactionMark.tsx. +export default function CompactionMark({ p }: { p: CompactionPart }) { + const l = compactionLabel(p) + const reduced = useReducedMotion() + const pulse = useSharedValue(1) + useEffect(() => { + if (l.active && !reduced) pulse.value = withRepeat(withTiming(0.45, { duration: 900 }), -1, true) + else { cancelAnimation(pulse); pulse.value = 1 } + }, [l.active, reduced, pulse]) + const fade = useAnimatedStyle(() => ({ opacity: pulse.value })) + const color = l.failed ? colors.red : vc.faint + const label = l.tokens ? `${l.text} ${l.tokens.before} → ${l.tokens.after} tokens` : l.text + const mark = ( + + + + + {l.tokens ? ( + <> + {l.text} {l.tokens.before} + + {l.tokens.after} tokens + + ) : {l.text}} + + + + ) + // A phone has no room for the reason beside the label: it goes under it. + return p.reason ? ( + + {mark} + {/* Read once, in the divider's own label. */} + {p.reason} + + ) : mark +} + +const st = StyleSheet.create({ + row: { flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 6 }, + rule: { flex: 1, height: StyleSheet.hairlineWidth, backgroundColor: vc.line }, + ruleFailed: { backgroundColor: colors.red, opacity: 0.3 }, + label: { flexDirection: 'row', alignItems: 'center', gap: 4, flexShrink: 1, maxWidth: '85%' }, + reason: { textAlign: 'center', opacity: 0.8, marginTop: -2, marginBottom: 4, paddingHorizontal: 24 }, +}) diff --git a/mobile/src/features/chat/Composer.tsx b/mobile/src/features/chat/Composer.tsx index 4f378d2..18181a2 100644 --- a/mobile/src/features/chat/Composer.tsx +++ b/mobile/src/features/chat/Composer.tsx @@ -78,6 +78,10 @@ export interface ComposerProps { allowCommands?: boolean maxUploadBytes?: number leftSlot?: React.ReactNode + /** Before the mic: how full the context is and the Compact chip (ContextMeter.tsx). */ + rightSlot?: React.ReactNode + /** The next send compacts the idle chat first (T3's Compact idle threads): Send says so. */ + compacting?: boolean /** Tells the chat the box grew, so the list keeps its last message above it. */ onFocus?: () => void /** The agent's questions are open (QuestionsPanel.tsx): the box is the typed answer. */ @@ -106,7 +110,7 @@ function rankCommands(catalog: ChatCommand[], prefix: string, term: string, alon } const Composer = forwardRef(function Composer(props, ref) { - const { value, onChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, above, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, leftSlot, onFocus, answering } = props + const { value, onChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, above, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, leftSlot, rightSlot, compacting, onFocus, answering } = props const input = useRef(null) const { height } = useWindowDimensions() const [drafts, setDrafts] = useState([]) @@ -411,6 +415,7 @@ const Composer = forwardRef(function Composer(pro ) : ( <> + {rightSlot} {!busy || followUps ? ( { tap(); dictation.start() }} accessibilityLabel="Dictate"> @@ -444,7 +449,7 @@ const Composer = forwardRef(function Composer(pro ) : showVoice ? ( { impact(); onVoice!() }} accessibilityLabel="Start voice"> ) : ( - + {uploading ? : } )} @@ -488,7 +493,7 @@ const st = StyleSheet.create({ recDot: { width: 12, height: 12, borderRadius: 6, backgroundColor: colors.red, shadowColor: colors.red, shadowOpacity: 0.4, shadowRadius: 4 }, bar: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 4, marginTop: 4 }, left: { flexDirection: 'row', alignItems: 'center', gap: 2, flexShrink: 1, minWidth: 0 }, - right: { flexDirection: 'row', alignItems: 'center', gap: 2, flexShrink: 1, minWidth: 0, justifyContent: 'flex-end' }, + right: { flexDirection: 'row', alignItems: 'center', gap: 2, flexShrink: 0, justifyContent: 'flex-end' }, iconBtn: { flexShrink: 0, width: 36, height: 36, borderRadius: 10, alignItems: 'center', justifyContent: 'center' }, send: { flexShrink: 0, width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.text }, sendOff: { backgroundColor: '#3a3f4d' }, diff --git a/mobile/src/features/chat/ContextMeter.tsx b/mobile/src/features/chat/ContextMeter.tsx new file mode 100644 index 0000000..73fad88 --- /dev/null +++ b/mobile/src/features/chat/ContextMeter.tsx @@ -0,0 +1,66 @@ +import React from 'react' +import { Alert, StyleSheet, View } from 'react-native' +import { contextLabel, contextTooltip, contextValue, formatContextTokens, type ContextSnapshot } from '../../lib/chat/context' +import { colors } from '../../theme' +import { T } from '../../ui/Text' +import { Press } from '../../ui/kit' +import { tap } from '../../ui/haptics' +import { TI, vc } from './ui' +import { IconArrowsDiagonal, IconArrowsDiagonalMinimize2 } from './icons' + +// How full the chat's context window is (web chat/ContextMeter.tsx, after T3 +// Code's context row): a thin bar in the composer's footer, amber from 80% and +// red from 90%, with a tick where Claude compacts when that is set below the +// window. A tap shows the numbers; with no window known, the tokens stand alone. +export default function ContextMeter({ s }: { s: ContextSnapshot }) { + const tick = s.max && s.autoCompactAt ? (s.autoCompactAt / s.max) * 100 : null + const fill = s.tone === 'error' ? colors.red : s.tone === 'warning' ? colors.amber : vc.soft + return ( + { tap(); const [head, ...rest] = contextTooltip(s); Alert.alert(head, rest.join('\n'), undefined, { userInterfaceStyle: 'dark' }) }} + accessibilityRole="button" + accessibilityLabel={`Context: ${contextLabel(s)}`} + hitSlop={4} + > + {s.percent != null ? ( + + + {tick != null ? : null} + + ) : null} + {/* The phone's footer already holds the model, effort and access: the numbers are a tap away. */} + {s.percent == null ? {contextValue(s)} : null} + + ) +} + +/** + * T3's Compact chip by Send: the next send compacts the idle chat first + * (pressed), or keeps the full history. A phone shows the glyph and the tokens. + */ +export function CompactChip({ tokens, keep, onToggle }: { tokens: number; keep: boolean; onToggle: () => void }) { + const n = formatContextTokens(tokens) + return ( + { tap(); onToggle() }} + accessibilityRole="button" + accessibilityState={{ selected: !keep }} + accessibilityLabel={`Compact ${n} tokens of history before sending`} + accessibilityHint={keep ? `Next send keeps all ${n} tokens. Tap to compact first.` : `Next send compacts ${n} tokens first. Tap to keep full history.`} + > + + {keep ? `Keep ${n}` : n} + + ) +} + +const st = StyleSheet.create({ + chip: { flexShrink: 0, flexDirection: 'row', alignItems: 'center', gap: 6, height: 36, paddingHorizontal: 8 }, + track: { width: 32, height: 3, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.14)' }, + fill: { position: 'absolute', left: 0, top: 0, bottom: 0, borderRadius: 2 }, + tick: { position: 'absolute', top: -3, width: StyleSheet.hairlineWidth * 2, height: 9, backgroundColor: vc.soft }, + value: { fontVariant: ['tabular-nums'] }, + compact: { flexShrink: 0, flexDirection: 'row', alignItems: 'center', gap: 3, height: 32, paddingHorizontal: 6, borderRadius: 9 }, +}) diff --git a/mobile/src/features/chat/Message.tsx b/mobile/src/features/chat/Message.tsx index a96e9d9..22f2cc9 100644 --- a/mobile/src/features/chat/Message.tsx +++ b/mobile/src/features/chat/Message.tsx @@ -26,7 +26,7 @@ import { useSmoothText } from '../../lib/chat/smooth' import { useTextTicks } from '../../lib/chat/ticks' import { POWER_NAMES } from '../../lib/chat/models' import { splitMentions } from '../../lib/chat/mentions' -import type { Attachment, ChangePart, ChatMessage, Part, ProviderRow, QuestionsPart, SteerPart, ToolPart, ApprovalPart, InboxPart, VisualPart } from '../../lib/chat/types' +import type { Attachment, ChangePart, ChatMessage, CompactionPart, Part, ProviderRow, QuestionsPart, SteerPart, ToolPart, ApprovalPart, InboxPart, VisualPart } from '../../lib/chat/types' import { getChatCommands, subscribeChatCommands } from '../../lib/studio' import WorkLog from './WorkLog' import { foldWork } from './workFold' @@ -35,6 +35,7 @@ import TurnStats, { TurnChip } from './TurnStats' import TotemProposal from './TotemProposal' import ChangeCard from './ChangeCard' import VisualCard from './VisualCard' +import CompactionMark from './CompactionMark' import { QuestionsRecord } from './QuestionsPanel' import ApprovalRow from './ApprovalRow' import InboxCardRow from './InboxCardRow' @@ -328,6 +329,7 @@ type Block = | { kind: 'approval'; part: ApprovalPart; key: string } | { kind: 'inbox'; part: InboxPart; key: string } | { kind: 'visual'; part: VisualPart; key: string } + | { kind: 'compaction'; part: CompactionPart; key: string } // A totem proposal arrives as a fenced block while streaming; the bridge turns it // into a card when the reply settles. Until then, don't show the raw JSON. @@ -367,7 +369,9 @@ function blocks(parts: Part[]): Block[] { else if (p.type === 'change-pr') out.push({ kind: 'change', part: p, key: `c${i}` }) else if (p.type === 'visual') out.push({ kind: 'visual', part: p, key: `v${i}` }) else if (p.type === 'steer') out.push({ kind: 'steer', part: p, key: `s${i}` }) - else if (p.text) { + // The context was compacted here: a divider, never folded into the steps. + else if (p.type === 'compaction') out.push({ kind: 'compaction', part: p, key: `cm${i}` }) + else if (p.type === 'text' && p.text) { const last = out[out.length - 1] // Two text parts with no tool between them are one paragraph run. if (last?.kind === 'text') last.text += p.text @@ -497,7 +501,8 @@ export const AssistantMessage = React.memo(function AssistantMessage({ m, live, // the working line too, so a live reply never looks stalled. const asking = !!m.parts?.some((p) => (p.type === 'questions' || p.type === 'approval') && p.status === 'pending') const approving = !!m.parts?.some((p) => p.type === 'approval' && p.status === 'pending') - const toolRunning = !asking && !!m.parts?.some((p) => p.type === 'tool' && p.status === 'running') + // A running compaction pulses in its own divider (CompactionMark.tsx). + const toolRunning = !asking && !!m.parts?.some((p) => (p.type === 'tool' || p.type === 'compaction') && p.status === 'running') const quiet = useQuiet(live, `${m.content.length}:${m.parts?.length || 0}`) const secs = m.durationMs && m.durationMs > 2000 ? formatDuration(m.durationMs) : null const lane = m.power ? [POWER_NAMES[String(m.power)], m.route === 'thinking' && secs ? `thought for ${secs}` : null].filter(Boolean).join(', ') @@ -521,6 +526,7 @@ export const AssistantMessage = React.memo(function AssistantMessage({ m, live, if (b.kind === 'proposal') return if (b.kind === 'change') return if (b.kind === 'visual') return + if (b.kind === 'compaction') return if (b.kind === 'steer') return if (b.kind === 'totem') return if (b.kind === 'questions') return @@ -546,7 +552,8 @@ export const AssistantMessage = React.memo(function AssistantMessage({ m, live, ) : null} ) : null} - {m.status === 'stopped' ? Stopped : null} + {/* A stopped compaction says so in its own divider. */} + {m.status === 'stopped' && !m.parts?.some((p) => p.type === 'compaction' && p.status === 'stopped') ? Stopped : null} ) diff --git a/mobile/src/features/chat/RunningChats.tsx b/mobile/src/features/chat/RunningChats.tsx index 99602c6..6013cb7 100644 --- a/mobile/src/features/chat/RunningChats.tsx +++ b/mobile/src/features/chat/RunningChats.tsx @@ -29,6 +29,7 @@ import { impact, tap } from '../../ui/haptics' import { ThreadIcon, ProjectIcon } from './ThreadIcon' import { TI, vc } from './ui' import { IconPlayerStopFilled, IconClock, IconCheck, IconMailOpened, IconChevronDown, IconHome } from './icons' +import { isCompactionTurn } from '../../lib/chat/context' /** Wait this long before a chat joins, so a run that ends at once doesn't flash in. */ const JOIN_DELAY_MS = 500 @@ -150,6 +151,8 @@ export default function RunningChats({ onOpenChat }: { onOpenChat?: (id: string) const t = getState().threads.find((x) => x.id === id) const last = t?.messages[t.messages.length - 1] if (!t || t.totemId || last?.role !== 'assistant' || (last.status !== 'done' && last.status !== 'error')) continue + // A compaction (`/compact`) is housekeeping, not news. + if (isCompactionTurn(t.messages[t.messages.length - 2])) continue if (getOnScreen().open.has(id)) continue const failed = last.status === 'error' const place = placeOf(t, getState().projects) diff --git a/mobile/src/features/chat/workFold.ts b/mobile/src/features/chat/workFold.ts index b8987ad..0762fc7 100644 --- a/mobile/src/features/chat/workFold.ts +++ b/mobile/src/features/chat/workFold.ts @@ -55,7 +55,8 @@ export function foldWork(list: B[], set list.forEach((b, i) => { const folds = i <= last && (b.kind === 'tools' || (b.kind === 'text' && isCommentary((b as unknown as { text: string }).text))) if (!folds) { - if (b.kind === 'text') close() + // Text, or a compaction divider, ends the run of steps before it. + if (b.kind === 'text' || b.kind === 'compaction') close() out.push(b) return } diff --git a/mobile/src/features/settings/panes/ChatPane.tsx b/mobile/src/features/settings/panes/ChatPane.tsx index 8cb1fc5..834252d 100644 --- a/mobile/src/features/settings/panes/ChatPane.tsx +++ b/mobile/src/features/settings/panes/ChatPane.tsx @@ -2,13 +2,13 @@ // chats settle, whether chats bring in totems, and who writes chat titles ("Pick // for me" keeps Totem's own rule). The chat's colour glow is a device setting, // under Appearance. -import React, { useEffect } from 'react' +import React, { useEffect, useState } from 'react' import { useChat, ensureModels, savePrefs, providerById, type ChatPrefs } from '../../../lib/chat/store' import { visibleModels, EFFORT_LABELS } from '../../../lib/chat/models' import { pushError } from '../../../lib/toast' import { T } from '../../../ui/Text' import { openPane } from '../open' -import { Link, Picker, Row, Section, Switch } from '../ui' +import { Field, Link, Picker, Row, Section, Switch } from '../ui' function Lane({ lane, title, hint }: { lane: 'titles'; title: string; hint: string }) { const prefs = useChat((s) => s.prefs) @@ -74,6 +74,33 @@ function Lane({ lane, title, hint }: { lane: 'titles'; title: string; hint: stri ) } +const shown = (v: string) => (v ? Number(v).toLocaleString('en-US') : '') + +/** Claude's auto-compact window: empty, or 100,000–1,000,000 (chat/context.mjs on the bridge). */ +function AutoCompactRow({ value, onSave }: { value: string; onSave: (v: string) => void }) { + const [text, setText] = useState(shown(value)) + useEffect(() => { setText(shown(value)) }, [value]) + const commit = () => { + const v = text.replace(/[,_\s]/g, '') + if (v === value) return + if (v && !/^(?:[1-9]\d{5}|1000000)$/.test(v)) { + pushError('Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude’s default.') + setText(shown(value)) + return + } + onSave(v) + } + return ( + } + /> + ) +} + export default function ChatPane() { const prefs = useChat((s) => s.prefs) const providers = useChat((s) => s.providers) @@ -105,6 +132,30 @@ export default function ChatPane() { /> +
Long chats fill the model’s context window; the bar in the message box shows how full it is. Claude and Codex compact a full chat on their own; in a Claude chat, /compact does it now.} + > + save({ compactIdle: v as ChatPrefs['compactIdle'] })} + options={[ + { value: 'onReturn', label: 'When you return' }, + { value: 'beforeCacheExpires', label: 'Before the cache expires (beta)' }, + { value: 'off', label: 'Never' }, + ]} + /> + } + /> + save({ autoCompactWindow: v })} /> +
+
= 0; i--) { + const m = messages[i] + if (m.role !== 'assistant' || (provider && m.provider !== provider)) continue + if (m.context && typeof m.context.used === 'number') return m.context + } + return null +} + +export function contextSnapshot(usage: ContextUsage | null | undefined): ContextSnapshot | null { + if (!usage || !Number.isFinite(usage.used)) return null + const used = Math.max(0, usage.used) + const max = usage.max && usage.max > 0 ? usage.max : null + const percent = max ? Math.round(Math.min(100, Math.max(0, (used / max) * 100))) : null + const autoCompactAt = usage.autoCompactAt && usage.autoCompactAt > 0 && (!max || usage.autoCompactAt < max) ? usage.autoCompactAt : null + const tone = percent == null ? null : percent >= 90 ? 'error' : percent >= 80 ? 'warning' : null + return { used, max, percent, autoCompactAt, tone, at: usage.at || 0 } +} + +/** The meter's value: "45k / 1m", or the tokens alone when the window is unknown. */ +export const contextValue = (s: ContextSnapshot) => (s.max ? `${formatContextTokens(s.used)} / ${formatContextTokens(s.max)}` : formatContextTokens(s.used)) + +/** The meter's accessible name. */ +export const contextLabel = (s: ContextSnapshot) => (s.percent != null ? `${s.percent}% used` : `${formatContextTokens(s.used)} tokens used`) + +/** T3's formatContextWindowCompactionMessage. */ +export function compactionMessage(autoCompactAt: number | null | undefined): string { + return autoCompactAt && autoCompactAt > 0 + ? `Compacts automatically at about ${autoCompactAt.toLocaleString('en-US')} tokens.` + : 'Context compacts automatically when needed.' +} + +/** The meter's tooltip, line by line (T3's thread details context row). */ +export function contextTooltip(s: ContextSnapshot): string[] { + const lines = [s.percent != null ? `Context: ${s.percent}% used` : `Context: ${formatContextTokens(s.used)} tokens used`] + if (s.max) lines.push(`${Math.round(s.used).toLocaleString('en-US')} of ${s.max.toLocaleString('en-US')} tokens`) + lines.push(compactionMessage(s.autoCompactAt)) + return lines +} + +export const isCompactionTurn = (m: ChatMessage | undefined) => m?.role === 'user' && m.command === 'compact' + +/** + * The tokens a plain send into an idle chat compacts first (Compact idle threads + * → When you return), or null when it sends as it is. T3's compactBeforeSendTokens: + * a Claude chat of 200k tokens or more, idle past its prompt cache's lifetime, + * with nothing waiting on the owner, the send not handing off to another + * account, and the words not a `/compact` of their own. + */ +export function compactBeforeSendTokens(input: { + thread: ChatThread | null | undefined + /** The account the composer would send on, and whether it is a Claude one. */ + provider: string + claude: boolean + setting: IdleCompaction | undefined + text: string + idle: boolean + now: number +}): number | null { + const { thread } = input + if (!thread || thread.summary || !input.claude || !input.idle) return null + if ((input.setting ?? 'onReturn') === 'off') return null + if (COMPACT_COMMAND.test(input.text.trim())) return null + // A send that hands off to another account starts that one fresh. + if (thread.provider && thread.provider !== input.provider) return null + if (thread.queueHeld && thread.queue?.length) return null + const messages = thread.messages || [] + if (!messages.some((m) => m.role === 'user' && !isCompactionTurn(m))) return null + const last = messages[messages.length - 1] + if (last?.role === 'assistant' && (last.parts || []).some((p) => (p.type === 'questions' || p.type === 'approval') && p.status === 'pending')) return null + const ctx = latestContext(messages, input.provider) + if (!ctx || ctx.used < COMPACTION_MIN_TOKENS || !ctx.at) return null + return input.now - ctx.at >= (ctx.cacheTtlMs ?? CACHE_TTL_FALLBACK_MS) ? ctx.used : null +} + +/** T3's compaction divider text. */ +export function compactionLabel(p: CompactionPart): { text: string; tokens: { before: string; after: string } | null; failed: boolean; active: boolean } { + if (p.status === 'failed') return { text: 'Context compaction failed', tokens: null, failed: true, active: false } + if (p.status === 'stopped') return { text: 'Context compaction stopped', tokens: null, failed: false, active: false } + if (p.status === 'running') { + const text = p.trigger === 'beforeCacheExpires' ? 'Compacting before the cache expires…' : p.trigger === 'onReturn' ? 'Compacting…' : 'Compacting context' + return { text, tokens: null, failed: false, active: true } + } + const text = p.trigger === 'beforeCacheExpires' ? 'Auto-compacted before cache expiry' : p.trigger === 'onReturn' ? 'Context compacted before sending' : 'Context compacted' + const tokens = p.before != null && p.after != null ? { before: formatContextTokens(p.before), after: formatContextTokens(p.after) } : null + return { text, tokens, failed: false, active: false } +} diff --git a/mobile/src/lib/chat/icons.ts b/mobile/src/lib/chat/icons.ts index deed378..4b57532 100644 --- a/mobile/src/lib/chat/icons.ts +++ b/mobile/src/lib/chat/icons.ts @@ -102,3 +102,6 @@ export { default as IconListNumbers } from '@tabler/icons-react-native/dist/esm/ export { default as IconGitPullRequest } from '@tabler/icons-react-native/dist/esm/icons/IconGitPullRequest.mjs' export { default as IconAlertTriangle } from '@tabler/icons-react-native/dist/esm/icons/IconAlertTriangle.mjs' export { default as IconChartBar } from '@tabler/icons-react-native/dist/esm/icons/IconChartBar.mjs' +// Context compaction (CompactionMark.tsx, the composer's Compact chip): T3's Minimize2. +export { default as IconArrowsDiagonalMinimize2 } from '@tabler/icons-react-native/dist/esm/icons/IconArrowsDiagonalMinimize2.mjs' +export { default as IconArrowsDiagonal } from '@tabler/icons-react-native/dist/esm/icons/IconArrowsDiagonal.mjs' diff --git a/mobile/src/lib/chat/reduce.ts b/mobile/src/lib/chat/reduce.ts index e223832..2f7d256 100644 --- a/mobile/src/lib/chat/reduce.ts +++ b/mobile/src/lib/chat/reduce.ts @@ -129,6 +129,22 @@ export function applyEvent(msg: ChatMessage, event: any, now = Date.now()): Chat parts.push({ type: 'visual', id: v.id, uploadId: v.uploadId, title: v.title || 'Chart', height: v.height || 320, ...(v.url ? { url: v.url } : {}) }) return next } + case 'context': { + // How full the context window is now (chat/context.mjs): the newest reading wins. + if (!event.context || typeof event.context.used !== 'number') return msg + next.context = { ...event.context } + return next + } + case 'compaction': { + // The session was (or is being) compacted: a divider, added where it began + // and settled in place by id. + const c = event.compaction || {} + if (!c.id) return msg + const at = parts.findIndex((p) => p.type === 'compaction' && p.id === c.id) + if (at >= 0) parts[at] = { ...parts[at], ...c } + else parts.push({ type: 'compaction', status: 'running', trigger: 'auto', startedAt: now, ...c }) + return next + } case 'steer': { // The owner's words mid-reply, kept where they landed among the steps. const st = event.steer || {} diff --git a/mobile/src/lib/chat/store.ts b/mobile/src/lib/chat/store.ts index 272e338..00fd04c 100644 --- a/mobile/src/lib/chat/store.ts +++ b/mobile/src/lib/chat/store.ts @@ -7,6 +7,7 @@ // (`start` carries the real ids, `done` the settled reply). localStorage is // only an instant-paint cache. import { useSyncExternalStore } from 'react' +import { isCompactionTurn } from './context' import { AppState } from 'react-native' import { getThreadSummaries, getThreadPage, peekThreadPage, forgetCached, isAccountChanged, putThread, deleteThread as apiDeleteThread, getChatModels, setProviderConfig, AuthError, api } from '../api' import { pushError, pushToast } from '../toast' @@ -90,6 +91,10 @@ export interface ChatPrefs { totemsInChat?: boolean /** What sending does while a reply runs: wait its turn or steer the reply. A long press does the other. */ followUp?: 'queue' | 'steer' + /** Claude's auto-compact window: '' for Claude's default, else 100,000–1,000,000 (chat/context.mjs). */ + autoCompactWindow?: string + /** What an idle Claude chat of 200k tokens or more does when its prompt cache goes cold (T3's Compact idle threads). */ + compactIdle?: 'onReturn' | 'beforeCacheExpires' | 'off' } export interface Artifact { uploadId: string; name: string; mime: string; url?: string; size?: number; path?: string } @@ -165,7 +170,11 @@ function withOutbox(threads: ChatThread[], sending: Set = new Set(), onl const lastUser = [...t.messages].reverse().find((m) => m.role === 'user') // A summary's preview is cut (SUMMARY_TEXT on the bridge), so it only has to start the same. const got = lastUser && (lastUser.content === e.message.content || (t.summary && lastUser.content.endsWith('…') && e.message.content.startsWith(lastUser.content.slice(0, -1)))) - if (got && (lastUser!.createdAt || 0) >= e.at - 60_000) { outboxDrop(id); continue } + const recent = !!lastUser && (lastUser.createdAt || 0) >= e.at - 60_000 + // Or it got through as a `/compact` (Compact and send), or was queued behind a run (one of those, or the bridge's own idle compaction). + const queued = (t.queue || []).some((q) => !q.id.startsWith('local-') && (q.createdAt || 0) >= e.at - 60_000 && q.text === e.message.content) + const compacting = !!e.args.compactFirst && recent && isCompactionTurn(lastUser) + if ((got && recent) || compacting || queued) { outboxDrop(id); continue } if (!t.messages.some((m) => m.id === e.message.id)) out[i] = { ...t, messages: [...t.messages.filter((m) => !m.unsent), unsent] } } return out @@ -977,7 +986,9 @@ function handleEvent(threadId: string, e: StreamEvent) { const ui = ai - 1 if (msgs[ai]?.role === 'assistant' && msgs[ai].status === 'streaming') { const live = msgs[ai] - msgs[ai] = { ...e.assistantMessage, parts: live.parts?.length ? live.parts : e.assistantMessage.parts, content: live.content || e.assistantMessage.content } + // Compact and send's stand-in divider gives way to the bridge's own (same compaction, real id). + const kept = (live.parts || []).filter((p) => !(p.type === 'compaction' && p.id.startsWith('local-'))) + msgs[ai] = { ...e.assistantMessage, parts: kept.length ? kept : e.assistantMessage.parts, content: live.content || e.assistantMessage.content } if (msgs[ui]?.role === 'user') msgs[ui] = e.userMessage } else { msgs.push(e.userMessage, e.assistantMessage) @@ -996,6 +1007,8 @@ function handleEvent(threadId: string, e: StreamEvent) { case 'approval': case 'inbox': case 'visual': + case 'context': + case 'compaction': case 'delta': case 'tool': case 'agent': @@ -1016,7 +1029,8 @@ function handleEvent(threadId: string, e: StreamEvent) { case 'done': patchAssistant(threadId, (m) => ({ ...e.message, parts: e.message.parts?.length ? e.message.parts : m.parts })) // The bridge marks it waiting on him too; this shows it without a sync. - if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) + // Not after a compaction (`/compact`, context.ts): housekeeping is nothing to read. + if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) break case 'error': patchAssistant(threadId, (m) => ({ ...m, status: 'error', error: e.text })) @@ -1111,6 +1125,8 @@ export interface SendInput { projectId?: string | null /** A new project chat that leaves the project's context out. */ projectContextOff?: boolean + /** "Compact and send" (context.ts): the chat compacts first and the message waits right behind it. */ + compactFirst?: boolean } /** Start a turn. Returns the thread id (new chats get one here). */ @@ -1130,13 +1146,20 @@ export function send(input: SendInput): string { } const wire = wireModel(row?.driver || 'cursor', settings) const t0 = now() - const userMessage: ChatMessage = { - id: `local-${newId()}`, role: 'user', content: input.text, createdAt: t0, - ...(input.attachments?.length ? { attachments: input.attachments } : {}), - ...(input.mode && input.mode !== 'chat' ? { mode: input.mode } : {}), - ...(input.voice ? { voice: true } : {}), + // Compact and send: what shows at once is the compaction, with his message waiting behind it. + const compactFirst = !!thread && !!input.compactFirst + const userMessage: ChatMessage = compactFirst + ? { id: `local-${newId()}`, role: 'user', content: '/compact', command: 'compact', createdAt: t0 } + : { + id: `local-${newId()}`, role: 'user', content: input.text, createdAt: t0, + ...(input.attachments?.length ? { attachments: input.attachments } : {}), + ...(input.mode && input.mode !== 'chat' ? { mode: input.mode } : {}), + ...(input.voice ? { voice: true } : {}), + } + const assistant: ChatMessage = { + id: `local-${newId()}`, role: 'assistant', content: '', status: 'streaming', provider, createdAt: t0, + parts: compactFirst ? [{ type: 'compaction', id: `local-${newId()}`, status: 'running', trigger: 'onReturn', startedAt: t0 }] : [], } - const assistant: ChatMessage = { id: `local-${newId()}`, role: 'assistant', content: '', parts: [], status: 'streaming', provider, createdAt: t0 } const contextOff = !!projectId && !thread && !!input.projectContextOff if (!thread) { thread = { @@ -1145,7 +1168,8 @@ export function send(input: SendInput): string { messages: [], createdAt: t0, updatedAt: t0, ...(kind === 'temporary' ? { expiresAt: endOfToday() } : {}), } } - upsertThread({ ...thread, messages: [...thread.messages, userMessage, assistant], updatedAt: t0 }) + const queue = compactFirst ? [{ id: `local-${newId()}`, text: input.text, attachments: input.attachments || [], createdAt: t0 }, ...(thread.queue || [])] : thread.queue + upsertThread({ ...thread, messages: [...thread.messages, userMessage, assistant], updatedAt: t0, ...(compactFirst ? { queue } : {}) }) const args: SendArgs = { threadId, text: input.text, attachments: (input.attachments || []).map((a) => a.id), provider, // The bridge keeps this model only when the turn runs on `provider`; a @@ -1156,9 +1180,14 @@ export function send(input: SendInput): string { // Only read for a chat the bridge hasn't seen; an existing one keeps its project. ...(projectId ? { projectId } : {}), ...(contextOff ? { projectContextOff: true } : {}), + ...(compactFirst ? { compactFirst: true } : {}), } const { messages: _m, needsReply: _n, keepUnread: _k, ...meta } = thread - outboxPut(threadId, { args, message: userMessage, thread: { ...meta, updatedAt: t0 }, at: t0 }) + // Unsent, Retry and Discard work on what he wrote; a compact-first send carries it in its args. + const unsentAs: ChatMessage = compactFirst + ? { id: userMessage.id, role: 'user', content: input.text, createdAt: t0, ...(input.attachments?.length ? { attachments: input.attachments } : {}) } + : userMessage + outboxPut(threadId, { args, message: unsentAs, thread: { ...meta, updatedAt: t0 }, at: t0 }) return startRun(threadId, args) } @@ -1184,6 +1213,8 @@ export function discardUnsent(threadId: string): string { const e = readOutbox()[threadId] outboxDrop(threadId) if (!e) return '' + // Compact and send: what he wrote is the message, not the compaction shown for it. + if (e.args.compactFirst) patchThread(threadId, (t) => ({ ...t, queue: (t.queue || []).filter((q) => !q.id.startsWith('local-')) })) patchThread(threadId, (t) => ({ ...t, messages: t.messages.filter((m) => m.id !== e.message.id) })) if (!state.threads.find((t) => t.id === threadId)?.messages.length) set((s) => ({ threads: s.threads.filter((t) => t.id !== threadId) })) return e.message.content @@ -1207,11 +1238,14 @@ function startRun(threadId: string, args: SendArgs) { const reason = (err.message || 'The connection dropped') box.message.sendError = reason outboxPut(threadId, box) + // Compact and send shows what he wrote, not the compaction that was to run first. + const local = (m: ChatMessage) => (m.parts || []).every((p) => p.type === 'compaction' && p.id.startsWith('local-')) patchThread(threadId, (t) => ({ ...t, + ...(box.args.compactFirst ? { queue: (t.queue || []).filter((q) => !q.id.startsWith('local-')) } : {}), messages: t.messages - .filter((m) => !(m.role === 'assistant' && m.status === 'streaming' && !m.content && !(m.parts || []).length)) - .map((m) => (m.id === box.message.id ? { ...m, unsent: true, sendError: reason } : m)), + .filter((m) => !(m.role === 'assistant' && m.status === 'streaming' && !m.content && local(m))) + .map((m) => (m.id === box.message.id ? { ...box.message, unsent: true, sendError: reason } : m)), })) setRun(threadId, null) return diff --git a/mobile/src/lib/chat/types.ts b/mobile/src/lib/chat/types.ts index 4ee7a05..c76aeb5 100644 --- a/mobile/src/lib/chat/types.ts +++ b/mobile/src/lib/chat/types.ts @@ -185,7 +185,43 @@ export interface InboxPart { * bridge adds on the way out; it serves the page sandboxed. */ export interface VisualPart { type: 'visual'; id: string; uploadId: string; title: string; height: number; url?: string } -export type Part = TextPart | ImagePart | ToolPart | FilePart | TotemProposalPart | ChangePart | SteerPart | QuestionsPart | ApprovalPart | InboxPart | VisualPart +/** + * The context was compacted here (chat/context.mjs on the bridge): the CLI's own + * compaction mid-reply (`auto`), a `/compact` the owner sent (`manual`), or one + * Totem ran for an idle chat (`onReturn`, `beforeCacheExpires`). A divider. + */ +export interface CompactionPart { + type: 'compaction' + id: string + status: 'running' | 'done' | 'failed' | 'stopped' + trigger: 'auto' | 'manual' | 'onReturn' | 'beforeCacheExpires' + before?: number + after?: number + reason?: string + startedAt?: number + endedAt?: number +} +export type Part = TextPart | ImagePart | ToolPart | FilePart | TotemProposalPart | ChangePart | SteerPart | QuestionsPart | ApprovalPart | InboxPart | VisualPart | CompactionPart + +/** + * How full the context window was after a reply's last request (chat/context.mjs): + * the request's prompt plus its output, never the reply's billed total. + * `max` is absent when the window is unknown; `autoCompactAt` only when Claude's + * compaction point is set below the window; `cacheExpiresAt` when Claude said + * how long its prompt cache lasts. + */ +export interface ContextUsage { + used: number + max?: number + input?: number + cached?: number + output?: number + autoCompactAt?: number + cacheTtlMs?: number + cacheExpiresAt?: number + /** When the reading arrived. */ + at: number +} export type ChatMode = 'chat' | 'task' | 'computer' @@ -212,6 +248,10 @@ export interface ChatMessage { effort?: string /** What the CLI reported for this reply (chat/stats.mjs); absent = not reported. */ stats?: TurnStatsData + /** How full the context window is after this reply (chat/context.mjs). */ + context?: ContextUsage + /** A user message that is `/compact`: the turn is drawn as its divider, never as a message. */ + command?: 'compact' /** A totem's scheduled run, posted to its chat. */ run?: { trigger: string; status: string; notified: boolean } /** The owner's decision on, or reply about, an inbox proposal (the bridge wrote this message). */ @@ -402,6 +442,8 @@ export type StreamEvent = | { type: 'approval'; approval: Partial & { id: string }; seq: number } | { type: 'inbox'; inbox: Partial & { id: string }; seq: number } | { type: 'visual'; visual: { id: string; uploadId: string; title: string; height: number; url?: string }; seq: number } + | { type: 'context'; context: ContextUsage; seq: number } + | { type: 'compaction'; compaction: Partial & { id: string }; seq: number } | { type: 'activity'; text: string; seq: number } | { type: 'title'; title: string; icon?: string; seq: number } | { type: 'done'; message: ChatMessage; seq: number } diff --git a/mobile/src/lib/components/settings/searchIndex.ts b/mobile/src/lib/components/settings/searchIndex.ts index 2f3cd7f..8e880f3 100644 --- a/mobile/src/lib/components/settings/searchIndex.ts +++ b/mobile/src/lib/components/settings/searchIndex.ts @@ -32,6 +32,8 @@ const ENTRIES: Partial> = { ], chat: [ ['follow-up', 'While a reply is running', 'Sending', 'queue steer follow-up enter'], + ['compact-idle', 'Compact idle threads', 'Context', 'compaction context window cache summarize tokens'], + ['auto-compact', 'Auto-compact after', 'Context', 'compaction context window tokens claude'], ['auto-settle', 'Settle quiet chats', 'Chat list', 'archive settled days'], ['totems-in-chat', 'Let chats bring in totems', 'Totems', 'group totem agents'], ['titles', 'Name chats automatically', 'Titles', 'thread title naming'], diff --git a/web/src/chat/CompactionMark.tsx b/web/src/chat/CompactionMark.tsx new file mode 100644 index 0000000..424607c --- /dev/null +++ b/web/src/chat/CompactionMark.tsx @@ -0,0 +1,23 @@ +import React from 'react' +import { compactionLabel } from './context' +import type { CompactionPart } from './types' +import { TI } from './ui' +import { IconAlertCircle, IconArrowRight, IconArrowsDiagonalMinimize2 } from './icons' + +// Where the context was compacted (T3 Code's timeline divider): a rule across the +// log, "Context compacted 412k → 38k tokens", shimmering while it runs and red if +// it failed. A `/compact` turn is only this; a compaction the CLI ran mid-reply +// sits among that reply's steps. +export default function CompactionMark({ p }: { p: CompactionPart }) { + const l = compactionLabel(p) + const label = l.tokens ? `${l.text} ${l.tokens.before} → ${l.tokens.after} tokens` : l.text + return ( +
+ + + {l.tokens ? <>{l.text} {l.tokens.before}{l.tokens.after} tokens : l.text} + {p.reason && · {p.reason}} + +
+ ) +} diff --git a/web/src/chat/Composer.tsx b/web/src/chat/Composer.tsx index a8a4f6c..9a5b327 100644 --- a/web/src/chat/Composer.tsx +++ b/web/src/chat/Composer.tsx @@ -17,8 +17,9 @@ import { TI, useDismiss } from './ui' import { IconArrowUp, IconPlayerStopFilled, IconPlus, IconPaperclip, IconPhoto, IconMicrophone, IconWaveSine, IconSparkles, IconX, IconCheck, IconLoader2, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled, - IconHome, IconChecklist, IconTable, IconFolder, + IconHome, IconChecklist, IconTable, IconFolder, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, } from './icons' +import { formatContextTokens } from './context' import type { ChatCommand } from '../studio' // A paste this long becomes a chip instead of filling the box. The text is sent @@ -68,6 +69,14 @@ export interface ComposerProps { onAuthError?: () => void /** The model chip and its effort and access menu (T3-style), before the mic and send. */ rightSlot?: React.ReactNode + /** After the plus button: how full the chat's context is (ContextMeter.tsx). */ + leftSlot?: React.ReactNode + /** + * The next send compacts the idle chat first (T3's Compact idle threads → When + * you return): a Compact/Keep chip by the send button, and the button says so. + * `keep` is the owner choosing full history for this send. + */ + compactSend?: { tokens: number; keep: boolean; onToggle: () => void } | null /** Attached to the box's top edge: the queued messages (QueuedMessages.tsx). */ above?: React.ReactNode /** @@ -149,7 +158,7 @@ function rankCommands(catalog: ChatCommand[], prefix: string, term: string, alon } const Composer = forwardRef(function Composer(props, ref) { - const { value, onChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, answering, above, destinations } = props + const { value, onChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, leftSlot, compactSend, answering, above, destinations } = props const ta = useRef(null) const fileInput = useRef(null) const photoInput = useRef(null) @@ -442,6 +451,7 @@ const Composer = forwardRef(function Composer(pro } const secs = dictation ? Math.floor((Date.now() - dictation.startedAt) / 1000) : 0 + const compacting = !!compactSend && !compactSend.keep const showVoice = !!onVoice && !busy && !value.trim() && !drafts.length && !dictation && !onResume return ( @@ -522,7 +532,7 @@ const Composer = forwardRef(function Composer(pro /> )} -
+
{!dictation && (
@@ -554,6 +564,7 @@ const Composer = forwardRef(function Composer(pro )}
)} + {!dictation && leftSlot}
{dictation ? ( @@ -566,6 +577,22 @@ const Composer = forwardRef(function Composer(pro ) : ( <> {rightSlot} + {compactSend && !busy && !answering && !queueEdit && ( + // T3's Compact chip: the next send summarises the idle chat first, unless he keeps the full history. + + + + {compactSend.keep ? `Next send keeps all ${formatContextTokens(compactSend.tokens)} tokens.` : `Next send compacts ${formatContextTokens(compactSend.tokens)} tokens first.`} + {compactSend.keep ? 'Click to compact first' : 'Click to keep full history'} + + + )} {(!busy || followUps) && ( ) : ( - )} diff --git a/web/src/chat/ContextMeter.tsx b/web/src/chat/ContextMeter.tsx new file mode 100644 index 0000000..4f43a71 --- /dev/null +++ b/web/src/chat/ContextMeter.tsx @@ -0,0 +1,31 @@ +import React, { useRef, useState } from 'react' +import { contextLabel, contextTooltip, contextValue, type ContextSnapshot } from './context' +import { useDismiss } from './ui' + +// How full the chat's context window is (T3 Code's context row): a thin bar in the +// composer's footer with "45k / 1m" beside it, amber from 80% and red from 90%, and +// a tick where Claude compacts when that is set below the window. Hover, focus or +// tap it for the exact numbers. Drawn only once the provider has reported usage. +export default function ContextMeter({ s }: { s: ContextSnapshot }) { + const [open, setOpen] = useState(false) + const ref = useRef(null) + useDismiss(open, ref, () => setOpen(false)) + const lines = contextTooltip(s) + const tick = s.max && s.autoCompactAt ? (s.autoCompactAt / s.max) * 100 : null + return ( + setOpen(false)}> + + + {lines.map((l, i) => {l})} + + + ) +} diff --git a/web/src/chat/Message.tsx b/web/src/chat/Message.tsx index 43aa1de..8618e52 100644 --- a/web/src/chat/Message.tsx +++ b/web/src/chat/Message.tsx @@ -11,11 +11,12 @@ import { outcomeLabel } from './inboxCards' import { isAskTool } from './questions' import { isRenderTool } from './visuals' import VisualFrame from './VisualFrame' +import CompactionMark from './CompactionMark' import WorkLog from './WorkLog' import { foldWork } from './workFold' import { AgentGroup } from './AgentsPanel' import TurnStats from './TurnStats' -import type { ApprovalPart, Attachment, ChangePart, ChatMessage, InboxPart, Part, ProviderRow, QuestionsPart, SteerPart, ToolPart, VisualPart } from './types' +import type { ApprovalPart, Attachment, ChangePart, ChatMessage, CompactionPart, InboxPart, Part, ProviderRow, QuestionsPart, SteerPart, ToolPart, VisualPart } from './types' import { TI, ProviderLogo, formatBytes, formatDuration } from './ui' import { IconAlertCircle, IconCopy, IconCheck, IconRefresh, IconVolume, IconPencil, IconFileText, IconFileTypePdf, IconClipboardText, @@ -213,7 +214,7 @@ export function UserMessage({ m, canEdit, onEdit, onRetry, onDiscard }: { m: Cha // --- assistant ------------------------------------------------------------------- -type Block = { kind: 'text'; text: string; key: string } | { kind: 'tools'; tools: ToolPart[]; key: string } | { kind: 'agents'; tools: ToolPart[]; key: string } | { kind: 'image'; part: any; key: string } | { kind: 'file'; part: any; key: string } | { kind: 'proposal'; part: any; key: string } | { kind: 'change'; part: ChangePart; key: string } | { kind: 'steer'; part: SteerPart; key: string } | { kind: 'totem'; answer: TotemAnswer; key: string } | { kind: 'questions'; part: QuestionsPart; key: string } | { kind: 'approval'; part: ApprovalPart; key: string } | { kind: 'inbox'; part: InboxPart; key: string } | { kind: 'visual'; part: VisualPart; key: string } +type Block = { kind: 'text'; text: string; key: string } | { kind: 'tools'; tools: ToolPart[]; key: string } | { kind: 'agents'; tools: ToolPart[]; key: string } | { kind: 'image'; part: any; key: string } | { kind: 'file'; part: any; key: string } | { kind: 'proposal'; part: any; key: string } | { kind: 'change'; part: ChangePart; key: string } | { kind: 'steer'; part: SteerPart; key: string } | { kind: 'totem'; answer: TotemAnswer; key: string } | { kind: 'questions'; part: QuestionsPart; key: string } | { kind: 'approval'; part: ApprovalPart; key: string } | { kind: 'inbox'; part: InboxPart; key: string } | { kind: 'visual'; part: VisualPart; key: string } | { kind: 'compaction'; part: CompactionPart; key: string } // A totem proposal arrives as a fenced block while streaming; the bridge turns it // into a card when the reply settles. Until then, don't show the raw JSON. @@ -254,7 +255,9 @@ function blocks(parts: Part[]): Block[] { else if (p.type === 'totem-proposal') out.push({ kind: 'proposal', part: p, key: `p${i}` }) else if (p.type === 'change-pr') out.push({ kind: 'change', part: p, key: `c${i}` }) else if (p.type === 'steer') out.push({ kind: 'steer', part: p, key: `s${i}` }) - else if (p.text) { + // The context was compacted here: a divider, never folded into the steps. + else if (p.type === 'compaction') out.push({ kind: 'compaction', part: p, key: `cm${i}` }) + else if (p.type === 'text' && p.text) { const last = out[out.length - 1] // Two text parts with no tool between them are one paragraph run. if (last?.kind === 'text') last.text += p.text @@ -345,7 +348,8 @@ export function AssistantMessage({ m, live, activity, provider, modelName, isLas // sentence — gets the working line too, so a live reply never looks stalled. const asking = !!m.parts?.some((p) => (p.type === 'questions' || p.type === 'approval') && p.status === 'pending') const approving = !!m.parts?.some((p) => p.type === 'approval' && p.status === 'pending') - const toolRunning = !asking && !!m.parts?.some((p) => p.type === 'tool' && p.status === 'running') + // A running compaction shimmers in its own divider (CompactionMark.tsx). + const toolRunning = !asking && !!m.parts?.some((p) => (p.type === 'tool' || p.type === 'compaction') && p.status === 'running') const quiet = useQuiet(live, `${m.content.length}:${m.parts?.length || 0}`) // Replies from the retired Auto/Instant/Thinking presets say which lane answered: "Thought for 14s" reads the // way ChatGPT's does and tells you the slower answer was deliberate. @@ -369,6 +373,7 @@ export function AssistantMessage({ m, live, activity, provider, modelName, isLas if (b.kind === 'approval') return if (b.kind === 'inbox') return if (b.kind === 'visual') return + if (b.kind === 'compaction') return if (b.kind === 'file') return openArtifact(b.part)} /> if (b.kind === 'image') { const src = b.part.url || `/api/chat/uploads/${b.part.uploadId}` @@ -392,7 +397,8 @@ export function AssistantMessage({ m, live, activity, provider, modelName, isLas {isLast && onRegenerate && }
)} - {m.status === 'stopped' &&
Stopped
} + {/* A stopped compaction says so in its own divider. */} + {m.status === 'stopped' && !m.parts?.some((p) => p.type === 'compaction' && p.status === 'stopped') &&
Stopped
}
{!live && (m.content || m.status === 'error') && (
diff --git a/web/src/chat/MessageLog.tsx b/web/src/chat/MessageLog.tsx index eeefddc..f3d2fca 100644 --- a/web/src/chat/MessageLog.tsx +++ b/web/src/chat/MessageLog.tsx @@ -2,6 +2,7 @@ import React from 'react' import { UserMessage, AssistantMessage } from './Message' import HandoffMark from './HandoffMark' import { providerSwitches } from './handoff' +import { isCompactionTurn } from './context' import { discardUnsent, editAndResend, providerById, regenerate, retryUnsent } from './store' import type { ChatMessage, ModelRow, ProviderRow } from './types' @@ -86,6 +87,9 @@ export default React.memo(function MessageLog({ threadId, messages, busy, activi {messages.map((m, i) => { const live = busy && i === messages.length - 1 const isLast = m === lastAssistant && i === messages.length - 1 + // `/compact` (context.ts): its reply's divider stands for the whole turn. + const compaction = isCompactionTurn(m) || isCompactionTurn(messages[i - 1]) + if (isCompactionTurn(m) && !m.unsent) return switches.has(m.id) ? : null return ( {switches.has(m.id) && } @@ -99,7 +103,7 @@ export default React.memo(function MessageLog({ threadId, messages, busy, activi provider={providerById(m.provider || provider) || providers.find((p) => p.driver === m.provider)} modelName={modelName(models, m.provider, m.model)} isLast={isLast} - canRegenerate={isLast && !busy && !!threadId} + canRegenerate={isLast && !busy && !!threadId && !compaction} />} ) diff --git a/web/src/chat/RunningChats.tsx b/web/src/chat/RunningChats.tsx index d9845cb..6893a8f 100644 --- a/web/src/chat/RunningChats.tsx +++ b/web/src/chat/RunningChats.tsx @@ -1,4 +1,5 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { isCompactionTurn } from './context' import { useChat, getState, setActive, stop, settleThread, snoozeThread, markRead, threadTitle, type RunState } from './store' import { useOnScreen, getOnScreen } from './onScreen' import { isSnoozed, ago } from './settle' @@ -146,6 +147,8 @@ export default function RunningChats({ onOpenChat, onShowPanel, narrow }: { onOp const t = getState().threads.find((x) => x.id === id) const last = t?.messages[t.messages.length - 1] if (!t || t.totemId || last?.role !== 'assistant' || (last.status !== 'done' && last.status !== 'error')) continue + // A compaction (`/compact`) is housekeeping, not news. + if (isCompactionTurn(t.messages[t.messages.length - 2])) continue const seen = getOnScreen() if (seen.open.has(id)) continue const failed = last.status === 'error' diff --git a/web/src/chat/api.ts b/web/src/chat/api.ts index b1a63cd..0fcadb5 100644 --- a/web/src/chat/api.ts +++ b/web/src/chat/api.ts @@ -21,6 +21,8 @@ export interface SendArgs { voice?: boolean regenerate?: boolean editMessageId?: string + /** Compact the idle chat first; the message waits at the front of its queue (chat/context.mjs). */ + compactFirst?: boolean } export interface StreamHandle { diff --git a/web/src/chat/chat.css b/web/src/chat/chat.css index 4baaa6c..a1f63f9 100644 --- a/web/src/chat/chat.css +++ b/web/src/chat/chat.css @@ -1925,3 +1925,73 @@ button.vc-file-row:hover, .vc-file-row:hover { background: var(--vc-raise); } .vc-inbox-details { margin: 6px 0 0 23px; } .vc-inbox-note { display: block; box-sizing: border-box; width: calc(100% - 23px); margin: 8px 0 0 23px; min-height: 30px; padding: 6px 8px; resize: vertical; border-radius: 8px; border: 1px solid var(--vc-line); background: transparent; color: var(--text); font: inherit; font-size: 12.5px; } @media (max-width: 640px) { .vc-approval-detail, .vc-approval-reason, .vc-approval-actions, .vc-inbox-disclose, .vc-inbox-details { margin-left: 0; } .vc-inbox-note { margin-left: 0; width: 100%; } } + +/* --- context window (ContextMeter.tsx, after T3 Code's context row) ---------------- + A thin bar and "45k / 1m" after the composer's plus: the fill is muted, amber from + 80% and red from 90%; the tick marks where Claude compacts when that is set below + the window. Hover, focus or tap shows the exact numbers above it, on the composer's + glass. Only once the provider has reported usage. */ +.vc-ctx { position: relative; display: inline-flex; min-width: 0; } +.vc-ctx-chip { + display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 8px; border-radius: 8px; + background: none; border: 0; color: var(--vc-faint); font: inherit; font-size: 12px; font-variant-numeric: tabular-nums; + cursor: default; white-space: nowrap; transition: color .15s; +} +.vc-ctx:hover .vc-ctx-chip, .vc-ctx.open .vc-ctx-chip { color: var(--vc-soft); } +.vc-ctx-track { position: relative; flex: none; width: 44px; height: 3px; border-radius: 3px; background: color-mix(in srgb, var(--text) 16%, transparent); } +.vc-ctx-fill { position: absolute; inset: 0 auto 0 0; border-radius: inherit; background: var(--vc-soft); } +.vc-ctx.tone-warning .vc-ctx-fill { background: var(--amber); } +.vc-ctx.tone-error .vc-ctx-fill { background: var(--red); } +.vc-ctx-tick { position: absolute; top: -3px; width: 1px; height: 9px; background: var(--vc-soft); transform: translateX(-.5px); } +.vc-ctx-tip, .vc-compact-tip { + position: absolute; z-index: 40; bottom: calc(100% + 8px); left: 0; + display: grid; gap: 2px; padding: 8px 11px; white-space: nowrap; + font-size: 12px; line-height: 1.4; color: var(--vc-soft); font-variant-numeric: tabular-nums; + background: color-mix(in srgb, var(--bg) 97%, transparent); + border: 1px solid #ffffff14; border-radius: 10px; + box-shadow: inset 0 1px 0 #ffffff14, 0 12px 32px -16px #00000099; + opacity: 0; transform: translateY(3px); pointer-events: none; transition: opacity .12s, transform .12s; +} +.vc-ctx-tip-head { color: var(--text); } +.vc-ctx:hover .vc-ctx-tip, .vc-ctx.open .vc-ctx-tip, .vc-ctx-chip:focus-visible + .vc-ctx-tip, +.vc-compact-wrap:hover .vc-compact-tip, .vc-compact-chip:focus-visible + .vc-compact-tip { opacity: 1; transform: none; } +@media (hover: none) { .vc-ctx:hover:not(.open) .vc-ctx-tip { opacity: 0; } } + +/* T3's Compact chip by the send button: the next send compacts the idle chat first + (pressed), or keeps the full history. */ +.vc-compact-wrap { position: relative; display: inline-flex; } +.vc-compact-wrap .vc-compact-tip { left: auto; right: 0; } +.vc-compact-chip { + display: inline-flex; align-items: center; gap: 5px; height: 30px; padding: 0 8px; border-radius: 8px; + background: none; border: 0; color: var(--vc-soft); font: inherit; font-size: 13px; font-weight: 500; + font-variant-numeric: tabular-nums; white-space: nowrap; transition: background .15s, color .15s; +} +.vc-compact-chip svg { color: var(--vc-faint); } +.vc-compact-chip:hover { background: var(--vc-raise); color: var(--text); } +.vc-compact-chip.on { background: color-mix(in srgb, var(--vc-raise) 70%, transparent); color: var(--text); } +.vc-compact-n { color: var(--vc-faint); font-weight: 400; } +/* A phone's footer keeps the model's name: the effort steps aside for the meter or + the chip (it is in the picker), and the meter for the chip, which names the tokens. */ +@media (max-width: 480px) { + .vc-box-bar:has(.vc-ctx) .vc-chip-effort, .vc-box-bar.has-compact .vc-chip-effort, .vc-box-bar.has-compact .vc-ctx { display: none; } +} +/* T3's rule: under 480px the chip is its glyph and the tokens, so the model keeps its name. */ +@media (max-width: 480px) { .vc-compact-word { display: none; } } +@media (max-width: 400px) { .vc-ctx-value { display: none; } .vc-ctx-chip { padding: 0 6px; } } + +/* Where the context was compacted (CompactionMark.tsx): T3's divider, a rule across + the reply with "Context compacted 412k → 38k tokens", shimmering while it runs. */ +.vc-compaction { display: flex; align-items: center; gap: 10px; margin: 6px 0; color: var(--vc-faint); font-size: 12px; font-variant-numeric: tabular-nums; } +.vc-compaction::before, .vc-compaction::after { content: ''; flex: 1; height: 1px; background: var(--vc-line); } +.vc-compaction-label { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 85%; white-space: nowrap; } +.vc-compaction-reason { min-width: 0; overflow: hidden; text-overflow: ellipsis; opacity: .8; } +.vc-compaction.failed { color: var(--red); } +.vc-compaction.failed::before, .vc-compaction.failed::after { background: color-mix(in srgb, var(--red) 30%, transparent); } +.vc-compaction.active .vc-compaction-label { + background: linear-gradient(90deg, var(--vc-faint) 0%, var(--vc-faint) 35%, var(--text) 50%, var(--vc-faint) 65%, var(--vc-faint) 100%); + background-size: 250% 100%; -webkit-background-clip: text; background-clip: text; color: transparent; + animation: vc-compaction-shimmer 1.8s linear infinite; +} +.vc-compaction.active .vc-compaction-label svg { color: var(--vc-faint); } +@keyframes vc-compaction-shimmer { from { background-position: 100% 0; } to { background-position: -150% 0; } } +@media (prefers-reduced-motion: reduce) { .vc-compaction.active .vc-compaction-label { animation: none; color: var(--vc-soft); background: none; } } diff --git a/web/src/chat/context.test.ts b/web/src/chat/context.test.ts new file mode 100644 index 0000000..233bf58 --- /dev/null +++ b/web/src/chat/context.test.ts @@ -0,0 +1,108 @@ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { compactBeforeSendTokens, compactionLabel, contextSnapshot, contextTooltip, contextValue, formatContextTokens, latestContext } from './context' +import type { ChatMessage, ChatThread } from './types' + +const HOUR = 3_600_000 +const reply = (patch: Partial = {}): ChatMessage => ({ id: `a${Math.random()}`, role: 'assistant', content: 'ok', createdAt: 0, status: 'done', provider: 'claude', ...patch }) +const ask = (content = 'hi', patch: Partial = {}): ChatMessage => ({ id: `u${Math.random()}`, role: 'user', content, createdAt: 0, ...patch }) +const thread = (messages: ChatMessage[], patch: Partial = {}): ChatThread => ({ id: 't', kind: 'regular', provider: 'claude', messages, createdAt: 0, updatedAt: 0, ...patch }) + +describe('formatContextTokens (T3\'s formatContextWindowTokens)', () => { + it('rounds the way T3 does', () => { + expect(formatContextTokens(999)).toBe('999') + expect(formatContextTokens(4_500)).toBe('4.5k') + expect(formatContextTokens(4_000)).toBe('4k') + expect(formatContextTokens(45_200)).toBe('45k') + expect(formatContextTokens(999_499)).toBe('999k') + expect(formatContextTokens(999_500)).toBe('1m') + expect(formatContextTokens(1_000_000)).toBe('1m') + expect(formatContextTokens(null)).toBe('0') + }) +}) + +describe('contextSnapshot', () => { + it('is amber from 80% and red from 90%, with the value and tooltip T3 shows', () => { + const s = contextSnapshot({ used: 45_200, max: 200_000, at: 1 })! + expect(s.percent).toBe(23) + expect(s.tone).toBe(null) + expect(contextValue(s)).toBe('45k / 200k') + expect(contextTooltip(s)).toEqual(['Context: 23% used', '45,200 of 200,000 tokens', 'Context compacts automatically when needed.']) + expect(contextSnapshot({ used: 160_000, max: 200_000, at: 1 })!.tone).toBe('warning') + expect(contextSnapshot({ used: 180_000, max: 200_000, at: 1 })!.tone).toBe('error') + }) + it('names where Claude compacts, and shows tokens alone when the window is unknown', () => { + const tick = contextSnapshot({ used: 50_000, max: 1_000_000, autoCompactAt: 117_000, at: 1 })! + expect(tick.autoCompactAt).toBe(117_000) + expect(contextTooltip(tick)[2]).toBe('Compacts automatically at about 117,000 tokens.') + const bare = contextSnapshot({ used: 12_345, at: 1 })! + expect(bare.percent).toBe(null) + expect(contextValue(bare)).toBe('12k') + expect(contextTooltip(bare)).toEqual(['Context: 12k tokens used', 'Context compacts automatically when needed.']) + }) +}) + +describe('latestContext', () => { + it('belongs to the account that would answer', () => { + const ms = [reply({ context: { used: 10, at: 1 } }), reply({ provider: 'codex', context: { used: 20, at: 2 } })] + expect(latestContext(ms, 'claude')!.used).toBe(10) + expect(latestContext(ms, 'codex')!.used).toBe(20) + expect(latestContext(ms, 'cursor')).toBe(null) + }) +}) + +describe('compactBeforeSendTokens (T3\'s Compact idle threads → When you return)', () => { + const now = 10 * HOUR + const cold = () => thread([ask(), reply({ context: { used: 250_000, max: 1_000_000, cacheTtlMs: HOUR, at: now - HOUR } })]) + const base = { provider: 'claude', claude: true, setting: 'onReturn' as const, text: 'next', idle: true, now } + it('offers to compact an idle Claude chat of 200k tokens whose cache expired', () => { + expect(compactBeforeSendTokens({ ...base, thread: cold() })).toBe(250_000) + }) + it('falls back to 70 minutes when the cache lifetime is unknown', () => { + const t = thread([ask(), reply({ context: { used: 250_000, at: now - 60 * 60_000 } })]) + expect(compactBeforeSendTokens({ ...base, thread: t })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: t, now: now + 10 * 60_000 })).toBe(250_000) + }) + it('stays out of the way otherwise', () => { + expect(compactBeforeSendTokens({ ...base, thread: cold(), setting: 'off' })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: cold(), idle: false })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: cold(), claude: false })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: cold(), text: '/compact keep the plan' })).toBe(null) + // A send that hands the chat to another account starts that one fresh. + expect(compactBeforeSendTokens({ ...base, thread: cold(), provider: 'claude_work' })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: { ...cold(), queueHeld: true, queue: [{ id: 'q', text: 'x', createdAt: 0 }] } })).toBe(null) + expect(compactBeforeSendTokens({ ...base, thread: { ...cold(), summary: true } })).toBe(null) + const small = thread([ask(), reply({ context: { used: 199_999, cacheTtlMs: HOUR, at: 0 } })]) + expect(compactBeforeSendTokens({ ...base, thread: small })).toBe(null) + const warm = thread([ask(), reply({ context: { used: 250_000, cacheTtlMs: HOUR, at: now - 10 * 60_000 } })]) + expect(compactBeforeSendTokens({ ...base, thread: warm })).toBe(null) + const onlyCompactions = thread([ask('/compact', { command: 'compact' }), reply({ context: { used: 250_000, cacheTtlMs: HOUR, at: 0 } })]) + expect(compactBeforeSendTokens({ ...base, thread: onlyCompactions })).toBe(null) + const asking = thread([ask(), reply({ parts: [{ type: 'questions', id: 'q', status: 'pending' } as any], context: { used: 250_000, cacheTtlMs: HOUR, at: 0 } })]) + expect(compactBeforeSendTokens({ ...base, thread: asking })).toBe(null) + }) +}) + +describe('compactionLabel (T3\'s timeline strings)', () => { + it('says what happened', () => { + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'running', trigger: 'manual' }).text).toBe('Compacting context') + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'running', trigger: 'beforeCacheExpires' }).text).toBe('Compacting before the cache expires…') + const done = compactionLabel({ type: 'compaction', id: 'c', status: 'done', trigger: 'auto', before: 412_000, after: 38_000 }) + expect(done.text).toBe('Context compacted') + expect(done.tokens).toEqual({ before: '412k', after: '38k' }) + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'done', trigger: 'onReturn' }).text).toBe('Context compacted before sending') + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'done', trigger: 'beforeCacheExpires' }).text).toBe('Auto-compacted before cache expiry') + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'failed', trigger: 'manual' }).failed).toBe(true) + expect(compactionLabel({ type: 'compaction', id: 'c', status: 'stopped', trigger: 'manual' }).text).toBe('Context compaction stopped') + }) +}) + +describe('the app\'s copy', () => { + it('is byte for byte the web\'s', () => { + const here = resolve(__dirname) + const web = readFileSync(join(here, 'context.ts'), 'utf8') + const app = readFileSync(join(here, '../../../mobile/src/lib/chat/context.ts'), 'utf8') + expect(app).toBe(web) + }) +}) diff --git a/web/src/chat/context.ts b/web/src/chat/context.ts new file mode 100644 index 0000000..06a888c --- /dev/null +++ b/web/src/chat/context.ts @@ -0,0 +1,127 @@ +// How full a chat's context window is, and when a send compacts it first. +// Ported from T3 Code (apps/web/src/lib/contextWindow.ts, packages/client-runtime/ +// src/state/contextWindow.ts and the timeline's compaction labels); the bridge's +// half is chat/context.mjs. Copied byte for byte to mobile/src/lib/chat/context.ts. +import type { ChatMessage, ChatThread, CompactionPart, ContextUsage } from './types' + +/** T3's COMPACT_COMMAND_PATTERN: `/compact`, optionally with instructions. */ +export const COMPACT_COMMAND = /^\/compact(?:\s|$)/i +/** No Compact chip below this: Claude Code's own idle-compaction floor. */ +export const COMPACTION_MIN_TOKENS = 200_000 +/** A chat counts as gone cold after this when Claude never said how long its cache lasts. */ +export const CACHE_TTL_FALLBACK_MS = 70 * 60_000 + +export type IdleCompaction = 'onReturn' | 'beforeCacheExpires' | 'off' + +/** 45,200 → "45k", 4,500 → "4.5k", 1,000,000 → "1m" (T3's formatContextWindowTokens). */ +export function formatContextTokens(value: number | null | undefined): string { + if (value == null || !Number.isFinite(value)) return '0' + if (value < 1_000) return `${Math.round(value)}` + if (value < 10_000) return `${(value / 1_000).toFixed(1).replace(/\.0$/, '')}k` + if (value < 999_500) return `${Math.round(value / 1_000)}k` + return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, '')}m` +} + +export interface ContextSnapshot { + used: number + max: number | null + /** 0–100, rounded; null when the window is unknown. */ + percent: number | null + /** Where Claude compacts, when set below the window: the bar's tick. */ + autoCompactAt: number | null + tone: 'error' | 'warning' | null + at: number +} + +/** + * The newest reading for `provider` among the loaded messages, newest last. A + * reading from another account belongs to that account's session: after a + * switch it is not this one's (T3 #28581). + */ +export function latestContext(messages: ChatMessage[], provider: string | undefined): ContextUsage | null { + for (let i = messages.length - 1; i >= 0; i--) { + const m = messages[i] + if (m.role !== 'assistant' || (provider && m.provider !== provider)) continue + if (m.context && typeof m.context.used === 'number') return m.context + } + return null +} + +export function contextSnapshot(usage: ContextUsage | null | undefined): ContextSnapshot | null { + if (!usage || !Number.isFinite(usage.used)) return null + const used = Math.max(0, usage.used) + const max = usage.max && usage.max > 0 ? usage.max : null + const percent = max ? Math.round(Math.min(100, Math.max(0, (used / max) * 100))) : null + const autoCompactAt = usage.autoCompactAt && usage.autoCompactAt > 0 && (!max || usage.autoCompactAt < max) ? usage.autoCompactAt : null + const tone = percent == null ? null : percent >= 90 ? 'error' : percent >= 80 ? 'warning' : null + return { used, max, percent, autoCompactAt, tone, at: usage.at || 0 } +} + +/** The meter's value: "45k / 1m", or the tokens alone when the window is unknown. */ +export const contextValue = (s: ContextSnapshot) => (s.max ? `${formatContextTokens(s.used)} / ${formatContextTokens(s.max)}` : formatContextTokens(s.used)) + +/** The meter's accessible name. */ +export const contextLabel = (s: ContextSnapshot) => (s.percent != null ? `${s.percent}% used` : `${formatContextTokens(s.used)} tokens used`) + +/** T3's formatContextWindowCompactionMessage. */ +export function compactionMessage(autoCompactAt: number | null | undefined): string { + return autoCompactAt && autoCompactAt > 0 + ? `Compacts automatically at about ${autoCompactAt.toLocaleString('en-US')} tokens.` + : 'Context compacts automatically when needed.' +} + +/** The meter's tooltip, line by line (T3's thread details context row). */ +export function contextTooltip(s: ContextSnapshot): string[] { + const lines = [s.percent != null ? `Context: ${s.percent}% used` : `Context: ${formatContextTokens(s.used)} tokens used`] + if (s.max) lines.push(`${Math.round(s.used).toLocaleString('en-US')} of ${s.max.toLocaleString('en-US')} tokens`) + lines.push(compactionMessage(s.autoCompactAt)) + return lines +} + +export const isCompactionTurn = (m: ChatMessage | undefined) => m?.role === 'user' && m.command === 'compact' + +/** + * The tokens a plain send into an idle chat compacts first (Compact idle threads + * → When you return), or null when it sends as it is. T3's compactBeforeSendTokens: + * a Claude chat of 200k tokens or more, idle past its prompt cache's lifetime, + * with nothing waiting on the owner, the send not handing off to another + * account, and the words not a `/compact` of their own. + */ +export function compactBeforeSendTokens(input: { + thread: ChatThread | null | undefined + /** The account the composer would send on, and whether it is a Claude one. */ + provider: string + claude: boolean + setting: IdleCompaction | undefined + text: string + idle: boolean + now: number +}): number | null { + const { thread } = input + if (!thread || thread.summary || !input.claude || !input.idle) return null + if ((input.setting ?? 'onReturn') === 'off') return null + if (COMPACT_COMMAND.test(input.text.trim())) return null + // A send that hands off to another account starts that one fresh. + if (thread.provider && thread.provider !== input.provider) return null + if (thread.queueHeld && thread.queue?.length) return null + const messages = thread.messages || [] + if (!messages.some((m) => m.role === 'user' && !isCompactionTurn(m))) return null + const last = messages[messages.length - 1] + if (last?.role === 'assistant' && (last.parts || []).some((p) => (p.type === 'questions' || p.type === 'approval') && p.status === 'pending')) return null + const ctx = latestContext(messages, input.provider) + if (!ctx || ctx.used < COMPACTION_MIN_TOKENS || !ctx.at) return null + return input.now - ctx.at >= (ctx.cacheTtlMs ?? CACHE_TTL_FALLBACK_MS) ? ctx.used : null +} + +/** T3's compaction divider text. */ +export function compactionLabel(p: CompactionPart): { text: string; tokens: { before: string; after: string } | null; failed: boolean; active: boolean } { + if (p.status === 'failed') return { text: 'Context compaction failed', tokens: null, failed: true, active: false } + if (p.status === 'stopped') return { text: 'Context compaction stopped', tokens: null, failed: false, active: false } + if (p.status === 'running') { + const text = p.trigger === 'beforeCacheExpires' ? 'Compacting before the cache expires…' : p.trigger === 'onReturn' ? 'Compacting…' : 'Compacting context' + return { text, tokens: null, failed: false, active: true } + } + const text = p.trigger === 'beforeCacheExpires' ? 'Auto-compacted before cache expiry' : p.trigger === 'onReturn' ? 'Context compacted before sending' : 'Context compacted' + const tokens = p.before != null && p.after != null ? { before: formatContextTokens(p.before), after: formatContextTokens(p.after) } : null + return { text, tokens, failed: false, active: false } +} diff --git a/web/src/chat/icons.ts b/web/src/chat/icons.ts index 396aede..6d7ab18 100644 --- a/web/src/chat/icons.ts +++ b/web/src/chat/icons.ts @@ -134,3 +134,6 @@ export { default as IconRepeat } from '@tabler/icons-react/dist/esm/icons/IconRe export { default as IconZzz } from '@tabler/icons-react/dist/esm/icons/IconZzz.mjs' export { default as IconArrowUpRight } from '@tabler/icons-react/dist/esm/icons/IconArrowUpRight.mjs' export { default as IconAdjustmentsHorizontal } from '@tabler/icons-react/dist/esm/icons/IconAdjustmentsHorizontal.mjs' +// Context compaction (CompactionMark.tsx, the composer's Compact chip): T3's Minimize2. +export { default as IconArrowsDiagonalMinimize2 } from '@tabler/icons-react/dist/esm/icons/IconArrowsDiagonalMinimize2.mjs' +export { default as IconArrowsDiagonal } from '@tabler/icons-react/dist/esm/icons/IconArrowsDiagonal.mjs' diff --git a/web/src/chat/reduce.ts b/web/src/chat/reduce.ts index e223832..2f7d256 100644 --- a/web/src/chat/reduce.ts +++ b/web/src/chat/reduce.ts @@ -129,6 +129,22 @@ export function applyEvent(msg: ChatMessage, event: any, now = Date.now()): Chat parts.push({ type: 'visual', id: v.id, uploadId: v.uploadId, title: v.title || 'Chart', height: v.height || 320, ...(v.url ? { url: v.url } : {}) }) return next } + case 'context': { + // How full the context window is now (chat/context.mjs): the newest reading wins. + if (!event.context || typeof event.context.used !== 'number') return msg + next.context = { ...event.context } + return next + } + case 'compaction': { + // The session was (or is being) compacted: a divider, added where it began + // and settled in place by id. + const c = event.compaction || {} + if (!c.id) return msg + const at = parts.findIndex((p) => p.type === 'compaction' && p.id === c.id) + if (at >= 0) parts[at] = { ...parts[at], ...c } + else parts.push({ type: 'compaction', status: 'running', trigger: 'auto', startedAt: now, ...c }) + return next + } case 'steer': { // The owner's words mid-reply, kept where they landed among the steps. const st = event.steer || {} diff --git a/web/src/chat/store.ts b/web/src/chat/store.ts index 7818e86..c90f1da 100644 --- a/web/src/chat/store.ts +++ b/web/src/chat/store.ts @@ -7,6 +7,7 @@ // (`start` carries the real ids, `done` the settled reply). localStorage is // only an instant-paint cache. import { useSyncExternalStore } from 'react' +import { isCompactionTurn } from './context' import { getThreadSummaries, getThreadPage, putThread, deleteThread as apiDeleteThread, getChatModels, setProviderConfig, AuthError, ApiError, api, authHeaders } from '../api' import { pushError, pushToast } from '../toast' import { announceTasks } from '../todos/bus' @@ -102,6 +103,10 @@ export interface ChatPrefs { totemsInChat?: boolean /** What sending does while a reply runs: wait its turn or steer the reply. Ctrl/⌘ does the other. */ followUp?: 'queue' | 'steer' + /** Claude's auto-compact window: '' for Claude's default, else 100,000–1,000,000 (chat/context.mjs). */ + autoCompactWindow?: string + /** What an idle Claude chat of 200k tokens or more does when its prompt cache goes cold (T3's Compact idle threads). */ + compactIdle?: 'onReturn' | 'beforeCacheExpires' | 'off' } // A file the bridge sent here to be shown (chat/files.mjs, chatFileRedirect). @@ -198,7 +203,11 @@ function withOutbox(threads: ChatThread[], sending: Set = new Set()): Ch const t = out[i] // It did get through (the response was what got lost): nothing to keep. const lastUser = [...t.messages].reverse().find((m) => m.role === 'user') - if (lastUser && sameText(lastUser.content, e.message.content, !!t.summary) && (lastUser.createdAt || 0) >= e.at - 60_000) { outboxDrop(id); continue } + const recent = !!lastUser && (lastUser.createdAt || 0) >= e.at - 60_000 + // Or it got through as a `/compact` (Compact and send), or was queued behind a run (one of those, or the bridge's own idle compaction). + const queued = (t.queue || []).some((q) => !q.id.startsWith('local-') && (q.createdAt || 0) >= e.at - 60_000 && sameText(q.text, e.message.content, false)) + const compacting = !!e.args.compactFirst && recent && isCompactionTurn(lastUser) + if ((recent && sameText(lastUser!.content, e.message.content, !!t.summary)) || compacting || queued) { outboxDrop(id); continue } if (!t.messages.some((m) => m.id === e.message.id)) out[i] = { ...t, messages: [...t.messages.filter((m) => !m.unsent), unsent] } } return out @@ -1160,7 +1169,9 @@ function handleEvent(threadId: string, e: StreamEvent) { const ui = ai - 1 if (msgs[ai]?.role === 'assistant' && msgs[ai].status === 'streaming') { const live = msgs[ai] - msgs[ai] = { ...e.assistantMessage, parts: live.parts?.length ? live.parts : e.assistantMessage.parts, content: live.content || e.assistantMessage.content } + // Compact and send's stand-in divider gives way to the bridge's own (same compaction, real id). + const kept = (live.parts || []).filter((p) => !(p.type === 'compaction' && p.id.startsWith('local-'))) + msgs[ai] = { ...e.assistantMessage, parts: kept.length ? kept : e.assistantMessage.parts, content: live.content || e.assistantMessage.content } if (msgs[ui]?.role === 'user') msgs[ui] = e.userMessage } else { msgs.push(e.userMessage, e.assistantMessage) @@ -1179,6 +1190,8 @@ function handleEvent(threadId: string, e: StreamEvent) { case 'approval': case 'inbox': case 'visual': + case 'context': + case 'compaction': case 'delta': case 'tool': case 'agent': @@ -1202,7 +1215,8 @@ function handleEvent(threadId: string, e: StreamEvent) { case 'done': patchAssistant(threadId, (m) => ({ ...e.message, parts: e.message.parts?.length ? e.message.parts : m.parts })) // The bridge marks it waiting on him too; this shows it without a sync. - if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) + // Not after a compaction (`/compact`, context.ts): housekeeping is nothing to read. + if (e.message.status !== 'stopped') patchThread(threadId, (t) => (t.totemId || isCompactionTurn(t.messages[t.messages.findIndex((m) => m.id === e.message.id) - 1]) ? t : { ...t, needsReply: true, ...(t.snoozedUntil && t.snoozedUntil > now() ? { snoozedUntil: now() } : {}) })) break case 'error': patchAssistant(threadId, (m) => ({ ...m, status: 'error', error: e.text })) @@ -1285,6 +1299,8 @@ export interface SendInput { projectContextOff?: boolean /** A new chat started from a task, linked to it from the first turn. */ taskId?: string + /** "Compact and send" (context.ts): the chat compacts first and the message waits right behind it. */ + compactFirst?: boolean } /** Start a turn. Returns the thread id (new chats get one here). */ @@ -1304,12 +1320,19 @@ export function send(input: SendInput): string { } const wire = wireModel(row?.driver || 'cursor', settings) const t0 = now() - const userMessage: ChatMessage = { - id: `local-${newId()}`, role: 'user', content: input.text, createdAt: t0, - ...(input.attachments?.length ? { attachments: input.attachments } : {}), - ...(input.voice ? { voice: true } : {}), + // Compact and send: what shows at once is the compaction, with his message waiting behind it. + const compactFirst = !!thread && !!input.compactFirst + const userMessage: ChatMessage = compactFirst + ? { id: `local-${newId()}`, role: 'user', content: '/compact', command: 'compact', createdAt: t0 } + : { + id: `local-${newId()}`, role: 'user', content: input.text, createdAt: t0, + ...(input.attachments?.length ? { attachments: input.attachments } : {}), + ...(input.voice ? { voice: true } : {}), + } + const assistant: ChatMessage = { + id: `local-${newId()}`, role: 'assistant', content: '', status: 'streaming', provider, createdAt: t0, + parts: compactFirst ? [{ type: 'compaction', id: `local-${newId()}`, status: 'running', trigger: 'onReturn', startedAt: t0 }] : [], } - const assistant: ChatMessage = { id: `local-${newId()}`, role: 'assistant', content: '', parts: [], status: 'streaming', provider, createdAt: t0 } const contextOff = !!projectId && !thread && !!input.projectContextOff const taskId = !thread && input.taskId ? input.taskId : undefined if (!thread) { @@ -1319,7 +1342,8 @@ export function send(input: SendInput): string { messages: [], createdAt: t0, updatedAt: t0, ...(kind === 'temporary' ? { expiresAt: endOfToday() } : {}), } } - upsertThread({ ...thread, messages: [...thread.messages, userMessage, assistant], updatedAt: t0 }) + const queue = compactFirst ? [{ id: `local-${newId()}`, text: input.text, attachments: input.attachments || [], createdAt: t0 }, ...(thread.queue || [])] : thread.queue + upsertThread({ ...thread, messages: [...thread.messages, userMessage, assistant], updatedAt: t0, ...(compactFirst ? { queue } : {}) }) const args: SendArgs = { threadId, text: input.text, attachments: (input.attachments || []).map((a) => a.id), provider, // The bridge keeps this model only when the turn runs on `provider`; a @@ -1330,9 +1354,14 @@ export function send(input: SendInput): string { ...(projectId ? { projectId } : {}), ...(contextOff ? { projectContextOff: true } : {}), ...(taskId ? { taskId } : {}), + ...(compactFirst ? { compactFirst: true } : {}), } const { messages: _m, needsReply: _n, keepUnread: _k, ...meta } = thread - outboxPut(threadId, { args, message: userMessage, thread: { ...meta, updatedAt: t0 }, at: t0 }) + // Unsent, Retry and Discard work on what he wrote; a compact-first send carries it in its args. + const unsentAs: ChatMessage = compactFirst + ? { id: userMessage.id, role: 'user', content: input.text, createdAt: t0, ...(input.attachments?.length ? { attachments: input.attachments } : {}) } + : userMessage + outboxPut(threadId, { args, message: unsentAs, thread: { ...meta, updatedAt: t0 }, at: t0 }) return startRun(threadId, args) } @@ -1358,6 +1387,8 @@ export function discardUnsent(threadId: string): string { const e = readOutbox()[threadId] outboxDrop(threadId) if (!e) return '' + // Compact and send: what he wrote is the message, not the compaction shown for it. + if (e.args.compactFirst) patchThread(threadId, (t) => ({ ...t, queue: (t.queue || []).filter((q) => !q.id.startsWith('local-')) })) patchThread(threadId, (t) => ({ ...t, messages: t.messages.filter((m) => m.id !== e.message.id) })) if (!state.threads.find((t) => t.id === threadId)?.messages.length) set((s) => ({ threads: s.threads.filter((t) => t.id !== threadId) })) return e.message.content @@ -1381,11 +1412,14 @@ function startRun(threadId: string, args: SendArgs) { const reason = navigator.onLine === false ? 'You were offline' : networkText(err) box.message.sendError = reason outboxPut(threadId, box) + // Compact and send shows what he wrote, not the compaction that was to run first. + const local = (m: ChatMessage) => (m.parts || []).every((p) => p.type === 'compaction' && p.id.startsWith('local-')) patchThread(threadId, (t) => ({ ...t, + ...(box.args.compactFirst ? { queue: (t.queue || []).filter((q) => !q.id.startsWith('local-')) } : {}), messages: t.messages - .filter((m) => !(m.role === 'assistant' && m.status === 'streaming' && !m.content && !(m.parts || []).length)) - .map((m) => (m.id === box.message.id ? { ...m, unsent: true, sendError: reason } : m)), + .filter((m) => !(m.role === 'assistant' && m.status === 'streaming' && !m.content && local(m))) + .map((m) => (m.id === box.message.id ? { ...box.message, unsent: true, sendError: reason } : m)), })) setRun(threadId, null) return diff --git a/web/src/chat/types.ts b/web/src/chat/types.ts index c56546c..1316af0 100644 --- a/web/src/chat/types.ts +++ b/web/src/chat/types.ts @@ -189,7 +189,43 @@ export interface InboxPart { * bridge adds on the way out; it serves the page sandboxed. */ export interface VisualPart { type: 'visual'; id: string; uploadId: string; title: string; height: number; url?: string } -export type Part = TextPart | ImagePart | ToolPart | FilePart | TotemProposalPart | ChangePart | SteerPart | QuestionsPart | ApprovalPart | InboxPart | VisualPart +/** + * The context was compacted here (chat/context.mjs on the bridge): the CLI's own + * compaction mid-reply (`auto`), a `/compact` the owner sent (`manual`), or one + * Totem ran for an idle chat (`onReturn`, `beforeCacheExpires`). A divider. + */ +export interface CompactionPart { + type: 'compaction' + id: string + status: 'running' | 'done' | 'failed' | 'stopped' + trigger: 'auto' | 'manual' | 'onReturn' | 'beforeCacheExpires' + before?: number + after?: number + reason?: string + startedAt?: number + endedAt?: number +} +export type Part = TextPart | ImagePart | ToolPart | FilePart | TotemProposalPart | ChangePart | SteerPart | QuestionsPart | ApprovalPart | InboxPart | VisualPart | CompactionPart + +/** + * How full the context window was after a reply's last request (chat/context.mjs): + * the request's prompt plus its output, never the reply's billed total. + * `max` is absent when the window is unknown; `autoCompactAt` only when Claude's + * compaction point is set below the window; `cacheExpiresAt` when Claude said + * how long its prompt cache lasts. + */ +export interface ContextUsage { + used: number + max?: number + input?: number + cached?: number + output?: number + autoCompactAt?: number + cacheTtlMs?: number + cacheExpiresAt?: number + /** When the reading arrived. */ + at: number +} export interface ChatMessage { id: string @@ -215,6 +251,10 @@ export interface ChatMessage { effort?: string /** What the CLI reported for this reply (chat/stats.mjs); absent = not reported. */ stats?: TurnStatsData + /** How full the context window is after this reply (chat/context.mjs). */ + context?: ContextUsage + /** A user message that is `/compact`: the turn is drawn as its divider, never as a message. */ + command?: 'compact' /** A totem's scheduled run, posted to its chat. */ run?: { trigger: string; status: string; notified: boolean } /** The owner's decision on, or reply about, an inbox proposal (the bridge wrote this message). */ @@ -408,6 +448,8 @@ export type StreamEvent = | { type: 'approval'; approval: Partial & { id: string }; seq: number } | { type: 'inbox'; inbox: Partial & { id: string }; seq: number } | { type: 'visual'; visual: { id: string; uploadId: string; title: string; height: number; url?: string }; seq: number } + | { type: 'context'; context: ContextUsage; seq: number } + | { type: 'compaction'; compaction: Partial & { id: string }; seq: number } | { type: 'activity'; text: string; seq: number } | { type: 'title'; title: string; icon?: string; seq: number } | { type: 'done'; message: ChatMessage; seq: number } diff --git a/web/src/chat/workFold.ts b/web/src/chat/workFold.ts index 5d2edd0..f8c6d9c 100644 --- a/web/src/chat/workFold.ts +++ b/web/src/chat/workFold.ts @@ -55,7 +55,8 @@ export function foldWork(list: B[], set list.forEach((b, i) => { const folds = i <= last && (b.kind === 'tools' || (b.kind === 'text' && isCommentary((b as unknown as { text: string }).text))) if (!folds) { - if (b.kind === 'text') close() + // Text, or a compaction divider, ends the run of steps before it. + if (b.kind === 'text' || b.kind === 'compaction') close() out.push(b) return } diff --git a/web/src/components/ChatSettings.tsx b/web/src/components/ChatSettings.tsx index bf9b0e0..eaed91a 100644 --- a/web/src/components/ChatSettings.tsx +++ b/web/src/components/ChatSettings.tsx @@ -4,7 +4,8 @@ import { visibleModels, EFFORT_LABELS } from '../chat/models' import { pushError } from '../toast' import { SettingsPage, SettingsRow, SettingsSection, Switch } from './settings/ui' -// Settings → Chat: what sending does mid-reply, when quiet chats settle, whether +// Settings → Chat: what sending does mid-reply, how long chats keep their context +// (T3 Code's Compact idle threads and Claude's auto-compact window), when quiet chats settle, whether // chats bring in totems, and who writes chat titles ("Pick for me" keeps Totem's // own rule). The chat's colour glow is a device setting, under Appearance. @@ -75,6 +76,47 @@ export default function ChatSettings({ onNavigate }: { onNavigate?: (section: st /> + + save({ compactIdle: e.target.value as ChatPrefs['compactIdle'] })}> + + + + + } + /> + { + const v = e.target.value.replace(/[,_\s]/g, '') + if (v === (prefs.autoCompactWindow ?? '')) return + if (v && !/^(?:[1-9]\d{5}|1000000)$/.test(v)) { + pushError('Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude’s default.') + e.target.value = prefs.autoCompactWindow ? Number(prefs.autoCompactWindow).toLocaleString('en-US') : '' + return + } + void save({ autoCompactWindow: v }) + }} + onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur() }} + /> + } + /> + + s.prefs.followUp ?? 'queue') + // Compact idle threads → When you return (context.ts): an idle Claude chat whose + // prompt cache went cold offers to compact before the next send. Keep is per send. + const compactIdle = useChat((s) => s.prefs.compactIdle) + const [keepHistory, setKeepHistory] = useState(false) + useEffect(() => { setKeepHistory(false) }, [activeId]) + const compactTokens = active && !pending ? compactBeforeSendTokens({ + thread: active, provider: choice.provider, claude: providerById(choice.provider)?.driver === 'claude', + setting: compactIdle, text: input, idle: !busy, now: Date.now(), + }) : null const queue = active?.queue || [] // A queued message being edited in the composer, and the draft it displaced. const [queueEdit, setQueueEdit] = useState<{ id: string; threadId: string; draftKey: string; stash: { text: string; attachments: Attachment[] } } | null>(null) @@ -585,7 +597,9 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane return ok } const onQueue = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : activeId ? queueMessage(activeId, p.text, p.attachments) : false) - const onSteerNow = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : activeId ? steer(activeId, p.text, p.attachments.map((a) => a.id)) : false) + // A `/compact` running cannot take words mid-way: they wait behind it (T3). + const compactingNow = busy && isCompactionTurn(messages[messages.length - 2]) + const onSteerNow = (p: FollowUpPayload) => (waitingApproval ? declineWith(p) : !activeId ? false : compactingNow ? queueMessage(activeId, p.text, p.attachments) : steer(activeId, p.text, p.attachments.map((a) => a.id))) const saveQueueEdit = async (p: FollowUpPayload) => { if (!queueEdit) return false const ok = await updateQueue(queueEdit.threadId, { action: 'edit', id: queueEdit.id, text: p.text, attachments: p.attachments.map((a) => a.id) }) @@ -644,8 +658,12 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane }) const destinations = useMemo(() => ({ projectId: scopeProject?.id ?? null, taskId: draftTaskId, onPick: pickDestination }), [scopeProject?.id, draftTaskId, pickDestination]) + // How full this chat's context is on the account it would send on (context.ts). + const contextShown = active && !empty ? contextSnapshot(latestContext(messages, choice.provider)) : null const composerEl = ( : null} + compactSend={compactTokens != null ? { tokens: compactTokens, keep: keepHistory, onToggle: () => setKeepHistory((k) => !k) } : null} rightSlot={
{/* T3 Code's chip: the model and its effort as one control, whose picker also diff --git a/web/src/components/settings/searchIndex.ts b/web/src/components/settings/searchIndex.ts index 2f3cd7f..8e880f3 100644 --- a/web/src/components/settings/searchIndex.ts +++ b/web/src/components/settings/searchIndex.ts @@ -32,6 +32,8 @@ const ENTRIES: Partial> = { ], chat: [ ['follow-up', 'While a reply is running', 'Sending', 'queue steer follow-up enter'], + ['compact-idle', 'Compact idle threads', 'Context', 'compaction context window cache summarize tokens'], + ['auto-compact', 'Auto-compact after', 'Context', 'compaction context window tokens claude'], ['auto-settle', 'Settle quiet chats', 'Chat list', 'archive settled days'], ['totems-in-chat', 'Let chats bring in totems', 'Totems', 'group totem agents'], ['titles', 'Name chats automatically', 'Titles', 'thread title naming'],