From 3a83e6ba84377b973a03d119be16116882748961 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:10:26 +0000 Subject: [PATCH 01/74] fix(ide): global focus-visible ring and 4.5:1 text tokens in both themes (#515) Add one zero-specificity :focus-visible ring from the accent token (Monaco and xterm internals excluded) and drop the bare outline:none rules that left crumbs, sashes, menu items, viewers, the debug console input and the diff and extension panes with only a hover tint (1.04-1.19:1). Darken light accent, ok, crit and warn, lighten dark muted, crit and symbol, and deepen the debug status bar so every text role clears 4.5:1 on chrome, panel, editor, raised, hover and active. designTokens.test.ts now measures every text token on every surface in both themes and fails on outline removal outside an allow-list. --- apps/ide/src/renderer/debug/debug.css | 1 - .../src/renderer/extensions/extensions.css | 1 - .../src/renderer/extensions/webviewHost.ts | 2 +- apps/ide/src/renderer/git/scm.css | 1 - apps/ide/src/renderer/styles.css | 34 ++++--- apps/ide/src/renderer/viewers/viewers.css | 2 +- apps/ide/test/designTokens.test.ts | 97 +++++++++++++++++++ 7 files changed, 119 insertions(+), 19 deletions(-) diff --git a/apps/ide/src/renderer/debug/debug.css b/apps/ide/src/renderer/debug/debug.css index 68ade709..a4863a68 100644 --- a/apps/ide/src/renderer/debug/debug.css +++ b/apps/ide/src/renderer/debug/debug.css @@ -129,7 +129,6 @@ body.is-debugging .status-bar { background: var(--status-debug); } min-width: 0; padding: 3px 0; border: 0; - outline: 0; background: none; color: var(--fg); font: var(--fs-sm) var(--font-mono); diff --git a/apps/ide/src/renderer/extensions/extensions.css b/apps/ide/src/renderer/extensions/extensions.css index 933d87c9..77938eff 100644 --- a/apps/ide/src/renderer/extensions/extensions.css +++ b/apps/ide/src/renderer/extensions/extensions.css @@ -31,7 +31,6 @@ .extension-busy, .extension-installed-mark { font-size: var(--fs-sm); } .extension-details { grid-area: editor; z-index: 39; display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--editor); overflow: auto; } -.extension-details:focus { outline: none; } .extension-details-loading { margin: 24px; } .extension-details-head { display: flex; gap: 20px; align-items: flex-start; padding: 20px 24px 16px; border-bottom: 1px solid var(--line); } .extension-details-title { flex: 1; min-width: 0; } diff --git a/apps/ide/src/renderer/extensions/webviewHost.ts b/apps/ide/src/renderer/extensions/webviewHost.ts index 6cf70c86..8f105b72 100644 --- a/apps/ide/src/renderer/extensions/webviewHost.ts +++ b/apps/ide/src/renderer/extensions/webviewHost.ts @@ -74,7 +74,7 @@ export function webviewTheme(root: HTMLElement = document.documentElement): { ki '--vscode-editor-font-weight': 'normal', '--vscode-foreground': fg, '--vscode-descriptionForeground': muted, - '--vscode-errorForeground': token('--crit', '#f85149'), + '--vscode-errorForeground': token('--crit', '#f96962'), '--vscode-focusBorder': accent, '--vscode-editor-background': editor, '--vscode-editor-foreground': fg, diff --git a/apps/ide/src/renderer/git/scm.css b/apps/ide/src/renderer/git/scm.css index 71d2c28f..88948ed5 100644 --- a/apps/ide/src/renderer/git/scm.css +++ b/apps/ide/src/renderer/git/scm.css @@ -96,7 +96,6 @@ flex-direction: column; background: var(--editor); } -.scm-diff:focus { outline: none; } .scm-diff-header { display: flex; align-items: center; diff --git a/apps/ide/src/renderer/styles.css b/apps/ide/src/renderer/styles.css index d38a49c4..7a211351 100644 --- a/apps/ide/src/renderer/styles.css +++ b/apps/ide/src/renderer/styles.css @@ -19,9 +19,10 @@ --line-strong: #314050; --hover: #1b2430; --active: #213041; - /* Text. */ + /* Text. O13: every text role clears 4.5:1 on every surface, --hover and --active + included, in both themes (test/designTokens.test.ts measures it). */ --fg: #d5dce5; - --muted: #8a96a5; + --muted: #8d99a7; /* Roles. */ --accent: #2fb0ff; /* Filled buttons and badges: white text needs a deeper blue than the accent (4.5:1). */ @@ -29,13 +30,13 @@ --button-hover: #0d7cbf; --on-accent: #ffffff; --ok: #3fb950; - --crit: #f85149; + --crit: #f96962; --warn: #d29922; --on-warn: #1b1300; - --symbol: #b180d7; + --symbol: #b384d8; --status: #0b3a5c; --status-fg: #e6f3fc; - --status-debug: #b8541b; + --status-debug: #b0511a; /* Debugger marks, the same in both themes, as in VS Code. */ --breakpoint: #e51400; --debug-frame: #ffcc00; @@ -89,13 +90,13 @@ --active: #dbe6f1; --fg: #1c2632; --muted: #596677; - --accent: #0073bd; + --accent: #0068ac; --button-bg: #0073bd; --button-hover: #0067a8; --on-accent: #ffffff; - --ok: #1a7f37; - --crit: #cf222e; - --warn: #9a6700; + --ok: #187432; + --crit: #c4202c; + --warn: #895c00; --on-warn: #ffffff; --symbol: #6f42c1; --status: #0073bd; @@ -125,6 +126,11 @@ html, body, #app { height: 100%; margin: 0; } scrollbar-color: var(--line-strong) transparent; } +/* O13: one keyboard focus ring for everything. Zero specificity (:where), so a component + that draws its own ring or signals focus another way still wins; Monaco and xterm keep + their own focus handling (their hidden textareas must never draw a ring). */ +:where(:focus-visible:not(.monaco-editor *, .xterm *)) { outline: 1px solid var(--accent); outline-offset: -1px; } + body { background: var(--editor); color: var(--fg); @@ -345,7 +351,7 @@ body { font: inherit; cursor: pointer; } -.crumb:hover, .crumb:focus-visible { color: var(--fg); background: var(--hover); outline: none; } +.crumb:hover, .crumb:focus-visible { color: var(--fg); background: var(--hover); } .crumb:last-child { color: var(--fg); } .crumb-separator { flex: none; width: 12px; height: 12px; fill: none; stroke: var(--muted); stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; } .explorer-body { padding: 0 0 8px; } @@ -492,7 +498,7 @@ body { .editor-split-sash + .editor-group { border-left: 1px solid var(--line); } .editor-split-sash { flex: none; position: relative; z-index: 2; width: 6px; margin: 0 -3px; cursor: ew-resize; } .editor-split-sash[hidden] { display: none; } -.editor-split-sash:hover, .editor-split-sash:active, .editor-split-sash:focus-visible { background: var(--accent); opacity: 0.5; outline: none; } +.editor-split-sash:hover, .editor-split-sash:active, .editor-split-sash:focus-visible { background: var(--accent); opacity: 0.5; } /* With two groups, only the active one keeps the accent under its selected tab. */ .editor-area.is-split .editor-group:not(.is-active-group) .editor-tab[aria-selected='true'] { box-shadow: none; color: var(--muted); } /* A tab dragged over the other group's strip. */ @@ -601,7 +607,7 @@ body { touch-action: none; } .sash[hidden] { display: none; } -.sash:hover, .sash:active, .sash:focus-visible { background: var(--accent); opacity: 0.5; outline: none; } +.sash:hover, .sash:active, .sash:focus-visible { background: var(--accent); opacity: 0.5; } .sash-side { grid-area: side; justify-self: end; width: 6px; margin-right: -3px; cursor: ew-resize; } /* The scene is a native view over its slot: the sash stays on the editor's side of the border. */ .sash-scene { grid-area: scene; justify-self: start; width: 6px; margin-left: -5px; cursor: ew-resize; } @@ -1147,7 +1153,7 @@ input[type='checkbox'], input[type='radio'] { accent-color: var(--button-bg); } cursor: pointer; } .terminal-menu-item[role='menuitemradio'] { justify-content: flex-start; } -.terminal-menu-item:hover, .terminal-menu-item:focus-visible { background: var(--hover); outline: none; } +.terminal-menu-item:hover, .terminal-menu-item:focus-visible { background: var(--hover); } .terminal-menu-check { width: 12px; color: var(--accent); font-size: var(--fs-2xs); } .terminal-menu-row { display: flex; align-items: center; padding-right: 8px; } .terminal-menu-row .terminal-menu-item { flex: 1; min-width: 0; } @@ -1444,7 +1450,7 @@ input[type='checkbox'], input[type='radio'] { accent-color: var(--button-bg); } text-align: left; cursor: pointer; } -.context-menu-item:hover:not(:disabled), .context-menu-item:focus-visible { background: var(--hover); outline: none; } +.context-menu-item:hover:not(:disabled), .context-menu-item:focus-visible { background: var(--hover); } .context-menu-item:disabled { color: var(--muted); cursor: default; } .context-menu-key { color: var(--muted); font-size: var(--fs-sm); white-space: nowrap; } .context-menu-separator { height: 1px; margin: 4px 0; background: var(--line); } diff --git a/apps/ide/src/renderer/viewers/viewers.css b/apps/ide/src/renderer/viewers/viewers.css index c83748a8..050c5af8 100644 --- a/apps/ide/src/renderer/viewers/viewers.css +++ b/apps/ide/src/renderer/viewers/viewers.css @@ -21,7 +21,7 @@ .viewer-separator { width: 1px; height: 16px; margin: 0 6px; background: var(--line); } .viewer-zoom { min-width: 40px; text-align: center; font-variant-numeric: tabular-nums; } .viewer-info { font-variant-numeric: tabular-nums; } -.viewer-scroll { flex: 1; min-height: 0; overflow: auto; outline: none; } +.viewer-scroll { flex: 1; min-height: 0; overflow: auto; } .viewer-scroll[hidden], .viewer-message[hidden] { display: none; } .viewer-message { flex: 1; display: grid; place-items: center; padding: 24px; text-align: center; } .viewer-find { display: flex; align-items: center; gap: 2px; } diff --git a/apps/ide/test/designTokens.test.ts b/apps/ide/test/designTokens.test.ts index d8ce0c67..30ca4861 100644 --- a/apps/ide/test/designTokens.test.ts +++ b/apps/ide/test/designTokens.test.ts @@ -84,4 +84,101 @@ describe('design tokens (visual polish V1)', () => { const hits = scan(/Consolas|Menlo/); assert.deepEqual(hits, [], report(hits)); }); + + it('gives every text token 4.5:1 on every surface it is drawn on, in both themes (O13)', () => { + const failures: string[] = []; + for (const [theme, tokens] of Object.entries(themeTokens())) { + const pairs: Array<[string, string]> = [ + ...TEXT_TOKENS.flatMap((text) => SURFACES.map((surface): [string, string] => [text, surface])), + ...FILLED_PAIRS, + ]; + for (const [text, background] of pairs) { + const fg = tokens[text]; + const bg = tokens[background]; + assert.ok(fg && bg, `${theme}: ${text} or ${background} is not declared`); + const ratio = contrast(fg, bg); + if (ratio < 4.5) { + failures.push(`${theme}: ${text} ${fg} on ${background} ${bg} = ${ratio.toFixed(2)}:1`); + } + } + } + assert.deepEqual(failures, [], failures.join('\n')); + }); + + it('draws a global focus-visible ring from the accent token (O13)', () => { + const css = withoutComments(readFileSync(join(RENDERER, 'styles.css'), 'utf8')); + const rule = /(^|\n)\s*(:where\(:focus-visible[^{]*\)|:focus-visible)\s*\{([^}]*)\}/.exec(css); + assert.ok(rule, 'no global :focus-visible rule in styles.css'); + assert.match(rule[3], /outline:\s*1px solid var\(--accent\)/); + // Monaco and xterm focus hidden textareas; a ring there would draw over the editor or terminal. + assert.match(rule[2], /:not\([^)]*\.monaco-editor \*[^)]*\.xterm \*/); + }); + + it('never removes the focus outline without a replacement (O13)', () => { + const hits: Hit[] = []; + for (const file of cssFiles(RENDERER)) { + const css = withoutComments(readFileSync(file, 'utf8')); + for (const match of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + const [, selector, body] = match; + if (!/outline(-style)?:\s*(none|0)\b/.test(body)) {continue;} + const name = selector.trim().replace(/\s+/g, ' '); + if (OUTLINE_ALLOWED.some((allowed) => allowed.test(name))) {continue;} + const line = css.slice(0, match.index + match[0].indexOf(body)).split('\n').length; + hits.push({ file: relative(RENDERER, file), line, text: name }); + } + } + assert.deepEqual(hits, [], report(hits)); + }); }); + +/** Text roles drawn straight on the workbench surfaces. */ +const TEXT_TOKENS = ['--fg', '--muted', '--accent', '--ok', '--crit', '--warn', '--symbol']; +/** Every surface those roles land on: frames, editor, raised cards, hovered and selected rows. */ +const SURFACES = ['--chrome', '--panel', '--editor', '--raised', '--hover', '--active']; +/** Filled controls: their own foreground on their own fill. */ +const FILLED_PAIRS: Array<[string, string]> = [ + ['--on-accent', '--button-bg'], + ['--on-accent', '--button-hover'], + ['--on-warn', '--warn'], + ['--status-fg', '--status'], + ['--status-fg', '--status-debug'], +]; + +/** + * Rules that may drop the outline because the element signals focus some other + * way, which the comment names. + */ +const OUTLINE_ALLOWED: RegExp[] = [ + // Text inputs that already carry an accent border (focus is the caret plus that border). + /^\.tree-input$/, /^\.tab-rename$/, /^\.quick-input-field$/, + /^\.terminal-find-input:focus$/, /^\.keybinding-recorder:focus$/, + // Fields inside a wrapper that turns its border accent on :focus-within. + /^\.af-input:focus$/, /^\.af-option \.af-select:focus$/, +]; + +/** The colour tokens of each theme: the dark `:root` block, overlaid by the light media query. */ +function themeTokens(): Record<'dark' | 'light', Record> { + const css = withoutComments(readFileSync(join(RENDERER, 'styles.css'), 'utf8')); + const blocks = [...css.matchAll(/:root\s*\{([^}]*)\}/g)].map((match) => match[1]); + const lightAt = css.indexOf('@media (prefers-color-scheme: light)'); + const lightBlock = [...css.slice(lightAt).matchAll(/:root\s*\{([^}]*)\}/g)][0]?.[1]; + assert.ok(blocks.length >= 2 && lightBlock, 'both theme blocks are found'); + const parse = (block: string): Record => Object.fromEntries( + [...block.matchAll(/(--[\w-]+):\s*(#[0-9a-f]{6})\s*;/gi)].map((match) => [match[1], match[2].toLowerCase()]), + ); + const dark = parse(blocks[0]); + return { dark, light: { ...dark, ...parse(lightBlock) } }; +} + +function luminance(hex: string): number { + const channel = (offset: number): number => { + const value = Number.parseInt(hex.slice(offset, offset + 2), 16) / 255; + return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; + }; + return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5); +} + +function contrast(a: string, b: string): number { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +} From 318f77faa3da2c18473757f098f34950637cdc62 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:10:43 +0000 Subject: [PATCH 02/74] fix(ide): keep the sidecar alive on errors nobody caught (#503) Log unhandled rejections and uncaught exceptions to the IDE log and the Output panel instead of letting Node end the process (which closed the app), catch rejected promises from RPC notification handlers, and report failures of the Open Recent / Clear Recently Opened menu actions. --- apps/ide/src/main/menu.ts | 14 +++- apps/ide/src/sidecar/crashGuard.ts | 45 +++++++++++++ apps/ide/src/sidecar/index.ts | 4 ++ apps/ide/src/sidecar/rpc.ts | 11 +++- apps/ide/test/sidecarCrashGuard.test.ts | 88 +++++++++++++++++++++++++ 5 files changed, 157 insertions(+), 5 deletions(-) create mode 100644 apps/ide/src/sidecar/crashGuard.ts create mode 100644 apps/ide/test/sidecarCrashGuard.test.ts diff --git a/apps/ide/src/main/menu.ts b/apps/ide/src/main/menu.ts index e4bdd1c4..cc8c9cc6 100644 --- a/apps/ide/src/main/menu.ts +++ b/apps/ide/src/main/menu.ts @@ -8,6 +8,7 @@ import { menuTemplate } from './menuTemplate.ts'; import { t } from '../shared/i18n/i18n.ts'; import { clearRecentFolders, openRecentFromMenu } from './workspace/workspaceWindows.ts'; import { checkForUpdates } from './updates/updateCheck.ts'; +import { log } from './log.ts'; /** What Help > About shows of the IDE's dependencies (#161), set once the core runs. */ export interface AboutDependencies { @@ -172,14 +173,23 @@ function recentSubmenu(folders: readonly string[]): MenuItemConstructorOptions[] label: folder, click: (_item, win) => { const target = win instanceof BrowserWindow ? win : BrowserWindow.getFocusedWindow(); - if (target) { void openRecentFromMenu(target, folder); } + if (target) { openRecentFromMenu(target, folder).catch(reportMenuFailure(t('menu.openRecent'), target)); } }, })), { type: 'separator' }, - { label: t('menu.clearRecent'), click: () => void clearRecentFolders() }, + { label: t('menu.clearRecent'), click: (_item, win) => void clearRecentFolders().catch(reportMenuFailure(t('menu.clearRecent'), win instanceof BrowserWindow ? win : undefined)) }, ]; } +/** O1 (#503): a menu action that fails says so (log, Output panel, a dialog) instead of becoming an unhandled rejection. */ +function reportMenuFailure(action: string, win: BrowserWindow | undefined): (error: unknown) => void { + return (error) => { + log.error(`${action} failed.`, error); + const options = { type: 'error' as const, title: action, message: error instanceof Error ? error.message : String(error) }; + (win ? dialog.showMessageBox(win, options) : dialog.showMessageBox(options)).catch(() => undefined); + }; +} + /** Menu commands the renderer runs (it owns the editors and their unsaved state). */ function sendCommand(win: unknown, command: IdeCommand): void { const target = win instanceof BrowserWindow ? win : BrowserWindow.getFocusedWindow(); diff --git a/apps/ide/src/sidecar/crashGuard.ts b/apps/ide/src/sidecar/crashGuard.ts new file mode 100644 index 00000000..a9c2ecc8 --- /dev/null +++ b/apps/ide/src/sidecar/crashGuard.ts @@ -0,0 +1,45 @@ +/** + * O1 (#503): the sidecar outlives an error nobody caught. + * + * Node's default for an unhandled rejection or an uncaught exception is to + * end the process, and the Rust core closes the app when its sidecar ends + * (src-tauri/src/sidecar.rs): one background task that failed (a menu + * click, a notification handler) took every unsaved editor with it. Here + * both are reported (the IDE's log, so the terminal and the Output panel) + * and the process keeps running. + * + * Pure apart from the target it is given, so a test can run it in a child + * process of its own. + */ + +export type CrashReport = (message: string, error: unknown) => void; + +/** What the guard listens on: `process`, or a stand-in in a test. */ +export interface CrashGuardTarget { + on(event: 'unhandledRejection' | 'uncaughtException', listener: (reason: unknown) => void): unknown; +} + +/** After this many reports the guard stops writing: a failing loop must not flood the log. */ +export const CRASH_REPORT_LIMIT = 50; + +export function installCrashGuard(target: CrashGuardTarget, report: CrashReport): void { + let reporting = false; + let reported = 0; + const handle = (message: string) => (reason: unknown): void => { + // A report that itself fails (stderr gone: EPIPE) would come straight back here. + if (reporting || reported >= CRASH_REPORT_LIMIT) { + return; + } + reporting = true; + reported += 1; + try { + report(reported === CRASH_REPORT_LIMIT ? `${message} (further errors are not reported)` : message, reason); + } catch { + // Nowhere left to report to; staying alive is what matters. + } finally { + reporting = false; + } + }; + target.on('unhandledRejection', handle('A background task failed and nothing handled it; the IDE keeps running.')); + target.on('uncaughtException', handle('An unexpected error was not caught; the IDE keeps running.')); +} diff --git a/apps/ide/src/sidecar/index.ts b/apps/ide/src/sidecar/index.ts index 9c1c814c..8615ffca 100644 --- a/apps/ide/src/sidecar/index.ts +++ b/apps/ide/src/sidecar/index.ts @@ -10,6 +10,7 @@ import { APP_ORIGIN, buildContentSecurityPolicy, trustedOrigins } from '../main/ import { BENCH_FLAG } from '../main/bench.ts'; import { SMOKE_FLAG } from '../main/smoke.ts'; import { log } from '../main/log.ts'; +import { installCrashGuard } from './crashGuard.ts'; /** * The Node sidecar (#482, epic #477). @@ -28,6 +29,9 @@ import { log } from '../main/log.ts'; * 100 ms on Linux. */ +// O1 (#503): an error nobody caught is logged (terminal, Output panel) instead of ending the app. +installCrashGuard(process, (message, error) => log.error(message, error)); + // out/sidecar/index.cjs, beside out/main, out/extensionHost and out/renderer. const OUT_DIR = path.resolve(__dirname, '..'); const MAIN_WINDOW = 'main'; diff --git a/apps/ide/src/sidecar/rpc.ts b/apps/ide/src/sidecar/rpc.ts index 95900521..163be60b 100644 --- a/apps/ide/src/sidecar/rpc.ts +++ b/apps/ide/src/sidecar/rpc.ts @@ -27,7 +27,8 @@ interface RpcMessage { } export type RequestHandler = (params: unknown) => unknown; -export type NotificationHandler = (params: unknown) => void; +/** May return a promise: its rejection is caught and logged like a throw (O1, #503). */ +export type NotificationHandler = (params: unknown) => unknown; export interface RpcTransport { /** Writes one message (no newline). */ @@ -124,10 +125,14 @@ export class RpcPeer { this.onLog(`No handler for the notification ${method}.`); return; } + const failed = (error: unknown): void => this.onLog(`The notification ${method} failed: ${String(error)}`); try { - handler(params); + const result = handler(params); + if (result instanceof Promise) { + result.catch(failed); + } } catch (error) { - this.onLog(`The notification ${method} failed: ${String(error)}`); + failed(error); } } diff --git a/apps/ide/test/sidecarCrashGuard.test.ts b/apps/ide/test/sidecarCrashGuard.test.ts new file mode 100644 index 00000000..5b825b3f --- /dev/null +++ b/apps/ide/test/sidecarCrashGuard.test.ts @@ -0,0 +1,88 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { EventEmitter } from 'node:events'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { CRASH_REPORT_LIMIT, installCrashGuard } from '../src/sidecar/crashGuard.ts'; +import { RpcPeer } from '../src/sidecar/rpc.ts'; + +const GUARD_URL = pathToFileURL(path.resolve(import.meta.dirname, '../src/sidecar/crashGuard.ts')).href; + +describe('the sidecar survives errors nobody caught (O1, #503)', () => { + it('logs a notification handler that returns a rejected promise, and one that throws', async () => { + const logged: string[] = []; + const peer = new RpcPeer({ write: () => {} }, (message) => logged.push(message)); + peer.onNotification('menu.click', async () => { + await Promise.resolve(); + throw new Error('the dialog failed'); + }); + peer.onNotification('window.event', () => { + throw new Error('sync failure'); + }); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown): void => { + unhandled.push(reason); + }; + process.on('unhandledRejection', onUnhandled); + try { + peer.receive('{"jsonrpc":"2.0","method":"menu.click","params":{"id":"x"}}'); + peer.receive('{"jsonrpc":"2.0","method":"window.event","params":{}}'); + await new Promise((resolve) => setTimeout(resolve, 10)); + } finally { + process.off('unhandledRejection', onUnhandled); + } + assert.deepEqual(unhandled, []); + assert.deepEqual(logged.sort(), [ + 'The notification menu.click failed: Error: the dialog failed', + 'The notification window.event failed: Error: sync failure', + ]); + }); + + it('reports both kinds of error, survives a failing reporter and stops after the limit', () => { + const target = new EventEmitter(); + const reports: Array<{ message: string; error: unknown }> = []; + let throwOnce = true; + installCrashGuard(target, (message, error) => { + reports.push({ message, error }); + if (throwOnce) { + throwOnce = false; + throw new Error('stderr is gone'); + } + }); + const rejection = new Error('rejected'); + target.emit('unhandledRejection', rejection); + target.emit('uncaughtException', new Error('thrown')); + assert.equal(reports.length, 2); + assert.equal(reports[0]?.error, rejection); + assert.match(reports[0]?.message ?? '', /keeps running/); + assert.match(reports[1]?.message ?? '', /not caught/); + for (let index = 0; index < CRASH_REPORT_LIMIT + 10; index++) { + target.emit('unhandledRejection', new Error(`flood ${index}`)); + } + assert.equal(reports.length, CRASH_REPORT_LIMIT); + assert.match(reports.at(-1)?.message ?? '', /further errors are not reported/); + }); + + it('keeps a real Node process alive after an unhandled rejection and an uncaught exception', async () => { + const script = [ + `import { installCrashGuard } from ${JSON.stringify(GUARD_URL)};`, + 'installCrashGuard(process, (message, error) => process.stderr.write(`${message} ${String(error)}\\n`));', + "void Promise.reject(new Error('background task'));", + "setTimeout(() => { throw new Error('timer'); }, 0);", + "setTimeout(() => { process.stdout.write('alive'); process.exit(0); }, 100);", + ].join('\n'); + const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { + execFile(process.execPath, ['--experimental-strip-types', '--no-warnings', '--input-type=module', '-e', script], { timeout: 10_000 }, (error, out, err) => { + if (error) { + reject(new Error(`${error.message}\n${err}`)); + } else { + resolve({ stdout: out, stderr: err }); + } + }); + }); + assert.equal(stdout, 'alive'); + assert.match(stderr, /background task/); + assert.match(stderr, /timer/); + }); +}); From ff3c0bfd91c23b2cc92141d2ec0c110ba00c80bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:11:24 +0000 Subject: [PATCH 03/74] fix(ide): never overwrite a malformed or externally edited settings.json (#504) A user-scope change now re-reads settings.json first, so edits made outside the IDE are kept, and refuses with a clear error (shown by the renderer's 'Could not change the setting' notification) when the file does not parse, leaving it untouched. User changes are serialized. --- apps/ide/src/main/settings/settingsService.ts | 27 ++++++++++++++++--- apps/ide/test/settings.test.ts | 26 ++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/apps/ide/src/main/settings/settingsService.ts b/apps/ide/src/main/settings/settingsService.ts index ae35420a..cf8e3fe5 100644 --- a/apps/ide/src/main/settings/settingsService.ts +++ b/apps/ide/src/main/settings/settingsService.ts @@ -9,7 +9,8 @@ import type { Workspace } from '../workspace/workspace.ts'; /** * Settings storage (#18, part 2). The user's settings are one JSON file in - * the IDE's user-data folder, read once and kept in memory; the folder's are + * the IDE's user-data folder, kept in memory and read again before each + * change (O2, #504); the folder's are * `.codexr/settings.json` in the open folder, read through the workspace * (so its path checks apply) every time they are asked for, which is how an * edit made in the editor takes effect. Writes keep keys this version does @@ -78,6 +79,7 @@ function applyChange(raw: Record, key: string, value: unknown): export class SettingsService { private userRaw: Record = {}; private userError: string | null = null; + private userWrites: Promise = Promise.resolve(); private readonly loaded: Promise; private readonly storage: SettingsStorage; @@ -119,8 +121,7 @@ export class SettingsService { throw new Error('Unknown setting.'); } if (scope === 'user') { - this.userRaw = applyChange(this.userRaw, key, value); - await this.storage.write(formatSettingsFile(this.userRaw)); + await this.updateUser(key, value); } else if (scope === 'folder') { if (settingDefinition(key)?.userOnly) { throw new Error('This setting can only be set for the user.'); @@ -139,6 +140,26 @@ export class SettingsService { return this.snapshot(workspace); } + /** + * O2 (#504): a user-scope change starts from the file on disk (an edit made + * outside the IDE is kept) and refuses to write over a file that does not + * parse: its contents would read as {} and the rest of the user's settings + * would be lost. Changes run one at a time, so each sees the one before. + */ + private updateUser(key: string, value: unknown): Promise { + const run = this.userWrites.catch(() => undefined).then(async () => { + await this.reloadUser(); + if (this.userError) { + throw new Error(`The setting was not changed: ${this.userError}. Fix settings.json and try again.`); + } + const next = applyChange(this.userRaw, key, value); + await this.storage.write(formatSettingsFile(next)); + this.userRaw = next; + }); + this.userWrites = run; + return run; + } + /** Creates the folder's settings file if needed and returns its workspace path, for the editor. */ async ensureFolderFile(workspace: Workspace): Promise { if ((await readFolderFile(workspace)) === null) { diff --git a/apps/ide/test/settings.test.ts b/apps/ide/test/settings.test.ts index 6ff93fe7..d7296adc 100644 --- a/apps/ide/test/settings.test.ts +++ b/apps/ide/test/settings.test.ts @@ -92,6 +92,32 @@ describe('SettingsService (#18)', () => { await assert.rejects(service.update(workspace, 'folder', 'editor.tabSize', 2)); assert.equal(fs.readFileSync(path.join(root, '.codexr', 'settings.json'), 'utf8'), '{ broken'); }); + + it('refuses to write over a malformed user file and leaves it untouched (O2, #504)', async () => { + const malformed = '{ "a": 1 "b": 2 }'; + const storage = memoryStorage(malformed); + const service = new SettingsService(storage); + await assert.rejects(service.update(null, 'user', 'editor.fontSize', 17), /not changed.*could not be read.*Fix settings\.json/s); + assert.equal(await storage.read(), malformed); + // Fixed outside the IDE: the next change goes through, from the fixed file. + await storage.write('{ "a": 1, "b": 2 }'); + const report = await service.update(null, 'user', 'editor.fontSize', 17); + assert.deepEqual(report.errors, []); + assert.deepEqual(JSON.parse((await storage.read()) ?? ''), { a: 1, b: 2, 'editor.fontSize': 17 }); + }); + + it('starts each user change from the file on disk, keeping outside edits (O2, #504)', async () => { + const storage = memoryStorage('{ "editor.tabSize": 8 }'); + const service = new SettingsService(storage); + await service.snapshot(null); + await storage.write('{ "editor.tabSize": 8, "future.setting": true }'); + await Promise.all([service.update(null, 'user', 'editor.fontSize', 17), service.update(null, 'user', 'editor.wordWrap', 'on')]); + assert.deepEqual(JSON.parse((await storage.read()) ?? ''), { 'editor.tabSize': 8, 'future.setting': true, 'editor.fontSize': 17, 'editor.wordWrap': 'on' }); + // A malformed file written meanwhile is never overwritten, even though the service read a good one before. + await storage.write('{ broken'); + await assert.rejects(service.update(null, 'user', 'editor.fontSize', 12)); + assert.equal(await storage.read(), '{ broken'); + }); }); describe('Settings view rows (#18)', () => { From 2767e27acbdf82cd6dac748f5218b4900a98284f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:12:12 +0000 Subject: [PATCH 04/74] ci(ide): rust-cache, unit tests before the Rust build, cargo fmt job (#516) Replace the registry-only cache with Swatinem/rust-cache (target/ of apps/ide/src-tauri, one shared key per OS) in ide-tauri.yml and the installers action. Run the legacy-shell gate and unit tests before any Rust, and only on pushes: on pull requests ci.yml's npm test already runs both on the same three systems. Keep cargo test in the release profile so it reuses the build's dependencies. Add a Linux cargo fmt --check job and rustfmt.toml (sources not reformatted here). Drop the stale claude/project-thread-urap9o push trigger from ide-bench.yml and cache the pinned baseline's sizes per OS. --- .../actions/ide-tauri-installers/action.yml | 14 +++-- .github/workflows/ide-bench.yml | 25 +++++---- .github/workflows/ide-tauri.yml | 52 ++++++++++++++----- apps/ide/src-tauri/rustfmt.toml | 2 + 4 files changed, 60 insertions(+), 33 deletions(-) create mode 100644 apps/ide/src-tauri/rustfmt.toml diff --git a/.github/actions/ide-tauri-installers/action.yml b/.github/actions/ide-tauri-installers/action.yml index 5632c4dd..0c2cee1a 100644 --- a/.github/actions/ide-tauri-installers/action.yml +++ b/.github/actions/ide-tauri-installers/action.yml @@ -28,15 +28,13 @@ runs: shell: bash run: rustup toolchain install stable --profile minimal && rustup default stable - - name: Cargo registry cache - uses: actions/cache@v4 + # target/ plus the registry and git checkouts (O14 #516); the same key per OS as the + # `tauri` job of ide-tauri.yml, which builds the same release profile. + - name: Rust cache + uses: Swatinem/rust-cache@v2 with: - path: | - ~/.cargo/registry/index - ~/.cargo/registry/cache - ~/.cargo/git/db - key: cargo-registry-${{ runner.os }}-${{ hashFiles('apps/ide/src-tauri/Cargo.lock') }} - restore-keys: cargo-registry-${{ runner.os }}- + workspaces: apps/ide/src-tauri -> target + shared-key: ide-tauri-${{ runner.os }} # The pinned Node runtime (scripts/bundledNode.mjs): checked against its pinned SHA-256 # whether it comes from the cache or from nodejs.org. diff --git a/.github/workflows/ide-bench.yml b/.github/workflows/ide-bench.yml index 45cd0498..dbb357e4 100644 --- a/.github/workflows/ide-bench.yml +++ b/.github/workflows/ide-bench.yml @@ -7,7 +7,7 @@ name: IDE benchmark # It is the yardstick of the desktop-shell migration (Electron to Tauri, epic in # docs/ide/tauri-migration.md): the same driver and the same numbers before and # after. Not a gate: runners are noisy, so it only reports (job summary + JSON -# artifact). Runs on a manual dispatch and on pull requests that touch it. +# artifact). Runs on a manual dispatch and on pull requests to `ide` that touch it. # # R13 (#491) removed Electron from the tree. The "before" side is now the last commit # that had it, BASELINE_SHA below, checked out next to the working tree and built there @@ -28,16 +28,6 @@ on: - 'apps/ide/scripts/benchCompare.mjs' - 'apps/ide/scripts/tauri.mjs' - 'apps/ide/src-tauri/**' - push: - branches: - - 'claude/project-thread-urap9o' - paths: - - '.github/workflows/ide-bench.yml' - - 'apps/ide/scripts/bench.mjs' - - 'apps/ide/scripts/benchSizes.mjs' - - 'apps/ide/scripts/benchCompare.mjs' - - 'apps/ide/scripts/tauri.mjs' - - 'apps/ide/src-tauri/**' permissions: contents: read @@ -76,19 +66,32 @@ jobs: with: ref: ${{ env.BASELINE_SHA }} + # The baseline is a pinned commit, so its sizes on one OS never change: measured once, + # then restored (O14 #516). After the checkout, whose clean would delete the file. + - name: Cached baseline sizes + id: sizes-cache + uses: actions/cache@v4 + with: + path: apps/ide/bench-sizes-electron-${{ runner.os }}.json + key: ide-bench-electron-sizes-${{ env.BASELINE_SHA }}-${{ runner.os }} + - name: Setup Node + if: steps.sizes-cache.outputs.cache-hit != 'true' uses: actions/setup-node@v4 with: node-version-file: .nvmrc cache: npm - name: Install + if: steps.sizes-cache.outputs.cache-hit != 'true' run: npm ci - name: Build the installers + if: steps.sizes-cache.outputs.cache-hit != 'true' run: npm run dist --workspace=code-xr-ide - name: Sizes + if: steps.sizes-cache.outputs.cache-hit != 'true' run: node apps/ide/scripts/benchSizes.mjs --label=electron --out=apps/ide/bench-sizes-electron-${{ runner.os }}.json - name: Summary diff --git a/.github/workflows/ide-tauri.yml b/.github/workflows/ide-tauri.yml index d1f2b19d..a284453a 100644 --- a/.github/workflows/ide-tauri.yml +++ b/.github/workflows/ide-tauri.yml @@ -4,9 +4,13 @@ name: IDE on Tauri # built and tested on the three operating systems on every pull request and every push to # the IDE branches: # -# - the legacy-shell gate (apps/ide/scripts/legacyShellGate.mjs, R13 #491); -# - the Rust core: cargo clippy -D warnings and cargo test (release profile, as built); -# - the IDE's unit tests (Node's runner, as in ci.yml's gate); +# - the legacy-shell gate (apps/ide/scripts/legacyShellGate.mjs, R13 #491) and the IDE's unit +# tests, on pushes only and BEFORE the Rust build, so a TypeScript failure costs a minute, not +# a build: on pull requests ci.yml's `npm test` already runs both on the same three systems +# (O14 #516); +# - the Rust core: cargo clippy -D warnings and cargo test (release profile, reusing the +# release build's dependencies), with target/ and the registry cached by Swatinem/rust-cache; +# - cargo fmt --check (job `rustfmt`, Linux only: formatting does not depend on the system); # - the smoke run (apps/ide/scripts/smoke.mjs): the probes run inside the real page through # the core (no WebDriver, which macOS lacks), plus the native menu, the message box path # and the profile migration's "no trace in a smoke run"; @@ -88,9 +92,16 @@ jobs: - name: Install run: npm ci + # O14 (#516): on pull requests ci.yml's `npm test` runs these two on all three systems; + # pushes to ide and claude/** have no ci.yml run, so they run here, before any Rust. - name: Legacy-shell gate (R13 #491) + if: github.event_name != 'pull_request' run: node apps/ide/scripts/legacyShellGate.mjs + - name: Unit tests + if: github.event_name != 'pull_request' + run: npm run test:unit --workspace=code-xr-ide + - name: Tauri system libraries (Linux) if: runner.os == 'Linux' run: | @@ -106,15 +117,13 @@ jobs: - name: Rust toolchain run: rustup toolchain install stable --profile minimal --component clippy && rustup default stable - - name: Cargo registry cache - uses: actions/cache@v4 + # target/ plus the registry and git checkouts, keyed on the toolchain and Cargo.lock. + # One key per OS, shared with the installers action (the same release profile). + - name: Rust cache + uses: Swatinem/rust-cache@v2 with: - path: | - ~/.cargo/registry/index - ~/.cargo/registry/cache - ~/.cargo/git/db - key: cargo-registry-${{ runner.os }}-${{ hashFiles('apps/ide/src-tauri/Cargo.lock') }} - restore-keys: cargo-registry-${{ runner.os }}- + workspaces: apps/ide/src-tauri -> target + shared-key: ide-tauri-${{ runner.os }} - name: Build (web, sidecar, bridges, Rust core) run: npm run build --workspace=code-xr-ide @@ -123,13 +132,12 @@ jobs: working-directory: apps/ide/src-tauri run: cargo clippy --release --locked --all-targets -- -D warnings + # --release on purpose: the dependencies are already compiled in that profile by the build + # above, so only the test harness is new; a debug `cargo test` would rebuild all of them. - name: cargo test working-directory: apps/ide/src-tauri run: cargo test --release --locked - - name: Unit tests - run: npm run test:unit --workspace=code-xr-ide - # A session bus of its own, as on a desktop: the runner's systemd user bus activates # portals that cannot reach the virtual display, and GTK waits 25 s + 2 x 5 s on them # at start-up (#480). No GPU render node on the runner: WebKitGTK's DMA-BUF renderer off @@ -182,6 +190,22 @@ jobs: shell: bash run: CODEXR_NODE="$(node -p process.execPath)" node --experimental-strip-types --no-warnings apps/ide/scripts/extensionCompat.mjs --built "$(ls apps/vscode-extension/artifacts/*.vsix | head -n 1)" + # Formatting only (apps/ide/src-tauri/rustfmt.toml). No system libraries, no build. + rustfmt: + name: cargo fmt --check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Rust toolchain + run: rustup toolchain install stable --profile minimal --component rustfmt && rustup default stable + + - name: cargo fmt --check + working-directory: apps/ide/src-tauri + run: cargo fmt --check + installers: name: installers (${{ matrix.os }}) if: github.event_name != 'pull_request' diff --git a/apps/ide/src-tauri/rustfmt.toml b/apps/ide/src-tauri/rustfmt.toml new file mode 100644 index 00000000..40d36bf9 --- /dev/null +++ b/apps/ide/src-tauri/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 160 +use_small_heuristics = "Max" From 543da95e7354decb87e833a8af15d2243641594a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:13:44 +0000 Subject: [PATCH 05/74] perf(ide): drop the Monaco contributions the IDE never uses from the renderer (#518) --- apps/ide/scripts/viteConfigs.mjs | 68 ++++++++++++++++++++++- apps/ide/test/monacoContributions.test.ts | 54 ++++++++++++++++++ 2 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 apps/ide/test/monacoContributions.test.ts diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 1328369d..bbc04b16 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -137,6 +137,72 @@ function withoutMonacoLspClient() { }; } +/** + * #518: Monaco's entry (`monaco-editor` → esm/vs/index.js) imports every editor + * contribution for its side effect, and so does esm/vs/internal/common/workers.js, + * which the CSS, HTML, JSON and TypeScript modes load: both are stripped (strip + * only the entry and the modes bring all of it back in a chunk of their own). + * These the IDE never uses: no inline + * completion provider is registered anywhere (renderer or extension host), the + * GPU renderer, middle-click scrolling, placeholder text, section headers and the + * floating menu are off by default and never turned on, and the standalone + * actions (Inspect Tokens, the high-contrast toggle, the iPad keyboard button, + * in-place replace, the long-lines and line-terminator prompts, the inline + * progress bar) are not reachable from the IDE. JavaScriptCore parses the whole + * chunk on every launch with no code cache, so they are dropped from the entry. + * A module another contribution imports still comes in through that import (part + * of the inline-completion model does, through suggest and hover): only the + * side-effect line goes. The colour picker stays (CSS files use it). + */ +export const MONACO_CONTRIBUTION_HOSTS = /monaco-editor[\\/]esm[\\/]vs[\\/](?:index|internal[\\/]common[\\/]workers)\.js$/; +/** Paths under monaco-editor/esm/vs/. */ +export const MONACO_UNUSED_CONTRIBUTIONS = [ + 'editor/contrib/floatingMenu/browser/floatingMenu.contribution.js', + 'editor/contrib/gpu/browser/gpuActions.js', + 'editor/contrib/inlineCompletions/browser/inlineCompletions.contribution.js', + 'editor/contrib/inlineProgress/browser/inlineProgress.js', + 'editor/contrib/inPlaceReplace/browser/inPlaceReplace.js', + 'editor/standalone/browser/inspectTokens/inspectTokens.js', + 'editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.js', + 'editor/contrib/longLinesHelper/browser/longLinesHelper.js', + 'editor/contrib/middleScroll/browser/middleScroll.contribution.js', + 'editor/contrib/placeholderText/browser/placeholderText.contribution.js', + 'editor/contrib/sectionHeaders/browser/sectionHeaders.js', + 'editor/standalone/browser/toggleHighContrast/toggleHighContrast.js', + 'editor/contrib/unusualLineTerminators/browser/unusualLineTerminators.js', +]; + +/** + * Drops the side-effect imports of MONACO_UNUSED_CONTRIBUTIONS from one of the + * MONACO_CONTRIBUTION_HOSTS (`import './editor/…';` in index.js, + * `import '../../editor/…';` in internal/common/workers.js). Throws when one is + * missing, so a Monaco upgrade that renames a contribution fails the build + * instead of quietly shipping it again. + * @param {string} code @param {string} [file] named in the error + */ +export function stripUnusedMonacoContributions(code, file = 'monaco-editor') { + let stripped = code; + for (const contribution of MONACO_UNUSED_CONTRIBUTIONS) { + const line = [`import './${contribution}';`, `import '../../${contribution}';`].find((candidate) => stripped.includes(candidate)); + if (!line) { + throw new Error(`${file} no longer imports ${contribution}: update MONACO_UNUSED_CONTRIBUTIONS (scripts/viteConfigs.mjs).`); + } + stripped = stripped.replace(line, ''); + } + return stripped; +} + +function withoutUnusedMonacoContributions() { + return { + name: 'codexr-without-unused-monaco-contributions', + enforce: 'pre', + transform(code, id) { + const file = id.split('?')[0]; + return MONACO_CONTRIBUTION_HOSTS.test(file) ? { code: stripUnusedMonacoContributions(code, file), map: null } : null; + }, + }; +} + /** @param {{ dev?: boolean }} [opts] */ export function rendererConfig(opts = {}) { return { @@ -151,7 +217,7 @@ export function rendererConfig(opts = {}) { target: RENDERER_TARGETS, sourcemap: false, }, - plugins: [withoutMonacoLspClient()], + plugins: [withoutMonacoLspClient(), withoutUnusedMonacoContributions()], // #173/#178: the pure, dependency-free metric logic of the core is // shared with the VS Code extension; the rest of the core stays in the sidecar. resolve: { alias: [ diff --git a/apps/ide/test/monacoContributions.test.ts b/apps/ide/test/monacoContributions.test.ts new file mode 100644 index 00000000..de5dffc7 --- /dev/null +++ b/apps/ide/test/monacoContributions.test.ts @@ -0,0 +1,54 @@ +// #518: the Monaco contributions the IDE never uses, dropped from the renderer +// bundle by a `pre` plugin (scripts/viteConfigs.mjs), like the LSP client (#499). +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +// @ts-expect-error -- a build script in plain JavaScript, no declarations +import { MONACO_CONTRIBUTION_HOSTS, MONACO_UNUSED_CONTRIBUTIONS, stripUnusedMonacoContributions } from '../scripts/viteConfigs.mjs'; + +const IDE_ROOT = path.resolve(import.meta.dirname, '..'); +const MONACO_VS = path.resolve(IDE_ROOT, '..', '..', 'node_modules', 'monaco-editor', 'esm', 'vs'); +const contributions = MONACO_UNUSED_CONTRIBUTIONS as string[]; +const strip = stripUnusedMonacoContributions as (code: string, file?: string) => string; + +function sources(dir: string): string[] { + return fs.readdirSync(path.join(IDE_ROOT, dir), { recursive: true }).map(String).filter((name) => name.endsWith('.ts')).map((name) => path.join(dir, name)); +} + +describe('Unused Monaco contributions (#518)', () => { + it('strips both files that import every contribution, and only those', () => { + assert.ok(MONACO_CONTRIBUTION_HOSTS.test('/repo/node_modules/monaco-editor/esm/vs/index.js')); + assert.ok(MONACO_CONTRIBUTION_HOSTS.test('C:\\repo\\node_modules\\monaco-editor\\esm\\vs\\internal\\common\\workers.js')); + assert.ok(!MONACO_CONTRIBUTION_HOSTS.test('/repo/node_modules/monaco-editor/esm/vs/editor/editor.api.js')); + assert.ok(!MONACO_CONTRIBUTION_HOSTS.test('/repo/node_modules/monaco-editor/esm/vs/languages/definitions/css/register.js')); + }); + + for (const host of ['index.js', path.join('internal', 'common', 'workers.js')]) { + it(`drops every listed contribution from the installed ${host} and keeps the rest`, () => { + const code = fs.readFileSync(path.join(MONACO_VS, host), 'utf8'); + const stripped = strip(code, host); + for (const contribution of contributions) { + assert.ok(code.includes(contribution), `${host} imports ${contribution}`); + assert.ok(!stripped.includes(contribution), `${contribution} left in ${host}`); + } + // The colour picker (CSS files), suggest, hover and find stay. + for (const kept of ['colorPicker/browser/colorPickerContribution.js', 'suggest/browser/suggestController.js', 'hover/browser/hoverContribution.js', 'find/browser/findController.js']) { + assert.ok(stripped.includes(kept), `${kept} kept`); + } + const imports = (text: string): number => (text.match(/^import '/gm) ?? []).length; + assert.equal(imports(code) - imports(stripped), contributions.length); + }); + } + + it('fails the build when Monaco renames a contribution', () => { + assert.throws(() => strip("import './editor/contrib/folding/browser/folding.js';\n", 'index.js'), /index\.js no longer imports editor\/contrib\/floatingMenu/); + }); + + it('drops nothing the IDE uses: no inline completion provider and no option turning a dropped one on', () => { + for (const file of [...sources('src/renderer'), ...sources('src/extensionHost')]) { + const code = fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); + assert.doesNotMatch(code, /registerInlineCompletion|inlineSuggest\s*:|experimentalGpuAcceleration|mouseMiddleClickAction|showMarkSectionHeaders|showRegionSectionHeaders/, file); + } + }); +}); From ad33860f26af12c38691248f6dc3bba54755ef32 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:17:17 +0000 Subject: [PATCH 06/74] fix(ide): wait for the services to stop before the IDE exits (#505) stopServices now awaits terminals, MCP servers, agent chats, language servers, extension hosts and debug sessions together (allSettled, capped at 2.5 s, within the core's 3 s) and logs any that fail or overrun. The sidecar's will-quit event gains waitUntil, and app.exit is only requested once the handed-over shutdown has settled. --- apps/ide/src/main/boot.ts | 44 ++++++++++++++++++++++-------- apps/ide/src/main/shutdown.ts | 40 +++++++++++++++++++++++++++ apps/ide/src/sidecar/session.ts | 5 ++-- apps/ide/src/sidecar/tauriHost.ts | 25 ++++++++++++----- apps/ide/test/shutdown.test.ts | 45 +++++++++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 19 deletions(-) create mode 100644 apps/ide/src/main/shutdown.ts create mode 100644 apps/ide/test/shutdown.test.ts diff --git a/apps/ide/src/main/boot.ts b/apps/ide/src/main/boot.ts index 78d75e78..0dafcd9e 100644 --- a/apps/ide/src/main/boot.ts +++ b/apps/ide/src/main/boot.ts @@ -28,6 +28,7 @@ import { startAgents, type AgentServices } from './agents/agentsRuntime.ts'; import { startAgentSessions, type AgentSessionsRuntime } from './agentSessions/agentSessionsRuntime.ts'; import { createLspHost, type LspHost } from './lsp/lspHost.ts'; import { stopAllDebugSessions } from './debug/debugHost.ts'; +import { SHUTDOWN_GRACE_MS, settleWithin, type SettleOutcome } from './shutdown.ts'; /** * The IDE's boot sequence (#482), run by the Node sidecar @@ -71,14 +72,35 @@ let agentSessions: AgentSessionsRuntime | null = null; // #21: so do the language servers. let languageServers: LspHost | null = null; -/** Stops what the services started; both shells call it when the app quits. */ -export function stopServices(): void { - void terminals?.killAll(); - void agentServices?.mcp.closeAll(); - void agentSessions?.service.stopAll(); - void languageServers?.stopAll(); - // #180: debug sessions end their adapter and their program. - void stopAllDebugSessions(); +// #259: and the extension hosts. +let extensionHosts: ExtensionHostManager | null = null; + +/** + * Stops what the services started when the app quits. O3 (#505): resolves + * once every service has stopped, or after `SHUTDOWN_GRACE_MS`, never + * rejects; the sidecar waits for it before it asks the core to exit. + */ +export async function stopServices(): Promise { + const services: ReadonlyArray unknown]> = [ + ['terminals', () => terminals?.killAll()], + ['MCP servers', () => agentServices?.mcp.closeAll()], + // AF1: their chats are written on the way out. + ['agent chats', () => agentSessions?.service.stopAll()], + ['language servers', () => languageServers?.stopAll()], + ['extension hosts', () => extensionHosts?.stopAll()], + // #180: debug sessions end their adapter and their program. + ['debug sessions', () => stopAllDebugSessions()], + ]; + const outcome = await settleWithin(services.map(([, stop]) => stop), SHUTDOWN_GRACE_MS); + outcome.results.forEach((result, index) => { + const name = services[index]?.[0] ?? 'a service'; + if (result.status === 'rejected') { + log.warn(`Stopping the ${name} failed: ${String(result.reason)}`); + } else if (result.status === 'pending') { + log.warn(`The ${name} did not stop within ${SHUTDOWN_GRACE_MS} ms; the IDE exits anyway.`); + } + }); + return outcome; } /** Everything before the first window: services, IPC handlers, theme, language, menu. */ @@ -138,9 +160,9 @@ export async function startServices(options: BootOptions): Promise extensionHosts.register(handle)); - app.on('will-quit', () => void extensionHosts.stopAll()); + const hostManager = new ExtensionHostManager({ service: extensions, hostScript: options.extensionHostPath, isDevelopment }); + extensionHosts = hostManager; + extensions.attachHost((handle) => hostManager.register(handle)); registerIpcHandlers(options.origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp, agentSessions, extensions, options.nativeChannels); const userSettings = (await settings.snapshot(null)).effective; // #171: the stored theme, before the first window paints. diff --git a/apps/ide/src/main/shutdown.ts b/apps/ide/src/main/shutdown.ts new file mode 100644 index 00000000..617b5f69 --- /dev/null +++ b/apps/ide/src/main/shutdown.ts @@ -0,0 +1,40 @@ +/** + * O3 (#505): the services' shutdown is waited for, within a cap. + * + * Language servers, the extension hosts, the coding agents (whose chats are + * written on the way out), MCP servers and debug adapters all stop + * asynchronously. The sidecar used to ask the core to end the app 250 ms + * after `will-quit`, whatever they were doing; now it waits until every one + * has settled or the cap has passed, whichever is first. + */ + +/** How long the app waits for its services before it exits anyway. */ +export const SHUTDOWN_GRACE_MS = 2500; + +export interface SettleOutcome { + /** One result per task, in order; a task still running at the cap is `pending`. */ + readonly results: ReadonlyArray | { readonly status: 'pending' }>; + readonly timedOut: boolean; +} + +/** + * Waits for every task to settle (a rejection or a synchronous throw never + * cuts the wait short), but no longer than `capMs`. Never rejects. + */ +export function settleWithin(tasks: ReadonlyArray<() => unknown>, capMs: number): Promise { + const results: Array | { readonly status: 'pending' }> = tasks.map(() => ({ status: 'pending' })); + const running = tasks.map((task, index) => + Promise.resolve() + .then(task) + .then( + (value: unknown) => { results[index] = { status: 'fulfilled', value }; }, + (reason: unknown) => { results[index] = { status: 'rejected', reason }; }, + )); + return new Promise((resolve) => { + const timer = setTimeout(() => resolve({ results: [...results], timedOut: true }), capMs); + void Promise.all(running).then(() => { + clearTimeout(timer); + resolve({ results: [...results], timedOut: false }); + }); + }); +} diff --git a/apps/ide/src/sidecar/session.ts b/apps/ide/src/sidecar/session.ts index a0756013..4fa00aab 100644 --- a/apps/ide/src/sidecar/session.ts +++ b/apps/ide/src/sidecar/session.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import fs from 'node:fs'; import type { RpcPeer } from './rpc.ts'; -import { app, dialog, openIpc, type TauriBrowserWindow } from './tauriHost.ts'; +import { app, dialog, openIpc, type QuitEvent, type TauriBrowserWindow } from './tauriHost.ts'; import { secretsNoticeBox, type SecretsNotice } from './profileMigration.ts'; import { afterFirstWindow, startServices, stopServices, type BootOptions } from '../main/boot.ts'; import { withLocale } from '../main/displayLanguage.ts'; @@ -77,7 +77,8 @@ export async function runSession(start: SessionStart): Promise { createRecentFolders: coreRecentFolders, }; const loadedUrl = await start.attached; - app.on('will-quit', stopServices); + // O3 (#505): the exit waits for the services to stop (capped). + app.on('will-quit', (event: QuitEvent) => event.waitUntil(stopServices())); app.on('window-all-closed', () => app.quit()); const services = await startServices(bootOptions); diff --git a/apps/ide/src/sidecar/tauriHost.ts b/apps/ide/src/sidecar/tauriHost.ts index 16d88e28..93066e1c 100644 --- a/apps/ide/src/sidecar/tauriHost.ts +++ b/apps/ide/src/sidecar/tauriHost.ts @@ -32,6 +32,7 @@ import { decodeValue, encodeValue, type Base64 } from '../shared/jsonCodec.ts'; import { aboutPanel, menuNodes, type MenuTemplateItem } from './menuModel.ts'; import { messageBoxRequest, messageBoxResult, type MessageBoxOptions } from './messageBox.ts'; import { SCENE_OPEN_IN_EDITOR_CHANNEL, sceneEvalScript, toSceneBridgeMessage } from '../shared/sceneBridge.ts'; +import { SHUTDOWN_GRACE_MS, settleWithin } from '../main/shutdown.ts'; import { WEBVIEW_EVAL_RESULT_CHANNEL, toWebviewEvalResult, webviewEvalScript } from '../shared/webviewEval.ts'; // -- The core connection ------------------------------------------------------- @@ -104,6 +105,12 @@ function readVersion(): string { } } +/** What `will-quit` handlers get: `waitUntil` delays the exit until the task settles (capped, O3 #505). */ +export interface QuitEvent { + preventDefault(): void; + waitUntil(task: Promise): void; +} + type PathName = 'userData' | 'appData' | 'temp' | 'home' | 'logs' | 'sessionData'; class TauriApp extends EventEmitter { @@ -184,12 +191,18 @@ class TauriApp extends EventEmitter { } this.quitting = true; this.emit('before-quit'); - this.emit('will-quit', { preventDefault: () => {} }); - // The services stop their children asynchronously: give them a moment. - setTimeout(() => { - void hostRequest('app.exit', { code }).catch(() => undefined).finally(() => process.exit(code)); - }, 250).unref(); - setTimeout(() => process.exit(code), 3000).unref(); + // O3 (#505): handlers hand their asynchronous shutdown over with `waitUntil`; the core is asked + // to end the app once all of it has settled, or after SHUTDOWN_GRACE_MS. The other handlers + // still get the moment they always had. + const stopping: Promise[] = []; + const event: QuitEvent = { preventDefault: () => {}, waitUntil: (task) => { stopping.push(task); } }; + this.emit('will-quit', event); + void Promise.all([settleWithin(stopping.map((task) => () => task), SHUTDOWN_GRACE_MS), new Promise((resolve) => setTimeout(resolve, 250))]) + .then(() => hostRequest('app.exit', { code })) + .catch(() => undefined) + .finally(() => process.exit(code)); + // Whatever happens to the request, the process ends. + setTimeout(() => process.exit(code), SHUTDOWN_GRACE_MS + 2000).unref(); } /** The about panel options: the About item of the macOS application menu shows them (menu.rs). */ diff --git a/apps/ide/test/shutdown.test.ts b/apps/ide/test/shutdown.test.ts new file mode 100644 index 00000000..2f578944 --- /dev/null +++ b/apps/ide/test/shutdown.test.ts @@ -0,0 +1,45 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { SHUTDOWN_GRACE_MS, settleWithin } from '../src/main/shutdown.ts'; + +const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +describe('services stop before the IDE exits (O3, #505)', () => { + it('waits for a slow service, through a failing and a throwing one', async () => { + let flushed = false; + const slowService = async (): Promise => { + await delay(150); + flushed = true; + return 'chats written'; + }; + const started = Date.now(); + const outcome = await settleWithin([ + slowService, + () => Promise.reject(new Error('language server gone')), + () => { + throw new Error('sync'); + }, + () => undefined, + ], 2000); + assert.ok(Date.now() - started >= 140, 'did not return before the slow service finished'); + assert.equal(flushed, true); + assert.equal(outcome.timedOut, false); + assert.deepEqual(outcome.results.map((result) => result.status), ['fulfilled', 'rejected', 'rejected', 'fulfilled']); + assert.deepEqual(outcome.results[0], { status: 'fulfilled', value: 'chats written' }); + }); + + it('gives up at the cap on a service that never stops', async () => { + const started = Date.now(); + const outcome = await settleWithin([() => new Promise(() => {}), () => delay(10)], 100); + const elapsed = Date.now() - started; + assert.ok(elapsed >= 90 && elapsed < 1000, `returned after ${elapsed} ms`); + assert.equal(outcome.timedOut, true); + assert.deepEqual(outcome.results.map((result) => result.status), ['pending', 'fulfilled']); + }); + + it('returns at once with nothing to stop, and caps within the core\'s three seconds', async () => { + const outcome = await settleWithin([], 1000); + assert.deepEqual(outcome, { results: [], timedOut: false }); + assert.ok(SHUTDOWN_GRACE_MS >= 2000 && SHUTDOWN_GRACE_MS < 3000); + }); +}); From 78c303c9c165b32edb322c780eb6063e3e4e1699 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:18:24 +0000 Subject: [PATCH 07/74] test(ide): strict-null types in the contrast and outline checks (#515) --- apps/ide/test/designTokens.test.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/apps/ide/test/designTokens.test.ts b/apps/ide/test/designTokens.test.ts index 30ca4861..02015733 100644 --- a/apps/ide/test/designTokens.test.ts +++ b/apps/ide/test/designTokens.test.ts @@ -109,9 +109,9 @@ describe('design tokens (visual polish V1)', () => { const css = withoutComments(readFileSync(join(RENDERER, 'styles.css'), 'utf8')); const rule = /(^|\n)\s*(:where\(:focus-visible[^{]*\)|:focus-visible)\s*\{([^}]*)\}/.exec(css); assert.ok(rule, 'no global :focus-visible rule in styles.css'); - assert.match(rule[3], /outline:\s*1px solid var\(--accent\)/); + assert.match(rule[3] ?? '', /outline:\s*1px solid var\(--accent\)/); // Monaco and xterm focus hidden textareas; a ring there would draw over the editor or terminal. - assert.match(rule[2], /:not\([^)]*\.monaco-editor \*[^)]*\.xterm \*/); + assert.match(rule[2] ?? '', /:not\([^)]*\.monaco-editor \*[^)]*\.xterm \*/); }); it('never removes the focus outline without a replacement (O13)', () => { @@ -119,10 +119,15 @@ describe('design tokens (visual polish V1)', () => { for (const file of cssFiles(RENDERER)) { const css = withoutComments(readFileSync(file, 'utf8')); for (const match of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { - const [, selector, body] = match; - if (!/outline(-style)?:\s*(none|0)\b/.test(body)) {continue;} + const selector = match[1] ?? ''; + const body = match[2] ?? ''; + if (!/outline(-style)?:\s*(none|0)\b/.test(body)) { + continue; + } const name = selector.trim().replace(/\s+/g, ' '); - if (OUTLINE_ALLOWED.some((allowed) => allowed.test(name))) {continue;} + if (OUTLINE_ALLOWED.some((allowed) => allowed.test(name))) { + continue; + } const line = css.slice(0, match.index + match[0].indexOf(body)).split('\n').length; hits.push({ file: relative(RENDERER, file), line, text: name }); } @@ -159,15 +164,15 @@ const OUTLINE_ALLOWED: RegExp[] = [ /** The colour tokens of each theme: the dark `:root` block, overlaid by the light media query. */ function themeTokens(): Record<'dark' | 'light', Record> { const css = withoutComments(readFileSync(join(RENDERER, 'styles.css'), 'utf8')); - const blocks = [...css.matchAll(/:root\s*\{([^}]*)\}/g)].map((match) => match[1]); + const blocks = [...css.matchAll(/:root\s*\{([^}]*)\}/g)].map((match) => match[1] ?? ''); const lightAt = css.indexOf('@media (prefers-color-scheme: light)'); const lightBlock = [...css.slice(lightAt).matchAll(/:root\s*\{([^}]*)\}/g)][0]?.[1]; assert.ok(blocks.length >= 2 && lightBlock, 'both theme blocks are found'); const parse = (block: string): Record => Object.fromEntries( - [...block.matchAll(/(--[\w-]+):\s*(#[0-9a-f]{6})\s*;/gi)].map((match) => [match[1], match[2].toLowerCase()]), + [...block.matchAll(/(--[\w-]+):\s*(#[0-9a-f]{6})\s*;/gi)].map((match) => [match[1] ?? '', (match[2] ?? '').toLowerCase()]), ); - const dark = parse(blocks[0]); - return { dark, light: { ...dark, ...parse(lightBlock) } }; + const dark = parse(blocks[0] ?? ''); + return { dark, light: { ...dark, ...parse(lightBlock ?? '') } }; } function luminance(hex: string): number { @@ -179,6 +184,7 @@ function luminance(hex: string): number { } function contrast(a: string, b: string): number { - const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + const hi = Math.max(luminance(a), luminance(b)); + const lo = Math.min(luminance(a), luminance(b)); return (hi + 0.05) / (lo + 0.05); } From 9790140da220dc10fffcb988532857b268e18d34 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:18:24 +0000 Subject: [PATCH 08/74] test(ide): wait on signals instead of sleeps in five timing tests (#516) agentsChat: a barrier that opens when both sub-agents are in flight instead of a 30 ms hold. agentSessions: wait for the permission request before cancelling. watcher: rewrite a probe file until the watch reports it instead of a 300 ms settle (fs.watch has no ready event). extensionHost: await the notification's delivery. lspEdits: mocked timers for the symbol-search debounce. --- apps/ide/test/agentSessions.test.ts | 9 ++++++++- apps/ide/test/agentsChat.test.ts | 11 ++++++++++- apps/ide/test/extensionHost.test.ts | 10 ++++++++-- apps/ide/test/lspEdits.test.ts | 10 +++++++--- apps/ide/test/watcher.test.ts | 9 +++++++-- 5 files changed, 40 insertions(+), 9 deletions(-) diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index 88c237fc..8d77086f 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -545,7 +545,14 @@ describe('AgentSessionService with a fake ACP agent', () => { const created = await service.create(window, ref); const turn = service.prompt(window, created.id, 'perm', []); await waitFor(() => log.prompts.length === 1, 'the prompt'); - await new Promise((resolve) => setTimeout(resolve, 30)); + // O14: wait for the permission request itself, not a 30 ms guess at when it arrives. + let asking = false; + await waitFor(() => { + void service.get(window, created.id).then((state) => { + asking = state.items.some((item) => item.kind === 'permission' && item.outcome === undefined); + }); + return asking; + }, 'the permission request'); await service.cancel(window, created.id); await turn; assert.deepEqual(log.permissionOutcome, { outcome: 'cancelled' }); diff --git a/apps/ide/test/agentsChat.test.ts b/apps/ide/test/agentsChat.test.ts index 5d9659b1..4751a317 100644 --- a/apps/ide/test/agentsChat.test.ts +++ b/apps/ide/test/agentsChat.test.ts @@ -513,6 +513,10 @@ describe('sub-agents (A11)', () => { it('runs two sub-agents in parallel with clean contexts and returns their answers to the supervisor', async () => { let active = 0; let peak = 0; + // O14: a barrier instead of a 30 ms sleep. Each sub-agent holds its reply until both are + // in flight; run one after the other, the first would wait out the guard and peak stay 1. + let bothIn: () => void = () => undefined; + const bothInFlight = new Promise((resolve) => { bothIn = resolve; }); const bodies: Array> = []; const { chat, agent, profiles, provider } = await setup(async (_url, init) => { const body = JSON.parse(String(init.body)) as { messages: Array<{ role: string; content: string }> }; @@ -526,7 +530,12 @@ describe('sub-agents (A11)', () => { } active += 1; peak = Math.max(peak, active); - await new Promise((resolve) => setTimeout(resolve, 30)); + if (active === 2) { + bothIn(); + } + let guard: ReturnType | undefined; + await Promise.race([bothInFlight, new Promise((resolve) => { guard = setTimeout(resolve, 5_000); })]); + clearTimeout(guard); active -= 1; return answer(last?.content === 'review a.ts' ? 'Looks fine.' : 'Three layers.', 10); }, [delegateTaskTool]); diff --git a/apps/ide/test/extensionHost.test.ts b/apps/ide/test/extensionHost.test.ts index 1e6d9bcb..b5000c60 100644 --- a/apps/ide/test/extensionHost.test.ts +++ b/apps/ide/test/extensionHost.test.ts @@ -58,9 +58,15 @@ describe('extension host protocol (#259)', () => { it('delivers notifications and rejects what is pending on dispose', async () => { const [main, host] = pair(); const seen: unknown[] = []; - main.handle('log', (line) => seen.push(line)); + // O14: await the delivery itself, not a 5 ms timer. + const delivered = new Promise((resolve) => { + main.handle('log', (line) => { + seen.push(line); + resolve(); + }); + }); host.notify('log', 'hello'); - await new Promise((resolve) => setTimeout(resolve, 5)); + await delivered; assert.deepEqual(seen, ['hello']); host.handle('slow', () => new Promise(() => undefined)); const waiting = main.request('slow'); diff --git a/apps/ide/test/lspEdits.test.ts b/apps/ide/test/lspEdits.test.ts index 67912914..e2f6d01a 100644 --- a/apps/ide/test/lspEdits.test.ts +++ b/apps/ide/test/lspEdits.test.ts @@ -229,7 +229,9 @@ describe('Quick open workspace symbols (#287)', () => { assert.ok(paletteView('', base).entries.some((entry) => entry.fill === '#'), 'a hint row for "#"'); }); - it('asks the servers after a pause and keeps only the latest answer', async () => { + it('asks the servers after a pause and keeps only the latest answer', async (t) => { + // O14: mocked timers, so "after the pause" is a tick of the clock, not a 30 ms sleep. + t.mock.timers.enable({ apis: ['setTimeout'] }); const asked: string[] = []; const answers = new Map void>(); let loaded = 0; @@ -240,7 +242,9 @@ describe('Quick open workspace symbols (#287)', () => { assert.deepEqual(search.state(''), { query: '', items: [] }); assert.equal(search.state('g').items, null); assert.equal(search.state('gr').items, null); - await new Promise((resolve) => setTimeout(resolve, 30)); + t.mock.timers.tick(4); + assert.deepEqual(asked, [], 'nothing is asked before the pause'); + t.mock.timers.tick(1); assert.deepEqual(asked, ['gr'], 'typing quickly asks once'); answers.get('gr')?.([{ name: 'greet', container: '', path: 'a.ts', line: 1, column: 1 }]); await Promise.resolve(); @@ -248,7 +252,7 @@ describe('Quick open workspace symbols (#287)', () => { assert.equal(search.state('gr').items?.length, 1); search.state('gre'); search.reset(); - await new Promise((resolve) => setTimeout(resolve, 30)); + t.mock.timers.tick(30); assert.deepEqual(asked, ['gr'], 'a reset cancels the pending question'); }); }); diff --git a/apps/ide/test/watcher.test.ts b/apps/ide/test/watcher.test.ts index a87e74fc..961972a6 100644 --- a/apps/ide/test/watcher.test.ts +++ b/apps/ide/test/watcher.test.ts @@ -66,8 +66,13 @@ describe('WorkspaceWatcher', () => { // macOS backs fs.watch with FSEvents, whose stream starts // asynchronously: a write in the same tick as the watch can land // before the stream does and never be reported (seen on CI, macos-latest). - // Let the watchers settle first, as any real edit would. - await new Promise((resolve) => setTimeout(resolve, 300)); + // O14: wait until the watch demonstrably reports (a probe file, rewritten until it + // is seen) instead of guessing a settle time; fs.watch has no ready event. + const probe = path.join(root, 'src', 'probe.txt'); + for (let attempt = 0; attempt < 100 && !(await rec.until((s) => s.has('src/probe.txt'), 50)).has('src/probe.txt'); attempt += 1) { + fs.writeFileSync(probe, String(attempt)); + } + assert.ok((await rec.until((s) => s.has('src/probe.txt'), 1000)).has('src/probe.txt'), 'the watch never reported the probe'); fs.writeFileSync(path.join(root, 'src', 'main.ts'), 'export const x = 1;\n'); fs.writeFileSync(path.join(root, 'src', 'new.ts'), ''); const seen = await rec.until((s) => s.has('src/main.ts') && s.has('src/new.ts'), 5000); From 5f2d865a172e70c579099e54fccaca767472ac28 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:21:30 +0000 Subject: [PATCH 09/74] feat(ide): chat loading and error states, starter prompts, double Esc and an accessible transcript (#510, #511) #510 (O8): chatPhase picks a skeleton until the first load resolves (no more flash of the empty prompt in restored tabs), an error notice with Retry when it fails, the empty prompt with four starter prompt chips that fill the composer without sending, or the conversation. New output while the reader is scrolled up raises a floating New activity pill. Esc in the composer arms first (Press Esc again to stop) and stops on a second press within 1.5 s (escapeIntent); the Stop button is unchanged. #511 (O9): the transcript is aria-busy while the agent streams, and an sr-only status region speaks only transitions (chatAnnouncement: finished, stopped, needs permission, error). The composer is a combobox wired to the slash popup options (unique ids, aria-activedescendant) and to the attachment popup. The chat is a size container: below 640px the header buttons keep only their icon (label as aria-label and title), nothing wraps, and they get a hover state. Every string of the chat view moves to the en/es catalogues. --- .../src/renderer/agentFirst/agentFirst.css | 44 ++- apps/ide/src/renderer/agentFirst/chatModel.ts | 88 ++++- apps/ide/src/renderer/agentFirst/chatView.ts | 353 +++++++++++++----- apps/ide/src/shared/i18n/messages.en.ts | 95 +++++ apps/ide/src/shared/i18n/messages.es.ts | 95 +++++ apps/ide/test/chatStates.test.ts | 106 ++++++ docs/ide/agent-first-test-guide.md | 2 +- 7 files changed, 688 insertions(+), 95 deletions(-) create mode 100644 apps/ide/test/chatStates.test.ts diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 9de8bd88..0eb77416 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -109,25 +109,56 @@ .af-link-button svg { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2; } /* ---- The chat (AF3) ------------------------------------------------------ */ -.af-chat { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--editor); } -.af-chat-header { display: flex; align-items: center; gap: 10px; padding: 8px 16px; border-bottom: 1px solid var(--line); } +/* #511: the chat is a size container, so its header adapts to the column it is in, not to the window. */ +.af-chat { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--editor); container: af-chat / inline-size; } +.af-chat-header { display: flex; flex-wrap: nowrap; align-items: center; gap: 10px; padding: 8px 16px; border-bottom: 1px solid var(--line); } .af-chat-heading { flex: 1; min-width: 0; } .af-chat-title { margin: 0; font-size: var(--fs-lg); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.af-chat-sub { display: flex; align-items: center; gap: 8px; font-size: var(--fs-sm); } +.af-chat-sub { display: flex; align-items: center; gap: 8px; min-width: 0; overflow: hidden; font-size: var(--fs-sm); white-space: nowrap; } .af-status-pill { padding: 0 6px; border-radius: var(--radius-pill); font-size: var(--fs-xs); line-height: 16px; background: var(--hover); color: var(--muted); } .af-status-pill[data-status='running'] { color: var(--accent); } .af-status-pill[data-status='awaiting'] { color: var(--warn); } .af-status-pill[data-status='error'] { color: var(--crit); } -.af-usage { font-size: var(--fs-xs); white-space: nowrap; } +.af-usage { flex: none; font-size: var(--fs-xs); white-space: nowrap; } .af-usage[hidden] { display: none; } -.af-header-button { display: inline-flex; align-items: center; gap: 6px; min-height: var(--control-h); padding: 0 10px; border: 1px solid var(--warn); border-radius: var(--radius); background: none; color: var(--fg); font: inherit; font-size: var(--fs-sm); cursor: pointer; } +.af-header-button { display: inline-flex; flex: none; align-items: center; justify-content: center; gap: 6px; min-height: var(--control-h); padding: 0 10px; border: 1px solid var(--warn); border-radius: var(--radius); background: none; color: var(--fg); font: inherit; font-size: var(--fs-sm); white-space: nowrap; cursor: pointer; } +.af-header-button:hover:not(:disabled) { background: var(--hover); } +.af-header-button:disabled { cursor: default; opacity: 0.6; } .af-header-button[hidden] { display: none; } -.af-header-button svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.6; } +.af-header-button svg { flex: none; width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.6; } +/* #511: in a narrow column the header buttons keep only their icon (each has its label as aria-label and title). */ +@container af-chat (max-width: 640px) { + .af-chat-header { gap: 6px; padding: 8px 10px; } + .af-header-button { min-width: var(--control-h); padding: 0 6px; } + .af-header-label { display: none; } +} +/* #510: the transcript and the "New activity" pill floating over its bottom edge. */ +.af-transcript-area { position: relative; display: flex; flex-direction: column; flex: 1; min-height: 0; } .af-transcript { flex: 1; min-height: 0; overflow: auto; padding: 16px max(16px, calc((100% - 860px) / 2)); display: flex; flex-direction: column; gap: 12px; } +.af-new-activity { position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%); display: inline-flex; align-items: center; gap: 6px; min-height: var(--control-h); padding: 0 12px; border: 0; border-radius: var(--radius-pill); background: var(--button-bg); color: var(--on-accent); font: inherit; font-size: var(--fs-sm); white-space: nowrap; box-shadow: var(--shadow-md); cursor: pointer; } +.af-new-activity:hover { background: var(--button-hover); } +.af-new-activity[hidden] { display: none; } +.af-new-activity svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; } +/* #510: the loading skeleton and the load error with Retry. */ +.af-skeleton { display: flex; flex-direction: column; gap: 12px; } +.af-skeleton[hidden] { display: none; } +.af-skeleton-bar { display: block; height: 14px; border-radius: var(--radius-md); background: var(--hover); animation: af-skeleton-pulse 1.4s ease-in-out infinite; } +.af-skeleton-bar.is-user { align-self: flex-end; width: 40%; height: 32px; } +.af-skeleton-bar.is-long { width: 90%; } +.af-skeleton-bar.is-short { width: 60%; } +@keyframes af-skeleton-pulse { 50% { opacity: 0.45; } } +@media (prefers-reduced-motion: reduce) { .af-skeleton-bar { animation: none; } } +.af-load-error { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: auto 0; } +.af-load-error[hidden] { display: none; } +.af-load-error-text { flex: 1 1 240px; margin: 0; } .af-empty { margin: auto 0; text-align: center; padding: 24px; } .af-empty[hidden] { display: none; } .af-empty h3 { margin: 0 0 8px; font-size: var(--fs-xl); } .af-empty p { margin: 0 auto; max-width: 480px; line-height: 1.5; } +/* #510: starter prompts: each fills the composer, none sends. */ +.af-starters { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; max-width: 560px; margin: 16px auto 0; } +.af-starter { min-height: var(--control-h); padding: 4px 12px; border: 1px solid var(--line); border-radius: var(--radius-pill); background: var(--panel); color: var(--fg); font: inherit; font-size: var(--fs-sm); line-height: 1.4; text-align: left; cursor: pointer; } +.af-starter:hover { border-color: var(--line-strong); background: var(--hover); } .af-message { min-width: 0; overflow-wrap: anywhere; line-height: 1.55; } .af-message.is-user { align-self: flex-end; max-width: 85%; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--hover); } .af-remote-origin { display: block; margin-bottom: 2px; font-size: var(--fs-2xs); } @@ -201,6 +232,7 @@ .af-input:focus { outline: none; } .af-queue { margin: 0; font-size: var(--fs-xs); } .af-queue[hidden] { display: none; } +.af-queue.is-armed { color: var(--warn); } .af-composer-row { display: flex; align-items: center; gap: 6px; min-width: 0; flex-wrap: wrap; } .af-options { display: contents; } .af-spacer { flex: 1; } diff --git a/apps/ide/src/renderer/agentFirst/chatModel.ts b/apps/ide/src/renderer/agentFirst/chatModel.ts index c2cf94d8..1397548e 100644 --- a/apps/ide/src/renderer/agentFirst/chatModel.ts +++ b/apps/ide/src/renderer/agentFirst/chatModel.ts @@ -1,5 +1,6 @@ import type { AgentSessionState, PromptAttachment, SlashCommandView, TranscriptItem } from '../../shared/agentSession.ts'; import { diffLines, splitLines } from '../../shared/lineDiff.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; /** * Pure helpers of the agent-first chat (AF3): what the composer suggests, @@ -23,13 +24,13 @@ export function slashSuggestions(text: string, commands: readonly SlashCommandVi export function toolStatusLabel(status: Extract['status']): string { switch (status) { case 'pending': - return 'Waiting'; + return t('chat.tool.pending'); case 'in_progress': - return 'Running'; + return t('chat.tool.inProgress'); case 'completed': - return 'Done'; + return t('chat.tool.completed'); case 'failed': - return 'Failed'; + return t('chat.tool.failed'); } } @@ -174,3 +175,82 @@ export function formatTokens(used: number, size: number): string { const short = (value: number): string => (value >= 1_000_000 ? `${Math.round(value / 100_000) / 10}M` : value >= 1000 ? `${Math.round(value / 1000)}k` : String(value)); return `${short(used)} / ${short(size)}`; } + +// ---- #510 (O8) / #511 (O9): states, starters, Esc, announcements ------------- + +/** What the chat's transcript area shows: a skeleton, the empty prompt, the conversation, or the load error. */ +export type ChatPhase = 'loading' | 'empty' | 'ready' | 'error'; + +/** + * #510: the transcript's phase. Until the first load resolves there is no + * state, so a restored chat shows a skeleton instead of flashing the empty + * prompt. A load error only takes over when nothing was ever loaded: a failed + * retry of a chat already on screen keeps its transcript. + */ +export function chatPhase(state: Pick | null, error: string | null): ChatPhase { + if (!state) { + return error ? 'error' : 'loading'; + } + return state.items.length === 0 ? 'empty' : 'ready'; +} + +/** #510: the starter prompts of an empty chat, as message keys: each chip puts its text in the composer. */ +export function starterPrompts(): readonly MessageKey[] { + return ['chat.starter.architecture', 'chat.starter.complexity', 'chat.starter.tests', 'chat.starter.review']; +} + +/** #510: how long the first Esc stays armed, in milliseconds. */ +export const ESCAPE_STOP_WINDOW_MS = 1500; + +/** + * #510: what Esc in the composer does. Nothing when no turn runs; the first + * press arms ("Press Esc again to stop") and a second one within + * `ESCAPE_STOP_WINDOW_MS` stops the turn, so one stray key never ends a long + * turn. `armedAt` is the time of the arming press, or null. + */ +export function escapeIntent(status: AgentSessionState['status'], armedAt: number | null, now: number): 'arm' | 'stop' | 'none' { + if (status !== 'running' && status !== 'awaiting') { + return 'none'; + } + return armedAt !== null && now >= armedAt && now - armedAt <= ESCAPE_STOP_WINDOW_MS ? 'stop' : 'arm'; +} + +type AnnouncedState = Pick; + +/** The newest permission request still waiting for an answer, if any. */ +function pendingPermission(state: AnnouncedState): Extract | undefined { + for (let index = state.items.length - 1; index >= 0; index -= 1) { + const item = state.items[index]; + if (item?.kind === 'permission' && item.outcome === undefined) { + return item; + } + } + return undefined; +} + +/** + * #511: what the chat's screen-reader status region says when the state goes + * from `prev` to `next`, or null. Only transitions speak: the turn finished + * (or was stopped), a permission is requested, the turn failed. Streaming + * deltas, and the first load (`prev` null), say nothing. + */ +export function chatAnnouncement(prev: AnnouncedState | null, next: AnnouncedState): string | null { + if (!prev) { + return null; + } + const permission = pendingPermission(next); + if (next.status === 'awaiting' && permission && pendingPermission(prev)?.id !== permission.id) { + return t('chat.announce.permission', { title: permission.title }); + } + if (next.status === prev.status) { + return null; + } + if (next.status === 'error') { + return t('chat.announce.error'); + } + if (next.status === 'idle' && (prev.status === 'running' || prev.status === 'awaiting')) { + const last = next.items.at(-1); + return last?.kind === 'turn-end' && last.stopReason === 'cancelled' ? t('chat.announce.stopped') : t('chat.announce.finished'); + } + return null; +} diff --git a/apps/ide/src/renderer/agentFirst/chatView.ts b/apps/ide/src/renderer/agentFirst/chatView.ts index 07328ad8..8f0c0ca5 100644 --- a/apps/ide/src/renderer/agentFirst/chatView.ts +++ b/apps/ide/src/renderer/agentFirst/chatView.ts @@ -9,10 +9,12 @@ import { metricDeltaFileLines, metricDeltaHeadline, restorePrompt } from './chan import { renderMarkdown } from '../agents/chatMarkdown.ts'; import { createAttachmentBar, type AttachmentSources } from '../agents/chatAttachments.ts'; import { el, icon } from '../dom.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; import { createWorktreeBar } from './worktreeBar.ts'; import { branchLabel, branchTitle } from './worktreeModel.ts'; import { - changeCounts, composerAction, diffLinesForCard, displayPath, formatTokens, lastUserIndex, slashSuggestions, TOOL_ICONS, toolStatusLabel, turnChanges, + changeCounts, chatAnnouncement, chatPhase, composerAction, diffLinesForCard, displayPath, escapeIntent, ESCAPE_STOP_WINDOW_MS, formatTokens, lastUserIndex, + slashSuggestions, starterPrompts, TOOL_ICONS, toolStatusLabel, turnChanges, } from './chatModel.ts'; /** @@ -57,8 +59,9 @@ export interface ChatView { /** Feeds a message from the main process; ignored when it is for another session. */ handle(message: AgentSessionMessage): void; focus(): void; - /** Puts text in the composer (for "Ask about this selection" and the like). */ + /** Puts text in the composer without sending it (for "Ask about this selection", the starter prompts and the like). */ insert(text: string): void; + /** Loads the chat again; a failure shows in the chat (with Retry) instead of rejecting. */ reload(): Promise; dispose(): void; } @@ -74,20 +77,49 @@ const ICONS = { flow: 'M3 19h18M6 19v-5M10 19V9M14 19v-7M18 19V6M6 14l4-5 4 3 4-6', remote: 'M4 6h16v10H4zM9 20h6M12 16v4', terminal: 'M4 5h16v14H4zM8 10l3 2-3 2M13 15h3', + down: 'M12 5v14M6 13l6 6 6-6', } as const; +/** Makes each chat's slash popup id unique: several chats can be open at once. */ +let slashPopupCount = 0; + +/** + * #511: a header button. Below ~640px of chat width (a container query in + * agentFirst.css) only its icon shows, so it always carries its label as + * `aria-label`, and a `title` for the pointer. + */ +function headerButton(path: string, label: string, title: string, attrs: Record, quiet = true): HTMLButtonElement { + return el('button', { className: quiet ? 'af-header-button is-quiet' : 'af-header-button', attrs: { type: 'button', 'aria-label': label, title, ...attrs } }, [ + icon(path), + el('span', { className: 'af-header-label', text: label }), + ]); +} + +function setHeaderLabel(button: HTMLButtonElement, label: string, title: string): void { + button.setAttribute('aria-label', label); + button.title = title; + button.lastElementChild!.textContent = label; +} + export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView { let state: AgentSessionState | null = null; let disposed = false; const queue: { text: string; attachments: PromptAttachment[] }[] = []; const rendered = new Map(); let frame = 0; + /** #510: why the last load failed, while nothing is loaded. */ + let loadError: string | null = null; + /** #510: the items drawn last, to tell new output from a plain re-render (null right after a load). */ + let drawnItems: readonly TranscriptItem[] | null = null; + /** #510: when the first Esc of a double Esc was pressed, or null. */ + let escapeArmedAt: number | null = null; + let escapeTimer = 0; // ---- Header ------------------------------------------------------------ - const title = el('h2', { className: 'af-chat-title', text: 'Chat' }); + const title = el('h2', { className: 'af-chat-title', text: t('chat.title') }); const agentLabel = el('span', { className: 'af-chat-agent muted' }); const statusPill = el('span', { className: 'af-status-pill', attrs: { 'data-testid': 'af-chat-status' } }); - const changesButton = el('button', { className: 'af-header-button', attrs: { type: 'button', hidden: '', 'data-testid': 'af-chat-changes' } }, [icon(ICONS.changes), el('span', { text: 'Changes' })]); + const changesButton = headerButton(ICONS.changes, t('chat.changes'), t('chat.changes'), { hidden: '', 'data-testid': 'af-chat-changes' }, false); changesButton.addEventListener('click', () => { if (state) { deps.openChanges?.(state); @@ -97,20 +129,18 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView // AF12: the branch of a chat that runs in its own worktree, and its Worktree bar. const branchBadge = el('span', { className: 'af-badge af-branch', attrs: { hidden: '', 'data-testid': 'af-chat-branch' } }); const worktreeBar = createWorktreeBar(sessionId, { api: deps.api, onStatus: deps.onStatus }); - const worktreeButton = el('button', { className: 'af-header-button is-quiet', attrs: { type: 'button', hidden: '', 'aria-expanded': 'false', 'data-testid': 'af-chat-worktree' } }, [icon(ICONS.branch), el('span', { text: 'Worktree' })]); + const worktreeButton = headerButton(ICONS.branch, t('chat.worktree'), t('chat.worktreeTitle'), { hidden: '', 'aria-expanded': 'false', 'data-testid': 'af-chat-worktree' }); worktreeButton.addEventListener('click', () => { worktreeBar.toggle(); worktreeButton.setAttribute('aria-expanded', String(worktreeBar.isOpen)); }); // Agent Flow (#319): the chat on the table of the project's XR scene. - const watchButton = el('button', { className: 'af-header-button is-quiet', attrs: { type: 'button', title: 'Watch this chat on the table of the XR scene (Agent Flow)', 'data-testid': 'af-chat-watch-xr' } }, [icon(ICONS.flow), el('span', { text: 'Watch in XR' })]); + const watchButton = headerButton(ICONS.flow, t('chat.watchXr'), t('chat.watchXrTitle'), { 'data-testid': 'af-chat-watch-xr' }); watchButton.addEventListener('click', () => { watchButton.disabled = true; deps.api.watchInXr(sessionId) .then(({ scenes }) => { - deps.onStatus(scenes > 0 - ? 'Agent Flow is following this chat on the XR table.' - : 'Open the XR analysis of this project first, then press Watch in XR again.'); + deps.onStatus(scenes > 0 ? t('chat.watchXrFollowing') : t('chat.watchXrNoScene')); }) .catch((error: unknown) => deps.onStatus(error instanceof Error ? error.message : String(error))) .finally(() => { @@ -123,10 +153,10 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView const url = state?.remoteControl?.url; if (url) { deps.copy(url); - deps.onStatus('The claude.ai link of this chat was copied. Open it in the browser or the Claude mobile app.'); + deps.onStatus(t('chat.remoteCopied')); } }); - const remoteButton = el('button', { className: 'af-header-button is-quiet', attrs: { type: 'button', hidden: '', 'data-testid': 'af-chat-remote' } }, [icon(ICONS.remote), el('span', { text: 'Share on claude.ai' })]); + const remoteButton = headerButton(ICONS.remote, t('chat.share'), t('chat.shareTitle'), { hidden: '', 'data-testid': 'af-chat-remote' }); remoteButton.addEventListener('click', () => { const on = !state?.remoteControl?.active; remoteButton.disabled = true; @@ -136,24 +166,22 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView return; } deps.onStatus(remote.error - ? `Could not share on claude.ai: ${remote.error}` - : remote.active - ? 'This chat is shared: continue it from claude.ai/code or the Claude mobile app. Click the badge to copy its link.' - : 'This chat is no longer shared with claude.ai.'); + ? t('chat.shareFailed', { error: remote.error }) + : remote.active ? t('chat.shared') : t('chat.unshared')); }) .catch((error: unknown) => deps.onStatus(errorText(error))) .finally(() => { remoteButton.disabled = false; }); }); - const terminalButton = el('button', { className: 'af-header-button is-quiet', attrs: { type: 'button', hidden: '', title: 'Continue this Claude Code session in a terminal (claude --resume). The next message here picks up what was done there.', 'data-testid': 'af-chat-terminal' } }, [icon(ICONS.terminal), el('span', { text: 'Continue in terminal' })]); + const terminalButton = headerButton(ICONS.terminal, t('chat.terminal'), t('chat.terminalTitle'), { hidden: '', 'data-testid': 'af-chat-terminal' }); terminalButton.addEventListener('click', () => { const run = deps.runInTerminal; if (!run) { return; } terminalButton.disabled = true; - run(`Claude Code: ${state?.title ?? 'chat'}`, (cols, rows) => deps.api.continueInTerminal(sessionId, cols, rows).then((opened) => ({ ...opened.terminal, command: opened.command }))) + run(t('chat.terminalLabel', { title: state?.title ?? t('chat.title') }), (cols, rows) => deps.api.continueInTerminal(sessionId, cols, rows).then((opened) => ({ ...opened.terminal, command: opened.command }))) .catch((error: unknown) => deps.onStatus(errorText(error))) .finally(() => { terminalButton.disabled = false; @@ -170,16 +198,53 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView ]); // ---- Transcript -------------------------------------------------------- - const transcript = el('div', { className: 'af-transcript', attrs: { role: 'log', 'aria-live': 'polite', 'aria-label': 'Conversation', 'data-testid': 'af-transcript' } }); - const empty = el('div', { className: 'af-empty' }, [ - el('h3', { text: 'What do you want to build?' }), - el('p', { className: 'muted', text: 'Describe a change, ask about the code, or type / for the agent\'s commands. Attach files with @. The live analysis on the right follows every change the agent makes.' }), + // #511: aria-busy while the agent streams, so a screen reader reads the reply once it is complete. + const transcript = el('div', { className: 'af-transcript', attrs: { role: 'log', 'aria-live': 'polite', 'aria-busy': 'true', 'aria-label': t('chat.conversation'), 'data-testid': 'af-transcript' } }); + // #510: until the first load resolves a skeleton shows, never the empty prompt (restored tabs flashed it). + const skeleton = el('div', { className: 'af-skeleton', attrs: { 'data-testid': 'af-chat-loading' } }, [ + el('span', { className: 'sr-only', text: t('chat.loading') }), + ...['is-user', 'is-long', 'is-short'].map((kind) => el('span', { className: `af-skeleton-bar ${kind}`, attrs: { 'aria-hidden': 'true' } })), ]); - transcript.append(empty); + const loadErrorText = el('p', { className: 'af-load-error-text' }); + const retryButton = el('button', { className: 'secondary-button', text: t('chat.retry'), attrs: { type: 'button', 'data-testid': 'af-chat-retry' } }); + retryButton.addEventListener('click', () => { + retryButton.disabled = true; + void reload().finally(() => { + retryButton.disabled = false; + }); + }); + const loadErrorBox = el('div', { className: 'af-notice is-error af-load-error', attrs: { role: 'alert', hidden: '', 'data-testid': 'af-chat-error' } }, [loadErrorText, retryButton]); + const starters = el('div', { className: 'af-starters', attrs: { role: 'group', 'aria-label': t('chat.starters') } }, starterPrompts().map((key: MessageKey) => { + const chip = el('button', { className: 'af-starter', text: t(key), attrs: { type: 'button', 'data-testid': 'af-starter' } }); + chip.addEventListener('click', () => insertText(t(key))); + return chip; + })); + const empty = el('div', { className: 'af-empty', attrs: { hidden: '' } }, [ + el('h3', { text: t('chat.empty.heading') }), + el('p', { className: 'muted', text: t('chat.empty.text') }), + starters, + ]); + transcript.append(skeleton, loadErrorBox, empty); let stickToBottom = true; + // #510: when the reader scrolled up, new output raises this pill instead of arriving unseen. + const newActivity = el('button', { className: 'af-new-activity', attrs: { type: 'button', hidden: '', title: t('chat.newActivityTitle'), 'data-testid': 'af-new-activity' } }, [ + icon(ICONS.down), + el('span', { text: t('chat.newActivity') }), + ]); + newActivity.addEventListener('click', () => { + stickToBottom = true; + newActivity.hidden = true; + transcript.scrollTop = transcript.scrollHeight; + }); transcript.addEventListener('scroll', () => { stickToBottom = transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight < 40; + if (stickToBottom) { + newActivity.hidden = true; + } }); + const transcriptArea = el('div', { className: 'af-transcript-area' }, [transcript, newActivity]); + // #511: speaks transitions only (finished, needs permission, error), never the stream. + const announcer = el('div', { className: 'sr-only', attrs: { role: 'status', 'data-testid': 'af-chat-announcer' } }); // ---- Plan -------------------------------------------------------------- const planList = el('ol', { className: 'af-plan-list' }); @@ -187,25 +252,34 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView const plan = el('details', { className: 'af-plan', attrs: { open: '', hidden: '', 'data-testid': 'af-plan' } }, [planSummary, planList]); // ---- Composer ---------------------------------------------------------- - const input = el('textarea', { className: 'af-input', attrs: { rows: '3', placeholder: 'Ask the agent to build, fix or explain something. @ to attach, / for commands.', 'aria-label': 'Message', 'data-testid': 'af-input' } }); + // #511: a combobox whose popup is the slash commands (or the attachment bar's `@` list). + const input = el('textarea', { + className: 'af-input', + attrs: { rows: '3', placeholder: t('chat.placeholder'), 'aria-label': t('chat.message'), role: 'combobox', 'aria-expanded': 'false', 'aria-haspopup': 'listbox', 'data-testid': 'af-input' }, + }); // #487: grows with its text on WebKit too, which has no `field-sizing`. const fitInput = autosizeTextarea(input); const bar = createAttachmentBar(input, deps.attachments); - const slashPopup = el('ul', { className: 'chat-mention af-slash', attrs: { role: 'listbox', hidden: '', 'aria-label': 'Commands' } }); + slashPopupCount += 1; + const slashId = `af-slash-${slashPopupCount}`; + const slashPopup = el('ul', { className: 'chat-mention af-slash', attrs: { role: 'listbox', id: slashId, hidden: '', 'aria-label': t('chat.commands') } }); let slashItems: ReturnType = []; let slashSelected = 0; + // The attachment bar shows and hides its own popup: the combobox follows it. + const mentionObserver = new MutationObserver(() => syncCombobox()); + mentionObserver.observe(bar.popup, { attributes: true, attributeFilter: ['hidden'] }); const queueNote = el('p', { className: 'af-queue muted', attrs: { hidden: '', 'data-testid': 'af-queue' } }); - const modeSelect = el('select', { className: 'af-select', attrs: { 'aria-label': 'Agent mode', hidden: '', 'data-testid': 'af-mode' } }); + const modeSelect = el('select', { className: 'af-select', attrs: { 'aria-label': t('chat.agentMode'), hidden: '', 'data-testid': 'af-mode' } }); const optionsSlot = el('span', { className: 'af-options' }); - const sendButton = el('button', { className: 'af-send', attrs: { type: 'button', 'aria-label': 'Send', title: 'Send (Enter)', 'data-testid': 'af-send' } }, [icon(ICONS.send)]); + const sendButton = el('button', { className: 'af-send', attrs: { type: 'button', 'aria-label': t('chat.send'), title: t('chat.sendTitle'), 'data-testid': 'af-send' } }, [icon(ICONS.send)]); const composer = el('div', { className: 'af-composer' }, [ bar.chips, el('div', { className: 'af-input-wrap' }, [input, bar.popup, slashPopup]), queueNote, - el('div', { className: 'af-composer-row' }, [bar.attachButton, el('label', { className: 'af-option' }, [el('span', { className: 'af-option-name', text: 'Mode' }), modeSelect]), optionsSlot, el('span', { className: 'af-spacer' }), sendButton]), + el('div', { className: 'af-composer-row' }, [bar.attachButton, el('label', { className: 'af-option' }, [el('span', { className: 'af-option-name', text: t('chat.mode') }), modeSelect]), optionsSlot, el('span', { className: 'af-spacer' }), sendButton]), ]); - const element = el('section', { className: 'af-chat', attrs: { 'data-testid': 'af-chat', 'data-session': sessionId } }, [header, worktreeBar.element, transcript, plan, composer]); + const element = el('section', { className: 'af-chat', attrs: { 'data-testid': 'af-chat', 'data-session': sessionId } }, [header, worktreeBar.element, transcriptArea, plan, composer, announcer]); // ---- Rendering --------------------------------------------------------- function schedule(): void { @@ -218,7 +292,17 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView }); } + /** #510: skeleton, load error, empty prompt or conversation; #511: aria-busy while loading or streaming. */ + function updatePhase(): void { + const phase = chatPhase(state, loadError); + skeleton.hidden = phase !== 'loading'; + loadErrorBox.hidden = phase !== 'error'; + empty.hidden = phase !== 'empty'; + transcript.setAttribute('aria-busy', String(phase === 'loading' || state?.status === 'running')); + } + function render(): void { + updatePhase(); if (!state) { return; } @@ -227,21 +311,26 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView statusPill.textContent = statusText(state); statusPill.dataset['status'] = state.status; changesButton.hidden = state.pendingChanges === 0 || !deps.openChanges; - changesButton.lastElementChild!.textContent = `Changes (${state.pendingChanges})`; + setHeaderLabel(changesButton, t('chat.changesCount', { count: state.pendingChanges }), t('chat.changesTitle', { count: state.pendingChanges })); usageMeter.hidden = !state.usage; if (state.usage) { - usageMeter.textContent = `Context ${formatTokens(state.usage.used, state.usage.size)}`; - usageMeter.title = `${state.usage.used.toLocaleString()} of ${state.usage.size.toLocaleString()} tokens of context used`; + usageMeter.textContent = t('chat.context', { tokens: formatTokens(state.usage.used, state.usage.size) }); + usageMeter.title = t('chat.contextTitle', { used: state.usage.used.toLocaleString(), size: state.usage.size.toLocaleString() }); } const worktree = state.worktree; branchBadge.hidden = !worktree; worktreeButton.hidden = !worktree; if (worktree) { - branchBadge.textContent = worktree.removed ? `${branchLabel(worktree)} (discarded)` : branchLabel(worktree); + branchBadge.textContent = worktree.removed ? t('chat.discarded', { branch: branchLabel(worktree) }) : branchLabel(worktree); branchBadge.title = branchTitle(worktree); worktreeBar.update(state); } + if (escapeArmedAt !== null && state.status !== 'running' && state.status !== 'awaiting') { + disarmEscape(); + } renderRemote(state); + const grew = drawnItems !== null && drawnItems !== state.items; + drawnItems = state.items; renderItems(state); markStreaming(state); renderPlan(state.plan); @@ -249,6 +338,8 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView updateSendButton(); if (stickToBottom) { transcript.scrollTop = transcript.scrollHeight; + } else if (grew) { + newActivity.hidden = false; } } @@ -264,7 +355,6 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } function renderItems(current: AgentSessionState): void { - empty.hidden = current.items.length > 0; const seen = new Set(); let previous: Node = empty; current.items.forEach((item, index) => { @@ -299,13 +389,14 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView const remote = current.remoteControl; const claude = current.agentRef === 'acp:claude'; remoteButton.hidden = !remote?.available; - remoteButton.lastElementChild!.textContent = remote?.active ? 'Stop sharing' : 'Share on claude.ai'; - remoteButton.title = remote?.active - ? 'Disconnect this chat from claude.ai and the Claude mobile app' - : 'Continue this chat from claude.ai/code or the Claude mobile app (Remote Control). Asks first.'; + if (remote?.active) { + setHeaderLabel(remoteButton, t('chat.stopSharing'), t('chat.stopSharingTitle')); + } else { + setHeaderLabel(remoteButton, t('chat.share'), t('chat.shareTitle')); + } remoteBadge.hidden = !remote?.active; - remoteBadge.textContent = 'On claude.ai'; - remoteBadge.title = remote?.url ? `Shared with claude.ai: ${remote.url} (click to copy)` : 'Shared with claude.ai'; + remoteBadge.textContent = t('chat.remoteBadge'); + remoteBadge.title = remote?.url ? t('chat.remoteBadgeUrlTitle', { url: remote.url }) : t('chat.remoteBadgeTitle'); terminalButton.hidden = !claude || !current.agentSessionId || !deps.runInTerminal || !!current.worktree?.removed; } @@ -314,9 +405,9 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView case 'user': { const actions = el('div', { className: 'af-message-actions' }); if (item.checkpoint && deps.restoreCheckpoint) { - const restore = el('button', { className: 'af-link-button', attrs: { type: 'button', title: 'Put the project\'s files back as they were before this message. The conversation is kept; effects of commands (network, databases) are not undone.', 'data-testid': 'af-restore' } }, [icon(ICONS.restore), el('span', { text: 'Restore files to here' })]); + const restore = el('button', { className: 'af-link-button', attrs: { type: 'button', title: t('chat.restoreTitle'), 'data-testid': 'af-restore' } }, [icon(ICONS.restore), el('span', { text: t('chat.restore') })]); const checkpoint = item.checkpoint; - const confirmBox = el('div', { className: 'af-restore-confirm', attrs: { hidden: '', role: 'group', 'aria-label': 'Restore files', 'data-testid': 'af-restore-confirm' } }); + const confirmBox = el('div', { className: 'af-restore-confirm', attrs: { hidden: '', role: 'group', 'aria-label': t('chat.restoreGroup'), 'data-testid': 'af-restore-confirm' } }); restore.addEventListener('click', () => { if (state) { restore.disabled = true; @@ -331,7 +422,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView ? el('div', { className: 'chat-chips is-static' }, item.attachments.map((label) => el('span', { className: 'chat-chip', attrs: { title: label } }, [el('span', { className: 'chat-chip-label', text: label })]))) : null; return el('div', { className: item.remote ? 'af-message is-user is-remote' : 'af-message is-user', attrs: { 'data-testid': 'af-user' } }, [ - ...(item.remote ? [el('span', { className: 'af-remote-origin muted', text: 'From claude.ai' })] : []), + ...(item.remote ? [el('span', { className: 'af-remote-origin muted', text: t('chat.fromClaude') })] : []), el('p', { className: 'af-user-text', text: item.text }), ...(chips ? [chips] : []), actions, @@ -344,7 +435,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } case 'thought': return el('details', { className: 'af-thought' }, [ - el('summary', { text: 'Thinking' }), + el('summary', { text: t('chat.thinking') }), el('div', { className: 'af-thought-body', text: item.text }), ]); case 'tool': @@ -405,8 +496,11 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } case 'terminal': return el('div', { className: 'af-terminal' }, [ - el('pre', { className: 'af-terminal-output', text: block.output || (block.exitCode === null ? 'Running...' : '(no output)') }), - ...(block.exitCode !== null ? [el('p', { className: `af-terminal-exit muted${block.exitCode === 0 ? '' : ' is-error'}`, text: `Exit code ${block.exitCode}${block.truncated ? ' (output truncated)' : ''}` })] : []), + el('pre', { className: 'af-terminal-output', text: block.output || (block.exitCode === null ? t('chat.terminalRunning') : t('chat.terminalNoOutput')) }), + ...(block.exitCode !== null ? [el('p', { + className: `af-terminal-exit muted${block.exitCode === 0 ? '' : ' is-error'}`, + text: t(block.truncated ? 'chat.exitCodeTruncated' : 'chat.exitCode', { code: block.exitCode }), + })] : []), ]); } } @@ -418,7 +512,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView if (item.outcome !== undefined) { const chosen = item.options.find((option) => option.id === item.outcome); card.classList.add('is-resolved'); - card.append(el('p', { className: 'muted', text: chosen ? `You chose: ${chosen.name}` : item.outcome === 'cancelled' ? 'Cancelled' : `Answered: ${item.outcome}` })); + card.append(el('p', { className: 'muted', text: chosen ? t('chat.youChose', { option: chosen.name }) : item.outcome === 'cancelled' ? t('chat.permissionCancelled') : t('chat.answered', { outcome: item.outcome }) })); return card; } const buttons = el('div', { className: 'af-permission-actions' }, item.options.map((option) => { @@ -451,14 +545,15 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView const changed = turnChanges(current.items.slice(0, index), start); if (changed.length > 0) { footer.append(el('div', { className: 'af-turn-files' }, [ - el('span', { className: 'muted', text: `${changed.length} file${changed.length === 1 ? '' : 's'} changed:` }), + el('span', { className: 'muted', text: changed.length === 1 ? t('chat.filesChangedOne') : t('chat.filesChangedMany', { count: changed.length }) }), ...changed.map((change) => { const counts = changeCounts(change.oldText, change.newText); return el('span', { className: 'af-turn-file' }, [fileLink(change.path, undefined, workRootOf(current)), el('span', { className: 'is-add', text: ` +${counts.added}` }), el('span', { className: 'is-remove', text: ` -${counts.removed}` })]); }), ])); } - const reason = STOP_TEXT[item.stopReason]; + const reasonKey = STOP_TEXT[item.stopReason]; + const reason = reasonKey ? t(reasonKey) : ''; if (reason) { footer.append(el('p', { className: `af-stop muted${item.stopReason === 'error' ? ' is-error' : ''}`, text: reason })); } @@ -473,7 +568,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView function renderMetricDelta(delta: TurnMetricDeltaView): HTMLElement { const lines = metricDeltaFileLines(delta); return el('details', { className: 'af-metric-delta', attrs: { 'data-testid': 'af-metric-delta' } }, [ - el('summary', { attrs: { title: delta.summary } }, [el('span', { className: 'af-metric-delta-label', text: 'Metrics' }), el('span', { text: ` ${metricDeltaHeadline(delta)}` })]), + el('summary', { attrs: { title: delta.summary } }, [el('span', { className: 'af-metric-delta-label', text: t('chat.metrics') }), el('span', { text: ` ${metricDeltaHeadline(delta)}` })]), el('p', { className: 'muted', text: delta.summary }), ...(lines.length > 0 ? [el('ul', { className: 'af-metric-delta-files' }, lines.map((line) => el('li', { text: line })))] : []), ]); @@ -496,9 +591,9 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView box.hidden = true; box.replaceChildren(); }; - const cancel = el('button', { className: 'secondary-button', text: paths.length === 0 ? 'Close' : 'Cancel', attrs: { type: 'button' } }); + const cancel = el('button', { className: 'secondary-button', text: paths.length === 0 ? t('chat.close') : t('chat.cancel'), attrs: { type: 'button' } }); cancel.addEventListener('click', close); - const confirm = el('button', { className: 'primary-button', text: `Restore ${paths.length} file${paths.length === 1 ? '' : 's'}`, attrs: { type: 'button', 'data-testid': 'af-restore-apply' } }); + const confirm = el('button', { className: 'primary-button', text: paths.length === 1 ? t('chat.restoreOne') : t('chat.restoreMany', { count: paths.length }), attrs: { type: 'button', 'data-testid': 'af-restore-apply' } }); confirm.addEventListener('click', () => { confirm.disabled = true; cancel.disabled = true; @@ -514,7 +609,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView el('p', { text: restorePrompt(paths) }), ...(shown.length > 0 ? [el('ul', { className: 'af-restore-files' }, [ ...shown.map((path) => el('li', { text: path })), - ...(paths.length > shown.length ? [el('li', { className: 'muted', text: `and ${paths.length - shown.length} more` })] : []), + ...(paths.length > shown.length ? [el('li', { className: 'muted', text: t('chat.andMore', { count: paths.length - shown.length }) })] : []), ])] : []), el('div', { className: 'af-restore-actions' }, paths.length === 0 ? [cancel] : [confirm, cancel]), ); @@ -524,13 +619,13 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView function fileLink(path: string, line: number | undefined, root: string | null): HTMLElement { const label = displayPath(path, root) + (line ? `:${line}` : ''); - const link = el('button', { className: 'af-file-link', text: label, attrs: { type: 'button', title: `Open ${label}` } }); + const link = el('button', { className: 'af-file-link', text: label, attrs: { type: 'button', title: t('chat.openFile', { label }) } }); link.addEventListener('click', (event) => { event.preventDefault(); event.stopPropagation(); if (state?.worktree) { // AF12: the file is in the chat's worktree; the editor shows the project's own copy. - deps.onStatus(`${label} is in this chat's worktree (${state.worktree.path}). The editor shows the main project; merge the branch to bring it in.`); + deps.onStatus(t('chat.inWorktree', { label, path: state.worktree.path })); return; } deps.openFile(path, line); @@ -544,7 +639,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView return; } const done = entries.filter((entry) => entry.status === 'completed').length; - planSummary.textContent = `Plan: ${done} of ${entries.length} done`; + planSummary.textContent = t('chat.plan', { done, total: entries.length }); planList.replaceChildren(...entries.map((entry) => el('li', { className: 'af-plan-entry', attrs: { 'data-status': entry.status } }, [ el('span', { className: 'af-plan-mark', attrs: { 'aria-hidden': 'true', 'data-status': entry.status } }), el('span', { text: entry.content }), @@ -593,13 +688,67 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView function updateSendButton(): void { const action = state ? composerAction(state, input.value) : 'none'; sendButton.replaceChildren(icon(action === 'stop' ? ICONS.stop : ICONS.send)); - const label = action === 'stop' ? 'Stop' : action === 'queue' ? 'Queue message (sent when the agent finishes)' : 'Send'; + const label = action === 'stop' ? t('chat.stop') : action === 'queue' ? t('chat.queue') : t('chat.send'); sendButton.setAttribute('aria-label', label); - sendButton.title = action === 'stop' ? 'Stop (Esc)' : action === 'queue' ? label : 'Send (Enter)'; + sendButton.title = action === 'stop' ? t('chat.stopTitle') : action === 'queue' ? label : t('chat.sendTitle'); sendButton.disabled = action === 'none'; sendButton.dataset['action'] = action; - queueNote.hidden = queue.length === 0; - queueNote.textContent = queue.length === 1 ? '1 message queued: it is sent when the agent finishes.' : `${queue.length} messages queued.`; + const armed = escapeArmedAt !== null; + queueNote.hidden = !armed && queue.length === 0; + queueNote.classList.toggle('is-armed', armed); + queueNote.textContent = armed + ? t('chat.escAgain') + : queue.length === 1 ? t('chat.queuedOne') : t('chat.queuedMany', { count: queue.length }); + } + + function disarmEscape(): void { + escapeArmedAt = null; + if (escapeTimer) { + clearTimeout(escapeTimer); + escapeTimer = 0; + } + } + + /** #510: Esc in the composer: the first press arms, a second one within 1.5 s stops the turn. */ + function handleEscape(event: KeyboardEvent): void { + if (!state) { + return; + } + const now = performance.now(); + const intent = escapeIntent(state.status, escapeArmedAt, now); + if (intent === 'none') { + return; + } + event.preventDefault(); + disarmEscape(); + if (intent === 'arm') { + escapeArmedAt = now; + escapeTimer = window.setTimeout(() => { + escapeTimer = 0; + escapeArmedAt = null; + updateSendButton(); + }, ESCAPE_STOP_WINDOW_MS); + announce(t('chat.escAgain')); + } else { + deps.api.cancel(sessionId).catch((error: unknown) => deps.onStatus(errorText(error))); + } + updateSendButton(); + } + + function announce(text: string): void { + announcer.textContent = ''; + requestAnimationFrame(() => { + if (!disposed) { + announcer.textContent = text; + } + }); + } + + function insertText(text: string): void { + input.value = input.value ? `${input.value}\n${text}` : text; + fitInput(); + input.focus(); + updateSendButton(); } function toPromptAttachments(items: readonly ChatAttachment[]): PromptAttachment[] { @@ -655,7 +804,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView slashPopup.hidden = slashItems.length === 0; slashSelected = Math.min(slashSelected, Math.max(0, slashItems.length - 1)); slashPopup.replaceChildren(...slashItems.map((command, index) => { - const row = el('li', { className: 'chat-mention-row', attrs: { role: 'option', 'aria-selected': String(index === slashSelected) } }, [ + const row = el('li', { className: 'chat-mention-row', attrs: { role: 'option', id: `${slashId}-${index}`, 'aria-selected': String(index === slashSelected) } }, [ el('span', { className: 'af-slash-name', text: `/${command.name}` }), el('span', { className: 'muted', text: ` ${command.description}` }), ]); @@ -665,11 +814,31 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView }); return row; })); + syncCombobox(); } function hideSlash(): void { slashItems = []; slashPopup.hidden = true; + syncCombobox(); + } + + /** #511: the combobox state of the composer: which popup it controls, whether one is open, the active option. */ + function syncCombobox(): void { + const slashOpen = !slashPopup.hidden; + const mentionOpen = !bar.popup.hidden; + input.setAttribute('aria-expanded', String(slashOpen || mentionOpen)); + if (slashOpen) { + input.setAttribute('aria-controls', slashId); + input.setAttribute('aria-activedescendant', `${slashId}-${slashSelected}`); + return; + } + if (bar.popup.id) { + input.setAttribute('aria-controls', bar.popup.id); + } + if (!mentionOpen) { + input.removeAttribute('aria-activedescendant'); + } } function pickSlash(index: number): void { @@ -715,22 +884,39 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView submit(); return; } - if (event.key === 'Escape' && state && (state.status === 'running' || state.status === 'awaiting')) { - event.preventDefault(); - deps.api.cancel(sessionId).catch((error: unknown) => deps.onStatus(errorText(error))); + if (event.key === 'Escape' && !event.isComposing) { + handleEscape(event); } }); sendButton.addEventListener('click', submit); // ---- Lifecycle --------------------------------------------------------- + /** #510: never rejects: a failure shows the error notice with Retry (or, over a chat on screen, a status message). */ async function reload(): Promise { - const loaded = await deps.api.get(sessionId); + loadError = null; + updatePhase(); + let loaded: AgentSessionState; + try { + loaded = await deps.api.get(sessionId); + } catch (error) { + if (disposed) { + return; + } + loadError = errorText(error); + loadErrorText.textContent = t('chat.loadFailed', { error: loadError }); + if (state) { + deps.onStatus(loadErrorText.textContent); + } + updatePhase(); + return; + } if (disposed) { return; } state = loaded; rendered.forEach((entry) => entry.node.remove()); rendered.clear(); + drawnItems = null; render(); deps.onDidChange?.(state); if (state.unread) { @@ -738,9 +924,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } } - reload().catch((error: unknown) => { - transcript.append(el('p', { className: 'af-notice is-error', text: `Could not open this chat: ${errorText(error)}` })); - }); + void reload(); return { element, @@ -764,20 +948,21 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView if (before.title !== state.title || before.status !== state.status || before.pendingChanges !== state.pendingChanges) { deps.onDidChange?.(state); } + const said = chatAnnouncement(before, state); + if (said) { + announce(said); + } schedule(); }, focus(): void { input.focus(); }, - insert(text: string): void { - input.value = input.value ? `${input.value}\n${text}` : text; - fitInput(); - input.focus(); - updateSendButton(); - }, + insert: insertText, reload, dispose(): void { disposed = true; + disarmEscape(); + mentionObserver.disconnect(); if (frame) { cancelAnimationFrame(frame); } @@ -785,13 +970,13 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView }; } -const STOP_TEXT: Readonly['stopReason'], string>> = { - end_turn: '', - max_tokens: 'The agent stopped: it reached its output limit.', - max_turn_requests: 'The agent stopped: it reached its limit of steps for one message.', - refusal: 'The agent declined to continue.', - cancelled: 'Stopped.', - error: 'The turn failed.', +const STOP_TEXT: Readonly['stopReason'], MessageKey | null>> = { + end_turn: null, + max_tokens: 'chat.stopReason.maxTokens', + max_turn_requests: 'chat.stopReason.maxTurnRequests', + refusal: 'chat.stopReason.refusal', + cancelled: 'chat.stopReason.cancelled', + error: 'chat.stopReason.error', }; /** AF12: the folder the agent's paths are relative to: its worktree, or the project. */ @@ -802,13 +987,13 @@ function workRootOf(state: AgentSessionState): string | null { function statusText(state: AgentSessionState): string { switch (state.status) { case 'idle': - return 'Ready'; + return t('chat.status.idle'); case 'running': - return 'Working'; + return t('chat.status.running'); case 'awaiting': - return 'Needs your approval'; + return t('chat.status.awaiting'); case 'error': - return 'Error'; + return t('chat.status.error'); } } diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index deb6a8cf..c8a39c68 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -415,6 +415,101 @@ export const en = { 'agent.installTitle': 'See what installing {name} downloads, then confirm', 'agent.updateTitle': 'See whether a newer {name} exists', + // One agent chat (agentFirst/chatView.ts, #510, #511). + 'chat.title': 'Chat', + 'chat.changes': 'Changes', + 'chat.changesCount': 'Changes ({count})', + 'chat.changesTitle': 'Review the changes of this chat ({count})', + 'chat.worktree': 'Worktree', + 'chat.worktreeTitle': 'Show the worktree of this chat', + 'chat.watchXr': 'Watch in XR', + 'chat.watchXrTitle': 'Watch this chat on the table of the XR scene (Agent Flow)', + 'chat.watchXrFollowing': 'Agent Flow is following this chat on the XR table.', + 'chat.watchXrNoScene': 'Open the XR analysis of this project first, then press Watch in XR again.', + 'chat.share': 'Share on claude.ai', + 'chat.shareTitle': 'Continue this chat from claude.ai/code or the Claude mobile app (Remote Control). Asks first.', + 'chat.stopSharing': 'Stop sharing', + 'chat.stopSharingTitle': 'Disconnect this chat from claude.ai and the Claude mobile app', + 'chat.shareFailed': 'Could not share on claude.ai: {error}', + 'chat.shared': 'This chat is shared: continue it from claude.ai/code or the Claude mobile app. Click the badge to copy its link.', + 'chat.unshared': 'This chat is no longer shared with claude.ai.', + 'chat.remoteBadge': 'On claude.ai', + 'chat.remoteBadgeTitle': 'Shared with claude.ai', + 'chat.remoteBadgeUrlTitle': 'Shared with claude.ai: {url} (click to copy)', + 'chat.remoteCopied': 'The claude.ai link of this chat was copied. Open it in the browser or the Claude mobile app.', + 'chat.terminal': 'Continue in terminal', + 'chat.terminalTitle': 'Continue this Claude Code session in a terminal (claude --resume). The next message here picks up what was done there.', + 'chat.terminalLabel': 'Claude Code: {title}', + 'chat.context': 'Context {tokens}', + 'chat.contextTitle': '{used} of {size} tokens of context used', + 'chat.discarded': '{branch} (discarded)', + 'chat.conversation': 'Conversation', + 'chat.loading': 'Loading the chat', + 'chat.loadFailed': 'Could not open this chat: {error}', + 'chat.retry': 'Retry', + 'chat.newActivity': 'New activity', + 'chat.newActivityTitle': 'Scroll to the latest output', + 'chat.empty.heading': 'What do you want to build?', + 'chat.empty.text': 'Describe a change, ask about the code, or type / for the agent\'s commands. Attach files with @. The live analysis on the right follows every change the agent makes.', + 'chat.starters': 'Ideas to start with', + 'chat.starter.architecture': 'Explain this project\'s architecture', + 'chat.starter.complexity': 'Find the most complex functions with the Code-XR analysis and suggest refactors', + 'chat.starter.tests': 'Add tests for the file I have open', + 'chat.starter.review': 'Review my uncommitted changes', + 'chat.placeholder': 'Ask the agent to build, fix or explain something. @ to attach, / for commands.', + 'chat.message': 'Message', + 'chat.commands': 'Commands', + 'chat.mode': 'Mode', + 'chat.agentMode': 'Agent mode', + 'chat.send': 'Send', + 'chat.sendTitle': 'Send (Enter)', + 'chat.stop': 'Stop', + 'chat.stopTitle': 'Stop (Esc twice)', + 'chat.queue': 'Queue message (sent when the agent finishes)', + 'chat.queuedOne': '1 message queued: it is sent when the agent finishes.', + 'chat.queuedMany': '{count} messages queued.', + 'chat.escAgain': 'Press Esc again to stop', + 'chat.restore': 'Restore files to here', + 'chat.restoreTitle': 'Put the project\'s files back as they were before this message. The conversation is kept; effects of commands (network, databases) are not undone.', + 'chat.restoreGroup': 'Restore files', + 'chat.restoreOne': 'Restore 1 file', + 'chat.restoreMany': 'Restore {count} files', + 'chat.close': 'Close', + 'chat.cancel': 'Cancel', + 'chat.andMore': 'and {count} more', + 'chat.fromClaude': 'From claude.ai', + 'chat.thinking': 'Thinking', + 'chat.terminalRunning': 'Running...', + 'chat.terminalNoOutput': '(no output)', + 'chat.exitCode': 'Exit code {code}', + 'chat.exitCodeTruncated': 'Exit code {code} (output truncated)', + 'chat.youChose': 'You chose: {option}', + 'chat.permissionCancelled': 'Cancelled', + 'chat.answered': 'Answered: {outcome}', + 'chat.filesChangedOne': '1 file changed:', + 'chat.filesChangedMany': '{count} files changed:', + 'chat.metrics': 'Metrics', + 'chat.openFile': 'Open {label}', + 'chat.inWorktree': '{label} is in this chat\'s worktree ({path}). The editor shows the main project; merge the branch to bring it in.', + 'chat.plan': 'Plan: {done} of {total} done', + 'chat.status.idle': 'Ready', + 'chat.status.running': 'Working', + 'chat.status.awaiting': 'Needs your approval', + 'chat.status.error': 'Error', + 'chat.stopReason.maxTokens': 'The agent stopped: it reached its output limit.', + 'chat.stopReason.maxTurnRequests': 'The agent stopped: it reached its limit of steps for one message.', + 'chat.stopReason.refusal': 'The agent declined to continue.', + 'chat.stopReason.cancelled': 'Stopped.', + 'chat.stopReason.error': 'The turn failed.', + 'chat.tool.pending': 'Waiting', + 'chat.tool.inProgress': 'Running', + 'chat.tool.completed': 'Done', + 'chat.tool.failed': 'Failed', + 'chat.announce.finished': 'The agent finished.', + 'chat.announce.stopped': 'The agent stopped.', + 'chat.announce.permission': 'Needs permission: {title}', + 'chat.announce.error': 'The agent ran into an error.', + // Status bar. 'status.noProblems': 'No Problems', 'status.problems': 'Errors: {errors}, Warnings: {warnings}', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index d02ce7dc..b8be2c80 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -418,6 +418,101 @@ export const es: Readonly> = { 'agent.installTitle': 'Ver qué descarga la instalación de {name} y confirmar', 'agent.updateTitle': 'Ver si hay una versión más reciente de {name}', + // Un chat con un agente (agentFirst/chatView.ts, #510, #511). + 'chat.title': 'Chat', + 'chat.changes': 'Cambios', + 'chat.changesCount': 'Cambios ({count})', + 'chat.changesTitle': 'Revisar los cambios de este chat ({count})', + 'chat.worktree': 'Worktree', + 'chat.worktreeTitle': 'Mostrar el worktree de este chat', + 'chat.watchXr': 'Ver en XR', + 'chat.watchXrTitle': 'Ver este chat sobre la mesa de la escena XR (Agent Flow)', + 'chat.watchXrFollowing': 'Agent Flow sigue este chat sobre la mesa XR.', + 'chat.watchXrNoScene': 'Abre primero el análisis XR de este proyecto y vuelve a pulsar Ver en XR.', + 'chat.share': 'Compartir en claude.ai', + 'chat.shareTitle': 'Continuar este chat desde claude.ai/code o la app móvil de Claude (Remote Control). Pide confirmación antes.', + 'chat.stopSharing': 'Dejar de compartir', + 'chat.stopSharingTitle': 'Desconectar este chat de claude.ai y de la app móvil de Claude', + 'chat.shareFailed': 'No se pudo compartir en claude.ai: {error}', + 'chat.shared': 'Este chat está compartido: continúalo desde claude.ai/code o la app móvil de Claude. Haz clic en la insignia para copiar su enlace.', + 'chat.unshared': 'Este chat ya no se comparte con claude.ai.', + 'chat.remoteBadge': 'En claude.ai', + 'chat.remoteBadgeTitle': 'Compartido con claude.ai', + 'chat.remoteBadgeUrlTitle': 'Compartido con claude.ai: {url} (haz clic para copiarlo)', + 'chat.remoteCopied': 'Se copió el enlace de claude.ai de este chat. Ábrelo en el navegador o en la app móvil de Claude.', + 'chat.terminal': 'Continuar en el terminal', + 'chat.terminalTitle': 'Continuar esta sesión de Claude Code en un terminal (claude --resume). El siguiente mensaje aquí retoma lo que se hizo allí.', + 'chat.terminalLabel': 'Claude Code: {title}', + 'chat.context': 'Contexto {tokens}', + 'chat.contextTitle': '{used} de {size} tokens de contexto usados', + 'chat.discarded': '{branch} (descartada)', + 'chat.conversation': 'Conversación', + 'chat.loading': 'Cargando el chat', + 'chat.loadFailed': 'No se pudo abrir este chat: {error}', + 'chat.retry': 'Reintentar', + 'chat.newActivity': 'Actividad nueva', + 'chat.newActivityTitle': 'Desplazarse a la última salida', + 'chat.empty.heading': '¿Qué quieres construir?', + 'chat.empty.text': 'Describe un cambio, pregunta sobre el código o escribe / para ver los comandos del agente. Adjunta archivos con @. El análisis en vivo de la derecha sigue cada cambio que hace el agente.', + 'chat.starters': 'Ideas para empezar', + 'chat.starter.architecture': 'Explica la arquitectura de este proyecto', + 'chat.starter.complexity': 'Busca las funciones más complejas con el análisis de Code-XR y sugiere refactorizaciones', + 'chat.starter.tests': 'Añade pruebas para el archivo que tengo abierto', + 'chat.starter.review': 'Revisa mis cambios sin confirmar', + 'chat.placeholder': 'Pide al agente que construya, corrija o explique algo. @ para adjuntar, / para comandos.', + 'chat.message': 'Mensaje', + 'chat.commands': 'Comandos', + 'chat.mode': 'Modo', + 'chat.agentMode': 'Modo del agente', + 'chat.send': 'Enviar', + 'chat.sendTitle': 'Enviar (Entrar)', + 'chat.stop': 'Detener', + 'chat.stopTitle': 'Detener (Esc dos veces)', + 'chat.queue': 'Poner el mensaje en cola (se envía cuando el agente termine)', + 'chat.queuedOne': '1 mensaje en cola: se envía cuando el agente termine.', + 'chat.queuedMany': '{count} mensajes en cola.', + 'chat.escAgain': 'Pulsa Esc otra vez para detener', + 'chat.restore': 'Restaurar los archivos hasta aquí', + 'chat.restoreTitle': 'Devolver los archivos del proyecto a como estaban antes de este mensaje. La conversación se conserva; los efectos de los comandos (red, bases de datos) no se deshacen.', + 'chat.restoreGroup': 'Restaurar archivos', + 'chat.restoreOne': 'Restaurar 1 archivo', + 'chat.restoreMany': 'Restaurar {count} archivos', + 'chat.close': 'Cerrar', + 'chat.cancel': 'Cancelar', + 'chat.andMore': 'y {count} más', + 'chat.fromClaude': 'Desde claude.ai', + 'chat.thinking': 'Razonamiento', + 'chat.terminalRunning': 'En ejecución...', + 'chat.terminalNoOutput': '(sin salida)', + 'chat.exitCode': 'Código de salida {code}', + 'chat.exitCodeTruncated': 'Código de salida {code} (salida truncada)', + 'chat.youChose': 'Elegiste: {option}', + 'chat.permissionCancelled': 'Cancelado', + 'chat.answered': 'Respuesta: {outcome}', + 'chat.filesChangedOne': '1 archivo cambiado:', + 'chat.filesChangedMany': '{count} archivos cambiados:', + 'chat.metrics': 'Métricas', + 'chat.openFile': 'Abrir {label}', + 'chat.inWorktree': '{label} está en el worktree de este chat ({path}). El editor muestra el proyecto principal; fusiona la rama para traerlo.', + 'chat.plan': 'Plan: {done} de {total} hechos', + 'chat.status.idle': 'Listo', + 'chat.status.running': 'Trabajando', + 'chat.status.awaiting': 'Necesita tu aprobación', + 'chat.status.error': 'Error', + 'chat.stopReason.maxTokens': 'El agente se detuvo: alcanzó su límite de salida.', + 'chat.stopReason.maxTurnRequests': 'El agente se detuvo: alcanzó su límite de pasos para un mensaje.', + 'chat.stopReason.refusal': 'El agente rehusó continuar.', + 'chat.stopReason.cancelled': 'Detenido.', + 'chat.stopReason.error': 'El turno falló.', + 'chat.tool.pending': 'En espera', + 'chat.tool.inProgress': 'En ejecución', + 'chat.tool.completed': 'Hecho', + 'chat.tool.failed': 'Error', + 'chat.announce.finished': 'El agente terminó.', + 'chat.announce.stopped': 'El agente se detuvo.', + 'chat.announce.permission': 'Necesita permiso: {title}', + 'chat.announce.error': 'El agente encontró un error.', + // Barra de estado. 'status.noProblems': 'No hay problemas', 'status.problems': 'Errores: {errors}, advertencias: {warnings}', diff --git a/apps/ide/test/chatStates.test.ts b/apps/ide/test/chatStates.test.ts new file mode 100644 index 00000000..5f777d4f --- /dev/null +++ b/apps/ide/test/chatStates.test.ts @@ -0,0 +1,106 @@ +import { describe, it, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import type { AgentSessionState, TranscriptItem } from '../src/shared/agentSession.ts'; +import { setLocale, t } from '../src/shared/i18n/i18n.ts'; +import { chatAnnouncement, chatPhase, ESCAPE_STOP_WINDOW_MS, escapeIntent, starterPrompts } from '../src/renderer/agentFirst/chatModel.ts'; + +/** #510 (O8) and #511 (O9): the chat view's loading, starter, Esc and announcement helpers. */ + +afterEach(() => setLocale('en')); + +type Status = AgentSessionState['status']; +const user: TranscriptItem = { kind: 'user', id: 'u1', text: 'Fix it', at: '2026-12-05T10:00:00.000Z' }; +const permission = (id: string, outcome?: string): TranscriptItem => ({ + kind: 'permission', id, title: `Edit ${id}.ts`, options: [{ id: 'allow', name: 'Allow', kind: 'allow_once' }], ...(outcome ? { outcome } : {}), +}); +const turnEnd = (stopReason: Extract['stopReason']): TranscriptItem => ({ kind: 'turn-end', id: 't1', stopReason, at: '2026-12-05T10:01:00.000Z' }); +const at = (status: Status, items: readonly TranscriptItem[] = [user]): Pick => ({ status, items }); + +describe('chatPhase (#510)', () => { + it('shows a skeleton until the first load, never the empty prompt', () => { + assert.equal(chatPhase(null, null), 'loading'); + }); + + it('shows the error with Retry when the first load failed', () => { + assert.equal(chatPhase(null, 'boom'), 'error'); + }); + + it('tells an empty chat from a conversation', () => { + assert.equal(chatPhase({ items: [] }, null), 'empty'); + assert.equal(chatPhase({ items: [user] }, null), 'ready'); + }); + + it('keeps a loaded transcript when a later reload fails', () => { + assert.equal(chatPhase({ items: [user] }, 'boom'), 'ready'); + assert.equal(chatPhase({ items: [] }, 'boom'), 'empty'); + }); +}); + +describe('starterPrompts (#510)', () => { + it('offers three or four prompts, one of them on the Code-XR analysis, in both languages', () => { + const keys = starterPrompts(); + assert.ok(keys.length >= 3 && keys.length <= 4); + assert.equal(new Set(keys).size, keys.length); + assert.ok(keys.some((key) => /Code-XR/.test(t(key)))); + setLocale('es'); + for (const key of keys) { + assert.notEqual(t(key), ''); + } + assert.equal(t('chat.starter.review'), 'Revisa mis cambios sin confirmar'); + }); +}); + +describe('escapeIntent (#510)', () => { + it('does nothing when no turn runs', () => { + assert.equal(escapeIntent('idle', null, 100), 'none'); + assert.equal(escapeIntent('error', 50, 100), 'none'); + }); + + it('arms on the first Esc of a running or awaiting turn', () => { + assert.equal(escapeIntent('running', null, 100), 'arm'); + assert.equal(escapeIntent('awaiting', null, 100), 'arm'); + }); + + it('stops on a second Esc within the window, and re-arms after it', () => { + assert.equal(escapeIntent('running', 1000, 1000 + ESCAPE_STOP_WINDOW_MS), 'stop'); + assert.equal(escapeIntent('awaiting', 1000, 1200), 'stop'); + assert.equal(escapeIntent('running', 1000, 1001 + ESCAPE_STOP_WINDOW_MS), 'arm'); + assert.equal(ESCAPE_STOP_WINDOW_MS, 1500); + }); + + it('does not stop on a clock that went backwards', () => { + assert.equal(escapeIntent('running', 1000, 900), 'arm'); + }); +}); + +describe('chatAnnouncement (#511)', () => { + it('says nothing on the first load or while the reply streams', () => { + assert.equal(chatAnnouncement(null, at('running')), null); + assert.equal(chatAnnouncement(at('running'), at('running', [user, { kind: 'assistant', id: 'a1', text: 'Hel' }])), null); + assert.equal(chatAnnouncement(at('idle'), at('running')), null); + }); + + it('announces a finished turn, and a stopped one as stopped', () => { + assert.equal(chatAnnouncement(at('running'), at('idle', [user, turnEnd('end_turn')])), 'The agent finished.'); + assert.equal(chatAnnouncement(at('awaiting'), at('idle', [user, turnEnd('cancelled')])), 'The agent stopped.'); + }); + + it('announces each new permission request once, with its title', () => { + const first = at('awaiting', [user, permission('p1')]); + assert.equal(chatAnnouncement(at('running'), first), 'Needs permission: Edit p1.ts'); + assert.equal(chatAnnouncement(first, at('awaiting', [user, permission('p1')])), null); + const second = at('awaiting', [user, permission('p1', 'allow'), permission('p2')]); + assert.equal(chatAnnouncement(first, second), 'Needs permission: Edit p2.ts'); + assert.equal(chatAnnouncement(second, at('running', [user, permission('p1', 'allow'), permission('p2', 'allow')])), null); + }); + + it('announces an error once', () => { + assert.equal(chatAnnouncement(at('running'), at('error', [user, turnEnd('error')])), 'The agent ran into an error.'); + assert.equal(chatAnnouncement(at('error'), at('error')), null); + }); + + it('speaks Spanish when the IDE does', () => { + setLocale('es'); + assert.equal(chatAnnouncement(at('running'), at('idle', [user, turnEnd('end_turn')])), 'El agente terminó.'); + }); +}); diff --git a/docs/ide/agent-first-test-guide.md b/docs/ide/agent-first-test-guide.md index fc9d761a..321f7323 100644 --- a/docs/ide/agent-first-test-guide.md +++ b/docs/ide/agent-first-test-guide.md @@ -35,7 +35,7 @@ Everything here has unit tests and the IDE smoke test, run on Linux, Windows and |---|---|---|---| | 3.1 | #268 | **New chat**, then ask for a small real change ("add input validation to X"). | The chat opens as a tab, streams the answer, shows the plan and each tool call (reads, edits with a diff, commands with their output). | | 3.2 | #266 | When the agent asks to edit or run something. | A card with Allow / Always allow / Reject. The chat in the list shows "Needs your approval"; with the window in the background you get a notification with *Open chat*. | -| 3.3 | #268 | Type `/` and `@` in the composer; change the mode and model selects; send a second message while the agent works. | Slash commands and file attachments are offered; the message is queued and sent when the turn ends. **Stop** (or Esc) cancels a turn. | +| 3.3 | #268 | Type `/` and `@` in the composer; change the mode and model selects; send a second message while the agent works. | Slash commands and file attachments are offered; the message is queued and sent when the turn ends. **Stop** (or Esc twice within 1.5 s, #510) cancels a turn. | | 3.4 | #275 | Ask: "Use the Code-XR tools to tell me the three most complex files". | The agent calls `get_hotspots` (tool card titled with `[Code-XR]`) and answers from your analysis. | | 3.5 | #272 | Create two chats, rename one, search, restart the IDE. | Chats are grouped by project with status and time; tabs come back after the restart; a deleted chat closes its tab. | | 3.6 | #298 | On a ready agent that you have already used in this project from its own CLI, press **Import chats**, keep the ticks and press **Import**. | Your earlier chats for this folder are listed with their dates; the chosen ones appear in the Chats list. Opening one shows its messages; sending a message continues it. Importing again does not duplicate them. | From b1472ac995a00be8acfc1a01a3f7aba2821b882f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:22:05 +0000 Subject: [PATCH 10/74] feat(ide): one toast per chat, pausable info toasts, errors read once (#509) A chat's new notice replaces its previous toast and closes when the chat is opened or read (createSessionNoticeTracker). Info toasts pause while hovered or focused and resume with the time left; a toast that closes on its own is no longer pinned just for having actions. Error toasts are role=alert and are no longer announced a second time. --- .../src/renderer/agentFirst/sessionNotices.ts | 57 ++++++++++++++ apps/ide/src/renderer/notifications.ts | 32 +++++--- apps/ide/src/renderer/toastTimer.ts | 77 +++++++++++++++++++ 3 files changed, 157 insertions(+), 9 deletions(-) create mode 100644 apps/ide/src/renderer/agentFirst/sessionNotices.ts create mode 100644 apps/ide/src/renderer/toastTimer.ts diff --git a/apps/ide/src/renderer/agentFirst/sessionNotices.ts b/apps/ide/src/renderer/agentFirst/sessionNotices.ts new file mode 100644 index 00000000..20691bfb --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/sessionNotices.ts @@ -0,0 +1,57 @@ +/** + * #509: at most one toast per chat. "X finished", "X needs your approval" and + * "X failed" used to stack up one per event overnight; now a new event for a + * chat replaces its previous toast, and opening or reading the chat closes it. + * Pure: it holds the handles the notification center returns, no DOM. + */ + +export interface NoticeHandle { + close(): void; +} + +export interface SessionNoticeTracker { + /** + * What a notice shown later must present to `show`: a notice prepared + * before the chat was opened (its title is read asynchronously) is dropped. + */ + claim(sessionId: string): number; + /** Shows the chat's notice (`open` makes it), closing the previous one. False when `claim` went stale. */ + show(sessionId: string, claim: number, open: () => NoticeHandle): boolean; + /** The chat was opened or read: its notice closes, and pending ones are dropped. */ + close(sessionId: string): void; + /** The notice closed by itself (its X, its action, its timeout). */ + forget(sessionId: string, handle: NoticeHandle): void; + /** How many chats have a notice on screen (tests). */ + readonly size: number; +} + +export function createSessionNoticeTracker(): SessionNoticeTracker { + const handles = new Map(); + const generations = new Map(); + const generation = (sessionId: string): number => generations.get(sessionId) ?? 0; + return { + claim: generation, + show(sessionId, claim, open): boolean { + if (claim !== generation(sessionId)) { + return false; + } + handles.get(sessionId)?.close(); + handles.set(sessionId, open()); + return true; + }, + close(sessionId): void { + generations.set(sessionId, generation(sessionId) + 1); + const handle = handles.get(sessionId); + handles.delete(sessionId); + handle?.close(); + }, + forget(sessionId, handle): void { + if (handles.get(sessionId) === handle) { + handles.delete(sessionId); + } + }, + get size(): number { + return handles.size; + }, + }; +} diff --git a/apps/ide/src/renderer/notifications.ts b/apps/ide/src/renderer/notifications.ts index e663bbfb..f6e4ca0f 100644 --- a/apps/ide/src/renderer/notifications.ts +++ b/apps/ide/src/renderer/notifications.ts @@ -2,6 +2,7 @@ import { t, type MessageKey } from '../shared/i18n/i18n.ts'; import { closeIcon, el } from './dom.ts'; import { clampPercent } from './progressPercent.ts'; import { stackLayout } from './notificationStack.ts'; +import { createToastTimer, type ToastTimer } from './toastTimer.ts'; /** * VS Code-style notifications (#153): toasts stacked in the window's @@ -9,7 +10,8 @@ import { stackLayout } from './notificationStack.ts'; * close button, and progress notifications whose bar and message update in * place until the task ends. * - * Info toasts fade on their own; warnings and errors stay until dismissed. + * Info toasts fade on their own (paused while hovered or focused, #509); + * warnings and errors stay until dismissed. * A polite live region announces each new notification once, so a progress * bar moving does not flood a screen reader. */ @@ -133,14 +135,14 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter return { notify(severity, message, options = {}): NotificationHandle { - let timer: ReturnType | undefined; + let timer: ToastTimer | undefined; const body: Node[] = [el('p', { className: 'notification-message', text: message })]; if (options.detail) { body.push(el('p', { className: 'notification-detail', text: options.detail })); } const handle: NotificationHandle = { close(): void { - clearTimeout(timer); + timer?.cancel(); drop(root); }, }; @@ -158,15 +160,27 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter handle.close(); options.onDismiss?.(); }; - const root = shell(severity, body, dismiss, severity === 'error' || Boolean(options.actions?.length)); - root.dataset['severity'] = severity; const timeout = options.timeoutMs ?? (severity === 'info' && !options.actions?.length ? INFO_TIMEOUT_MS : 0); + // #509: a toast that closes on its own is not pinned, actions or not; one that waits for an answer is. + const root = shell(severity, body, dismiss, severity === 'error' || (Boolean(options.actions?.length) && timeout <= 0)); + root.dataset['severity'] = severity; if (timeout > 0) { - timer = setTimeout(dismiss, timeout); - // Reading a toast keeps it. - root.addEventListener('mouseenter', () => clearTimeout(timer)); + const running = createToastTimer(timeout, dismiss); + timer = running; + // #509: reading a toast, with the pointer or the keyboard, keeps it until the reader leaves. + root.addEventListener('mouseenter', () => running.hold('hover')); + root.addEventListener('mouseleave', () => running.release('hover')); + root.addEventListener('focusin', () => running.hold('focus')); + root.addEventListener('focusout', (event) => { + if (!(event.relatedTarget instanceof Node && root.contains(event.relatedTarget))) { + running.release('focus'); + } + }); + } + // #509: an error toast is role=alert, which a screen reader reads on its own; announcing it too read it twice. + if (severity !== 'error') { + announce(`${t(SEVERITY_LABEL[severity])}: ${message}`); } - announce(`${t(SEVERITY_LABEL[severity])}: ${message}`); return handle; }, diff --git a/apps/ide/src/renderer/toastTimer.ts b/apps/ide/src/renderer/toastTimer.ts new file mode 100644 index 00000000..f4878c96 --- /dev/null +++ b/apps/ide/src/renderer/toastTimer.ts @@ -0,0 +1,77 @@ +/** + * #509: the timeout of an info toast, paused while the person reads it. It + * holds while the pointer is over the toast OR the keyboard focus is in it, + * and runs again, for the time it had left, once neither is true. No DOM: + * notifications.ts wires mouseenter/mouseleave and focusin/focusout to it. + */ + +export interface TimerScheduler { + now(): number; + set(run: () => void, ms: number): unknown; + clear(id: unknown): void; +} + +export type ToastHold = 'hover' | 'focus'; + +export interface ToastTimer { + hold(reason: ToastHold): void; + release(reason: ToastHold): void; + /** Stops it for good (the toast closed). */ + cancel(): void; + readonly paused: boolean; +} + +const realScheduler: TimerScheduler = { + now: () => Date.now(), + set: (run, ms) => setTimeout(run, ms), + clear: (id) => clearTimeout(id as ReturnType), +}; + +export function createToastTimer(ms: number, onExpire: () => void, scheduler: TimerScheduler = realScheduler): ToastTimer { + let remaining = ms; + let startedAt = scheduler.now(); + let id: unknown = scheduler.set(fire, remaining); + let done = false; + const holds = new Set(); + + function fire(): void { + id = undefined; + if (!done) { + done = true; + onExpire(); + } + } + + return { + hold(reason): void { + if (done) { + return; + } + if (holds.size === 0 && id !== undefined) { + scheduler.clear(id); + id = undefined; + remaining = Math.max(0, remaining - (scheduler.now() - startedAt)); + } + holds.add(reason); + }, + release(reason): void { + if (done || !holds.delete(reason) || holds.size > 0) { + return; + } + // A toast read to its last second still gets a moment before it goes. + remaining = Math.max(remaining, 1500); + startedAt = scheduler.now(); + id = scheduler.set(fire, remaining); + }, + cancel(): void { + done = true; + if (id !== undefined) { + scheduler.clear(id); + id = undefined; + } + }, + get paused(): boolean { + return holds.size > 0; + }, + }; +} From 6fb89b62721151d3f1aabe4059cc96be09a42f50 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:22:10 +0000 Subject: [PATCH 11/74] feat(ide): pinned Needs you chats, attention badge and next-chat command (#508, #509) - Chats list: a pinned "Needs you" group across projects (approval, then failed, then unread), hidden while searching; collapsed projects are remembered across restarts. - The Chats activity item gets a badge (Workbench.setActivityBadge); the status bar adds "N done" and opens the most urgent chat on click. - chat.nextNeedingAttention, default key Ctrl/Cmd+K Ctrl/Cmd+N. - The dock says "No folder" instead of "Waiting" with no folder open. - Background refreshes wait while a rename field or delete confirmation is open; focus is restored by session after a redraw; the list uses a roving tabindex with Up/Down/Home/End. - Status labels, relative times and attention text in English and Spanish. --- .../src/renderer/agentFirst/agentWorkbench.ts | 67 +++-- .../src/renderer/agentFirst/sessionsModel.ts | 173 ++++++++++- .../src/renderer/agentFirst/sessionsView.ts | 270 ++++++++++++++---- apps/ide/src/renderer/workbench.ts | 24 ++ apps/ide/src/shared/defaultKeybindings.ts | 2 + apps/ide/src/shared/i18n/messages.en.ts | 28 ++ apps/ide/src/shared/i18n/messages.es.ts | 28 ++ apps/ide/test/agentFirst.test.ts | 2 +- apps/ide/test/chatsAttention.test.ts | 248 ++++++++++++++++ apps/ide/test/keybindingDefaults.test.ts | 2 +- 10 files changed, 751 insertions(+), 93 deletions(-) create mode 100644 apps/ide/test/chatsAttention.test.ts diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 32202f25..226b5bba 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -16,6 +16,9 @@ import { changesIdOf, changesTabId } from './changesModel.ts'; import { createGettingStartedView, type GettingStartedView } from './gettingStartedView.ts'; import { ONBOARDED_KEY, progressTitle, shouldShowOnboarding } from './agentSetupModel.ts'; import { errorText as setupErrorText } from './agentSetup.ts'; +import { attentionText } from './sessionsModel.ts'; +import { createSessionNoticeTracker } from './sessionNotices.ts'; +import { t } from '../../shared/i18n/i18n.ts'; import './agentFirst.css'; /** @@ -78,6 +81,8 @@ export interface AgentWorkbench { const MODE_KEY = 'codexr.layout.mode'; const GUIDE_TAB_ID = 'guide:getting-started'; +/** #509: how long a "finished" toast stays when nobody reads it. */ +const FINISHED_TOAST_MS = 10_000; const DOCK_ART = 'M12 3l8 4.5v9L12 21l-8-4.5v-9zM12 12l8-4.5M12 12v9M12 12L4 7.5'; export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWorkbench { @@ -100,7 +105,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork const hideDock = el('button', { className: 'icon-button', attrs: { type: 'button', title: 'Hide the live analysis column', 'aria-label': 'Hide the live analysis column' } }, [closeIcon()]); hideDock.addEventListener('click', () => setDockHidden(true)); // CI3: the dock says what is happening instead of "Waiting" while the first analysis runs. - const live = el('span', { className: 'af-live', text: 'Waiting', attrs: { 'data-state': 'idle', 'data-testid': 'af-dock-live' } }); + const live = el('span', { className: 'af-live', text: t('dock.live.waiting'), attrs: { 'data-state': 'idle', 'data-testid': 'af-dock-live' } }); const dockBar = el('div', { className: 'progress-bar' }); const dockTrack = el('div', { className: 'progress-track', attrs: { role: 'progressbar', 'aria-label': 'Analysis progress' } }, [dockBar]); const dockStep = el('p', { className: 'muted small af-dock-step' }); @@ -114,7 +119,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork function renderDock(): void { const folder = options.hasFolder(); const running = dockAnalysis !== null && folder; - live.textContent = running ? 'Analysing' : 'Waiting'; + // #508: with no folder open there is nothing to wait for. + live.textContent = running ? t('dock.live.analysing') : folder ? t('dock.live.waiting') : t('dock.live.noFolder'); live.dataset['state'] = running ? 'running' : 'idle'; dockNote.textContent = running ? `${dockAnalysis?.title ?? ''} The scene opens here when it is ready.` @@ -239,6 +245,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork onShow: () => { activeChatId = sessionId; sessions.setActive(sessionId); + // #509: the chat is on screen: its toast has done its job. + notices.close(sessionId); api.markRead(sessionId).catch(() => undefined); }, onHide: () => { @@ -303,23 +311,27 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork openBuiltinAgents: () => workbench.showView('agents'), onRemoved: (id) => tabClosers.get(id)?.(), onAttention: (counts) => { - const parts = []; - if (counts.running > 0) { - parts.push(`${counts.running} working`); - } - if (counts.waiting > 0) { - parts.push(`${counts.waiting} waiting for you`); - } - attention.textContent = parts.length ? `Agents: ${parts.join(', ')}` : ''; - attention.hidden = parts.length === 0; + // #508: the status bar says what is going on, finished chats included; the Chats item counts the "Needs you" group. + const text = attentionText(counts); + attention.textContent = text; + attention.hidden = text === ''; + attention.title = counts.needsYou > 0 ? t('chats.attention.openUrgent') : t('chats.attention.showChats'); + workbench.setActivityBadge('chats', counts.needsYou, text); }, }); - const attention = el('button', { className: 'status-item', attrs: { type: 'button', hidden: '', 'data-testid': 'af-attention', title: 'Show the chats' } }); - attention.addEventListener('click', () => workbench.showView('chats')); + const attention = el('button', { className: 'status-item', attrs: { type: 'button', hidden: '', 'data-testid': 'af-attention', title: t('chats.attention.showChats') } }); + // #508: clicking opens the chat that needs the person most, or the list when none does. + attention.addEventListener('click', () => { + if (!sessions.openNeedingAttention('urgent')) { + workbench.showView('chats'); + } + }); workbench.editorStatus.parentElement?.prepend(attention); // ---- Messages from the main process ------------------------------------- const lastSeen = new Map(); + /** #509: one toast per chat. */ + const notices = createSessionNoticeTracker(); api.onMessage((message: AgentSessionMessage) => { if (message.kind === 'install-progress') { installProgress(message); @@ -470,14 +482,29 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork if (event.type === 'status') { lastSeen.set(sessionId, event.status); } + // #509: read here or in another window: its toast closes. + if (event.type === 'read') { + notices.close(sessionId); + } } function notify(sessionId: string, severity: 'info' | 'warning' | 'error', fallback: string): void { - api.get(sessionId).then((state) => { - options.notifications.notify(severity, `${state.title}: ${fallback.replace(/^An agent/, state.agentName)}`, { - actions: [{ label: 'Open chat', run: () => void openChat(sessionId) }], + // #509: the title is read asynchronously; a chat opened meanwhile drops this toast. + const claim = notices.claim(sessionId); + const show = (message: string): void => { + notices.show(sessionId, claim, () => { + const handle = options.notifications.notify(severity, message, { + actions: [{ label: 'Open chat', run: () => void openChat(sessionId) }], + // A finished chat is news, not a question: it fades (paused while read); approvals and failures stay. + ...(severity === 'info' ? { timeoutMs: FINISHED_TOAST_MS } : {}), + onDismiss: () => notices.forget(sessionId, handle), + }); + return handle; }); - }).catch(() => options.notifications.notify(severity, fallback)); + }; + api.get(sessionId).then((state) => { + show(`${state.title}: ${fallback.replace(/^An agent/, state.agentName)}`); + }).catch(() => show(fallback)); } // ---- Layout mode (AF4) -------------------------------------------------- @@ -505,6 +532,12 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork showGettingStarted().catch((error: unknown) => options.onStatus(setupErrorText(error))); } }); options.registry.register({ id: 'chat.showChats', category: 'Chat', title: 'Show Chats', run: () => workbench.showView('chats') }); + // #508: walks the "Needs you" group, from the chat on screen. + options.registry.register({ id: 'chat.nextNeedingAttention', category: 'Chat', title: t('chats.nextNeedingAttention'), run: () => { + if (!sessions.openNeedingAttention('next')) { + options.onStatus(t('chats.nothingNeedsYou')); + } + } }); options.registry.register({ id: 'chat.searchChats', category: 'Chat', title: 'Search Chats', run: () => { workbench.showView('chats'); sessions.focusSearch(); diff --git a/apps/ide/src/renderer/agentFirst/sessionsModel.ts b/apps/ide/src/renderer/agentFirst/sessionsModel.ts index 3154b340..73a6a885 100644 --- a/apps/ide/src/renderer/agentFirst/sessionsModel.ts +++ b/apps/ide/src/renderer/agentFirst/sessionsModel.ts @@ -1,4 +1,4 @@ -import { t } from '../../shared/i18n/i18n.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; import type { AgentView, ProjectSessions, SessionStatus, SessionSummary } from '../../shared/agentSession.ts'; /** @@ -28,16 +28,16 @@ export function filterProjects(projects: readonly ProjectSessions[], query: stri /** What the status dot means, for its tooltip and screen readers. */ export function statusLabel(session: Pick): string { - const base: Record = { - idle: 'Done', - running: 'Working', - awaiting: 'Needs your approval', - error: 'Failed', + const base: Record = { + idle: 'chats.status.idle', + running: 'chats.status.running', + awaiting: 'chats.status.awaiting', + error: 'chats.status.error', }; - return session.unread && session.status === 'idle' ? 'Done, not read yet' : base[session.status]; + return t(session.unread && session.status === 'idle' ? 'chats.status.unread' : base[session.status]); } -/** "now", "5 min", "3 h", "2 d", or a date for older chats. */ +/** "now", "5 min", "3 h", "2 d", or a date for older chats (in the IDE's language). */ export function shortTime(iso: string, nowMs: number): string { const then = Date.parse(iso); if (!Number.isFinite(then)) { @@ -45,38 +45,181 @@ export function shortTime(iso: string, nowMs: number): string { } const seconds = Math.max(0, Math.round((nowMs - then) / 1000)); if (seconds < 60) { - return 'now'; + return t('chats.time.now'); } if (seconds < 3600) { - return `${Math.floor(seconds / 60)} min`; + return t('chats.time.minutes', { count: Math.floor(seconds / 60) }); } if (seconds < 86_400) { - return `${Math.floor(seconds / 3600)} h`; + return t('chats.time.hours', { count: Math.floor(seconds / 3600) }); } if (seconds < 7 * 86_400) { - return `${Math.floor(seconds / 86_400)} d`; + return t('chats.time.days', { count: Math.floor(seconds / 86_400) }); } return new Date(then).toISOString().slice(0, 10); } +/** Why a chat is in the pinned "Needs you" group (#508), most urgent first. */ +export type NeedsYouReason = 'awaiting' | 'failed' | 'unread'; +const REASON_RANK: Readonly> = { awaiting: 0, failed: 1, unread: 2 }; + +export interface NeedsYouEntry { + readonly project: ProjectSessions; + readonly session: SessionSummary; + readonly reason: NeedsYouReason; +} + +/** + * Why the chat needs the person, or null. An approval always does; a failed + * or finished turn does until the chat is read (a failed chat keeps its + * status until its next turn, and would otherwise stay pinned for good). + */ +export function needsYouReason(session: Pick): NeedsYouReason | null { + if (session.status === 'awaiting') { + return 'awaiting'; + } + if (!session.unread) { + return null; + } + return session.status === 'error' ? 'failed' : 'unread'; +} + +/** #508: the chats that wait for the person, across projects: approvals, then failures, then unread; newest first within each. */ +export function needsYou(projects: readonly ProjectSessions[]): NeedsYouEntry[] { + const entries: NeedsYouEntry[] = []; + for (const project of projects) { + for (const session of project.sessions) { + const reason = needsYouReason(session); + if (reason) { + entries.push({ project, session, reason }); + } + } + } + const time = (entry: NeedsYouEntry): number => Date.parse(entry.session.updatedAt) || 0; + return entries.sort((a, b) => REASON_RANK[a.reason] - REASON_RANK[b.reason] || time(b) - time(a)); +} + +/** + * #508: the chat "Next Chat Needing Attention" opens: the one after + * `activeId` in the "Needs you" order, wrapping round; the most urgent one + * when the active chat is not in the group. Null when no other chat needs the person. + */ +export function nextAttention(projects: readonly ProjectSessions[], activeId: string | null): NeedsYouEntry | null { + const entries = needsYou(projects); + const at = activeId === null ? -1 : entries.findIndex((entry) => entry.session.id === activeId); + if (at === -1) { + return entries[0] ?? null; + } + return entries.length < 2 ? null : entries[(at + 1) % entries.length] ?? null; +} + +export interface AttentionCounts { + readonly running: number; + /** Waiting for an approval. */ + readonly waiting: number; + /** Any chat with something not seen yet. */ + readonly unread: number; + /** Failed and not read yet. */ + readonly failed: number; + /** Finished and not read yet. */ + readonly done: number; + /** The chats of the "Needs you" group (the Chats activity badge). */ + readonly needsYou: number; +} + /** How many chats across all projects are working, and how many wait for the person. */ -export function attentionCounts(projects: readonly ProjectSessions[]): { readonly running: number; readonly waiting: number; readonly unread: number } { +export function attentionCounts(projects: readonly ProjectSessions[]): AttentionCounts { let running = 0; let waiting = 0; let unread = 0; + let failed = 0; + let done = 0; + let pinned = 0; for (const project of projects) { for (const session of project.sessions) { if (session.status === 'running') { running += 1; - } else if (session.status === 'awaiting') { + } + const reason = needsYouReason(session); + if (reason) { + pinned += 1; + } + if (reason === 'awaiting') { waiting += 1; + } else if (reason === 'failed') { + failed += 1; + } else if (reason === 'unread' && session.status === 'idle') { + done += 1; } if (session.unread) { unread += 1; } } } - return { running, waiting, unread }; + return { running, waiting, unread, failed, done, needsYou: pinned }; +} + +/** #508: the status-bar text, "Agents: 1 working, 2 waiting for you, 3 done"; empty when nothing is going on. */ +export function attentionText(counts: Pick): string { + const part = (count: number, one: MessageKey, many: MessageKey): string[] => (count <= 0 ? [] : [count === 1 ? t(one) : t(many, { count })]); + const parts = [ + ...part(counts.running, 'chats.attention.workingOne', 'chats.attention.workingMany'), + ...part(counts.waiting, 'chats.attention.waitingOne', 'chats.attention.waitingMany'), + ...part(counts.failed, 'chats.attention.failedOne', 'chats.attention.failedMany'), + ...part(counts.done, 'chats.attention.doneOne', 'chats.attention.doneMany'), + ]; + return parts.length === 0 ? '' : t('chats.attention.text', { parts: parts.join(', ') }); +} + +/** #508: the collapsed projects, as stored (a JSON array of folder paths); anything else reads as none. */ +export function parseCollapsed(raw: string | null): Set { + if (!raw) { + return new Set(); + } + try { + const value: unknown = JSON.parse(raw); + return new Set(Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []); + } catch { + return new Set(); + } +} + +export function serializeCollapsed(roots: ReadonlySet): string { + return JSON.stringify([...roots].sort()); +} + +/** #509: Up/Down/Home/End move the focus among `count` rows; null for any other key (or no rows). */ +export function rovingIndex(key: string, index: number, count: number): number | null { + if (count <= 0) { + return null; + } + switch (key) { + case 'ArrowDown': + return Math.min(count - 1, index + 1); + case 'ArrowUp': + return Math.max(0, index - 1); + case 'Home': + return 0; + case 'End': + return count - 1; + default: + return null; + } +} + +/** + * #509: after the list is drawn again, the row that gets the focus back: the + * same one (by its key) if it is still there, else the row now at the place it + * had (the next one, as after a deletion), else none. + */ +export function focusAfterRender(previous: { readonly key: string; readonly index: number } | null, keys: readonly string[]): string | null { + if (!previous || keys.length === 0) { + return null; + } + if (keys.includes(previous.key)) { + return previous.key; + } + return keys[Math.min(Math.max(0, previous.index), keys.length - 1)] ?? null; } /** The agent a new chat uses by default: the last one used if still usable, else the first usable one. */ diff --git a/apps/ide/src/renderer/agentFirst/sessionsView.ts b/apps/ide/src/renderer/agentFirst/sessionsView.ts index 06d36af7..88a3a173 100644 --- a/apps/ide/src/renderer/agentFirst/sessionsView.ts +++ b/apps/ide/src/renderer/agentFirst/sessionsView.ts @@ -2,7 +2,10 @@ import { t } from '../../shared/i18n/i18n.ts'; import type { AgentSessionMessage, AgentSessionsApi, AgentView, ProjectSessions, SessionSummary } from '../../shared/agentSession.ts'; import type { TerminalCreated } from '../../shared/api.ts'; import { el, icon } from '../dom.ts'; -import { attentionCounts, availabilityLabel, defaultAgent, filterProjects, shortTime, statusLabel } from './sessionsModel.ts'; +import { + attentionCounts, availabilityLabel, defaultAgent, filterProjects, focusAfterRender, needsYou, nextAttention, parseCollapsed, rovingIndex, serializeCollapsed, shortTime, statusLabel, + type AttentionCounts, +} from './sessionsModel.ts'; import { agentActions, type AgentSetupDeps } from './agentSetup.ts'; import { branchLabel, branchTitle, parseWorktreeChoice } from './worktreeModel.ts'; import { localModelForm } from './localModelForm.ts'; @@ -31,7 +34,7 @@ export interface SessionsViewDeps { mode(): 'agent' | 'classic'; setMode(mode: 'agent' | 'classic'): void; /** Called when the attention counts change (for the status bar). */ - onAttention?(counts: { running: number; waiting: number; unread: number }): void; + onAttention?(counts: AttentionCounts): void; /** #297: runs an agent's terminal sign-in in a terminal of its own. */ runInTerminal?(label: string, start: (cols: number, rows: number) => Promise): Promise; /** Shows the Agents view, where the IDE's own agents chat (epic #189). */ @@ -55,11 +58,19 @@ export interface SessionsView { /** Called whenever the agents list changes (the first-run guide follows it). */ onAgentsChange(listener: (agents: readonly AgentView[]) => void): void; focusSearch(): void; + /** + * #508: opens a chat that needs the person: the next one after the active + * chat (`next`, the command) or the most urgent one (`urgent`, the status + * bar). False when there is none. + */ + openNeedingAttention(which: 'next' | 'urgent'): boolean; } const LAST_AGENT_KEY = 'codexr.agentFirst.lastAgent'; /** AF12: the last state of "Separate worktree". */ const WORKTREE_CHOICE_KEY = 'codexr.agentFirst.separateWorktree'; +/** #508: the projects folded in the list, kept across restarts. */ +const COLLAPSED_KEY = 'codexr.agentFirst.collapsedProjects'; const ICONS = { plus: 'M12 5v14M5 12h14', trash: 'M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13', @@ -74,8 +85,12 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep let agents: readonly AgentView[] = []; let query = ''; let active: string | null = null; - const collapsed = new Set(); + const collapsed = readCollapsed(); let refreshTimer = 0; + /** #509: a rename field or a delete confirmation is open: drawing the list again would destroy it. */ + let editing = false; + /** #509: the row that holds the list's single Tab stop (roving tabindex), by its `data-key`. */ + let focusKey: string | null = null; const lastAgent = (): string | null => { try { @@ -162,6 +177,16 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep }); const search = el('input', { className: 'agents-input af-search', attrs: { type: 'search', placeholder: 'Search chats', 'aria-label': 'Search chats', 'data-testid': 'af-search' } }); + search.addEventListener('keydown', (event) => { + // #509: Down from the search moves into the list. + if (event.key === 'ArrowDown') { + const first = rows()[0]; + if (first) { + event.preventDefault(); + first.focus(); + } + } + }); search.addEventListener('input', () => { query = search.value; renderProjects(); @@ -169,6 +194,13 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep // ---- Lists ------------------------------------------------------------- const projectList = el('div', { className: 'af-projects', attrs: { 'data-testid': 'af-projects' } }); + // #508: the pinned "Needs you" group, above the projects. + const needsList = el('ul', { className: 'af-session-list' }); + const needsSection = el('section', { className: 'af-project af-needs-you', attrs: { 'aria-label': t('chats.needsYou'), 'data-testid': 'af-needs-you', hidden: '' } }, [ + el('h3', { className: 'af-section-title', text: t('chats.needsYou') }), + needsList, + ]); + const lists = el('div', { className: 'af-lists' }, [needsSection, el('h3', { className: 'af-section-title', text: t('chats.projects') }), projectList]); const agentList = el('ul', { className: 'af-agent-list', attrs: { 'data-testid': 'af-agents' } }); const agentsRefresh = iconButton('Check the agents again', ICONS.refresh, () => void refreshAgents(true)); // #313: local models are added below the list, in a form that opens in place. @@ -206,8 +238,7 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep el('div', { className: 'af-new-row' }, [newChatButton, agentSelect]), worktreeOption, search, - el('h3', { className: 'af-section-title', text: t('chats.projects') }), - projectList, + lists, agentsSection, ...(deps.extraSections ?? []), ])); @@ -275,89 +306,183 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep } } + function readCollapsed(): Set { + try { + return parseCollapsed(localStorage.getItem(COLLAPSED_KEY)); + } catch { + return new Set(); + } + } + function rememberCollapsed(): void { + try { + localStorage.setItem(COLLAPSED_KEY, serializeCollapsed(collapsed)); + } catch { + // Storage is a convenience only. + } + } + + /** Every chat row, the pinned group's first, in the order the arrows walk. */ + function rows(): HTMLElement[] { + return [...lists.querySelectorAll('.af-session[data-key]')]; + } + function rowByKey(key: string): HTMLElement | null { + return rows().find((row) => row.dataset['key'] === key) ?? null; + } + /** #509: one Tab stop in the list: the row last focused, else the active chat, else the first. */ + function applyRoving(): void { + const all = rows(); + const chosen = all.find((row) => row.dataset['key'] === focusKey) + ?? all.find((row) => row.dataset['session'] === active) + ?? all[0]; + for (const row of all) { + row.tabIndex = row === chosen ? 0 : -1; + } + focusKey = chosen?.dataset['key'] ?? null; + } + function renderProjects(): void { + // #509: a background refresh waits while a rename or a delete confirmation is open; closing either draws the list. + if (editing) { + return; + } + // #509: what had the focus, so that it gets it back once the list is drawn again. + const focused = document.activeElement instanceof HTMLElement && lists.contains(document.activeElement) ? document.activeElement : null; + const focusedRow = focused?.closest('[data-key]') ?? null; + const before = [...lists.querySelectorAll('[data-key]')]; + const previous = focusedRow ? { key: focusedRow.dataset['key'] ?? '', index: before.indexOf(focusedRow) } : null; + const focusedHead = focused?.classList.contains('af-project-head') === true ? focused.closest('.af-project')?.dataset['root'] ?? null : null; + const now = Date.now(); + const pinned = query ? [] : needsYou(projects); + needsList.replaceChildren(...pinned.map((entry) => sessionRow(entry.project, entry.session, now, 'needs'))); + needsSection.hidden = pinned.length === 0; const shown = filterProjects(projects, query); if (shown.length === 0) { - projectList.replaceChildren(el('p', { className: 'muted side-note', text: query ? 'No chat matches.' : 'No chats yet. Open a folder and start a new chat.' })); - return; + projectList.replaceChildren(el('p', { className: 'muted side-note', text: query ? t('chats.noMatch') : t('chats.empty') })); + } else { + projectList.replaceChildren(...shown.map((project) => projectSection(project, now))); } - projectList.replaceChildren(...shown.map((project) => { - const isCollapsed = collapsed.has(project.root) && !query; - const head = el('button', { className: `af-project-head${project.current ? ' is-current' : ''}`, attrs: { type: 'button', 'aria-expanded': String(!isCollapsed), title: project.root } }, [ - icon(ICONS.chevron, 'af-project-chevron'), - icon(ICONS.folder, 'af-project-icon'), - el('span', { className: 'af-project-name', text: project.name }), - el('span', { className: 'af-project-count muted', text: String(project.sessions.length) }), - ]); - head.addEventListener('click', () => { - if (collapsed.has(project.root)) { - collapsed.delete(project.root); - } else { - collapsed.add(project.root); - } - renderProjects(); - }); - const children: HTMLElement[] = [head]; - if (!project.current) { - const open = el('button', { className: 'af-link-button af-project-open', text: 'Open project', attrs: { type: 'button' } }); - open.addEventListener('click', () => deps.openProject(project.root)); - children.push(open); - } - if (!isCollapsed) { - children.push(el('ul', { className: 'af-session-list' }, project.sessions.map((session) => sessionRow(project, session, now)))); + + const target = focusAfterRender(previous, rows().map((row) => row.dataset['key'] ?? '')); + if (target) { + focusKey = target; + } + applyRoving(); + if (target) { + rowByKey(target)?.focus(); + } else if (focusedHead !== null) { + [...projectList.querySelectorAll('.af-project')].find((section) => section.dataset['root'] === focusedHead)?.querySelector('.af-project-head')?.focus(); + } + } + + function projectSection(project: ProjectSessions, now: number): HTMLElement { + const isCollapsed = collapsed.has(project.root) && !query; + const head = el('button', { className: `af-project-head${project.current ? ' is-current' : ''}`, attrs: { type: 'button', 'aria-expanded': String(!isCollapsed), title: project.root } }, [ + icon(ICONS.chevron, 'af-project-chevron'), + icon(ICONS.folder, 'af-project-icon'), + el('span', { className: 'af-project-name', text: project.name }), + el('span', { className: 'af-project-count muted', text: String(project.sessions.length) }), + ]); + head.addEventListener('click', () => { + if (collapsed.has(project.root)) { + collapsed.delete(project.root); + } else { + collapsed.add(project.root); } - return el('section', { className: 'af-project', attrs: { 'data-root': project.root, 'data-current': String(project.current) } }, children); - })); + rememberCollapsed(); + renderProjects(); + }); + const children: HTMLElement[] = [head]; + if (!project.current) { + const open = el('button', { className: 'af-link-button af-project-open', text: 'Open project', attrs: { type: 'button' } }); + open.addEventListener('click', () => deps.openProject(project.root)); + children.push(open); + } + if (!isCollapsed) { + children.push(el('ul', { className: 'af-session-list' }, project.sessions.map((session) => sessionRow(project, session, now, project.root)))); + } + return el('section', { className: 'af-project', attrs: { 'data-root': project.root, 'data-current': String(project.current) } }, children); } - function sessionRow(project: ProjectSessions, session: SessionSummary, now: number): HTMLElement { + function openSession(project: ProjectSessions, sessionId: string): void { + if (project.current) { + deps.openChat(sessionId); + } else { + deps.openChatInProject(project.root, sessionId); + } + } + + /** `group` tells the pinned copy of a chat (`needs`) from its row under its project (the project's folder). */ + function sessionRow(project: ProjectSessions, session: SessionSummary, now: number, group: string): HTMLElement { + const sub = [...(group === 'needs' ? [project.name] : []), session.agentName, statusLabel(session), shortTime(session.updatedAt, now)]; const row = el('li', { className: `af-session${session.id === active ? ' is-active' : ''}${session.unread ? ' is-unread' : ''}`, - attrs: { tabindex: '0', role: 'button', 'data-session': session.id, 'data-status': session.status, 'data-testid': 'af-session', title: `${session.title} (${statusLabel(session)})` }, + attrs: { + tabindex: '-1', + role: 'button', + 'aria-keyshortcuts': 'F2 Delete', + 'data-session': session.id, + 'data-key': `${group}\n${session.id}`, + 'data-status': session.status, + 'data-testid': 'af-session', + title: `${session.title} (${statusLabel(session)})`, + }, }, [ el('span', { className: 'af-dot', attrs: { 'data-status': session.status, 'data-unread': String(session.unread), 'aria-label': statusLabel(session) } }), el('span', { className: 'af-session-main' }, [ el('span', { className: 'af-session-title', text: session.title }), - el('span', { className: 'af-session-sub muted', text: [session.agentName, statusLabel(session), shortTime(session.updatedAt, now)].filter(Boolean).join(' · ') }), + el('span', { className: 'af-session-sub muted', text: sub.filter(Boolean).join(' · ') }), ]), ...(session.worktree ? [el('span', { className: `af-badge af-branch${session.worktree.removed ? ' is-removed' : ''}`, text: branchLabel(session.worktree), attrs: { title: branchTitle(session.worktree), 'data-testid': 'af-session-branch' } })] : []), ...(session.pendingChanges > 0 ? [el('span', { className: 'af-badge af-pending', text: String(session.pendingChanges), attrs: { title: `${session.pendingChanges} changed file(s) to review` } })] : []), el('span', { className: 'af-session-actions' }, [ - iconButton('Rename', ICONS.edit, () => rename(session)), - iconButton('Delete', ICONS.trash, () => remove(session)), + // #509: one Tab stop per list; the row's F2 and Delete reach these from the keyboard. + outOfTabOrder(iconButton('Rename (F2)', ICONS.edit, () => rename(row, session))), + outOfTabOrder(iconButton('Delete (Delete)', ICONS.trash, () => remove(row, session))), ]), ]); - const open = (): void => { - if (project.current) { - deps.openChat(session.id); - } else { - deps.openChatInProject(project.root, session.id); - } - }; + const open = (): void => openSession(project, session.id); row.addEventListener('click', open); + row.addEventListener('focus', () => { + focusKey = row.dataset['key'] ?? null; + applyRoving(); + }); row.addEventListener('keydown', (event) => { - if (event.key === 'Enter' || event.key === ' ') { + if (event.target !== row) { + return; + } + const all = rows(); + const next = rovingIndex(event.key, all.indexOf(row), all.length); + if (next !== null) { + event.preventDefault(); + all[next]?.focus(); + } else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); open(); } else if (event.key === 'F2') { event.preventDefault(); - rename(session); + rename(row, session); } else if (event.key === 'Delete') { event.preventDefault(); - remove(session); + remove(row, session); } }); return row; } - function rename(session: SessionSummary): void { - const row = projectList.querySelector(`[data-session="${CSS.escape(session.id)}"] .af-session-title`); - if (!row) { + function outOfTabOrder(button: HTMLButtonElement): HTMLButtonElement { + button.tabIndex = -1; + return button; + } + + function rename(row: HTMLElement, session: SessionSummary): void { + const titleElement = row.querySelector('.af-session-title'); + if (!titleElement || editing) { return; } const field = el('input', { className: 'agents-input af-rename', attrs: { value: session.title, 'aria-label': 'Chat title' } }); - row.replaceWith(field); + editing = true; + titleElement.replaceWith(field); field.focus(); field.select(); let done = false; @@ -366,9 +491,13 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep return; } done = true; + editing = false; const title = field.value.trim(); if (save && title && title !== session.title) { - deps.api.rename(session.id, title).then(() => refresh()).catch((error: unknown) => deps.onStatus(errorText(error))); + deps.api.rename(session.id, title).then(() => refresh()).catch((error: unknown) => { + deps.onStatus(errorText(error)); + renderProjects(); + }); } else { renderProjects(); } @@ -385,10 +514,9 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep field.addEventListener('blur', () => finish(true)); } - function remove(session: SessionSummary): void { + function remove(row: HTMLElement, session: SessionSummary): void { // A native confirm would block the window; ask inline instead. - const row = projectList.querySelector(`[data-session="${CSS.escape(session.id)}"]`); - if (!row) { + if (!row.isConnected || editing) { return; } const yes = el('button', { className: 'secondary-button is-danger af-small-button', text: 'Delete', attrs: { type: 'button' } }); @@ -397,21 +525,37 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep const hasWorktree = !!session.worktree && !session.worktree.removed; const alsoWorktree = el('input', { attrs: { type: 'checkbox', 'data-testid': 'af-delete-worktree' } }); alsoWorktree.checked = true; - const confirm = el('li', { className: `af-confirm${hasWorktree ? ' has-worktree' : ''}` }, [ + const confirm = el('li', { className: `af-confirm${hasWorktree ? ' has-worktree' : ''}`, attrs: { 'data-key': row.dataset['key'] ?? '' } }, [ el('span', { text: `Delete "${session.title}"?` }), ...(hasWorktree && session.worktree ? [el('label', { className: 'af-confirm-worktree', attrs: { title: `Remove the worktree folder and delete the branch ${session.worktree.branch}. Unchecked, both are kept.` } }, [alsoWorktree, el('span', { text: `Also remove its worktree and branch ${branchLabel(session.worktree)}` })])] : []), yes, no, ]); + editing = true; row.replaceWith(confirm); yes.focus(); + const cancel = (): void => { + editing = false; + renderProjects(); + }; yes.addEventListener('click', () => { + editing = false; deps.api.remove(session.id, { removeWorktree: hasWorktree && alsoWorktree.checked }).then(() => { deps.onRemoved?.(session.id); return refresh(); - }).catch((error: unknown) => deps.onStatus(errorText(error))); + }).catch((error: unknown) => { + deps.onStatus(errorText(error)); + renderProjects(); + }); + }); + no.addEventListener('click', cancel); + confirm.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + cancel(); + } }); - no.addEventListener('click', () => renderProjects()); } async function refreshAgents(probe = false): Promise { @@ -498,6 +642,14 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep focusSearch(): void { search.focus(); }, + openNeedingAttention(which): boolean { + const entry = which === 'next' ? nextAttention(projects, active ?? deps.activeChat()) : needsYou(projects)[0] ?? null; + if (!entry) { + return false; + } + openSession(entry.project, entry.session.id); + return true; + }, }; } diff --git a/apps/ide/src/renderer/workbench.ts b/apps/ide/src/renderer/workbench.ts index 5fec42af..22e43407 100644 --- a/apps/ide/src/renderer/workbench.ts +++ b/apps/ide/src/renderer/workbench.ts @@ -132,6 +132,8 @@ export interface Workbench { readonly extensionStatusRight: HTMLElement; /** Sizes and visibility of the side bar, panel and scene column (#169, layout/layout.ts). */ readonly layout: WorkbenchLayout; + /** #508: a built-in activity item's badge (the Chats item counts the chats that need the person); 0 hides it. */ + setActivityBadge(id: ViewId, value: number, tooltip: string): void; /** #261: adds an extension's view container (an activity item and its pane), before Settings. */ addViewContainer(id: string, title: string, icon: Element | null): ExtensionViewContainer; /** #261: where extensions' views go in the built-in Explorer, Source Control and Run and Debug views. */ @@ -264,6 +266,27 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null }; } + /** #508: the badges of built-in items, made on first use (the same look as an extension container's). */ + const builtinBadges = new Map(); + function setActivityBadge(id: ViewId, value: number, tooltip: string): void { + const button = buttons.get(id); + if (!button) { + return; + } + let badge = builtinBadges.get(id); + if (!badge) { + badge = el('span', { className: 'activity-badge', attrs: { hidden: '', 'aria-hidden': 'true' } }); + button.append(badge); + builtinBadges.set(id, badge); + } + badge.hidden = value <= 0; + badge.textContent = value > 99 ? '99+' : String(value); + const title = labels.get(id) ?? id; + const label = value > 0 && tooltip ? `${title} - ${tooltip}` : title; + button.title = label; + button.setAttribute('aria-label', label); + } + const infoList = el('dl', { className: 'info-list' }); const status = el('p', { className: 'muted', text: t('welcome.connecting') }); @@ -373,6 +396,7 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null extensionStatusRight, layout, addViewContainer, + setActivityBadge, extensionSections, onDidChangeView(listener) { viewListeners.add(listener); diff --git a/apps/ide/src/shared/defaultKeybindings.ts b/apps/ide/src/shared/defaultKeybindings.ts index 3f54caad..4198a417 100644 --- a/apps/ide/src/shared/defaultKeybindings.ts +++ b/apps/ide/src/shared/defaultKeybindings.ts @@ -180,6 +180,8 @@ const DEFAULTS: Readonly> = { // The editor keeps Ctrl/Cmd+Shift+L (Select All Occurrences) while it has the focus. 'chat.new': { keys: ['CmdOrCtrl+Shift+L'], when: '!editorTextFocus' }, 'layout.toggleAgentMode': { keys: ['CmdOrCtrl+Alt+M'] }, + // #508: a chord, free on every OS and in Monaco (VS Code leaves Ctrl/Cmd+K Ctrl/Cmd+N unbound too). + 'chat.nextNeedingAttention': { keys: ['CmdOrCtrl+K CmdOrCtrl+N'] }, ...Object.fromEntries(EDITOR_ACTIONS.map((action) => [action.id, { keys: action.keys, ...(action.mac ? { mac: action.mac } : {}), diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index deb6a8cf..b65845c8 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -160,6 +160,34 @@ export const en = { 'extensions.noneInstalled': 'No extensions installed yet. Search Open VSX above, or install a .vsix file.', 'chats.projects': 'Projects', 'chats.projectInstructions': 'Project instructions', + 'chats.needsYou': 'Needs you', + 'chats.noMatch': 'No chat matches.', + 'chats.empty': 'No chats yet. Open a folder and start a new chat.', + 'chats.status.idle': 'Done', + 'chats.status.running': 'Working', + 'chats.status.awaiting': 'Needs your approval', + 'chats.status.error': 'Failed', + 'chats.status.unread': 'Done, not read yet', + 'chats.time.now': 'now', + 'chats.time.minutes': '{count} min', + 'chats.time.hours': '{count} h', + 'chats.time.days': '{count} d', + 'chats.attention.text': 'Agents: {parts}', + 'chats.attention.workingOne': '1 working', + 'chats.attention.workingMany': '{count} working', + 'chats.attention.waitingOne': '1 waiting for you', + 'chats.attention.waitingMany': '{count} waiting for you', + 'chats.attention.failedOne': '1 failed', + 'chats.attention.failedMany': '{count} failed', + 'chats.attention.doneOne': '1 done', + 'chats.attention.doneMany': '{count} done', + 'chats.attention.openUrgent': 'Open the chat that needs you most', + 'chats.attention.showChats': 'Show the chats', + 'chats.nextNeedingAttention': 'Next Chat Needing Attention', + 'chats.nothingNeedsYou': 'No other chat needs you.', + 'dock.live.waiting': 'Waiting', + 'dock.live.analysing': 'Analysing', + 'dock.live.noFolder': 'No folder', 'action.refresh': 'Refresh', 'action.retry': 'Retry', 'action.showOutput': 'Show Output', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index d02ce7dc..33df0458 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -163,6 +163,34 @@ export const es: Readonly> = { 'extensions.noneInstalled': 'Aún no hay extensiones instaladas. Busca en Open VSX arriba o instala un archivo .vsix.', 'chats.projects': 'Proyectos', 'chats.projectInstructions': 'Instrucciones del proyecto', + 'chats.needsYou': 'Te necesitan', + 'chats.noMatch': 'Ningún chat coincide.', + 'chats.empty': 'Aún no hay chats. Abre una carpeta e inicia un chat nuevo.', + 'chats.status.idle': 'Terminado', + 'chats.status.running': 'Trabajando', + 'chats.status.awaiting': 'Necesita tu aprobación', + 'chats.status.error': 'Ha fallado', + 'chats.status.unread': 'Terminado, sin leer', + 'chats.time.now': 'ahora', + 'chats.time.minutes': '{count} min', + 'chats.time.hours': '{count} h', + 'chats.time.days': '{count} d', + 'chats.attention.text': 'Agentes: {parts}', + 'chats.attention.workingOne': '1 trabajando', + 'chats.attention.workingMany': '{count} trabajando', + 'chats.attention.waitingOne': '1 espera tu respuesta', + 'chats.attention.waitingMany': '{count} esperan tu respuesta', + 'chats.attention.failedOne': '1 ha fallado', + 'chats.attention.failedMany': '{count} han fallado', + 'chats.attention.doneOne': '1 terminado', + 'chats.attention.doneMany': '{count} terminados', + 'chats.attention.openUrgent': 'Abrir el chat que más te necesita', + 'chats.attention.showChats': 'Mostrar los chats', + 'chats.nextNeedingAttention': 'Siguiente chat que necesita atención', + 'chats.nothingNeedsYou': 'Ningún otro chat te necesita.', + 'dock.live.waiting': 'En espera', + 'dock.live.analysing': 'Analizando', + 'dock.live.noFolder': 'Sin carpeta', 'action.refresh': 'Actualizar', 'action.retry': 'Reintentar', 'action.showOutput': 'Mostrar salida', diff --git a/apps/ide/test/agentFirst.test.ts b/apps/ide/test/agentFirst.test.ts index 58fd615b..dc3be108 100644 --- a/apps/ide/test/agentFirst.test.ts +++ b/apps/ide/test/agentFirst.test.ts @@ -113,7 +113,7 @@ describe('sessions model', () => { }); it('counts what needs attention', () => { - assert.deepEqual(attentionCounts(projects), { running: 1, waiting: 1, unread: 1 }); + assert.deepEqual(attentionCounts(projects), { running: 1, waiting: 1, unread: 1, failed: 0, done: 0, needsYou: 1 }); }); it('labels statuses', () => { diff --git a/apps/ide/test/chatsAttention.test.ts b/apps/ide/test/chatsAttention.test.ts new file mode 100644 index 00000000..ce02c7d8 --- /dev/null +++ b/apps/ide/test/chatsAttention.test.ts @@ -0,0 +1,248 @@ +import { afterEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { ProjectSessions, SessionSummary } from '../src/shared/agentSession.ts'; +import { setLocale } from '../src/shared/i18n/i18n.ts'; +import { + attentionCounts, attentionText, focusAfterRender, needsYou, needsYouReason, nextAttention, parseCollapsed, rovingIndex, serializeCollapsed, shortTime, statusLabel, +} from '../src/renderer/agentFirst/sessionsModel.ts'; +import { createSessionNoticeTracker, type NoticeHandle } from '../src/renderer/agentFirst/sessionNotices.ts'; +import { createToastTimer, type TimerScheduler } from '../src/renderer/toastTimer.ts'; + +/** #508 / #509: the chats that need the person, and a calm, keyboard-friendly list. */ + +afterEach(() => setLocale('en')); + +function summary(overrides: Partial): SessionSummary { + return { + id: 's', title: 'Chat', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/p', + createdAt: '2026-12-01T10:00:00.000Z', updatedAt: '2026-12-01T10:00:00.000Z', status: 'idle', unread: false, pendingChanges: 0, + ...overrides, + }; +} + +const projects: ProjectSessions[] = [ + { + root: '/shop', name: 'shop', current: true, sessions: [ + summary({ id: 'done-old', unread: true, updatedAt: '2026-12-01T09:00:00.000Z' }), + summary({ id: 'working', status: 'running' }), + summary({ id: 'failed', status: 'error', unread: true }), + summary({ id: 'failed-read', status: 'error' }), + summary({ id: 'quiet' }), + ], + }, + { + root: '/blog', name: 'blog', current: false, sessions: [ + summary({ id: 'done-new', unread: true, updatedAt: '2026-12-01T11:00:00.000Z' }), + summary({ id: 'approve', status: 'awaiting' }), + ], + }, +]; + +describe('"Needs you" (#508)', () => { + it('pins approvals, then failures, then unread chats, across projects and newest first', () => { + assert.deepEqual(needsYou(projects).map((entry) => [entry.session.id, entry.reason, entry.project.name]), [ + ['approve', 'awaiting', 'blog'], + ['failed', 'failed', 'shop'], + ['done-new', 'unread', 'blog'], + ['done-old', 'unread', 'shop'], + ]); + assert.deepEqual(needsYou([]), []); + }); + + it('lets a failed chat go once it is read, but never an approval', () => { + assert.equal(needsYouReason({ status: 'error', unread: false }), null); + assert.equal(needsYouReason({ status: 'awaiting', unread: false }), 'awaiting'); + assert.equal(needsYouReason({ status: 'running', unread: false }), null); + assert.equal(needsYouReason({ status: 'idle', unread: true }), 'unread'); + }); + + it('walks the group from the active chat, wrapping, and starts at the most urgent', () => { + assert.equal(nextAttention(projects, null)?.session.id, 'approve'); + assert.equal(nextAttention(projects, 'quiet')?.session.id, 'approve'); + assert.equal(nextAttention(projects, 'approve')?.session.id, 'failed'); + assert.equal(nextAttention(projects, 'done-old')?.session.id, 'approve'); + const single: ProjectSessions[] = [{ root: '/a', name: 'a', current: true, sessions: [summary({ id: 'only', status: 'awaiting' })] }]; + assert.equal(nextAttention(single, 'only'), null, 'nothing else needs the person'); + assert.equal(nextAttention(single, null)?.session.id, 'only'); + assert.equal(nextAttention([], null), null); + }); + + it('counts what the status bar and the badge show', () => { + assert.deepEqual(attentionCounts(projects), { running: 1, waiting: 1, unread: 3, failed: 1, done: 2, needsYou: 4 }); + assert.equal(attentionText(attentionCounts(projects)), 'Agents: 1 working, 1 waiting for you, 1 failed, 2 done'); + assert.equal(attentionText({ running: 0, waiting: 0, failed: 0, done: 3 }), 'Agents: 3 done'); + assert.equal(attentionText({ running: 0, waiting: 0, failed: 0, done: 0 }), ''); + }); + + it('remembers collapsed projects and survives bad storage', () => { + const roots = new Set(['/b', '/a']); + assert.deepEqual([...parseCollapsed(serializeCollapsed(roots))].sort(), ['/a', '/b']); + assert.equal(parseCollapsed(null).size, 0); + assert.equal(parseCollapsed('{not json').size, 0); + assert.equal(parseCollapsed('{"a":1}').size, 0); + assert.deepEqual([...parseCollapsed('["C:\\\\work\\\\shop", 3]')], ['C:\\work\\shop']); + }); +}); + +describe('the chats list in Spanish (#508)', () => { + it('labels statuses, times and the attention summary', () => { + setLocale('es'); + assert.equal(statusLabel({ status: 'idle', unread: true }), 'Terminado, sin leer'); + assert.equal(statusLabel({ status: 'awaiting', unread: false }), 'Necesita tu aprobación'); + assert.equal(statusLabel({ status: 'error', unread: false }), 'Ha fallado'); + const now = Date.parse('2026-12-01T12:00:00.000Z'); + assert.equal(shortTime('2026-12-01T11:59:50.000Z', now), 'ahora'); + assert.equal(shortTime('2026-12-01T11:55:00.000Z', now), '5 min'); + assert.equal(attentionText({ running: 2, waiting: 1, failed: 0, done: 1 }), 'Agentes: 2 trabajando, 1 espera tu respuesta, 1 terminado'); + }); + + it('keeps the English labels in English', () => { + assert.equal(statusLabel({ status: 'running', unread: false }), 'Working'); + assert.equal(shortTime('2026-12-01T09:00:00.000Z', Date.parse('2026-12-01T12:00:00.000Z')), '3 h'); + }); +}); + +describe('roving focus in the chats list (#509)', () => { + it('moves with Up, Down, Home and End, and stops at the ends', () => { + assert.equal(rovingIndex('ArrowDown', 0, 3), 1); + assert.equal(rovingIndex('ArrowDown', 2, 3), 2); + assert.equal(rovingIndex('ArrowUp', 0, 3), 0); + assert.equal(rovingIndex('ArrowUp', 2, 3), 1); + assert.equal(rovingIndex('Home', 2, 3), 0); + assert.equal(rovingIndex('End', 0, 3), 2); + assert.equal(rovingIndex('Enter', 0, 3), null); + assert.equal(rovingIndex('ArrowDown', 0, 0), null); + }); + + it('gives the focus back to the same chat after a redraw, or to the one now in its place', () => { + assert.equal(focusAfterRender({ key: 'b', index: 1 }, ['x', 'a', 'b']), 'b', 'same chat, even if it moved'); + assert.equal(focusAfterRender({ key: 'gone', index: 1 }, ['a', 'c']), 'c', 'the next one after a deletion'); + assert.equal(focusAfterRender({ key: 'gone', index: 5 }, ['a', 'c']), 'c', 'the last one when it was last'); + assert.equal(focusAfterRender({ key: 'gone', index: -1 }, ['a']), 'a'); + assert.equal(focusAfterRender(null, ['a']), null, 'the list did not have the focus'); + assert.equal(focusAfterRender({ key: 'a', index: 0 }, []), null); + }); +}); + +describe('one toast per chat (#509)', () => { + function fakeToast(log: string[], name: string): NoticeHandle { + return { close: () => log.push(`close ${name}`) }; + } + + it('replaces a chat\'s toast with the newer one and leaves other chats alone', () => { + const log: string[] = []; + const tracker = createSessionNoticeTracker(); + assert.ok(tracker.show('a', tracker.claim('a'), () => fakeToast(log, 'a1'))); + assert.ok(tracker.show('b', tracker.claim('b'), () => fakeToast(log, 'b1'))); + assert.ok(tracker.show('a', tracker.claim('a'), () => fakeToast(log, 'a2'))); + assert.deepEqual(log, ['close a1']); + assert.equal(tracker.size, 2); + }); + + it('closes it when the chat is opened or read, and drops a toast prepared before that', () => { + const log: string[] = []; + const tracker = createSessionNoticeTracker(); + tracker.show('a', tracker.claim('a'), () => fakeToast(log, 'a1')); + const late = tracker.claim('a'); + tracker.close('a'); + assert.deepEqual(log, ['close a1']); + let made = false; + assert.equal(tracker.show('a', late, () => { + made = true; + return fakeToast(log, 'late'); + }), false); + assert.equal(made, false); + assert.equal(tracker.size, 0); + tracker.close('nothing'); + assert.deepEqual(log, ['close a1']); + }); + + it('forgets a toast that closed by itself, but not a newer one', () => { + const log: string[] = []; + const tracker = createSessionNoticeTracker(); + const first = fakeToast(log, 'a1'); + tracker.show('a', tracker.claim('a'), () => first); + tracker.forget('a', first); + assert.equal(tracker.size, 0); + const second = fakeToast(log, 'a2'); + tracker.show('a', tracker.claim('a'), () => second); + tracker.forget('a', first); + assert.equal(tracker.size, 1); + }); +}); + +describe('the info toast timer (#509)', () => { + function fakeClock(): TimerScheduler & { advance(ms: number): void } { + let now = 0; + let next = 1; + const timers = new Map void }>(); + return { + now: () => now, + set(run, ms) { + const id = next++; + timers.set(id, { at: now + ms, run }); + return id; + }, + clear(id) { + timers.delete(id as number); + }, + advance(ms) { + now += ms; + for (const [id, timer] of [...timers]) { + if (timer.at <= now) { + timers.delete(id); + timer.run(); + } + } + }, + }; + } + + it('expires on its own', () => { + const clock = fakeClock(); + let expired = 0; + createToastTimer(6000, () => expired++, clock); + clock.advance(5999); + assert.equal(expired, 0); + clock.advance(1); + assert.equal(expired, 1); + }); + + it('pauses while hovered or focused, and resumes with the time left once neither holds', () => { + const clock = fakeClock(); + let expired = 0; + const timer = createToastTimer(6000, () => expired++, clock); + clock.advance(2000); + timer.hold('hover'); + timer.hold('focus'); + clock.advance(60_000); + assert.equal(expired, 0); + timer.release('hover'); + assert.ok(timer.paused, 'the focus still holds it'); + clock.advance(60_000); + assert.equal(expired, 0); + timer.release('focus'); + clock.advance(3999); + assert.equal(expired, 0); + clock.advance(1); + assert.equal(expired, 1); + }); + + it('leaves a moment after being read to its last second, and stops for good when cancelled', () => { + const clock = fakeClock(); + let expired = 0; + const timer = createToastTimer(1000, () => expired++, clock); + clock.advance(999); + timer.hold('hover'); + timer.release('hover'); + clock.advance(1000); + assert.equal(expired, 0); + clock.advance(500); + assert.equal(expired, 1); + const other = createToastTimer(1000, () => expired++, clock); + other.cancel(); + other.release('hover'); + clock.advance(5000); + assert.equal(expired, 1); + }); +}); diff --git a/apps/ide/test/keybindingDefaults.test.ts b/apps/ide/test/keybindingDefaults.test.ts index 3fecf2aa..15618233 100644 --- a/apps/ide/test/keybindingDefaults.test.ts +++ b/apps/ide/test/keybindingDefaults.test.ts @@ -24,7 +24,7 @@ const REGISTERED_ELSEWHERE = new Set([ 'workbench.view.debug', 'workbench.action.debug.start', 'workbench.action.debug.pause', 'workbench.action.debug.stepOver', 'workbench.action.debug.stepInto', 'workbench.action.debug.stepOut', 'workbench.action.debug.stop', 'workbench.action.debug.restart', 'editor.debug.action.toggleBreakpoint', 'workbench.debug.action.toggleRepl', 'extensions.showView', 'agents.newChat', 'chat.new', - 'layout.toggleAgentMode', + 'layout.toggleAgentMode', 'chat.nextNeedingAttention', ]); function registry(platform = 'linux'): ReturnType { From 2fe21b6e2804c90698e1de34ae97906429239219 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:23:00 +0000 Subject: [PATCH 12/74] feat(ide): scene freshness chip, load placeholder and pending metric deltas (#512, #513) O10 (#512): wire codexr:analysis:scene-updated from AnalysisService to the renderer with the refresh state (revision, settled/pending/paused, mode, following). The scene header shows a chip (Updating, Updated 12 s ago, Paused: shown, Not following changes with a Follow changes button), redrawn every 15 s and briefly highlighted on a refresh unless reduced motion is on. The scene slot shows a placeholder until the page loads; showScene now gives up after 45 s (a Tauri webview reports no failed load) and codexr:analysis:scene-load lets the placeholder offer Reload and Run again. Removes the dead .af-live[data-state='live'] CSS. O11 (#513): MetricDeltaReport and TurnMetricDeltaView carry a freshness (fresh, paused, timeout, not-following) from the settle result; a delta not measured on refreshed data is kept as 'delta pending: ' instead of comparing stale data or staying silent. --- apps/ide/README.md | 2 + apps/ide/src/bridge/codexrApi.ts | 7 +- apps/ide/src/main/analysis/analysisService.ts | 101 ++++++++++-- apps/ide/src/main/analysis/metricDelta.ts | 54 ++++++- apps/ide/src/main/analysis/sceneRefresh.ts | 57 +++++-- apps/ide/src/main/analysis/sceneView.ts | 15 +- apps/ide/src/main/ipc.ts | 9 ++ .../src/renderer/agentFirst/agentFirst.css | 2 - .../src/renderer/agentFirst/changesModel.ts | 22 ++- apps/ide/src/renderer/sceneHeaderModel.ts | 121 ++++++++++++++- apps/ide/src/renderer/scenePanel.ts | 145 +++++++++++++++++- apps/ide/src/renderer/styles.css | 16 ++ apps/ide/src/shared/agentSession.ts | 16 ++ apps/ide/src/shared/api.ts | 58 +++++++ apps/ide/src/shared/i18n/messages.en.ts | 34 ++++ apps/ide/src/shared/i18n/messages.es.ts | 34 ++++ apps/ide/test/ipcCalls.test.ts | 23 +++ apps/ide/test/metricDelta.test.ts | 52 ++++++- apps/ide/test/sceneHeaderModel.test.ts | 58 ++++++- apps/ide/test/sceneRefresh.test.ts | 28 +++- 20 files changed, 804 insertions(+), 50 deletions(-) diff --git a/apps/ide/README.md b/apps/ide/README.md index c8d4fa76..34b7d428 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -77,6 +77,8 @@ The scene is a second webview of the window, made by the Rust core (`src-tauri/s **Analyse on open (#139).** When a folder opens (at launch with `--folder`, from File > Open Folder… or Open Recent), the IDE analyses it in XR (deep) without a click, the same analysis as the button. The Code-XR view's **Analyse in XR when a folder opens** checkbox turns it off; the choice is kept in the core's global state (`ide.analysis.autoStartOnOpen`, `xr-deep` or `off`, on by default). Without a ready Python environment it waits for one and never sets it up itself. It never asks first, whatever the project's size (#203): the progress notification counts the files as they are analysed (`28/833`), and the scene's header then shows how many the analysis took, read from its own `data.json` (`analysis/analysedFiles.ts`), so the number always matches the analyser's filters. While the scene is open the IDE watches that `data.json` (`watchAnalysedFileCount`, debounced) and the header follows each re-analysis on save (`codexr:analysis:scene-files-changed`). Reopening the folder a window already shows reuses its running scene; opening another folder closes the old scene and stops its server, so a project left behind is not served on. +**Scene freshness (O10 #512, O11 #513).** The header carries a chip that says where the scene stands against the disk: *Updating…*, *Updated 12 s ago* (redrawn every 15 s, briefly highlighted on each refresh unless reduced motion is on), *Paused: dependency graph shown* (the scene shows another analysis, so the classic view's `data.json` waits) or *Not following changes* (the core's auto-analysis setting is off; a **Follow changes** button turns it back on). It is fed by `codexr:analysis:scene-updated` (`SceneUpdatedEvent`: revision, refresh state, mode, following), sent from `AnalysisService` through `followRefreshStatus` (`analysis/sceneRefresh.ts`). Until the scene's page has loaded, the native view stays hidden and the slot shows a placeholder; a Tauri webview reports only finished loads, so `showScene` gives up after `SCENE_LOAD_TIMEOUT_MS` (45 s, a cold WebKitGTK can take 35 s) and `codexr:analysis:scene-load` tells the renderer, which then offers **Reload** (a fresh view with a new sign-in link) and **Run again**. An agent turn's metric delta carries a `freshness` (`fresh`, `paused`, `timeout`, `not-following`): when the scene did not catch up, the chat says *delta pending* with the reason instead of comparing stale data. + **Every analysis of the extension (#398).** `src/shared/analysisKinds.ts` is the one table of the eleven kinds of the extension's "Code-XR: Analysis" submenu: a file (XR, LivePanel), a folder and the project (XR, XR deep, LivePanel, LivePanel deep) and Visualize DOM for an HTML file, each with its label, palette command, mode, target, depth and the files it applies to (file kinds: the core's `SUPPORTED_LANGUAGES` without HTML, the metric analyzer's contract; the DOM: `.html`, `.htm`, `.xhtml`). The explorer (on a file, a folder, or its free space for the project), the tab menu and the editor's own Monaco menu read it to offer **Run Last: ** (the window's last explicit analysis, the extension's default `project-xr-deep` before any) and the **Code-XR: Analysis** submenu with the kinds that apply; the palette has one **Code-XR: Analyse ...** command per kind (a file kind on the active editor's file, a folder kind on its folder) and the Analysis view a button per project kind. The renderer sends one call, `analysis.analyse(kind, path)`; the main process checks the kind, that the workspace path stays inside the folder (also through links), exists and is what the kind analyses (`analysis/analysisTarget.ts`), then maps it to `AnalysisOrchestrator.orchestrateAnalysis(path, mode, 'file' | 'directory', context, deep)`, refusing as before without a folder or a ready Python environment. The Monaco submenu goes through Monaco's menu registry (`editor/analysisEditorMenu.ts`; `addAction` has no submenus) with per-editor context keys. The context menu (`contextMenu.ts`, positions and keys in `contextMenuModel.ts`) opens a submenu on hover, Right, Enter or Space and closes it with Left or Escape, beside its item and left of the scene view. **Help > About lists the dependencies (#161)**: Python, the analysis environment, each pinned package, the language parsers (checked with `download_parsers.py --check`, no network) and cloudflared, each marked `[ok]`, `[installing]`, `[missing]` or `[problem]`, with **Install missing dependencies** when the IDE can install one of them. diff --git a/apps/ide/src/bridge/codexrApi.ts b/apps/ide/src/bridge/codexrApi.ts index 9022d453..4c89b417 100644 --- a/apps/ide/src/bridge/codexrApi.ts +++ b/apps/ide/src/bridge/codexrApi.ts @@ -2,7 +2,7 @@ import type { ColorTheme, SettingScope, SettingValue } from '../shared/settings. import type { UserKeybinding } from '../shared/keybindings.ts'; import type { OutputChannelId } from '../shared/output.ts'; import type { FunctionMetricsSnapshot } from '../shared/problems.ts'; -import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AnalysisKind, type AutoStartMode, type BenchReport, type CodeXRApi, type HostNotification, type IdeCommand, type KeybindingsReport, type OutputAppended, type ProgressEvent, type PythonEnvStatus, type SceneAddress, type SceneBounds, type SceneFilesEvent, type SceneInfo, type SceneOpenInEditorEvent, type SceneShareEvent, type SearchDoneEvent, type SearchFileEvent, type SearchQuery, type SettingsReport, type TerminalDataEvent, type TerminalExitEvent, type Unsubscribe, type WatchedEntry, type WorkspaceInfo, type WorkspaceTrustInfo } from '../shared/api.ts'; +import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AnalysisKind, type AutoStartMode, type BenchReport, type CodeXRApi, type HostNotification, type IdeCommand, type KeybindingsReport, type OutputAppended, type ProgressEvent, type PythonEnvStatus, type SceneAddress, type SceneBounds, type SceneFilesEvent, type SceneInfo, type SceneLoadEvent, type SceneUpdatedEvent, type SceneOpenInEditorEvent, type SceneShareEvent, type SearchDoneEvent, type SearchFileEvent, type SearchQuery, type SettingsReport, type TerminalDataEvent, type TerminalExitEvent, type Unsubscribe, type WatchedEntry, type WorkspaceInfo, type WorkspaceTrustInfo } from '../shared/api.ts'; import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS } from '../shared/git.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentProfileInput, type ApprovalDecision, type EditReviewResult, type ChatAttachment, type McpServerInput, type ModelPrice, type BudgetSettings, type ProviderInput } from '../shared/agents.ts'; import { AGENT_SESSION_CHANNELS, AGENT_SESSION_EVENTS, type AcpAgentDefinition, type AgentSessionMessage, type ImportableSession, type LocalModelInput, type PromptAttachment } from '../shared/agentSession.ts'; @@ -257,6 +257,11 @@ export function createCodexrApi(ipc: IpcAdapter): CodeXRApi { closeScene: () => ipc.invoke(IPC_CHANNELS.analysisCloseScene), onDidOpenScene: (listener: (scene: SceneInfo) => void) => ipc.on(IPC_EVENTS.analysisSceneOpened, listener), onDidChangeSceneFiles: (listener: (event: SceneFilesEvent) => void) => ipc.on(IPC_EVENTS.analysisSceneFilesChanged, listener), + onDidUpdateScene: (listener: (event: SceneUpdatedEvent) => void) => ipc.on(IPC_EVENTS.analysisSceneUpdated, listener), + onDidLoadScene: (listener: (event: SceneLoadEvent) => void) => ipc.on(IPC_EVENTS.analysisSceneLoad, listener), + reloadScene: () => ipc.invoke(IPC_CHANNELS.analysisReloadScene), + rerunScene: () => ipc.invoke(IPC_CHANNELS.analysisRerunScene), + setFollowsChanges: (enabled: boolean) => ipc.invoke(IPC_CHANNELS.analysisSetFollowsChanges, enabled === true), onDidRequestOpenInEditor: (listener: (event: SceneOpenInEditorEvent) => void) => ipc.on(IPC_EVENTS.analysisOpenInEditor, listener), // #155: no server id crosses the bridge; main acts on the calling window's scene. shareScene: () => ipc.invoke(IPC_CHANNELS.analysisShareScene), diff --git a/apps/ide/src/main/analysis/analysisService.ts b/apps/ide/src/main/analysis/analysisService.ts index 3429b492..268cad50 100644 --- a/apps/ide/src/main/analysis/analysisService.ts +++ b/apps/ide/src/main/analysis/analysisService.ts @@ -20,15 +20,15 @@ import { getActiveServerRegistry } from '@codexr/core/server/registry/activeServ import { ServerControl } from '@codexr/core/server/serverControl'; import { ServerSettingsManager } from '@codexr/core/server/serverSettingsManager'; import { ANALYSIS_KIND_INFO, orchestratorArgs, sceneViewName, type AnalysisKind } from '../../shared/analysisKinds.ts'; -import { AUTO_START_MODES, IPC_EVENTS, type AnalysisStartResult, type AutoStartMode, type EnterXrResult, type SceneAddress, type SceneInfo, type SceneFilesEvent, type SceneShareEvent, type SceneShareState } from '../../shared/api.ts'; +import { AUTO_START_MODES, IPC_EVENTS, type AnalysisStartResult, type AutoStartMode, type EnterXrResult, type SceneAddress, type SceneInfo, type SceneFilesEvent, type SceneLoadEvent, type SceneLoadState, type SceneShareEvent, type SceneShareState, type SceneUpdatedEvent } from '../../shared/api.ts'; import { CODEXR_IPC_EVENTS, type SceneClosedEvent, type SceneModeEvent, type SceneModeResult, type SceneModes, type StopAllResult } from '../../shared/codexr.ts'; import { channelLog } from '../log.ts'; import type { PythonEnvironmentService } from '../python/pythonEnvironment.ts'; import { resolveAnalysisTarget } from './analysisTarget.ts'; import { readAnalysedFileCount, watchAnalysedFileCount } from './analysedFiles.ts'; import { readMetrics, type FileMetrics } from '../agents/tools/analysisQueries.ts'; -import { computeMetricDelta, type MetricDeltaReport } from './metricDelta.ts'; -import { followRefreshes, waitUntilSettled, type RefreshPort, type SceneUpdatedEvent, type SettleResult } from './sceneRefresh.ts'; +import { computeMetricDelta, freshnessOfSettle, type MetricDeltaReport } from './metricDelta.ts'; +import { followRefreshStatus, waitUntilSettled, type RefreshPort, type RefreshStatus, type SettleResult } from './sceneRefresh.ts'; import { closeScene, enterSceneXr, sceneSupportsImmersiveXr, showScene } from './sceneView.ts'; import { ENTER_XR_IN_SCENE_MESSAGE, inIdeXrUnavailable, unsupportedXrMessage } from './sceneXrPolicy.ts'; import { sceneTargetToWorkspacePath } from './sceneEditorTarget.ts'; @@ -95,6 +95,8 @@ interface WindowScene { share: SceneShareState; /** #16: stops following the analysis's file count. */ unwatch: () => void; + /** O10 (#512): sends the window the scene's refresh state again (following changes was turned on or off). */ + republish: () => void; } export class AnalysisService { @@ -228,9 +230,47 @@ export class AnalysisService { async setFollowsChanges(enabled: boolean): Promise { await AnalysisConfigurationStorage.getInstance(this.context).setAutoAnalysisEnabled(enabled); + // O10 (#512): every scene header's freshness chip follows. + for (const scene of this.scenes.values()) { + scene.republish(); + } return enabled; } + /** + * O10 (#512): the scene placeholder's Reload: loads the window's scene + * again, with a new sign-in link (the last one was single use), and tells + * the window how it ended, as the first load does. + */ + async reloadScene(win: BrowserWindow): Promise { + const scene = this.liveScene(win); + return this.loadScene(win, scene.serverId, scene.url); + } + + /** O10 (#512): the scene placeholder's Run again: the window's scene's analysis, same kind and target. */ + async rerunScene(win: BrowserWindow, folder: string | undefined): Promise { + const scene = this.scenes.get(win.webContents.id); + if (!scene) { + return { ok: false, reason: 'failed', message: 'This window shows no analysis to run again.' }; + } + const root = folder ?? scene.folder; + const relative = ANALYSIS_KIND_INFO[scene.kind].target === 'project' ? '' : path.relative(root, scene.target).split(path.sep).join('/'); + return this.analyse(win, folder, scene.kind, relative); + } + + /** Loads a scene into the window's view and tells the window how it ended (O10, #512). */ + private async loadScene(win: BrowserWindow, serverId: string, serverUrl: string): Promise { + const contents = win.webContents; + const state = await showScene(win, authenticatedSceneUrl(serverId, serverUrl)); + if (state !== 'loaded') { + log.warn(`The scene at ${serverUrl} did not load (${state}).`); + } + if (!contents.isDestroyed() && this.scenes.get(contents.id)?.url === serverUrl) { + contents.send(IPC_EVENTS.analysisSceneLoad, { url: serverUrl, state } satisfies SceneLoadEvent); + } + return state; + } + /** * AF8: `listener` hears each re-analysis of a window's scene that a change * on disk caused (the editor's save, a terminal, an agent). Returns the @@ -289,7 +329,8 @@ export class AnalysisService { * AF9: what a turn did to the measurements: waits for the scene to catch * up with the disk, then compares its records with `before` (from * `sceneMetrics` at the turn's start). `changedPaths` are relative to the - * window's folder (the folder a project scene analyses). + * window's folder (the folder a project scene analyses). O11 (#513): the + * report's `freshness` says whether the wait ended on refreshed data. */ async turnMetricDelta( contents: WebContents, @@ -298,7 +339,7 @@ export class AnalysisService { options: { readonly timeoutMs?: number } = {}, ): Promise<{ readonly settle: SceneSettleResult; readonly report: MetricDeltaReport }> { const settle = await this.settleScene(contents, options.timeoutMs); - return { settle, report: computeMetricDelta(before, await this.sceneMetrics(contents), changedPaths) }; + return { settle, report: computeMetricDelta(before, await this.sceneMetrics(contents), changedPaths, freshnessOfSettle(settle)) }; } /** @@ -713,20 +754,47 @@ export class AnalysisService { } }); const sessionId = this.sessionOf(serverId); - // AF8: each finished re-analysis of this scene, for whoever listens. - const unfollow = sessionId - ? followRefreshes(refreshPort(sessionId), (revision) => { - void readAnalysedFileCount(single ? undefined : server?.htmlFile).then((count) => { - if (contents.isDestroyed()) { - return; - } - const event: SceneUpdatedEvent = count === undefined ? { url: serverUrl, revision } : { url: serverUrl, revision, files: count }; + // AF8, O10 (#512): the scene's refresh state for the window's header, + // and each finished re-analysis for whoever listens. + let lastFiles = files; + let lastStatus: RefreshStatus | null = null; + // Reads are async: only the newest status reaches the window, never an older one after it. + let published = 0; + const publish = (status: RefreshStatus, refreshed: boolean): void => { + const order = ++published; + void (async () => { + if (refreshed) { + lastFiles = await readAnalysedFileCount(single ? undefined : server?.htmlFile) ?? lastFiles; + } + const following = await this.followsChanges().catch(() => true); + if (contents.isDestroyed() || this.scenes.get(contents.id)?.url !== serverUrl) { + return; + } + const event: SceneUpdatedEvent = { url: serverUrl, revision: status.revision, files: lastFiles, refresh: status.refresh, mode: status.mode, following }; + if (order === published) { + contents.send(IPC_EVENTS.analysisSceneUpdated, event); + } + if (refreshed) { for (const listener of this.updateListeners) { listener(contents, event); } - }); + } + })().catch((error: unknown) => log.warn(`Could not report the scene's refresh: ${String(error)}`)); + }; + const unfollow = sessionId + ? followRefreshStatus(refreshPort(sessionId), (status, previous) => { + lastStatus = status; + // The first call is the state at opening: the window hears it once the scene is registered (below). + if (previous) { + publish(status, status.revision > previous.revision); + } }) : () => undefined; + const republish = (): void => { + if (lastStatus) { + publish(lastStatus, false); + } + }; // #399: the scene's analysis changed (the IDE, the scene's own menu, a guest): the Scene section follows. let shownMode = sessionId ? analysisRefreshCoordinator.getViewState(sessionId)?.mode : undefined; const unfollowMode = sessionId @@ -743,7 +811,7 @@ export class AnalysisService { unfollowMode(); }; win.once('closed', unwatch); - this.scenes.set(win.webContents.id, { folder: this.ownerFolder, kind: this.ownerKind, target: this.ownerTarget, serverId, sessionId, url: serverUrl, share, unwatch }); + this.scenes.set(win.webContents.id, { folder: this.ownerFolder, kind: this.ownerKind, target: this.ownerTarget, serverId, sessionId, url: serverUrl, share, unwatch, republish }); if (previous && previous.serverId !== serverId) { // A new analysis replaces the window's scene; its old server (and tunnel) has nothing left to show. void this.stopTunnel(previous.serverId); @@ -766,7 +834,8 @@ export class AnalysisService { if (this.ownerFolder && !isFileKind(this.ownerKind)) { this.hooks.sceneOpened?.(win.webContents, this.ownerFolder); } - await showScene(win, authenticatedSceneUrl(serverId, serverUrl)); + republish(); + await this.loadScene(win, serverId, serverUrl); } } diff --git a/apps/ide/src/main/analysis/metricDelta.ts b/apps/ide/src/main/analysis/metricDelta.ts index e89c26f5..24b08e05 100644 --- a/apps/ide/src/main/analysis/metricDelta.ts +++ b/apps/ide/src/main/analysis/metricDelta.ts @@ -1,4 +1,6 @@ -import type { MetricChangeView, TurnMetricDeltaView } from '../../shared/agentSession.ts'; +import type { MetricChangeView, MetricDeltaFreshness, TurnMetricDeltaView } from '../../shared/agentSession.ts'; + +export type { MetricDeltaFreshness } from '../../shared/agentSession.ts'; import { normalize, type FileMetrics } from '../agents/tools/analysisQueries.ts'; /** @@ -73,6 +75,42 @@ export interface MetricDeltaReport { }; /** One line for a chat or a header: what moved, or that nothing did. */ readonly summary: string; + /** + * O11 (#513): whether `after` caught up with the disk. When not `fresh`, + * the comparison may be against the analysis from before the turn, so a + * "No metric changes." would be a guess: the summary says it is pending. + */ + readonly freshness: MetricDeltaFreshness; +} + +/** + * O11 (#513): how a turn's wait for the scene ended (`SceneSettleResult` of + * analysisService.ts), as a delta's freshness. `no-scene` is `fresh`: without + * a scene there is no analysis after the turn, and no delta to qualify. + */ +export function freshnessOfSettle(settle: string): MetricDeltaFreshness { + switch (settle) { + case 'paused': + return 'paused'; + case 'not-following': + return 'not-following'; + case 'timeout': + case 'pending': + return 'timeout'; + default: + return 'fresh'; + } +} + +const PENDING_REASONS: Readonly, string>> = { + paused: 'the scene shows another analysis, so its data was not refreshed', + timeout: 'the analysis did not catch up with the changes in time', + 'not-following': 'the scene is not following changes on disk', +}; + +/** "Delta pending: ." for an agent or a log; null when fresh. */ +export function pendingSummary(freshness: MetricDeltaFreshness): string | null { + return freshness === 'fresh' ? null : `Delta pending: ${PENDING_REASONS[freshness]}.`; } const round = (value: number): number => Math.round(value * 100) / 100; @@ -188,13 +226,14 @@ export function computeMetricDelta( before: readonly FileMetrics[] | null | undefined, after: readonly FileMetrics[] | null | undefined, changedPaths?: readonly string[] | null, + freshness: MetricDeltaFreshness = 'fresh', ): MetricDeltaReport { if (!after) { - return { status: 'no-analysis', files: [], totals: { before: before ? metricTotals(before) : null, after: null, delta: {} }, summary: 'No analysis to measure the change with.' }; + return { status: 'no-analysis', files: [], totals: { before: before ? metricTotals(before) : null, after: null, delta: {} }, summary: 'No analysis to measure the change with.', freshness }; } const afterTotals = metricTotals(after); if (!before) { - return { status: 'no-baseline', files: [], totals: { before: null, after: afterTotals, delta: {} }, summary: `No analysis before the turn; the project now has ${afterTotals.files} analysed files.` }; + return { status: 'no-baseline', files: [], totals: { before: null, after: afterTotals, delta: {} }, summary: `No analysis before the turn; the project now has ${afterTotals.files} analysed files.`, freshness }; } const was = byPath(before); const now = byPath(after); @@ -225,7 +264,8 @@ export function computeMetricDelta( } const beforeTotals = metricTotals(before); const delta = totalsDelta(beforeTotals, afterTotals); - return { status: 'ok', files, totals: { before: beforeTotals, after: afterTotals, delta }, summary: describe(files, beforeTotals, afterTotals, delta) }; + const summary = pendingSummary(freshness) ?? describe(files, beforeTotals, afterTotals, delta); + return { status: 'ok', files, totals: { before: beforeTotals, after: afterTotals, delta }, summary, freshness }; } /** The report as text for an agent or a log: the summary, then one line per file. */ @@ -247,13 +287,17 @@ const VIEW_TOTALS: readonly (keyof MetricTotals)[] = [ * AF9: the report as the chat keeps it on a turn: serialisable, only what * moved, at most `maxFiles` files. Null when there is nothing to show (no * analysis on either side, or no metric moved), so a chat without a scene - * stays quiet. + * stays quiet. O11 (#513): a delta not measured on fresh data is kept as + * pending, with no numbers, so "nothing moved" is only said when it is true. */ export function toTurnMetricDeltaView(report: MetricDeltaReport, maxFiles = 30): TurnMetricDeltaView | null { const { before, after } = report.totals; if (report.status !== 'ok' || !before || !after) { return null; } + if (report.freshness !== 'fresh') { + return { summary: report.summary, totals: [], files: [], moreFiles: 0, freshness: report.freshness }; + } const totals: MetricChangeView[] = VIEW_TOTALS.filter((key) => before[key] !== after[key]).map((key) => ({ metric: key, before: before[key], after: after[key] })); const moved = report.files.filter((file) => file.status === 'added' || file.status === 'removed' || file.status === 'changed'); if (totals.length === 0 && moved.length === 0) { diff --git a/apps/ide/src/main/analysis/sceneRefresh.ts b/apps/ide/src/main/analysis/sceneRefresh.ts index ae00407d..e050e16f 100644 --- a/apps/ide/src/main/analysis/sceneRefresh.ts +++ b/apps/ide/src/main/analysis/sceneRefresh.ts @@ -12,6 +12,10 @@ * coordinator's view state, through this pure, host-free module. */ +import type { SceneLoadState, SceneRefreshState } from '../../shared/api.ts'; + +export type { SceneUpdatedEvent } from '../../shared/api.ts'; + /** The fields of the core's `AnalysisViewState` this module reads. */ export interface RefreshView { readonly mode: string; @@ -28,7 +32,7 @@ export interface RefreshView { * evolution, the mode menu), where the core leaves `data.json` alone until * the classic view comes back, so waiting would not help. */ -export type RefreshState = 'settled' | 'pending' | 'paused'; +export type RefreshState = SceneRefreshState; /** `data.json` is the classic view's dataset, the coordinator's `single` mode. */ const DATA_MODE = 'single'; @@ -106,16 +110,47 @@ export function followRefreshes(port: RefreshPort, onRefreshed: (revision: numbe }); } +/** O10 (#512): what the scene header's freshness chip needs from the core's view state. */ +export interface RefreshStatus { + readonly revision: number; + readonly refresh: RefreshState; + readonly mode: string; +} + +export function refreshStatus(view: RefreshView): RefreshStatus { + return { revision: dataRevision(view), refresh: refreshState(view), mode: view.mode }; +} + /** - * Sent to the window when its scene's analysis was refreshed after a change - * on disk (to be declared in shared/api.ts as `SceneUpdatedEvent` with the - * IPC event `codexr:analysis:scene-updated` when it is wired). + * O10 (#512): calls `onStatus` with the current status at once, then each + * time its revision, refresh state or mode changes (the core reports every + * change of its view state, most of which change none of these). Returns the + * function that stops it. */ -export interface SceneUpdatedEvent { - /** The scene's local URL, like the other scene events, to drop a stale one. */ - readonly url: string; - /** The refresh count of the classic view: increases by at least 1 per event. */ - readonly revision: number; - /** How many files the analysis holds now, when known. */ - readonly files?: number; +export function followRefreshStatus(port: RefreshPort, onStatus: (status: RefreshStatus, previous: RefreshStatus | null) => void): () => void { + let last = refreshStatus(port.view()); + onStatus(last, null); + return port.onChange(() => { + const next = refreshStatus(port.view()); + if (next.revision !== last.revision || next.refresh !== last.refresh || next.mode !== last.mode) { + const previous = last; + last = next; + onStatus(next, previous); + } + }); +} + +/** + * O10 (#512): how loading a page ended. A Tauri webview reports only a + * finished load (no failure), so a load that never finishes would leave the + * caller waiting for ever: after `timeoutMs` it is `timeout`. Never rejects. + */ +export function loadWithin(load: Promise, timeoutMs: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve('timeout'), timeoutMs); + load.then( + () => { clearTimeout(timer); resolve('loaded'); }, + () => { clearTimeout(timer); resolve('failed'); }, + ); + }); } diff --git a/apps/ide/src/main/analysis/sceneView.ts b/apps/ide/src/main/analysis/sceneView.ts index 91a65949..f8b0f7bd 100644 --- a/apps/ide/src/main/analysis/sceneView.ts +++ b/apps/ide/src/main/analysis/sceneView.ts @@ -1,6 +1,7 @@ import { BrowserWindow, WebContentsView, session, type Session, type WebContents } from '../host/desktop.ts'; -import type { SceneBounds } from '../../shared/api.ts'; +import { SCENE_LOAD_TIMEOUT_MS, type SceneBounds, type SceneLoadState } from '../../shared/api.ts'; import { log } from '../log.ts'; +import { loadWithin } from './sceneRefresh.ts'; import { localSceneOrigin } from './sceneUrl.ts'; import { allowXrPermission, XR_ARM_MS, type XrArm } from './sceneXrPolicy.ts'; import { SCENE_BRIDGE_INTERNALS } from '../../shared/sceneBridge.ts'; @@ -56,8 +57,13 @@ const views = new Map(); /** #19: per window, the scene the person just asked to enter in XR. */ const xrArms = new Map(); -/** Shows `url` in `win`'s scene view, replacing what it showed. Refuses anything but a local Code-XR server. */ -export async function showScene(win: BrowserWindow, url: string): Promise { +/** + * Shows `url` in `win`'s scene view, replacing what it showed. Refuses anything but a local Code-XR server. + * O10 (#512): resolves with how the load ended, `timeout` after `timeoutMs` + * (a Tauri webview reports no failed load, so one could otherwise hang the caller). + * The placeholder's Reload calls it again: a fresh view, never one whose creation may still hang. + */ +export async function showScene(win: BrowserWindow, url: string, timeoutMs = SCENE_LOAD_TIMEOUT_MS): Promise { const origin = localSceneOrigin(url); if (!origin) { throw new Error(`Refused to show ${url}: not a local Code-XR server.`); @@ -68,9 +74,10 @@ export async function showScene(win: BrowserWindow, url: string): Promise win.contentView.addChildView(view); views.set(win.id, view); win.once('closed', () => views.delete(win.id)); - await view.webContents.loadURL(url); + return loadWithin(view.webContents.loadURL(url), timeoutMs); } + /** Places the scene over the renderer's slot, or hides it (null). */ export function setSceneBounds(win: BrowserWindow, bounds: SceneBounds | null): void { const view = views.get(win.id); diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index 08ec59a0..7df53569 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -291,6 +291,15 @@ export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: handle(IPC_CHANNELS.analysisEnterXr, (event) => core.analysis.enterXr(ownerOf(event))); handle(IPC_CHANNELS.analysisOpenSceneInBrowser, (event) => core.analysis.openSceneInBrowser(ownerOf(event), (url) => shell.openExternal(url))); handle(IPC_CHANNELS.analysisHeadsetLink, (event) => core.analysis.headsetLink(ownerOf(event))); + // O10 (#512): the scene placeholder's Reload and Run again act on the calling window's scene only. + handle(IPC_CHANNELS.analysisReloadScene, (event) => core.analysis.reloadScene(ownerOf(event))); + handle(IPC_CHANNELS.analysisRerunScene, (event) => core.analysis.rerunScene(ownerOf(event), currentWorkspaceInfo(event.sender)?.root)); + handle(IPC_CHANNELS.analysisSetFollowsChanges, (_event, enabled) => { + if (typeof enabled !== 'boolean') { + throw new Error('Following changes is on or off.'); + } + return core.analysis.setFollowsChanges(enabled); + }); // #137: the terminal. Profiles are addressed by id only; a terminal only by // the window that created it (TerminalService checks the owner). handle(IPC_CHANNELS.terminalProfiles, () => terminal.profiles()); diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 9de8bd88..5013d56d 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -33,8 +33,6 @@ .af-dock-art path { fill: none; stroke: var(--accent); stroke-width: 1.2; stroke-linejoin: round; } .af-live { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-sm); font-weight: 600; color: var(--muted); } .af-live::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); } -.af-live[data-state='live'] { color: var(--accent); } -.af-live[data-state='live']::before { background: var(--accent); } .af-live[data-state='running'] { color: var(--accent); } .af-live[data-state='running']::before { background: var(--accent); animation: af-live-pulse 1.4s ease-in-out infinite; } @keyframes af-live-pulse { 50% { opacity: 0.35; } } diff --git a/apps/ide/src/renderer/agentFirst/changesModel.ts b/apps/ide/src/renderer/agentFirst/changesModel.ts index c7272cf1..005aa8d9 100644 --- a/apps/ide/src/renderer/agentFirst/changesModel.ts +++ b/apps/ide/src/renderer/agentFirst/changesModel.ts @@ -1,4 +1,5 @@ -import type { ChangedFileView, MetricChangeView, TurnMetricDeltaView } from '../../shared/agentSession.ts'; +import type { ChangedFileView, MetricChangeView, MetricDeltaFreshness, TurnMetricDeltaView } from '../../shared/agentSession.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; /** * Pure helpers of the review of a chat's changes (AF5, #270), its restores @@ -92,8 +93,27 @@ export function formatMetricChange(change: MetricChangeView): string { return `${label} ${delta > 0 ? '+' : ''}${delta}`; } +const PENDING_REASON_KEYS: Readonly, MessageKey>> = { + paused: 'metricDelta.reason.paused', + timeout: 'metricDelta.reason.timeout', + 'not-following': 'metricDelta.reason.notFollowing', +}; + +/** + * O11 (#513): "delta pending: " when the delta was not measured on + * refreshed data, else null (an older chat's delta has no freshness: fresh). + */ +export function metricDeltaPending(delta: TurnMetricDeltaView): string | null { + const freshness = delta.freshness ?? 'fresh'; + return freshness === 'fresh' ? null : t('metricDelta.pending', { reason: t(PENDING_REASON_KEYS[freshness]) }); +} + /** The short line under a turn: the first few totals that moved, else the analysis' own summary. */ export function metricDeltaHeadline(delta: TurnMetricDeltaView, max = 3): string { + const pending = metricDeltaPending(delta); + if (pending !== null) { + return pending; + } if (delta.totals.length === 0) { return delta.summary; } diff --git a/apps/ide/src/renderer/sceneHeaderModel.ts b/apps/ide/src/renderer/sceneHeaderModel.ts index 0bb650d4..ee88a96f 100644 --- a/apps/ide/src/renderer/sceneHeaderModel.ts +++ b/apps/ide/src/renderer/sceneHeaderModel.ts @@ -1,5 +1,6 @@ import { ANALYSIS_KIND_INFO, sceneKindLabel, type AnalysisKind } from '../shared/analysisKinds.ts'; -import type { EnterXrResult, SceneInfo, SceneShareState, SceneShareStatus } from '../shared/api.ts'; +import { SCENE_LOAD_TIMEOUT_MS, type EnterXrResult, type SceneInfo, type SceneLoadState, type SceneShareState, type SceneShareStatus, type SceneUpdatedEvent } from '../shared/api.ts'; +import { t, type MessageKey } from '../shared/i18n/i18n.ts'; /** * Pure state of the scene's header (#155): what ran, where it is served, and @@ -124,3 +125,121 @@ export function enterXrState(scene: Pick): export function enterXrNote(result: EnterXrResult): string { return result.ok ? result.message ?? '' : result.message; } + +/** + * O10 (#512): the scene header's freshness chip. Where the scene's analysis + * stands against the disk, from the last `SceneUpdatedEvent`, in order of + * what matters most: not following changes at all, showing another analysis + * (the classic view's data waits), a refresh running, else when it last + * caught up. Pure: `now` and `updatedAt` are milliseconds. + */ +export type SceneFreshness = + | { readonly kind: 'not-following' } + | { readonly kind: 'paused'; readonly mode: string } + | { readonly kind: 'updating' } + | { readonly kind: 'updated'; readonly seconds: number }; + +/** How often the chip's "Updated 12 s ago" is redrawn. */ +export const SCENE_STATUS_TICK_MS = 15_000; + +export function sceneFreshness(status: Pick, updatedAt: number, now: number): SceneFreshness { + if (!status.following) { + return { kind: 'not-following' }; + } + if (status.refresh === 'paused') { + return { kind: 'paused', mode: status.mode }; + } + if (status.refresh === 'pending') { + return { kind: 'updating' }; + } + return { kind: 'updated', seconds: Math.max(0, Math.floor((now - updatedAt) / 1000)) }; +} + +const MODE_NAME_KEYS: Readonly> = { + 'dependency-graph': 'scene.mode.dependencyGraph', + 'historical-compare': 'scene.mode.historicalCompare', + 'project-evolution': 'scene.mode.projectEvolution', + 'agent-flow': 'scene.mode.agentFlow', + 'drill-down': 'scene.mode.drillDown', + selection: 'scene.mode.selection', +}; + +/** "dependency graph": what the scene shows instead of the classic view. */ +export function sceneModeName(mode: string): string { + const key = MODE_NAME_KEYS[mode]; + return key ? t(key) : t('scene.mode.other'); +} + +/** "12 s", "3 min", "2 h", "4 d". */ +export function elapsedLabel(seconds: number): string { + const whole = Math.max(0, Math.floor(seconds)); + if (whole < 60) { + return t('scene.elapsed.seconds', { count: String(whole) }); + } + if (whole < 3600) { + return t('scene.elapsed.minutes', { count: String(Math.floor(whole / 60)) }); + } + if (whole < 86_400) { + return t('scene.elapsed.hours', { count: String(Math.floor(whole / 3600)) }); + } + return t('scene.elapsed.days', { count: String(Math.floor(whole / 86_400)) }); +} + +/** "Updating…", "Updated 12 s ago", "Paused: dependency graph shown", "Not following changes". */ +export function sceneStatusLabel(freshness: SceneFreshness): string { + switch (freshness.kind) { + case 'not-following': + return t('scene.status.notFollowing'); + case 'paused': + return t('scene.status.paused', { mode: sceneModeName(freshness.mode) }); + case 'updating': + return t('scene.status.updating'); + case 'updated': + return t('scene.status.updated', { elapsed: elapsedLabel(freshness.seconds) }); + } +} + +/** The chip's tooltip: what the state means. */ +export function sceneStatusTitle(freshness: SceneFreshness): string { + switch (freshness.kind) { + case 'not-following': + return t('scene.status.notFollowingTitle'); + case 'paused': + return t('scene.status.pausedTitle'); + case 'updating': + return t('scene.status.updatingTitle'); + case 'updated': + return t('scene.status.updatedTitle'); + } +} + +/** + * O10 (#512): the scene slot's placeholder while the page loads, and after it + * failed. `loading` and `failed` keep the native view hidden, so the + * placeholder (with Reload and Run again after a failure) is what the slot shows. + */ +export type SceneLoadView = + | { readonly kind: 'loading' } + | { readonly kind: 'loaded' } + | { readonly kind: 'failed'; readonly state: 'failed' | 'timeout' }; + +export const SCENE_LOADING: SceneLoadView = { kind: 'loading' }; + +/** The renderer's own backstop, a little after the main process's timeout, should its answer never come. */ +export const SCENE_PLACEHOLDER_TIMEOUT_MS = SCENE_LOAD_TIMEOUT_MS + 5_000; + +export function sceneLoadView(state: SceneLoadState): SceneLoadView { + return state === 'loaded' ? { kind: 'loaded' } : { kind: 'failed', state }; +} + +/** What the placeholder says; empty once loaded. */ +export function scenePlaceholderText(view: SceneLoadView): string { + switch (view.kind) { + case 'loading': + return t('scene.placeholder.loading'); + case 'loaded': + return ''; + case 'failed': + return view.state === 'timeout' ? t('scene.placeholder.timeout') : t('scene.placeholder.failed'); + } +} diff --git a/apps/ide/src/renderer/scenePanel.ts b/apps/ide/src/renderer/scenePanel.ts index 6dd808e2..62145333 100644 --- a/apps/ide/src/renderer/scenePanel.ts +++ b/apps/ide/src/renderer/scenePanel.ts @@ -1,7 +1,12 @@ -import type { CodeXRApi, SceneAddress, SceneInfo } from '../shared/api.ts'; +import type { CodeXRApi, SceneAddress, SceneInfo, SceneLoadState, SceneUpdatedEvent } from '../shared/api.ts'; +import { t } from '../shared/i18n/i18n.ts'; import { closeIcon, el, icon } from './dom.ts'; import { createSceneXrControls } from './sceneXrControls.ts'; -import { analysedFilesLabel, analysisKindLabel, displayAddress, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, shareControls, type ShareAction, type ShareView } from './sceneHeaderModel.ts'; +import { + analysedFilesLabel, analysisKindLabel, displayAddress, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, SCENE_LOADING, SCENE_PLACEHOLDER_TIMEOUT_MS, + SCENE_STATUS_TICK_MS, sceneFreshness, sceneLoadView, scenePlaceholderText, sceneStatusLabel, sceneStatusTitle, shareControls, + type SceneLoadView, type ShareAction, type ShareView, +} from './sceneHeaderModel.ts'; /** * The analysis scene beside the code (#16). The scene itself is drawn by the @@ -22,6 +27,8 @@ export interface ScenePanel { const COPY_ICON = 'M9 9h11v11H9z M5 15H4V4h11v1'; const COPIED_MS = 1500; +/** O10 (#512): how long the chip stays highlighted after a refresh (no highlight under reduced motion: styles.css). */ +const UPDATED_HIGHLIGHT_MS = 1200; function copyButton(label: string, testId: string): HTMLButtonElement { return el('button', { className: 'icon-button scene-copy', attrs: { type: 'button', title: label, 'aria-label': label, 'data-testid': testId } }, [icon(COPY_ICON)]); @@ -36,6 +43,9 @@ export function createScenePanel( const title = el('span', { className: 'scene-title', attrs: { 'data-testid': 'scene-title' } }); const files = el('span', { className: 'scene-files', attrs: { 'data-testid': 'scene-files' } }); const close = el('button', { className: 'icon-button', attrs: { type: 'button', title: 'Close the scene', 'aria-label': 'Close the scene' } }, [closeIcon()]); + // O10 (#512): where the scene's analysis stands against the disk. + const status = el('span', { className: 'scene-status', attrs: { 'data-testid': 'scene-status' } }); + const follow = el('button', { className: 'secondary-button scene-follow', text: t('scene.status.follow'), attrs: { type: 'button', title: t('scene.status.followTitle'), 'data-testid': 'scene-follow' } }); const localAddress = el('span', { className: 'scene-address', attrs: { 'data-testid': 'scene-local-address' } }); const copyLocal = copyButton('Copy the local address', 'scene-copy-local'); @@ -52,7 +62,7 @@ export function createScenePanel( // `report` is declared below; the controls only call it after a click or a scene change. const xr = createSceneXrControls(api, { onError: (message) => callbacks.onError(message), relayout: () => report() }); const header = el('header', { className: 'scene-header', attrs: { 'data-testid': 'scene-header' } }, [ - el('div', { className: 'scene-header-row' }, [kind, title, files, close]), + el('div', { className: 'scene-header-row' }, [kind, title, files, status, follow, close]), // CI1: one row for where the scene is served and what to do with it (two before, plus an XR row). el('div', { className: 'scene-header-row scene-actions-row' }, [ localAddress, copyLocal, xr.row, el('span', { className: 'scene-header-spacer' }), share, stop, @@ -62,7 +72,13 @@ export function createScenePanel( xr.note, xr.headset, ]); - const slot = el('div', { className: 'scene-slot', attrs: { 'data-testid': 'scene-slot' } }); + // O10 (#512): shown in the slot until the page loaded, and after it failed, under the (hidden) native view. + const placeholderText = el('p', { className: 'scene-placeholder-text', attrs: { role: 'status' } }); + const reload = el('button', { className: 'secondary-button', text: t('scene.placeholder.reload'), attrs: { type: 'button', title: t('scene.placeholder.reloadTitle'), 'data-testid': 'scene-reload' } }); + const rerun = el('button', { className: 'secondary-button', text: t('scene.placeholder.rerun'), attrs: { type: 'button', title: t('scene.placeholder.rerunTitle'), 'data-testid': 'scene-rerun' } }); + const placeholderActions = el('div', { className: 'scene-placeholder-actions' }, [reload, rerun]); + const placeholder = el('div', { className: 'scene-placeholder', attrs: { 'data-testid': 'scene-placeholder' } }, [placeholderText, placeholderActions]); + const slot = el('div', { className: 'scene-slot', attrs: { 'data-testid': 'scene-slot' } }, [placeholder]); area.replaceChildren(header, slot); let open = false; @@ -70,11 +86,17 @@ export function createScenePanel( let current: SceneInfo | null = null; let shareView: ShareView = INITIAL_SHARE_VIEW; let frame = 0; + let load: SceneLoadView = SCENE_LOADING; + let loadTimer: ReturnType | undefined; + let sceneStatus: SceneUpdatedEvent | null = null; + let updatedAt = Date.now(); + let highlightTimer: ReturnType | undefined; const report = (): void => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => { const rect = slot.getBoundingClientRect(); - const visible = open && !suspended && rect.width > 0 && rect.height > 0; + // O10: the native view stays hidden until its page loaded, so the placeholder shows. + const visible = open && !suspended && load.kind === 'loaded' && rect.width > 0 && rect.height > 0; api.setSceneBounds(visible ? { x: rect.left, y: rect.top, width: rect.width, height: rect.height } : null) .catch((reason: unknown) => callbacks.onError(`Could not place the scene: ${String(reason)}`)); }); @@ -155,9 +177,118 @@ export function createScenePanel( } }); + function renderStatus(): void { + if (!sceneStatus) { + status.hidden = true; + follow.hidden = true; + return; + } + const freshness = sceneFreshness(sceneStatus, updatedAt, Date.now()); + status.hidden = false; + status.textContent = sceneStatusLabel(freshness); + status.title = sceneStatusTitle(freshness); + status.dataset['state'] = freshness.kind; + follow.hidden = freshness.kind !== 'not-following'; + } + renderStatus(); + // "Updated 12 s ago" moves on while nothing happens. + setInterval(() => { + if (open && sceneStatus) { + renderStatus(); + } + }, SCENE_STATUS_TICK_MS); + + function highlightUpdate(): void { + clearTimeout(highlightTimer); + status.classList.remove('is-updated'); + // Restarts the highlight when refreshes come close together. + void status.offsetWidth; + status.classList.add('is-updated'); + highlightTimer = setTimeout(() => status.classList.remove('is-updated'), UPDATED_HIGHLIGHT_MS); + } + + api.onDidUpdateScene((event) => { + if (!current || event.url !== current.url) { + return; + } + const refreshed = sceneStatus !== null && event.revision > sceneStatus.revision; + if (refreshed) { + updatedAt = Date.now(); + highlightUpdate(); + } + sceneStatus = event; + if (event.files !== undefined) { + files.textContent = analysedFilesLabel(event.files); + files.hidden = files.textContent === ''; + } + renderStatus(); + }); + follow.addEventListener('click', () => { + follow.disabled = true; + api.setFollowsChanges(true) + .catch((reason: unknown) => callbacks.onError(ipcErrorMessage(reason))) + .finally(() => { follow.disabled = false; }); + }); + + function setLoad(next: SceneLoadView): void { + load = next; + clearTimeout(loadTimer); + if (next.kind === 'loading') { + const scene = current; + loadTimer = setTimeout(() => { + if (scene === current && load.kind === 'loading') { + setLoad(sceneLoadView('timeout')); + } + }, SCENE_PLACEHOLDER_TIMEOUT_MS); + } + placeholder.hidden = next.kind === 'loaded'; + placeholderText.textContent = scenePlaceholderText(next); + placeholderActions.hidden = next.kind !== 'failed'; + reload.disabled = false; + rerun.disabled = false; + report(); + } + api.onDidLoadScene((event) => { + if (current && event.url === current.url) { + setLoad(sceneLoadView(event.state)); + } + }); + reload.addEventListener('click', () => { + const scene = current; + setLoad(SCENE_LOADING); + api.reloadScene().then( + (state: SceneLoadState) => { + if (scene === current) { setLoad(sceneLoadView(state)); } + }, + (reason: unknown) => { + if (scene === current) { + setLoad(sceneLoadView('failed')); + callbacks.onError(ipcErrorMessage(reason)); + } + }, + ); + }); + rerun.addEventListener('click', () => { + reload.disabled = true; + rerun.disabled = true; + // A new scene opens through onDidOpenScene when the analysis is done. + api.rerunScene().then( + (result) => { + if (!result.ok) { + callbacks.onError(result.message); + } + }, + (reason: unknown) => callbacks.onError(ipcErrorMessage(reason)), + ).finally(() => { + reload.disabled = false; + rerun.disabled = false; + }); + }); + function hide(): void { open = false; current = null; + clearTimeout(loadTimer); callbacks.setVisible(false); report(); } @@ -175,6 +306,10 @@ export function createScenePanel( title.title = scene.targetPath; files.textContent = analysedFilesLabel(scene.files); files.hidden = files.textContent === ''; + sceneStatus = null; + updatedAt = Date.now(); + renderStatus(); + setLoad(SCENE_LOADING); const address = displayAddress(scene.url); localAddress.textContent = address; localAddress.title = address; diff --git a/apps/ide/src/renderer/styles.css b/apps/ide/src/renderer/styles.css index d38a49c4..ab2a08ba 100644 --- a/apps/ide/src/renderer/styles.css +++ b/apps/ide/src/renderer/styles.css @@ -868,6 +868,22 @@ input[type='checkbox'], input[type='radio'] { accent-color: var(--button-bg); } .scene-share { flex: none; margin-left: auto; padding: 2px 8px; font-size: var(--fs-sm); white-space: nowrap; } .scene-share-error { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--crit); } .scene-slot { flex: 1; min-height: 0; } +/* O10 (#512): the scene's freshness chip, and the slot's placeholder while the page loads or after it failed + (the native view is hidden then, so this is what the slot shows). */ +.scene-status { flex: none; color: var(--muted); font-size: var(--fs-xs); white-space: nowrap; border-radius: var(--radius-sm); padding: 0 4px; } +.scene-status[hidden], .scene-follow[hidden] { display: none; } +.scene-status[data-state='updating'] { color: var(--accent); } +.scene-status[data-state='paused'], .scene-status[data-state='not-following'] { color: var(--warn); } +.scene-follow { flex: none; } +@media (prefers-reduced-motion: no-preference) { + .scene-status.is-updated { animation: scene-status-updated 1.2s ease-out; } + @keyframes scene-status-updated { from { background: var(--active); color: var(--fg); } } +} +.scene-slot { display: flex; } +.scene-placeholder { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 16px; text-align: center; color: var(--muted); } +.scene-placeholder[hidden], .scene-placeholder-actions[hidden] { display: none; } +.scene-placeholder-text { margin: 0; } +.scene-placeholder-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; } @media (max-width: 720px) { .workbench.has-scene { --scene-col: minmax(0, 1fr); } } diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index 9b4b9734..e4eb0709 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -261,6 +261,17 @@ export interface MetricChangeView { readonly after: number | null; } +/** + * O11 (#513): whether a turn's delta was measured on data that caught up + * with the disk. + * - `fresh`: the analysis refreshed after the turn's changes; + * - `paused`: the scene shows another analysis (dependency graph, history...), + * so the classic view's data was not refreshed; + * - `timeout`: the refresh did not finish in time; + * - `not-following`: the scene does not follow changes on disk. + */ +export type MetricDeltaFreshness = 'fresh' | 'paused' | 'timeout' | 'not-following'; + /** A compact, serialisable metric delta of one turn (AF9), kept on its turn-end item. */ export interface TurnMetricDeltaView { /** One line, from the analysis ("2 files (2 changed): code lines -6 ..."). */ @@ -271,6 +282,11 @@ export interface TurnMetricDeltaView { readonly files: readonly { readonly path: string; readonly status: string; readonly changes: readonly MetricChangeView[] }[]; /** Files left out of `files` by the cap. */ readonly moreFiles: number; + /** + * O11 (#513): absent or `fresh` when measured on refreshed data; any other + * value means the delta is pending (no totals or files are kept then). + */ + readonly freshness?: MetricDeltaFreshness; } export interface PlanEntryView { diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index c951558a..ed647d7c 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -335,6 +335,49 @@ export interface SceneFilesEvent { readonly files: number; } +/** + * AF8, O10 (#512): where the scene's analysis stands against the disk. + * - `settled`: `data.json` reflects every change the core has seen; + * - `pending`: a refresh is running or queued; + * - `paused`: the scene shows another analysis (`mode`), where the core + * leaves `data.json` alone until the classic view comes back. + */ +export type SceneRefreshState = 'settled' | 'pending' | 'paused'; + +/** + * AF8, O10 (#512): the refresh state of the scene `url` changed: a refresh + * started or finished (`revision` moved), it switched analysis, or following + * changes on disk was turned on or off. + */ +export interface SceneUpdatedEvent { + /** The scene's local URL, like the other scene events, to drop a stale one. */ + readonly url: string; + /** The refresh count of the classic view: moves by at least 1 per finished refresh. */ + readonly revision: number; + /** How many files the analysis holds now, when known. */ + readonly files?: number | undefined; + readonly refresh: SceneRefreshState; + /** The analysis the scene shows (the core's view mode: `single`, `dependency-graph`...). */ + readonly mode: string; + /** Whether the scene follows changes on disk (the core's auto-analysis setting). */ + readonly following: boolean; +} + +/** + * O10 (#512): how loading the scene's page ended. `timeout` (no load within + * `SCENE_LOAD_TIMEOUT_MS`; a cold WebKitGTK can take 35 s) and `failed` both + * leave the renderer's placeholder with Reload and Run again. + */ +export type SceneLoadState = 'loaded' | 'failed' | 'timeout'; + +export interface SceneLoadEvent { + readonly url: string; + readonly state: SceneLoadState; +} + +/** O10 (#512): how long the scene's page may take to load before it counts as failed. */ +export const SCENE_LOAD_TIMEOUT_MS = 45_000; + /** #16: the scene asked to open a file of the open folder in the editor. */ export interface SceneOpenInEditorEvent { /** Workspace-relative, already checked by the main process. */ @@ -465,6 +508,16 @@ export interface CodeXRApi { onDidOpenScene(listener: (scene: SceneInfo) => void): Unsubscribe; /** #16: the scene's analysis re-ran (a save) and its file count changed. */ onDidChangeSceneFiles(listener: (event: SceneFilesEvent) => void): Unsubscribe; + /** O10 (#512): the scene's refresh state changed (refreshing, refreshed, paused, following or not). */ + onDidUpdateScene(listener: (event: SceneUpdatedEvent) => void): Unsubscribe; + /** O10 (#512): the scene's page loaded, failed or timed out. */ + onDidLoadScene(listener: (event: SceneLoadEvent) => void): Unsubscribe; + /** O10 (#512): loads this window's scene again (a new sign-in link); resolves with how it ended. */ + reloadScene(): Promise; + /** O10 (#512): runs this window's scene's analysis again, same kind and target. */ + rerunScene(): Promise; + /** O10 (#512): whether open scenes follow changes on disk (the core's auto-analysis setting). */ + setFollowsChanges(enabled: boolean): Promise; /** * #178: marks a file of the open folder (a workspace path) in this * window's scene. Resolves false when no scene shows it. @@ -766,6 +819,9 @@ export const IPC_CHANNELS = { analysisEnterXr: 'codexr:analysis:enter-xr', analysisOpenSceneInBrowser: 'codexr:analysis:open-scene-in-browser', analysisHeadsetLink: 'codexr:analysis:headset-link', + analysisReloadScene: 'codexr:analysis:reload-scene', + analysisRerunScene: 'codexr:analysis:rerun-scene', + analysisSetFollowsChanges: 'codexr:analysis:set-follows-changes', terminalProfiles: 'codexr:terminal:profiles', terminalSetDefaultProfile: 'codexr:terminal:set-default-profile', terminalAddCustomProfile: 'codexr:terminal:add-custom-profile', @@ -809,6 +865,8 @@ export const IPC_EVENTS = { analysisSceneOpened: 'codexr:analysis:scene-opened', analysisSceneShareChanged: 'codexr:analysis:scene-share-changed', analysisSceneFilesChanged: 'codexr:analysis:scene-files-changed', + analysisSceneUpdated: 'codexr:analysis:scene-updated', + analysisSceneLoad: 'codexr:analysis:scene-load', analysisOpenInEditor: 'codexr:analysis:open-in-editor', terminalData: 'codexr:terminal:data', terminalExit: 'codexr:terminal:exit', diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index deb6a8cf..f3f2f0d9 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -610,6 +610,40 @@ export const en = { 'settings.note.userOnly': 'Only your user settings set this: it applies to every window.', 'settings.note.folderWins': 'This folder sets its own value, which wins here.', 'settings.note.userApplies': 'Your user setting applies.', + // O11 (#513): a turn's metric delta measured before the scene caught up. + 'metricDelta.pending': 'delta pending: {reason}', + 'metricDelta.reason.paused': 'the scene shows another analysis', + 'metricDelta.reason.timeout': 'the analysis did not catch up in time', + 'metricDelta.reason.notFollowing': 'the scene is not following changes', + // O10 (#512): the scene header's freshness chip and the scene slot's placeholder. + 'scene.status.updating': 'Updating…', + 'scene.status.updated': 'Updated {elapsed} ago', + 'scene.status.paused': 'Paused: {mode} shown', + 'scene.status.notFollowing': 'Not following changes', + 'scene.status.updatingTitle': 'The analysis is catching up with changes on disk.', + 'scene.status.updatedTitle': 'The scene shows the files as they are on disk.', + 'scene.status.pausedTitle': 'The scene shows another analysis: the classic view catches up with changes when it comes back.', + 'scene.status.notFollowingTitle': 'Changes on disk do not update the scene until you analyse again.', + 'scene.status.follow': 'Follow changes', + 'scene.status.followTitle': 'Update open scenes when files change on disk (a scene opened while this was off follows after you run it again)', + 'scene.mode.dependencyGraph': 'dependency graph', + 'scene.mode.historicalCompare': 'historical comparison', + 'scene.mode.projectEvolution': 'project evolution', + 'scene.mode.agentFlow': 'agent flow', + 'scene.mode.drillDown': 'drill-down', + 'scene.mode.selection': 'analyses menu', + 'scene.mode.other': 'another analysis', + 'scene.elapsed.seconds': '{count} s', + 'scene.elapsed.minutes': '{count} min', + 'scene.elapsed.hours': '{count} h', + 'scene.elapsed.days': '{count} d', + 'scene.placeholder.loading': 'Loading the scene…', + 'scene.placeholder.failed': 'Scene did not load.', + 'scene.placeholder.timeout': 'Scene did not load: it took too long.', + 'scene.placeholder.reload': 'Reload', + 'scene.placeholder.reloadTitle': 'Load the scene again from its server', + 'scene.placeholder.rerun': 'Run again', + 'scene.placeholder.rerunTitle': 'Run this analysis again', }; export type MessageKey = keyof typeof en; diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index d02ce7dc..00420237 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -613,4 +613,38 @@ export const es: Readonly> = { 'settings.note.userOnly': 'Solo la configuración de usuario puede establecerlo: se aplica a todas las ventanas.', 'settings.note.folderWins': 'Esta carpeta establece su propio valor, que es el que se aplica aquí.', 'settings.note.userApplies': 'Se aplica tu configuración de usuario.', + // O11 (#513): la variación de métricas de un turno medida antes de que la escena se pusiera al día. + 'metricDelta.pending': 'variación pendiente: {reason}', + 'metricDelta.reason.paused': 'la escena muestra otro análisis', + 'metricDelta.reason.timeout': 'el análisis no se puso al día a tiempo', + 'metricDelta.reason.notFollowing': 'la escena no sigue los cambios', + // O10 (#512): el indicador de actualización de la escena y el marcador de su espacio. + 'scene.status.updating': 'Actualizando...', + 'scene.status.updated': 'Actualizada hace {elapsed}', + 'scene.status.paused': 'En pausa: se muestra {mode}', + 'scene.status.notFollowing': 'No sigue los cambios', + 'scene.status.updatingTitle': 'El análisis se está poniendo al día con los cambios en disco.', + 'scene.status.updatedTitle': 'La escena muestra los archivos tal como están en disco.', + 'scene.status.pausedTitle': 'La escena muestra otro análisis: la vista clásica se pone al día con los cambios cuando vuelve.', + 'scene.status.notFollowingTitle': 'Los cambios en disco no actualizan la escena hasta que vuelvas a analizar.', + 'scene.status.follow': 'Seguir los cambios', + 'scene.status.followTitle': 'Actualizar las escenas abiertas cuando cambien los archivos en disco (una escena abierta mientras estaba desactivado los sigue al volver a ejecutarla)', + 'scene.mode.dependencyGraph': 'el grafo de dependencias', + 'scene.mode.historicalCompare': 'la comparación histórica', + 'scene.mode.projectEvolution': 'la evolución del proyecto', + 'scene.mode.agentFlow': 'el flujo del agente', + 'scene.mode.drillDown': 'el detalle', + 'scene.mode.selection': 'el menú de análisis', + 'scene.mode.other': 'otro análisis', + 'scene.elapsed.seconds': '{count} s', + 'scene.elapsed.minutes': '{count} min', + 'scene.elapsed.hours': '{count} h', + 'scene.elapsed.days': '{count} d', + 'scene.placeholder.loading': 'Cargando la escena...', + 'scene.placeholder.failed': 'La escena no se cargó.', + 'scene.placeholder.timeout': 'La escena no se cargó: tardó demasiado.', + 'scene.placeholder.reload': 'Recargar', + 'scene.placeholder.reloadTitle': 'Cargar de nuevo la escena desde su servidor', + 'scene.placeholder.rerun': 'Ejecutar de nuevo', + 'scene.placeholder.rerunTitle': 'Ejecutar de nuevo este análisis', }; diff --git a/apps/ide/test/ipcCalls.test.ts b/apps/ide/test/ipcCalls.test.ts index dac1988b..a399e29a 100644 --- a/apps/ide/test/ipcCalls.test.ts +++ b/apps/ide/test/ipcCalls.test.ts @@ -1,6 +1,7 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { createIpcCalls, newPageId } from '../src/bridge/ipcCalls.ts'; +import { ALLOWED_IPC_CHANNELS, IPC_CHANNELS, IPC_EVENTS } from '../src/shared/api.ts'; interface Sent { readonly command: string; @@ -94,3 +95,25 @@ describe('IPC call order (#497)', () => { await assert.rejects(call, /^Error: Error invoking remote method 'workspace:current': Error: Refused\.$/); }); }); + +describe('scene freshness calls and events (O10, #512)', () => { + it('are declared, allowed, and stamped like any call', async () => { + for (const channel of [IPC_CHANNELS.analysisReloadScene, IPC_CHANNELS.analysisRerunScene, IPC_CHANNELS.analysisSetFollowsChanges]) { + assert.ok(ALLOWED_IPC_CHANNELS.has(channel), channel); + } + assert.equal(IPC_EVENTS.analysisSceneUpdated, 'codexr:analysis:scene-updated'); + assert.equal(IPC_EVENTS.analysisSceneLoad, 'codexr:analysis:scene-load'); + // Events go main -> renderer only: never something the page can invoke. + assert.equal(ALLOWED_IPC_CHANNELS.has(IPC_EVENTS.analysisSceneUpdated), false); + assert.equal(ALLOWED_IPC_CHANNELS.has(IPC_EVENTS.analysisSceneLoad), false); + const tauri = fakeTauri(); + const calls = createIpcCalls(tauri.invoke, 'page'); + const reload = calls.invoke(IPC_CHANNELS.analysisReloadScene); + const follow = calls.invoke(IPC_CHANNELS.analysisSetFollowsChanges, true); + assert.deepEqual(tauri.sent.map((sent) => [sent.payload.channel, sent.payload.seq]), [[IPC_CHANNELS.analysisReloadScene, 0], [IPC_CHANNELS.analysisSetFollowsChanges, 1]]); + tauri.sent[1]?.answer(true); + tauri.sent[0]?.answer('timeout'); + assert.equal(await reload, 'timeout'); + assert.equal(await follow, true); + }); +}); diff --git a/apps/ide/test/metricDelta.test.ts b/apps/ide/test/metricDelta.test.ts index 3ff663f0..c4ca40d1 100644 --- a/apps/ide/test/metricDelta.test.ts +++ b/apps/ide/test/metricDelta.test.ts @@ -4,7 +4,8 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { readMetrics, type FileMetrics } from '../src/main/agents/tools/analysisQueries.ts'; -import { computeMetricDelta, formatMetricDelta, metricTotals, toTurnMetricDeltaView } from '../src/main/analysis/metricDelta.ts'; +import { computeMetricDelta, formatMetricDelta, freshnessOfSettle, metricTotals, pendingSummary, toTurnMetricDeltaView } from '../src/main/analysis/metricDelta.ts'; +import { metricDeltaHeadline, metricDeltaPending } from '../src/renderer/agentFirst/changesModel.ts'; /** AF9 (#274): the metric delta of an agent's turn, from two analyses' records. */ @@ -152,3 +153,52 @@ describe('metric delta as a chat keeps it (AF9)', () => { assert.equal(toTurnMetricDeltaView(computeMetricDelta(before, null)), null); }); }); + +describe('metric delta freshness (O11, #513)', () => { + it('maps how the wait for the scene ended to a freshness', () => { + assert.equal(freshnessOfSettle('settled'), 'fresh'); + assert.equal(freshnessOfSettle('no-scene'), 'fresh'); + assert.equal(freshnessOfSettle('paused'), 'paused'); + assert.equal(freshnessOfSettle('timeout'), 'timeout'); + assert.equal(freshnessOfSettle('pending'), 'timeout'); + assert.equal(freshnessOfSettle('not-following'), 'not-following'); + }); + + it('is fresh by default and says what moved', () => { + const report = computeMetricDelta(before, afterTurn, ['src/a.ts']); + assert.equal(report.freshness, 'fresh'); + assert.equal(pendingSummary('fresh'), null); + assert.equal(toTurnMetricDeltaView(report)?.freshness, undefined); + }); + + it('never says "No metric changes." on data that did not catch up', () => { + // The scene showed the dependency graph: data.json is still the one from before the turn. + const stale = computeMetricDelta(before, before, ['src/b.ts'], 'paused'); + assert.equal(stale.freshness, 'paused'); + assert.notEqual(stale.summary, 'No metric changes.'); + assert.match(stale.summary, /^Delta pending: /); + assert.match(formatMetricDelta(stale), /^Delta pending: /); + // Fresh, the same comparison is quiet (nothing moved), as before. + assert.equal(toTurnMetricDeltaView(computeMetricDelta(before, before, ['src/b.ts'])), null); + }); + + it('keeps a pending delta on the turn, without numbers, for every reason', () => { + for (const freshness of ['paused', 'timeout', 'not-following'] as const) { + const view = toTurnMetricDeltaView(computeMetricDelta(before, afterTurn, ['src/a.ts'], freshness)); + assert.ok(view); + assert.equal(view.freshness, freshness); + assert.deepEqual([view.totals, view.files, view.moreFiles], [[], [], 0]); + assert.match(metricDeltaPending(view) ?? '', /^delta pending: /); + assert.equal(metricDeltaHeadline(view), metricDeltaPending(view)); + assert.deepEqual(JSON.parse(JSON.stringify(view)), view); + } + assert.equal(metricDeltaHeadline(toTurnMetricDeltaView(computeMetricDelta(before, afterTurn, ['src/a.ts'], 'paused'))!), 'delta pending: the scene shows another analysis'); + // Without an analysis on either side there is still nothing to show. + assert.equal(toTurnMetricDeltaView(computeMetricDelta(null, afterTurn, null, 'timeout')), null); + assert.equal(toTurnMetricDeltaView(computeMetricDelta(before, null, null, 'timeout')), null); + }); + + it('reads a delta saved before freshness existed as fresh', () => { + assert.equal(metricDeltaPending({ summary: 's', totals: [], files: [], moreFiles: 0 }), null); + }); +}); diff --git a/apps/ide/test/sceneHeaderModel.test.ts b/apps/ide/test/sceneHeaderModel.test.ts index bdffefe4..cd2bc53c 100644 --- a/apps/ide/test/sceneHeaderModel.test.ts +++ b/apps/ide/test/sceneHeaderModel.test.ts @@ -1,6 +1,11 @@ -import { describe, it } from 'node:test'; +import { afterEach, describe, it } from 'node:test'; import assert from 'node:assert/strict'; -import { analysedFilesLabel, analysisKindLabel, displayAddress, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, shareControls, type ShareAction, type ShareView } from '../src/renderer/sceneHeaderModel.ts'; +import { + analysedFilesLabel, analysisKindLabel, displayAddress, elapsedLabel, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, SCENE_LOADING, SCENE_PLACEHOLDER_TIMEOUT_MS, + sceneFreshness, sceneLoadView, scenePlaceholderText, sceneStatusLabel, sceneStatusTitle, shareControls, type ShareAction, type ShareView, +} from '../src/renderer/sceneHeaderModel.ts'; +import { SCENE_LOAD_TIMEOUT_MS, type SceneUpdatedEvent } from '../src/shared/api.ts'; +import { setLocale } from '../src/shared/i18n/i18n.ts'; const PUBLIC = 'https://calm-river-42.trycloudflare.com'; @@ -101,3 +106,52 @@ describe('analysedFilesLabel (#203)', () => { }); }); + +describe('scene freshness chip (O10, #512)', () => { + afterEach(() => setLocale('en')); + const status = (overrides: Partial> = {}): Pick => ({ refresh: 'settled', mode: 'single', following: true, ...overrides }); + + it('says how fresh the scene is, most important first', () => { + assert.equal(sceneStatusLabel(sceneFreshness(status({ refresh: 'pending' }), 0, 0)), 'Updating…'); + assert.equal(sceneStatusLabel(sceneFreshness(status(), 1_000, 13_500)), 'Updated 12 s ago'); + assert.equal(sceneStatusLabel(sceneFreshness(status(), 0, 180_000)), 'Updated 3 min ago'); + assert.equal(sceneStatusLabel(sceneFreshness(status({ refresh: 'paused', mode: 'dependency-graph' }), 0, 0)), 'Paused: dependency graph shown'); + assert.equal(sceneStatusLabel(sceneFreshness(status({ refresh: 'paused', mode: 'something-new' }), 0, 0)), 'Paused: another analysis shown'); + // Not following wins over everything: nothing will refresh. + assert.equal(sceneStatusLabel(sceneFreshness(status({ refresh: 'pending', following: false }), 0, 0)), 'Not following changes'); + assert.deepEqual(sceneFreshness(status(), 5_000, 1_000), { kind: 'updated', seconds: 0 }); + }); + + it('counts elapsed time in seconds, minutes, hours and days', () => { + assert.equal(elapsedLabel(59), '59 s'); + assert.equal(elapsedLabel(60), '1 min'); + assert.equal(elapsedLabel(7_200), '2 h'); + assert.equal(elapsedLabel(3 * 86_400 + 5), '3 d'); + }); + + it('speaks Spanish too', () => { + setLocale('es'); + assert.equal(sceneStatusLabel(sceneFreshness(status({ refresh: 'paused', mode: 'dependency-graph' }), 0, 0)), 'En pausa: se muestra el grafo de dependencias'); + assert.equal(sceneStatusLabel(sceneFreshness(status(), 0, 12_000)), 'Actualizada hace 12 s'); + }); + + it('has a tooltip for every state', () => { + const states = [status({ following: false }), status({ refresh: 'paused' }), status({ refresh: 'pending' }), status()]; + for (const state of states) { + assert.notEqual(sceneStatusTitle(sceneFreshness(state, 0, 0)), ''); + } + }); +}); + +describe('scene placeholder (O10, #512)', () => { + it('loads, then shows nothing, or says the scene did not load', () => { + assert.equal(scenePlaceholderText(SCENE_LOADING), 'Loading the scene…'); + assert.deepEqual(sceneLoadView('loaded'), { kind: 'loaded' }); + assert.equal(scenePlaceholderText(sceneLoadView('loaded')), ''); + assert.equal(scenePlaceholderText(sceneLoadView('failed')), 'Scene did not load.'); + assert.equal(scenePlaceholderText(sceneLoadView('timeout')), 'Scene did not load: it took too long.'); + // The renderer's backstop never fires before the main process's own timeout (a cold WebKitGTK takes up to 35 s). + assert.ok(SCENE_PLACEHOLDER_TIMEOUT_MS > SCENE_LOAD_TIMEOUT_MS); + assert.ok(SCENE_LOAD_TIMEOUT_MS >= 40_000); + }); +}); diff --git a/apps/ide/test/sceneRefresh.test.ts b/apps/ide/test/sceneRefresh.test.ts index f692ba8b..88d2bb60 100644 --- a/apps/ide/test/sceneRefresh.test.ts +++ b/apps/ide/test/sceneRefresh.test.ts @@ -1,6 +1,6 @@ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; -import { followRefreshes, refreshState, waitUntilSettled, type RefreshPort, type RefreshView } from '../src/main/analysis/sceneRefresh.ts'; +import { followRefreshes, followRefreshStatus, loadWithin, refreshState, refreshStatus, waitUntilSettled, type RefreshPort, type RefreshView } from '../src/main/analysis/sceneRefresh.ts'; /** AF8/AF9: reading the core's refresh coordinator for an open scene. */ @@ -72,3 +72,29 @@ describe('scene refresh state', () => { assert.deepEqual(seen, [4, 6]); }); }); + +describe('scene refresh status for the header (O10, #512)', () => { + it('reports the opening status, then only changes of revision, state or mode', () => { + const port = fakePort(view()); + const seen: string[] = []; + const stop = followRefreshStatus(port, (status, previous) => { + seen.push(`${previous ? 'change' : 'open'} ${status.revision} ${status.refresh} ${status.mode}`); + }); + port.set(view({ sourceRevision: 1, status: 'updating' })); + port.set(view({ sourceRevision: 1, status: 'updating' })); + port.set(view({ sourceRevision: 1, appliedRevision: { single: 1 }, modeRevision: { single: 1 } })); + port.set(view({ mode: 'dependency-graph', sourceRevision: 1, appliedRevision: { single: 1 }, modeRevision: { single: 1 } })); + stop(); + port.set(view({ sourceRevision: 5, status: 'updating' })); + assert.deepEqual(seen, ['open 0 settled single', 'change 0 pending single', 'change 1 settled single', 'change 1 paused dependency-graph']); + assert.equal(refreshStatus(view({ modeRevision: { single: 3 } })).revision, 3); + }); +}); + +describe('scene load with a timeout (O10, #512)', () => { + it('says loaded, failed, or timeout when the load never finishes', async () => { + assert.equal(await loadWithin(Promise.resolve(), 1_000), 'loaded'); + assert.equal(await loadWithin(Promise.reject(new Error('refused')), 1_000), 'failed'); + assert.equal(await loadWithin(new Promise(() => undefined), 20), 'timeout'); + }); +}); From 7ae06fae3bf697a739388d37768f947fd14bb311 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:23:59 +0000 Subject: [PATCH 13/74] fix(ide): reveal the scene when its load times out instead of hiding it (#512) --- apps/ide/src/renderer/scenePanel.ts | 8 +++++++- apps/ide/src/shared/i18n/messages.en.ts | 1 + apps/ide/src/shared/i18n/messages.es.ts | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/ide/src/renderer/scenePanel.ts b/apps/ide/src/renderer/scenePanel.ts index 62145333..36e5890b 100644 --- a/apps/ide/src/renderer/scenePanel.ts +++ b/apps/ide/src/renderer/scenePanel.ts @@ -96,7 +96,10 @@ export function createScenePanel( frame = requestAnimationFrame(() => { const rect = slot.getBoundingClientRect(); // O10: the native view stays hidden until its page loaded, so the placeholder shows. - const visible = open && !suspended && load.kind === 'loaded' && rect.width > 0 && rect.height > 0; + // A timeout reveals it anyway: the page may have loaded without the engine saying so, + // and a working scene must never stay hidden behind the placeholder. + const revealed = load.kind === 'loaded' || (load.kind === 'failed' && load.state === 'timeout'); + const visible = open && !suspended && revealed && rect.width > 0 && rect.height > 0; api.setSceneBounds(visible ? { x: rect.left, y: rect.top, width: rect.width, height: rect.height } : null) .catch((reason: unknown) => callbacks.onError(`Could not place the scene: ${String(reason)}`)); }); @@ -242,6 +245,9 @@ export function createScenePanel( }, SCENE_PLACEHOLDER_TIMEOUT_MS); } placeholder.hidden = next.kind === 'loaded'; + if (next.kind === 'failed' && next.state === 'timeout') { + callbacks.onError(t('scene.placeholder.timeoutRevealed')); + } placeholderText.textContent = scenePlaceholderText(next); placeholderActions.hidden = next.kind !== 'failed'; reload.disabled = false; diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 44cdd031..6b6ff8c9 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -763,6 +763,7 @@ export const en = { 'scene.placeholder.loading': 'Loading the scene…', 'scene.placeholder.failed': 'Scene did not load.', 'scene.placeholder.timeout': 'Scene did not load: it took too long.', + 'scene.placeholder.timeoutRevealed': 'The scene took too long to report that it loaded. It is shown anyway; if it stays blank, close the scene and run the analysis again.', 'scene.placeholder.reload': 'Reload', 'scene.placeholder.reloadTitle': 'Load the scene again from its server', 'scene.placeholder.rerun': 'Run again', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 456ff7e0..358fdd75 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -766,6 +766,7 @@ export const es: Readonly> = { 'scene.placeholder.loading': 'Cargando la escena...', 'scene.placeholder.failed': 'La escena no se cargó.', 'scene.placeholder.timeout': 'La escena no se cargó: tardó demasiado.', + 'scene.placeholder.timeoutRevealed': 'La escena tardó demasiado en avisar de que había cargado. Se muestra de todos modos; si sigue en blanco, cierra la escena y vuelve a ejecutar el análisis.', 'scene.placeholder.reload': 'Recargar', 'scene.placeholder.reloadTitle': 'Cargar de nuevo la escena desde su servidor', 'scene.placeholder.rerun': 'Ejecutar de nuevo', From 6b781f877841d8dd410545c1fdc1f090401d97f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:27:18 +0000 Subject: [PATCH 14/74] perf(ide): wait on DOM mutations and frames in the start-up bench, keep the main window unthrottled (#517) --- apps/ide/scripts/bench.mjs | 3 +- apps/ide/scripts/benchCompare.mjs | 1 + apps/ide/src-tauri/src/host.rs | 7 ++ apps/ide/src/renderer/bench/benchDriver.ts | 36 ++++---- apps/ide/src/renderer/bench/waitFor.ts | 53 +++++++++++ apps/ide/src/renderer/startup/startupMarks.ts | 5 + apps/ide/src/shared/api.ts | 2 + apps/ide/test/benchWait.test.ts | 92 +++++++++++++++++++ 8 files changed, 181 insertions(+), 18 deletions(-) create mode 100644 apps/ide/src/renderer/bench/waitFor.ts create mode 100644 apps/ide/test/benchWait.test.ts diff --git a/apps/ide/scripts/bench.mjs b/apps/ide/scripts/bench.mjs index 282f888b..2d15b601 100644 --- a/apps/ide/scripts/bench.mjs +++ b/apps/ide/scripts/bench.mjs @@ -211,7 +211,7 @@ async function oneRun(index) { idleCpuPct: Math.round(idleCpuPct * 100) / 100, byProcess: settled.map((p) => ({ name: p.name, pssMB: mb(p.pss), rssMB: mb(p.rss), privateMB: mb(p.priv) })), }; - console.error(`[bench] run ${index}: ready ${run.readyMs} ms, ${run.processes} processes, PSS ${run.pssMB} MB, RSS ${run.rssMB} MB, private ${run.privateMB} MB, idle CPU ${run.idleCpuPct}%, page: explorer/editor/terminal at ${Math.round(report.workbenchReadyMs)}/${Math.round(report.editorReadyMs)}/${Math.round(report.terminalReadyMs)} ms${report.visibility ? ` (${report.visibility})` : ''}${report.resources ? `, slowest: ${report.resources}` : ''}${report.jsLoopMs !== undefined ? `, JS loop ${report.jsLoopMs} ms, ${report.framesPerSecond} frames/s, timer(0) ${report.timerDelayMs} ms, IPC ${report.ipcRoundTripMs} ms, asset ${report.assetFetchMs} ms` : ''}${report.failures.length ? `, failures: ${report.failures.join('; ')}` : ''}`); + console.error(`[bench] run ${index}: ready ${run.readyMs} ms, ${run.processes} processes, PSS ${run.pssMB} MB, RSS ${run.rssMB} MB, private ${run.privateMB} MB, idle CPU ${run.idleCpuPct}%, page: explorer/editor/terminal at ${Math.round(report.workbenchReadyMs)}/${Math.round(report.editorReadyMs)}/${Math.round(report.terminalReadyMs)} ms${report.editorFirstViewLineMs !== undefined ? ` (editor first line at ${Math.round(report.editorFirstViewLineMs)} ms)` : ''}${report.visibility ? ` (${report.visibility})` : ''}${report.resources ? `, slowest: ${report.resources}` : ''}${report.jsLoopMs !== undefined ? `, JS loop ${report.jsLoopMs} ms, ${report.framesPerSecond} frames/s, timer(0) ${report.timerDelayMs} ms, IPC ${report.ipcRoundTripMs} ms, asset ${report.assetFetchMs} ms` : ''}${report.failures.length ? `, failures: ${report.failures.join('; ')}` : ''}`); // #499: where the page's start-up went (src/renderer/startup/startupMarks.ts). if (report.startup) { console.error(`[bench] run ${index} timeline: ${report.startup}`); @@ -245,6 +245,7 @@ const summary = { readyMs: pick((r) => r.readyMs), workbenchReadyMs: pick((r) => r.renderer.workbenchReadyMs), editorReadyMs: pick((r) => r.renderer.editorReadyMs), + editorFirstViewLineMs: pick((r) => r.renderer.editorFirstViewLineMs ?? -1), terminalReadyMs: pick((r) => r.renderer.terminalReadyMs), startupCpuMs: pick((r) => r.startupCpuMs), processes: pick((r) => r.processes), diff --git a/apps/ide/scripts/benchCompare.mjs b/apps/ide/scripts/benchCompare.mjs index 275d0212..0f9cbe5e 100644 --- a/apps/ide/scripts/benchCompare.mjs +++ b/apps/ide/scripts/benchCompare.mjs @@ -95,6 +95,7 @@ const METRICS = [ ['Spawn to usable (ms)', (r) => r.readyMs], ['Page: explorer ready (ms)', (r) => r.renderer.workbenchReadyMs], ['Page: editor ready (ms)', (r) => r.renderer.editorReadyMs], + ['Page: editor first line drawn (ms)', (r) => r.renderer.editorFirstViewLineMs ?? -1], ['Page: terminal ready (ms)', (r) => r.renderer.terminalReadyMs], ['CPU time to usable (ms)', (r) => r.startupCpuMs], ['Memory PSS (MB, Linux)', (r) => r.pssMB], diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index 58c3f4f1..6c8724dc 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -427,6 +427,13 @@ fn build_window(app: &AppHandle, shell: &Arc, sidecar: &Arc, spe if crate::smoke::is_smoke_run() { builder = builder.data_directory(crate::smoke::webview_data_dir()); } + // #517: the main window's timers and tasks are never suspended or throttled when it is + // hidden, occluded or behind another app (WKWebView on macOS 14+; a no-op elsewhere): + // the editor, the terminal and the chats keep running, and the macOS start-up bench + // measures the IDE rather than WebKit's throttling of a window that is not key. + if spec.label == MAIN_WINDOW { + builder = builder.background_throttling(tauri::utils::config::BackgroundThrottlingPolicy::Disabled); + } crate::trace(format_args!("building window {}", spec.label)); let window = builder.build().map_err(|error| error.to_string())?; crate::trace(format_args!("built window {}", spec.label)); diff --git a/apps/ide/src/renderer/bench/benchDriver.ts b/apps/ide/src/renderer/bench/benchDriver.ts index 1f6e5254..0ee523b8 100644 --- a/apps/ide/src/renderer/bench/benchDriver.ts +++ b/apps/ide/src/renderer/bench/benchDriver.ts @@ -1,5 +1,6 @@ import type { BenchReport, CodeXRApi } from '../../shared/api.ts'; -import { startupStep, startupTimeline } from '../startup/startupMarks.ts'; +import { startupMarkTime, startupStep, startupTimeline } from '../startup/startupMarks.ts'; +import { waitFor, type WaitHost } from './waitFor.ts'; /** * The renderer half of a benchmark run (`--codexr-bench`, query `bench=1`). @@ -30,7 +31,7 @@ async function runBench(hooks: BenchHooks): Promise { const visibility = (): string => `${document.visibilityState}${document.hasFocus() ? '+focus' : ''}`; const visibleAtStart = visibility(); const step = async (name: string, ready: () => boolean): Promise => { - if (await waitFor(ready)) { + if (await waitFor(ready, STEP_TIMEOUT_MS, browserWaitHost())) { return performance.now(); } failures.push(`${name} not ready after ${STEP_TIMEOUT_MS / 1000}s`); @@ -57,25 +58,26 @@ async function runBench(hooks: BenchHooks): Promise { const timerDelayMs = await timerDelay(20); const ipcRoundTripMs = await meanMs(20, () => hooks.api.app.getInfo()); const assetFetchMs = await meanMs(10, () => fetch(new URL('index.html', window.location.href)).then((response) => response.text())); - const report: BenchReport = { workbenchReadyMs, editorReadyMs, terminalReadyMs, failures, visibility: `${visibleAtStart} -> ${visibility()}`, resources: slowestResources(), jsLoopMs: timeJsLoop(), framesPerSecond, timerDelayMs, ipcRoundTripMs, assetFetchMs, diagnosticsMs: 0, startup }; + // #517: when Monaco drew its first line, whatever the step's own wait added (editorGroup.ts). + const editorFirstViewLineMs = startupMarkTime('editor-first-view-line') ?? -1; + const report: BenchReport = { workbenchReadyMs, editorReadyMs, editorFirstViewLineMs, terminalReadyMs, failures, visibility: `${visibleAtStart} -> ${visibility()}`, resources: slowestResources(), jsLoopMs: timeJsLoop(), framesPerSecond, timerDelayMs, ipcRoundTripMs, assetFetchMs, diagnosticsMs: 0, startup }; const withDiagnostics: BenchReport = { ...report, diagnosticsMs: Math.round(performance.now() - diagnosticsStarted) }; await hooks.api.app.benchReport(withDiagnostics); } -function waitFor(ready: () => boolean): Promise { - const started = performance.now(); - return new Promise((resolve) => { - const poll = (): void => { - if (ready()) { - resolve(true); - } else if (performance.now() - started > STEP_TIMEOUT_MS) { - resolve(false); - } else { - window.setTimeout(poll, 16); - } - }; - poll(); - }); +/** #517: the page's own wait host (bench/waitFor.ts): a MutationObserver over the whole document. */ +function browserWaitHost(): WaitHost { + return { + observe(onChange) { + const observer = new MutationObserver(onChange); + observer.observe(document, { childList: true, subtree: true, attributes: true, characterData: true }); + return () => observer.disconnect(); + }, + requestAnimationFrame: (run) => window.requestAnimationFrame(run), + cancelAnimationFrame: (handle) => window.cancelAnimationFrame(handle), + setTimeout: (run, ms) => window.setTimeout(run, ms), + clearTimeout: (handle) => window.clearTimeout(handle), + }; } function slowestResources(): string { diff --git a/apps/ide/src/renderer/bench/waitFor.ts b/apps/ide/src/renderer/bench/waitFor.ts new file mode 100644 index 00000000..03ec36e0 --- /dev/null +++ b/apps/ide/src/renderer/bench/waitFor.ts @@ -0,0 +1,53 @@ +/** + * #517: how the benchmark waits for a step. It used to poll on a 16 ms timer, + * and WebKit on macOS throttles nested timers: the CI timelines show gaps of + * 1,041-1,150 ms between polls while the page kept drawing frames, so the + * editor step was recorded up to ~785 ms after Monaco had drawn its first line. + * Now the condition is checked on every DOM mutation and every animation frame + * (neither is throttled in a visible page), with a single timer for the + * timeout. A page that draws nothing and changes nothing has nothing to report. + */ +export interface WaitHost { + /** Calls `onChange` on any change under the document; returns the disconnect. */ + observe(onChange: () => void): () => void; + requestAnimationFrame(run: () => void): number; + cancelAnimationFrame(handle: number): void; + setTimeout(run: () => void, ms: number): number; + clearTimeout(handle: number): void; +} + +export function waitFor(ready: () => boolean, timeoutMs: number, host: WaitHost): Promise { + if (ready()) { + return Promise.resolve(true); + } + return new Promise((resolve) => { + let done = false; + let frame = 0; + let timer = 0; + let disconnect = (): void => undefined; + const finish = (result: boolean): void => { + if (done) { + return; + } + done = true; + disconnect(); + host.cancelAnimationFrame(frame); + host.clearTimeout(timer); + resolve(result); + }; + const check = (): void => { + if (!done && ready()) { + finish(true); + } + }; + const onFrame = (): void => { + check(); + if (!done) { + frame = host.requestAnimationFrame(onFrame); + } + }; + disconnect = host.observe(check); + frame = host.requestAnimationFrame(onFrame); + timer = host.setTimeout(() => finish(ready()), timeoutMs); + }); +} diff --git a/apps/ide/src/renderer/startup/startupMarks.ts b/apps/ide/src/renderer/startup/startupMarks.ts index e5b11acc..5d2e78ca 100644 --- a/apps/ide/src/renderer/startup/startupMarks.ts +++ b/apps/ide/src/renderer/startup/startupMarks.ts @@ -49,6 +49,11 @@ export function startupMarkFrame(name: string): void { setTimeout(() => startupMark(`${name}+task`), 0); } +/** #517: when a mark was first set (`performance.now()` clock), or undefined. */ +export function startupMarkTime(name: string): number | undefined { + return performance.getEntriesByName(`${STARTUP_MARK_PREFIX}${name}`, 'mark')[0]?.startTime; +} + /** A step at a time measured by the caller (`performance.now()` clock). */ export function startupStep(name: string, at: number): void { extraSteps.push([name, at]); diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index c951558a..769066db 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -35,6 +35,8 @@ export interface BenchReport { readonly workbenchReadyMs: number; /** A file clicked in the explorer is drawn in a Monaco tab. */ readonly editorReadyMs: number; + /** #517: when Monaco drew its first line (the `editor-first-view-line` mark), -1 if never: what editorReadyMs would be with no wait of its own. */ + readonly editorFirstViewLineMs?: number; /** The terminal panel ran a command and drew its output. */ readonly terminalReadyMs: number; readonly failures: readonly string[]; diff --git a/apps/ide/test/benchWait.test.ts b/apps/ide/test/benchWait.test.ts new file mode 100644 index 00000000..9c6a09e5 --- /dev/null +++ b/apps/ide/test/benchWait.test.ts @@ -0,0 +1,92 @@ +// #517: the benchmark's wait for a step: DOM mutations and animation frames, one timeout timer. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { waitFor, type WaitHost } from '../src/renderer/bench/waitFor.ts'; + +const IDE_ROOT = path.resolve(import.meta.dirname, '..'); + +function fakeHost(): WaitHost & { mutate(): void; frame(): void; fireTimeout(): void; timers: number[]; observers: number; frames: Map void>; cleared: number[] } { + let observer: (() => void) | null = null; + let next = 1; + const frames = new Map void>(); + const timeouts = new Map void>(); + const host = { + timers: [] as number[], + observers: 0, + frames, + cleared: [] as number[], + observe(onChange: () => void) { + observer = onChange; + host.observers += 1; + return () => { observer = null; host.observers -= 1; }; + }, + requestAnimationFrame(run: () => void) { const id = next++; frames.set(id, run); return id; }, + cancelAnimationFrame(id: number) { frames.delete(id); }, + setTimeout(run: () => void, ms: number) { const id = next++; timeouts.set(id, run); host.timers.push(ms); return id; }, + clearTimeout(id: number) { timeouts.delete(id); host.cleared.push(id); }, + mutate() { observer?.(); }, + frame() { const pending = [...frames.entries()]; frames.clear(); for (const [, run] of pending) {run();} }, + fireTimeout() { for (const [id, run] of [...timeouts]) { timeouts.delete(id); run(); } }, + }; + return host; +} + +describe('Benchmark wait (#517)', () => { + it('answers at once when the step is already done, with no observer or timer', async () => { + const host = fakeHost(); + assert.equal(await waitFor(() => true, 1000, host), true); + assert.equal(host.observers, 0); + assert.deepEqual(host.timers, []); + }); + + it('answers on the DOM change that makes the step ready, and cleans up', async () => { + const host = fakeHost(); + let ready = false; + const waiting = waitFor(() => ready, 60_000, host); + assert.deepEqual(host.timers, [60_000], 'one timer: the timeout, never a polling loop'); + host.mutate(); + ready = true; + host.mutate(); + assert.equal(await waiting, true); + assert.equal(host.observers, 0, 'observer disconnected'); + assert.equal(host.frames.size, 0, 'no frame left pending'); + assert.equal(host.cleared.length, 1, 'timeout cleared'); + }); + + it('answers on an animation frame when nothing in the DOM changed', async () => { + const host = fakeHost(); + let ready = false; + const waiting = waitFor(() => ready, 60_000, host); + host.frame(); + host.frame(); + assert.equal(host.frames.size, 1, 'checks again on every frame'); + ready = true; + host.frame(); + assert.equal(await waiting, true); + assert.equal(host.timers.length, 1); + }); + + it('gives up at the timeout, and never answers twice', async () => { + const host = fakeHost(); + let ready = false; + let answers = 0; + const waiting = waitFor(() => ready, 500, host).then((result) => { answers += 1; return result; }); + host.fireTimeout(); + ready = true; + host.mutate(); + host.frame(); + assert.equal(await waiting, false); + assert.equal(answers, 1); + assert.equal(host.observers, 0); + }); + + it('is what the bench driver waits with, and reports the first line Monaco drew', () => { + const driver = fs.readFileSync(path.join(IDE_ROOT, 'src/renderer/bench/benchDriver.ts'), 'utf8'); + assert.doesNotMatch(driver, /setTimeout\(poll/); + assert.match(driver, /waitFor\(ready, STEP_TIMEOUT_MS, browserWaitHost\(\)\)/); + assert.match(driver, /editorFirstViewLineMs = startupMarkTime\('editor-first-view-line'\)/); + assert.match(fs.readFileSync(path.join(IDE_ROOT, 'src-tauri/src/host.rs'), 'utf8'), /spec\.label == MAIN_WINDOW \{\s*builder = builder\.background_throttling\(tauri::utils::config::BackgroundThrottlingPolicy::Disabled\)/); + }); +}); From fb72d7b9e3871e596eee94647a38aca256970084 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:27:18 +0000 Subject: [PATCH 15/74] perf(ide): load the Markdown preview, extension language support, QR code, launch animation and tour on demand (#518) --- apps/ide/src/renderer/codexr/sceneSection.ts | 4 +- apps/ide/src/renderer/editor/editorGroup.ts | 12 ++- .../renderer/editor/lazyMarkdownPreview.ts | 74 ++++++++++++++++++ .../renderer/extensions/extensionsWiring.ts | 78 +++++++++++-------- .../src/renderer/extensions/languageModel.ts | 13 +++- apps/ide/src/renderer/main.ts | 6 +- apps/ide/src/renderer/sceneQr.ts | 26 +++++++ apps/ide/src/renderer/sceneXrControls.ts | 27 +------ .../src/renderer/startup/launchController.ts | 77 ++++++++++++------ apps/ide/src/renderer/startup/launchGate.ts | 22 ++++++ apps/ide/src/renderer/startup/launchModel.ts | 20 +---- apps/ide/src/renderer/tour/lazyTour.ts | 51 ++++++++++++ apps/ide/src/shared/i18n/messages.en.ts | 2 + apps/ide/src/shared/i18n/messages.es.ts | 1 + apps/ide/test/startupLazyChunks.test.ts | 68 ++++++++++++++++ 15 files changed, 374 insertions(+), 107 deletions(-) create mode 100644 apps/ide/src/renderer/editor/lazyMarkdownPreview.ts create mode 100644 apps/ide/src/renderer/sceneQr.ts create mode 100644 apps/ide/src/renderer/startup/launchGate.ts create mode 100644 apps/ide/src/renderer/tour/lazyTour.ts create mode 100644 apps/ide/test/startupLazyChunks.test.ts diff --git a/apps/ide/src/renderer/codexr/sceneSection.ts b/apps/ide/src/renderer/codexr/sceneSection.ts index a712de1e..9d859e72 100644 --- a/apps/ide/src/renderer/codexr/sceneSection.ts +++ b/apps/ide/src/renderer/codexr/sceneSection.ts @@ -3,7 +3,6 @@ import type { CodeXRApi, SceneInfo } from '../../shared/api.ts'; import type { CodeXrViewApi, SceneModes } from '../../shared/codexr.ts'; import { el } from '../dom.ts'; import { analysedFilesLabel, analysisKindLabel, displayAddress, enterXrNote, enterXrState, INITIAL_SHARE_VIEW, ipcErrorMessage, reduceShare, shareControls, type ShareAction, type ShareView } from '../sceneHeaderModel.ts'; -import { qrSvg } from '../sceneXrControls.ts'; import type { CodeXrSection } from './codexrView.ts'; import { modeLabel, modePicker, withActive } from './sceneModel.ts'; @@ -146,7 +145,8 @@ export function createSceneSection( return; } const asked = ++headsetRequest; - api.analysis.headsetLink().then((link) => { + // #518: the QR encoder loads with the first headset panel (sceneQr.ts). + Promise.all([api.analysis.headsetLink(), import('../sceneQr.ts')]).then(([link, { qrSvg }]) => { if (asked !== headsetRequest) { return; } diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index e60c4d02..9e01ef06 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -9,7 +9,8 @@ import { installMetricLens } from './metricLens.ts'; import { installGitDecorations, type GitDecorationsHooks } from './gitDecorations.ts'; import { installDebugDecorations, type DebugDecorationsHooks } from './debugDecorations.ts'; import { installAnalysisEditorMenu, type AnalysisEditorMenuHooks } from './analysisEditorMenu.ts'; -import { createMarkdownPreview, type MarkdownPreview } from './markdownPreview.ts'; +import { lazyMarkdownPreview } from './lazyMarkdownPreview.ts'; +import type { MarkdownPreview } from './markdownPreview.ts'; import { isMarkdownPath } from './markdownPath.ts'; import { applyTextEdits, type FileTextEdits, type WorkspaceEditOutcome } from '../lsp/lspEdits.ts'; import type { CustomEditorContext, CustomEditorInput, CustomEditorResolver, CustomEditorView } from './customEditor.ts'; @@ -1444,7 +1445,7 @@ export function createEditorGroup( /** #253: the view of a Markdown preview tab: the open file's live text, else the file on disk. */ function markdownPreviewTab(path: string, context: CustomEditorContext): CustomEditorView { - const view = createMarkdownPreview({ + const view = lazyMarkdownPreview({ readImage: (image) => api.readImage(image), openExternalLink: (url) => api.openExternalLink(url), openFile: (target) => void openIn(current, target), @@ -1477,7 +1478,10 @@ export function createEditorGroup( }; void follow(); return { - element: view.element, + // #518: a getter, the preview's module loads on first use (lazyMarkdownPreview.ts). + get element() { + return view.element; + }, onShow: () => void follow(), fileChanged: () => { if (!subscription) { void follow(); } }, dispose: () => { @@ -1494,7 +1498,7 @@ export function createEditorGroup( return false; } if (!preview) { - preview = createMarkdownPreview({ + preview = lazyMarkdownPreview({ readImage: (path) => api.readImage(path), openExternalLink: (url) => api.openExternalLink(url), openFile: (path) => void openIn(current, path), diff --git a/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts b/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts new file mode 100644 index 00000000..d98dab1d --- /dev/null +++ b/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts @@ -0,0 +1,74 @@ +import { t } from '../../shared/i18n/i18n.ts'; +import { el } from '../dom.ts'; +import type { MarkdownPreview, MarkdownPreviewHost } from './markdownPreview.ts'; + +type PreviewModule = { createMarkdownPreview(host: MarkdownPreviewHost): MarkdownPreview }; + +/** + * #518: the Markdown preview (marked, DOMPurify and the renderer of + * markdownPreview.ts) loads on the first preview, not with the editor groups, + * which every first file open waits for. Until it arrives a holder stands in + * for it, with the same classes and size (the side pane's `style.flex`, a + * tab's `is-tab`), and keeps the last file, text and line asked for; the real + * preview then takes the holder's place in the document. `element` is a + * getter: it is the holder, then the preview. + */ +export function lazyMarkdownPreview(host: MarkdownPreviewHost, load: () => Promise = () => import('./markdownPreview.ts')): MarkdownPreview { + const holder = el('section', { className: 'markdown-preview', attrs: { 'aria-label': 'Markdown preview', 'aria-busy': 'true', 'data-testid': 'markdown-preview-loading' } }); + let real: MarkdownPreview | null = null; + let shown: { path: string; text: string } | null = null; + let line: number | null = null; + let disposed = false; + load().then((module) => { + if (disposed) { + return; + } + const preview = module.createMarkdownPreview(host); + real = preview; + preview.element.classList.add(...holder.classList); + if (holder.style.flex) { + preview.element.style.flex = holder.style.flex; + } + holder.replaceWith(preview.element); + if (shown) { + preview.show(shown.path, shown.text); + } + if (line !== null) { + preview.scrollToLine(line); + } + }).catch((error: unknown) => { + holder.removeAttribute('aria-busy'); + holder.replaceChildren(el('div', { className: 'viewer-message muted', text: t('markdownPreview.failed', { error: error instanceof Error ? error.message : String(error) }) })); + }); + return { + get element() { + return real?.element ?? holder; + }, + path: () => (real ? real.path() : shown?.path ?? null), + show(path, text) { + if (real) { + real.show(path, text); + } else { + shown = { path, text }; + } + }, + update(text) { + if (real) { + real.update(text); + } else if (shown) { + shown = { ...shown, text }; + } + }, + scrollToLine(next) { + if (real) { + real.scrollToLine(next); + } else { + line = next; + } + }, + dispose() { + disposed = true; + real?.dispose(); + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/extensionsWiring.ts b/apps/ide/src/renderer/extensions/extensionsWiring.ts index 038fa967..f25b5028 100644 --- a/apps/ide/src/renderer/extensions/extensionsWiring.ts +++ b/apps/ide/src/renderer/extensions/extensionsWiring.ts @@ -8,6 +8,7 @@ import { createContributionsController, type ContributionsController } from './c import { createExtensionsView, type ExtensionsView } from './extensionsView.ts'; import { ContextKeys } from './contextKeys.ts'; import { createHostBridge } from './hostBridge.ts'; +import { needsEditorLanguages } from './languageModel.ts'; import { fileUriOf, type MenuGroup } from './menuModel.ts'; import { createViewsController, type ViewsWorkbench } from './viewsController.ts'; import { createWebviewHost } from './webviewHost.ts'; @@ -204,10 +205,12 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork api.extensions.onDidChange((event) => { installed = event.installed; view.setInstalled(event.installed); + startLanguages(); void refresh(); }); void api.extensions.list().then((list) => { installed = list; + startLanguages(); return refresh(); }).catch((error: unknown) => deps.notify('error', `Could not list the extensions: ${String(error)}`)); const firedLanguages = new Set(); @@ -219,6 +222,48 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork }; api.extensions.onDidChange(() => firedLanguages.clear()); + /** + * #259, #260: onLanguage: events, the document sync, the language bridge and the + * editor menus. #518: loaded once Monaco is (watchEditorLanguages) and an extension + * needs them (needsEditorLanguages), so a window with none loads none of it. + */ + let editorLoaded = false; + let languagesStarted = false; + function startLanguages(): void { + if (!editorLoaded || languagesStarted || !needsEditorLanguages(installed)) { + return; + } + languagesStarted = true; + void import('./monacoContributions.ts').then((part) => part.watchModelLanguages(fireLanguage)); + void Promise.all([import('./documentSync.ts'), import('./languageBridge.ts'), import('./editorMenus.ts')]).then(([syncModule, bridgeModule, menusModule]) => { + if (languages) { + return; + } + const sync = syncModule.installDocumentSync(api.extensions); + // #261: the extensions' entries in the editor's context menu. + menusModule.installEditorMenus({ + contextKeys, + menu: (menu, extra) => views.menu(menu, extra), + pathOf: (model) => sync.pathOf(model), + run: (command, path) => void api.workspace.current().then((workspace) => runCommand(command, workspace ? [{ $uri: fileUriOf(workspace.root, path) }] : [])), + }); + const languageBridge = bridgeModule.createLanguageBridge({ + extensions: api.extensions, + sync, + openFile: deps.openFile, + saveFile: deps.saveFile, + runCommand: (id, args) => { + api.extensions.executeCommand(id, args).catch((error: unknown) => deps.notify('error', `Command '${id}' failed: ${error instanceof Error ? error.message : String(error)}`)); + }, + }); + languages = { bridge: languageBridge, sync }; + for (const notification of earlyNotifications.splice(0)) { + languageNotification(notification, languageBridge); + } + languagesReady(languages); + }).catch((error: unknown) => deps.notify('error', `Extensions' language features could not start: ${String(error)}`)); + } + const commands = [ { id: 'extensions.showView', category: 'Extensions', title: 'Show Extensions', run: () => { deps.showView(); view.focusSearch(); } }, { id: 'extensions.installVsix', category: 'Extensions', title: 'Install from VSIX…', run: () => { deps.showView(); void view.installVsix(); } }, @@ -241,37 +286,8 @@ export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWork contributions, themes: () => contributions.current().themes, watchEditorLanguages() { - void import('./monacoContributions.ts').then((part) => part.watchModelLanguages(fireLanguage)); - if (languages) { - return; - } - void Promise.all([import('./documentSync.ts'), import('./languageBridge.ts'), import('./editorMenus.ts')]).then(([syncModule, bridgeModule, menusModule]) => { - if (languages) { - return; - } - const sync = syncModule.installDocumentSync(api.extensions); - // #261: the extensions' entries in the editor's context menu. - menusModule.installEditorMenus({ - contextKeys, - menu: (menu, extra) => views.menu(menu, extra), - pathOf: (model) => sync.pathOf(model), - run: (command, path) => void api.workspace.current().then((workspace) => runCommand(command, workspace ? [{ $uri: fileUriOf(workspace.root, path) }] : [])), - }); - const languageBridge = bridgeModule.createLanguageBridge({ - extensions: api.extensions, - sync, - openFile: deps.openFile, - saveFile: deps.saveFile, - runCommand: (id, args) => { - api.extensions.executeCommand(id, args).catch((error: unknown) => deps.notify('error', `Command '${id}' failed: ${error instanceof Error ? error.message : String(error)}`)); - }, - }); - languages = { bridge: languageBridge, sync }; - for (const notification of earlyNotifications.splice(0)) { - languageNotification(notification, languageBridge); - } - languagesReady(languages); - }).catch((error: unknown) => deps.notify('error', `Extensions' language features could not start: ${String(error)}`)); + editorLoaded = true; + startLanguages(); }, documentSaved(path) { languages?.sync.saved(path); diff --git a/apps/ide/src/renderer/extensions/languageModel.ts b/apps/ide/src/renderer/extensions/languageModel.ts index eb079b74..175e3bfe 100644 --- a/apps/ide/src/renderer/extensions/languageModel.ts +++ b/apps/ide/src/renderer/extensions/languageModel.ts @@ -1,4 +1,4 @@ -import type { ContributedLanguage, ContributedSnippet } from '../../shared/extensions.ts'; +import type { ContributedLanguage, ContributedSnippet, InstalledExtension } from '../../shared/extensions.ts'; /** * Languages contributed by extensions (#258), as Monaco takes them: the @@ -201,3 +201,14 @@ function globToRegExp(glob: string): RegExp { export function snippetsFor(snippets: readonly ContributedSnippet[], languageId: string): ContributedSnippet[] { return snippets.filter((snippet) => snippet.language === languageId || snippet.language === '*'); } + +/** + * #518: whether the editor needs the extensions' language side (onLanguage: + * activation, the document sync with the extension host, the language bridge, + * the editor menus): only once an enabled extension has code to run, or + * contributes languages or grammars. With none, a first file open loads none of it. + */ +export function needsEditorLanguages(installed: readonly Pick[]): boolean { + return installed.some((extension) => extension.state === 'enabled' + && (extension.hasCode || extension.contributes.languages.length > 0 || extension.contributes.grammars > 0)); +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index cf725f0f..5d099f11 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -10,7 +10,7 @@ import { createAnalysisRunView } from './analysisRunView.ts'; import { analysisMenuItems, paletteTarget } from './analysisMenu.ts'; import type { AnalysisSubject } from '../shared/analysisKinds.ts'; import { createStartupAnimation } from './startup/launchController.ts'; -import { createGuidedTour } from './tour/tourView.ts'; +import { lazyGuidedTour } from './tour/lazyTour.ts'; import { shouldAutoStartTour, TOUR_DONE_KEY, TOUR_SETTING, TOUR_SETTLE_MS } from './tour/tourModel.ts'; import codeXrLogoUrl from '../../../vscode-extension/resources/icon.svg?url'; import { createScenePanel } from './scenePanel.ts'; @@ -1449,7 +1449,7 @@ const startupAnimation = createStartupAnimation({ // CI12 (#404): the welcome card and the guided tour. On the first launch it // opens once the window has settled, after the launch animation if one plays; // an animation that starts while it is open puts it aside until it ends. -const guidedTour = createGuidedTour({ +const guidedTour = lazyGuidedTour({ platform: () => platform, logoUrl: codeXrLogoUrl, currentView: () => workbench.currentView, @@ -1464,7 +1464,7 @@ const guidedTour = createGuidedTour({ // Without storage the welcome may show again; nothing else depends on it. } }, -}); +}, () => import('./tour/tourView.ts')); // #518: loaded when it first opens startupAnimation.onDidStart(() => { guidedTour.hold(); startupAnimation.afterAnimation(() => guidedTour.release()); diff --git a/apps/ide/src/renderer/sceneQr.ts b/apps/ide/src/renderer/sceneQr.ts new file mode 100644 index 00000000..5e10abb3 --- /dev/null +++ b/apps/ide/src/renderer/sceneQr.ts @@ -0,0 +1,26 @@ +import { qrDrawing } from '@codexr/core/xr/headsetQr'; + +// #518: on its own, so qrcode-generator loads with the first QR code drawn (sceneXrControls.ts, codexr/sceneSection.ts). + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +/** The QR code of `text`, black on white whatever the theme (a camera reads it). #399: the Scene section draws one too. */ +export function qrSvg(text: string, testId = 'scene-headset-qr'): SVGSVGElement { + const drawing = qrDrawing(text); + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', `0 0 ${drawing.size} ${drawing.size}`); + svg.setAttribute('class', 'scene-qr'); + svg.setAttribute('role', 'img'); + svg.setAttribute('aria-label', `QR code of ${text}`); + svg.setAttribute('data-testid', testId); + svg.setAttribute('shape-rendering', 'crispEdges'); + const background = document.createElementNS(SVG_NS, 'rect'); + background.setAttribute('width', String(drawing.size)); + background.setAttribute('height', String(drawing.size)); + background.setAttribute('fill', '#fff'); + const modules = document.createElementNS(SVG_NS, 'path'); + modules.setAttribute('d', drawing.path); + modules.setAttribute('fill', '#000'); + svg.append(background, modules); + return svg; +} diff --git a/apps/ide/src/renderer/sceneXrControls.ts b/apps/ide/src/renderer/sceneXrControls.ts index b0c17c06..ba00bf02 100644 --- a/apps/ide/src/renderer/sceneXrControls.ts +++ b/apps/ide/src/renderer/sceneXrControls.ts @@ -1,7 +1,6 @@ import type { CodeXRApi, SceneInfo } from '../shared/api.ts'; import { el } from './dom.ts'; import { enterXrNote, enterXrState, ipcErrorMessage } from './sceneHeaderModel.ts'; -import { qrDrawing } from '@codexr/core/xr/headsetQr'; /** * #19: the scene header's XR row. *Enter XR* starts an immersive session on @@ -25,29 +24,6 @@ export interface SceneXrControls { shareChanged(): void; } -const SVG_NS = 'http://www.w3.org/2000/svg'; - -/** The QR code of `text`, black on white whatever the theme (a camera reads it). #399: the Scene section draws one too. */ -export function qrSvg(text: string, testId = 'scene-headset-qr'): SVGSVGElement { - const drawing = qrDrawing(text); - const svg = document.createElementNS(SVG_NS, 'svg'); - svg.setAttribute('viewBox', `0 0 ${drawing.size} ${drawing.size}`); - svg.setAttribute('class', 'scene-qr'); - svg.setAttribute('role', 'img'); - svg.setAttribute('aria-label', `QR code of ${text}`); - svg.setAttribute('data-testid', testId); - svg.setAttribute('shape-rendering', 'crispEdges'); - const background = document.createElementNS(SVG_NS, 'rect'); - background.setAttribute('width', String(drawing.size)); - background.setAttribute('height', String(drawing.size)); - background.setAttribute('fill', '#fff'); - const modules = document.createElementNS(SVG_NS, 'path'); - modules.setAttribute('d', drawing.path); - modules.setAttribute('fill', '#000'); - svg.append(background, modules); - return svg; -} - export function createSceneXrControls(api: CodeXRApi['analysis'], callbacks: { onError(message: string): void; relayout(): void }): SceneXrControls { const enter = el('button', { className: 'secondary-button scene-xr-button', text: 'Enter XR', attrs: { type: 'button', 'data-testid': 'scene-enter-xr', title: 'Enter the scene on a headset connected to this computer' } }); const browser = el('button', { className: 'secondary-button scene-xr-button', text: 'Open in browser', attrs: { type: 'button', 'data-testid': 'scene-open-browser', title: 'Open the scene in your browser (its local address)' } }); @@ -76,7 +52,8 @@ export function createSceneXrControls(api: CodeXRApi['analysis'], callbacks: { o return; } const asked = ++generation; - api.headsetLink().then((link) => { + // #518: the QR encoder loads with the first headset panel, not with the page. + Promise.all([api.headsetLink(), import('./sceneQr.ts')]).then(([link, { qrSvg }]) => { if (asked !== generation) { return; } diff --git a/apps/ide/src/renderer/startup/launchController.ts b/apps/ide/src/renderer/startup/launchController.ts index 9dddb019..43b6be52 100644 --- a/apps/ide/src/renderer/startup/launchController.ts +++ b/apps/ide/src/renderer/startup/launchController.ts @@ -1,7 +1,7 @@ import { t } from '../../shared/i18n/i18n.ts'; import type { CodeXRApi } from '../../shared/api.ts'; -import { playLaunchAnimation, type LaunchAnimation } from './launchAnimation.ts'; -import { shouldPlayLaunchAnimation } from './launchModel.ts'; +import type { LaunchAnimation } from './launchAnimation.ts'; +import { shouldPlayLaunchAnimation } from './launchGate.ts'; import codeXrLogoUrl from '../../../../vscode-extension/resources/icon.svg?url'; /** @@ -10,6 +10,9 @@ import codeXrLogoUrl from '../../../../vscode-extension/resources/icon.svg?url'; * `workbench.startupAnimation` on. The scene is a native view drawn over the * page, so a scene that opens while the animation still plays is shown only * once the overlay is gone (`afterAnimation`). + * + * #518: the animation and its model load when it is about to play, not with + * the page; what waits for it also waits while they load. */ export interface StartupAnimation { /** An analysis started; `automatic` when the folder opening started it. */ @@ -30,9 +33,38 @@ export function createStartupAnimation(deps: { const createdAt = performance.now(); let played = false; let current: LaunchAnimation | null = null; + /** The animation's module is loading: it will play. */ + let loading = false; + /** The analysis ended while it loaded. */ + let endedEarly: boolean | null = null; let pending: Array<() => void> = []; const started = new Set<() => void>(); + // The scene and the guided tour may both be waiting. + const release = (): void => { + const waiting = pending; + pending = []; + for (const show of waiting) { + show(); + } + }; + const start = (animation: LaunchAnimation): void => { + current = animation; + for (const listener of started) { + listener(); + } + if (endedEarly !== null) { + animation.analysisEnded(endedEarly); + endedEarly = null; + } + const unsubscribe = deps.app.onProgress((event) => animation.progress(event)); + void animation.done.then(() => { + unsubscribe(); + current = null; + release(); + }); + }; + return { analysisStarted(automatic: boolean): void { const play = shouldPlayLaunchAnimation({ enabled: deps.enabled(), automatic, sinceStartMs: performance.now() - createdAt, alreadyPlayed: played }); @@ -43,33 +75,30 @@ export function createStartupAnimation(deps: { if (!play) { return; } - const animation = playLaunchAnimation({ - projectName: deps.workspace.current().then((workspace) => workspace?.name ?? t('launch.yourProject')), - files: deps.workspace.listFiles().then((list) => list.files, () => []), - logoUrl: codeXrLogoUrl, - reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches, - }); - current = animation; - for (const listener of started) { - listener(); - } - const unsubscribe = deps.app.onProgress((event) => animation.progress(event)); - void animation.done.then(() => { - unsubscribe(); - current = null; - // The scene and the guided tour may both be waiting. - const waiting = pending; - pending = []; - for (const show of waiting) { - show(); - } + loading = true; + void import('./launchAnimation.ts').then(({ playLaunchAnimation }) => { + loading = false; + start(playLaunchAnimation({ + projectName: deps.workspace.current().then((workspace) => workspace?.name ?? t('launch.yourProject')), + files: deps.workspace.listFiles().then((list) => list.files, () => []), + logoUrl: codeXrLogoUrl, + reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches, + })); + }, () => { + // Not played after all: whatever waits goes on. + loading = false; + release(); }); }, analysisFinished(ok: boolean): void { - current?.analysisEnded(ok); + if (current) { + current.analysisEnded(ok); + } else if (loading) { + endedEarly = ok; + } }, afterAnimation(show: () => void): void { - if (current) { + if (current || loading) { pending.push(show); } else { show(); diff --git a/apps/ide/src/renderer/startup/launchGate.ts b/apps/ide/src/renderer/startup/launchGate.ts new file mode 100644 index 00000000..673118a9 --- /dev/null +++ b/apps/ide/src/renderer/startup/launchGate.ts @@ -0,0 +1,22 @@ +/** + * When the launch animation (#403) plays. #518: apart from launchModel.ts and + * launchAnimation.ts, which load only when it does (launchController.ts). + */ + +/** The animation plays for the first automatic analysis that starts this long after the window opened, at most. */ +export const LAUNCH_WINDOW_MS = 45_000; + +export interface LaunchGate { + /** The `workbench.startupAnimation` setting. */ + readonly enabled: boolean; + /** The analysis was started by the folder opening, not by the person. */ + readonly automatic: boolean; + /** Milliseconds since the window's renderer started. */ + readonly sinceStartMs: number; + readonly alreadyPlayed: boolean; +} + +/** Only once per window, only for the analysis of the folder the IDE opened with. */ +export function shouldPlayLaunchAnimation(gate: LaunchGate): boolean { + return gate.enabled && gate.automatic && !gate.alreadyPlayed && gate.sinceStartMs >= 0 && gate.sinceStartMs <= LAUNCH_WINDOW_MS; +} diff --git a/apps/ide/src/renderer/startup/launchModel.ts b/apps/ide/src/renderer/startup/launchModel.ts index 70f6f6c5..755fcfdb 100644 --- a/apps/ide/src/renderer/startup/launchModel.ts +++ b/apps/ide/src/renderer/startup/launchModel.ts @@ -1,5 +1,8 @@ import { t } from '../../shared/i18n/i18n.ts'; +// #518: the gate is a module of its own, so the page decides without loading the animation. +export { LAUNCH_WINDOW_MS, shouldPlayLaunchAnimation, type LaunchGate } from './launchGate.ts'; + /** * The launch animation's model (#403): when it plays, how the analysis * progress reads, how the open folder becomes a city of buildings, where @@ -8,8 +11,6 @@ import { t } from '../../shared/i18n/i18n.ts'; * (test/launchModel.test.ts); launchAnimation.ts only draws what this says. */ -/** The animation plays for the first automatic analysis that starts this long after the window opened, at most. */ -export const LAUNCH_WINDOW_MS = 45_000; /** It never lasts longer than this, whatever the analysis does. */ export const MAX_DURATION_MS = 12_000; /** The finished city holds this long before the lenses open. */ @@ -29,21 +30,6 @@ export const MAX_BUILDINGS = 168; /** The title of the core's analysis progress (executePython.ts). */ export const ANALYSIS_PROGRESS_TITLE = 'Code-XR Analysis'; -export interface LaunchGate { - /** The `workbench.startupAnimation` setting. */ - readonly enabled: boolean; - /** The analysis was started by the folder opening, not by the person. */ - readonly automatic: boolean; - /** Milliseconds since the window's renderer started. */ - readonly sinceStartMs: number; - readonly alreadyPlayed: boolean; -} - -/** Only once per window, only for the analysis of the folder the IDE opened with. */ -export function shouldPlayLaunchAnimation(gate: LaunchGate): boolean { - return gate.enabled && gate.automatic && !gate.alreadyPlayed && gate.sinceStartMs >= 0 && gate.sinceStartMs <= LAUNCH_WINDOW_MS; -} - export interface CountedProgress { readonly current: number; readonly total: number; diff --git a/apps/ide/src/renderer/tour/lazyTour.ts b/apps/ide/src/renderer/tour/lazyTour.ts new file mode 100644 index 00000000..88581a9e --- /dev/null +++ b/apps/ide/src/renderer/tour/lazyTour.ts @@ -0,0 +1,51 @@ +/** What main.ts uses of the guided tour (tourView.ts's GuidedTour). */ +export interface LazyTour { + start(): void; + readonly isOpen: boolean; + hold(): void; + release(): void; +} + +/** + * #518: the guided tour (its view, strings and CSS) loads when it first opens + * (the first launch, or Help: Start the Guided Tour), not with the page: + * main.ts passes `() => import('./tour/tourView.ts')`. Until then a hold from + * the launch animation is only remembered, and handed to the tour if it loads + * while the animation still plays. No DOM: unit-tested. + */ +export function lazyGuidedTour(deps: Deps, load: () => Promise<{ createGuidedTour(deps: Deps): LazyTour }>): LazyTour { + let tour: LazyTour | null = null; + let loading: Promise | null = null; + let held = false; + const loaded = (): Promise => { + loading ??= load().then((module) => { + const created = module.createGuidedTour(deps); + tour = created; + if (held) { + created.hold(); + } + return created; + }); + return loading; + }; + return { + start() { + if (tour) { + tour.start(); + return; + } + loaded().then((ready) => ready.start(), (error: unknown) => console.error('[codexr] The guided tour could not load:', error)); + }, + get isOpen() { + return tour?.isOpen ?? false; + }, + hold() { + held = true; + tour?.hold(); + }, + release() { + held = false; + tour?.release(); + }, + }; +} diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index deb6a8cf..90487d17 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -610,6 +610,8 @@ export const en = { 'settings.note.userOnly': 'Only your user settings set this: it applies to every window.', 'settings.note.folderWins': 'This folder sets its own value, which wins here.', 'settings.note.userApplies': 'Your user setting applies.', + // #518: the Markdown preview, whose module loads on first use. + 'markdownPreview.failed': 'The Markdown preview could not start: {error}', }; export type MessageKey = keyof typeof en; diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index d02ce7dc..258a2d38 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -613,4 +613,5 @@ export const es: Readonly> = { 'settings.note.userOnly': 'Solo la configuración de usuario puede establecerlo: se aplica a todas las ventanas.', 'settings.note.folderWins': 'Esta carpeta establece su propio valor, que es el que se aplica aquí.', 'settings.note.userApplies': 'Se aplica tu configuración de usuario.', + 'markdownPreview.failed': 'No se pudo iniciar la vista previa de Markdown: {error}', }; diff --git a/apps/ide/test/startupLazyChunks.test.ts b/apps/ide/test/startupLazyChunks.test.ts new file mode 100644 index 00000000..8fdf6093 --- /dev/null +++ b/apps/ide/test/startupLazyChunks.test.ts @@ -0,0 +1,68 @@ +// #518: what the page loads on demand instead of at start-up: the Markdown +// preview, the extensions' language side, the QR encoder, the launch animation +// and the guided tour. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { needsEditorLanguages } from '../src/renderer/extensions/languageModel.ts'; +import { lazyGuidedTour, type LazyTour } from '../src/renderer/tour/lazyTour.ts'; + +const IDE_ROOT = path.resolve(import.meta.dirname, '..'); +const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); +const staticImports = (file: string): string[] => [...read(file).matchAll(/^import (?!type)[^;]* from '([^']+)';$/gm)].map((match) => match[1] ?? ''); + +const summary = { themes: [], iconThemes: [], languages: [] as string[], grammars: 0, snippets: 0, commands: [], views: [], settings: 0, keybindings: 0, localizations: [] }; + +describe('Start-up chunks loaded on demand (#518)', () => { + it('loads the extensions\' language side only for an enabled extension with code, languages or grammars', () => { + assert.equal(needsEditorLanguages([]), false); + assert.equal(needsEditorLanguages([{ state: 'enabled', hasCode: false, contributes: { ...summary, themes: [] } }]), false, 'a theme alone'); + assert.equal(needsEditorLanguages([{ state: 'enabled', hasCode: true, contributes: summary }]), true, 'code: onLanguage, document sync, LSP-like features'); + assert.equal(needsEditorLanguages([{ state: 'enabled', hasCode: false, contributes: { ...summary, grammars: 1 } }]), true); + assert.equal(needsEditorLanguages([{ state: 'enabled', hasCode: false, contributes: { ...summary, languages: ['toml'] } }]), true); + assert.equal(needsEditorLanguages([{ state: 'disabled', hasCode: true, contributes: summary }]), false); + const wiring = read('src/renderer/extensions/extensionsWiring.ts'); + assert.match(wiring, /if \(!editorLoaded \|\| languagesStarted \|\| !needsEditorLanguages\(installed\)\)/); + // Re-checked when the extensions are listed and whenever they change. + assert.equal(wiring.match(/installed = (?:list|event\.installed);\n\s*(?:view\.setInstalled\(event\.installed\);\n\s*)?startLanguages\(\);/g)?.length, 2); + }); + + it('imports the preview, the QR encoder, the animation and the tour dynamically', () => { + assert.ok(!staticImports('src/renderer/editor/editorGroup.ts').includes('./markdownPreview.ts')); + assert.match(read('src/renderer/editor/lazyMarkdownPreview.ts'), /import\('\.\/markdownPreview\.ts'\)/); + for (const file of ['src/renderer/sceneXrControls.ts', 'src/renderer/codexr/sceneSection.ts']) { + assert.ok(!staticImports(file).some((source) => /headsetQr|sceneQr|sceneXrControls/.test(source)), file); + } + assert.ok(!staticImports('src/renderer/startup/launchController.ts').some((source) => /launchAnimation|launchModel/.test(source))); + assert.ok(!staticImports('src/renderer/main.ts').some((source) => /tourView/.test(source))); + }); + + it('creates the tour on its first start, handing it a hold from the animation', async () => { + const calls: string[] = []; + const fake: LazyTour = { + start: () => calls.push('start'), + get isOpen() { return calls.includes('start'); }, + hold: () => calls.push('hold'), + release: () => calls.push('release'), + }; + let loads = 0; + const tour = lazyGuidedTour({}, async () => { + loads += 1; + return { createGuidedTour: () => fake }; + }); + tour.hold(); + tour.release(); + tour.hold(); + assert.equal(loads, 0, 'nothing loaded before it opens'); + assert.equal(tour.isOpen, false); + tour.start(); + tour.start(); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(loads, 1); + assert.deepEqual(calls, ['hold', 'start', 'start']); + assert.equal(tour.isOpen, true); + tour.release(); + assert.deepEqual(calls.at(-1), 'release'); + }); +}); From 21028fdf560784dba699fc521793072f7f9a4b96 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:27:23 +0000 Subject: [PATCH 16/74] feat(core): host-neutral prompt templates to ask an agent about a hotspot (#514) --- .../src/core/agent-prompts/hotspotPrompt.ts | 182 ++++++++++++++++++ .../test/agent_prompts/hotspotPrompt.test.cjs | 26 +++ 2 files changed, 208 insertions(+) create mode 100644 apps/vscode-extension/src/core/agent-prompts/hotspotPrompt.ts create mode 100644 apps/vscode-extension/test/agent_prompts/hotspotPrompt.test.cjs diff --git a/apps/vscode-extension/src/core/agent-prompts/hotspotPrompt.ts b/apps/vscode-extension/src/core/agent-prompts/hotspotPrompt.ts new file mode 100644 index 00000000..b491ed42 --- /dev/null +++ b/apps/vscode-extension/src/core/agent-prompts/hotspotPrompt.ts @@ -0,0 +1,182 @@ +/** + * #514 (O12): "Ask the agent about a hotspot". The prompt a host drafts in its + * agent chat when the person asks about a measured function (a CodeLens, a + * Problems row, the editor's context menu, the top hotspot of the project). + * + * Pure and host-neutral on purpose: no `vscode`, no Node, no DOM and no + * runtime imports, because the Code-XR IDE loads it in its sandboxed renderer + * and the VS Code extension's chat can reuse it as is. The prompt text is + * English whatever the display language: it is addressed to the agent, not + * shown as UI. Hosts only pick the function and insert the draft (never send it). + */ + +import type { FileFunctionMetrics, FunctionMetric, MetricThresholds } from '../metrics/functionMetrics'; + +/** What the person wants the agent to do with the function. */ +export type HotspotIntent = 'explain' | 'refactor' | 'tests'; + +/** The intents in the order menus offer them; the default first. */ +export const HOTSPOT_INTENTS: readonly HotspotIntent[] = ['refactor', 'explain', 'tests']; + +export const DEFAULT_HOTSPOT_INTENT: HotspotIntent = 'refactor'; + +export function isHotspotIntent(value: unknown): value is HotspotIntent { + return typeof value === 'string' && (HOTSPOT_INTENTS as readonly string[]).includes(value); +} + +/** One measured function, where it is and what it measured. */ +export interface HotspotTarget { + /** Workspace-relative path, with forward slashes. */ + readonly path: string; + readonly name: string; + /** 1-based, inclusive. */ + readonly lineStart: number; + readonly lineEnd: number; + /** Cyclomatic complexity (CCN). */ + readonly complexity: number; + /** Lines of code (NLOC). */ + readonly lineCount: number; + readonly parameters: number; +} + +export function hotspotTarget(path: string, fn: FunctionMetric): HotspotTarget { + return { + path: path.replace(/\\/g, '/'), + name: fn.name, + lineStart: fn.lineStart, + lineEnd: Math.max(fn.lineStart, fn.lineEnd), + complexity: fn.complexity, + lineCount: fn.lineCount, + parameters: fn.parameters, + }; +} + +/** + * The function a line belongs to: the innermost (shortest) one whose range + * holds it, so a nested function wins over the one around it. Null outside + * every measured function. + */ +export function functionAtLine(functions: readonly FunctionMetric[], line: number): FunctionMetric | null { + let best: FunctionMetric | null = null; + for (const fn of functions) { + const end = Math.max(fn.lineStart, fn.lineEnd); + if (line >= fn.lineStart && line <= end && (!best || end - fn.lineStart < Math.max(best.lineStart, best.lineEnd) - best.lineStart)) { + best = fn; + } + } + return best; +} + +/** + * The function a metric problem is about: metric problems sit on the + * function's first line (`metricProblems`), so the function of `path` that + * starts on `line`, else the innermost one holding it. + */ +export function functionForProblem(files: readonly FileFunctionMetrics[], path: string, line: number): HotspotTarget | null { + const file = files.find((candidate) => candidate.path === path); + if (!file) { + return null; + } + const fn = file.functions.find((candidate) => candidate.lineStart === line) ?? functionAtLine(file.functions, line); + return fn ? hotspotTarget(file.path, fn) : null; +} + +/** + * The project's top hotspot: the most complex measured function (CCN), ties + * broken by length (NLOC), then parameters, then path and name so the answer + * is stable. Null when nothing has been measured. + */ +export function topHotspot(files: readonly FileFunctionMetrics[]): HotspotTarget | null { + let best: HotspotTarget | null = null; + for (const file of files) { + for (const fn of file.functions) { + const candidate = hotspotTarget(file.path, fn); + if (!best || compareHotspots(candidate, best) < 0) { + best = candidate; + } + } + } + return best; +} + +/** Negative when `a` is the hotter of the two. */ +export function compareHotspots(a: HotspotTarget, b: HotspotTarget): number { + return (b.complexity - a.complexity) + || (b.lineCount - a.lineCount) + || (b.parameters - a.parameters) + || a.path.localeCompare(b.path) + || a.name.localeCompare(b.name) + || a.lineStart - b.lineStart; +} + +/** Text from a report (a path, a function name) on one line, without control characters. */ +function oneLine(text: string): string { + return text.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim(); +} + +/** A Markdown code span that survives backticks in the text. */ +export function codeSpan(text: string): string { + const clean = oneLine(text) || '?'; + const longest = Math.max(0, ...(clean.match(/`+/g) ?? []).map((run) => run.length)); + const fence = '`'.repeat(longest + 1); + const pad = longest > 0 || clean.startsWith('`') || clean.endsWith('`') ? ' ' : ''; + return `${fence}${pad}${clean}${pad}${fence}`; +} + +function lineRange(target: HotspotTarget): string { + return target.lineEnd > target.lineStart ? `lines ${target.lineStart}-${target.lineEnd}` : `line ${target.lineStart}`; +} + +function limitNote(value: number, limit: number | undefined): string { + return limit !== undefined && limit > 0 ? (value > limit ? ` (over the limit of ${limit})` : ` (limit ${limit})`) : ''; +} + +/** The measurements, one Markdown bullet each. */ +export function metricLines(target: HotspotTarget, thresholds?: MetricThresholds): string[] { + return [ + `- Cyclomatic complexity (CCN): ${target.complexity}${limitNote(target.complexity, thresholds?.complexity)}`, + `- Lines of code (NLOC): ${target.lineCount}${limitNote(target.lineCount, thresholds?.lines)}`, + `- Parameters: ${target.parameters}${limitNote(target.parameters, thresholds?.parameters)}`, + ]; +} + +const REQUESTS: Readonly string; readonly how: readonly string[] }>> = { + explain: { + ask: (fn, where) => `Explain what the function ${fn} in ${where} does.`, + how: [ + 'Walk through its control flow and its inputs and outputs, point out which branches make it complex, and say where it could be simplified.', + 'Do not change any files.', + ], + }, + refactor: { + ask: (fn, where) => `Refactor the function ${fn} in ${where} to reduce its complexity.`, + how: [ + 'Keep its behaviour and its public signature unchanged. Split it into smaller, well-named functions, flatten nested conditions and remove duplication where that helps.', + 'Explain each change, and run the project\'s existing tests afterwards if there are any.', + ], + }, + tests: { + ask: (fn, where) => `Add unit tests for the function ${fn} in ${where}.`, + how: [ + 'Cover each of its independent paths (its cyclomatic complexity is the number to aim for) and its edge cases, using the project\'s existing test framework and conventions.', + 'Do not change the function itself; tell me if something in it looks like a bug.', + ], + }, +}; + +/** + * The draft for one function and one intent: what to do, where (path and + * line range), the measurements, and how. English Markdown, ready to edit. + */ +export function hotspotPrompt(target: HotspotTarget, intent: HotspotIntent = DEFAULT_HOTSPOT_INTENT, thresholds?: MetricThresholds): string { + const request = REQUESTS[isHotspotIntent(intent) ? intent : DEFAULT_HOTSPOT_INTENT]; + const where = `${codeSpan(target.path)} (${lineRange(target)})`; + return [ + request.ask(codeSpan(target.name), where), + '', + 'Code-XR measured it as:', + ...metricLines(target, thresholds), + '', + ...request.how, + ].join('\n'); +} diff --git a/apps/vscode-extension/test/agent_prompts/hotspotPrompt.test.cjs b/apps/vscode-extension/test/agent_prompts/hotspotPrompt.test.cjs new file mode 100644 index 00000000..4f2ff1ac --- /dev/null +++ b/apps/vscode-extension/test/agent_prompts/hotspotPrompt.test.cjs @@ -0,0 +1,26 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { hotspotPrompt, topHotspot, functionAtLine, codeSpan, DEFAULT_HOTSPOT_INTENT } = require('../../out/core/agent-prompts/hotspotPrompt.js'); + +// #514: the "Ask agent" templates live in the core so this extension's chat can reuse them (the IDE tests them in depth). +const files = [ + { path: 'src/a.ts', functions: [{ name: 'outer', lineStart: 1, lineEnd: 40, lineCount: 30, complexity: 4, parameters: 2 }, { name: 'inner', lineStart: 10, lineEnd: 20, lineCount: 8, complexity: 2, parameters: 0 }] }, + { path: 'src/b.ts', functions: [{ name: 'parseConfig', lineStart: 12, lineEnd: 88, lineCount: 64, complexity: 27, parameters: 3 }] }, +]; + +test('the core drafts a host-neutral English prompt about the top hotspot (#514)', () => { + const target = topHotspot(files); + assert.equal(target.name, 'parseConfig'); + assert.equal(DEFAULT_HOTSPOT_INTENT, 'refactor'); + const text = hotspotPrompt(target); + assert.match(text, /^Refactor the function `parseConfig` in `src\/b\.ts` \(lines 12-88\) to reduce its complexity\./); + assert.match(text, /- Cyclomatic complexity \(CCN\): 27\n- Lines of code \(NLOC\): 64\n- Parameters: 3/); + assert.match(hotspotPrompt(target, 'explain'), /^Explain what the function/); + assert.match(hotspotPrompt(target, 'tests'), /^Add unit tests for the function/); +}); + +test('functionAtLine picks the innermost function and codeSpan survives backticks', () => { + assert.equal(functionAtLine(files[0].functions, 15).name, 'inner'); + assert.equal(functionAtLine(files[0].functions, 41), null); + assert.equal(codeSpan('a`b'), '`` a`b ``'); +}); From a0517f6eeec1e7493f210058de1ba869962081c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:27:23 +0000 Subject: [PATCH 17/74] feat(ide): ask the agent about a hotspot from the lens, Problems, editor menu and palette (#514) --- apps/ide/eslint.config.mjs | 4 +- apps/ide/scripts/viteConfigs.mjs | 2 + .../src/renderer/agentFirst/agentWorkbench.ts | 48 ++++- apps/ide/src/renderer/agentFirst/askAgent.ts | 121 ++++++++++++ .../src/renderer/editor/analysisEditorMenu.ts | 48 +++++ apps/ide/src/renderer/editor/editorGroup.ts | 21 +- apps/ide/src/renderer/editor/metricLens.ts | 33 +++- apps/ide/src/renderer/main.ts | 18 ++ .../ide/src/renderer/problems/problemsView.ts | 16 +- apps/ide/src/shared/i18n/messages.en.ts | 12 ++ apps/ide/src/shared/i18n/messages.es.ts | 12 ++ apps/ide/test/askAgent.test.ts | 180 ++++++++++++++++++ apps/ide/tsconfig.web.json | 5 +- 13 files changed, 510 insertions(+), 10 deletions(-) create mode 100644 apps/ide/src/renderer/agentFirst/askAgent.ts create mode 100644 apps/ide/test/askAgent.test.ts diff --git a/apps/ide/eslint.config.mjs b/apps/ide/eslint.config.mjs index 47375c5c..f6d2f85d 100644 --- a/apps/ide/eslint.config.mjs +++ b/apps/ide/eslint.config.mjs @@ -34,8 +34,8 @@ export default [ patterns: [ { group: ['node:*'], message: 'The renderer cannot use Node. Add a member to CodeXRApi instead.' }, { group: ['../main/*', '../sidecar/*', '../bridge/*'], message: 'The renderer may only import src/shared.' }, - // core/metrics and core/xr are the exceptions: pure logic shared with the extension (#173/#178, #19). - { group: ['@codexr/core/*', '!@codexr/core/metrics', '!@codexr/core/xr', '@codexr/logging/*'], message: 'The core runs in the main process only (#15), except the pure core/metrics and core/xr. Add a member to CodeXRApi instead.' }, + // core/metrics, core/xr and core/agent-prompts are the exceptions: pure logic shared with the extension (#173/#178, #19, #514). + { group: ['@codexr/core/*', '!@codexr/core/metrics', '!@codexr/core/xr', '!@codexr/core/agent-prompts', '@codexr/logging/*'], message: 'The core runs in the main process only (#15), except the pure core/metrics, core/xr and core/agent-prompts. Add a member to CodeXRApi instead.' }, ], }], 'no-restricted-properties': ['error', diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 1328369d..f2d5ccf0 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -162,6 +162,8 @@ export function rendererConfig(opts = {}) { { find: /^@codexr\/core\/xr\//, replacement: `${CORE_SRC}/xr/` }, // #398: the analysable file extensions (a dependency-free table), for the analysis menus. { find: /^@codexr\/core\/analysis\/languages\//, replacement: `${CORE_SRC}/analysis/languages/` }, + // #514: the "Ask agent" prompt templates (pure, type-only imports of core/metrics). + { find: /^@codexr\/core\/agent-prompts\//, replacement: `${CORE_SRC}/agent-prompts/` }, ] }, }; } diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 32202f25..a094d886 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -66,6 +66,12 @@ export interface AgentWorkbench { readonly sessions: SessionsView; openChat(sessionId: string): Promise; newChat(agentRef?: string): Promise; + /** + * #514: puts `text` in the composer of the active chat (the one on screen, + * else the last one shown that is still open), or of a new chat when there + * is none, and focuses it. Never sends it. False when no chat could be opened. + */ + draftInChat(text: string): Promise; setMode(mode: LayoutMode): void; readonly mode: LayoutMode; /** Turns a saved tab id into a chat tab; main.ts registers it on the editor group. */ @@ -84,6 +90,10 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork const { workbench, api } = options; const views = new Set(); let activeChatId: string | null = null; + /** #514: the chat shown last (it stays the target of a draft while a file tab covers it). */ + let lastChatId: string | null = null; + /** #514: a draft waiting for the chat that `sessions.newChat` is about to open. */ + let pendingDraft: string | null = null; let mode: LayoutMode = readMode(); // ---- Dock placeholder (AF8) -------------------------------------------- @@ -238,6 +248,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork element: view.element, onShow: () => { activeChatId = sessionId; + lastChatId = sessionId; sessions.setActive(sessionId); api.markRead(sessionId).catch(() => undefined); }, @@ -251,6 +262,9 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork dispose: () => { view.dispose(); views.delete(view); + if (lastChatId === sessionId) { + lastChatId = null; + } tabClosers.delete(sessionId); }, }; @@ -283,11 +297,42 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork await group.openCustom(chatInput(sessionId, title), { preview: false }); } + // ---- Drafts from the analysis (#514) ------------------------------------- + function viewOf(sessionId: string): ChatView | undefined { + return [...views].reverse().find((view) => view.sessionId === sessionId); + } + + async function draftInChat(text: string): Promise { + const target = activeChatId ?? lastChatId; + if (target && viewOf(target)) { + await openChat(target); + viewOf(target)?.insert(text); + return true; + } + // The sessions view opens the chat it creates synchronously before + // newChat resolves (openChat below takes the draft), or reports why not. + pendingDraft = text; + try { + await sessions.newChat(); + return pendingDraft === null; + } finally { + pendingDraft = null; + } + } + // ---- Chats view (AF7) and project instructions (AF11) ------------------ const instructions = createInstructionsView({ ...options.instructions, openFile: (path) => options.openFile(path), hasFolder: options.hasFolder, onStatus: options.onStatus }); const sessions = createSessionsView(workbench.chatsView, { api, - openChat: (id) => void openChat(id), + openChat: (id) => { + const draft = pendingDraft; + pendingDraft = null; + void openChat(id).then(() => { + if (draft !== null) { + viewOf(id)?.insert(draft); + } + }); + }, openChatInProject: (root, id) => { options.openProject(root).then(() => openChat(id)).catch((error: unknown) => options.onStatus(errorText(error))); }, @@ -521,6 +566,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork sessions, openChat, newChat: (agentRef?: string) => sessions.newChat(agentRef), + draftInChat, setMode, resolveCustomEditor, get mode() { diff --git a/apps/ide/src/renderer/agentFirst/askAgent.ts b/apps/ide/src/renderer/agentFirst/askAgent.ts new file mode 100644 index 00000000..8f7dc084 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/askAgent.ts @@ -0,0 +1,121 @@ +import { + DEFAULT_HOTSPOT_INTENT, functionAtLine, functionForProblem, HOTSPOT_INTENTS, hotspotPrompt, hotspotTarget, topHotspot, + type HotspotIntent, type HotspotTarget, +} from '@codexr/core/agent-prompts/hotspotPrompt'; +import type { FunctionMetric, FunctionMetricsSnapshot, MetricThresholds, Problem } from '../../shared/problems.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import type { CommandDefinition } from '../commands/commandRegistry.ts'; + +/** + * #514 (O12): "Ask the agent about a hotspot", from the live analysis. The + * metric CodeLens, the metric rows of the Problems panel, the editor's + * context menu and the palette's "top hotspot" command all end here: the + * function is looked up in the window's measured functions, a prompt is + * drafted from the core's template (core/agent-prompts, shared with the VS + * Code extension) and put in the active chat's composer, or a new chat's. + * It is never sent: the person reads it, edits it and presses Send. + * + * No DOM here: the chat is reached through `draft` (agentWorkbench), so the + * module is unit-tested in Node. + */ + +export interface AskAgentDeps { + /** The window's measured functions (null before any analysis). */ + snapshot(): FunctionMetricsSnapshot | null; + /** The Problems limits, quoted beside the measurements (null when unknown). */ + thresholds(): MetricThresholds | null; + /** Inserts the text in the active (or a new) chat without sending it; false when no chat opened. */ + draft(text: string): Promise; + onStatus(message: string): void; +} + +export interface AskAgent { + /** The measured function a line of `path` belongs to (the innermost), or null. */ + functionAt(path: string, line: number): FunctionMetric | null; + aboutFunction(path: string, fn: FunctionMetric, intent?: HotspotIntent): Promise; + /** The function at a line (the editor's cursor). */ + aboutLine(path: string, line: number, intent?: HotspotIntent): Promise; + /** A metric problem's function. */ + aboutProblem(problem: Problem, intent?: HotspotIntent): Promise; + /** The project's most complex measured function. */ + aboutTopHotspot(intent?: HotspotIntent): Promise; +} + +export { DEFAULT_HOTSPOT_INTENT, HOTSPOT_INTENTS, type HotspotIntent }; + +const INTENT_LABELS: Readonly> = { + explain: 'askAgent.intent.explain', + refactor: 'askAgent.intent.refactor', + tests: 'askAgent.intent.tests', +}; + +/** A sub-action's label: "Refactor to Reduce Complexity", "Explain", "Add Tests". */ +export function intentLabel(intent: HotspotIntent): string { + return t(INTENT_LABELS[intent]); +} + +/** Whether a Problems row is one of the metric checks the agent can be asked about. */ +export function canAskAbout(problem: Problem): boolean { + return problem.origin === 'metrics'; +} + +export function createAskAgent(deps: AskAgentDeps): AskAgent { + const files = (): FunctionMetricsSnapshot['files'] => deps.snapshot()?.files ?? []; + + async function send(target: HotspotTarget, intent: HotspotIntent): Promise { + let drafted = false; + try { + drafted = await deps.draft(hotspotPrompt(target, intent, deps.thresholds() ?? undefined)); + } catch (error) { + deps.onStatus(error instanceof Error ? error.message : String(error)); + } + if (drafted) { + deps.onStatus(t('askAgent.drafted', { name: target.name })); + } + return drafted; + } + + function functionAt(path: string, line: number): FunctionMetric | null { + const file = files().find((candidate) => candidate.path === path); + return file ? functionAtLine(file.functions, line) : null; + } + + return { + functionAt, + aboutFunction: (path, fn, intent = DEFAULT_HOTSPOT_INTENT) => send(hotspotTarget(path, fn), intent), + async aboutLine(path, line, intent = DEFAULT_HOTSPOT_INTENT) { + const fn = functionAt(path, line); + if (!fn) { + deps.onStatus(t('askAgent.noFunction')); + return false; + } + return send(hotspotTarget(path, fn), intent); + }, + async aboutProblem(problem, intent = DEFAULT_HOTSPOT_INTENT) { + const target = canAskAbout(problem) ? functionForProblem(files(), problem.path, problem.startLine) : null; + if (!target) { + deps.onStatus(t('askAgent.noFunction')); + return false; + } + return send(target, intent); + }, + async aboutTopHotspot(intent = DEFAULT_HOTSPOT_INTENT) { + const target = topHotspot(files()); + if (!target) { + deps.onStatus(t('askAgent.noHotspot')); + return false; + } + return send(target, intent); + }, + }; +} + +/** The palette's commands: `chat.askAboutHotspot` (refactor), and one per other intent. */ +export function askAgentCommands(ask: AskAgent): CommandDefinition[] { + return HOTSPOT_INTENTS.map((intent): CommandDefinition => ({ + id: intent === DEFAULT_HOTSPOT_INTENT ? 'chat.askAboutHotspot' : `chat.askAboutHotspot.${intent}`, + category: t('category.chat'), + title: t('askAgent.command', { action: intentLabel(intent) }), + run: () => void ask.aboutTopHotspot(intent), + })); +} diff --git a/apps/ide/src/renderer/editor/analysisEditorMenu.ts b/apps/ide/src/renderer/editor/analysisEditorMenu.ts index d20bf879..b2af639f 100644 --- a/apps/ide/src/renderer/editor/analysisEditorMenu.ts +++ b/apps/ide/src/renderer/editor/analysisEditorMenu.ts @@ -4,6 +4,8 @@ import { CommandsRegistry } from 'monaco-editor/platform/commands/common/command import { ContextKeyExpr } from 'monaco-editor/platform/contextkey/common/contextkey.js'; import { ANALYSIS_KIND_INFO, ANALYSIS_KINDS, kindAppliesTo, type AnalysisKind } from '../../shared/analysisKinds.ts'; import { analysisSubmenuLabel, pathForKind, runLastLabel } from '../analysisMenu.ts'; +import { t } from '../../shared/i18n/i18n.ts'; +import { HOTSPOT_INTENTS, intentLabel, type HotspotIntent } from '../agentFirst/askAgent.ts'; /** * #398: the analyses in the editor's own (Monaco) context menu, as the @@ -13,6 +15,10 @@ import { analysisSubmenuLabel, pathForKind, runLastLabel } from '../analysisMenu * by context keys each editor keeps for its file (`kindAppliesTo`, the same * conditions as every other menu) and the window's state (last kind, whether * an analysis can start). + * + * #514: "Ask Agent about This Function", a submenu of the three intents + * (refactor first), shown while the cursor is in a function the analysis + * measured; it drafts a prompt about it in the active chat. */ export interface AnalysisEditorMenuHooks { @@ -21,6 +27,11 @@ export interface AnalysisEditorMenuHooks { /** The workspace path of a model the editor group opened from the folder, else null. */ pathOf(uri: monaco.Uri): string | null; run(kind: AnalysisKind, path: string): void; + /** #514: whether `line` of `path` is in a measured function, and asking the agent about it. */ + askAgent?: { + hasFunction(path: string, line: number): boolean; + ask(path: string, line: number, intent: HotspotIntent): void; + }; } export interface AnalysisEditorMenu { @@ -33,6 +44,9 @@ export interface AnalysisEditorMenu { const CAN_ANALYSE = 'codexrCanAnalyse'; const LAST_KIND = 'codexrAnalysisLastKind'; const appliesKey = (kind: AnalysisKind): string => `codexrAnalysisApplies.${kind}`; +const IN_FUNCTION = 'codexrInMeasuredFunction'; +/** #514: the editor the context menu opened on (its cursor is the function asked about). */ +let menuEditor: monaco.editor.IStandaloneCodeEditor | null = null; /** A file kind applies to the editor's file, a project kind to any file of the folder; a folder kind never (as in the extension's editor menu). */ function applies(kind: AnalysisKind, path: string | null): boolean { @@ -75,6 +89,24 @@ function register(hooks: AnalysisEditorMenuHooks): void { }); }); MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu, title: analysisSubmenuLabel(), group: 'codexr', order: 11 }); + const askAgent = hooks.askAgent; + if (askAgent) { + const askSubmenu = new MenuId('codexr.askAgentSubmenu'); + HOTSPOT_INTENTS.forEach((intent, order) => { + const id = `codexr.editorAskAgent.${intent}`; + CommandsRegistry.registerCommand(id, (_accessor, uri) => { + const editor = menuEditor; + const model = editor?.getModel(); + const position = editor?.getPosition(); + const path = model && position && (!uri || String(uri) === model.uri.toString()) ? hooks.pathOf(model.uri) : null; + if (path !== null && position) { + askAgent.ask(path, position.lineNumber, intent); + } + }); + MenuRegistry.appendMenuItem(askSubmenu, { command: { id, title: intentLabel(intent) }, group: '1_intent', order }); + }); + MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: askSubmenu, title: t('askAgent.menu'), group: 'codexr', order: 12, when: ContextKeyExpr.has(IN_FUNCTION) }); + } } export function installAnalysisEditorMenu(hooks: AnalysisEditorMenuHooks): AnalysisEditorMenu { @@ -85,11 +117,17 @@ export function installAnalysisEditorMenu(hooks: AnalysisEditorMenuHooks): Analy const canAnalyse = editor.createContextKey(CAN_ANALYSE, false); const lastKind = editor.createContextKey(LAST_KIND, ''); const kinds = ANALYSIS_KINDS.map((kind) => [kind, editor.createContextKey(appliesKey(kind), false)] as const); + const inFunction = editor.createContextKey(IN_FUNCTION, false); + const updateInFunction = (path: string | null): void => { + const line = editor.getPosition()?.lineNumber; + inFunction.set(path !== null && line !== undefined && (hooks.askAgent?.hasFunction(path, line) ?? false)); + }; const entry = { editor, update(): void { const model = editor.getModel(); const path = model ? hooks.pathOf(model.uri) : null; + updateInFunction(path); const state = hooks.state(); canAnalyse.set(state.enabled); lastKind.set(state.lastKind); @@ -101,9 +139,19 @@ export function installAnalysisEditorMenu(hooks: AnalysisEditorMenuHooks): Analy editors.add(entry); entry.update(); const changed = editor.onDidChangeModel(() => entry.update()); + const moved = hooks.askAgent ? editor.onDidChangeCursorPosition(() => { + const model = editor.getModel(); + updateInFunction(model ? hooks.pathOf(model.uri) : null); + }) : null; + const focused = editor.onDidFocusEditorWidget(() => { menuEditor = editor; }); return { dispose(): void { changed.dispose(); + moved?.dispose(); + focused.dispose(); + if (menuEditor === editor) { + menuEditor = null; + } editors.delete(entry); }, }; diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index e60c4d02..047343bf 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -4,7 +4,8 @@ import { followSystemTheme, monaco } from './monaco.ts'; import { startupMarkFrame, startupMarkOnce } from '../startup/startupMarks.ts'; import { languageName, type EditorStatusState, type EndOfLine, type Indentation, type LanguageInfo } from './editorStatusModel.ts'; import { settingOf, type SettingValues } from '../../shared/settings.ts'; -import type { FileFunctionMetrics, MetricThresholds, Problem, ProblemSeverity } from '../../shared/problems.ts'; +import type { FileFunctionMetrics, FunctionMetric, MetricThresholds, Problem, ProblemSeverity } from '../../shared/problems.ts'; +import type { HotspotIntent } from '../agentFirst/askAgent.ts'; import { installMetricLens } from './metricLens.ts'; import { installGitDecorations, type GitDecorationsHooks } from './gitDecorations.ts'; import { installDebugDecorations, type DebugDecorationsHooks } from './debugDecorations.ts'; @@ -319,6 +320,11 @@ export function createEditorGroup( analyzeInScene?(path: string): void; /** #398: the analyses of the editor's context menu ("Run Last", the "Code-XR: Analysis" submenu). */ analysis?: Pick; + /** #514: "Ask agent" about a measured function, from its lens and the editor's context menu. */ + askAgent?: { + functionAt(path: string, line: number): FunctionMetric | null; + ask(path: string, fn: FunctionMetric, intent?: HotspotIntent): void; + }; /** #175: the files' text at HEAD and their blame, from the main process (null when Git has nothing to say). */ git?: GitDecorationsHooks; /** #180: the breakpoints in the glyph margin, owned by the debugger. */ @@ -453,14 +459,25 @@ export function createEditorGroup( const metricLens = installMetricLens(FILE_SCHEME, { isStale: (model) => [...docs.values()].some((doc) => doc.model === model && isDirty(doc)), showProblems: (path, name) => callbacks.showFunctionProblems?.(path, name), + ...(callbacks.askAgent ? { askAgent: callbacks.askAgent.ask } : {}), }); // #175: change markers against HEAD and the cursor line's blame. const gitDecorations = callbacks.git ? installGitDecorations(callbacks.git) : null; // #180: breakpoints and the paused line. const debugDecorations = callbacks.debug ? installDebugDecorations(callbacks.debug) : null; // #398: the analyses of the editor's context menu, on the file of the folder it shows. + const askAgent = callbacks.askAgent; const analysisMenu = callbacks.analysis ? installAnalysisEditorMenu({ ...callbacks.analysis, + ...(askAgent ? { + askAgent: { + hasFunction: (path: string, line: number) => askAgent.functionAt(path, line) !== null, + ask: (path: string, line: number, intent: HotspotIntent) => { + const fn = askAgent.functionAt(path, line); + if (fn) { askAgent.ask(path, fn, intent); } + }, + }, + } : {}), pathOf: (uri) => { const key = uri.toString(); return uri.scheme === FILE_SCHEME ? [...docs.values()].find((doc) => doc.model.uri.toString() === key)?.path ?? null : null; @@ -1942,6 +1959,8 @@ export function createEditorGroup( }, setFunctionMetrics(metricFiles: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean): void { metricLens.update(metricFiles, thresholds, enabled); + // #514: the "Ask agent" entry of the context menu follows the measured functions. + analysisMenu?.refresh(); }, setMetricProblems(problems: readonly Problem[]): void { const next = new Map(); diff --git a/apps/ide/src/renderer/editor/metricLens.ts b/apps/ide/src/renderer/editor/metricLens.ts index 25507227..59285750 100644 --- a/apps/ide/src/renderer/editor/metricLens.ts +++ b/apps/ide/src/renderer/editor/metricLens.ts @@ -1,4 +1,5 @@ import { complexityBand, metricLensTitle, type FileFunctionMetrics, type FunctionMetric, type MetricThresholds } from '../../shared/problems.ts'; +import { t } from '../../shared/i18n/i18n.ts'; import { monaco } from './monaco.ts'; /** @@ -11,6 +12,9 @@ import { monaco } from './monaco.ts'; * disk: while a tab has unsaved changes its lenses give way to one * "out of date" lens, and saving measures it again. The strip is a set of * decorations, so it follows the lines as they are edited. + * + * #514: beside each function's lens, an "Ask agent" lens drafts a prompt + * about it (refactor, the default intent) in the active chat. */ export interface MetricLens { @@ -23,6 +27,7 @@ export interface MetricLens { } export const SHOW_PROBLEMS_COMMAND = 'codexr.metrics.showProblems'; +export const ASK_AGENT_COMMAND = 'codexr.metrics.askAgent'; const BAND_CLASS = { high: 'metric-heat is-high', critical: 'metric-heat is-critical' } as const; const BAND_RULER = { high: 'editorWarning.foreground', critical: 'editorError.foreground' } as const; @@ -31,6 +36,8 @@ export function installMetricLens(scheme: string, hooks: { isStale(model: monaco.editor.ITextModel): boolean; /** A lens over a function past a limit was clicked: list its problems. */ showProblems(path: string, name: string): void; + /** #514: the "Ask agent" lens of a function was clicked (no lens without this hook). */ + askAgent?(path: string, fn: FunctionMetric): void; }): MetricLens { let byPath = new Map(); let thresholds: MetricThresholds = { complexity: 0, lines: 0, parameters: 0 }; @@ -45,6 +52,16 @@ export function installMetricLens(scheme: string, hooks: { } }); + const askAgent = hooks.askAgent; + if (askAgent) { + monaco.editor.registerCommand(ASK_AGENT_COMMAND, (_accessor, path: unknown, name: unknown, line: unknown) => { + const fn = typeof path === 'string' ? byPath.get(path)?.find((candidate) => candidate.name === name && candidate.lineStart === line) : undefined; + if (typeof path === 'string' && fn) { + askAgent(path, fn); + } + }); + } + const provider: monaco.languages.CodeLensProvider = { onDidChange: changed.event, provideCodeLenses(model) { @@ -62,14 +79,24 @@ export function installMetricLens(scheme: string, hooks: { }; } const lastLine = model.getLineCount(); - const lenses = functions.filter((fn) => fn.lineStart <= lastLine).map((fn): monaco.languages.CodeLens => { + const lenses = functions.filter((fn) => fn.lineStart <= lastLine).flatMap((fn): monaco.languages.CodeLens[] => { const { title, over } = metricLensTitle(fn, thresholds); - return { - range: new monaco.Range(fn.lineStart, 1, fn.lineStart, 1), + const range = new monaco.Range(fn.lineStart, 1, fn.lineStart, 1); + const metric: monaco.languages.CodeLens = { + range, command: over ? { id: SHOW_PROBLEMS_COMMAND, title, arguments: [pathOf(model), fn.name], tooltip: `Show the problems of '${fn.name}'` } : { id: '', title }, }; + return askAgent ? [metric, { + range, + command: { + id: ASK_AGENT_COMMAND, + title: `$(sparkle) ${t('askAgent.lens')}`, + arguments: [pathOf(model), fn.name, fn.lineStart], + tooltip: t('askAgent.lensTooltip', { name: fn.name }), + }, + }] : [metric]; }); return { lenses, dispose(): void {} }; }, diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index cf725f0f..6c29db1b 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -31,6 +31,7 @@ import { createOutputView } from './outputPanel/outputView.ts'; import { createPanelHost } from './panel/panelHost.ts'; import { createAgentsView } from './agents/agentsView.ts'; import { installAgentWorkbench } from './agentFirst/agentWorkbench.ts'; +import { askAgentCommands, createAskAgent } from './agentFirst/askAgent.ts'; import { displayPath } from './agentFirst/chatModel.ts'; import { createEditReviewer } from './agents/editReview.ts'; import { registerAgentCommands } from './agents/agentCommands.ts'; @@ -217,6 +218,11 @@ function editorGroup(): Promise { state: () => ({ enabled: runView.canAnalyse(), lastKind: runView.lastKind() }), run: (kind, path) => { runView.analyse(kind, path); }, }, + // #514: "Ask agent" from a function's lens and the editor's context menu. + askAgent: { + functionAt: (path, line) => askAgent.functionAt(path, line), + ask: (path, fn, intent) => void askAgent.aboutFunction(path, fn, intent), + }, titleActions: (tabId) => editorTitleButtons(tabId), }); editors.setSceneShown(!workbench.sceneArea.hidden); @@ -802,6 +808,8 @@ const problemsView = createProblemsView(panelHost, { group.quickFix(); }), rightInset: () => (workbench.sceneArea.hidden ? 0 : workbench.sceneArea.getBoundingClientRect().width), + // #514: a metric row's "Ask Agent about This Function". + askAgent: (problem, intent) => void askAgent.aboutProblem(problem, intent), onCounts: (counts) => workbench.setProblemCounts(counts.error, counts.warning), }); workbench.onProblemsClick(() => (panelHost.isShowing('problems') ? panelHost.hide() : problemsView.show())); @@ -1381,6 +1389,16 @@ const agentWorkbench = installAgentWorkbench({ registry.execute('workspace.openFolder'); }, }); +// #514 (O12): drafts about the measured functions in the active chat, never sent. +const askAgent = createAskAgent({ + snapshot: () => metricSnapshot, + thresholds: () => metricThresholds, + draft: (text) => agentWorkbench.draftInChat(text), + onStatus: (message) => workbench.setStatus(message), +}); +for (const command of askAgentCommands(askAgent)) { + registry.register(command); +} function agentFolderChanged(root: string | null): void { agentRoot = root; agentWorkbench.folderChanged(); diff --git a/apps/ide/src/renderer/problems/problemsView.ts b/apps/ide/src/renderer/problems/problemsView.ts index efe6868b..98d30e9f 100644 --- a/apps/ide/src/renderer/problems/problemsView.ts +++ b/apps/ide/src/renderer/problems/problemsView.ts @@ -1,7 +1,9 @@ import { filterProblems, groupProblems, PROBLEM_SEVERITIES, problemCounts, type Problem, type ProblemOrigin, type ProblemSeverity } from '../../shared/problems.ts'; import { copyText, el, fileIcon, icon } from '../dom.ts'; import type { PanelHost } from '../panel/panelHost.ts'; -import { showContextMenu } from '../contextMenu.ts'; +import { showContextMenu, type ContextMenuItem } from '../contextMenu.ts'; +import { t } from '../../shared/i18n/i18n.ts'; +import { canAskAbout, HOTSPOT_INTENTS, intentLabel, type HotspotIntent } from '../agentFirst/askAgent.ts'; /** * The Problems view of the bottom panel (#173): what the editor's languages @@ -9,6 +11,7 @@ import { showContextMenu } from '../contextMenu.ts'; * functions, in one list grouped by file. A row opens its file at the * problem; its context menu (#287) offers the language server's quick fixes * there. The list (shared/problems.ts) is pure; this view only draws it. + * #514: a metric row's menu also asks the agent about its function. */ export const PROBLEM_ICONS: Record = { @@ -38,6 +41,8 @@ export interface ProblemsHooks { open(problem: Problem): void; /** #287: opens the problem's file at its range and shows the quick fixes there (Monaco's Ctrl+. menu). */ quickFix?(problem: Problem): void; + /** #514: drafts a prompt about a metric problem's function in the active chat. */ + askAgent?(problem: Problem, intent: HotspotIntent): void; /** Width taken by the scene column on the right, for the context menu. */ rightInset?(): number; /** The totals changed (the status bar's counts). */ @@ -203,9 +208,18 @@ export function createProblemsView(host: PanelHost, hooks: ProblemsHooks): Probl /** #287: a problem's context menu. The metric checks are Code-XR's own and have no fixes. */ function showProblemMenu(problem: Problem, x: number, y: number): void { const quickFix = hooks.quickFix; + const askAgent = hooks.askAgent; + const ask: ContextMenuItem[] = askAgent && canAskAbout(problem) ? [{ + label: t('askAgent.menu'), + testId: 'problems-menu-ask-agent', + submenu: HOTSPOT_INTENTS.map((intent) => ({ + label: intentLabel(intent), run: () => askAgent(problem, intent), testId: `problems-menu-ask-agent-${intent}`, + })), + }] : []; showContextMenu([ { label: 'Go to Problem', run: () => hooks.open(problem), testId: 'problems-menu-open' }, { label: 'Quick Fix...', run: () => quickFix?.(problem), enabled: quickFix !== undefined && problem.origin !== 'metrics', testId: 'problems-menu-quick-fix' }, + ...ask, { separator: true }, { label: 'Copy Message', run: () => copyText(problem.message), testId: 'problems-menu-copy' }, ], x, y, { label: 'Problem', ...(hooks.rightInset ? { rightInset: hooks.rightInset } : {}) }); diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index deb6a8cf..f823d954 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -610,6 +610,18 @@ export const en = { 'settings.note.userOnly': 'Only your user settings set this: it applies to every window.', 'settings.note.folderWins': 'This folder sets its own value, which wins here.', 'settings.note.userApplies': 'Your user setting applies.', + // #514: "Ask agent" about a measured function (the prompt itself stays in English, it is for the agent). + 'category.chat': 'Chat', + 'askAgent.intent.refactor': 'Refactor to Reduce Complexity', + 'askAgent.intent.explain': 'Explain', + 'askAgent.intent.tests': 'Add Tests', + 'askAgent.command': 'Ask Agent about the Top Hotspot: {action}', + 'askAgent.menu': 'Ask Agent about This Function', + 'askAgent.lens': 'Ask agent', + 'askAgent.lensTooltip': 'Draft a prompt in the chat to refactor \'{name}\' (you review it before sending)', + 'askAgent.drafted': 'Drafted a prompt about \'{name}\' in the chat: review it, then press Send.', + 'askAgent.noFunction': 'Code-XR has not measured a function here. Analyse the project to measure its functions.', + 'askAgent.noHotspot': 'No hotspot yet: analyse the project to measure its functions.', }; export type MessageKey = keyof typeof en; diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index d02ce7dc..9d2ee0c8 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -613,4 +613,16 @@ export const es: Readonly> = { 'settings.note.userOnly': 'Solo la configuración de usuario puede establecerlo: se aplica a todas las ventanas.', 'settings.note.folderWins': 'Esta carpeta establece su propio valor, que es el que se aplica aquí.', 'settings.note.userApplies': 'Se aplica tu configuración de usuario.', + // #514: "Preguntar al agente" por una función medida (la petición sigue en inglés: es para el agente). + 'category.chat': 'Chat', + 'askAgent.intent.refactor': 'Refactorizar para reducir la complejidad', + 'askAgent.intent.explain': 'Explicar', + 'askAgent.intent.tests': 'Añadir pruebas', + 'askAgent.command': 'Preguntar al agente por el punto crítico principal: {action}', + 'askAgent.menu': 'Preguntar al agente por esta función', + 'askAgent.lens': 'Preguntar al agente', + 'askAgent.lensTooltip': 'Redactar en el chat una petición para refactorizar \'{name}\' (la revisas antes de enviarla)', + 'askAgent.drafted': 'Petición sobre \'{name}\' redactada en el chat: revísala y pulsa Enviar.', + 'askAgent.noFunction': 'Code-XR no ha medido ninguna función aquí. Analiza el proyecto para medir sus funciones.', + 'askAgent.noHotspot': 'Aún no hay puntos críticos: analiza el proyecto para medir sus funciones.', }; diff --git a/apps/ide/test/askAgent.test.ts b/apps/ide/test/askAgent.test.ts new file mode 100644 index 00000000..c4ca5b2c --- /dev/null +++ b/apps/ide/test/askAgent.test.ts @@ -0,0 +1,180 @@ +import { afterEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { + codeSpan, compareHotspots, DEFAULT_HOTSPOT_INTENT, functionAtLine, functionForProblem, HOTSPOT_INTENTS, hotspotPrompt, hotspotTarget, + isHotspotIntent, metricLines, topHotspot, type HotspotTarget, +} from '@codexr/core/agent-prompts/hotspotPrompt'; +import type { FileFunctionMetrics, FunctionMetric, Problem } from '../src/shared/problems.ts'; +import { metricProblems } from '../src/shared/problems.ts'; +import { askAgentCommands, canAskAbout, createAskAgent, intentLabel } from '../src/renderer/agentFirst/askAgent.ts'; +import { setLocale } from '../src/shared/i18n/i18n.ts'; + +const fn = (name: string, lineStart: number, lineEnd: number, complexity: number, lineCount = 10, parameters = 1): FunctionMetric => + ({ name, lineStart, lineEnd, complexity, lineCount, parameters }); + +const FILES: FileFunctionMetrics[] = [ + { path: 'src/a.ts', functions: [fn('outer', 1, 40, 4, 30, 2), fn('inner', 10, 20, 2, 8, 0), fn('tail', 50, 50, 1, 1, 0)] }, + { path: 'src/b.ts', functions: [fn('parseConfig', 12, 88, 27, 64, 3), fn('small', 90, 95, 2)] }, +]; + +const TARGET: HotspotTarget = { path: 'src/b.ts', name: 'parseConfig', lineStart: 12, lineEnd: 88, complexity: 27, lineCount: 64, parameters: 3 }; + +afterEach(() => setLocale('en')); + +describe('hotspot prompt templates (#514, core/agent-prompts)', () => { + it('offers refactor first and as the default, then explain and tests', () => { + assert.deepEqual(HOTSPOT_INTENTS, ['refactor', 'explain', 'tests']); + assert.equal(DEFAULT_HOTSPOT_INTENT, 'refactor'); + assert.ok(isHotspotIntent('tests')); + assert.ok(!isHotspotIntent('delete')); + assert.ok(!isHotspotIntent(undefined)); + }); + + it('drafts a refactor prompt with the path, the function, its lines and its metrics', () => { + const text = hotspotPrompt(TARGET, 'refactor', { complexity: 10, lines: 50, parameters: 5 }); + assert.equal(text, [ + 'Refactor the function `parseConfig` in `src/b.ts` (lines 12-88) to reduce its complexity.', + '', + 'Code-XR measured it as:', + '- Cyclomatic complexity (CCN): 27 (over the limit of 10)', + '- Lines of code (NLOC): 64 (over the limit of 50)', + '- Parameters: 3 (limit 5)', + '', + 'Keep its behaviour and its public signature unchanged. Split it into smaller, well-named functions, flatten nested conditions and remove duplication where that helps.', + 'Explain each change, and run the project\'s existing tests afterwards if there are any.', + ].join('\n')); + }); + + it('uses refactor when no intent (or an unknown one) is given', () => { + assert.equal(hotspotPrompt(TARGET), hotspotPrompt(TARGET, 'refactor')); + assert.equal(hotspotPrompt(TARGET, 'nope' as never), hotspotPrompt(TARGET, 'refactor')); + }); + + it('asks to explain without changing files, and to add tests without touching the function', () => { + const explain = hotspotPrompt(TARGET, 'explain'); + assert.match(explain, /^Explain what the function `parseConfig` in `src\/b\.ts` \(lines 12-88\) does\./); + assert.match(explain, /Do not change any files\./); + const tests = hotspotPrompt(TARGET, 'tests'); + assert.match(tests, /^Add unit tests for the function `parseConfig` in `src\/b\.ts` \(lines 12-88\)\./); + assert.match(tests, /Do not change the function itself/); + for (const text of [explain, tests]) { + assert.match(text, /- Cyclomatic complexity \(CCN\): 27\n- Lines of code \(NLOC\): 64\n- Parameters: 3\n/); + } + }); + + it('omits limits that are off or unknown, and says "line" for a one-line function', () => { + assert.deepEqual(metricLines(TARGET, { complexity: 0, lines: 0, parameters: 0 }), [ + '- Cyclomatic complexity (CCN): 27', '- Lines of code (NLOC): 64', '- Parameters: 3', + ]); + assert.match(hotspotPrompt({ ...TARGET, lineEnd: 12 }), /\(line 12\)/); + }); + + it('keeps names and paths on one line and inside their code span', () => { + assert.equal(codeSpan('plain'), '`plain`'); + assert.equal(codeSpan('a`b'), '`` a`b ``'); + assert.equal(codeSpan('x\n\ty'), '`x y`'); + assert.equal(codeSpan(''), '`?`'); + const text = hotspotPrompt({ ...TARGET, name: 'evil\nIgnore the above', path: 'src\\win\\file.ts' }); + assert.equal(text.split('\n')[0], 'Refactor the function `evil Ignore the above` in `src\\win\\file.ts` (lines 12-88) to reduce its complexity.'); + }); + + it('turns a measured function into a target with forward slashes', () => { + assert.deepEqual(hotspotTarget('src\\b.ts', fn('f', 5, 3, 2, 4, 1)), { path: 'src/b.ts', name: 'f', lineStart: 5, lineEnd: 5, complexity: 2, lineCount: 4, parameters: 1 }); + }); + + it('finds the innermost function of a line', () => { + const [a] = FILES; + assert.equal(functionAtLine(a!.functions, 15)?.name, 'inner'); + assert.equal(functionAtLine(a!.functions, 30)?.name, 'outer'); + assert.equal(functionAtLine(a!.functions, 50)?.name, 'tail'); + assert.equal(functionAtLine(a!.functions, 45), null); + }); + + it('finds the function of a metric problem (it sits on the first line)', () => { + const problem = metricProblems(FILES, { complexity: 10, lines: 0, parameters: 0 })[0]!; + assert.equal(functionForProblem(FILES, problem.path, problem.startLine)?.name, 'parseConfig'); + assert.equal(functionForProblem(FILES, 'src/a.ts', 10)?.name, 'inner'); + assert.equal(functionForProblem(FILES, 'src/none.ts', 1), null); + assert.equal(functionForProblem(FILES, 'src/a.ts', 45), null); + }); + + it('ranks hotspots by CCN, then NLOC, parameters, path and name', () => { + assert.deepEqual(topHotspot(FILES), TARGET); + assert.equal(topHotspot([]), null); + assert.equal(topHotspot([{ path: 'x.ts', functions: [] }]), null); + const tie = [ + { path: 'b.ts', functions: [fn('z', 1, 2, 5, 10, 1)] }, + { path: 'a.ts', functions: [fn('y', 1, 2, 5, 10, 1), fn('longer', 3, 9, 5, 11, 0)] }, + ]; + assert.equal(topHotspot(tie)?.name, 'longer'); + assert.ok(compareHotspots(hotspotTarget('a.ts', fn('y', 1, 2, 5)), hotspotTarget('b.ts', fn('z', 1, 2, 5))) < 0); + }); +}); + +describe('askAgent (#514)', () => { + function setup(drafted = true): { ask: ReturnType; drafts: string[]; statuses: string[] } { + const drafts: string[] = []; + const statuses: string[] = []; + const ask = createAskAgent({ + snapshot: () => ({ root: '/p', files: FILES }), + thresholds: () => ({ complexity: 10, lines: 50, parameters: 5 }), + draft: async (text) => { drafts.push(text); return drafted; }, + onStatus: (message) => statuses.push(message), + }); + return { ask, drafts, statuses }; + } + + it('drafts the refactor prompt of the top hotspot by default, and never anything else', async () => { + const { ask, drafts, statuses } = setup(); + assert.equal(await ask.aboutTopHotspot(), true); + assert.deepEqual(drafts, [hotspotPrompt(TARGET, 'refactor', { complexity: 10, lines: 50, parameters: 5 })]); + assert.deepEqual(statuses, ['Drafted a prompt about \'parseConfig\' in the chat: review it, then press Send.']); + }); + + it('asks about the function at a line, a problem, or a given function', async () => { + const { ask, drafts } = setup(); + await ask.aboutLine('src/a.ts', 15, 'explain'); + const problem = metricProblems(FILES, { complexity: 10, lines: 0, parameters: 0 })[0]!; + await ask.aboutProblem(problem, 'tests'); + await ask.aboutFunction('src/a.ts', FILES[0]!.functions[0]!); + assert.match(drafts[0]!, /^Explain what the function `inner` in `src\/a\.ts` \(lines 10-20\)/); + assert.match(drafts[1]!, /^Add unit tests for the function `parseConfig`/); + assert.match(drafts[2]!, /^Refactor the function `outer`/); + assert.equal(ask.functionAt('src/a.ts', 45), null); + }); + + it('reports instead of drafting when nothing is measured there', async () => { + const { ask, drafts, statuses } = setup(); + assert.equal(await ask.aboutLine('src/a.ts', 45), false); + const editorProblem: Problem = { path: 'src/b.ts', severity: 'error', message: 'x', source: 'ts', origin: 'editor', startLine: 12, startColumn: 1, endLine: 12, endColumn: 2 }; + assert.equal(canAskAbout(editorProblem), false); + assert.equal(await ask.aboutProblem(editorProblem), false); + const empty = createAskAgent({ snapshot: () => null, thresholds: () => null, draft: async () => true, onStatus: (message) => statuses.push(message) }); + assert.equal(await empty.aboutTopHotspot(), false); + assert.deepEqual(drafts, []); + assert.equal(statuses.length, 3); + assert.match(statuses[2]!, /No hotspot yet/); + }); + + it('says nothing when no chat could take the draft (the workbench reported why)', async () => { + const { ask, statuses } = setup(false); + assert.equal(await ask.aboutTopHotspot(), false); + assert.deepEqual(statuses, []); + }); + + it('registers chat.askAboutHotspot (refactor) and one palette command per other intent, in both languages', async () => { + const { ask, drafts } = setup(); + const commands = askAgentCommands(ask); + assert.deepEqual(commands.map((command) => command.id), ['chat.askAboutHotspot', 'chat.askAboutHotspot.explain', 'chat.askAboutHotspot.tests']); + assert.equal(commands[0]!.title, 'Ask Agent about the Top Hotspot: Refactor to Reduce Complexity'); + await commands[2]!.run(); + await new Promise((resolve) => setImmediate(resolve)); + assert.match(drafts[0]!, /^Add unit tests/); + setLocale('es'); + assert.equal(intentLabel('explain'), 'Explicar'); + assert.equal(askAgentCommands(ask)[0]!.category, 'Chat'); + // The prompt itself stays in English: it is for the agent. + await ask.aboutTopHotspot(); + assert.match(drafts[1]!, /^Refactor the function/); + }); +}); diff --git a/apps/ide/tsconfig.web.json b/apps/ide/tsconfig.web.json index f465a127..2e0e3ae6 100644 --- a/apps/ide/tsconfig.web.json +++ b/apps/ide/tsconfig.web.json @@ -1,5 +1,5 @@ { - "//": "Renderer: DOM types only. No Node types, so a Node API used here fails the type check. Of the core it may use only the pure core/metrics (#173/#178), core/xr (#19) and core/analysis/languages (#398).", + "//": "Renderer: DOM types only. No Node types, so a Node API used here fails the type check. Of the core it may use only the pure core/metrics (#173/#178), core/xr (#19) and core/analysis/languages (#398) and core/agent-prompts (#514).", "extends": "./tsconfig.base.json", "compilerOptions": { "lib": ["ES2023", "DOM", "DOM.Iterable"], @@ -8,7 +8,8 @@ "@codexr/local-models/*": ["../../packages/local-models/src/*"], "@codexr/core/metrics/*": ["./.core-types/core/metrics/*"], "@codexr/core/xr/*": ["./.core-types/core/xr/*"], - "@codexr/core/analysis/languages/*": ["./.core-types/core/analysis/languages/*"] + "@codexr/core/analysis/languages/*": ["./.core-types/core/analysis/languages/*"], + "@codexr/core/agent-prompts/*": ["./.core-types/core/agent-prompts/*"] } }, "include": ["src/renderer/**/*.ts", "src/shared/**/*.ts", "src/bridge/**/*.ts", "src/sceneBridge/**/*.ts"] From 22f2763093d551f86ab8c378229f72f6f4def7b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:28:28 +0000 Subject: [PATCH 18/74] fix(ide): crash-safe saves, recent list, folder switches and terminal starts (#507) - Editor saves (Rust core and the Node workspace) write a temporary file in the same folder and rename it, keeping the permissions; symlinks, hard links, files of another owner and Windows hidden/system files are written in place; Windows renames are retried, then written in place. - recent.rs holds its lock across read-modify-write, writes atomically and changes the list in memory only after the write succeeded. - host.workspace.set opens the new folder before dropping the old one and cancels the window's running search; a closed window cancels it too. - A terminal whose reader or writer cannot be created kills its shell; the per-window limit is checked and reserved under one lock. --- apps/ide/src-tauri/src/atomic_file.rs | 282 +++++++++++++++++++++ apps/ide/src-tauri/src/main.rs | 1 + apps/ide/src-tauri/src/native.rs | 62 ++++- apps/ide/src-tauri/src/recent.rs | 55 +++- apps/ide/src-tauri/src/search.rs | 6 + apps/ide/src-tauri/src/terminal.rs | 123 ++++++++- apps/ide/src-tauri/src/workspace.rs | 7 +- apps/ide/src/main/workspace/atomicWrite.ts | 111 ++++++++ apps/ide/src/main/workspace/workspace.ts | 4 +- apps/ide/test/atomicWrite.test.ts | 70 +++++ 10 files changed, 690 insertions(+), 31 deletions(-) create mode 100644 apps/ide/src-tauri/src/atomic_file.rs create mode 100644 apps/ide/src/main/workspace/atomicWrite.ts create mode 100644 apps/ide/test/atomicWrite.test.ts diff --git a/apps/ide/src-tauri/src/atomic_file.rs b/apps/ide/src-tauri/src/atomic_file.rs new file mode 100644 index 00000000..bbaa8c40 --- /dev/null +++ b/apps/ide/src-tauri/src/atomic_file.rs @@ -0,0 +1,282 @@ +//! Crash-safe file writes (#507): the new bytes go to a temporary file in the +//! same folder, which is flushed to disk and then renamed over the target, so +//! a full disk, a crash or a power cut leaves either the old file or the new +//! one, never a truncated one. `fs::write` truncated the file first. +//! +//! The rename is not used where it would change what the file is: a symlink +//! (the link would become a plain file), a file with other hard links (they +//! would keep the old content), a file owned by someone else (the new file +//! would be ours), a Windows hidden or system file (the attributes would go), +//! or a folder where no new file may be created. Those are written in place, +//! as before. On Windows a rename over a file another program holds open +//! (an indexer, an antivirus) fails for a moment: it is retried, then written +//! in place. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, ErrorKind, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// How the file was written. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Written { + /// A temporary file renamed over the target. + Replaced, + /// The target itself, truncated and written (the cases listed above). + InPlace, +} + +static NEXT_TEMPORARY: AtomicU64 = AtomicU64::new(0); + +/// Writes `bytes` to `path` (created if missing), atomically where it can. +pub fn write_file(path: &Path, bytes: &[u8]) -> io::Result { + let existing = match fs::symlink_metadata(path) { + Ok(metadata) => Some(metadata), + Err(error) if error.kind() == ErrorKind::NotFound => None, + Err(error) => return Err(error), + }; + if existing.as_ref().is_some_and(|metadata| must_write_in_place(path, metadata)) { + return write_in_place(path, bytes); + } + let (temporary, mut file) = match create_temporary(path) { + Ok(created) => created, + // A folder that takes no new file, where the file itself may still be writable. + Err(error) if existing.is_some() && error.kind() == ErrorKind::PermissionDenied => return write_in_place(path, bytes), + Err(error) => return Err(error), + }; + let prepared = prepare(&mut file, &temporary, existing.as_ref(), bytes); + drop(file); + match prepared { + Ok(true) => {} + Ok(false) => { + let _ = fs::remove_file(&temporary); + return write_in_place(path, bytes); + } + Err(error) => { + let _ = fs::remove_file(&temporary); + return Err(error); + } + } + match rename_with_retry(&temporary, path) { + Ok(()) => { + sync_folder(path); + Ok(Written::Replaced) + } + Err(error) => { + let _ = fs::remove_file(&temporary); + if existing.is_some() { + write_in_place(path, bytes) + } else { + Err(error) + } + } + } +} + +fn write_in_place(path: &Path, bytes: &[u8]) -> io::Result { + let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(path)?; + file.write_all(bytes)?; + file.sync_data()?; + Ok(Written::InPlace) +} + +/// A new, empty file beside `path`, hidden on Unix (a leading dot) and unique to this write. +fn create_temporary(path: &Path) -> io::Result<(PathBuf, File)> { + let folder = path.parent().filter(|folder| !folder.as_os_str().is_empty()).unwrap_or(Path::new(".")); + loop { + let n = NEXT_TEMPORARY.fetch_add(1, Ordering::Relaxed); + let temporary = folder.join(format!(".codexr-save-{}-{n}.tmp", std::process::id())); + match OpenOptions::new().write(true).create_new(true).open(&temporary) { + Ok(file) => return Ok((temporary, file)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } +} + +/// Writes and flushes the temporary file with the target's permissions; false when it cannot +/// take the target's place (another owner, Unix), so the caller writes in place. +fn prepare(file: &mut File, temporary: &Path, existing: Option<&fs::Metadata>, bytes: &[u8]) -> io::Result { + file.write_all(bytes)?; + if let Some(metadata) = existing { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let created = file.metadata()?; + if created.uid() != metadata.uid() || created.gid() != metadata.gid() { + return Ok(false); + } + } + fs::set_permissions(temporary, metadata.permissions())?; + } + file.sync_all()?; + Ok(true) +} + +fn must_write_in_place(path: &Path, metadata: &fs::Metadata) -> bool { + if metadata.file_type().is_symlink() { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let _ = path; + metadata.nlink() > 1 + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + const HIDDEN: u32 = 0x2; + const SYSTEM: u32 = 0x4; + metadata.file_attributes() & (HIDDEN | SYSTEM) != 0 || link_count(path).is_none_or(|links| links > 1) + } + #[cfg(not(any(unix, windows)))] + { + let _ = path; + false + } +} + +/// The number of hard links of a Windows file (std reports it on nightly only). +#[cfg(windows)] +fn link_count(path: &Path) -> Option { + use std::os::windows::ffi::OsStrExt; + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, + }; + let wide: Vec = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect(); + // SAFETY: `wide` is NUL-terminated and outlives the call; the handle is closed below. + let handle = unsafe { + CreateFileW( + wide.as_ptr(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + std::ptr::null_mut(), + ) + }; + if handle == INVALID_HANDLE_VALUE { + return None; + } + // SAFETY: an all-zero BY_HANDLE_FILE_INFORMATION is valid, and `handle` is open. + let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; + let ok = unsafe { GetFileInformationByHandle(handle, &mut info) }; + unsafe { CloseHandle(handle) }; + (ok != 0).then_some(info.nNumberOfLinks) +} + +/// Windows refuses to replace a file another process holds without FILE_SHARE_DELETE +/// (access denied, sharing or lock violation) until it lets go: a few tries, about 0.3 s. +fn rename_with_retry(from: &Path, to: &Path) -> io::Result<()> { + let mut delay = std::time::Duration::from_millis(10); + for _ in 0..5 { + match fs::rename(from, to) { + Err(error) if is_transient(&error) => { + std::thread::sleep(delay); + delay *= 2; + } + result => return result, + } + } + fs::rename(from, to) +} + +fn is_transient(error: &io::Error) -> bool { + // ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION. + cfg!(windows) && matches!(error.raw_os_error(), Some(5 | 32 | 33)) +} + +/// The rename is durable once the folder's entry is on disk (Unix; Windows has no such call). +fn sync_folder(path: &Path) { + #[cfg(unix)] + if let Some(folder) = path.parent().filter(|folder| !folder.as_os_str().is_empty()) { + if let Ok(folder) = File::open(folder) { + let _ = folder.sync_all(); + } + } + #[cfg(not(unix))] + let _ = path; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::workspace::tests::Scratch; + + fn leftovers(dir: &Path) -> Vec { + fs::read_dir(dir).unwrap().filter_map(Result::ok).map(|entry| entry.file_name().to_string_lossy().into_owned()).filter(|name| name.starts_with(".codexr-save-")).collect() + } + + #[test] + fn replaces_a_file_through_a_temporary_and_leaves_nothing_behind() { + let dir = Scratch::new("atomic-replace"); + let file = dir.0.join("a.txt"); + fs::write(&file, "old content that is longer").unwrap(); + assert_eq!(write_file(&file, b"new").unwrap(), Written::Replaced); + assert_eq!(fs::read_to_string(&file).unwrap(), "new"); + assert_eq!(write_file(&dir.0.join("created.txt"), b"fresh").unwrap(), Written::Replaced); + assert_eq!(fs::read_to_string(dir.0.join("created.txt")).unwrap(), "fresh"); + assert!(leftovers(&dir.0).is_empty()); + } + + #[test] + fn a_failed_write_keeps_the_old_file_whole() { + let dir = Scratch::new("atomic-fail"); + // The target is a folder: the rename and the in-place write both fail, and nothing is left behind. + let folder = dir.0.join("taken"); + fs::create_dir(&folder).unwrap(); + fs::write(folder.join("inside.txt"), "kept").unwrap(); + assert!(write_file(&folder, b"x").is_err()); + assert_eq!(fs::read_to_string(folder.join("inside.txt")).unwrap(), "kept"); + assert!(leftovers(&dir.0).is_empty()); + // A missing folder: no temporary can be made, and no file appears. + assert!(write_file(&dir.0.join("missing").join("a.txt"), b"x").is_err()); + } + + #[cfg(unix)] + #[test] + fn keeps_the_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = Scratch::new("atomic-mode"); + let file = dir.0.join("run.sh"); + fs::write(&file, "#!/bin/sh\n").unwrap(); + fs::set_permissions(&file, fs::Permissions::from_mode(0o750)).unwrap(); + assert_eq!(write_file(&file, b"#!/bin/sh\necho hi\n").unwrap(), Written::Replaced); + assert_eq!(fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o750); + } + + #[cfg(unix)] + #[test] + fn writes_symlinks_and_hard_links_in_place() { + let dir = Scratch::new("atomic-links"); + let target = dir.0.join("target.txt"); + fs::write(&target, "old").unwrap(); + let link = dir.0.join("link.txt"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert_eq!(write_file(&link, b"through the link").unwrap(), Written::InPlace); + assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "still a link"); + assert_eq!(fs::read_to_string(&target).unwrap(), "through the link"); + + let hard = dir.0.join("hard.txt"); + fs::hard_link(&target, &hard).unwrap(); + assert_eq!(write_file(&target, b"both names").unwrap(), Written::InPlace); + assert_eq!(fs::read_to_string(&hard).unwrap(), "both names", "the other name sees the new content"); + assert!(leftovers(&dir.0).is_empty()); + } + + #[cfg(windows)] + #[test] + fn writes_hard_links_in_place_on_windows() { + let dir = Scratch::new("atomic-links"); + let target = dir.0.join("target.txt"); + fs::write(&target, "old").unwrap(); + assert_eq!(write_file(&target, b"alone").unwrap(), Written::Replaced); + let hard = dir.0.join("hard.txt"); + fs::hard_link(&target, &hard).unwrap(); + assert_eq!(write_file(&target, b"both names").unwrap(), Written::InPlace); + assert_eq!(fs::read_to_string(&hard).unwrap(), "both names"); + } +} diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index c60ae1da..e1993038 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -19,6 +19,7 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod assets; +mod atomic_file; mod call_order; mod collation; mod host; diff --git a/apps/ide/src-tauri/src/native.rs b/apps/ide/src-tauri/src/native.rs index 4f6fe225..d179f815 100644 --- a/apps/ide/src-tauri/src/native.rs +++ b/apps/ide/src-tauri/src/native.rs @@ -139,6 +139,20 @@ fn home_dir() -> PathBuf { std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).unwrap_or_else(std::env::temp_dir) } +/// #507: the folder `label` has open becomes `root` (none: no folder). The new folder is opened +/// before the old one is let go, so one that cannot be opened keeps the window on the folder +/// (and watcher) it had; once it changes, the window's running search, over the old folder, stops. +fn switch_folder(folders: &Mutex>, searches: &Searches, label: &str, root: Option<&str>) -> Result<(), String> { + let opened = root.map(|root| Workspace::open(&PathBuf::from(root))).transpose()?; + let _ = searches.cancel(label, &Value::Null); + let mut folders = folders.lock().unwrap(); + match opened { + Some(workspace) => folders.insert(label.to_string(), Open { workspace: Arc::new(workspace), watcher: None }), + None => folders.remove(label), + }; + Ok(()) +} + /// Argument `index` of a call; a missing or `{"$undefined": true}` one is null (src/shared/jsonCodec.ts). fn arg(args: &[Value], index: usize) -> &Value { static NULL: Value = Value::Null; @@ -196,17 +210,13 @@ impl Native { /// `host.workspace.set` from the sidecar: the folder a window has open now, or none. pub fn set_workspace(&self, label: &str, root: Option<&str>) -> Result { - let mut folders = self.folders.lock().unwrap(); - folders.remove(label); - if let Some(root) = root { - let workspace = Workspace::open(&PathBuf::from(root))?; - folders.insert(label.to_string(), Open { workspace: Arc::new(workspace), watcher: None }); - } + switch_folder(&self.folders, &self.searches, label, root)?; Ok(Value::Null) } - /// A window is gone: its folder and its terminals with it. + /// A window is gone: its folder, its search and its terminals with it. pub fn window_destroyed(&self, label: &str) { + let _ = self.searches.cancel(label, &Value::Null); self.folders.lock().unwrap().remove(label); self.terminals.kill_owned_by(label); } @@ -327,9 +337,7 @@ impl Native { let (Some(cols), Some(rows)) = (dimension(cols), dimension(rows)) else { return Err("Invalid terminal size.".into()); }; - if self.terminals.count_of(label) >= crate::terminal::MAX_TERMINALS_PER_WINDOW { - return Err(format!("At most {} terminals per window.", crate::terminal::MAX_TERMINALS_PER_WINDOW)); - } + // The per-window limit is checked and the place taken in one step by `Terminals::start` (#507). let profile = self.profiles.resolve(profile_id)?; self.start(Some(label), &profile, profile.args.clone(), None, cwd, cols, rows, false) } @@ -417,4 +425,38 @@ mod tests { thread.join().unwrap(); assert!(gate.wait(Duration::from_millis(0)), "open for good"); } + + #[test] + fn a_folder_that_fails_to_open_keeps_the_previous_one_and_a_switch_stops_the_search() { + use crate::workspace::tests::Scratch; + let first = Scratch::new("native-first"); + let second = Scratch::new("native-second"); + first.write("a.txt", "needle\n"); + let folders = Mutex::new(HashMap::new()); + let searches = Arc::new(Searches::default()); + let root = |dir: &Scratch| dir.0.to_string_lossy().into_owned(); + let current = |folders: &Mutex>| folders.lock().unwrap().get("w").map(|open| open.workspace.root.clone()); + switch_folder(&folders, &searches, "w", Some(&root(&first))).unwrap(); + + let missing = first.0.join("missing").to_string_lossy().into_owned(); + assert!(switch_folder(&folders, &searches, "w", Some(&missing)).is_err()); + assert_eq!(current(&folders), Some(first.0.clone()), "still on the folder it had"); + + // The search's events wait until released, so it is still running when the folder changes. + let (release, released) = std::sync::mpsc::channel::<()>(); + let released = Mutex::new(released); + let workspace = folders.lock().unwrap().get("w").unwrap().workspace.clone(); + let query = json!({ "pattern": "needle", "isRegex": false, "matchCase": false, "wholeWord": false, "include": "", "exclude": "" }); + searches.start("w", workspace, &json!(1), &query, move |_, _| { + let _ = released.lock().unwrap().recv_timeout(Duration::from_secs(10)); + }); + assert!(searches.is_running("w")); + switch_folder(&folders, &searches, "w", Some(&root(&second))).unwrap(); + assert!(!searches.is_running("w"), "the search over the old folder is stopped"); + assert_eq!(current(&folders), Some(second.0.clone())); + drop(release); + + switch_folder(&folders, &searches, "w", None).unwrap(); + assert_eq!(current(&folders), None); + } } diff --git a/apps/ide/src-tauri/src/recent.rs b/apps/ide/src-tauri/src/recent.rs index 05993ab8..ac961105 100644 --- a/apps/ide/src-tauri/src/recent.rs +++ b/apps/ide/src-tauri/src/recent.rs @@ -48,30 +48,33 @@ impl RecentFolders { self.list.lock().unwrap().clone() } - fn update(&self, next: Vec) -> Result { + /// #507: changes the list under its lock, from reading it to writing the file, so two + /// changes at once cannot lose one; the file is replaced atomically (atomic_file.rs), and + /// the list in memory changes only once it is on disk. + fn update(&self, change: impl FnOnce(&[String]) -> Vec) -> Result { let Some(file) = &self.file else { return Ok(json!([])) }; - *self.list.lock().unwrap() = next.clone(); + let mut list = self.list.lock().unwrap(); + let next = change(&list); if let Some(parent) = file.parent() { std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; } let text = format!("{}\n", serde_json::to_string_pretty(&json!({ "folders": next })).map_err(|error| error.to_string())?); - std::fs::write(file, text).map_err(|error| error.to_string())?; - Ok(json!(next)) + crate::atomic_file::write_file(file, text.as_bytes()).map_err(|error| error.to_string())?; + *list = next; + Ok(json!(*list)) } pub fn add(&self, folder: &str) -> Result { - let next = with_recent(&self.folders(), folder, cfg!(target_os = "linux")); - self.update(next) + self.update(|list| with_recent(list, folder, cfg!(target_os = "linux"))) } /// Drops a folder that could no longer be opened. pub fn remove(&self, folder: &str) -> Result { - let next = self.folders().into_iter().filter(|path| path != folder).collect(); - self.update(next) + self.update(|list| list.iter().filter(|path| *path != folder).cloned().collect()) } pub fn clear(&self) -> Result { - self.update(Vec::new()) + self.update(|_| Vec::new()) } /// `host.recent.*` from the sidecar; each answers the list as it is now. @@ -135,4 +138,38 @@ mod tests { assert_eq!(off.handle("recent.add", &json!({ "folder": a })).unwrap(), json!([])); assert_eq!(off.handle("recent.list", &Value::Null).unwrap(), json!([])); } + + #[test] + fn changes_at_once_lose_none_of_them() { + let dir = crate::workspace::tests::Scratch::new("recent-race"); + let file = dir.0.join("recent-folders.json"); + let recent = std::sync::Arc::new(RecentFolders::open(Some(file.clone()))); + let threads: Vec<_> = (0..MAX_RECENT_FOLDERS) + .map(|i| { + let recent = recent.clone(); + let folder = dir.0.join(format!("f{i}")).to_string_lossy().into_owned(); + std::thread::spawn(move || recent.add(&folder).unwrap()) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(recent.folders().len(), MAX_RECENT_FOLDERS); + assert_eq!(RecentFolders::open(Some(file)).folders().len(), MAX_RECENT_FOLDERS, "the file has every one too"); + } + + #[test] + fn a_failed_write_leaves_the_list_as_it_was() { + let dir = crate::workspace::tests::Scratch::new("recent-fail"); + let file = dir.0.join("recent-folders.json"); + let recent = RecentFolders::open(Some(file.clone())); + let a = dir.0.join("a").to_string_lossy().into_owned(); + recent.add(&a).unwrap(); + // The file's place is taken by a folder: the write fails. + std::fs::remove_file(&file).unwrap(); + std::fs::create_dir(&file).unwrap(); + std::fs::write(file.join("keep"), "").unwrap(); + assert!(recent.add(&dir.0.join("b").to_string_lossy()).is_err()); + assert_eq!(recent.folders(), vec![a]); + } } diff --git a/apps/ide/src-tauri/src/search.rs b/apps/ide/src-tauri/src/search.rs index 9cbe4c43..8d353c64 100644 --- a/apps/ide/src-tauri/src/search.rs +++ b/apps/ide/src-tauri/src/search.rs @@ -449,6 +449,12 @@ impl Searches { Ok(()) } + /// Whether a search of `window` is running (not cancelled nor done). + #[cfg(test)] + pub fn is_running(&self, window: &str) -> bool { + self.running.lock().unwrap().contains_key(window) + } + /// Starts a search in the background; `send` delivers an event to the window. pub fn start(self: &Arc, window: &str, workspace: Arc, search_id: &Value, query: &Value, send: impl Fn(&str, Value) + Send + 'static) { // A malformed id or query starts nothing and answers nothing. diff --git a/apps/ide/src-tauri/src/terminal.rs b/apps/ide/src-tauri/src/terminal.rs index d9b79614..560737fb 100644 --- a/apps/ide/src-tauri/src/terminal.rs +++ b/apps/ide/src-tauri/src/terminal.rs @@ -70,6 +70,9 @@ struct Live { pub struct Terminals { next_id: AtomicU64, running: Mutex>, + /// #507: per window, the terminals being started (counted against the limit until they run). + /// Locked only while `running` is, so the count and the reservation are one step. + starting: Mutex>, live: Arc, sink: Sink, } @@ -204,6 +207,41 @@ impl Utf8Stream { } } +/// A place under the per-window limit, taken by `Terminals::reserve`. +struct Reservation<'a> { + terminals: &'a Terminals, + owner: Option, +} + +impl Reservation<'_> { + /// The terminal runs: it counts as running from now on, in the same step as the place is given back. + fn run(mut self, id: u64, terminal: Running) { + let mut running = self.terminals.running.lock().unwrap(); + running.insert(id, terminal); + if let Some(owner) = self.owner.take() { + self.terminals.release(&mut self.terminals.starting.lock().unwrap(), &owner); + } + } +} + +impl Drop for Reservation<'_> { + fn drop(&mut self) { + if let Some(owner) = self.owner.take() { + let _running = self.terminals.running.lock().unwrap(); + self.terminals.release(&mut self.terminals.starting.lock().unwrap(), &owner); + } + } +} + +/// `result`, or its error once the child is killed and reaped. +fn or_kill(result: Result, child: &mut dyn portable_pty::Child) -> Result { + result.map_err(|error| { + let _ = child.kill(); + let _ = child.wait(); + format!("Could not open a terminal: {error}") + }) +} + enum Message { Data(String), Eof, @@ -212,20 +250,43 @@ enum Message { impl Terminals { pub fn new(sink: Sink) -> Self { - Self { next_id: AtomicU64::new(1), running: Mutex::new(HashMap::new()), live: Arc::new(Live::default()), sink } + Self { next_id: AtomicU64::new(1), running: Mutex::new(HashMap::new()), starting: Mutex::new(HashMap::new()), live: Arc::new(Live::default()), sink } + } + + /// #507: checks the per-window limit and takes a place under it in one step, so two + /// terminals started at once cannot both pass a check made before either runs. The + /// place is given back when the reservation is dropped (the start failed) or turned + /// into a running terminal. + fn reserve(&self, owner: Option<&str>) -> Result, String> { + let Some(owner) = owner else { return Ok(Reservation { terminals: self, owner: None }) }; + let running = self.running.lock().unwrap(); + let mut starting = self.starting.lock().unwrap(); + let live = running.values().filter(|running| running.owner.as_deref() == Some(owner)).count(); + let pending = starting.get(owner).copied().unwrap_or(0); + if live + pending >= MAX_TERMINALS_PER_WINDOW { + return Err(format!("At most {MAX_TERMINALS_PER_WINDOW} terminals per window.")); + } + *starting.entry(owner.to_string()).or_default() += 1; + Ok(Reservation { terminals: self, owner: Some(owner.to_string()) }) + } + + fn release(&self, starting: &mut HashMap, owner: &str) { + if let Some(count) = starting.get_mut(owner) { + *count = count.saturating_sub(1); + if *count == 0 { + starting.remove(owner); + } + } } + #[cfg(test)] pub fn count_of(&self, owner: &str) -> usize { self.running.lock().unwrap().values().filter(|running| running.owner.as_deref() == Some(owner)).count() } /// Starts a terminal; returns its id and process id. The caller checked the profile, size and folder. pub fn start(self: &Arc, spawn: Spawn) -> Result<(u64, Option), String> { - if let Some(owner) = &spawn.owner { - if self.count_of(owner) >= MAX_TERMINALS_PER_WINDOW { - return Err(format!("At most {MAX_TERMINALS_PER_WINDOW} terminals per window.")); - } - } + let reservation = self.reserve(spawn.owner.as_deref())?; let pair = native_pty_system() .openpty(PtySize { rows: spawn.rows, cols: spawn.cols, pixel_width: 0, pixel_height: 0 }) .map_err(|error| format!("Could not open a terminal: {error}"))?; @@ -241,8 +302,9 @@ impl Terminals { drop(pair.slave); let pid = child.process_id(); let killer = child.clone_killer(); - let mut reader = pair.master.try_clone_reader().map_err(|error| error.to_string())?; - let mut writer = pair.master.take_writer().map_err(|error| error.to_string())?; + // #507: a terminal that cannot be read or written is no terminal: its shell must not outlive the error. + let mut reader = or_kill(pair.master.try_clone_reader(), child.as_mut())?; + let mut writer = or_kill(pair.master.take_writer(), child.as_mut())?; let id = self.next_id.fetch_add(1, Ordering::Relaxed); let (input, inputs) = mpsc::channel::>(); let (messages, received) = mpsc::channel::(); @@ -307,7 +369,7 @@ impl Terminals { let _ = messages.send(Message::Exit(code)); }); *self.live.count.lock().unwrap() += 1; - self.running.lock().unwrap().insert(id, Running { owner: spawn.owner.clone(), input, master: pair.master, killer }); + reservation.run(id, Running { owner: spawn.owner.clone(), input, master: pair.master, killer }); let this = self.clone(); let (owner, notify) = (spawn.owner, spawn.notify); std::thread::spawn(move || this.pump(id, owner, notify, received)); @@ -488,6 +550,49 @@ mod tests { assert_eq!(stream.finish(), "\u{FFFD}"); } + #[test] + fn the_per_window_limit_is_checked_and_taken_in_one_step() { + let terminals = Arc::new(Terminals::new(Arc::new(|_, _, _| {}))); + // Starts at once from many threads: exactly the limit gets a place. + let tried = Arc::new(std::sync::Barrier::new(MAX_TERMINALS_PER_WINDOW * 2)); + let threads: Vec<_> = (0..MAX_TERMINALS_PER_WINDOW * 2) + .map(|_| { + let (terminals, tried) = (terminals.clone(), tried.clone()); + std::thread::spawn(move || { + let reserved = terminals.reserve(Some("w")); + let ok = reserved.is_ok(); + // Keep the place until every thread has tried. + tried.wait(); + drop(reserved); + ok + }) + }) + .collect(); + let granted = threads.into_iter().map(|thread| thread.join().unwrap()).filter(|ok| *ok).count(); + assert_eq!(granted, MAX_TERMINALS_PER_WINDOW); + // Every failed or abandoned start gave its place back; another window and the sidecar have their own. + assert!(terminals.starting.lock().unwrap().is_empty()); + let all: Vec<_> = (0..MAX_TERMINALS_PER_WINDOW).map(|_| terminals.reserve(Some("w")).unwrap()).collect(); + assert!(terminals.reserve(Some("w")).is_err()); + assert!(terminals.reserve(Some("other")).is_ok()); + assert!(terminals.reserve(None).is_ok()); + drop(all); + assert!(terminals.reserve(Some("w")).is_ok()); + } + + #[test] + fn a_terminal_that_cannot_be_opened_kills_its_shell() { + let mut child = if cfg!(windows) { + std::process::Command::new("ping").args(["-n", "30", "127.0.0.1"]).stdout(std::process::Stdio::null()).spawn().unwrap() + } else { + std::process::Command::new("sleep").arg("30").spawn().unwrap() + }; + let result: Result<(), String> = or_kill(Err::<(), _>("no reader"), &mut child); + assert_eq!(result.unwrap_err(), "Could not open a terminal: no reader"); + assert!(child.try_wait().unwrap().is_some(), "killed and reaped"); + assert_eq!(or_kill(Ok::<_, String>(7), &mut child).unwrap(), 7); + } + #[cfg(unix)] type Seen = Arc, bool, String)>>>; diff --git a/apps/ide/src-tauri/src/workspace.rs b/apps/ide/src-tauri/src/workspace.rs index 6eabbb88..808410c9 100644 --- a/apps/ide/src-tauri/src/workspace.rs +++ b/apps/ide/src-tauri/src/workspace.rs @@ -385,7 +385,7 @@ impl Workspace { Ok(json!({ "$bytes": base64::engine::general_purpose::STANDARD.encode(bytes) })) } - /// Overwrites an existing file with `text`; refuses a folder, a text over the editor limit and, + /// Overwrites an existing file with `text` (atomically, atomic_file.rs); refuses a folder, a text over the editor limit and, /// with `expected_mtime_ms`, a file whose modification time moved (`MODIFIED_ON_DISK`). pub fn write_file(&self, relative: &Value, text: &Value, expected_mtime_ms: &Value) -> Result { let text = text.as_str().ok_or("File content must be a string.")?; @@ -407,7 +407,8 @@ impl Workspace { return Err(MODIFIED_ON_DISK.into()); } } - fs::write(&absolute, text).map_err(|error| io_error(error, "open", &absolute))?; + // #507: a temporary file renamed over it, so a full disk or a crash never leaves it truncated. + crate::atomic_file::write_file(&absolute, text.as_bytes()).map_err(|error| io_error(error, "open", &absolute))?; let after = fs::metadata(&absolute).map_err(|error| io_error(error, "stat", &absolute))?; Ok(json!({ "mtimeMs": mtime_ms(&after) })) } @@ -933,6 +934,8 @@ pub mod tests { let saved = ws.write_file(&s("a.txt"), &s("two"), &read["mtimeMs"]).unwrap(); assert_eq!(dir.read("a.txt"), "two"); assert!(saved["mtimeMs"].as_f64().is_some()); + // #507: written through a temporary file, which is gone afterwards. + assert_eq!(fs::read_dir(&dir.0).unwrap().count(), 1); assert_eq!(ws.write_file(&s("a.txt"), &s("three"), &json!(1.5)).unwrap_err(), MODIFIED_ON_DISK); assert!(ws.write_file(&s("a.txt"), &json!(3), &Value::Null).is_err()); assert!(ws.write_file(&s("a.txt"), &s("x"), &s("1")).unwrap_err().contains("must be a number")); diff --git a/apps/ide/src/main/workspace/atomicWrite.ts b/apps/ide/src/main/workspace/atomicWrite.ts new file mode 100644 index 00000000..017d2d55 --- /dev/null +++ b/apps/ide/src/main/workspace/atomicWrite.ts @@ -0,0 +1,111 @@ +import { randomBytes } from 'node:crypto'; +import type { Stats } from 'node:fs'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +/** + * #507: crash-safe saves, the Node twin of src-tauri/src/atomic_file.rs. The + * text goes to a temporary file in the same folder, flushed to disk, then + * renamed over the target: a full disk or a crash leaves the old file or the + * new one, never a truncated one (`fs.writeFile` truncated it first). + * + * Written in place instead, as before: a symlink (the link would become a + * plain file), a file with other hard links (they would keep the old text), + * a file owned by another user or group (POSIX), and a folder that takes no + * new file. On Windows a rename over a file another program holds open (an + * indexer, an antivirus) is retried for about 0.3 s, then written in place. + */ +export type WriteMode = 'replaced' | 'in-place'; + +const RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']); + +async function writeInPlace(file: string, data: string | Uint8Array): Promise { + const handle = await fs.open(file, 'w'); + try { + await handle.writeFile(data); + await handle.datasync(); + } finally { + await handle.close(); + } + return 'in-place'; +} + +function mustWriteInPlace(stats: Stats): boolean { + return stats.isSymbolicLink() || stats.nlink > 1; +} + +async function renameWithRetry(from: string, to: string, platform: NodeJS.Platform): Promise { + let delay = 10; + for (let attempt = 0; ; attempt += 1) { + try { + await fs.rename(from, to); + return; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? ''; + if (platform !== 'win32' || attempt >= 5 || !RETRY_CODES.has(code)) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, delay)); + delay *= 2; + } + } +} + +/** Writes `data` to `file` (created if missing), atomically where it can; says how. */ +export async function writeFileAtomic(file: string, data: string | Uint8Array, platform: NodeJS.Platform = process.platform): Promise { + const existing = await fs.lstat(file).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') { + return null; + } + throw error; + }); + if (existing && mustWriteInPlace(existing)) { + return writeInPlace(file, data); + } + const temporary = path.join(path.dirname(file), `.codexr-save-${process.pid}-${randomBytes(6).toString('hex')}.tmp`); + let handle: fs.FileHandle; + try { + handle = await fs.open(temporary, 'wx'); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (existing && (code === 'EACCES' || code === 'EPERM')) { + return writeInPlace(file, data); + } + throw error; + } + let takesItsPlace = true; + try { + try { + await handle.writeFile(data); + if (existing) { + if (platform !== 'win32') { + const created = await handle.stat(); + takesItsPlace = created.uid === existing.uid && created.gid === existing.gid; + } + if (takesItsPlace) { + await handle.chmod(existing.mode & 0o7777); + } + } + await handle.sync(); + } finally { + await handle.close(); + } + } catch (error) { + await fs.rm(temporary, { force: true }); + throw error; + } + if (!takesItsPlace) { + await fs.rm(temporary, { force: true }); + return writeInPlace(file, data); + } + try { + await renameWithRetry(temporary, file, platform); + return 'replaced'; + } catch (error) { + await fs.rm(temporary, { force: true }); + if (existing) { + return writeInPlace(file, data); + } + throw error; + } +} diff --git a/apps/ide/src/main/workspace/workspace.ts b/apps/ide/src/main/workspace/workspace.ts index aac25a8f..cc959628 100644 --- a/apps/ide/src/main/workspace/workspace.ts +++ b/apps/ide/src/main/workspace/workspace.ts @@ -7,6 +7,7 @@ import { childPath, isInside, parentPath, parseWorkspacePath, resolveInWorkspace import { foldersToWatch, WorkspaceWatcher } from './watcher.ts'; import { listWorkspaceFiles, type FileIndex } from './fileIndex.ts'; import { searchWorkspace, type SearchStats } from './textSearch.ts'; +import { writeFileAtomic } from './atomicWrite.ts'; import { replaceInText, type CompiledQuery } from '../../shared/searchText.ts'; /** Files above this are not sent to the editor (Monaco slows down well before). */ @@ -229,7 +230,8 @@ export class Workspace { if (expectedMtimeMs !== undefined && before.mtimeMs !== expectedMtimeMs) { throw new Error(MODIFIED_ON_DISK); } - await fs.writeFile(absolute, text, 'utf8'); + // #507: a temporary file renamed over it, so a full disk or a crash never leaves it truncated. + await writeFileAtomic(absolute, text); return { mtimeMs: (await fs.stat(absolute)).mtimeMs }; } diff --git a/apps/ide/test/atomicWrite.test.ts b/apps/ide/test/atomicWrite.test.ts new file mode 100644 index 00000000..7f6e2f13 --- /dev/null +++ b/apps/ide/test/atomicWrite.test.ts @@ -0,0 +1,70 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { writeFileAtomic } from '../src/main/workspace/atomicWrite.ts'; + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-atomic-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +function folder(name: string): string { + const dir = path.join(base, name); + fs.mkdirSync(dir, { recursive: true }); + return dir; +} + +const leftovers = (dir: string): string[] => fs.readdirSync(dir).filter((name) => name.startsWith('.codexr-save-')); + +describe('writeFileAtomic (#507)', () => { + it('replaces a file through a temporary one and leaves nothing behind', async () => { + const dir = folder('replace'); + const file = path.join(dir, 'a.txt'); + fs.writeFileSync(file, 'old content that is longer'); + assert.equal(await writeFileAtomic(file, 'new'), 'replaced'); + assert.equal(fs.readFileSync(file, 'utf8'), 'new'); + assert.equal(await writeFileAtomic(path.join(dir, 'b.txt'), 'fresh'), 'replaced'); + assert.equal(fs.readFileSync(path.join(dir, 'b.txt'), 'utf8'), 'fresh'); + assert.deepEqual(leftovers(dir), []); + }); + + it('keeps the old file whole when the write fails', async () => { + const dir = folder('fail'); + const taken = path.join(dir, 'taken'); + fs.mkdirSync(taken); + fs.writeFileSync(path.join(taken, 'inside.txt'), 'kept'); + await assert.rejects(writeFileAtomic(taken, 'x')); + assert.equal(fs.readFileSync(path.join(taken, 'inside.txt'), 'utf8'), 'kept'); + assert.deepEqual(leftovers(dir), []); + await assert.rejects(writeFileAtomic(path.join(dir, 'missing', 'a.txt'), 'x')); + }); + + it('keeps the permissions', { skip: process.platform === 'win32' }, async () => { + const dir = folder('mode'); + const file = path.join(dir, 'run.sh'); + fs.writeFileSync(file, '#!/bin/sh\n'); + fs.chmodSync(file, 0o750); + assert.equal(await writeFileAtomic(file, '#!/bin/sh\necho hi\n'), 'replaced'); + assert.equal(fs.statSync(file).mode & 0o777, 0o750); + }); + + it('writes a hard link in place, so every name sees the new text', async () => { + const dir = folder('hard'); + const file = path.join(dir, 'a.txt'); + fs.writeFileSync(file, 'old'); + fs.linkSync(file, path.join(dir, 'b.txt')); + assert.equal(await writeFileAtomic(file, 'both'), 'in-place'); + assert.equal(fs.readFileSync(path.join(dir, 'b.txt'), 'utf8'), 'both'); + }); + + it('writes through a symlink in place, keeping the link', { skip: process.platform === 'win32' }, async () => { + const dir = folder('symlink'); + const target = path.join(dir, 'target.txt'); + fs.writeFileSync(target, 'old'); + const link = path.join(dir, 'link.txt'); + fs.symlinkSync(target, link); + assert.equal(await writeFileAtomic(link, 'via link'), 'in-place'); + assert.ok(fs.lstatSync(link).isSymbolicLink()); + assert.equal(fs.readFileSync(target, 'utf8'), 'via link'); + }); +}); From 8bcee220b43d7d5ba30170f669abea3f31181a66 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:32:22 +0000 Subject: [PATCH 19/74] feat(ide): shared tree keyboard model for SCM, Search and Debug trees (#525) --- apps/ide/src/renderer/debug/debug.css | 2 + apps/ide/src/renderer/debug/debugView.ts | 43 +++++-- apps/ide/src/renderer/explorer.ts | 30 +++-- apps/ide/src/renderer/git/scm.css | 4 +- apps/ide/src/renderer/git/scmView.ts | 58 ++++++++-- apps/ide/src/renderer/search/searchView.ts | 23 +++- apps/ide/src/renderer/treeKeyModel.ts | 87 ++++++++++++++ apps/ide/src/renderer/treeKeyboard.ts | 125 +++++++++++++++++++++ apps/ide/test/treeKeyModel.test.ts | 84 ++++++++++++++ 9 files changed, 421 insertions(+), 35 deletions(-) create mode 100644 apps/ide/src/renderer/treeKeyModel.ts create mode 100644 apps/ide/src/renderer/treeKeyboard.ts create mode 100644 apps/ide/test/treeKeyModel.test.ts diff --git a/apps/ide/src/renderer/debug/debug.css b/apps/ide/src/renderer/debug/debug.css index a4863a68..83ee827b 100644 --- a/apps/ide/src/renderer/debug/debug.css +++ b/apps/ide/src/renderer/debug/debug.css @@ -51,6 +51,8 @@ cursor: pointer; } .debug-row:hover { background: var(--hover); } +.debug-node:focus { outline: none; } +.debug-node:focus > .debug-row { outline: 1px solid var(--accent); outline-offset: -1px; } .debug-twisty { flex: none; width: 14px; text-align: center; color: var(--muted); } .debug-twisty::before { content: '\203A'; display: inline-block; transition: transform 0.1s; } .debug-node[aria-expanded='true'] > .debug-row .debug-twisty::before { transform: rotate(90deg); } diff --git a/apps/ide/src/renderer/debug/debugView.ts b/apps/ide/src/renderer/debug/debugView.ts index d0a6bf68..eecde970 100644 --- a/apps/ide/src/renderer/debug/debugView.ts +++ b/apps/ide/src/renderer/debug/debugView.ts @@ -1,8 +1,15 @@ import { t } from '../../shared/i18n/i18n.ts'; import type { DebugBreakpoint, DebugScope, DebugStackFrame, DebugVariable, LaunchConfiguration } from '../../shared/debug.ts'; import { el, icon } from '../dom.ts'; +import { installTreeKeyboard, type TreeKeyboard } from '../treeKeyboard.ts'; import './debug.css'; +/** A tree of the view (Variables, Watch): its redraw count and its keyboard (#525). */ +interface DebugTree { + generation: number; + readonly keyboard: TreeKeyboard; +} + /** * #180: the Run and Debug view of the side bar, VS Code's sections kept: * the configuration to start, Variables (a tree loaded as it is expanded, @@ -135,11 +142,14 @@ export function createDebugView(container: HTMLElement, hooks: DebugViewHooks): // ---- variables tree: what is open stays open across stops (keys are name paths). const expanded = new Set(); + /** #525: how each expandable row opens and closes, for Left/Right. */ + const toggles = new WeakMap void>(); + const treeKeys = { setExpanded: (row: HTMLElement, open: boolean) => toggles.get(row)?.(open) }; /** Bumped when a tree is redrawn, so children loaded for the old one are dropped. */ - const variablesTree = { generation: 0 }; - const watchTree = { generation: 0 }; + const variablesTree: DebugTree = { generation: 0, keyboard: installTreeKeyboard(variables.body, treeKeys) }; + const watchTree: DebugTree = { generation: 0, keyboard: installTreeKeyboard(watchList, treeKeys) }; - function variableRow(tree: { generation: number }, key: string, name: string, value: string | null, type: string | null, reference: number, depth: number, failed = false, extra: HTMLElement[] = []): HTMLLIElement { + function variableRow(tree: DebugTree, key: string, name: string, value: string | null, type: string | null, reference: number, depth: number, failed = false, extra: HTMLElement[] = []): HTMLLIElement { const twisty = el('span', { className: reference > 0 ? 'debug-twisty' : 'debug-twisty is-leaf', attrs: { 'aria-hidden': 'true' } }); const label = el('span', { className: 'debug-var-name', text: name }); const row = el('div', { className: 'debug-row', attrs: { title: type ? `${name}: ${type}` : name } }, [ @@ -149,7 +159,10 @@ export function createDebugView(container: HTMLElement, hooks: DebugViewHooks): ...extra, ]); row.style.paddingLeft = `${8 + depth * 12}px`; - const item = el('li', { className: 'debug-node', attrs: { role: 'treeitem', 'data-key': key } }, [row]); + const item = el('li', { + className: 'debug-node', + attrs: { role: 'treeitem', tabindex: '-1', 'aria-level': String(depth + 1), 'aria-selected': 'false', 'data-key': key, 'data-tree-key': key }, + }, [row]); if (reference > 0) { item.setAttribute('aria-expanded', 'false'); const children = el('ul', { className: 'debug-tree', attrs: { role: 'group' } }); @@ -169,19 +182,29 @@ export function createDebugView(container: HTMLElement, hooks: DebugViewHooks): children.replaceChildren(...(list.length === 0 ? [el('li', { className: 'debug-empty muted', text: 'No items' })] : list.map((child) => variableRow(tree, `${key}/${child.name}`, child.name, child.value, child.type, child.variablesReference, depth + 1)))); + tree.keyboard.sync(); }, (error: unknown) => { children.replaceChildren(el('li', { className: 'debug-empty muted', text: error instanceof Error ? error.message : String(error) })); }); }; + const close = (): void => { + item.setAttribute('aria-expanded', 'false'); + expanded.delete(key); + children.replaceChildren(); + }; row.addEventListener('click', () => { if (item.getAttribute('aria-expanded') === 'true') { - item.setAttribute('aria-expanded', 'false'); - expanded.delete(key); - children.replaceChildren(); + close(); } else { open(true); } }); + // The keys go through the row's click, so a scope remembers it was closed by hand. + toggles.set(item, (next) => { + if ((item.getAttribute('aria-expanded') === 'true') !== next) { + row.click(); + } + }); if (expanded.has(key)) { open(true); } @@ -213,17 +236,17 @@ export function createDebugView(container: HTMLElement, hooks: DebugViewHooks): }); list.append(item); } - variables.body.replaceChildren(list); + variablesTree.keyboard.render(() => variables.body.replaceChildren(list)); } function setWatches(rows: readonly WatchRow[]): void { watchTree.generation += 1; - watchList.replaceChildren(...rows.map((row, index) => { + watchTree.keyboard.render(() => watchList.replaceChildren(...rows.map((row, index) => { const remove = iconButton('Remove Expression', DEBUG_ICONS.remove, 'debug-watch-remove', () => hooks.removeWatch(index)); remove.classList.add('debug-row-action'); const value = row.value === null ? 'not available' : row.value.text; return variableRow(watchTree, `watch:${index}:${row.expression}`, row.expression, value, null, row.value?.reference ?? 0, 0, row.value?.failed ?? false, [remove]); - })); + }))); if (rows.length === 0) { watchList.replaceChildren(el('li', { className: 'debug-empty muted', text: 'No expressions. Add one with +.' })); } diff --git a/apps/ide/src/renderer/explorer.ts b/apps/ide/src/renderer/explorer.ts index a131387a..45301224 100644 --- a/apps/ide/src/renderer/explorer.ts +++ b/apps/ide/src/renderer/explorer.ts @@ -2,6 +2,8 @@ import { t } from '../shared/i18n/i18n.ts'; import type { CodeXRApi, DirEntry, WorkspaceInfo } from '../shared/api.ts'; import { el, fileIcon, icon } from './dom.ts'; import type { ExplorerGitDecoration } from '../shared/gitGutter.ts'; +import { treeKeyAction } from './treeKeyModel.ts'; +import { treeKeyRow } from './treeKeyboard.ts'; /** * The explorer (#14): the open folder as a tree that loads each folder's @@ -326,20 +328,24 @@ export function createExplorer( if (!row || !node) { return; } + // #525: the arrows, Home and End follow the shared tree model. const rows = visibleRows(); - const index = rows.indexOf(row); - const move = (target: HTMLElement | undefined): void => { if (target) { focusRow(target); } }; + const action = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey + ? null + : treeKeyAction(event.key, rows.map(treeKeyRow), rows.indexOf(row)); + if (action) { + event.preventDefault(); + const subject = rows[action.index]; + const subjectNode = subject ? nodes.get(subject) : undefined; + if (action.kind === 'focus' && subject) { + focusRow(subject); + subject.scrollIntoView({ block: 'nearest' }); + } else if (subjectNode) { + void toggle(subjectNode, action.kind === 'expand'); + } + return; + } switch (event.key) { - case 'ArrowDown': move(rows[index + 1]); break; - case 'ArrowUp': move(rows[index - 1]); break; - case 'Home': move(rows[0]); break; - case 'End': move(rows[rows.length - 1]); break; - case 'ArrowRight': - if (node.entry.kind === 'directory' && !node.expanded) { void toggle(node, true); } else if (node.expanded) { move(rows[index + 1]); } - break; - case 'ArrowLeft': - if (node.expanded) { void toggle(node, false); } else { move(row.parentElement?.parentElement?.closest('li')?.querySelector(':scope > [role="treeitem"]') ?? undefined); } - break; case 'Enter': case ' ': activate(node); diff --git a/apps/ide/src/renderer/git/scm.css b/apps/ide/src/renderer/git/scm.css index 88948ed5..4953919b 100644 --- a/apps/ide/src/renderer/git/scm.css +++ b/apps/ide/src/renderer/git/scm.css @@ -62,7 +62,9 @@ .scm-group-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; } .scm-change { padding-left: 20px; cursor: pointer; } .scm-change:hover, .scm-group-header:hover { background: var(--hover); } -.scm-change:focus { outline: 1px solid var(--accent); outline-offset: -1px; } +.scm-change:focus, .scm-group-header:focus { outline: 1px solid var(--accent); outline-offset: -1px; } +.scm-group-header { cursor: pointer; } +.scm-group-header[aria-expanded="false"] .scm-group-label::before { content: '\203A '; } .scm-name { flex-shrink: 0; } .scm-change.is-deleted .scm-name { text-decoration: line-through; } .scm-folder { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: var(--fs-sm); } diff --git a/apps/ide/src/renderer/git/scmView.ts b/apps/ide/src/renderer/git/scmView.ts index 446e2309..e333fb5d 100644 --- a/apps/ide/src/renderer/git/scmView.ts +++ b/apps/ide/src/renderer/git/scmView.ts @@ -4,6 +4,7 @@ import { emptyGitStatus, type GitChange, type GitRemoteOperation, type GitStatus import type { QuickInputProvider } from '../commands/quickInput.ts'; import { showContextMenu, type ContextMenuItem } from '../contextMenu.ts'; import { el, fileIcon, icon } from '../dom.ts'; +import { installTreeKeyboard } from '../treeKeyboard.ts'; import { gitCommandEntries, type GitActions } from './gitCommands.ts'; import { branchLabel, branchPickerView, changeCount, deleteBranchPickerView, letterTitle, parseBranchAction, parseStashPick, @@ -94,6 +95,8 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo let remoteRunning: GitRemoteOperation | null = null; /** What the list shows now, so an unchanged status (the poll, a focus) does not rebuild it. */ let rendered = ''; + /** #525: the groups closed with Left (or a click on their header). */ + const collapsed = new Set(); const iconButton = (label: string, path: string, testId: string, run: () => void): HTMLButtonElement => { const button = el('button', { className: 'icon-button', attrs: { type: 'button', title: label, 'aria-label': label, 'data-testid': testId } }, [icon(path)]); @@ -126,6 +129,23 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo const commitBox = el('div', { className: 'scm-commit-box' }, [message, commitButton]); const empty = el('div', { className: 'scm-empty', attrs: { 'data-testid': 'scm-empty' } }); const list = el('div', { className: 'scm-groups', attrs: { role: 'tree', 'aria-label': t('scm.changes'), 'data-testid': 'scm-groups' } }); + // #525: arrows move between the group headers and the files; Left/Right close and open a group. + const keyboard = installTreeKeyboard(list, { + setExpanded: (row, expanded) => { + const group = row.dataset['group']; + if (group) { + setCollapsed(group, !expanded); + } + }, + }); + function setCollapsed(group: string, closed: boolean): void { + if (closed) { + collapsed.add(group); + } else { + collapsed.delete(group); + } + render(); + } const header = el('div', { className: 'side-bar-header' }, [ el('h2', { className: 'side-bar-title', text: t('view.scm') }), el('div', { className: 'side-bar-actions' }, [ @@ -160,7 +180,7 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo commitButton.addEventListener('click', () => void commit()); function render(): void { - const key = JSON.stringify([status, busy, remoteRunning]); + const key = JSON.stringify([status, busy, remoteRunning, [...collapsed]]); if (key === rendered) { return; } @@ -178,10 +198,12 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo const target = status.branch ?? 'HEAD'; message.placeholder = `Message (${navigator.userAgent.includes('Macintosh') ? 'Cmd' : 'Ctrl'}+Enter to commit on "${target}")`; commitButton.disabled = busy; - list.replaceChildren(...(ok ? scmGroups(status).map(renderGroup) : [])); - if (ok && changeCount(status) === 0) { - list.append(el('p', { className: 'muted side-note small', attrs: { 'data-testid': 'scm-clean' }, text: 'No changes in the working tree.' })); - } + keyboard.render(() => { + list.replaceChildren(...(ok ? scmGroups(status).map(renderGroup) : [])); + if (ok && changeCount(status) === 0) { + list.append(el('p', { className: 'muted side-note small', attrs: { 'data-testid': 'scm-clean' }, text: 'No changes in the working tree.' })); + } + }); const count = ok ? changeCount(status) : 0; badge.hidden = count === 0; @@ -211,12 +233,27 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo const actions = group.id === 'staged' ? [iconButton('Unstage All Changes', ICONS.unstage, `scm-unstage-all`, () => void run(() => api.unstage(paths)))] : [iconButton(group.id === 'untracked' ? 'Stage All Untracked' : 'Stage All Changes', ICONS.stage, `scm-stage-all-${group.id}`, () => void run(() => api.stage(paths)))]; - const head = el('div', { className: 'scm-group-header', attrs: { role: 'treeitem', 'aria-expanded': 'true', 'data-group': group.id } }, [ + const open = !collapsed.has(group.id); + const head = el('div', { + className: 'scm-group-header', + attrs: { + role: 'treeitem', tabindex: '-1', 'aria-level': '1', 'aria-expanded': String(open), 'aria-selected': 'false', + 'data-group': group.id, 'data-tree-key': `group:${group.id}`, + }, + }, [ el('span', { className: 'scm-group-label', text: group.label }), el('span', { className: 'scm-row-actions' }, actions), el('span', { className: 'scm-count', text: String(group.changes.length) }), ]); - return el('div', { className: 'scm-group', attrs: { role: 'group', 'data-testid': `scm-group-${group.id}` } }, [head, ...group.changes.map((change) => renderChange(group, change))]); + head.addEventListener('click', () => setCollapsed(group.id, open)); + head.addEventListener('keydown', (event) => { + if (event.target === head && (event.key === 'Enter' || event.key === ' ')) { + event.preventDefault(); + setCollapsed(group.id, open); + } + }); + const changes = el('div', { attrs: { role: 'group', ...(open ? {} : { hidden: '' }) } }, group.changes.map((change) => renderChange(group, change))); + return el('div', { className: 'scm-group', attrs: { role: 'none', 'data-testid': `scm-group-${group.id}` } }, [head, changes]); } function renderChange(group: ScmGroup, change: GitChange): HTMLElement { @@ -237,7 +274,10 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo const title = `${change.origPath ? `${change.origPath} -> ` : ''}${change.path} - ${letterTitle(change.letter)}`; const row = el('div', { className: `scm-change${deleted ? ' is-deleted' : ''}`, - attrs: { role: 'treeitem', tabindex: '0', title, 'data-path': change.path, 'data-letter': change.letter, 'data-testid': 'scm-change' }, + attrs: { + role: 'treeitem', tabindex: '-1', 'aria-level': '2', 'aria-selected': 'false', title, + 'data-path': change.path, 'data-letter': change.letter, 'data-testid': 'scm-change', 'data-tree-key': `${group.id}:${change.path}`, + }, }, [ fileIcon(name, 'file'), el('span', { className: 'scm-name', text: name }), @@ -254,7 +294,7 @@ export function createScmView(container: HTMLElement, api: CodeXRApi['git'], hoo }; row.addEventListener('click', open); row.addEventListener('keydown', (event) => { - if (event.key === 'Enter') { + if (event.key === 'Enter' && event.target === row) { event.preventDefault(); open(); } diff --git a/apps/ide/src/renderer/search/searchView.ts b/apps/ide/src/renderer/search/searchView.ts index 9f4fad0a..e703069d 100644 --- a/apps/ide/src/renderer/search/searchView.ts +++ b/apps/ide/src/renderer/search/searchView.ts @@ -2,6 +2,7 @@ import { t } from '../../shared/i18n/i18n.ts'; import type { CodeXRApi, SearchDoneEvent, SearchFileEvent, SearchMatch, SearchQuery } from '../../shared/api.ts'; import { compileQuery, replaceInText } from '../../shared/searchText.ts'; import { el, fileIcon, icon } from '../dom.ts'; +import { installTreeKeyboard } from '../treeKeyboard.ts'; import { searchSummary } from './searchModel.ts'; /** @@ -73,6 +74,16 @@ export function createSearchView(container: HTMLElement, api: CodeXRApi['workspa const summary = el('p', { className: 'search-summary muted', attrs: { 'aria-live': 'polite', 'data-testid': 'search-summary' } }); const results = el('div', { className: 'search-results', attrs: { role: 'tree', 'aria-label': t('search.results'), 'data-testid': 'search-results' } }); + // #525: arrows move between files and matches; Left/Right close and open a file's matches. + const keyboard = installTreeKeyboard(results, { + setExpanded: (row, expanded) => { + const file = files.get(row.dataset['path'] ?? ''); + if (file && file.collapsed === expanded) { + file.collapsed = !expanded; + renderResults(); + } + }, + }); const header = el('div', { className: 'side-bar-header' }, [ el('h2', { className: 'side-bar-title', text: t('view.search') }), el('div', { className: 'side-bar-actions' }, [ @@ -215,7 +226,7 @@ export function createSearchView(container: HTMLElement, api: CodeXRApi['workspa } } } - results.replaceChildren(...rows); + keyboard.render(() => results.replaceChildren(...rows)); } function fileRow(file: FileState): HTMLElement { @@ -223,7 +234,10 @@ export function createSearchView(container: HTMLElement, api: CodeXRApi['workspa const folder = file.path.includes('/') ? file.path.slice(0, file.path.lastIndexOf('/')) : ''; const row = el('div', { className: file.collapsed ? 'search-file is-collapsed' : 'search-file', - attrs: { role: 'treeitem', 'aria-expanded': String(!file.collapsed), tabindex: '0', title: file.path, 'data-path': file.path }, + attrs: { + role: 'treeitem', 'aria-level': '1', 'aria-expanded': String(!file.collapsed), 'aria-selected': 'false', tabindex: '-1', + title: file.path, 'data-path': file.path, 'data-tree-key': `file:${file.path}`, + }, }, [ icon(ICONS.chevron, 'search-chevron'), fileIcon(name, 'file'), @@ -253,7 +267,10 @@ export function createSearchView(container: HTMLElement, api: CodeXRApi['workspa parts.push(document.createTextNode(after)); const row = el('div', { className: 'search-match', - attrs: { role: 'treeitem', tabindex: '0', title: `Line ${match.line}, column ${match.column}`, 'data-line': String(match.line) }, + attrs: { + role: 'treeitem', 'aria-level': '2', 'aria-selected': 'false', tabindex: '-1', title: `Line ${match.line}, column ${match.column}`, + 'data-line': String(match.line), 'data-tree-key': `match:${path}:${match.line}:${match.column}`, + }, }, [el('span', { className: 'search-line-number muted', text: String(match.line) }), el('span', { className: 'search-preview' }, parts)]); const open = (): void => hooks.openMatch(path, match); row.addEventListener('click', open); diff --git a/apps/ide/src/renderer/treeKeyModel.ts b/apps/ide/src/renderer/treeKeyModel.ts new file mode 100644 index 00000000..ee0d3631 --- /dev/null +++ b/apps/ide/src/renderer/treeKeyModel.ts @@ -0,0 +1,87 @@ +/** + * #525 (O23): what an arrow key does in a tree (the WAI-ARIA tree pattern), + * shared by the explorer, Source Control, Search and the Debug trees. Kept + * free of the DOM so it is unit-tested, like `contextMenuModel.ts`; + * `treeKeyboard.ts` applies it to a rendered tree. + * + * A tree is described as its visible rows, top to bottom: each row's depth + * (`level`, 1 at the top) and whether it is expanded (`true`), collapsed + * (`false`) or a leaf (`undefined`). Rows of a collapsed folder are not + * visible, so they are not in the list. + */ + +export interface TreeKeyRow { + readonly level: number; + /** true: expanded, false: collapsed, undefined: a leaf (nothing to expand). */ + readonly expanded?: boolean | undefined; +} + +/** What the key asks for: move the focus to a row, expand or collapse one, or nothing. */ +export type TreeKeyAction = + | { readonly kind: 'focus'; readonly index: number } + | { readonly kind: 'expand'; readonly index: number } + | { readonly kind: 'collapse'; readonly index: number } + | null; + +/** The row a row belongs to: the nearest row above it at a lower level; -1 at the top. */ +export function parentIndex(rows: readonly TreeKeyRow[], index: number): number { + const row = rows[index]; + if (!row) { + return -1; + } + for (let candidate = index - 1; candidate >= 0; candidate--) { + if ((rows[candidate]?.level ?? 0) < row.level) { + return candidate; + } + } + return -1; +} + +/** + * The action of `key` on the row at `index`: + * Down/Up move one row, Home/End to the first/last, Right expands a collapsed + * row or enters an expanded one (its first child), Left collapses an expanded + * row or goes to its parent. Any other key: null (the view handles it). + */ +export function treeKeyAction(key: string, rows: readonly TreeKeyRow[], index: number): TreeKeyAction { + const row = rows[index]; + if (!row) { + // Nothing focused yet: any move starts at the top. + return rows.length > 0 && ['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(key) + ? { kind: 'focus', index: key === 'End' ? rows.length - 1 : 0 } + : null; + } + const focus = (target: number): TreeKeyAction => (target >= 0 && target < rows.length && target !== index ? { kind: 'focus', index: target } : null); + switch (key) { + case 'ArrowDown': return focus(index + 1); + case 'ArrowUp': return focus(index - 1); + case 'Home': return focus(0); + case 'End': return focus(rows.length - 1); + case 'ArrowRight': + if (row.expanded === false) { + return { kind: 'expand', index }; + } + // An expanded row enters its first child; an empty one or a leaf stays. + return row.expanded === true && (rows[index + 1]?.level ?? 0) > row.level ? focus(index + 1) : null; + case 'ArrowLeft': + if (row.expanded === true) { + return { kind: 'collapse', index }; + } + return focus(parentIndex(rows, index)); + default: + return null; + } +} + +/** + * The row that keeps the tab stop after a tree is drawn again (roving + * tabindex): the one with the key that had it, else the first row; -1 when + * the tree is empty. + */ +export function rovingIndex(keys: readonly string[], previous: string | null): number { + if (keys.length === 0) { + return -1; + } + const kept = previous === null ? -1 : keys.indexOf(previous); + return kept >= 0 ? kept : 0; +} diff --git a/apps/ide/src/renderer/treeKeyboard.ts b/apps/ide/src/renderer/treeKeyboard.ts new file mode 100644 index 00000000..26179d49 --- /dev/null +++ b/apps/ide/src/renderer/treeKeyboard.ts @@ -0,0 +1,125 @@ +import { rovingIndex, treeKeyAction, type TreeKeyRow } from './treeKeyModel.ts'; + +/** + * #525 (O23): the keyboard of a tree drawn by a view (Source Control, Search, + * the Debug trees), on the pure `treeKeyAction`. The rows are the visible + * `[role="treeitem"]` elements inside `container`; each one's depth is its + * `aria-level` and `aria-expanded` says whether it can open. One row at a time + * is in the Tab order (roving tabindex) and is `aria-selected`; the others + * are reached with the arrows. + * + * Views redraw their rows often (every search result, every Git status): + * `render` wraps a redraw so the tab stop stays on the row with the same key + * (`data-tree-key`), and the focus comes back to it when it was in the tree. + */ +export interface TreeKeyboardOptions { + /** Opens or closes a row that has `aria-expanded`. */ + setExpanded?(row: HTMLElement, expanded: boolean): void; +} + +export interface TreeKeyboard { + /** Runs a redraw of the rows and puts the tab stop (and the focus, if it was there) back. */ + render(draw: () => void): void; + /** Re-applies the roving tabindex after rows were added (children loaded later). */ + sync(): void; + /** Removes the listeners. */ + dispose(): void; +} + +const keyOf = (row: HTMLElement): string => row.dataset['treeKey'] ?? row.getAttribute('data-path') ?? row.textContent ?? ''; + +/** The visible rows of a tree container, top to bottom. */ +export function visibleTreeRows(container: HTMLElement): HTMLElement[] { + return [...container.querySelectorAll('[role="treeitem"]')].filter((row) => { + const hidden = row.closest('[hidden]'); + return !hidden || !container.contains(hidden); + }); +} + +/** A rendered row as the model sees it. */ +export function treeKeyRow(row: HTMLElement): TreeKeyRow { + const expanded = row.getAttribute('aria-expanded'); + return { level: Number(row.getAttribute('aria-level')) || 1, expanded: expanded === null ? undefined : expanded === 'true' }; +} + +export function installTreeKeyboard(container: HTMLElement, options: TreeKeyboardOptions = {}): TreeKeyboard { + let current: string | null = null; + + function setStop(rows: readonly HTMLElement[], target: HTMLElement | undefined): void { + for (const row of rows) { + const on = row === target; + row.setAttribute('tabindex', on ? '0' : '-1'); + row.setAttribute('aria-selected', String(on)); + } + if (target) { + current = keyOf(target); + } + } + + function focusRow(target: HTMLElement): void { + setStop(visibleTreeRows(container), target); + target.focus(); + target.scrollIntoView?.({ block: 'nearest' }); + } + + function sync(): void { + const rows = visibleTreeRows(container); + setStop(rows, rows[rovingIndex(rows.map(keyOf), current)]); + } + + const onKeyDown = (event: KeyboardEvent): void => { + if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } + const target = event.target as HTMLElement; + if (target.closest('input, textarea, button, select')) { + return; // a field or a row action keeps its own keys + } + const row = target.closest('[role="treeitem"]'); + if (!row || !container.contains(row)) { + return; + } + const rows = visibleTreeRows(container); + const action = treeKeyAction(event.key, rows.map(treeKeyRow), rows.indexOf(row)); + if (!action) { + return; + } + event.preventDefault(); + event.stopPropagation(); + const subject = rows[action.index]; + if (!subject) { + return; + } + if (action.kind === 'focus') { + focusRow(subject); + } else { + options.setExpanded?.(subject, action.kind === 'expand'); + } + }; + // A click or Tab onto a row makes it the tab stop. + const onFocusIn = (event: FocusEvent): void => { + const row = (event.target as HTMLElement).closest('[role="treeitem"]'); + if (row && row === event.target && container.contains(row) && row.getAttribute('tabindex') !== '0') { + setStop(visibleTreeRows(container), row); + } + }; + container.addEventListener('keydown', onKeyDown); + container.addEventListener('focusin', onFocusIn); + + return { + render(draw) { + const active = document.activeElement; + const hadFocus = active instanceof HTMLElement && container.contains(active) && active.getAttribute('role') === 'treeitem'; + draw(); + sync(); + if (hadFocus && !container.contains(document.activeElement)) { + container.querySelector('[role="treeitem"][tabindex="0"]')?.focus(); + } + }, + sync, + dispose() { + container.removeEventListener('keydown', onKeyDown); + container.removeEventListener('focusin', onFocusIn); + }, + }; +} diff --git a/apps/ide/test/treeKeyModel.test.ts b/apps/ide/test/treeKeyModel.test.ts new file mode 100644 index 00000000..468d9773 --- /dev/null +++ b/apps/ide/test/treeKeyModel.test.ts @@ -0,0 +1,84 @@ +// #525 (O23): the shared tree keyboard model of the explorer, Source Control, +// Search and the Debug trees: arrows, Home/End, expand/collapse, parent, and +// which row keeps the tab stop after a redraw. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { parentIndex, rovingIndex, treeKeyAction, type TreeKeyRow } from '../src/renderer/treeKeyModel.ts'; + +// src/ (expanded) +// a.ts +// lib/ (collapsed) +// README.md +const rows: TreeKeyRow[] = [ + { level: 1, expanded: true }, + { level: 2 }, + { level: 2, expanded: false }, + { level: 1 }, +]; + +describe('treeKeyAction', () => { + it('moves up and down one row, and stops at the ends', () => { + assert.deepEqual(treeKeyAction('ArrowDown', rows, 0), { kind: 'focus', index: 1 }); + assert.deepEqual(treeKeyAction('ArrowUp', rows, 2), { kind: 'focus', index: 1 }); + assert.equal(treeKeyAction('ArrowDown', rows, 3), null); + assert.equal(treeKeyAction('ArrowUp', rows, 0), null); + }); + + it('goes to the first and last rows with Home and End', () => { + assert.deepEqual(treeKeyAction('Home', rows, 2), { kind: 'focus', index: 0 }); + assert.deepEqual(treeKeyAction('End', rows, 1), { kind: 'focus', index: 3 }); + assert.equal(treeKeyAction('Home', rows, 0), null); + }); + + it('expands a collapsed row with Right, and enters an expanded one', () => { + assert.deepEqual(treeKeyAction('ArrowRight', rows, 2), { kind: 'expand', index: 2 }); + assert.deepEqual(treeKeyAction('ArrowRight', rows, 0), { kind: 'focus', index: 1 }); + assert.equal(treeKeyAction('ArrowRight', rows, 1), null, 'a leaf has nothing to open'); + assert.equal(treeKeyAction('ArrowRight', [{ level: 1, expanded: true }, { level: 1 }], 0), null, 'an empty expanded folder stays'); + }); + + it('collapses an expanded row with Left, else goes to the parent', () => { + assert.deepEqual(treeKeyAction('ArrowLeft', rows, 0), { kind: 'collapse', index: 0 }); + assert.deepEqual(treeKeyAction('ArrowLeft', rows, 2), { kind: 'focus', index: 0 }); + assert.deepEqual(treeKeyAction('ArrowLeft', rows, 1), { kind: 'focus', index: 0 }); + assert.equal(treeKeyAction('ArrowLeft', rows, 3), null, 'a top row has no parent'); + }); + + it('starts at the top when nothing is focused, and leaves other keys to the view', () => { + assert.deepEqual(treeKeyAction('ArrowDown', rows, -1), { kind: 'focus', index: 0 }); + assert.deepEqual(treeKeyAction('End', rows, -1), { kind: 'focus', index: 3 }); + assert.equal(treeKeyAction('ArrowDown', [], -1), null); + assert.equal(treeKeyAction('Enter', rows, 0), null); + assert.equal(treeKeyAction('F2', rows, 1), null); + }); +}); + +describe('parentIndex', () => { + it('is the nearest row above at a lower level', () => { + const deep: TreeKeyRow[] = [{ level: 1, expanded: true }, { level: 2, expanded: true }, { level: 3 }, { level: 2 }]; + assert.equal(parentIndex(deep, 2), 1); + assert.equal(parentIndex(deep, 3), 0); + assert.equal(parentIndex(deep, 0), -1); + assert.equal(parentIndex(deep, 9), -1); + }); +}); + +describe('rovingIndex', () => { + it('keeps the tab stop on the same key after a redraw, else the first row', () => { + assert.equal(rovingIndex(['a', 'b', 'c'], 'b'), 1); + assert.equal(rovingIndex(['a', 'c'], 'b'), 0); + assert.equal(rovingIndex(['a'], null), 0); + assert.equal(rovingIndex([], 'a'), -1); + }); +}); + +describe('the views use the shared model', () => { + for (const file of ['explorer.ts', 'git/scmView.ts', 'search/searchView.ts', 'debug/debugView.ts']) { + it(file, () => { + const source = readFileSync(new URL(`../src/renderer/${file}`, import.meta.url), 'utf8'); + assert.match(source, /treeKeyAction|installTreeKeyboard/); + assert.doesNotMatch(source, /role: 'treeitem', tabindex: '0'/, 'no row is a tab stop of its own'); + }); + } +}); From fa784ffb3b9a1b6e79ff3596e3e0eb33c0f8059b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:33:32 +0000 Subject: [PATCH 20/74] feat(core): host-neutral hunk split, revert/keep and review-comment prompt (#521) --- apps/ide/test/hunkReview.test.ts | 178 +++++++++++++++ .../src/core/agent-review/hunkReview.ts | 211 ++++++++++++++++++ .../src/core/agent-review/reviewComments.ts | 93 ++++++++ .../test/agent_review/hunkReview.test.cjs | 20 ++ 4 files changed, 502 insertions(+) create mode 100644 apps/ide/test/hunkReview.test.ts create mode 100644 apps/vscode-extension/src/core/agent-review/hunkReview.ts create mode 100644 apps/vscode-extension/src/core/agent-review/reviewComments.ts create mode 100644 apps/vscode-extension/test/agent_review/hunkReview.test.cjs diff --git a/apps/ide/test/hunkReview.test.ts b/apps/ide/test/hunkReview.test.ts new file mode 100644 index 00000000..213ddb98 --- /dev/null +++ b/apps/ide/test/hunkReview.test.ts @@ -0,0 +1,178 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { hunkAtDiskLine, hunkDiskRange, keepHunks, revertHunks, splitHunks, StaleHunkError } from '@codexr/core/agent-review/hunkReview'; +import { formatReviewComments, MAX_QUOTED_LINES } from '@codexr/core/agent-review/reviewComments'; + +/** #521 (O19): per-hunk Keep/Undo of an agent's edits and the follow-up prompt of line comments (core/agent-review). */ + +const ids = (base: string, disk: string): string[] => splitHunks(base, disk).map((hunk) => hunk.id); + +describe('hunk review: split, revert, keep (#521)', () => { + it('finds nothing to review when the texts are equal', () => { + assert.deepEqual(splitHunks('a\nb\n', 'a\nb\n'), []); + assert.equal(revertHunks('a\n', 'a\n', []), 'a\n'); + }); + + it('splits a change into its hunks with both sides, in order', () => { + const hunks = splitHunks('one\ntwo\nthree\nfour\nfive\n', 'one\nTWO\nthree\nfour\nfive\nsix\n'); + assert.deepEqual(hunks.map((hunk) => [hunk.baseStart, hunk.baseLines, hunk.diskStart, hunk.diskLines]), [ + [1, ['two'], 1, ['TWO']], + [5, [], 5, ['six']], + ]); + assert.notEqual(hunks[0]?.id, hunks[1]?.id); + assert.deepEqual(ids('one\ntwo\n', 'one\nTWO\n'), ids('one\ntwo\n', 'one\nTWO\n'), 'ids are deterministic'); + }); + + it('reverts only the middle hunk of three, leaving the others on disk', () => { + const base = 'a\nb\nc\nd\ne\nf\ng\n'; + const disk = 'A\nb\nc\nD1\nD2\ne\nf\nG\n'; + const hunks = splitHunks(base, disk); + assert.equal(hunks.length, 3); + const middle = hunks[1]; + assert.ok(middle); + assert.deepEqual(middle.baseLines, ['d']); + assert.deepEqual(middle.diskLines, ['D1', 'D2']); + assert.equal(revertHunks(base, disk, [middle.id]), 'A\nb\nc\nd\ne\nf\nG\n'); + assert.equal(revertHunks(base, disk, hunks.map((hunk) => hunk.id)), base, 'every hunk reverted: the base'); + assert.equal(keepHunks(base, disk, hunks.map((hunk) => hunk.id)), disk, 'every hunk kept: the disk'); + }); + + it('keeps adjacent hunks (one unchanged line apart) independent', () => { + const base = 'x\nkeep\ny\n'; + const disk = 'X\nkeep\nY\n'; + const hunks = splitHunks(base, disk); + assert.equal(hunks.length, 2, 'one common line separates them'); + assert.equal(revertHunks(base, disk, [hunks[0]?.id ?? '']), 'x\nkeep\nY\n'); + assert.equal(revertHunks(base, disk, [hunks[1]?.id ?? '']), 'X\nkeep\ny\n'); + assert.equal(keepHunks(base, disk, [hunks[0]?.id ?? '']), 'X\nkeep\ny\n'); + }); + + it('merges touching changes into one hunk, so no two hunks ever overlap', () => { + const hunks = splitHunks('a\nb\nc\n', 'a\nB\nC\nextra\n'); + assert.equal(hunks.length, 1); + for (let index = 1; index < hunks.length; index += 1) { + const previous = hunks[index - 1]; + const current = hunks[index]; + assert.ok(previous && current && current.diskStart > previous.diskStart + previous.diskLines.length); + } + const many = splitHunks('1\n2\n3\n4\n5\n6\n', '1\nx\n3\ny\nz\n6\n'); + for (let index = 1; index < many.length; index += 1) { + const previous = many[index - 1]; + const current = many[index]; + assert.ok(previous && current && current.baseStart > previous.baseStart + previous.baseLines.length, 'at least one common line between hunks'); + } + }); + + it('handles pure insertions and deletions', () => { + const insertBase = 'a\nc\n'; + const insertDisk = 'a\nb\nc\n'; + const [insert] = splitHunks(insertBase, insertDisk); + assert.ok(insert); + assert.equal(revertHunks(insertBase, insertDisk, [insert.id]), insertBase); + assert.equal(keepHunks(insertBase, insertDisk, [insert.id]), insertDisk); + const deleteBase = 'a\nb\nc\n'; + const deleteDisk = 'a\nc\n'; + const [removal] = splitHunks(deleteBase, deleteDisk); + assert.ok(removal); + assert.deepEqual(removal.diskLines, []); + assert.equal(revertHunks(deleteBase, deleteDisk, [removal.id]), deleteBase); + assert.equal(hunkAtDiskLine([removal], 2), removal, 'a deletion belongs to the line that follows it'); + }); + + it('keeps CRLF files byte for byte, mixed endings and a missing final newline included', () => { + const base = 'one\r\ntwo\r\nthree\r\nfour'; + const disk = 'one\r\nTWO\r\nthree\r\nFOUR'; + const hunks = splitHunks(base, disk); + assert.equal(hunks.length, 2); + assert.deepEqual(hunks[0]?.diskLines, ['TWO\r']); + assert.equal(revertHunks(base, disk, [hunks[0]?.id ?? '']), 'one\r\ntwo\r\nthree\r\nFOUR'); + assert.equal(keepHunks(base, disk, [hunks[1]?.id ?? '']), 'one\r\ntwo\r\nthree\r\nFOUR'); + const mixed = 'a\r\nb\nc\r\n'; + const mixedDisk = 'a\r\nB\nc\r\n'; + const [only] = splitHunks(mixed, mixedDisk); + assert.equal(revertHunks(mixed, mixedDisk, [only?.id ?? '']), mixed); + // An agent that rewrote the endings: every line differs, and undoing gives the CRLF text back exactly. + const lf = 'one\ntwo\n'; + const crlf = 'one\r\ntwo\r\n'; + assert.equal(revertHunks(crlf, lf, ids(crlf, lf)), crlf); + // Adding the final newline is a hunk of its own. + const [newline] = splitHunks('a', 'a\n'); + assert.equal(revertHunks('a', 'a\n', [newline?.id ?? '']), 'a'); + }); + + it('keeps one hunk, then undoes the rest: the disk ends as the base with the kept hunk', () => { + const base = 'a\nb\nc\nd\ne\n'; + const disk = 'A\nb\nc\nd\nE\n'; + const [first, second] = splitHunks(base, disk); + assert.ok(first && second); + const newBase = keepHunks(base, disk, [first.id]); + assert.equal(newBase, 'A\nb\nc\nd\ne\n'); + const remaining = splitHunks(newBase, disk); + assert.equal(remaining.length, 1, 'the kept hunk no longer shows'); + assert.deepEqual(remaining[0]?.diskLines, ['E']); + const written = revertHunks(newBase, disk, [remaining[0]?.id ?? '']); + assert.equal(written, newBase); + assert.deepEqual(splitHunks(newBase, written), [], 'nothing left to review'); + }); + + it('refuses an id that is not a hunk any more (the file changed in between)', () => { + const [hunk] = splitHunks('a\nb\n', 'a\nB\n'); + assert.ok(hunk); + assert.throws(() => revertHunks('a\nb\n', 'a\nBB\n', [hunk.id]), StaleHunkError); + assert.throws(() => keepHunks('a\nb\n', 'a\nB\n', ['0+1:0+1:zzz']), StaleHunkError); + assert.equal(revertHunks('a\nb\n', 'a\nB\n', [hunk.id, hunk.id]), 'a\nb\n', 'a repeated id counts once'); + }); + + it('maps disk lines to hunks and labels their range', () => { + const hunks = splitHunks('a\nb\nc\nd\n', 'a\nB1\nB2\nc\nd\n'); + assert.equal(hunkAtDiskLine(hunks, 1), null); + assert.equal(hunkAtDiskLine(hunks, 2), hunks[0]); + assert.equal(hunkAtDiskLine(hunks, 3), hunks[0]); + assert.equal(hunkAtDiskLine(hunks, 4), null); + assert.deepEqual(hunkDiskRange(hunks[0] ?? { id: '', baseStart: 0, baseLines: [], diskStart: 0, diskLines: [] }), [2, 3]); + }); +}); + +describe('review comments prompt (#521)', () => { + it('is empty without a comment that has text', () => { + assert.equal(formatReviewComments([]), ''); + assert.equal(formatReviewComments([{ path: 'a.ts', line: 1, comment: ' ', hunk: null }]), ''); + }); + + it('lists path:line, the comment and the hunk as a diff, sorted by path and line', () => { + const text = formatReviewComments([ + { path: 'src/b.ts', line: 9, comment: 'Second file.', hunk: null, lineText: 'const x = 1;\r' }, + { path: 'src/a.ts', line: 12, comment: 'Name this\nbetter.\n', hunk: { baseLines: ['let v = 1;\r'], diskLines: ['let value = 2;\r', 'log(value);\r'] } }, + { path: 'src/a.ts', line: 3, comment: 'Why?', hunk: { baseLines: ['gone'], diskLines: [] } }, + ]); + assert.equal(text, [ + 'I reviewed your changes and left comments on some lines. Please address each one:', + '', + '1. src/a.ts:3 — Why?', + ' ```diff', + ' -gone', + ' ```', + '', + '2. src/a.ts:12 — Name this better.', + ' ```diff', + ' -let v = 1;', + ' +let value = 2;', + ' +log(value);', + ' ```', + '', + '3. src/b.ts:9 — Second file.', + ' ```', + ' const x = 1;', + ' ```', + '', + ].join('\n')); + }); + + it('fences a quote that holds backticks with a longer fence and caps long hunks', () => { + const fenced = formatReviewComments([{ path: 'README.md', line: 1, comment: 'Fix.', hunk: { baseLines: [], diskLines: ['```js'] } }]); + assert.match(fenced, /\n {3}````diff\n {3}\+```js\n {3}````/); + const long = formatReviewComments([{ path: 'a.ts', line: 1, comment: 'Too long.', hunk: { baseLines: [], diskLines: Array.from({ length: MAX_QUOTED_LINES + 5 }, (_, index) => `line ${index}`) } }]); + assert.match(long, /\.\.\. \(5 more lines\)/); + assert.doesNotMatch(long, /line 44/); + }); +}); diff --git a/apps/vscode-extension/src/core/agent-review/hunkReview.ts b/apps/vscode-extension/src/core/agent-review/hunkReview.ts new file mode 100644 index 00000000..549a09e6 --- /dev/null +++ b/apps/vscode-extension/src/core/agent-review/hunkReview.ts @@ -0,0 +1,211 @@ +/** + * #521 (O19): hunk-by-hunk review of an agent's edits. A file the agent + * changed has a review base (what it was before, or what the person last + * kept) and its content on disk; this splits base -> disk into hunks and + * builds the two texts a per-hunk decision needs: + * + * - Undo some hunks: the disk with those hunks put back as they were in the + * base (`revertHunks`); the host writes it to disk. + * - Keep some hunks: the base with those hunks applied (`keepHunks`); the host + * records it as the file's new review base, so the kept hunks stop showing. + * + * Pure and host-neutral on purpose: no `vscode`, no Node, no DOM, so the + * Code-XR IDE runs it both in its sidecar (which writes) and in its sandboxed + * renderer (which shows the hunks), and the VS Code extension's chat can reuse + * it. Lines are split on "\n" only, so a "\r" stays part of its line and a + * CRLF file (or a file with mixed endings) comes back byte for byte; the last + * line's newline, or its absence, is kept the same way. + * + * Hunk ids are derived from the hunk's position and content: the host that + * showed the hunks and the host that applies the decision compute them from + * their own copies of the two texts, and an id that no longer matches means + * the file changed in between (`StaleHunkError`) instead of a wrong write. + */ + +export interface ReviewHunk { + /** Stable for the same base and disk texts; see `hunkId`. */ + readonly id: string; + /** First base line the hunk replaces, 0-based (for a pure insertion: the line it goes before). */ + readonly baseStart: number; + /** The base lines it replaces (empty for a pure insertion). */ + readonly baseLines: readonly string[]; + /** First line of the hunk on disk, 0-based (for a pure deletion: the line that follows it). */ + readonly diskStart: number; + /** The lines that took their place on disk (empty for a pure deletion). */ + readonly diskLines: readonly string[]; +} + +/** An id that is not one of the file's hunks any more: the file changed since they were computed. */ +export class StaleHunkError extends Error { + constructor(message = 'The file changed since its changes were shown. Look at them again before keeping or undoing a part.') { + super(message); + this.name = 'StaleHunkError'; + } +} + +/** Above this many cells the differing middle is one hunk instead of an exact diff. */ +const MAX_CELLS = 4_000_000; + +/** The lines of a text, split on "\n" only ("\r" stays on its line). */ +export function reviewLines(text: string): string[] { + return text.split('\n'); +} + +/** The hunks that turn `base` into `disk`, in order. Consecutive hunks are always separated by at least one unchanged line. */ +export function splitHunks(base: string, disk: string): ReviewHunk[] { + const a = reviewLines(base); + const b = reviewLines(disk); + let start = 0; + while (start < a.length && start < b.length && a[start] === b[start]) { + start += 1; + } + let endA = a.length; + let endB = b.length; + while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) { + endA -= 1; + endB -= 1; + } + const n = endA - start; + const m = endB - start; + if (n === 0 && m === 0) { + return []; + } + if (n === 0 || m === 0 || (n + 1) * (m + 1) > MAX_CELLS) { + return [makeHunk(start, a.slice(start, endA), start, b.slice(start, endB))]; + } + // Longest common subsequence over the middle, filled from the end so the walk goes forwards. + const width = m + 1; + const table = new Uint32Array((n + 1) * width); + for (let i = n - 1; i >= 0; i -= 1) { + for (let j = m - 1; j >= 0; j -= 1) { + table[i * width + j] = a[start + i] === b[start + j] + ? (table[(i + 1) * width + j + 1] ?? 0) + 1 + : Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0); + } + } + const hunks: ReviewHunk[] = []; + let i = 0; + let j = 0; + let open: { baseStart: number; diskStart: number; baseLines: string[]; diskLines: string[] } | null = null; + const close = (): void => { + if (open) { + hunks.push(makeHunk(open.baseStart, open.baseLines, open.diskStart, open.diskLines)); + open = null; + } + }; + while (i < n || j < m) { + if (i < n && j < m && a[start + i] === b[start + j]) { + close(); + i += 1; + j += 1; + continue; + } + open ??= { baseStart: start + i, diskStart: start + j, baseLines: [], diskLines: [] }; + if (j < m && (i >= n || (table[i * width + j + 1] ?? 0) >= (table[(i + 1) * width + j] ?? 0))) { + open.diskLines.push(b[start + j] ?? ''); + j += 1; + } else { + open.baseLines.push(a[start + i] ?? ''); + i += 1; + } + } + close(); + return hunks; +} + +/** + * The disk text with the hunks in `ids` put back as they were in the base + * (what "Undo" on those hunks writes). Throws `StaleHunkError` for an id that + * is not a hunk of base -> disk. + */ +export function revertHunks(base: string, disk: string, ids: Iterable): string { + const hunks = splitHunks(base, disk); + const chosen = pickHunks(hunks, ids); + const lines = reviewLines(disk); + const out: string[] = []; + let cursor = 0; + for (const hunk of hunks) { + if (!chosen.has(hunk.id)) { + continue; + } + out.push(...lines.slice(cursor, hunk.diskStart), ...hunk.baseLines); + cursor = hunk.diskStart + hunk.diskLines.length; + } + out.push(...lines.slice(cursor)); + return out.join('\n'); +} + +/** + * The base text with the hunks in `ids` applied (the file's new review base + * after "Keep" on those hunks: they stop differing, the others still do). + * Throws `StaleHunkError` for an id that is not a hunk of base -> disk. + */ +export function keepHunks(base: string, disk: string, ids: Iterable): string { + const hunks = splitHunks(base, disk); + const chosen = pickHunks(hunks, ids); + const lines = reviewLines(base); + const out: string[] = []; + let cursor = 0; + for (const hunk of hunks) { + if (!chosen.has(hunk.id)) { + continue; + } + out.push(...lines.slice(cursor, hunk.baseStart), ...hunk.diskLines); + cursor = hunk.baseStart + hunk.baseLines.length; + } + out.push(...lines.slice(cursor)); + return out.join('\n'); +} + +/** The hunk that covers a 1-based line of the disk text (a pure deletion covers the line that follows it), or null. */ +export function hunkAtDiskLine(hunks: readonly ReviewHunk[], line: number): ReviewHunk | null { + const index = line - 1; + for (const hunk of hunks) { + const end = hunk.diskStart + Math.max(1, hunk.diskLines.length); + if (index >= hunk.diskStart && index < end) { + return hunk; + } + } + return null; +} + +/** The 1-based disk lines a hunk covers, for labels: `[first, last]` (equal for one line or a pure deletion). */ +export function hunkDiskRange(hunk: ReviewHunk): readonly [number, number] { + const first = hunk.diskStart + 1; + return [first, first + Math.max(0, hunk.diskLines.length - 1)]; +} + +/** `+:+:`, numbers in base 36. */ +export function hunkId(baseStart: number, baseLines: readonly string[], diskStart: number, diskLines: readonly string[]): string { + let hash = 0x811c9dc5; + const feed = (text: string): void => { + for (let index = 0; index < text.length; index += 1) { + hash ^= text.charCodeAt(index); + hash = Math.imul(hash, 0x01000193); + } + }; + for (const line of baseLines) { + feed(`-${line}\n`); + } + for (const line of diskLines) { + feed(`+${line}\n`); + } + const counts = [baseStart, baseLines.length, diskStart, diskLines.length].map((value) => value.toString(36)); + return `${counts[0] ?? ''}+${counts[1] ?? ''}:${counts[2] ?? ''}+${counts[3] ?? ''}:${(hash >>> 0).toString(36)}`; +} + +function makeHunk(baseStart: number, baseLines: readonly string[], diskStart: number, diskLines: readonly string[]): ReviewHunk { + return { id: hunkId(baseStart, baseLines, diskStart, diskLines), baseStart, baseLines, diskStart, diskLines }; +} + +function pickHunks(hunks: readonly ReviewHunk[], ids: Iterable): Set { + const known = new Set(hunks.map((hunk) => hunk.id)); + const chosen = new Set(); + for (const id of ids) { + if (!known.has(id)) { + throw new StaleHunkError(); + } + chosen.add(id); + } + return chosen; +} diff --git a/apps/vscode-extension/src/core/agent-review/reviewComments.ts b/apps/vscode-extension/src/core/agent-review/reviewComments.ts new file mode 100644 index 00000000..a477c4cb --- /dev/null +++ b/apps/vscode-extension/src/core/agent-review/reviewComments.ts @@ -0,0 +1,93 @@ +/** + * #521 (O19): the follow-up prompt built from the person's line comments on + * an agent's changes. Each comment names `path:line`, says what the person + * wants and quotes the hunk the line belongs to (or the line itself when it + * is outside every hunk), so the agent gets the context without the person + * retyping it. One prompt for all comments, which the host drafts in the + * chat's composer (never sends). + * + * Pure and host-neutral, like `hunkReview`: no `vscode`, no Node, no DOM. + * The prompt is English whatever the display language: it is addressed to + * the agent, not shown as UI. + */ + +import type { ReviewHunk } from './hunkReview'; + +export interface ReviewComment { + /** Project-relative path, forward slashes. */ + readonly path: string; + /** 1-based line of the file as it is now (the disk side of the diff). */ + readonly line: number; + readonly comment: string; + /** The hunk the line is in, quoted as a diff; null when the line is outside every hunk. */ + readonly hunk: Pick | null; + /** The commented line itself, quoted when there is no hunk (optional). */ + readonly lineText?: string | null; +} + +/** Longest quote per comment; the rest is summarised as a count. */ +export const MAX_QUOTED_LINES = 40; + +const INTRO = 'I reviewed your changes and left comments on some lines. Please address each one:'; + +/** The follow-up prompt for these comments, sorted by path then line; '' when there are none with text. */ +export function formatReviewComments(comments: readonly ReviewComment[]): string { + const usable = comments + .filter((entry) => entry.comment.trim() !== '') + .slice() + .sort((a, b) => (a.path === b.path ? a.line - b.line : a.path < b.path ? -1 : 1)); + if (usable.length === 0) { + return ''; + } + const blocks = usable.map((entry, index) => { + const head = `${index + 1}. ${entry.path}:${entry.line} — ${oneParagraph(entry.comment)}`; + const quote = quoteFor(entry); + return quote ? `${head}\n${indent(quote)}` : head; + }); + return `${INTRO}\n\n${blocks.join('\n\n')}\n`; +} + +/** The fenced quote of one comment: the hunk as a diff, else the line, else nothing. */ +function quoteFor(entry: ReviewComment): string | null { + let lines: string[]; + let language: string; + if (entry.hunk && (entry.hunk.baseLines.length > 0 || entry.hunk.diskLines.length > 0)) { + lines = [...entry.hunk.baseLines.map((line) => `-${stripCr(line)}`), ...entry.hunk.diskLines.map((line) => `+${stripCr(line)}`)]; + language = 'diff'; + } else if (typeof entry.lineText === 'string') { + lines = [stripCr(entry.lineText)]; + language = ''; + } else { + return null; + } + if (lines.length > MAX_QUOTED_LINES) { + const hidden = lines.length - MAX_QUOTED_LINES; + lines = [...lines.slice(0, MAX_QUOTED_LINES), `... (${hidden} more line${hidden === 1 ? '' : 's'})`]; + } + const fence = fenceFor(lines); + return `${fence}${language}\n${lines.join('\n')}\n${fence}`; +} + +/** A backtick fence longer than any run of backticks in the quote. */ +function fenceFor(lines: readonly string[]): string { + let longest = 0; + for (const line of lines) { + for (const run of line.match(/`+/g) ?? []) { + longest = Math.max(longest, run.length); + } + } + return '`'.repeat(Math.max(3, longest + 1)); +} + +function indent(text: string): string { + return text.split('\n').map((line) => (line === '' ? line : ` ${line}`)).join('\n'); +} + +/** A comment on one line of the list: its lines joined by spaces, blank ones dropped. */ +function oneParagraph(text: string): string { + return text.replace(/\r\n?/g, '\n').trim().split('\n').map((line) => line.trim()).filter((line) => line !== '').join(' '); +} + +function stripCr(line: string): string { + return line.endsWith('\r') ? line.slice(0, -1) : line; +} diff --git a/apps/vscode-extension/test/agent_review/hunkReview.test.cjs b/apps/vscode-extension/test/agent_review/hunkReview.test.cjs new file mode 100644 index 00000000..7341ab5b --- /dev/null +++ b/apps/vscode-extension/test/agent_review/hunkReview.test.cjs @@ -0,0 +1,20 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { splitHunks, revertHunks, keepHunks, StaleHunkError } = require('../../out/core/agent-review/hunkReview.js'); +const { formatReviewComments } = require('../../out/core/agent-review/reviewComments.js'); + +// #521: per-hunk review lives in the core so this extension's chat can reuse it (the IDE tests it in depth). +test('the core splits base -> disk into hunks and reverts or keeps one of them (#521)', () => { + const base = 'a\r\nb\r\nc\r\nd\r\n'; + const disk = 'A\r\nb\r\nc\r\nD\r\n'; + const hunks = splitHunks(base, disk); + assert.equal(hunks.length, 2); + assert.equal(revertHunks(base, disk, [hunks[0].id]), 'a\r\nb\r\nc\r\nD\r\n'); + assert.equal(keepHunks(base, disk, [hunks[1].id]), 'a\r\nb\r\nc\r\nD\r\n'); + assert.throws(() => revertHunks(base, disk, ['nope']), StaleHunkError); +}); + +test('the core formats line comments as one follow-up prompt (#521)', () => { + const text = formatReviewComments([{ path: 'src/a.ts', line: 3, comment: 'Use a constant.', hunk: { baseLines: ['x = 1'], diskLines: ['x = 2'] } }]); + assert.match(text, /1\. src\/a\.ts:3 — Use a constant\.\n {3}```diff\n {3}-x = 1\n {3}\+x = 2\n {3}```/); +}); From 48ca1595fdad488ac916defa2d1c3c5432fb10e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:34:07 +0000 Subject: [PATCH 21/74] feat(ide): sidecar log file and a fatal dialog that names it (#506) - The sidecar logger also writes a rotating log (2 files x 2 MB, sidecar.log / sidecar.1.log) in the platform log folder, which the core passes as CODEXR_LOG_DIR (Tauri app_log_dir) and the sidecar takes out of its environment. - A non-zero host.app.exit (a failed start-up) and an unexpected sidecar exit show a dialog with the log path, distinguishing start-up from later; benchmark and smoke runs show none. A sidecar that cannot be spawned shows one too instead of a panic. - The sidecar's last stderr lines that its logger did not write (a crash before the log file opened) are appended to the log when it dies. --- apps/ide/src-tauri/src/host.rs | 6 + apps/ide/src-tauri/src/main.rs | 16 ++- apps/ide/src-tauri/src/native.rs | 9 ++ apps/ide/src-tauri/src/sidecar.rs | 197 +++++++++++++++++++++++++++--- apps/ide/src/main/log.ts | 24 +++- apps/ide/src/main/logFile.ts | 105 ++++++++++++++++ apps/ide/src/sidecar/index.ts | 8 +- apps/ide/test/logFile.test.ts | 68 +++++++++++ 8 files changed, 408 insertions(+), 25 deletions(-) create mode 100644 apps/ide/src/main/logFile.ts create mode 100644 apps/ide/test/logFile.test.ts diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index 58c3f4f1..49114051 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -263,6 +263,12 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) "app.exit" => { let code = params.get("code").and_then(Value::as_i64).unwrap_or(0) as i32; sidecar.begin_exit(); + // #506: an exit for an error (a failed start-up, src/sidecar/index.ts) says so, with the log's path. + let started = app.try_state::>().is_some_and(|native| native.ipc_is_open()); + if let Some(message) = sidecar.fatal_notice(&crate::sidecar::SidecarExit::Requested(code), started) { + eprintln!("[codexr-ide] The Node sidecar asked to exit with code {code}."); + show_fatal(app, &message); + } app.exit(code); Ok(Value::Null) } diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index e1993038..34c9a9e6 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -321,7 +321,21 @@ fn main() { let cache_dir = app.path().app_cache_dir().ok(); // The switch is the webview's alone: the sidecar's children (terminals) do not inherit it. let unset = if set_dmabuf_switch { vec![DMABUF_SWITCH] } else { Vec::new() }; - sidecar.start(app.handle().clone(), &layout, &args, cache_dir.as_deref(), &unset)?; + // #506: the sidecar's rotating log file lives in the platform's log folder. + let log_dir = app.path().app_log_dir().ok(); + if let Err(error) = sidecar.start(app.handle().clone(), &layout, &args, cache_dir.as_deref(), log_dir.as_deref(), &unset) { + if bench || smoke { + return Err(error.into()); + } + // An installed IDE has no terminal: the reason is shown, then the app ends (once its loop runs). + eprintln!("[codexr-ide] {error}"); + let app = app.handle().clone(); + std::thread::spawn(move || { + host::show_fatal(&app, &format!("The Code-XR IDE could not start.\n\n{error}")); + app.exit(1); + }); + return Ok(()); + } let url = host::main_window_url(&locale::initial_locale(cache_dir.as_deref(), bench), bench); eprintln!("[codexr-ide] Opening the main window on {url}"); host::open_main_window(app.handle(), &shell, &sidecar, url)?; diff --git a/apps/ide/src-tauri/src/native.rs b/apps/ide/src-tauri/src/native.rs index d179f815..88cd9d6a 100644 --- a/apps/ide/src-tauri/src/native.rs +++ b/apps/ide/src-tauri/src/native.rs @@ -107,6 +107,10 @@ impl IpcGate { self.opened.notify_all(); } + pub fn is_open(&self) -> bool { + *self.open.lock().unwrap() + } + /// Returns once the gate is open, or after `timeout`; whether it is open. pub fn wait(&self, timeout: Duration) -> bool { let open = self.open.lock().unwrap(); @@ -199,6 +203,11 @@ impl Native { self.ipc.open(); } + /// #506: whether the sidecar got as far as opening IPC (its start-up is over). + pub fn ipc_is_open(&self) -> bool { + self.ipc.is_open() + } + /// #499: waits (on a blocking thread) until the sidecar opened IPC. The page loads while the sidecar boots /// and can call before it is ready: a folder channel answered then said "No folder is open in this window" /// for the folder the window was opening. The sidecar's own channels wait for it the same way (tauriHost.ts). diff --git a/apps/ide/src-tauri/src/sidecar.rs b/apps/ide/src-tauri/src/sidecar.rs index cebf5c2d..7687ac9b 100644 --- a/apps/ide/src-tauri/src/sidecar.rs +++ b/apps/ide/src-tauri/src/sidecar.rs @@ -4,17 +4,19 @@ //! Core to sidecar: `ipc.invoke` (requests), `window.event`, //! `app.secondInstance` (notifications). Sidecar to core: `webview.send` //! (notifications, delivered on the webview's event channel) and `host.` -//! (requests, answered by host.rs). The sidecar logs to stderr only; lines -//! that start with `CODEXR_` (the benchmark's and smoke run's result lines) -//! are passed to this process's stdout, everything else to its stderr. +//! (requests, answered by host.rs). The sidecar logs to stderr and (#506) to a +//! rotating `sidecar.log` in the app's log folder; lines on its stderr that +//! start with `CODEXR_` (the benchmark's and smoke run's result lines) are +//! passed to this process's stdout, everything else to its stderr. A sidecar +//! that fails or dies shows a dialog naming that file (`fatal_message`). -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::io::{BufRead, BufReader, Write}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::Duration; use serde_json::{json, Value}; @@ -82,6 +84,63 @@ pub struct Sidecar { /// The thread that runs the host requests of `host::runs_in_sequence`, started on first use. sequence: Mutex>>, pub events: Events, + /// #506: the sidecar's log file (`/sidecar.log`), named by the fatal dialog. + log_file: Mutex>, + /// #506: false in a benchmark or smoke run, which nobody watches: no dialog may hold it. + interactive: AtomicBool, + /// #506: the sidecar's last stderr lines that did not come from its logger (a crash before + /// the log file opened, Node's own fatal errors), appended to the log file if it dies. + stderr_tail: Arc>>, +} + +/// How many of the sidecar's last stderr lines are kept for its log (#506). +const STDERR_TAIL_LINES: usize = 60; +/// The sidecar logger's prefix (src/main/log.ts): those lines are in the log file already. +const LOGGER_PREFIX: &str = "[code-xr-ide]"; +/// The log file's name in the log folder (src/main/logFile.ts `LOG_FILE_NAME`). +pub const LOG_FILE_NAME: &str = "sidecar.log"; + +/// Why the sidecar ended (#506). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SidecarExit { + /// It asked the core to end the app (`host.app.exit`) with this code. + Requested(i32), + /// The process ended on its own (a crash, `process.exit`), with this status. + Unexpected(String), +} + +/// #506: the message of the fatal dialog for a sidecar exit, or None when no dialog is due: a +/// requested exit with code 0, or a run nobody watches (a benchmark or smoke run). `started`: +/// the sidecar had opened IPC (its services were up). An installed IDE has no terminal, so the +/// dialog names the log file; without one (no log folder) the log is in the terminal. +pub fn fatal_message(exit: &SidecarExit, started: bool, interactive: bool, log_file: Option<&Path>) -> Option { + if !interactive || *exit == SidecarExit::Requested(0) { + return None; + } + let what = match (exit, started) { + (SidecarExit::Requested(code), false) => format!("The Code-XR IDE could not start (exit code {code})."), + (SidecarExit::Requested(code), true) => format!("The Code-XR IDE stopped because of an error (exit code {code})."), + (SidecarExit::Unexpected(status), false) => format!("The Code-XR IDE's Node process stopped while starting ({status})."), + (SidecarExit::Unexpected(status), true) => format!("The Code-XR IDE's Node process stopped ({status})."), + }; + let log = match log_file { + Some(file) => format!("Its log, to attach to a report:\n{}", file.display()), + None => "Its log is in the terminal that started it.".to_string(), + }; + Some(format!("{what} The IDE will close.\n\n{log}")) +} + +/// Appends the sidecar's last stderr lines to its log file, once it is gone (no other writer). +fn append_stderr_tail(file: &Path, status: &str, lines: &[String]) -> std::io::Result<()> { + if let Some(folder) = file.parent() { + std::fs::create_dir_all(folder)?; + } + let mut out = std::fs::OpenOptions::new().create(true).append(true).open(file)?; + writeln!(out, "--- The Node process stopped ({status}); its last output that was not logged above: ---")?; + for line in lines { + writeln!(out, "{line}")?; + } + out.flush() } impl Sidecar { @@ -95,9 +154,17 @@ impl Sidecar { exiting: AtomicBool::new(false), sequence: Mutex::new(None), events: Events::new(), + log_file: Mutex::new(None), + interactive: AtomicBool::new(true), + stderr_tail: Arc::new(Mutex::new(VecDeque::new())), } } + /// #506: the fatal dialog's message for this exit, if one is due (`fatal_message`). + pub fn fatal_notice(&self, exit: &SidecarExit, started: bool) -> Option { + fatal_message(exit, started, self.interactive.load(Ordering::SeqCst), self.log_file.lock().unwrap().as_deref()) + } + pub fn is_alive(&self) -> bool { self.alive.load(Ordering::SeqCst) } @@ -117,8 +184,12 @@ impl Sidecar { /// `cache_dir` is the app's cache folder: V8's compile cache of the sidecar lives /// there (NODE_COMPILE_CACHE, about 45 ms of its start-up once warm) and the /// sidecar keeps its last display language beside it (locale.rs). `unset` are - /// variables the core set for its webview only. - pub fn start(self: &std::sync::Arc, app: AppHandle, layout: &crate::install::Layout, args: &[String], cache_dir: Option<&Path>, unset: &[&str]) -> Result<(), String> { + /// variables the core set for its webview only. `log_dir` is the app's log folder: the + /// sidecar keeps its rotating log there (`CODEXR_LOG_DIR`, src/main/logFile.ts, #506). + pub fn start(self: &std::sync::Arc, app: AppHandle, layout: &crate::install::Layout, args: &[String], cache_dir: Option<&Path>, log_dir: Option<&Path>, unset: &[&str]) -> Result<(), String> { + let unwatched = args.iter().any(|arg| arg == "--codexr-bench" || arg == crate::smoke::SMOKE_FLAG); + self.interactive.store(!unwatched, Ordering::SeqCst); + *self.log_file.lock().unwrap() = log_dir.map(|dir| dir.join(LOG_FILE_NAME)); let script = std::env::var_os("CODEXR_SIDECAR") .map(std::path::PathBuf::from) .unwrap_or_else(|| layout.out.join("sidecar").join("index.cjs")); @@ -147,6 +218,11 @@ impl Sidecar { // The sidecar takes both out of its environment before starting any child. command.env("NODE_COMPILE_CACHE", dir.join("node-compile-cache")).env("CODEXR_CACHE_DIR", dir); } + match log_dir { + // Taken out of its environment at once too (src/sidecar/index.ts). + Some(dir) => command.env("CODEXR_LOG_DIR", dir), + None => command.env_remove("CODEXR_LOG_DIR"), + }; let mut child = command .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -161,17 +237,29 @@ impl Sidecar { self.alive.store(true, Ordering::SeqCst); // The sidecar's logs, and the result lines harnesses read from stdout. - std::thread::spawn(move || { - for line in BufReader::new(stderr).lines().map_while(Result::ok) { - if line.starts_with("CODEXR_") { - let mut out = std::io::stdout().lock(); - let _ = writeln!(out, "{line}"); - let _ = out.flush(); - } else { - eprintln!("{line}"); + let (stderr_closed, stderr_done) = mpsc::channel::<()>(); + { + let tail = self.stderr_tail.clone(); + std::thread::spawn(move || { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if line.starts_with("CODEXR_") { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{line}"); + let _ = out.flush(); + } else { + eprintln!("{line}"); + if !line.starts_with(LOGGER_PREFIX) { + let mut tail = tail.lock().unwrap(); + if tail.len() == STDERR_TAIL_LINES { + tail.pop_front(); + } + tail.push_back(line); + } + } } - } - }); + let _ = stderr_closed.send(()); + }); + } // The protocol. { @@ -205,12 +293,25 @@ impl Sidecar { this.died(); app.state::>().release_csp(); // #499: nothing waits for the sidecar's IPC any more either. - if let Some(native) = app.try_state::>() { + let native = app.try_state::>(); + let started = native.as_ref().is_some_and(|native| native.ipc_is_open()); + if let Some(native) = native { native.open_ipc(); } if !this.is_exiting() { eprintln!("[codexr-ide] The Node sidecar exited unexpectedly ({status})."); - host::show_fatal(&app, &format!("The Code-XR IDE's Node process stopped ({status}). The IDE will close; its log is in the terminal that started it.")); + let status = status.to_string(); + // #506: what it printed outside its logger (a crash before the log file opened) goes to the log too. + let _ = stderr_done.recv_timeout(Duration::from_millis(500)); + let lines: Vec = this.stderr_tail.lock().unwrap().drain(..).collect(); + if let Some(file) = this.log_file.lock().unwrap().clone() { + if let Err(error) = append_stderr_tail(&file, &status, &lines) { + eprintln!("[codexr-ide] Could not write to {}: {error}", file.display()); + } + } + if let Some(message) = this.fatal_notice(&SidecarExit::Unexpected(status), started) { + host::show_fatal(&app, &message); + } app.exit(1); } return; @@ -359,3 +460,59 @@ impl Sidecar { let _ = waiter.send(result); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_failed_or_unexpected_exit_shows_the_log_path_and_a_clean_one_nothing() { + let log = Path::new("/logs/sidecar.log"); + assert_eq!(fatal_message(&SidecarExit::Requested(0), true, true, Some(log)), None, "a quit"); + assert_eq!(fatal_message(&SidecarExit::Requested(0), false, true, Some(log)), None); + + let start_up = fatal_message(&SidecarExit::Requested(1), false, true, Some(log)).unwrap(); + assert!(start_up.starts_with("The Code-XR IDE could not start (exit code 1)."), "{start_up}"); + assert!(start_up.contains(&log.display().to_string())); + let later = fatal_message(&SidecarExit::Requested(2), true, true, Some(log)).unwrap(); + assert!(later.contains("stopped because of an error (exit code 2)"), "{later}"); + + let crash = fatal_message(&SidecarExit::Unexpected("exit status: 0".into()), true, true, Some(log)).unwrap(); + assert!(crash.contains("Node process stopped (exit status: 0)") && crash.contains("sidecar.log"), "{crash}"); + let early = fatal_message(&SidecarExit::Unexpected("signal: 9".into()), false, true, Some(log)).unwrap(); + assert!(early.contains("stopped while starting (signal: 9)"), "{early}"); + + let no_folder = fatal_message(&SidecarExit::Requested(1), false, true, None).unwrap(); + assert!(no_folder.ends_with("Its log is in the terminal that started it."), "{no_folder}"); + } + + #[test] + fn a_run_nobody_watches_shows_no_dialog() { + let log = Some(Path::new("/logs/sidecar.log")); + assert_eq!(fatal_message(&SidecarExit::Requested(1), true, false, log), None); + assert_eq!(fatal_message(&SidecarExit::Unexpected("exit status: 1".into()), true, false, log), None); + } + + #[test] + fn the_last_unlogged_output_is_appended_to_the_log() { + let dir = crate::workspace::tests::Scratch::new("sidecar-log"); + let file = dir.0.join("logs").join(LOG_FILE_NAME); + append_stderr_tail(&file, "exit status: 1", &["Error: Cannot find module 'x'".into(), " at load".into()]).unwrap(); + append_stderr_tail(&file, "exit status: 2", &[]).unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 4); + assert!(lines[0].contains("exit status: 1")); + assert_eq!(lines[1], "Error: Cannot find module 'x'"); + assert!(lines[3].contains("exit status: 2")); + } + + #[test] + fn the_sidecar_knows_its_log_file_only_once_started() { + let sidecar = Sidecar::new(); + let notice = sidecar.fatal_notice(&SidecarExit::Requested(1), false).unwrap(); + assert!(notice.contains("terminal that started it")); + *sidecar.log_file.lock().unwrap() = Some(PathBuf::from("/logs").join(LOG_FILE_NAME)); + assert!(sidecar.fatal_notice(&SidecarExit::Requested(1), false).unwrap().contains(LOG_FILE_NAME)); + } +} diff --git a/apps/ide/src/main/log.ts b/apps/ide/src/main/log.ts index cb8ec2c6..d385b7fb 100644 --- a/apps/ide/src/main/log.ts +++ b/apps/ide/src/main/log.ts @@ -1,9 +1,11 @@ import type { OutputChannelId } from '../shared/output.ts'; +import { formatLogLine, RotatingLogFile } from './logFile.ts'; /** - * Main-process logging. Lines go to the terminal that started the IDE and, - * once the Output panel's service is up (#174), to its channels. No - * telemetry, ever. + * Main-process logging. Lines go to the terminal that started the IDE, to a + * rotating file in the app's log folder once the sidecar opened it (#506, + * logFile.ts: an installed IDE has no terminal) and, once the Output panel's + * service is up (#174), to its channels. No telemetry, ever. */ const PREFIX = '[code-xr-ide]'; @@ -11,12 +13,25 @@ export type LogLevel = 'info' | 'warn' | 'error'; export type LogSink = (channel: OutputChannelId, level: LogLevel, message: string) => void; let sink: LogSink | null = null; +let logFile: RotatingLogFile | null = null; /** #174: where every line also goes (the Output panel); null detaches it. */ export function setLogSink(next: LogSink | null): void { sink = next; } +/** #506: every line also goes to `/sidecar.log` (rotated); returns its path. */ +export function startLogFile(dir: string): string { + logFile?.close(); + logFile = new RotatingLogFile(dir); + logFile.write(formatLogLine(new Date(), 'info', 'ide', `Code-XR IDE sidecar started (pid ${process.pid}, Node ${process.version}, ${process.platform}).`)); + return logFile.file; +} + +function toFile(channel: OutputChannelId, level: LogLevel, message: string): void { + logFile?.write(formatLogLine(new Date(), level, channel, message)); +} + function describe(error: unknown): string { if (error === undefined || error === '') { return ''; @@ -35,14 +50,17 @@ export function channelLog(channel: OutputChannelId): Logger { return { info(message: string): void { console.log(`${PREFIX} ${message}`); + toFile(channel, 'info', message); sink?.(channel, 'info', message); }, warn(message: string): void { console.warn(`${PREFIX} ${message}`); + toFile(channel, 'warn', message); sink?.(channel, 'warn', message); }, error(message: string, error?: unknown): void { console.error(`${PREFIX} ${message}`, error ?? ''); + toFile(channel, 'error', `${message}${describe(error)}`); sink?.(channel, 'error', `${message}${describe(error)}`); }, }; diff --git a/apps/ide/src/main/logFile.ts b/apps/ide/src/main/logFile.ts new file mode 100644 index 00000000..9b4d57fc --- /dev/null +++ b/apps/ide/src/main/logFile.ts @@ -0,0 +1,105 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * #506: the sidecar's log on disk, for an installed IDE that has no terminal + * to print to. Lines go to `/sidecar.log`; once it would pass + * `maxBytes`, it becomes `sidecar.1.log` (the one before is dropped) and a + * new file starts, so the folder never holds more than `files` x `maxBytes`. + * Writes are synchronous, so the last lines before a crash are on disk; any + * error turns the file off for good (logging never fails the IDE). + */ +export const LOG_FILE_NAME = 'sidecar.log'; +export const LOG_MAX_BYTES = 2 * 1024 * 1024; +export const LOG_FILES = 2; + +export interface RotatingLogOptions { + maxBytes?: number; + /** How many files are kept, the current one included (at least 1). */ + files?: number; +} + +/** `sidecar.log`, `sidecar.1.log`, `sidecar.2.log`… */ +export function rotatedName(name: string, index: number): string { + if (index === 0) { + return name; + } + const extension = path.extname(name); + return `${name.slice(0, name.length - extension.length)}.${index}${extension}`; +} + +export class RotatingLogFile { + readonly dir: string; + readonly file: string; + private readonly maxBytes: number; + private readonly files: number; + private fd: number | null = null; + private size = 0; + private failed = false; + + constructor(dir: string, name = LOG_FILE_NAME, options: RotatingLogOptions = {}) { + this.dir = dir; + this.file = path.join(dir, name); + this.maxBytes = options.maxBytes ?? LOG_MAX_BYTES; + this.files = Math.max(1, options.files ?? LOG_FILES); + } + + /** Appends one line (a newline is added); false once the file is off. */ + write(line: string): boolean { + if (this.failed) { + return false; + } + try { + const bytes = Buffer.from(`${line}\n`, 'utf8'); + if (this.fd === null) { + this.open(); + } + if (this.size > 0 && this.size + bytes.length > this.maxBytes) { + this.rotate(); + } + fs.writeSync(this.fd as number, bytes); + this.size += bytes.length; + return true; + } catch { + this.failed = true; + this.close(); + return false; + } + } + + close(): void { + if (this.fd !== null) { + try { + fs.closeSync(this.fd); + } catch { + // Already gone. + } + this.fd = null; + } + } + + private open(): void { + fs.mkdirSync(this.dir, { recursive: true }); + this.fd = fs.openSync(this.file, 'a'); + this.size = fs.fstatSync(this.fd).size; + } + + private rotate(): void { + this.close(); + const name = path.basename(this.file); + // The oldest is dropped, each other moves one up (renaming over a file works on Windows too). + fs.rmSync(path.join(this.dir, rotatedName(name, this.files - 1)), { force: true }); + for (let index = this.files - 2; index >= 0; index -= 1) { + const from = path.join(this.dir, rotatedName(name, index)); + if (fs.existsSync(from)) { + fs.renameSync(from, path.join(this.dir, rotatedName(name, index + 1))); + } + } + this.open(); + } +} + +/** One log line: time, level, channel, message. */ +export function formatLogLine(time: Date, level: string, channel: string, message: string): string { + return `${time.toISOString()} ${level.toUpperCase().padEnd(5)} [${channel}] ${message}`; +} diff --git a/apps/ide/src/sidecar/index.ts b/apps/ide/src/sidecar/index.ts index 9c1c814c..5e367a1a 100644 --- a/apps/ide/src/sidecar/index.ts +++ b/apps/ide/src/sidecar/index.ts @@ -9,7 +9,7 @@ import { webviewFrameSources } from '../shared/extensionWebviewProtocol.ts'; import { APP_ORIGIN, buildContentSecurityPolicy, trustedOrigins } from '../main/security.ts'; import { BENCH_FLAG } from '../main/bench.ts'; import { SMOKE_FLAG } from '../main/smoke.ts'; -import { log } from '../main/log.ts'; +import { log, startLogFile } from '../main/log.ts'; /** * The Node sidecar (#482, epic #477). @@ -78,6 +78,12 @@ function connect(): RpcPeer { const cacheDir = process.env['CODEXR_CACHE_DIR'] ?? null; delete process.env['CODEXR_CACHE_DIR']; delete process.env['NODE_COMPILE_CACHE']; +// #506: the app's log folder, given by the core: the log file there is what its fatal dialog points at. +const logDir = process.env['CODEXR_LOG_DIR']; +delete process.env['CODEXR_LOG_DIR']; +if (logDir) { + startLogFile(logDir); +} /** #488: the profile migration's secrets step, over the core and the Tauri cipher. */ const migrationHost: SecretsMigrationHost = { diff --git a/apps/ide/test/logFile.test.ts b/apps/ide/test/logFile.test.ts new file mode 100644 index 00000000..6e90e701 --- /dev/null +++ b/apps/ide/test/logFile.test.ts @@ -0,0 +1,68 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { formatLogLine, LOG_FILES, LOG_MAX_BYTES, RotatingLogFile, rotatedName } from '../src/main/logFile.ts'; + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-log-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +describe('RotatingLogFile (#506)', () => { + it('keeps two files of 2 MB by default', () => { + assert.equal(LOG_MAX_BYTES, 2 * 1024 * 1024); + assert.equal(LOG_FILES, 2); + assert.equal(rotatedName('sidecar.log', 0), 'sidecar.log'); + assert.equal(rotatedName('sidecar.log', 1), 'sidecar.1.log'); + }); + + it('creates its folder and appends to what an earlier run left', () => { + const dir = path.join(base, 'append', 'logs'); + const first = new RotatingLogFile(dir); + assert.ok(first.write('one')); + first.close(); + const second = new RotatingLogFile(dir); + assert.ok(second.write('two')); + second.close(); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.log'), 'utf8'), 'one\ntwo\n'); + }); + + it('rotates before a line would pass the limit and keeps only the configured files', () => { + const dir = path.join(base, 'rotate'); + const log = new RotatingLogFile(dir, 'sidecar.log', { maxBytes: 20, files: 2 }); + for (const line of ['aaaaaaaaa', 'bbbbbbbbb', 'ccccccccc', 'ddddddddd', 'eeeeeeeee']) { + log.write(line); + } + log.close(); + assert.deepEqual(fs.readdirSync(dir).sort(), ['sidecar.1.log', 'sidecar.log']); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.1.log'), 'utf8'), 'ccccccccc\nddddddddd\n'); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.log'), 'utf8'), 'eeeeeeeee\n'); + for (const name of fs.readdirSync(dir)) { + assert.ok(fs.statSync(path.join(dir, name)).size <= 20); + } + }); + + it('writes a line longer than the limit into a file of its own', () => { + const dir = path.join(base, 'long'); + const log = new RotatingLogFile(dir, 'sidecar.log', { maxBytes: 10, files: 3 }); + log.write('short'); + log.write('x'.repeat(30)); + log.write('next'); + log.close(); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.2.log'), 'utf8'), 'short\n'); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.1.log'), 'utf8'), `${'x'.repeat(30)}\n`); + assert.equal(fs.readFileSync(path.join(dir, 'sidecar.log'), 'utf8'), 'next\n'); + }); + + it('turns itself off when the folder cannot be written, without throwing', () => { + const blocker = path.join(base, 'blocker'); + fs.writeFileSync(blocker, ''); + const log = new RotatingLogFile(path.join(blocker, 'logs')); + assert.equal(log.write('lost'), false); + assert.equal(log.write('lost too'), false); + }); + + it('formats time, level and channel', () => { + assert.equal(formatLogLine(new Date(Date.UTC(2026, 11, 5, 21, 0, 0)), 'warn', 'ide', 'hello'), '2026-12-05T21:00:00.000Z WARN [ide] hello'); + }); +}); From 288eddf3476ab996e5e9a1009f7d34e19dc863fc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:34:08 +0000 Subject: [PATCH 22/74] feat(ide): edit review dialog traps Tab, closes on Escape and returns focus (#525) --- apps/ide/src/renderer/agents/editReview.ts | 20 +++++++++- apps/ide/src/renderer/focusTrap.ts | 35 ++++++++++++++++++ apps/ide/src/renderer/focusTrapModel.ts | 21 +++++++++++ apps/ide/src/renderer/tour/tourView.ts | 12 ++---- apps/ide/test/focusTrap.test.ts | 43 ++++++++++++++++++++++ 5 files changed, 121 insertions(+), 10 deletions(-) create mode 100644 apps/ide/src/renderer/focusTrap.ts create mode 100644 apps/ide/src/renderer/focusTrapModel.ts create mode 100644 apps/ide/test/focusTrap.test.ts diff --git a/apps/ide/src/renderer/agents/editReview.ts b/apps/ide/src/renderer/agents/editReview.ts index 1855aaea..efce3627 100644 --- a/apps/ide/src/renderer/agents/editReview.ts +++ b/apps/ide/src/renderer/agents/editReview.ts @@ -2,6 +2,7 @@ import type { editor } from 'monaco-editor'; import type { EditReviewRequest, EditReviewResult } from '../../shared/agents.ts'; import { applyHunks, diffLines, type Hunk } from '../../shared/lineDiff.ts'; import { el } from '../dom.ts'; +import { trapTab } from '../focusTrap.ts'; /** * The review of a change an agent proposes (A8): a Monaco diff over the @@ -30,6 +31,8 @@ export function createEditReviewer(host: HTMLElement, hooks: EditReviewHooks): ( } async function review(host: HTMLElement, hooks: EditReviewHooks, request: EditReviewRequest): Promise { + // #525: the focus goes back where it was when the review closes. + const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; const hunks = diffLines(request.original, request.proposed); const accepted = new Set(hunks.map((_, index) => index)); const { monaco } = await import('../editor/monaco.ts'); @@ -40,7 +43,7 @@ async function review(host: HTMLElement, hooks: EditReviewHooks, request: EditRe const acceptAll = el('button', { className: 'secondary-button', text: 'Accept all', attrs: { type: 'button', 'data-action': 'accept-all' } }); const reject = el('button', { className: 'secondary-button', text: 'Reject', attrs: { type: 'button', 'data-action': 'reject' } }); const error = el('p', { className: 'error small', attrs: { role: 'alert', hidden: '' } }); - const layer = el('div', { className: 'edit-review', attrs: { role: 'dialog', 'aria-modal': 'false', 'aria-label': `Review change to ${request.path}`, 'data-testid': 'edit-review' } }, [ + const layer = el('div', { className: 'edit-review', attrs: { role: 'dialog', 'aria-modal': 'true', 'aria-label': `Review change to ${request.path}`, 'data-testid': 'edit-review' } }, [ el('div', { className: 'edit-review-head' }, [ el('div', { className: 'edit-review-title' }, [ el('span', { className: 'edit-review-kicker', text: request.isNew ? 'New file proposed by an agent' : 'Change proposed by an agent' }), @@ -98,7 +101,11 @@ async function review(host: HTMLElement, hooks: EditReviewHooks, request: EditRe diff?.dispose(); original.dispose(); proposed.dispose(); + const hadFocus = layer.contains(document.activeElement); layer.remove(); + if ((hadFocus || document.activeElement === document.body) && returnFocus?.isConnected) { + returnFocus.focus(); + } resolve(result); }; const apply = async (chosen: ReadonlySet): Promise => { @@ -127,6 +134,17 @@ async function review(host: HTMLElement, hooks: EditReviewHooks, request: EditRe applySelected.addEventListener('click', () => void apply(accepted)); acceptAll.addEventListener('click', () => void apply(new Set(hunks.map((_, index) => index)))); reject.addEventListener('click', () => finish({ outcome: 'rejected', accepted: 0, total: hunks.length })); + // #525: Tab stays in the review; Escape rejects it (unless Monaco used the key, or a write is running). + layer.addEventListener('keydown', (event) => { + if (trapTab(event, layer)) { + return; + } + if (event.key === 'Escape' && !event.defaultPrevented && !reject.disabled) { + event.preventDefault(); + event.stopPropagation(); + reject.click(); + } + }); }); } diff --git a/apps/ide/src/renderer/focusTrap.ts b/apps/ide/src/renderer/focusTrap.ts new file mode 100644 index 00000000..b7905d76 --- /dev/null +++ b/apps/ide/src/renderer/focusTrap.ts @@ -0,0 +1,35 @@ +/** + * #525 (O23): keeps Tab inside a dialog (the guided tour's card, the review of + * an agent's edit). `trapTabTarget` (focusTrapModel.ts) is the pure decision, unit-tested; + * `trapTab` applies it to a keydown and `focusablesIn` lists what Tab visits. + */ +import { trapTabTarget } from './focusTrapModel.ts'; + +const FOCUSABLE = 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex]:not([tabindex="-1"])'; + +/** The elements of `container` Tab visits, in order (hidden ones left out). */ +export function focusablesIn(container: HTMLElement, selector = FOCUSABLE): HTMLElement[] { + return [...container.querySelectorAll(selector)].filter((node) => !node.closest('[hidden]') && node.getClientRects().length > 0); +} + +/** + * Handles a Tab keydown for `container`: wraps from the last element to the + * first (and back with Shift), and brings an outside focus back in. Returns + * whether the key was a Tab (so the caller stops looking at it). + */ +export function trapTab(event: KeyboardEvent, container: HTMLElement, focusables: readonly HTMLElement[] = focusablesIn(container)): boolean { + if (event.key !== 'Tab') { + return false; + } + const active = document.activeElement; + const inside = active instanceof HTMLElement && container.contains(active); + const index = inside ? focusables.indexOf(active) : -1; + // Focus inside the container but on nothing listed (a Monaco editor's own field): leave it to the browser. + const target = inside && index < 0 ? null : trapTabTarget(focusables.length, index, event.shiftKey); + const element = target === null ? undefined : focusables[target]; + if (element) { + event.preventDefault(); + element.focus(); + } + return true; +} diff --git a/apps/ide/src/renderer/focusTrapModel.ts b/apps/ide/src/renderer/focusTrapModel.ts new file mode 100644 index 00000000..1c92bf78 --- /dev/null +++ b/apps/ide/src/renderer/focusTrapModel.ts @@ -0,0 +1,21 @@ +/** #525 (O23): the pure part of the focus trap (`focusTrap.ts`), free of the DOM so it is unit-tested. */ + +/** Where Tab must go, as an index into the focusable elements, or null to let the browser move it. */ +export function trapTabTarget(count: number, activeIndex: number, shift: boolean): number | null { + if (count === 0) { + return null; + } + const first = 0; + const last = count - 1; + if (activeIndex < 0) { + // The focus is outside: it comes back in at the end it would enter from. + return shift ? last : first; + } + if (shift && activeIndex === first) { + return last; + } + if (!shift && activeIndex === last) { + return first; + } + return null; +} diff --git a/apps/ide/src/renderer/tour/tourView.ts b/apps/ide/src/renderer/tour/tourView.ts index cafeba9b..7e26b9bd 100644 --- a/apps/ide/src/renderer/tour/tourView.ts +++ b/apps/ide/src/renderer/tour/tourView.ts @@ -1,4 +1,5 @@ import { el } from '../dom.ts'; +import { trapTab } from '../focusTrap.ts'; import type { ViewId } from '../workbench.ts'; import { currentStep, placePopover, reduceTour, spotlightRect, stepPosition, TOUR_CLOSED, tourKeyAction, @@ -275,17 +276,10 @@ export function createGuidedTour(deps: GuidedTourDeps): GuidedTour { if (event.key === 'Tab') { // The focus stays in the card while the tour is open. const list = focusables(); - const first = list[0]; - const last = list[list.length - 1]; - if (!first || !last) { + if (list.length === 0) { return; } - const active = document.activeElement; - const inside = active instanceof HTMLElement && card.contains(active); - if (!inside || (event.shiftKey && active === first) || (!event.shiftKey && active === last)) { - event.preventDefault(); - (event.shiftKey ? last : first).focus(); - } + trapTab(event, card, list); event.stopPropagation(); return; } diff --git a/apps/ide/test/focusTrap.test.ts b/apps/ide/test/focusTrap.test.ts new file mode 100644 index 00000000..00f9bb6d --- /dev/null +++ b/apps/ide/test/focusTrap.test.ts @@ -0,0 +1,43 @@ +// #525 (O23): the shared focus trap of the guided tour and the edit review dialog. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { trapTabTarget } from '../src/renderer/focusTrapModel.ts'; + +describe('trapTabTarget', () => { + it('wraps from the last element to the first, and back with Shift', () => { + assert.equal(trapTabTarget(3, 2, false), 0); + assert.equal(trapTabTarget(3, 0, true), 2); + }); + + it('lets the browser move between the elements in the middle', () => { + assert.equal(trapTabTarget(3, 0, false), null); + assert.equal(trapTabTarget(3, 1, true), null); + }); + + it('brings a focus from outside back in at the end Tab enters from', () => { + assert.equal(trapTabTarget(3, -1, false), 0); + assert.equal(trapTabTarget(3, -1, true), 2); + }); + + it('keeps a lone element focused and does nothing with none', () => { + assert.equal(trapTabTarget(1, 0, false), 0); + assert.equal(trapTabTarget(1, 0, true), 0); + assert.equal(trapTabTarget(0, -1, false), null); + }); +}); + +describe('the dialogs use it', () => { + it('the edit review traps Tab, closes on Escape and gives the focus back', () => { + const source = readFileSync(new URL('../src/renderer/agents/editReview.ts', import.meta.url), 'utf8'); + assert.match(source, /trapTab\(event, layer\)/); + assert.match(source, /event\.key === 'Escape'/); + assert.match(source, /returnFocus\.focus\(\)/); + assert.match(source, /'aria-modal': 'true'/); + }); + + it('the tour card shares the same trap', () => { + const source = readFileSync(new URL('../src/renderer/tour/tourView.ts', import.meta.url), 'utf8'); + assert.match(source, /trapTab\(event, card, list\)/); + }); +}); From 761b36e3a54f70789c28c4e92f31ee96c53d4327 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:35:28 +0000 Subject: [PATCH 23/74] perf(ide): find instruction files by name, share repeated start-up reads, keep Monaco's TypeScript worker idle under a language server (#519) --- apps/ide/src/bridge/codexrApi.ts | 25 ++- apps/ide/src/bridge/sharedReads.ts | 88 ++++++++++ .../renderer/agentFirst/instructionsModel.ts | 41 +++++ .../renderer/agentFirst/instructionsView.ts | 7 +- .../src/renderer/editor/outlineController.ts | 12 +- apps/ide/src/renderer/lsp/languageClient.ts | 26 ++- apps/ide/src/renderer/main.ts | 2 +- apps/ide/test/startupWork.test.ts | 156 ++++++++++++++++++ 8 files changed, 338 insertions(+), 19 deletions(-) create mode 100644 apps/ide/src/bridge/sharedReads.ts create mode 100644 apps/ide/test/startupWork.test.ts diff --git a/apps/ide/src/bridge/codexrApi.ts b/apps/ide/src/bridge/codexrApi.ts index 9022d453..cb5336fe 100644 --- a/apps/ide/src/bridge/codexrApi.ts +++ b/apps/ide/src/bridge/codexrApi.ts @@ -16,6 +16,7 @@ import { DEBUG_IPC_CHANNELS, DEBUG_IPC_EVENTS, type DebugEvent, type DebugStepKi import { CODEXR_IPC_CHANNELS, CODEXR_IPC_EVENTS, type AnalysisAction, type AnalysisInfo, type CodeXrSettings, type CodeXrSettingsPatch, type SceneClosedEvent, type SceneModeEvent, type ServerAction, type ServersSnapshot } from '../shared/codexr.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspDiagnosticsEvent, type LspLanguage, type LspRequestMethod } from '../shared/lsp.ts'; import { orderedInput } from './orderedInput.ts'; +import { shareInFlightReads, type SharedReadRules } from './sharedReads.ts'; const KNOWN_COMMANDS: ReadonlySet = new Set(IDE_COMMANDS); @@ -34,6 +35,26 @@ export interface IpcAdapter { on(channel: string, listener: (payload: T) => void): Unsubscribe; } +/** Calls that open or close a folder: every shared read depends on it. */ +const FOLDER_CALLS: readonly string[] = [IPC_CHANNELS.workspaceOpenFolder, IPC_CHANNELS.workspaceOpenRecent, IPC_CHANNELS.workspaceCloseFolder, IPC_CHANNELS.workspaceSetTrust]; +/** Calls that write the folder's files (`.vscode/settings.json`, `.vscode/launch.json`). */ +const FILE_WRITES: readonly string[] = [ + IPC_CHANNELS.workspaceWriteFile, IPC_CHANNELS.workspaceSaveAs, IPC_CHANNELS.workspaceCreateEntry, IPC_CHANNELS.workspaceRename, + IPC_CHANNELS.workspaceTrash, IPC_CHANNELS.workspaceMoveEntry, IPC_CHANNELS.workspaceCopyEntry, IPC_CHANNELS.workspaceReplaceInFiles, +]; + +/** #519: the reads the page repeats while it starts, and what makes a pending one stale. */ +export const SHARED_READS: SharedReadRules = { + reads: { + [IPC_CHANNELS.settingsGet]: { calls: [...FOLDER_CALLS, ...FILE_WRITES], events: [IPC_EVENTS.settingsChanged] }, + [AGENT_SESSION_CHANNELS.listProjects]: { calls: FOLDER_CALLS, events: [AGENT_SESSION_EVENTS.message] }, + [EXTENSION_IPC_CHANNELS.extensionsList]: { calls: FOLDER_CALLS, events: [EXTENSION_IPC_EVENTS.extensionsChanged] }, + [AGENT_IPC_CHANNELS.agentsListProviders]: { calls: FOLDER_CALLS }, + [DEBUG_IPC_CHANNELS.debugConfigurations]: { calls: [...FOLDER_CALLS, ...FILE_WRITES], events: [IPC_EVENTS.workspaceFilesChanged] }, + }, + dropAllOn: [IPC_EVENTS.workspaceChanged, IPC_EVENTS.workspaceTrustChanged], +}; + /** * The only bridge between the sandboxed renderer and the rest of the IDE. * @@ -46,7 +67,9 @@ export interface IpcAdapter { * It may import src/shared only: everything it imports is bundled into the * bridge script. */ -export function createCodexrApi(ipc: IpcAdapter): CodeXRApi { +export function createCodexrApi(shell: IpcAdapter): CodeXRApi { + // #519: the start-up's repeated reads share one call while it is in flight (sharedReads.ts). + const ipc = shareInFlightReads(shell, SHARED_READS); // #489: one call at a time per terminal, so keystrokes cannot overtake each other on the way to the pty. const terminalInput = orderedInput((id, data) => ipc.invoke(IPC_CHANNELS.terminalInput, id, data)); return Object.freeze({ diff --git a/apps/ide/src/bridge/sharedReads.ts b/apps/ide/src/bridge/sharedReads.ts new file mode 100644 index 00000000..3636c835 --- /dev/null +++ b/apps/ide/src/bridge/sharedReads.ts @@ -0,0 +1,88 @@ +/** + * #519: reads the page makes several times while it starts, shared while one + * is in flight. At start-up several views ask for the same thing in the same + * moments (settings:get three times, agent-sessions:list-projects four times, + * extensions:list, agents:list-providers and debug:configurations twice): each + * is a sidecar round trip and the same work there. A call to one of these + * channels, with no arguments, made while an identical one is still pending + * gets that call's answer instead of a call of its own; once it settles, the + * next call asks again. Nothing is cached beyond the round trip. + * + * A shared answer is never older than the caller could expect, because a + * pending read is dropped (the next caller makes a call of its own) on: + * - a call of its own family (`codexr:settings:update` drops + * `codexr:settings:get`: same prefix up to the last `:`), or one of the + * other calls its rule names (a file written, for the debug configurations); + * - an event saying its data changed, or one that changes everything (the + * folder). The core hands calls on in the order they were made (#497), so a + * read made after a write is answered after it. + * The callers after the first get a structured clone, so one that changes + * its answer in place cannot change another's. + */ +export interface SharedReadsAdapter { + invoke(channel: string, ...args: unknown[]): Promise; + on(channel: string, listener: (payload: T) => void): () => void; +} + +export interface SharedRead { + /** Calls outside the read's family that change its answer. */ + readonly calls?: readonly string[]; + /** Events that say its answer changed. */ + readonly events?: readonly string[]; +} + +export interface SharedReadRules { + readonly reads: Readonly>; + /** Events that make every pending answer stale (the folder changed). */ + readonly dropAllOn: readonly string[]; +} + +/** `codexr:settings:get` → `codexr:settings:`. */ +export function channelFamily(channel: string): string { + return channel.slice(0, channel.lastIndexOf(':') + 1); +} + +export function shareInFlightReads(ipc: T, rules: SharedReadRules, clone: (value: V) => V = structuredClone): T { + const pending = new Map>(); + const reads = Object.entries(rules.reads); + const dropAll = new Set(rules.dropAllOn); + const drop = (stale: (read: string, rule: SharedRead) => boolean): void => { + for (const [read, rule] of reads) { + if (stale(read, rule)) { + pending.delete(read); + } + } + }; + const shared: SharedReadsAdapter = { + invoke(channel: string, ...args: unknown[]): Promise { + if (!Object.hasOwn(rules.reads, channel) || args.length > 0) { + drop((read, rule) => (read !== channel && channelFamily(read) === channelFamily(channel)) || rule.calls?.includes(channel) === true); + return ipc.invoke(channel, ...args); + } + const inFlight = pending.get(channel); + if (inFlight) { + return inFlight.then((value) => clone(value)); + } + const call = ipc.invoke(channel); + pending.set(channel, call); + const settle = (): void => { + if (pending.get(channel) === call) { + pending.delete(channel); + } + }; + call.then(settle, settle); + return call; + }, + on(event: string, listener: (payload: V) => void): () => void { + return ipc.on(event, (payload) => { + if (dropAll.has(event)) { + pending.clear(); + } else { + drop((_read, rule) => rule.events?.includes(event) === true); + } + listener(payload); + }); + }, + }; + return { ...ipc, invoke: shared.invoke, on: shared.on }; +} diff --git a/apps/ide/src/renderer/agentFirst/instructionsModel.ts b/apps/ide/src/renderer/agentFirst/instructionsModel.ts index 70d4fc0e..8600a6f0 100644 --- a/apps/ide/src/renderer/agentFirst/instructionsModel.ts +++ b/apps/ide/src/renderer/agentFirst/instructionsModel.ts @@ -68,6 +68,47 @@ export function otherRuleFiles(files: readonly string[], limit = 20): string[] { .slice(0, limit); } +/** A folder entry, as `workspace.listDirectory` gives it. */ +export interface InstructionDirEntry { + readonly name: string; + readonly kind: 'file' | 'directory'; +} + +/** The folders where rule files live besides the root, each read only when its parent lists it. */ +const RULE_FOLDERS: readonly string[] = ['.github', '.github/instructions', '.cursor', '.cursor/rules']; + +/** + * #519: the instruction and rule files of the project, found by reading the + * few folders they live in (the root, `.github`, `.github/instructions`, + * `.cursor/rules`) rather than walking the whole folder (`listFiles`, up to + * 50,000 files) to look for a handful of names at every folder change. A + * folder its parent does not list is never read, so a project with none of + * them costs one listing, of the root. Nested AGENTS.md files below other + * folders are no longer listed (the agents find those themselves). The paths + * feed `instructionEntries` and `otherRuleFiles` unchanged. + */ +export async function findInstructionFiles(listDirectory: (path: string) => Promise): Promise { + const read = (path: string): Promise => listDirectory(path).catch(() => []); + const found: string[] = []; + const folders = new Map([['', await read('')]]); + for (const folder of RULE_FOLDERS) { + const slash = folder.lastIndexOf('/'); + const parent = slash < 0 ? '' : folder.slice(0, slash); + const name = folder.slice(slash + 1); + if (folders.get(parent)?.some((entry) => entry.kind === 'directory' && entry.name === name)) { + folders.set(folder, await read(folder)); + } + } + for (const [folder, entries] of folders) { + for (const entry of entries) { + if (entry.kind === 'file') { + found.push(folder ? `${folder}/${entry.name}` : entry.name); + } + } + } + return found; +} + /** The parent folder and name of a workspace path, for `createEntry`. */ export function splitWorkspacePath(path: string): { readonly parent: string; readonly name: string } { const index = path.lastIndexOf('/'); diff --git a/apps/ide/src/renderer/agentFirst/instructionsView.ts b/apps/ide/src/renderer/agentFirst/instructionsView.ts index 3001bec3..18f18386 100644 --- a/apps/ide/src/renderer/agentFirst/instructionsView.ts +++ b/apps/ide/src/renderer/agentFirst/instructionsView.ts @@ -1,6 +1,6 @@ import { t } from '../../shared/i18n/i18n.ts'; import { el } from '../dom.ts'; -import { instructionEntries, otherRuleFiles, splitWorkspacePath, type InstructionEntry } from './instructionsModel.ts'; +import { findInstructionFiles, instructionEntries, otherRuleFiles, splitWorkspacePath, type InstructionDirEntry, type InstructionEntry } from './instructionsModel.ts'; /** * The "Project instructions" section of the Chats view (AF11, #276): which @@ -10,7 +10,8 @@ import { instructionEntries, otherRuleFiles, splitWorkspacePath, type Instructio */ export interface InstructionsViewDeps { - listFiles(): Promise; + /** #519: one folder of the project (`workspace.listDirectory`): the files are found by name (findInstructionFiles). */ + listDirectory(path: string): Promise; createEntry(parent: string, name: string, kind: 'file' | 'directory'): Promise; writeFile(path: string, text: string): Promise; openFile(path: string): void; @@ -56,7 +57,7 @@ export function createInstructionsView(deps: InstructionsViewDeps): Instructions } let files: readonly string[] = []; try { - files = await deps.listFiles(); + files = await findInstructionFiles((path) => deps.listDirectory(path)); } catch { files = []; } diff --git a/apps/ide/src/renderer/editor/outlineController.ts b/apps/ide/src/renderer/editor/outlineController.ts index 7e6c8155..e514772a 100644 --- a/apps/ide/src/renderer/editor/outlineController.ts +++ b/apps/ide/src/renderer/editor/outlineController.ts @@ -82,13 +82,13 @@ function fromDocumentSymbols(symbols: readonly monaco.languages.DocumentSymbol[] })); } -/** The language server's symbols, or null when none runs for the file (or it found none). */ +/** The language server's symbols (empty when it found none), or null when no server answered for the file. */ async function serverSymbols(model: monaco.editor.ITextModel): Promise { if (!SERVER_LANGUAGES.has(model.getLanguageId())) { return null; } - const symbols = await languageServerSymbols(model).catch(() => []); - return symbols.length > 0 ? sortOutline(fromDocumentSymbols(symbols), 'position') : null; + const symbols = await languageServerSymbols(model).catch(() => null); + return symbols === null ? null : sortOutline(fromDocumentSymbols(symbols), 'position'); } async function typeScriptSymbols(model: monaco.editor.ITextModel): Promise { @@ -160,7 +160,8 @@ export function createOutlineController(options: { } const { path, model } = target; const languageId = model.getLanguageId(); - const fromServer = await serverSymbols(model); + const answer = await serverSymbols(model); + const fromServer = answer !== null && answer.length > 0 ? answer : null; if (run !== generation) { return; } @@ -170,7 +171,8 @@ export function createOutlineController(options: { return; } if (TYPESCRIPT_LANGUAGES.has(languageId)) { - const symbols = await typeScriptSymbols(model).catch(() => null); + // #519: Monaco's TypeScript worker (6.9 MB to parse) only when no language server answered. + const symbols = answer ?? await typeScriptSymbols(model).catch(() => null); if (run === generation) { publish(symbols && symbols.length > 0 ? { kind: 'symbols', path, symbols, source: 'language' } : { kind: 'empty', path, reason: 'No symbols found in this file.' }); } diff --git a/apps/ide/src/renderer/lsp/languageClient.ts b/apps/ide/src/renderer/lsp/languageClient.ts index fc5cc6f6..7501d2c7 100644 --- a/apps/ide/src/renderer/lsp/languageClient.ts +++ b/apps/ide/src/renderer/lsp/languageClient.ts @@ -56,15 +56,16 @@ interface TrackedModel { let installed = false; /** #172: the server's document symbols of a model, for the Outline view; set once the client is installed. */ -let symbolsOf: ((model: monaco.editor.ITextModel) => Promise) | null = null; +let symbolsOf: ((model: monaco.editor.ITextModel) => Promise) | null = null; /** * #172: what the language server says the model's symbols are, for the - * Outline view and the breadcrumbs: empty when the model's language has no - * server running (none installed for Python) or the server found none. + * Outline view and the breadcrumbs: empty when the server found none, null + * when no server answered (the model's language has none running: none + * installed for Python), so the outline falls back to Monaco's worker only then (#519). */ -export function languageServerSymbols(model: monaco.editor.ITextModel): Promise { - return symbolsOf ? symbolsOf(model) : Promise.resolve([]); +export function languageServerSymbols(model: monaco.editor.ITextModel): Promise { + return symbolsOf ? symbolsOf(model) : Promise.resolve(null); } let reopenAll: (() => void) | null = null; @@ -89,6 +90,12 @@ export function installLanguageClient(api: LspApi, host: LanguageClientHost): vo completionItems: false, hovers: false, definitions: false, documentSymbols: false, diagnostics: false, // #287: the server's answers cover the files that are not open. references: false, rename: false, signatureHelp: false, documentHighlights: false, codeActions: false, + // #519: Monaco asks its worker for inlay hints as soon as a TypeScript or JavaScript file is + // shown, which loads ts.worker (6.9 MB to parse) for hints that are all off by default + // (`inlayHintsOptions` is never set): the language server serves the file instead. + // Formatting stays, as the fallback formatter: the server's client has none, and the + // worker starts only when a file is formatted. + inlayHints: false, }); } @@ -255,18 +262,19 @@ export function installLanguageClient(api: LspApi, host: LanguageClientHost): vo }, }); - async function documentSymbols(model: monaco.editor.ITextModel): Promise { + /** Null when no server answered (none runs for the file, or it failed). */ + async function documentSymbols(model: monaco.editor.ITextModel): Promise { const uri = synced(model); if (!uri) { - return []; + return null; } const result = await request<(Lsp.DocumentSymbol | Lsp.SymbolInformation)[]>('textDocument/documentSymbol', { textDocument: { uri } }); - return toSymbols(result, uri) as monaco.languages.DocumentSymbol[]; + return Array.isArray(result) ? toSymbols(result, uri) as monaco.languages.DocumentSymbol[] : null; } symbolsOf = documentSymbols; monaco.languages.registerDocumentSymbolProvider(all, { displayName: 'Language server', - provideDocumentSymbols: (model) => documentSymbols(model), + provideDocumentSymbols: async (model) => (await documentSymbols(model)) ?? [], }); // #287: references, highlights and signature help. diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 5d099f11..ae3338f0 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -1354,7 +1354,7 @@ const agentWorkbench = installAgentWorkbench({ onStatus: (message) => workbench.setStatus(message), }, instructions: { - listFiles: async () => (await api.workspace.listFiles()).files, + listDirectory: (path) => api.workspace.listDirectory(path), createEntry: (parent, name, kind) => api.workspace.createEntry(parent, name, kind), writeFile: (path, text) => api.workspace.writeFile(path, text), }, diff --git a/apps/ide/test/startupWork.test.ts b/apps/ide/test/startupWork.test.ts new file mode 100644 index 00000000..73e14577 --- /dev/null +++ b/apps/ide/test/startupWork.test.ts @@ -0,0 +1,156 @@ +// #519: less work while the IDE starts: instruction files found by name, the +// start-up's repeated reads shared while in flight, and Monaco's TypeScript +// worker left alone when a language server serves the file. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { findInstructionFiles, instructionEntries, otherRuleFiles, type InstructionDirEntry } from '../src/renderer/agentFirst/instructionsModel.ts'; +import { channelFamily, shareInFlightReads, type SharedReadRules } from '../src/bridge/sharedReads.ts'; +import { SHARED_READS } from '../src/bridge/codexrApi.ts'; +import { IPC_CHANNELS, IPC_EVENTS } from '../src/shared/api.ts'; + +const IDE_ROOT = path.resolve(import.meta.dirname, '..'); +const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); + +function folders(tree: Record): { list: (path: string) => Promise; asked: string[] } { + const asked: string[] = []; + return { + asked, + list: async (dir) => { + asked.push(dir); + const entries = tree[dir]; + if (!entries) { + throw new Error(`ENOENT ${dir}`); + } + return entries; + }, + }; +} +const file = (name: string): InstructionDirEntry => ({ name, kind: 'file' }); +const dir = (name: string): InstructionDirEntry => ({ name, kind: 'directory' }); + +describe('Instruction files found by name (#519)', () => { + it('reads the root only when the project has none of the rule folders', async () => { + const fake = folders({ '': [file('package.json'), dir('src'), file('AGENTS.md')] }); + const files = await findInstructionFiles(fake.list); + assert.deepEqual(fake.asked, ['']); + assert.deepEqual(instructionEntries(files).filter((entry) => entry.exists).map((entry) => entry.path), ['AGENTS.md']); + }); + + it('finds Copilot, Cursor and other rule files in their own folders', async () => { + const fake = folders({ + '': [file('CLAUDE.md'), file('.cursorrules'), dir('.github'), dir('.cursor'), dir('node_modules')], + '.github': [file('copilot-instructions.md'), dir('instructions'), dir('workflows')], + '.github/instructions': [file('tests.md')], + '.cursor': [dir('rules')], + '.cursor/rules': [file('style.mdc')], + }); + const files = await findInstructionFiles(fake.list); + assert.deepEqual(fake.asked, ['', '.github', '.github/instructions', '.cursor', '.cursor/rules']); + assert.deepEqual(instructionEntries(files).filter((entry) => entry.exists).map((entry) => entry.path), ['CLAUDE.md', '.github/copilot-instructions.md']); + assert.deepEqual(otherRuleFiles(files), ['.cursor/rules/style.mdc', '.cursorrules', '.github/instructions/tests.md']); + }); + + it('treats a folder it cannot read as empty, and never walks the folder', async () => { + const fake = folders({ '': [dir('.github')] }); + assert.deepEqual(await findInstructionFiles(fake.list), []); + assert.doesNotMatch(read('src/renderer/agentFirst/instructionsView.ts'), /listFiles/); + assert.match(read('src/renderer/main.ts'), /instructions: \{\n\s*listDirectory: \(path\) => api\.workspace\.listDirectory\(path\),/); + }); +}); + +function fakeIpc(): { invoke(channel: string, ...args: unknown[]): Promise; on(channel: string, listener: (payload: T) => void): () => void; calls: string[]; answer(channel: string, value: unknown): void; emit(event: string): void } { + const waiting = new Map void>>(); + const listeners = new Map void>>(); + const calls: string[] = []; + return { + calls, + invoke(channel: string) { + calls.push(channel); + return new Promise((resolve) => waiting.set(channel, [...(waiting.get(channel) ?? []), resolve])); + }, + on(channel: string, listener: (payload: T) => void) { + listeners.set(channel, [...(listeners.get(channel) ?? []), listener as (payload: unknown) => void]); + return () => undefined; + }, + answer(channel: string, value: unknown) { + for (const resolve of waiting.get(channel) ?? []) { + resolve(value); + } + waiting.delete(channel); + }, + emit(event: string) { + for (const listener of listeners.get(event) ?? []) { + listener(null); + } + }, + }; +} + +const RULES: SharedReadRules = { + reads: { 'x:settings:get': { calls: ['x:workspace:write-file'], events: ['x:settings:changed'] }, 'x:ext:list': {} }, + dropAllOn: ['x:workspace:changed'], +}; + +describe('Start-up reads shared while in flight (#519)', () => { + it('makes one call for reads made while one is pending, and a new one once it settled', async () => { + const ipc = fakeIpc(); + const shared = shareInFlightReads(ipc, RULES); + const first = shared.invoke('x:settings:get'); + const second = shared.invoke('x:settings:get'); + assert.deepEqual(ipc.calls, ['x:settings:get']); + const answer = { values: [1] }; + ipc.answer('x:settings:get', answer); + assert.equal(await first, answer); + const copy = await second; + assert.deepEqual(copy, answer); + assert.notEqual(copy, answer, 'a clone: changing one answer changes no other'); + }); + + it('asks again after a write of the family, a named call or an event', async () => { + for (const stale of [ + (shared: ReturnType) => void shared.invoke('x:settings:update', 'user', 'a', 1), + (shared: ReturnType) => void shared.invoke('x:workspace:write-file', 'a', 'b'), + (_shared: unknown, ipc: ReturnType) => ipc.emit('x:settings:changed'), + (_shared: unknown, ipc: ReturnType) => ipc.emit('x:workspace:changed'), + ]) { + const ipc = fakeIpc(); + const shared = shareInFlightReads(ipc, RULES); + shared.on('x:settings:changed', () => undefined); + shared.on('x:workspace:changed', () => undefined); + void shared.invoke('x:settings:get'); + stale(shared, ipc); + void shared.invoke('x:settings:get'); + assert.equal(ipc.calls.filter((channel) => channel === 'x:settings:get').length, 2, String(stale)); + } + }); + + it('leaves unrelated calls and other reads alone, and never shares a read with arguments', () => { + const ipc = fakeIpc(); + const shared = shareInFlightReads(ipc, RULES); + void shared.invoke('x:settings:get'); + void shared.invoke('x:git:status'); + void shared.invoke('x:ext:list'); + void shared.invoke('x:settings:get'); + void shared.invoke('x:ext:list', 'filter'); + assert.deepEqual(ipc.calls, ['x:settings:get', 'x:git:status', 'x:ext:list', 'x:ext:list']); + assert.equal(channelFamily('codexr:agent-sessions:list-projects'), 'codexr:agent-sessions:'); + }); + + it('shares the start-up duplicates through window.codexr', () => { + assert.deepEqual(Object.keys(SHARED_READS.reads).sort(), ['codexr:agent-sessions:list-projects', 'codexr:agents:list-providers', 'codexr:debug:configurations', 'codexr:extensions:list', 'codexr:settings:get']); + assert.ok(SHARED_READS.reads[IPC_CHANNELS.settingsGet]?.events?.includes(IPC_EVENTS.settingsChanged)); + assert.ok(SHARED_READS.dropAllOn.includes(IPC_EVENTS.workspaceChanged)); + assert.match(read('src/bridge/codexrApi.ts'), /const ipc = shareInFlightReads\(shell, SHARED_READS\);/); + }); +}); + +describe('Monaco\'s TypeScript worker (#519)', () => { + it('is not started by inlay hints, nor by the outline when a language server answered', () => { + const client = read('src/renderer/lsp/languageClient.ts'); + assert.match(client, /setModeConfiguration\(\{[^}]*inlayHints: false,/s); + assert.match(client, /return Array\.isArray\(result\) \? toSymbols\(result, uri\) as monaco\.languages\.DocumentSymbol\[\] : null;/); + assert.match(read('src/renderer/editor/outlineController.ts'), /const symbols = answer \?\? await typeScriptSymbols\(model\)/); + }); +}); From a52d3df24c03d12bb25f076bb71c4ae876a2d475 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:35:32 +0000 Subject: [PATCH 24/74] feat(ide): keep-hunks and undo-hunks for a chat's changes, through checkpoints and IPC (#521) --- apps/ide/src/bridge/codexrApi.ts | 2 + .../main/agentSessions/agentSessionService.ts | 36 ++++++++++++ .../main/agentSessions/agentSessionsIpc.ts | 2 + .../src/main/checkpoints/checkpointStore.ts | 57 ++++++++++++++++++- .../src/main/checkpoints/sessionChanges.ts | 44 +++++++++++++- apps/ide/src/shared/agentSession.ts | 6 ++ apps/ide/test/agentSessions.test.ts | 20 +++++++ apps/ide/test/ipcCalls.test.ts | 15 +++++ apps/ide/test/sessionChanges.test.ts | 48 ++++++++++++++++ 9 files changed, 228 insertions(+), 2 deletions(-) diff --git a/apps/ide/src/bridge/codexrApi.ts b/apps/ide/src/bridge/codexrApi.ts index 4c89b417..52a32204 100644 --- a/apps/ide/src/bridge/codexrApi.ts +++ b/apps/ide/src/bridge/codexrApi.ts @@ -111,6 +111,8 @@ export function createCodexrApi(ipc: IpcAdapter): CodeXRApi { changeDiff: (sessionId: string, path: string) => ipc.invoke(AGENT_SESSION_CHANNELS.changeDiff, sessionId, path), keepChanges: (sessionId: string, paths: readonly string[] | 'all') => ipc.invoke(AGENT_SESSION_CHANNELS.keepChanges, sessionId, paths), undoChanges: (sessionId: string, paths: readonly string[] | 'all') => ipc.invoke(AGENT_SESSION_CHANNELS.undoChanges, sessionId, paths), + keepHunks: (sessionId: string, path: string, hunkIds: readonly string[]) => ipc.invoke(AGENT_SESSION_CHANNELS.keepHunks, sessionId, path, hunkIds), + undoHunks: (sessionId: string, path: string, hunkIds: readonly string[]) => ipc.invoke(AGENT_SESSION_CHANNELS.undoHunks, sessionId, path, hunkIds), previewRestore: (sessionId: string, checkpointId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.previewRestore, sessionId, checkpointId), restoreCheckpoint: (sessionId: string, checkpointId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.restoreCheckpoint, sessionId, checkpointId), // AF12: a chat's worktree is named by the chat id only; main looks up its path. diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 4c2c923c..18fb43e0 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -197,12 +197,24 @@ export interface ChangeReview { diff(sessionId: string, root: string, path: string): Promise<{ readonly oldText: string | null; readonly newText: string | null }>; keep(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise; undo(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise; + /** #521: per-hunk Keep/Undo of one file (absent: the review offers per-file decisions only). */ + keepHunks?(sessionId: string, root: string, path: string, hunkIds: readonly string[]): Promise; + undoHunks?(sessionId: string, root: string, path: string, hunkIds: readonly string[]): Promise; previewRestore(root: string, checkpointId: string): Promise; restoreCheckpoint(root: string, checkpointId: string): Promise; forget?(sessionId: string): Promise; } const MAX_REVIEW_PATHS = 5000; +const MAX_HUNK_IDS = 5000; + +/** #521: hunk ids from the renderer (core/agent-review `hunkId`): a non-empty list of short strings. */ +function hunkIds(value: unknown): readonly string[] { + if (!Array.isArray(value) || value.length === 0 || value.length > MAX_HUNK_IDS) { + throw new Error('Invalid list of changes.'); + } + return [...new Set(value.map((entry) => requireString(entry, 'change id', 64)))]; +} /** Paths from the renderer: an array of project-relative paths (normalised), or 'all'. */ function reviewPaths(value: unknown): readonly string[] | 'all' { @@ -1264,6 +1276,30 @@ export class AgentSessionService { return this.refreshChanges(live, review); } + /** #521: keeps some hunks of one file (its base takes them). */ + async keepHunks(window: WindowPort, sessionId: unknown, filePath: unknown, ids: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, true); + const relative = normalizeProjectPath(requireString(filePath, 'file path')); + const chosen = hunkIds(ids); + if (!review.keepHunks) { + throw new Error('Keeping part of a file is not available here.'); + } + await review.keepHunks(live.state.id, this.workRoot(live), relative, chosen); + return this.refreshChanges(live, review); + } + + /** #521: undoes some hunks of one file (written to disk). */ + async undoHunks(window: WindowPort, sessionId: unknown, filePath: unknown, ids: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, true); + const relative = normalizeProjectPath(requireString(filePath, 'file path')); + const chosen = hunkIds(ids); + if (!review.undoHunks) { + throw new Error('Undoing part of a file is not available here.'); + } + await review.undoHunks(live.state.id, this.workRoot(live), relative, chosen); + return this.refreshChanges(live, review); + } + async previewRestore(window: WindowPort, sessionId: unknown, checkpointId: unknown): Promise { const { live, review } = await this.reviewOf(window, sessionId, false); return review.previewRestore(this.workRoot(live), this.checkpointOf(live, checkpointId)); diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts index f4207c9e..68f54b3f 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -42,6 +42,8 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi handle(C.changeDiff, (event, id, filePath) => service.changeDiff(portOf(event.sender), id, filePath)); handle(C.keepChanges, (event, id, paths) => service.keepChanges(portOf(event.sender), id, paths)); handle(C.undoChanges, (event, id, paths) => service.undoChanges(portOf(event.sender), id, paths)); + handle(C.keepHunks, (event, id, filePath, hunkIds) => service.keepHunks(portOf(event.sender), id, filePath, hunkIds)); + handle(C.undoHunks, (event, id, filePath, hunkIds) => service.undoHunks(portOf(event.sender), id, filePath, hunkIds)); handle(C.previewRestore, (event, id, checkpointId) => service.previewRestore(portOf(event.sender), id, checkpointId)); handle(C.restoreCheckpoint, (event, id, checkpointId) => service.restoreCheckpoint(portOf(event.sender), id, checkpointId)); // AF12: the worktree is looked up from the chat id in main; no path from the page is used. diff --git a/apps/ide/src/main/checkpoints/checkpointStore.ts b/apps/ide/src/main/checkpoints/checkpointStore.ts index f99633b1..afe97f2c 100644 --- a/apps/ide/src/main/checkpoints/checkpointStore.ts +++ b/apps/ide/src/main/checkpoints/checkpointStore.ts @@ -127,6 +127,8 @@ interface RunOptions { readonly okExitCodes?: readonly number[] | undefined; /** Without a work tree and an index: for `init` and object reads. */ readonly bare?: boolean | undefined; + /** #521: another index than the snapshot one (a per-hunk keep builds its tree there). */ + readonly indexFile?: string | undefined; } interface RunResult { @@ -361,6 +363,59 @@ export class CheckpointStore { }); } + /** + * #521: a checkpoint that is `commitId` with one file's content replaced + * (or removed, for null), for a per-hunk "Keep": it becomes that file's + * review base. Built on a private index of its own, so the snapshot index + * is untouched, and chained on the checkpoint ref so it stays reachable. + */ + commitWithFile(commitId: string, filePath: string, content: string | null, label = 'Kept part of a change'): Promise { + return this.locked(async () => { + const commit = await this.resolveCommit(commitId); + const relative = normalizeProjectPath(filePath); + const indexFile = `${this.indexFile}.hunk-${randomBytes(6).toString('hex')}`; + try { + await this.run(['read-tree', commit], { indexFile }); + if (content === null) { + await this.run(['update-index', '--force-remove', '--', relative], { indexFile }); + } else { + const blob = (await this.run(['hash-object', '-w', '--no-filters', '--stdin'], { input: Buffer.from(content, 'utf8') })).stdout.toString('utf8').trim(); + const mode = (await this.treeEntries(commit, [relative])).get(relative)?.mode ?? '100644'; + await this.run(['update-index', '--add', '--cacheinfo', `${mode},${blob},${relative}`], { indexFile }); + } + const tree = (await this.run(['write-tree'], { indexFile })).stdout.toString('utf8').trim(); + const parent = await this.currentHead(); + const id = (await this.run(['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-F', '-'], { input: label })).stdout.toString('utf8').trim(); + await this.run(['update-ref', CHECKPOINT_REF, id]); + return id; + } finally { + await fs.rm(indexFile, { force: true }); + await fs.rm(`${indexFile}.lock`, { force: true }); + } + }); + } + + /** + * #521: writes one text file of the project (a per-hunk "Undo"), keeping + * its executable bit. Refuses a folder or a symbolic link in its place. + */ + writeText(filePath: string, content: string): Promise { + return this.locked(async () => { + const relative = normalizeProjectPath(filePath); + const current = await fs.lstat(this.absolute(relative)).catch((error: unknown) => { + if (isNotFound(error)) { + return null; + } + throw error; + }); + if (current?.isSymbolicLink()) { + throw new Error(`${relative} is a symbolic link now; undo the whole file instead.`); + } + const executable = current?.isFile() === true && (current.mode & 0o111) !== 0; + await this.writeFile(relative, executable ? '100755' : '100644', Buffer.from(content, 'utf8')); + }); + } + /** Restores every snapshotted file that differs from the checkpoint; returns the paths changed. */ restoreAll(commitId: string): Promise { return this.locked(async () => { @@ -422,7 +477,7 @@ export class CheckpointStore { if (!options.bare) { env['GIT_DIR'] = this.gitDir; env['GIT_WORK_TREE'] = this.projectRoot; - env['GIT_INDEX_FILE'] = this.indexFile; + env['GIT_INDEX_FILE'] = options.indexFile ?? this.indexFile; } const fullArgs = [...this.configArgs, ...args]; return new Promise((resolve, reject) => { diff --git a/apps/ide/src/main/checkpoints/sessionChanges.ts b/apps/ide/src/main/checkpoints/sessionChanges.ts index 2f1871ae..21589c69 100644 --- a/apps/ide/src/main/checkpoints/sessionChanges.ts +++ b/apps/ide/src/main/checkpoints/sessionChanges.ts @@ -1,7 +1,8 @@ import path from 'node:path'; +import { keepHunks, revertHunks } from '@codexr/core/agent-review/hunkReview'; import { CheckpointStore, normalizeProjectPath, type ChangedFile, type CheckpointStoreOptions, type DiffText } from './checkpointStore.ts'; import { - baseFor, basesToQuery, createReviewBase, keepAll, keepFiles, mergePendingChanges, parseReviewBase, type ReviewBaseState, + baseFor, basesToQuery, createReviewBase, keepAll, keepFile, keepFiles, mergePendingChanges, parseReviewBase, type ReviewBaseState, } from './reviewBase.ts'; /** @@ -157,6 +158,29 @@ export class SessionChanges { return targets; } + /** + * #521: puts some hunks of one file back as they were at its base and + * writes the result to disk; the other hunks stay. The ids are those of + * `splitHunks(base, disk)` (core/agent-review), so a file that changed + * since the hunks were shown is refused instead of written wrongly. + */ + async undoHunks(sessionId: string, root: string, filePath: string, hunkIds: readonly string[]): Promise { + const { store, relative, oldText, newText } = await this.textSides(sessionId, root, filePath); + await store.writeText(relative, revertHunks(oldText, newText, hunkIds)); + } + + /** + * #521: accepts some hunks of one file: its base becomes the base with + * those hunks applied (a checkpoint of its own), so they stop being + * pending while the others still are. The disk is not touched. + */ + async keepHunks(sessionId: string, root: string, filePath: string, hunkIds: readonly string[]): Promise { + const { state, store, base, relative, oldText, newText } = await this.textSides(sessionId, root, filePath); + const checkpointId = await store.commitWithFile(base, relative, keepHunks(oldText, newText, hunkIds)); + // Re-read: another keep may have moved other files' bases meanwhile. + await this.saveBase(sessionId, keepFile(this.reviewBase(sessionId) ?? state, relative, checkpointId)); + } + /** What `restoreCheckpoint` would write. */ previewRestore(root: string, checkpointId: string): Promise { return this.storeFor(root).previewRestore(checkCheckpointId(checkpointId)); @@ -187,6 +211,24 @@ export class SessionChanges { return state; } + /** Both sides of a file whose change can be reviewed hunk by hunk: it exists on both sides and is UTF-8 text. */ + private async textSides(sessionId: string, root: string, filePath: string): Promise<{ + readonly state: ReviewBaseState; readonly store: CheckpointStore; readonly base: string; readonly relative: string; readonly oldText: string; readonly newText: string; + }> { + const relative = normalizeProjectPath(filePath); + const state = this.requireBase(sessionId); + const store = this.storeFor(root); + const base = baseFor(state, relative); + const { oldText, newText } = await store.diffText(base, relative); + if (oldText === null || newText === null) { + throw new Error(`${relative} was ${oldText === null ? 'added' : 'deleted'}: keep or undo the whole file.`); + } + if (oldText.includes('�') || newText.includes('�')) { + throw new Error(`${relative} is not UTF-8 text: keep or undo the whole file.`); + } + return { state, store, base, relative, oldText, newText }; + } + private saveBase(sessionId: string, state: ReviewBaseState): Promise { return this.options.bases.update(sessionId, { baseId: state.baseId, fileBases: state.fileBases }); } diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index e4eb0709..7738da4c 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -767,6 +767,8 @@ export const AGENT_SESSION_CHANNELS = { changeDiff: 'codexr:agent-sessions:change-diff', keepChanges: 'codexr:agent-sessions:keep-changes', undoChanges: 'codexr:agent-sessions:undo-changes', + keepHunks: 'codexr:agent-sessions:keep-hunks', + undoHunks: 'codexr:agent-sessions:undo-hunks', previewRestore: 'codexr:agent-sessions:preview-restore', restoreCheckpoint: 'codexr:agent-sessions:restore-checkpoint', worktreeAvailability: 'codexr:agent-sessions:worktree-availability', @@ -860,6 +862,10 @@ export interface AgentSessionsApi { keepChanges(sessionId: string, paths: readonly string[] | 'all'): Promise; /** AF5: puts these files (or all) back as they were at their review base. */ undoChanges(sessionId: string, paths: readonly string[] | 'all'): Promise; + /** #521: accepts these hunks of one file (ids of core/agent-review `splitHunks`): its review base takes them, the disk is untouched. */ + keepHunks(sessionId: string, path: string, hunkIds: readonly string[]): Promise; + /** #521: puts these hunks of one file back as they were at its review base, on disk; the other hunks stay. */ + undoHunks(sessionId: string, path: string, hunkIds: readonly string[]): Promise; /** AF6: the files `restoreCheckpoint` would write, without writing anything. */ previewRestore(sessionId: string, checkpointId: string): Promise; /** AF6: puts every file back as it was before the message with this checkpoint; returns the paths written. */ diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index 8d77086f..c0939d17 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -12,6 +12,7 @@ import { AgentCatalog, agentEnvironment, findOnPath, diskProbe } from '../src/ma import { AgentSessionService, type AgentSessionServiceOptions, type WindowPort } from '../src/main/agentSessions/agentSessionService.ts'; import { keepTail, loginCommandLine } from '../src/main/agentSessions/agentTerminals.ts'; import { SessionStore, projectKey } from '../src/main/agentSessions/sessionStore.ts'; +import { splitHunks } from '@codexr/core/agent-review/hunkReview'; import { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-agent-sessions-')); @@ -620,6 +621,25 @@ describe('AgentSessionService with a fake ACP agent', () => { state = await service.get(window, created.id); assert.equal(state.pendingChanges, 1, 'the restore differs from what was kept'); + // #521: per hunk. Undo writes the hunk back; keep moves the base and leaves the disk. + let sides = await service.changeDiff(window, created.id, 'a.txt'); + let hunks = splitHunks(sides.oldText ?? '', sides.newText ?? ''); + listed = await service.undoHunks(window, created.id, 'a.txt', hunks.map((hunk) => hunk.id)); + assert.equal(listed.files.length, 0); + assert.equal(fs.readFileSync(file, 'utf8'), 'written'); + await service.restoreCheckpoint(window, created.id, first.checkpoint); + sides = await service.changeDiff(window, created.id, 'a.txt'); + hunks = splitHunks(sides.oldText ?? '', sides.newText ?? ''); + listed = await service.keepHunks(window, created.id, 'a.txt', [hunks[0]?.id ?? '']); + assert.equal(listed.files.length, 0); + assert.equal(fs.readFileSync(file, 'utf8'), 'one\ntwo\nthree\n'); + assert.equal((await service.get(window, created.id)).pendingChanges, 0); + await assert.rejects(service.undoHunks(window, created.id, 'a.txt', []), /Invalid list of changes/); + await assert.rejects(service.keepHunks(window, created.id, 'a.txt', [7]), /Invalid change id/); + await assert.rejects(service.keepHunks(window, created.id, 'a.txt', ['x'.repeat(65)]), /Invalid change id/); + await assert.rejects(service.undoHunks(window, created.id, '../secret.txt', ['x']), /cannot leave the project/); + await assert.rejects(service.undoHunks(window, created.id, 'a.txt', ['0+1:0+1:zz']), /changed since/); + // The renderer is untrusted: foreign checkpoints, paths that leave the project and bad lists are refused. await assert.rejects(service.restoreCheckpoint(window, created.id, 'a'.repeat(40)), /not part of this chat/); await assert.rejects(service.changeDiff(window, created.id, '../secret.txt'), /cannot leave the project/); diff --git a/apps/ide/test/ipcCalls.test.ts b/apps/ide/test/ipcCalls.test.ts index a399e29a..36c648a5 100644 --- a/apps/ide/test/ipcCalls.test.ts +++ b/apps/ide/test/ipcCalls.test.ts @@ -117,3 +117,18 @@ describe('scene freshness calls and events (O10, #512)', () => { assert.equal(await follow, true); }); }); + +describe('per-hunk review calls (O19, #521)', () => { + it('are declared, allowed, and carry the chat, the path and the hunk ids', async () => { + assert.equal(IPC_CHANNELS.keepHunks, 'codexr:agent-sessions:keep-hunks'); + assert.equal(IPC_CHANNELS.undoHunks, 'codexr:agent-sessions:undo-hunks'); + assert.ok(ALLOWED_IPC_CHANNELS.has(IPC_CHANNELS.keepHunks)); + assert.ok(ALLOWED_IPC_CHANNELS.has(IPC_CHANNELS.undoHunks)); + const tauri = fakeTauri(); + const calls = createIpcCalls(tauri.invoke, 'page'); + const undo = calls.invoke(IPC_CHANNELS.undoHunks, 'chat-1', 'src/a.ts', ['1+1:1+2:abc']); + assert.deepEqual(tauri.sent[0]?.payload.args, ['chat-1', 'src/a.ts', ['1+1:1+2:abc']]); + tauri.sent[0]?.answer({ files: [], disabledReason: null }); + assert.deepEqual(await undo, { files: [], disabledReason: null }); + }); +}); diff --git a/apps/ide/test/sessionChanges.test.ts b/apps/ide/test/sessionChanges.test.ts index 2437a240..fefa145d 100644 --- a/apps/ide/test/sessionChanges.test.ts +++ b/apps/ide/test/sessionChanges.test.ts @@ -4,6 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { JsonKeyValueStore } from '../src/main/core/jsonStore.ts'; +import { splitHunks } from '@codexr/core/agent-review/hunkReview'; import { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-session-changes-'))); @@ -98,6 +99,53 @@ describe('SessionChanges', () => { await changes.dispose(); }); + it('undoes and keeps single hunks of a CRLF file (#521)', async () => { + const original = 'one\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nseven\r\n'; + const { root, changes } = setup({ 'a.txt': original, 'other.txt': 'o\n' }); + await changes.beforePrompt('s1', root); + const edited = 'ONE\r\ntwo\r\nthree\r\nFOUR\r\nfive\r\nsix\r\nSEVEN\r\n'; + write(root, 'a.txt', edited); + write(root, 'other.txt', 'O\n'); + const sides = await changes.diff('s1', root, 'a.txt'); + const hunks = splitHunks(sides.oldText ?? '', sides.newText ?? ''); + assert.equal(hunks.length, 3); + const [first, middle, last] = hunks; + assert.ok(first && middle && last); + + // Undo the middle hunk: written to disk, CRLF intact, the other two still pending. + await changes.undoHunks('s1', root, 'a.txt', [middle.id]); + assert.equal(read(root, 'a.txt'), 'ONE\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nSEVEN\r\n'); + const afterUndo = await changes.diff('s1', root, 'a.txt'); + assert.equal(afterUndo.oldText, original, 'undo does not move the base'); + assert.equal(splitHunks(afterUndo.oldText ?? '', afterUndo.newText ?? '').length, 2); + + // Keep the first hunk: the base takes it, the disk is untouched. + const now = splitHunks(afterUndo.oldText ?? '', afterUndo.newText ?? ''); + await changes.keepHunks('s1', root, 'a.txt', [now[0]?.id ?? '']); + assert.equal(read(root, 'a.txt'), 'ONE\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nSEVEN\r\n'); + const afterKeep = await changes.diff('s1', root, 'a.txt'); + assert.equal(afterKeep.oldText, 'ONE\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nseven\r\n'); + const left = splitHunks(afterKeep.oldText ?? '', afterKeep.newText ?? ''); + assert.deepEqual(left.map((hunk) => hunk.diskLines), [['SEVEN\r']]); + assert.deepEqual((await changes.pending('s1', root)).files.map((file) => [file.path, file.additions, file.deletions]), [['a.txt', 1, 1], ['other.txt', 1, 1]]); + + // Then undo the last one: the file is back at its (moved) base and no longer pending. + await changes.undoHunks('s1', root, 'a.txt', [left[0]?.id ?? '']); + assert.equal(read(root, 'a.txt'), 'ONE\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nseven\r\n'); + assert.deepEqual((await changes.pending('s1', root)).files.map((file) => file.path), ['other.txt']); + // Undoing the whole file goes back to the kept base, not to the chat's first snapshot. + write(root, 'a.txt', 'x\r\n'); + await changes.undo('s1', root, ['a.txt']); + assert.equal(read(root, 'a.txt'), 'ONE\r\ntwo\r\nthree\r\nfour\r\nfive\r\nsix\r\nseven\r\n'); + + // A stale id, an added file and a path outside the project are refused. + await assert.rejects(changes.undoHunks('s1', root, 'other.txt', [middle.id]), /changed since/); + write(root, 'new.txt', 'n\n'); + await assert.rejects(changes.keepHunks('s1', root, 'new.txt', ['x']), /added: keep or undo the whole file/); + await assert.rejects(changes.undoHunks('s1', root, '../outside.txt', ['x']), /cannot leave the project/); + await changes.dispose(); + }); + it('previews and restores the project to a checkpoint', async () => { const { root, changes } = setup({ 'a.txt': 'a\n' }); const first = await changes.beforePrompt('s1', root); From c2d47f2cb4c43418f9ade717f6e0a984baf3dce1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:35:56 +0000 Subject: [PATCH 25/74] style(ide): cargo fmt the Rust core with the new rustfmt.toml (#516) --- apps/ide/src-tauri/build.rs | 10 +++-- apps/ide/src-tauri/src/atomic_file.rs | 10 ++++- apps/ide/src-tauri/src/collation.rs | 9 +++- apps/ide/src-tauri/src/host.rs | 15 +++---- apps/ide/src-tauri/src/install.rs | 6 ++- apps/ide/src-tauri/src/locale.rs | 9 ++-- apps/ide/src-tauri/src/main.rs | 2 +- apps/ide/src-tauri/src/menu.rs | 41 ++++++++++++++++-- apps/ide/src-tauri/src/message_box.rs | 17 ++++++-- apps/ide/src-tauri/src/migration.rs | 7 +++- apps/ide/src-tauri/src/native.rs | 60 +++++++++++++++++++++------ apps/ide/src-tauri/src/parity.rs | 12 ++++-- apps/ide/src-tauri/src/profiles.rs | 45 ++++++++++++++++---- apps/ide/src-tauri/src/recent.rs | 4 +- apps/ide/src-tauri/src/scene.rs | 10 ++--- apps/ide/src-tauri/src/search.rs | 55 +++++++++++++++++++----- apps/ide/src-tauri/src/sidecar.rs | 14 +++++-- apps/ide/src-tauri/src/smoke.rs | 15 ++++--- apps/ide/src-tauri/src/terminal.rs | 16 +++++-- apps/ide/src-tauri/src/webviews.rs | 3 +- apps/ide/src-tauri/src/workspace.rs | 16 +++---- 21 files changed, 277 insertions(+), 99 deletions(-) diff --git a/apps/ide/src-tauri/build.rs b/apps/ide/src-tauri/build.rs index 0162b289..845b7e35 100644 --- a/apps/ide/src-tauri/build.rs +++ b/apps/ide/src-tauri/build.rs @@ -2,9 +2,11 @@ fn main() { // The commands of the IDE are declared, so only a capability can allow them: // capabilities/app.json grants codexr_ipc, codexr_events and codexr_log to the main window's local pages, // capabilities/scene.json the scene bridge's to the scene views' loopback pages. - tauri_build::try_build( - tauri_build::Attributes::new() - .app_manifest(tauri_build::AppManifest::new().commands(&["codexr_ipc", "codexr_events", "codexr_log", "codexr_scene"])), - ) + tauri_build::try_build(tauri_build::Attributes::new().app_manifest(tauri_build::AppManifest::new().commands(&[ + "codexr_ipc", + "codexr_events", + "codexr_log", + "codexr_scene", + ]))) .expect("failed to run tauri-build"); } diff --git a/apps/ide/src-tauri/src/atomic_file.rs b/apps/ide/src-tauri/src/atomic_file.rs index bbaa8c40..ba40fe45 100644 --- a/apps/ide/src-tauri/src/atomic_file.rs +++ b/apps/ide/src-tauri/src/atomic_file.rs @@ -143,7 +143,8 @@ fn link_count(path: &Path) -> Option { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; use windows_sys::Win32::Storage::FileSystem::{ - CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, + CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, + FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, }; let wide: Vec = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect(); // SAFETY: `wide` is NUL-terminated and outlives the call; the handle is closed below. @@ -207,7 +208,12 @@ mod tests { use crate::workspace::tests::Scratch; fn leftovers(dir: &Path) -> Vec { - fs::read_dir(dir).unwrap().filter_map(Result::ok).map(|entry| entry.file_name().to_string_lossy().into_owned()).filter(|name| name.starts_with(".codexr-save-")).collect() + fs::read_dir(dir) + .unwrap() + .filter_map(Result::ok) + .map(|entry| entry.file_name().to_string_lossy().into_owned()) + .filter(|name| name.starts_with(".codexr-save-")) + .collect() } #[test] diff --git a/apps/ide/src-tauri/src/collation.rs b/apps/ide/src-tauri/src/collation.rs index 7999e962..f7bae0b6 100644 --- a/apps/ide/src-tauri/src/collation.rs +++ b/apps/ide/src-tauri/src/collation.rs @@ -32,7 +32,11 @@ pub fn posix_to_bcp47(name: &str) -> String { /// ICU's default locale on Unix: the first set of `LC_ALL`, `LC_MESSAGES`, `LANG`. #[cfg_attr(windows, allow(dead_code))] pub fn posix_default_locale(get: impl Fn(&str) -> Option) -> String { - ["LC_ALL", "LC_MESSAGES", "LANG"].iter().filter_map(|name| get(name)).find(|value| !value.is_empty()).map_or_else(|| "en-US".into(), |value| posix_to_bcp47(&value)) + ["LC_ALL", "LC_MESSAGES", "LANG"] + .iter() + .filter_map(|name| get(name)) + .find(|value| !value.is_empty()) + .map_or_else(|| "en-US".into(), |value| posix_to_bcp47(&value)) } /// The tag `Intl` resolves `undefined` to. @@ -76,7 +80,8 @@ mod tests { #[test] fn reads_the_locale_as_icu_does() { - let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()); + let env = + |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()); assert_eq!(posix_default_locale(env(&[("LANG", "es_ES.UTF-8")])), "es-ES"); assert_eq!(posix_default_locale(env(&[("LANGUAGE", "es"), ("LANG", "en_US.UTF-8")])), "en-US"); assert_eq!(posix_default_locale(env(&[("LC_ALL", "sv_SE.UTF-8"), ("LANG", "en_US.UTF-8")])), "sv-SE"); diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index 49114051..cd3f5f18 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -13,7 +13,7 @@ use base64::Engine; use serde_json::{json, Value}; use tauri::image::Image; use tauri::webview::{NewWindowResponse, PageLoadEvent}; -use tauri::{AppHandle, LogicalSize, Manager, Theme, Url, WebviewUrl, Window, WebviewWindowBuilder}; +use tauri::{AppHandle, LogicalSize, Manager, Theme, Url, WebviewUrl, WebviewWindowBuilder, Window}; use tauri_plugin_clipboard_manager::ClipboardExt; use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; use tauri_plugin_opener::OpenerExt; @@ -127,12 +127,7 @@ fn window_icon(shell: &Shell) -> Option> { } pub fn show_fatal(app: &AppHandle, message: &str) { - app.dialog() - .message(message) - .title("Code-XR") - .kind(MessageDialogKind::Error) - .buttons(MessageDialogButtons::Ok) - .blocking_show(); + app.dialog().message(message).title("Code-XR").kind(MessageDialogKind::Error).buttons(MessageDialogButtons::Ok).blocking_show(); } /// The host requests answered on the reader thread, in the order they came: the @@ -306,7 +301,8 @@ pub fn main_window_url(locale: &str, bench: bool) -> Url { pub fn open_main_window(app: &AppHandle, shell: &Arc, sidecar: &Arc, url: Url) -> Result<(), String> { *shell.main_url.lock().unwrap() = Some(url.to_string()); - let spec = WindowSpec { label: MAIN_WINDOW.into(), url, title: "Code-XR".into(), width: 1280.0, height: 800.0, min_width: 640.0, min_height: 400.0, show: true }; + let spec = + WindowSpec { label: MAIN_WINDOW.into(), url, title: "Code-XR".into(), width: 1280.0, height: 800.0, min_width: 640.0, min_height: 400.0, show: true }; build_window(app, shell, sidecar, spec) } @@ -463,7 +459,8 @@ fn with_filters(mut dialog: tauri_plugin_dialog::FileDialogBuilder, if let Some(filters) = params.get("filters").and_then(Value::as_array) { for filter in filters { let name = filter.get("name").and_then(Value::as_str).unwrap_or(""); - let extensions: Vec<&str> = filter.get("extensions").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let extensions: Vec<&str> = + filter.get("extensions").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); if !extensions.is_empty() && !extensions.contains(&"*") { dialog = dialog.add_filter(name, &extensions); } diff --git a/apps/ide/src-tauri/src/install.rs b/apps/ide/src-tauri/src/install.rs index 060da6f7..f00a92b1 100644 --- a/apps/ide/src-tauri/src/install.rs +++ b/apps/ide/src-tauri/src/install.rs @@ -87,7 +87,11 @@ pub fn resolve(package_info: &tauri::PackageInfo) -> Layout { let layout = layout_from(&source_out, resources.as_deref(), non_empty("CODEXR_IDE_OUT"), non_empty("CODEXR_NODE")); match &layout.packaged { Some(dir) => eprintln!("[codexr-ide] Installed IDE in {}", dir.display()), - None if installed => eprintln!("[codexr-ide] No installed IDE in {}: running from {}", resources.map(|dir| dir.display().to_string()).unwrap_or_default(), layout.out.display()), + None if installed => eprintln!( + "[codexr-ide] No installed IDE in {}: running from {}", + resources.map(|dir| dir.display().to_string()).unwrap_or_default(), + layout.out.display() + ), None => {} } layout diff --git a/apps/ide/src-tauri/src/locale.rs b/apps/ide/src-tauri/src/locale.rs index 7e7bb165..81d72bb3 100644 --- a/apps/ide/src-tauri/src/locale.rs +++ b/apps/ide/src-tauri/src/locale.rs @@ -30,11 +30,7 @@ pub fn environment_language(get: impl Fn(&str) -> Option) -> Option, bench: bool) -> String { let remembered = if bench { None } else { cache_dir.and_then(|dir| std::fs::read_to_string(dir.join(LOCALE_FILE)).ok()) }; - remembered - .as_deref() - .and_then(language_of) - .or_else(|| environment_language(|name| std::env::var(name).ok())) - .unwrap_or_else(|| "en".into()) + remembered.as_deref().and_then(language_of).or_else(|| environment_language(|name| std::env::var(name).ok())).unwrap_or_else(|| "en".into()) } #[cfg(test)] @@ -43,7 +39,8 @@ mod tests { #[test] fn reads_the_environment_like_the_sidecar() { - let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()); + let env = + |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string()); assert_eq!(environment_language(env(&[("LANG", "es_ES.UTF-8")])).as_deref(), Some("es")); assert_eq!(environment_language(env(&[("LANGUAGE", "C:es"), ("LANG", "en_US.UTF-8")])).as_deref(), Some("es")); assert_eq!(environment_language(env(&[("LC_ALL", "C.UTF-8")])), None); diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index 34c9a9e6..c40c272a 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -28,8 +28,8 @@ mod install; mod jsregex; mod locale; mod menu; -mod migration; mod message_box; +mod migration; mod native; #[cfg(test)] mod parity; diff --git a/apps/ide/src-tauri/src/menu.rs b/apps/ide/src-tauri/src/menu.rs index c12e8433..32dd534e 100644 --- a/apps/ide/src-tauri/src/menu.rs +++ b/apps/ide/src-tauri/src/menu.rs @@ -190,7 +190,8 @@ fn role_item(app: &AppHandle, role: &str, label: Option<&str>, accel: Option<&st fn about_metadata(about: &Value) -> AboutMetadata<'static> { let owned = |key: &str| text(about, key).map(str::to_string); - let authors: Vec = about.get("authors").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + let authors: Vec = + about.get("authors").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); AboutMetadata { name: owned("name"), version: owned("version"), @@ -209,10 +210,20 @@ fn build_items(app: &AppHandle, nodes: &[Value], about: &Value) -> Result built.push(Built::Predefined(PredefinedMenuItem::separator(app).map_err(err)?)), - Some("normal") => built.push(plain(app, text(node, "id").ok_or("menu item without id")?, text(node, "label").unwrap_or(""), enabled, text(node, "accelerator"))?), + Some("normal") => { + built.push(plain(app, text(node, "id").ok_or("menu item without id")?, text(node, "label").unwrap_or(""), enabled, text(node, "accelerator"))?) + } Some("checkbox") => { let accel = text(node, "accelerator").and_then(accelerator); - let item = CheckMenuItem::with_id(app, text(node, "id").ok_or("menu item without id")?, text(node, "label").unwrap_or(""), enabled, flag(node, "checked", false), accel.as_deref()).map_err(err)?; + let item = CheckMenuItem::with_id( + app, + text(node, "id").ok_or("menu item without id")?, + text(node, "label").unwrap_or(""), + enabled, + flag(node, "checked", false), + accel.as_deref(), + ) + .map_err(err)?; built.push(Built::Check(item)); } Some("role") => { @@ -420,7 +431,29 @@ mod tests { #[test] fn every_role_of_the_template_has_a_label() { - for role in ["undo", "redo", "cut", "copy", "paste", "pasteAndMatchStyle", "delete", "selectAll", "minimize", "close", "quit", "reload", "toggleDevTools", "resetZoom", "zoomIn", "zoomOut", "togglefullscreen", "startSpeaking", "stopSpeaking", "windowMenu", "help"] { + for role in [ + "undo", + "redo", + "cut", + "copy", + "paste", + "pasteAndMatchStyle", + "delete", + "selectAll", + "minimize", + "close", + "quit", + "reload", + "toggleDevTools", + "resetZoom", + "zoomIn", + "zoomOut", + "togglefullscreen", + "startSpeaking", + "stopSpeaking", + "windowMenu", + "help", + ] { assert!(!role_label(role).is_empty(), "{role}"); } } diff --git a/apps/ide/src-tauri/src/message_box.rs b/apps/ide/src-tauri/src/message_box.rs index fe646df2..cc564b9a 100644 --- a/apps/ide/src-tauri/src/message_box.rs +++ b/apps/ide/src-tauri/src/message_box.rs @@ -72,7 +72,8 @@ impl MessageBox { /// Reads the request; `cancelId` and `defaultId` outside the buttons fall back as messageBox.ts documents. pub fn from_params(params: &Value) -> Result { let message = params.get("message").and_then(Value::as_str).ok_or("missing message")?.to_string(); - let mut buttons: Vec = params.get("buttons").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + let mut buttons: Vec = + params.get("buttons").and_then(Value::as_array).map(|list| list.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); if buttons.is_empty() { buttons.push("OK".into()); } @@ -147,7 +148,13 @@ mod platform { Kind::Question => gtk::MessageType::Question, }; let parent = parent.and_then(|window| window.gtk_window().ok()); - let dialog = gtk::MessageDialog::new(parent.as_ref(), gtk::DialogFlags::MODAL | gtk::DialogFlags::DESTROY_WITH_PARENT, kind, gtk::ButtonsType::None, &spec.message); + let dialog = gtk::MessageDialog::new( + parent.as_ref(), + gtk::DialogFlags::MODAL | gtk::DialogFlags::DESTROY_WITH_PARENT, + kind, + gtk::ButtonsType::None, + &spec.message, + ); dialog.set_title(&spec.title); if let Some(detail) = &spec.detail { dialog.set_secondary_text(Some(detail)); @@ -198,7 +205,8 @@ mod platform { use windows_sys::Win32::Foundation::HWND; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; use windows_sys::Win32::UI::Controls::{ - TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TDF_ALLOW_DIALOG_CANCELLATION, TDF_SIZE_TO_CONTENT, TDF_VERIFICATION_FLAG_CHECKED, TD_ERROR_ICON, TD_INFORMATION_ICON, TD_WARNING_ICON, + TASKDIALOGCONFIG, TASKDIALOG_BUTTON, TDF_ALLOW_DIALOG_CANCELLATION, TDF_SIZE_TO_CONTENT, TDF_VERIFICATION_FLAG_CHECKED, TD_ERROR_ICON, + TD_INFORMATION_ICON, TD_WARNING_ICON, }; use super::{Answer, Kind, MessageBox}; @@ -243,7 +251,8 @@ mod platform { let message = wide(&spec.message); let detail = spec.detail.as_deref().map(wide); let labels: Vec> = spec.buttons.iter().map(|label| wide(label)).collect(); - let buttons: Vec = labels.iter().enumerate().map(|(index, label)| TASKDIALOG_BUTTON { nButtonID: ID_START + index as i32, pszButtonText: label.as_ptr() }).collect(); + let buttons: Vec = + labels.iter().enumerate().map(|(index, label)| TASKDIALOG_BUTTON { nButtonID: ID_START + index as i32, pszButtonText: label.as_ptr() }).collect(); let checkbox = spec.checkbox.as_deref().map(wide); let mut config = TASKDIALOGCONFIG { cbSize: std::mem::size_of::() as u32, hwndParent: owner, ..Default::default() }; // Escape and the close button are allowed whenever there is a cancel button, which there always is here. diff --git a/apps/ide/src-tauri/src/migration.rs b/apps/ide/src-tauri/src/migration.rs index c4d23692..12e4c6b2 100644 --- a/apps/ide/src-tauri/src/migration.rs +++ b/apps/ide/src-tauri/src/migration.rs @@ -285,7 +285,8 @@ fn kwallet_password() -> Result, String> { if handle < 0 { return Err("the wallet did not open".to_string()); } - let password: Result<(String,), _> = proxy.method_call("org.kde.KWallet", "readPassword", (handle, "Chromium Keys", "Chromium Safe Storage", app_id.clone())); + let password: Result<(String,), _> = + proxy.method_call("org.kde.KWallet", "readPassword", (handle, "Chromium Keys", "Chromium Safe Storage", app_id.clone())); let _: Result<(i32,), _> = proxy.method_call("org.kde.KWallet", "close", (handle, false, app_id)); let (password,) = password.map_err(|error| error.to_string())?; if password.is_empty() { @@ -336,7 +337,9 @@ fn dpapi_unprotect(data: &[u8]) -> Result, String> { let mut output = CRYPT_INTEGER_BLOB { cbData: 0, pbData: std::ptr::null_mut() }; // SAFETY: `input` points at `data` for the call; DPAPI only reads it. On success `output` // holds a buffer DPAPI allocated with LocalAlloc, copied out and freed here. - let ok = unsafe { CryptUnprotectData(&input, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut output) }; + let ok = unsafe { + CryptUnprotectData(&input, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null(), CRYPTPROTECT_UI_FORBIDDEN, &mut output) + }; if ok == 0 || output.pbData.is_null() { return Err(format!("DPAPI could not unprotect the key ({})", std::io::Error::last_os_error())); } diff --git a/apps/ide/src-tauri/src/native.rs b/apps/ide/src-tauri/src/native.rs index 88cd9d6a..be11952c 100644 --- a/apps/ide/src-tauri/src/native.rs +++ b/apps/ide/src-tauri/src/native.rs @@ -31,9 +31,9 @@ use tauri::{AppHandle, Manager}; use tauri_plugin_clipboard_manager::ClipboardExt; use tauri_plugin_opener::OpenerExt; +use crate::profiles::{split_args, Profile, ProfileRegistry, SettingsFile}; use crate::recent::RecentFolders; use crate::search::Searches; -use crate::profiles::{split_args, Profile, ProfileRegistry, SettingsFile}; use crate::sidecar::Sidecar; use crate::terminal::{dimension, terminal_environment, Event, Spawn, Terminals}; use crate::watcher::{folders_to_watch, WorkspaceWatcher}; @@ -352,9 +352,22 @@ impl Native { } #[allow(clippy::too_many_arguments)] - fn start(&self, owner: Option<&str>, profile: &Profile, args: Vec, env: Option>, cwd: PathBuf, cols: u16, rows: u16, notify: bool) -> Result { - let env = env.unwrap_or_else(|| terminal_environment(std::env::vars_os().map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())), &self.unset)); - let (id, pid) = self.terminals.start(Spawn { file: profile.path.clone(), args, cwd: cwd.clone(), env, cols, rows, owner: owner.map(str::to_string), notify })?; + fn start( + &self, + owner: Option<&str>, + profile: &Profile, + args: Vec, + env: Option>, + cwd: PathBuf, + cols: u16, + rows: u16, + notify: bool, + ) -> Result { + let env = env.unwrap_or_else(|| { + terminal_environment(std::env::vars_os().map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())), &self.unset) + }); + let (id, pid) = + self.terminals.start(Spawn { file: profile.path.clone(), args, cwd: cwd.clone(), env, cols, rows, owner: owner.map(str::to_string), notify })?; eprintln!("[codexr-ide] Terminal {id}: {} in {}", profile.name, cwd.display()); Ok(json!({ "id": id, "pid": pid, "profile": profile.to_json(), "cwd": cwd.to_string_lossy() })) } @@ -391,21 +404,42 @@ impl Native { "terminal.defaultProfile" => Ok(self.profiles.resolve(&Value::Null)?.to_json()), "terminal.spawn" => { let file = params.get("file").and_then(Value::as_str).ok_or("missing file")?; - let args: Vec = params.get("args").and_then(Value::as_array).map(|list| list.iter().filter_map(|a| a.as_str().map(str::to_string)).collect()).unwrap_or_default(); - let env: Option> = params.get("env").and_then(Value::as_object).map(|env| env.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string()))).collect()); + let args: Vec = params + .get("args") + .and_then(Value::as_array) + .map(|list| list.iter().filter_map(|a| a.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + let env: Option> = params + .get("env") + .and_then(Value::as_object) + .map(|env| env.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string()))).collect()); let cwd = params.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(home_dir); - let (Some(cols), Some(rows)) = (dimension(params.get("cols").unwrap_or(&Value::Null)), dimension(params.get("rows").unwrap_or(&Value::Null))) else { + let (Some(cols), Some(rows)) = (dimension(params.get("cols").unwrap_or(&Value::Null)), dimension(params.get("rows").unwrap_or(&Value::Null))) + else { return Err("Invalid terminal size.".into()); }; - let profile = params - .get("profile") - .and_then(Profile::from_json) - .unwrap_or_else(|| Profile { id: "program".into(), name: file.into(), path: file.into(), args: args.clone(), custom: true }); + let profile = params.get("profile").and_then(Profile::from_json).unwrap_or_else(|| Profile { + id: "program".into(), + name: file.into(), + path: file.into(), + args: args.clone(), + custom: true, + }); let profile = Profile { path: file.to_string(), ..profile }; self.start(window, &profile, args, env, cwd, cols, rows, true) } - "terminal.input" => self.terminals.input(window, params.get("id").unwrap_or(&Value::Null), params.get("data").unwrap_or(&Value::Null)).map(|_| Value::Null), - "terminal.resize" => self.terminals.resize(window, params.get("id").unwrap_or(&Value::Null), params.get("cols").unwrap_or(&Value::Null), params.get("rows").unwrap_or(&Value::Null)).map(|_| Value::Null), + "terminal.input" => { + self.terminals.input(window, params.get("id").unwrap_or(&Value::Null), params.get("data").unwrap_or(&Value::Null)).map(|_| Value::Null) + } + "terminal.resize" => self + .terminals + .resize( + window, + params.get("id").unwrap_or(&Value::Null), + params.get("cols").unwrap_or(&Value::Null), + params.get("rows").unwrap_or(&Value::Null), + ) + .map(|_| Value::Null), "terminal.kill" => { self.terminals.kill(window, params.get("id").unwrap_or(&Value::Null)); Ok(Value::Null) diff --git a/apps/ide/src-tauri/src/parity.rs b/apps/ide/src-tauri/src/parity.rs index 75e5e8d0..3ab4d11c 100644 --- a/apps/ide/src-tauri/src/parity.rs +++ b/apps/ide/src-tauri/src/parity.rs @@ -81,13 +81,15 @@ fn case_canonicalization_matches_v8_for_every_bmp_unit() { #[test] fn gitignore_rules_and_globs_match_typescript() { let data = fixture(include_str!("../../test/fixtures/rust-parity/ignore.json")); - let paths: Vec<(String, bool)> = data["paths"].as_array().unwrap().iter().map(|pair| (pair[0].as_str().unwrap().to_string(), pair[1].as_bool().unwrap())).collect(); + let paths: Vec<(String, bool)> = + data["paths"].as_array().unwrap().iter().map(|pair| (pair[0].as_str().unwrap().to_string(), pair[1].as_bool().unwrap())).collect(); for case in data["gitignore"].as_array().unwrap() { let text = case["text"].as_str().unwrap(); match parse_gitignore(text) { Ok(rules) => { let actual: Vec = paths.iter().map(|(path, is_dir)| is_ignored(path, *is_dir, &rules)).collect(); - let expected: Vec = serde_json::from_value(case["ignored"].clone()).unwrap_or_else(|_| panic!("TypeScript refused {text:?}: {}", case["error"])); + let expected: Vec = + serde_json::from_value(case["ignored"].clone()).unwrap_or_else(|_| panic!("TypeScript refused {text:?}: {}", case["error"])); for (index, (a, e)) in actual.iter().zip(&expected).enumerate() { assert_eq!(a, e, ".gitignore {text:?}, path {:?}", paths[index]); } @@ -105,7 +107,8 @@ fn gitignore_rules_and_globs_match_typescript() { match compile_globs(text) { Ok(globs) => { let actual: Option> = globs.map(|globs| paths.iter().map(|(path, _)| path_matches(path, &globs)).collect()); - let expected: Option> = serde_json::from_value(case["matches"].clone()).unwrap_or_else(|_| panic!("TypeScript refused glob {text:?}: {}", case["error"])); + let expected: Option> = + serde_json::from_value(case["matches"].clone()).unwrap_or_else(|_| panic!("TypeScript refused glob {text:?}: {}", case["error"])); assert_eq!(actual, expected, "glob {text:?}"); } Err(message) => { @@ -166,7 +169,8 @@ fn a_folder_lists_opens_and_renames_like_typescript() { let same_locale = default_locale() == data["locale"][0].as_str().unwrap(); for listing in data["listings"].as_array().unwrap() { let folder = &listing["folder"]; - let actual: Vec = workspace.list_directory(folder).unwrap().as_array().unwrap().iter().map(|entry| json!([entry["name"], entry["kind"], entry["ignored"]])).collect(); + let actual: Vec = + workspace.list_directory(folder).unwrap().as_array().unwrap().iter().map(|entry| json!([entry["name"], entry["kind"], entry["ignored"]])).collect(); let mut expected: Vec = listing["entries"].as_array().unwrap().clone(); if same_locale { assert_eq!(actual, expected, "listing of {folder}"); diff --git a/apps/ide/src-tauri/src/profiles.rs b/apps/ide/src-tauri/src/profiles.rs index 5214b2dc..c5e0d593 100644 --- a/apps/ide/src-tauri/src/profiles.rs +++ b/apps/ide/src-tauri/src/profiles.rs @@ -38,7 +38,8 @@ impl Profile { /// A profile the sidecar describes (a task's or a program's terminal, `TerminalProfile`). pub fn from_json(value: &Value) -> Option { let text = |key: &str| value.get(key).and_then(Value::as_str).map(str::to_string); - let args = value.get("args").and_then(Value::as_array).map(|args| args.iter().filter_map(|a| a.as_str().map(str::to_string)).collect()).unwrap_or_default(); + let args = + value.get("args").and_then(Value::as_array).map(|args| args.iter().filter_map(|a| a.as_str().map(str::to_string)).collect()).unwrap_or_default(); Some(Self { id: text("id")?, name: text("name")?, path: text("path")?, args, custom: value.get("source").and_then(Value::as_str) == Some("custom") }) } } @@ -103,7 +104,12 @@ fn windows_candidates(detection: &Detection) -> Vec { // Git Bash as a login, interactive shell: what its own shortcut starts, so ~/.bash_profile runs. Candidate { id: "git-bash", name: "Git Bash".into(), paths: git_bash, args: vec!["--login".into(), "-i".into()] }, Candidate { id: "pwsh", name: "PowerShell".into(), paths: pwsh, args: Vec::new() }, - Candidate { id: "powershell", name: "Windows PowerShell".into(), paths: vec![win_join(&system32, &["WindowsPowerShell", "v1.0", "powershell.exe"])], args: Vec::new() }, + Candidate { + id: "powershell", + name: "Windows PowerShell".into(), + paths: vec![win_join(&system32, &["WindowsPowerShell", "v1.0", "powershell.exe"])], + args: Vec::new(), + }, Candidate { id: "cmd", name: "Command Prompt".into(), paths: cmd, args: Vec::new() }, Candidate { id: "wsl", name: "WSL".into(), paths: vec![win_join(&system32, &["wsl.exe"])], args: Vec::new() }, ] @@ -203,7 +209,8 @@ pub fn split_args(text: &str) -> Result, String> { } fn is_custom_id(id: &str) -> bool { - id.strip_prefix("custom-").is_some_and(|rest| !rest.is_empty() && rest.len() <= 64 && rest.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')) + id.strip_prefix("custom-") + .is_some_and(|rest| !rest.is_empty() && rest.len() <= 64 && rest.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')) } /// Custom profiles from the settings file; anything malformed is dropped. @@ -214,9 +221,20 @@ pub fn parse_custom_profiles(data: Option<&Value>, windows: bool) -> Vec>>()) else { continue }; + let Some(args) = + item.get("args").and_then(Value::as_array).and_then(|args| args.iter().map(|a| a.as_str().map(str::to_string)).collect::>>()) + else { + continue; + }; let absolute = if windows { is_win_absolute(file) } else { file.starts_with('/') }; - if !is_custom_id(id) || ids.contains(id) || name.is_empty() || name.encode_utf16().count() > 200 || file.contains('\0') || !absolute || !is_valid_args(&args) { + if !is_custom_id(id) + || ids.contains(id) + || name.is_empty() + || name.encode_utf16().count() > 200 + || file.contains('\0') + || !absolute + || !is_valid_args(&args) + { continue; } ids.insert(id.to_string()); @@ -239,7 +257,11 @@ pub fn custom_profile_name(file: &str, windows: bool) -> String { /// The profile list the renderer gets (`TerminalProfileList`). pub fn profile_list(profiles: &[Profile], saved_default: Option<&Value>) -> Value { - let default = saved_default.and_then(Value::as_str).filter(|id| profiles.iter().any(|p| p.id == *id)).map(str::to_string).or_else(|| profiles.first().map(|p| p.id.clone())); + let default = saved_default + .and_then(Value::as_str) + .filter(|id| profiles.iter().any(|p| p.id == *id)) + .map(str::to_string) + .or_else(|| profiles.first().map(|p| p.id.clone())); json!({ "profiles": profiles.iter().map(Profile::to_json).collect::>(), "defaultProfileId": default }) } @@ -373,7 +395,9 @@ fn env_value(name: &str) -> Option { } if cfg!(windows) { let lower = name.to_lowercase(); - return std::env::vars_os().find(|(key, value)| key.to_string_lossy().to_lowercase() == lower && !value.is_empty()).map(|(_, value)| value.to_string_lossy().into_owned()); + return std::env::vars_os() + .find(|(key, value)| key.to_string_lossy().to_lowercase() == lower && !value.is_empty()) + .map(|(_, value)| value.to_string_lossy().into_owned()); } None } @@ -441,7 +465,12 @@ mod tests { #[test] fn detects_windows_shells_in_preference_order() { - let files = [r"D:\Git\bin\bash.exe", r"C:\Program Files\PowerShell\7\pwsh.exe", r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", r"C:\Windows\System32\cmd.exe"]; + let files = [ + r"D:\Git\bin\bash.exe", + r"C:\Program Files\PowerShell\7\pwsh.exe", + r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", + r"C:\Windows\System32\cmd.exe", + ]; let profiles = detect(true, false, &[("ProgramFiles", r"C:\Program Files"), ("SystemRoot", r"C:\Windows")], &files, Some(r"D:\Git")); assert_eq!(profiles.iter().map(|p| p.id.as_str()).collect::>(), vec!["git-bash", "pwsh", "powershell", "cmd"]); assert_eq!(profiles[0].path, r"D:\Git\bin\bash.exe"); diff --git a/apps/ide/src-tauri/src/recent.rs b/apps/ide/src-tauri/src/recent.rs index ac961105..e75b7112 100644 --- a/apps/ide/src-tauri/src/recent.rs +++ b/apps/ide/src-tauri/src/recent.rs @@ -28,7 +28,9 @@ pub fn parse_recent(text: &str) -> Vec { let Ok(data) = serde_json::from_str::(text) else { return Vec::new() }; data.get("folders") .and_then(Value::as_array) - .map(|folders| folders.iter().filter_map(Value::as_str).filter(|path| Path::new(path).is_absolute()).take(MAX_RECENT_FOLDERS).map(str::to_string).collect()) + .map(|folders| { + folders.iter().filter_map(Value::as_str).filter(|path| Path::new(path).is_absolute()).take(MAX_RECENT_FOLDERS).map(str::to_string).collect() + }) .unwrap_or_default() } diff --git a/apps/ide/src-tauri/src/scene.rs b/apps/ide/src-tauri/src/scene.rs index d0d704fc..2814e3da 100644 --- a/apps/ide/src-tauri/src/scene.rs +++ b/apps/ide/src-tauri/src/scene.rs @@ -198,12 +198,10 @@ fn create(app: &AppHandle, shell: &Arc, sidecar: &Arc, params: & let rect = params.get("bounds").and_then(scene_rect); let factor = crate::menu::zoom_factor_of(app, window_label); let (x, y, width, height) = rect.map(|rect| zoomed(rect, factor)).unwrap_or((0.0, 0.0, 1.0, 1.0)); - let webview = window - .add_child(builder, LogicalPosition::new(x, y), LogicalSize::new(width, height)) - .map_err(|error| { - shell.scenes.remove(&label); - error.to_string() - })?; + let webview = window.add_child(builder, LogicalPosition::new(x, y), LogicalSize::new(width, height)).map_err(|error| { + shell.scenes.remove(&label); + error.to_string() + })?; #[cfg(target_os = "linux")] crate::permissions::allow_screen_capture(&webview); #[cfg(windows)] diff --git a/apps/ide/src-tauri/src/search.rs b/apps/ide/src-tauri/src/search.rs index 8d353c64..6b644417 100644 --- a/apps/ide/src-tauri/src/search.rs +++ b/apps/ide/src-tauri/src/search.rs @@ -61,7 +61,12 @@ pub struct Query { pub fn parse_query(value: &Value) -> Result { let record = value.as_object().ok_or("Invalid search query.")?; let text = |key: &str, max: usize| -> Result { - record.get(key).and_then(Value::as_str).filter(|text| text.encode_utf16().count() <= max).map(str::to_string).ok_or_else(|| format!("Invalid search query field \"{key}\".")) + record + .get(key) + .and_then(Value::as_str) + .filter(|text| text.encode_utf16().count() <= max) + .map(str::to_string) + .ok_or_else(|| format!("Invalid search query field \"{key}\".")) }; let flag = |key: &str| -> Result { record.get(key).and_then(Value::as_bool).ok_or_else(|| format!("Invalid search query field \"{key}\".")) }; Ok(Query { @@ -112,7 +117,8 @@ pub fn compile(query: &Query) -> Result { } let flags = if query.match_case { "g" } else { "gi" }; // V8's SyntaxError message, wrapped as compileQuery wraps it; the reason's wording can differ. - let regex = JsRegex::new(&source, !query.match_case).map_err(|reason| format!("Invalid regular expression: Invalid regular expression: /{source}/{flags}: {reason}"))?; + let regex = JsRegex::new(&source, !query.match_case) + .map_err(|reason| format!("Invalid regular expression: Invalid regular expression: /{source}/{flags}: {reason}"))?; Ok(Compiled { engine: Engine::Js(regex), is_regex: query.is_regex }) } @@ -215,7 +221,11 @@ pub fn find_in_text(text: &str, compiled: &Compiled, limit: usize) -> (Vec Result>, String> { - let patterns: Vec<&str> = text.split(',').map(|pattern| pattern.trim_matches(|c: char| (c as u32) <= 0xFFFF && crate::jsregex::is_js_space(c as u16))).filter(|pattern| !pattern.is_empty()).collect(); + let patterns: Vec<&str> = text + .split(',') + .map(|pattern| pattern.trim_matches(|c: char| (c as u32) <= 0xFFFF && crate::jsregex::is_js_space(c as u16))) + .filter(|pattern| !pattern.is_empty()) + .collect(); if patterns.is_empty() { return Ok(None); } @@ -252,7 +262,15 @@ pub struct Stats { } /// Searches every file under `root`, reporting each file with matches as it is read (searchWorkspace). -pub fn search_workspace(root: &Path, rules: &[IgnoreRule], query: &Query, compiled: &Compiled, cancelled: &AtomicBool, max_matches: usize, mut on_file: impl FnMut(&str, Vec, usize)) -> Result { +pub fn search_workspace( + root: &Path, + rules: &[IgnoreRule], + query: &Query, + compiled: &Compiled, + cancelled: &AtomicBool, + max_matches: usize, + mut on_file: impl FnMut(&str, Vec, usize), +) -> Result { let include = compile_globs(&query.include)?; let exclude = compile_globs(&query.exclude)?; let (files, _) = list_workspace_files(root, rules, SEARCH_FILE_LIMIT); @@ -399,7 +417,8 @@ pub fn replace_in_text(text: &str, compiled: &Compiled, replacement: &str) -> (S pub fn replace_in_files(workspace: &Workspace, query: &Value, replacement: &Value, paths: &Value) -> Result { let query = parse_query(query)?; let replacement = replacement.as_str().filter(|text| text.encode_utf16().count() <= MAX_PATTERN).ok_or("Invalid replacement.")?; - let paths = paths.as_array().filter(|list| list.len() <= MAX_REPLACE_PATHS && list.iter().all(Value::is_string)).ok_or("Invalid list of files to replace in.")?; + let paths = + paths.as_array().filter(|list| list.len() <= MAX_REPLACE_PATHS && list.iter().all(Value::is_string)).ok_or("Invalid list of files to replace in.")?; let compiled = compile(&query)?; let (mut files, mut replacements, mut failed) = (0, 0, Vec::new()); for path in paths { @@ -495,10 +514,15 @@ impl Searches { if !aborted { flush(&mut pending, &mut last_flush); } - send(SEARCH_DONE_EVENT, json!({ "searchId": search_id, "files": stats.files, "matches": stats.matches, "limitHit": stats.limit_hit, "cancelled": aborted || stats.cancelled })); + send( + SEARCH_DONE_EVENT, + json!({ "searchId": search_id, "files": stats.files, "matches": stats.matches, "limitHit": stats.limit_hit, "cancelled": aborted || stats.cancelled }), + ); } // A malformed include or exclude glob, as startSearch's catch reports it. - Err(error) => send(SEARCH_DONE_EVENT, json!({ "searchId": search_id, "files": 0, "matches": 0, "limitHit": false, "cancelled": false, "error": error })), + Err(error) => { + send(SEARCH_DONE_EVENT, json!({ "searchId": search_id, "files": 0, "matches": 0, "limitHit": false, "cancelled": false, "error": error })) + } } let mut running = this.running.lock().unwrap(); if running.get(&window).is_some_and(|(_, current)| Arc::ptr_eq(current, &flag)) { @@ -533,7 +557,10 @@ mod tests { fn reports_an_invalid_pattern_or_an_empty_query() { assert_eq!(compile(&query("", false, false, false)).err().unwrap(), "Type something to search for."); assert!(compile(&query("(", true, false, false)).err().unwrap().starts_with("Invalid regular expression")); - assert_eq!(compile(&query("(", true, false, false)).err().unwrap(), "Invalid regular expression: Invalid regular expression: /(/gi: Unbalanced parenthesis"); + assert_eq!( + compile(&query("(", true, false, false)).err().unwrap(), + "Invalid regular expression: Invalid regular expression: /(/gi: Unbalanced parenthesis" + ); // Look-around and backreferences are JavaScript syntax, so they work (#496). assert_eq!(columns("ab ac", &query("a(?=b)", true, true, false)), vec![(1, 1, 1)]); assert_eq!(columns("xx xy", &query(r"(\w)\1", true, true, false)), vec![(1, 1, 2)]); @@ -605,7 +632,10 @@ mod tests { let mut q = query("needle", false, true, false); let run = |q: &Query, max: usize| { let mut seen = Vec::new(); - let stats = search_workspace(&ws.real_root, &ws.rules, q, &compile(q).unwrap(), &AtomicBool::new(false), max, |path, matches, total| seen.push((path.to_string(), matches.len(), total))).unwrap(); + let stats = search_workspace(&ws.real_root, &ws.rules, q, &compile(q).unwrap(), &AtomicBool::new(false), max, |path, matches, total| { + seen.push((path.to_string(), matches.len(), total)) + }) + .unwrap(); seen.sort(); (seen, stats) }; @@ -619,7 +649,9 @@ mod tests { assert!(run(&q, SEARCH_MAX_MATCHES).0.is_empty()); q.exclude = String::new(); assert!(run(&q, 2).1.limit_hit); - let cancelled = search_workspace(&ws.real_root, &ws.rules, &q, &compile(&q).unwrap(), &AtomicBool::new(true), 10, |_, _, _| panic!("no file after a cancel")).unwrap(); + let cancelled = + search_workspace(&ws.real_root, &ws.rules, &q, &compile(&q).unwrap(), &AtomicBool::new(true), 10, |_, _, _| panic!("no file after a cancel")) + .unwrap(); assert!(cancelled.cancelled); } @@ -643,7 +675,8 @@ mod tests { fn accepts_only_a_well_formed_query_and_id() { assert!(parse_query(&json!({ "pattern": "a", "isRegex": false, "matchCase": false, "wholeWord": false, "include": "", "exclude": "" })).is_ok()); assert!(parse_query(&json!({ "pattern": "a", "isRegex": "no", "matchCase": false, "wholeWord": false, "include": "", "exclude": "" })).is_err()); - assert!(parse_query(&json!({ "pattern": "a".repeat(2001), "isRegex": false, "matchCase": false, "wholeWord": false, "include": "", "exclude": "" })).is_err()); + assert!(parse_query(&json!({ "pattern": "a".repeat(2001), "isRegex": false, "matchCase": false, "wholeWord": false, "include": "", "exclude": "" })) + .is_err()); assert!(parse_query(&json!(null)).is_err()); assert!(parse_search_id(&json!(-1)).is_err()); assert!(parse_search_id(&json!(1.5)).is_err()); diff --git a/apps/ide/src-tauri/src/sidecar.rs b/apps/ide/src-tauri/src/sidecar.rs index 7687ac9b..5d538ab1 100644 --- a/apps/ide/src-tauri/src/sidecar.rs +++ b/apps/ide/src-tauri/src/sidecar.rs @@ -186,13 +186,19 @@ impl Sidecar { /// sidecar keeps its last display language beside it (locale.rs). `unset` are /// variables the core set for its webview only. `log_dir` is the app's log folder: the /// sidecar keeps its rotating log there (`CODEXR_LOG_DIR`, src/main/logFile.ts, #506). - pub fn start(self: &std::sync::Arc, app: AppHandle, layout: &crate::install::Layout, args: &[String], cache_dir: Option<&Path>, log_dir: Option<&Path>, unset: &[&str]) -> Result<(), String> { + pub fn start( + self: &std::sync::Arc, + app: AppHandle, + layout: &crate::install::Layout, + args: &[String], + cache_dir: Option<&Path>, + log_dir: Option<&Path>, + unset: &[&str], + ) -> Result<(), String> { let unwatched = args.iter().any(|arg| arg == "--codexr-bench" || arg == crate::smoke::SMOKE_FLAG); self.interactive.store(!unwatched, Ordering::SeqCst); *self.log_file.lock().unwrap() = log_dir.map(|dir| dir.join(LOG_FILE_NAME)); - let script = std::env::var_os("CODEXR_SIDECAR") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| layout.out.join("sidecar").join("index.cjs")); + let script = std::env::var_os("CODEXR_SIDECAR").map(std::path::PathBuf::from).unwrap_or_else(|| layout.out.join("sidecar").join("index.cjs")); if !script.is_file() { return Err(format!("The sidecar is missing ({}): run `npm run build` first.", script.display())); } diff --git a/apps/ide/src-tauri/src/smoke.rs b/apps/ide/src-tauri/src/smoke.rs index 9b09b4e6..a1efb01f 100644 --- a/apps/ide/src-tauri/src/smoke.rs +++ b/apps/ide/src-tauri/src/smoke.rs @@ -74,7 +74,11 @@ pub fn webview_data_dir() -> std::path::PathBuf { use std::sync::OnceLock; static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { - let unique = format!("codexr-smoke-webview-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_nanos()).unwrap_or(0)); + let unique = format!( + "codexr-smoke-webview-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_nanos()).unwrap_or(0) + ); match std::env::var_os("CODEXR_USER_DATA").filter(|dir| !dir.is_empty()) { Some(profile) => std::path::PathBuf::from(profile).join(unique), None => std::env::temp_dir().join(unique), @@ -120,9 +124,7 @@ pub fn evaluate(app: &AppHandle, params: &Value) -> Result { /// The top-level items of the application menu, by their text (empty when none is set). fn menu_items(app: &AppHandle) -> Vec { let Some(menu) = app.menu() else { return Vec::new() }; - menu.items() - .map(|items| items.iter().filter_map(|item| item.as_submenu().and_then(|submenu| submenu.text().ok())).collect()) - .unwrap_or_default() + menu.items().map(|items| items.iter().filter_map(|item| item.as_submenu().and_then(|submenu| submenu.text().ok())).collect()).unwrap_or_default() } /// The message box part of the probe: the request as `dialog.message` parses it. @@ -195,7 +197,10 @@ mod tests { #[test] fn the_message_box_probe_parses_as_the_dialog_would() { - let probe = message_box_probe(&json!({ "type": "question", "message": "Pick", "buttons": ["Alpha", "Beta", "Gamma", "Cancel"], "defaultId": 0, "cancelId": 3 }), true); + let probe = message_box_probe( + &json!({ "type": "question", "message": "Pick", "buttons": ["Alpha", "Beta", "Gamma", "Cancel"], "defaultId": 0, "cancelId": 3 }), + true, + ); assert_eq!(probe["buttons"], json!(["Alpha", "Beta", "Gamma", "Cancel"])); assert_eq!(probe["cancelId"], json!(3)); assert_eq!(probe["defaultId"], json!(0)); diff --git a/apps/ide/src-tauri/src/terminal.rs b/apps/ide/src-tauri/src/terminal.rs index 560737fb..09ff063d 100644 --- a/apps/ide/src-tauri/src/terminal.rs +++ b/apps/ide/src-tauri/src/terminal.rs @@ -442,7 +442,10 @@ impl Terminals { } pub fn input(&self, owner: Option<&str>, id: &Value, data: &Value) -> Result<(), String> { - let data = data.as_str().filter(|data| data.len() <= MAX_INPUT_LENGTH * 3 && data.encode_utf16().count() <= MAX_INPUT_LENGTH).ok_or("Invalid terminal input.")?; + let data = data + .as_str() + .filter(|data| data.len() <= MAX_INPUT_LENGTH * 3 && data.encode_utf16().count() <= MAX_INPUT_LENGTH) + .ok_or("Invalid terminal input.")?; self.with_owned(owner, id, |terminal| { let _ = terminal.input.send(data.as_bytes().to_vec()); }) @@ -525,7 +528,13 @@ mod tests { #[test] fn drops_the_ide_switches_and_announces_the_terminal() { - let env = vec![("PATH".to_string(), "/bin".to_string()), ("NODE_OPTIONS".into(), "--x".into()), ("node_options".into(), "--y".into()), ("TERM".into(), "dumb".into()), ("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into())]; + let env = vec![ + ("PATH".to_string(), "/bin".to_string()), + ("NODE_OPTIONS".into(), "--x".into()), + ("node_options".into(), "--y".into()), + ("TERM".into(), "dumb".into()), + ("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into()), + ]; let result = terminal_environment(env.into_iter(), &["WEBKIT_DISABLE_DMABUF_RENDERER"]); let get = |key: &str| result.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()); assert_eq!(get("PATH"), Some("/bin")); @@ -645,7 +654,8 @@ mod tests { assert!(pid.is_some()); assert!(wait_for(&seen, &format!("exit {id} 3")), "{:?}", seen.lock().unwrap()); let lines = seen.lock().unwrap().clone(); - let output: String = lines.iter().filter(|(_, _, line)| line.starts_with("data")).map(|(_, _, line)| line.splitn(3, ' ').nth(2).unwrap().to_string()).collect(); + let output: String = + lines.iter().filter(|(_, _, line)| line.starts_with("data")).map(|(_, _, line)| line.splitn(3, ' ').nth(2).unwrap().to_string()).collect(); assert!(output.contains("hello codexr"), "{output:?}"); // The exit comes after every output event, and only to its owner. assert!(lines.last().unwrap().2.starts_with("exit")); diff --git a/apps/ide/src-tauri/src/webviews.rs b/apps/ide/src-tauri/src/webviews.rs index a451f39a..ef025f16 100644 --- a/apps/ide/src-tauri/src/webviews.rs +++ b/apps/ide/src-tauri/src/webviews.rs @@ -149,7 +149,8 @@ mod tests { #[test] fn builds_the_response_the_sidecar_describes() { - let page = response_of(&json!({ "status": 200, "headers": { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }, "body": "

hi

" })); + let page = + response_of(&json!({ "status": 200, "headers": { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }, "body": "

hi

" })); assert_eq!(page.status(), StatusCode::OK); assert_eq!(page.headers().get("content-type").unwrap(), "text/html; charset=utf-8"); assert_eq!(page.headers().get("cache-control").unwrap(), "no-store"); diff --git a/apps/ide/src-tauri/src/workspace.rs b/apps/ide/src-tauri/src/workspace.rs index 808410c9..8ffd3a61 100644 --- a/apps/ide/src-tauri/src/workspace.rs +++ b/apps/ide/src-tauri/src/workspace.rs @@ -312,10 +312,7 @@ impl Workspace { _ => Ordering::Greater, }); Ok(Value::Array( - entries - .into_iter() - .map(|(name, kind, path, ignored)| json!({ "name": name, "path": path, "kind": kind.as_str(), "ignored": ignored })) - .collect(), + entries.into_iter().map(|(name, kind, path, ignored)| json!({ "name": name, "path": path, "kind": kind.as_str(), "ignored": ignored })).collect(), )) } @@ -438,7 +435,9 @@ impl Workspace { EntryKind::Directory => fs::create_dir(&target), EntryKind::File => fs::OpenOptions::new().write(true).create_new(true).open(&target).map(|_| ()), }; - created.map_err(|error| if error.kind() == ErrorKind::AlreadyExists { format!("{entry_name} already exists.") } else { io_error(error, "open", &target) })?; + created.map_err( + |error| if error.kind() == ErrorKind::AlreadyExists { format!("{entry_name} already exists.") } else { io_error(error, "open", &target) }, + )?; Ok(Value::String(child_path(&parse_workspace_path(parent)?.join("/"), &entry_name))) } @@ -631,8 +630,8 @@ fn entry_id(path: &Path) -> std::io::Result<(u64, u64)> { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; use windows_sys::Win32::Storage::FileSystem::{ - CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, - FILE_SHARE_WRITE, OPEN_EXISTING, + CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, + FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, }; let wide: Vec = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect(); // SAFETY: `wide` is NUL-terminated and outlives the call; the handle is closed below. @@ -764,7 +763,8 @@ pub fn list_workspace_files(root: &Path, rules: &[IgnoreRule], limit: usize) -> while !queue.is_empty() { let mut next = Vec::new(); for relative in &queue { - let folder = if relative.is_empty() { root.to_path_buf() } else { relative.split('/').fold(root.to_path_buf(), |path, segment| path.join(segment)) }; + let folder = + if relative.is_empty() { root.to_path_buf() } else { relative.split('/').fold(root.to_path_buf(), |path, segment| path.join(segment)) }; let Ok(reader) = fs::read_dir(&folder) else { continue }; for entry in reader.flatten() { let name = entry.file_name().to_string_lossy().into_owned(); From cf207ca4a467e7f0dcc3e4df2667bc55233e4e3a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:37:04 +0000 Subject: [PATCH 26/74] fix(ide): a Markdown preview closed before its module loaded leaves the page (#518) --- apps/ide/src/renderer/editor/lazyMarkdownPreview.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts b/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts index d98dab1d..f4815b8d 100644 --- a/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts +++ b/apps/ide/src/renderer/editor/lazyMarkdownPreview.ts @@ -68,6 +68,8 @@ export function lazyMarkdownPreview(host: MarkdownPreviewHost, load: () => Promi }, dispose() { disposed = true; + // Like the preview's own dispose, it leaves the document. + holder.remove(); real?.dispose(); }, }; From 2168f2b376e6d5bc2965184ec800cec5ff0fdc29 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:40:54 +0000 Subject: [PATCH 27/74] test(extension): register core/agent-prompts in the folder map, guardrail baseline and test README (#514) --- apps/vscode-extension/test/README.md | 1 + .../test/tooling/folderDependencies.json | 3 +++ .../test/tooling/guardrail-baseline.json | 24 ++++++++++++------- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/apps/vscode-extension/test/README.md b/apps/vscode-extension/test/README.md index 4fe2ee11..e892717d 100644 --- a/apps/vscode-extension/test/README.md +++ b/apps/vscode-extension/test/README.md @@ -6,6 +6,7 @@ This folder contains the local validation suite for CodeXR. Every `*.test.cjs` below `test/` is collected by `npm run test:unit`, except under `test/runners/`, which the collector skips on purpose. +- `test/agent_prompts`: the host-neutral agent prompt templates of the core (`core/agent-prompts`), shared with the Code-XR IDE (#514). - `test/analysis`: the largest group: browser runtimes (tables, charts, mapping UI, modes, dependency graph, historical comparison, project evolution, collaboration), parsers, export, Git services, watchers. - `test/baseline`: the feature baseline of the cleanup epic (#26): a snapshot of everything a user can see, invoke or rely on, and the register of the only removals the maintainer authorized. `node test/baseline/featureSurface.cjs --write` regenerates it and refuses to drop an unauthorized entry. - `test/collaboration`: collaborative XR sessions. diff --git a/apps/vscode-extension/test/tooling/folderDependencies.json b/apps/vscode-extension/test/tooling/folderDependencies.json index 9d75f219..dea05663 100644 --- a/apps/vscode-extension/test/tooling/folderDependencies.json +++ b/apps/vscode-extension/test/tooling/folderDependencies.json @@ -46,6 +46,9 @@ "platform" ], "core/agent-flow": [], + "core/agent-prompts": [ + "core/metrics" + ], "core/claude-sessions": [], "core/analysis": [ "core/charts", diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 2915be2a..ecdcb2e6 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -64,6 +64,7 @@ "complexity.over30": 0, "reachability.unreachable": [ "src/core/agent-flow/acpSessionEvents.ts", + "src/core/agent-prompts/hotspotPrompt.ts", "src/core/analysis/session/activeAnalyses.ts", "src/core/claude-sessions/claudeSessionContinuity.ts" ], @@ -76,10 +77,10 @@ } }, "informational": { - "src.files": 363, - "src.lines": 60705, - "src.functions": 4325, - "src.unreachableLines": 499, + "src.files": 366, + "src.lines": 61606, + "src.functions": 4428, + "src.unreachableLines": 804, "console.byFile": { "src/platform/logging/sink.ts": 2 }, @@ -268,6 +269,10 @@ "file": "src/core/export/exportManifest.ts", "lines": 747 }, + { + "file": "src/core/server/httpServer.ts", + "lines": 698 + }, { "file": "src/core/server/collaboration/collaborationRoomServer.ts", "lines": 685 @@ -276,10 +281,6 @@ "file": "src/core/history/gitRepositoryService.ts", "lines": 679 }, - { - "file": "src/core/server/httpServer.ts", - "lines": 676 - }, { "file": "src/features/active-servers/views/handleServerActions.ts", "lines": 634 @@ -368,6 +369,13 @@ "to": 3, "reason": "#431: core/claude-sessions is the IDE's shared core for Claude Code session continuity; the extension reaches it on v1.3.0 (claudeSessionCommands.ts), the ide branch has only the IDE consumer", "date": "2026-12-02" + }, + { + "metric": "reachability.unreachable", + "from": 3, + "to": 4, + "reason": "#514: core/agent-prompts is the IDE's shared core for the Ask-agent prompt templates; the extension reaches it when its chat lands (#216), the ide branch has only the IDE consumer", + "date": "2026-12-05" } ] } From bec758866be37ba31671a9b26860e428df7a5be2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:41:42 +0000 Subject: [PATCH 28/74] feat(ide): explorer badges and filter for the files the active chat touched (#525) --- .../src/renderer/agentFirst/agentWorkbench.ts | 5 + apps/ide/src/renderer/chatFootprint.ts | 119 +++++++++++ apps/ide/src/renderer/chatFootprintFeed.ts | 80 ++++++++ apps/ide/src/renderer/debug/debug.css | 2 - apps/ide/src/renderer/explorer.ts | 89 ++++++++- apps/ide/src/renderer/git/scm.css | 6 + apps/ide/src/renderer/main.ts | 5 + apps/ide/src/shared/i18n/messages.en.ts | 6 + apps/ide/src/shared/i18n/messages.es.ts | 6 + apps/ide/test/chatFootprint.test.ts | 186 ++++++++++++++++++ 10 files changed, 497 insertions(+), 7 deletions(-) create mode 100644 apps/ide/src/renderer/chatFootprint.ts create mode 100644 apps/ide/src/renderer/chatFootprintFeed.ts create mode 100644 apps/ide/test/chatFootprint.test.ts diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 226b5bba..6e8778bf 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -61,6 +61,9 @@ export interface AgentWorkbenchOptions { openFolder(): void; /** The workspace calls the project instructions section needs (AF11). */ readonly instructions: Omit; + /** #525: a chat tab came on screen / closed (the explorer's footprint follows the chat last shown). */ + onChatShown?(sessionId: string): void; + onChatClosed?(sessionId: string): void; /** Optional hooks of later stories. */ readonly chatHooks?: Pick; } @@ -245,6 +248,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork onShow: () => { activeChatId = sessionId; sessions.setActive(sessionId); + options.onChatShown?.(sessionId); // #509: the chat is on screen: its toast has done its job. notices.close(sessionId); api.markRead(sessionId).catch(() => undefined); @@ -260,6 +264,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork view.dispose(); views.delete(view); tabClosers.delete(sessionId); + options.onChatClosed?.(sessionId); }, }; }, diff --git a/apps/ide/src/renderer/chatFootprint.ts b/apps/ide/src/renderer/chatFootprint.ts new file mode 100644 index 00000000..c1251d93 --- /dev/null +++ b/apps/ide/src/renderer/chatFootprint.ts @@ -0,0 +1,119 @@ +import type { AgentSessionState, ToolKind } from '../shared/agentSession.ts'; + +/** + * #525 (O23): the footprint of the active chat in the explorer: the files it + * edited (an "A" on the row) and the files it only read (a dim dot), and the + * folders above them, which the "Files touched by this chat" filter keeps. + * Built from what the renderer already has: the chat's transcript (its tool + * calls and their locations and diffs, as the agent reported them) and the + * chat's pending changes (`AgentSessionsApi.changes`, from the checkpoints). + * Pure, so it is unit-tested; `explorer.ts` draws it. + */ + +export type FootprintMark = 'edited' | 'read'; + +export interface ChatFootprint { + readonly sessionId: string; + readonly chatTitle: string; + /** Workspace-relative paths (forward slashes) and what the chat did to each. */ + readonly files: ReadonlyMap; + /** Every folder above a touched file ('' is the top folder and never listed). */ + readonly folders: ReadonlySet; +} + +const EDIT_KINDS = new Set(['edit', 'delete', 'move']); + +const isAbsolute = (path: string): boolean => path.startsWith('/') || /^[A-Za-z]:\//.test(path) || path.startsWith('//'); + +/** + * `path` (absolute, as an agent reports it, or already relative) as a path of + * the workspace, under the first of `roots` that holds it; null outside them. + * Windows separators are accepted, and roots compare without case (Windows and + * the default macOS file system do). + */ +export function workspaceRelative(path: string, roots: readonly string[]): string | null { + const normalized = path.replace(/\\/g, '/'); + if (!isAbsolute(normalized)) { + const relative = normalized.replace(/^(\.\/)+/, '').replace(/\/+$/, ''); + return relative === '' || relative === '.' || relative.startsWith('../') ? null : relative; + } + for (const root of roots) { + const base = root.replace(/\\/g, '/').replace(/\/+$/, ''); + if (base !== '' && normalized.toLowerCase().startsWith(`${base.toLowerCase()}/`)) { + const relative = normalized.slice(base.length + 1).replace(/\/+$/, ''); + return relative === '' ? null : relative; + } + } + return null; +} + +/** The folders above a workspace path, nearest last: `a/b/c.ts` gives `a`, `a/b`. */ +export function foldersAbove(path: string): string[] { + const parts = path.split('/'); + return parts.slice(0, -1).map((_, index) => parts.slice(0, index + 1).join('/')); +} + +/** The footprint of a chat from its transcript and its pending changes (workspace-relative paths). */ +export function chatFootprint( + state: Pick, + changed: readonly string[], +): ChatFootprint { + // A worktree chat reports paths under its worktree (where the project sits in it, `cwd`): + // they are shown on the same paths of the project. + const roots = [state.worktree?.cwd, state.workspaceRoot].filter((root): root is string => typeof root === 'string' && root !== ''); + const files = new Map(); + const mark = (path: string | null, what: FootprintMark): void => { + if (path !== null && files.get(path) !== 'edited') { + files.set(path, what); + } + }; + for (const item of state.items) { + if (item.kind !== 'tool' || item.status === 'failed') { + continue; + } + const what: FootprintMark | null = EDIT_KINDS.has(item.toolKind) ? 'edited' : item.toolKind === 'read' ? 'read' : null; + if (what) { + for (const location of item.locations) { + mark(workspaceRelative(location.path, roots), what); + } + } + for (const block of item.content) { + if (block.type === 'diff') { + mark(workspaceRelative(block.path, roots), 'edited'); + } + } + } + for (const path of changed) { + mark(workspaceRelative(path, roots), 'edited'); + } + const folders = new Set(); + for (const path of files.keys()) { + for (const folder of foldersAbove(path)) { + folders.add(folder); + } + } + return { sessionId: state.id, chatTitle: state.title, files, folders }; +} + +/** What the explorer shows on a row: the file's mark, or null (folders and untouched files). */ +export function footprintMark(footprint: ChatFootprint | null, path: string): FootprintMark | null { + return footprint?.files.get(path) ?? null; +} + +/** Whether the "Files touched by this chat" filter keeps a row: a touched file, or a folder above one. */ +export function footprintKeeps(footprint: ChatFootprint | null, path: string, kind: 'file' | 'directory'): boolean { + if (!footprint) { + return false; + } + return kind === 'directory' ? footprint.folders.has(path) : footprint.files.has(path); +} + +/** The folders to open so every touched file is on screen, outermost first. */ +export function foldersToReveal(footprint: ChatFootprint | null): string[] { + return footprint ? [...footprint.folders].sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b)) : []; +} + +/** Session events after which the footprint may have changed. */ +export function footprintMayChange(eventType: string): boolean { + return eventType === 'tool' || eventType === 'pending-changes' || eventType === 'turn-end'; +} diff --git a/apps/ide/src/renderer/chatFootprintFeed.ts b/apps/ide/src/renderer/chatFootprintFeed.ts new file mode 100644 index 00000000..fffd8794 --- /dev/null +++ b/apps/ide/src/renderer/chatFootprintFeed.ts @@ -0,0 +1,80 @@ +import type { AgentSessionMessage, AgentSessionsApi } from '../shared/agentSession.ts'; +import { chatFootprint, footprintMayChange, type ChatFootprint } from './chatFootprint.ts'; + +/** + * #525 (O23): keeps the explorer's chat footprint on the chat last shown. The + * agent workbench says which chat came on screen and which closed; this asks + * for the chat's transcript and pending changes through the existing session + * calls (no new IPC) and redraws after each tool call, pending-changes count + * or end of turn of that chat, at most a few times a second. + */ +export interface ChatFootprintFeed { + /** A chat tab came on screen: the footprint follows it. */ + chatShown(sessionId: string): void; + /** A chat tab closed: if it was the one followed, the footprint goes. */ + chatClosed(sessionId: string): void; + dispose(): void; +} + +const REFRESH_MS = 300; + +export function createChatFootprintFeed( + api: Pick, + apply: (footprint: ChatFootprint | null) => void, +): ChatFootprintFeed { + let current: string | null = null; + let generation = 0; + let timer: ReturnType | undefined; + + async function load(sessionId: string, mine: number): Promise { + try { + const state = await api.get(sessionId); + const changes = await api.changes(sessionId).then((result) => result.files.map((file) => file.path), () => []); + if (mine === generation && current === sessionId) { + apply(chatFootprint(state, changes)); + } + } catch { + // The chat is gone (deleted here or in another window). + if (mine === generation && current === sessionId) { + current = null; + apply(null); + } + } + } + + function refresh(delay: number): void { + clearTimeout(timer); + const sessionId = current; + const mine = ++generation; + if (sessionId === null) { + apply(null); + return; + } + timer = setTimeout(() => void load(sessionId, mine), delay); + } + + const unsubscribe = api.onMessage((message: AgentSessionMessage) => { + if (message.kind === 'event' && message.sessionId === current && footprintMayChange(message.event.type)) { + refresh(REFRESH_MS); + } + }); + + return { + chatShown(sessionId) { + if (sessionId !== current) { + current = sessionId; + refresh(0); + } + }, + chatClosed(sessionId) { + if (sessionId === current) { + current = null; + refresh(0); + } + }, + dispose() { + clearTimeout(timer); + unsubscribe(); + }, + }; +} diff --git a/apps/ide/src/renderer/debug/debug.css b/apps/ide/src/renderer/debug/debug.css index 83ee827b..a4863a68 100644 --- a/apps/ide/src/renderer/debug/debug.css +++ b/apps/ide/src/renderer/debug/debug.css @@ -51,8 +51,6 @@ cursor: pointer; } .debug-row:hover { background: var(--hover); } -.debug-node:focus { outline: none; } -.debug-node:focus > .debug-row { outline: 1px solid var(--accent); outline-offset: -1px; } .debug-twisty { flex: none; width: 14px; text-align: center; color: var(--muted); } .debug-twisty::before { content: '\203A'; display: inline-block; transition: transform 0.1s; } .debug-node[aria-expanded='true'] > .debug-row .debug-twisty::before { transform: rotate(90deg); } diff --git a/apps/ide/src/renderer/explorer.ts b/apps/ide/src/renderer/explorer.ts index 45301224..74dafcc7 100644 --- a/apps/ide/src/renderer/explorer.ts +++ b/apps/ide/src/renderer/explorer.ts @@ -3,6 +3,7 @@ import type { CodeXRApi, DirEntry, WorkspaceInfo } from '../shared/api.ts'; import { el, fileIcon, icon } from './dom.ts'; import type { ExplorerGitDecoration } from '../shared/gitGutter.ts'; import { treeKeyAction } from './treeKeyModel.ts'; +import { footprintKeeps, footprintMark, foldersToReveal, type ChatFootprint } from './chatFootprint.ts'; import { treeKeyRow } from './treeKeyboard.ts'; /** @@ -27,6 +28,7 @@ const NEW_FILE = 'M6 3h8l4 4v14H6zM12 11v6M9 14h6'; const NEW_FOLDER = 'M3 6h7l2 2h9v11H3zM12 11v6M9 14h6'; const REFRESH = 'M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5'; const COLLAPSE_ALL = 'M4 4h16v16H4zM8 12h8'; +const FILTER = 'M4 5h16l-6 7v6l-4 2v-8z'; const parentOf = (path: string): string => path.split('/').slice(0, -1).join('/'); @@ -46,6 +48,8 @@ export interface Explorer { reveal(path: string): Promise; /** #175: the Git state of the changed files and of the folders above them (colour, and a letter on files). */ setGitDecorations(decorations: ReadonlyMap): void; + /** #525: the files the active chat edited ("A") and read (a dot); null when no chat is followed. */ + setChatFootprint(footprint: ChatFootprint | null): void; /** #285: the entry operations of the context menu, on a workspace path (`''` is the top folder). */ rename(path: string): void; trash(path: string): void; @@ -107,6 +111,11 @@ export function createExplorer( actionButton(t('explorer.refresh'), REFRESH, 'explorer-refresh', () => void refreshAll()), actionButton(t('explorer.collapseAll'), COLLAPSE_ALL, 'explorer-collapse-all', () => collapseAll()), ]); + // #525: "Files touched by this chat" hides every other row. + const chatFilter = actionButton(t('explorer.chatFilter'), FILTER, 'explorer-chat-filter', () => setChatFilter(!chatFilterOn)); + chatFilter.setAttribute('aria-pressed', 'false'); + actions.prepend(chatFilter); + const filterNote = el('p', { className: 'muted side-note small explorer-filter-note', attrs: { hidden: '', 'data-testid': 'explorer-filter-note' } }); actions.hidden = true; const header = el('div', { className: 'side-bar-header' }, [title, actions]); const body = el('div', { className: 'explorer-body' }); @@ -194,24 +203,47 @@ export function createExplorer( } // #175: rows follow the last Git status; a row rendered later picks its state up in renderItem. + // #525: and the active chat's footprint (an "A" for an edit, a dot for a read). let gitDecorations: ReadonlyMap = new Map(); + let footprint: ChatFootprint | null = null; + let chatFilterOn = false; function decorate(row: HTMLElement, path: string): void { const decoration = gitDecorations.get(path); const state = decoration?.state ?? ''; - if ((row.dataset['git'] ?? '') === state && (row.querySelector('.tree-git-letter')?.textContent ?? '') === (decoration?.letter ?? '')) { + const agent = footprintMark(footprint, path) ?? ''; + const signature = `${state}|${decoration?.letter ?? ''}|${agent}`; + if ((row.dataset['decor'] ?? '||') === signature) { return; } + row.dataset['decor'] = signature; if (state) { row.dataset['git'] = state; } else { delete row.dataset['git']; } + if (agent) { + row.dataset['agent'] = agent; + } else { + delete row.dataset['agent']; + } row.querySelector('.tree-git-letter')?.remove(); + row.querySelector('.tree-agent-mark')?.remove(); + const agentLabel = agent === 'edited' ? t('explorer.agentEdited') : agent === 'read' ? t('explorer.agentRead') : ''; + if (agent) { + row.append(el('span', { className: 'tree-agent-mark', text: agent === 'edited' ? 'A' : '\u2022', attrs: { 'aria-hidden': 'true' } })); + } if (decoration?.letter) { row.append(el('span', { className: 'tree-git-letter', text: decoration.letter, attrs: { 'aria-hidden': 'true' } })); } - const base = row.title.replace(/ \((modified|added|deleted|untracked|renamed|conflict)\)$/, ''); - row.title = state ? `${base} (${state})` : base; + const base = row.dataset['path'] ?? path; + row.title = `${base}${state ? ` (${state})` : ''}${agentLabel ? ` - ${agentLabel}` : ''}`; + // The marks are hidden from screen readers: the row says it in its name. + const label = row.querySelector('.tree-label')?.textContent ?? ''; + if (agentLabel) { + row.setAttribute('aria-label', `${label}, ${agentLabel}`); + } else { + row.removeAttribute('aria-label'); + } } function setGitDecorations(decorations: ReadonlyMap): void { gitDecorations = decorations; @@ -219,6 +251,50 @@ export function createExplorer( decorate(node.row, node.entry.path); } } + /** Folders the filter already opened for this chat: one the person closes again stays closed. */ + const revealed = new Set(); + function setChatFootprint(next: ChatFootprint | null): void { + if (next?.sessionId !== footprint?.sessionId) { + revealed.clear(); + } + footprint = next; + for (const node of nodes.values()) { + decorate(node.row, node.entry.path); + } + applyChatFilter(); + } + function setChatFilter(on: boolean): void { + chatFilterOn = on; + revealed.clear(); + applyChatFilter(); + } + /** Hides the rows the chat did not touch (with the filter on) and opens the folders down to the touched files. */ + function applyChatFilter(): void { + chatFilter.setAttribute('aria-pressed', String(chatFilterOn)); + const label = footprint ? t('explorer.chatFilterOf', { name: footprint.chatTitle }) : t('explorer.chatFilter'); + chatFilter.title = label; + chatFilter.setAttribute('aria-label', label); + for (const node of nodes.values()) { + node.item.hidden = chatFilterOn && !footprintKeeps(footprint, node.entry.path, node.entry.kind); + } + filterNote.hidden = !chatFilterOn || (footprint !== null && footprint.files.size > 0); + filterNote.textContent = footprint ? t('explorer.chatFilterEmpty') : t('explorer.chatFilterNoChat'); + if (chatFilterOn) { + void revealFootprint(); + } + } + async function revealFootprint(): Promise { + for (const folder of foldersToReveal(footprint)) { + const node = nodeAt(folder); + if (!node || revealed.has(folder)) { + continue; + } + revealed.add(folder); + if (!node.expanded) { + await toggle(node, true); + } + } + } function forget(item: HTMLElement): void { for (const row of item.querySelectorAll('[role="treeitem"]')) { @@ -255,6 +331,7 @@ export function createExplorer( const item = el('li', { attrs: { role: 'none' } }, [row]); nodes.set(row, { entry, row, item, group: null, expanded: false }); decorate(row, entry.path); + item.hidden = chatFilterOn && !footprintKeeps(footprint, entry.path, entry.kind); row.classList.toggle('is-cut', clipboard?.mode === 'cut' && clipboard.path === entry.path); return item; } @@ -409,7 +486,9 @@ export function createExplorer( }); root.addEventListener('keydown', onKeyDown); tree = root; - body.replaceChildren(root); + body.replaceChildren(filterNote, root); + revealed.clear(); + applyChatFilter(); const first = root.querySelector('[role="treeitem"]'); first?.setAttribute('tabindex', '0'); if (!first) { @@ -702,7 +781,7 @@ export function createExplorer( } return { - show, openFolder, expandedFolders, refresh, newFile: () => createEntry('file'), newFolder: () => createEntry('directory'), reveal, setGitDecorations, + show, openFolder, expandedFolders, refresh, newFile: () => createEntry('file'), newFolder: () => createEntry('directory'), reveal, setGitDecorations, setChatFootprint, rename: (path) => onNode(path, renameEntry), trash: (path) => onNode(path, trashEntry), cut: (path) => setClipboard(path, 'cut'), diff --git a/apps/ide/src/renderer/git/scm.css b/apps/ide/src/renderer/git/scm.css index 4953919b..7bbf0478 100644 --- a/apps/ide/src/renderer/git/scm.css +++ b/apps/ide/src/renderer/git/scm.css @@ -134,3 +134,9 @@ .git-peek-title { flex: 1; color: var(--muted); } .git-peek-original { flex: 1; margin: 0; padding: 0 8px 4px; overflow: auto; color: var(--crit); white-space: pre; } .git-peek-note { margin: 0; padding: 0 8px 4px; } +/* #525: the active chat's footprint in the explorer: "A" for an edit, a dim dot for a read. */ +.tree-agent-mark { flex-shrink: 0; margin-left: auto; padding: 0 2px 0 6px; font-size: var(--fs-xs); font-weight: 600; color: var(--accent); } +.tree-row[data-agent='read'] .tree-agent-mark { color: var(--muted); font-weight: 400; opacity: 0.7; } +.tree-agent-mark + .tree-git-letter { margin-left: 0; } +.explorer-filter-note { padding: 4px 12px; } +.side-bar-actions .icon-button[data-testid='explorer-chat-filter'][aria-pressed='true'] { background: var(--hover); color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index cf725f0f..0fc2e41b 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -5,6 +5,7 @@ import './locale.ts'; import { renderWorkbench } from './workbench.ts'; import { isSchemeId } from './editor/customEditorRegistry.ts'; import { createExplorer } from './explorer.ts'; +import { createChatFootprintFeed } from './chatFootprintFeed.ts'; import { createPythonView, pythonStatusText } from './pythonView.ts'; import { createAnalysisRunView } from './analysisRunView.ts'; import { analysisMenuItems, paletteTarget } from './analysisMenu.ts'; @@ -1340,6 +1341,8 @@ let agentRoot: string | null = null; function workspacePathOf(path: string): string { return displayPath(path, agentRoot); } +// #525: the explorer marks the files the chat last shown read and edited. +const chatFootprints = createChatFootprintFeed(api.agentSessions, (footprint) => explorer.setChatFootprint(footprint)); const agentWorkbench = installAgentWorkbench({ workbench, api: api.agentSessions, @@ -1380,6 +1383,8 @@ const agentWorkbench = installAgentWorkbench({ openFolder: () => { registry.execute('workspace.openFolder'); }, + onChatShown: (sessionId) => chatFootprints.chatShown(sessionId), + onChatClosed: (sessionId) => chatFootprints.chatClosed(sessionId), }); function agentFolderChanged(root: string | null): void { agentRoot = root; diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 6b6ff8c9..d445ec92 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -139,6 +139,12 @@ export const en = { 'explorer.recentFolders': 'Recent folders', 'explorer.newFileName': 'New file name', 'explorer.newFolderName': 'New folder name', + 'explorer.chatFilter': 'Files Touched by This Chat', + 'explorer.chatFilterOf': 'Files touched by the chat "{name}"', + 'explorer.chatFilterNoChat': 'Open a chat to see the files it read and edited.', + 'explorer.chatFilterEmpty': 'This chat has not read or edited any file yet.', + 'explorer.agentEdited': 'edited by the active chat', + 'explorer.agentRead': 'read by the active chat', 'search.replace': 'Replace', 'search.include': 'Files to include', 'search.includeExample': 'e.g. src, *.ts', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 358fdd75..cbe4a1ac 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -142,6 +142,12 @@ export const es: Readonly> = { 'explorer.recentFolders': 'Carpetas recientes', 'explorer.newFileName': 'Nombre del nuevo archivo', 'explorer.newFolderName': 'Nombre de la nueva carpeta', + 'explorer.chatFilter': 'Archivos usados por este chat', + 'explorer.chatFilterOf': 'Archivos usados por el chat "{name}"', + 'explorer.chatFilterNoChat': 'Abre un chat para ver los archivos que ha leído y editado.', + 'explorer.chatFilterEmpty': 'Este chat todavía no ha leído ni editado ningún archivo.', + 'explorer.agentEdited': 'editado por el chat activo', + 'explorer.agentRead': 'leído por el chat activo', 'search.replace': 'Reemplazar', 'search.include': 'Archivos para incluir', 'search.includeExample': 'p. ej. src, *.ts', diff --git a/apps/ide/test/chatFootprint.test.ts b/apps/ide/test/chatFootprint.test.ts new file mode 100644 index 00000000..cfba4637 --- /dev/null +++ b/apps/ide/test/chatFootprint.test.ts @@ -0,0 +1,186 @@ +// #525 (O23): the explorer's footprint of the active chat: which files it +// edited and read (from its tool calls and pending changes), the folders the +// filter keeps, and the feed that follows the chat last shown. +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import type { AgentSessionMessage, AgentSessionState, ChatChanges, SessionWorktree, ToolKind, ToolStatus, TranscriptItem } from '../src/shared/agentSession.ts'; +import { + chatFootprint, footprintKeeps, footprintMark, footprintMayChange, foldersAbove, foldersToReveal, workspaceRelative, +} from '../src/renderer/chatFootprint.ts'; +import { createChatFootprintFeed } from '../src/renderer/chatFootprintFeed.ts'; +import { en } from '../src/shared/i18n/messages.en.ts'; +import { es } from '../src/shared/i18n/messages.es.ts'; + +let toolId = 0; +function tool(toolKind: ToolKind, paths: readonly string[], status: ToolStatus = 'completed', diff?: string): TranscriptItem { + return { + kind: 'tool', id: `t${toolId++}`, title: toolKind, toolKind, status, + locations: paths.map((path) => ({ path })), + content: diff ? [{ type: 'diff', path: diff, oldText: 'a', newText: 'b' }] : [], + }; +} + +type FootprintState = Pick; +function state(items: readonly TranscriptItem[], extra: Partial = {}): FootprintState { + return { id: 'chat-1', title: 'Fix the parser', items, workspaceRoot: '/home/me/project', ...extra }; +} + +describe('workspaceRelative', () => { + it('makes an absolute path relative to the first root that holds it', () => { + assert.equal(workspaceRelative('/home/me/project/src/a.ts', ['/home/me/project']), 'src/a.ts'); + assert.equal(workspaceRelative('/home/me/other/a.ts', ['/home/me/project']), null); + assert.equal(workspaceRelative('/home/me/project', ['/home/me/project']), null); + assert.equal(workspaceRelative('/home/me/projectile/a.ts', ['/home/me/project']), null, 'a prefix is not a parent'); + }); + + it('accepts Windows paths and compares roots without case', () => { + assert.equal(workspaceRelative('C:\\Users\\Me\\Project\\src\\a.ts', ['c:\\users\\me\\project\\']), 'src/a.ts'); + assert.equal(workspaceRelative('d:/x/a.ts', ['C:/x']), null); + }); + + it('keeps a relative path, without a leading ./, and refuses one that climbs out', () => { + assert.equal(workspaceRelative('./src/a.ts', []), 'src/a.ts'); + assert.equal(workspaceRelative('src\\a.ts', []), 'src/a.ts'); + assert.equal(workspaceRelative('../a.ts', []), null); + assert.equal(workspaceRelative('.', []), null); + }); +}); + +describe('chatFootprint', () => { + it('marks edited and read files; an edit wins over a read', () => { + const footprint = chatFootprint(state([ + tool('read', ['/home/me/project/src/a.ts', '/home/me/project/README.md']), + tool('edit', ['/home/me/project/src/a.ts']), + tool('read', ['/home/me/project/src/a.ts']), + ]), []); + assert.equal(footprintMark(footprint, 'src/a.ts'), 'edited'); + assert.equal(footprintMark(footprint, 'README.md'), 'read'); + assert.equal(footprintMark(footprint, 'src'), null); + assert.equal(footprint.chatTitle, 'Fix the parser'); + assert.equal(footprint.sessionId, 'chat-1'); + }); + + it('counts deletes, moves, diffs and pending changes as edits, and skips failed calls and other kinds', () => { + const footprint = chatFootprint(state([ + tool('delete', ['/home/me/project/old.ts']), + tool('move', ['/home/me/project/lib/b.ts']), + tool('other', [], 'completed', '/home/me/project/lib/c.ts'), + tool('edit', ['/home/me/project/failed.ts'], 'failed'), + tool('search', ['/home/me/project/found.ts']), + tool('execute', ['/home/me/project/run.sh']), + ]), ['docs/notes.md']); + assert.deepEqual([...footprint.files.entries()].sort(), [ + ['docs/notes.md', 'edited'], ['lib/b.ts', 'edited'], ['lib/c.ts', 'edited'], ['old.ts', 'edited'], + ]); + }); + + it('moves a worktree chat\'s paths onto the project', () => { + const footprint = chatFootprint(state([tool('edit', ['/data/worktrees/chat-1/app/src/a.ts'])], { + worktree: { branch: 'codexr/chat-1', path: '/data/worktrees/chat-1', cwd: '/data/worktrees/chat-1/app' } as SessionWorktree, + }), []); + assert.equal(footprintMark(footprint, 'src/a.ts'), 'edited'); + }); + + it('lists the folders above every touched file, for the filter', () => { + const footprint = chatFootprint(state([tool('read', ['/home/me/project/a/b/c.ts', '/home/me/project/a/d.ts', '/home/me/project/top.ts'])]), []); + assert.deepEqual([...footprint.folders].sort(), ['a', 'a/b']); + assert.equal(footprintKeeps(footprint, 'a', 'directory'), true); + assert.equal(footprintKeeps(footprint, 'a/b/c.ts', 'file'), true); + assert.equal(footprintKeeps(footprint, 'a/e.ts', 'file'), false); + assert.equal(footprintKeeps(footprint, 'z', 'directory'), false); + assert.equal(footprintKeeps(null, 'a', 'directory'), false); + assert.deepEqual(foldersToReveal(footprint), ['a', 'a/b']); + assert.deepEqual(foldersToReveal(null), []); + }); + + it('foldersAbove lists the parents outermost first', () => { + assert.deepEqual(foldersAbove('a/b/c.ts'), ['a', 'a/b']); + assert.deepEqual(foldersAbove('top.ts'), []); + }); + + it('changes after tool calls, pending changes and turn ends only', () => { + assert.equal(footprintMayChange('tool'), true); + assert.equal(footprintMayChange('pending-changes'), true); + assert.equal(footprintMayChange('turn-end'), true); + assert.equal(footprintMayChange('assistant-chunk'), false); + }); +}); + +describe('createChatFootprintFeed', () => { + function fakeApi(items: readonly TranscriptItem[], changed: readonly string[] = []) { + const listeners: ((message: AgentSessionMessage) => void)[] = []; + let gets = 0; + const api = { + get: async (id: string) => { + gets++; + if (id === 'gone') { + throw new Error('That chat no longer exists.'); + } + return { ...state(items), id } as AgentSessionState; + }, + changes: async (): Promise => ({ files: changed.map((path) => ({ path, status: 'modified', additions: 1, deletions: 0, binary: false })), disabledReason: null }), + onMessage: (listener: (message: AgentSessionMessage) => void) => { + listeners.push(listener); + return () => listeners.splice(listeners.indexOf(listener), 1); + }, + }; + const emit = (message: AgentSessionMessage) => listeners.forEach((listener) => listener(message)); + return { api, emit, gets: () => gets, listeners }; + } + const settle = () => new Promise((resolve) => setTimeout(resolve, 10)); + + it('follows the chat shown, and drops it when its tab closes', async () => { + const fake = fakeApi([tool('edit', ['/home/me/project/a.ts'])], ['b.ts']); + const applied: (string[] | null)[] = []; + const feed = createChatFootprintFeed(fake.api, (footprint) => applied.push(footprint ? [...footprint.files.keys()].sort() : null)); + feed.chatShown('chat-1'); + await settle(); + assert.deepEqual(applied.at(-1), ['a.ts', 'b.ts']); + feed.chatClosed('other'); + assert.deepEqual(applied.at(-1), ['a.ts', 'b.ts'], 'another chat closing changes nothing'); + feed.chatClosed('chat-1'); + assert.equal(applied.at(-1), null); + feed.dispose(); + assert.equal(fake.listeners.length, 0); + }); + + it('refreshes after the followed chat\'s tool calls only', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const fake = fakeApi([]); + const feed = createChatFootprintFeed(fake.api, () => undefined); + feed.chatShown('chat-1'); + t.mock.timers.tick(0); + const before = fake.gets(); + fake.emit({ kind: 'event', sessionId: 'chat-2', event: { type: 'pending-changes', count: 1 }, updatedAt: '' }); + fake.emit({ kind: 'event', sessionId: 'chat-1', event: { type: 'read' }, updatedAt: '' }); + t.mock.timers.tick(1000); + assert.equal(fake.gets(), before); + fake.emit({ kind: 'event', sessionId: 'chat-1', event: { type: 'pending-changes', count: 1 }, updatedAt: '' }); + fake.emit({ kind: 'event', sessionId: 'chat-1', event: { type: 'pending-changes', count: 2 }, updatedAt: '' }); + t.mock.timers.tick(1000); + assert.equal(fake.gets(), before + 1, 'a burst is one refresh'); + feed.dispose(); + }); + + it('clears the footprint when the chat no longer exists', async () => { + const fake = fakeApi([]); + const applied: unknown[] = []; + const feed = createChatFootprintFeed(fake.api, (footprint) => applied.push(footprint)); + feed.chatShown('gone'); + await settle(); + assert.equal(applied.at(-1), null); + feed.dispose(); + }); +}); + +describe('wiring and strings', () => { + it('the explorer draws the marks and the filter; the strings exist in English and Spanish', () => { + const source = readFileSync(new URL('../src/renderer/explorer.ts', import.meta.url), 'utf8'); + assert.match(source, /setChatFootprint/); + assert.match(source, /explorer-chat-filter/); + for (const key of ['explorer.chatFilter', 'explorer.chatFilterOf', 'explorer.chatFilterNoChat', 'explorer.chatFilterEmpty', 'explorer.agentEdited', 'explorer.agentRead'] as const) { + assert.ok(en[key] && es[key] && en[key] !== es[key], key); + } + }); +}); From 408fd9e622b197582b948d0f33c12b8f0b90433a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:43:01 +0000 Subject: [PATCH 29/74] feat(agent-flow): open in editor from the pinned building and function cards (#526) Pinned Agent Flow cards get an 'Open in editor' button: the building card opens the file, the function card opens it at the function's first line. Same contract as the drill-down inspector (#16): CodeXRHostBridge in the Code-XR IDE, else the open-in-editor room message from a local page, so both hosts already carry the line. Hover cards stay button-free and the button is raycastable only while it shows. --- .../agentFlowRuntime/modeLifecycle.js | 1 + .../agentFlowRuntime/sceneOverlays.js | 93 +++++++++- .../analysis/agentFlowOpenInEditor.test.cjs | 168 ++++++++++++++++++ docs/agent-flow/legends.md | 1 + 4 files changed, 259 insertions(+), 4 deletions(-) create mode 100644 apps/vscode-extension/test/analysis/agentFlowOpenInEditor.test.cjs diff --git a/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/modeLifecycle.js b/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/modeLifecycle.js index d036e9e2..6ca1a344 100644 --- a/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/modeLifecycle.js +++ b/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/modeLifecycle.js @@ -382,6 +382,7 @@ showTooltip: showTooltip, tooltipModel: tooltipModel, legendModel: legendModel, + editorTargetOf: editorTargetOf, togglePin: togglePin, layoutLegends: layoutLegends, skylineY: skylineY, diff --git a/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/sceneOverlays.js b/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/sceneOverlays.js index 461074b9..32e03492 100644 --- a/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/sceneOverlays.js +++ b/apps/vscode-extension/templates/components/codexr/agent-flow/agentFlowRuntime/sceneOverlays.js @@ -444,11 +444,90 @@ }; } - /** Both cards of a legend: { building, floor|null }. */ + /** Both cards of a legend: { building, floor|null }; a pinned one's cards carry their `editor` target. */ function legendModel(v, fileIndex, floorIndex, pinned) { var fileState = v.cityState?.files[fileIndex]; var floor = Number.isInteger(floorIndex) ? floorIndex : -1; - return { building: buildingCardModel(v, fileIndex, fileState, !!pinned), floor: floorCardModel(v, fileIndex, fileState, floor) }; + var model = { building: buildingCardModel(v, fileIndex, fileState, !!pinned), floor: floorCardModel(v, fileIndex, fileState, floor) }; + if (pinned && canOpenInEditor()) { + model.building.editor = editorTargetOf(v.files[fileIndex], -1); + if (model.floor) { model.floor.editor = editorTargetOf(v.files[fileIndex], floor); } + } + return model; + } + + // -- Open in editor (#526): the pinned cards' one action ---------------------- + // Same contract as the drill-down inspector and the dependency graph (#16): + // the Code-XR IDE embeds the scene beside its editor and exposes + // CodeXRHostBridge; anywhere else a page on this machine asks the analysis + // server over the room, which opens the file in VS Code or the IDE. A guest + // through a tunnel or the LAN, or an offline export, gets no button (the + // server would refuse it anyway). Paths are relative to the analysed root. + + function canOpenInEditor() { + if (typeof root.CodeXRHostBridge?.openInEditor === 'function') { return true; } + var host = String(root.location?.hostname || ''); + var local = host === 'localhost' || host === '[::1]' || host === '::1' || /^127(?:\.\d{1,3}){3}$/.test(host); + var connection = client(); + return local && typeof connection?.sendMessage === 'function' && !connection.isOfflineExport?.(); + } + + function openInEditor(request) { + var hostBridge = root.CodeXRHostBridge; + if (typeof hostBridge?.openInEditor === 'function') { hostBridge.openInEditor(request); return; } + client()?.sendMessage?.('open-in-editor', request); + } + + /** + * What a card opens: the file, at the function's first line for a floor + * card. Null for a file the session deleted (nothing left to open); a + * function it removed opens its file without a line, its span is gone. + */ + function editorTargetOf(file, floorIndex) { + if (!file?.path || file.deleted) { return null; } + var floor = floorIndex >= 0 ? file.floors?.[floorIndex] : null; + return floor && floor.diedStep < 0 && floor.lineStart > 0 ? { path: file.path, line: floor.lineStart } : { path: file.path }; + } + + // Same look as the drill-down inspector's "Open in editor" (COLORS.editor there). + var EDITOR_BUTTON = { width: 1.3, height: 0.24, footer: 0.3, color: '#0f766e' }; + + /** The card's button, made on first use; clickable (raycaster class) only while it shows. */ + function syncEditorButton(card, target) { + if (!target && !card.editorButton) { return; } + if (!card.editorButton) { + var el = entity('a-plane', { + visible: 'false', width: EDITOR_BUTTON.width, height: EDITOR_BUTTON.height, + material: 'color: ' + EDITOR_BUTTON.color + '; opacity: 0.97; shader: flat', + 'data-codexr-interactive': 'true' + }); + el.appendChild(text('Open in editor', '0 0 0.01', 1.5, '#ffffff', 'center', 22)); + el.addEventListener('click', function (event) { + event?.stopPropagation?.(); + if (card.editorButton.target) { openInEditor(card.editorButton.target); } + }); + card.root.appendChild(el); + card.editorButton = { el: el, target: null }; + } + var button = card.editorButton; + button.target = target || null; + if (target) { + // On the card's own (dynamic) bottom edge, in the footer it reserved. + button.el.setAttribute('position', '0 ' + (-(card.height / 2) + 0.17).toFixed(3) + ' 0.02'); + button.el.setAttribute('class', RAYCAST_CLASS + ' codexr-agent-flow-button'); + button.el.setAttribute('data-codexr-role', 'agent-flow legend open-in-editor'); + } else { + button.el.removeAttribute('class'); + } + setNodeVisible(button.el, !!target); + } + + function withFooter(options, target) { + if (!target) { return options; } + var copy = {}; + Object.keys(options).forEach(function (key) { copy[key] = options[key]; }); + copy.footerReserve = EDITOR_BUTTON.footer; + return copy; } /** Kept for the harness: the floor card when a floor is pointed, else the building card. */ @@ -468,12 +547,14 @@ */ function fillLegend(legend, model) { var common = root.CodeXRCommonRuntime; - common.updateTooltip(legend.building, model.building, null, CARD_OPTIONS); + common.updateTooltip(legend.building, model.building, null, withFooter(CARD_OPTIONS, model.building.editor)); + syncEditorButton(legend.building, model.building.editor); var buildingHeight = legend.building.height; var height = buildingHeight; var width = LEGEND.width; if (model.floor) { - common.updateTooltip(legend.floor, model.floor, null, FLOOR_CARD_OPTIONS); + common.updateTooltip(legend.floor, model.floor, null, withFooter(FLOOR_CARD_OPTIONS, model.floor.editor)); + syncEditorButton(legend.floor, model.floor.editor); var floorHeight = legend.floor.height; var offset = (LEGEND.width + LEGEND.stackGap / LEGEND.scale) / 2; legend.building.root.setAttribute('position', (-offset) + ' ' + (buildingHeight / 2) + ' 0'); @@ -484,6 +565,7 @@ } else { legend.building.root.setAttribute('position', '0 ' + (buildingHeight / 2) + ' 0'); common.hideTooltip(legend.floor); + syncEditorButton(legend.floor, null); legend.color = model.building.accentColor; } legend.height = height * LEGEND.scale; @@ -508,6 +590,9 @@ if (!legend.station && (fileIndex < 0 || !v.files[fileIndex])) { legend.file = -1; legend.floorIndex = -1; + // A hidden card's buttons must not catch the pointer either. + syncEditorButton(legend.building, null); + syncEditorButton(legend.floor, null); setNodeVisible(legend.wrap, false); setLeader(legend.leader, null); return; diff --git a/apps/vscode-extension/test/analysis/agentFlowOpenInEditor.test.cjs b/apps/vscode-extension/test/analysis/agentFlowOpenInEditor.test.cjs new file mode 100644 index 00000000..393bb451 --- /dev/null +++ b/apps/vscode-extension/test/analysis/agentFlowOpenInEditor.test.cjs @@ -0,0 +1,168 @@ +// #526: "Open in editor" on Agent Flow's pinned building and function cards, +// through the same bridge-or-room contract as the drill-down inspector (#16). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const vm = require('node:vm'); + +const projectRoot = path.resolve(__dirname, '..', '..'); +const { readAssembledRuntime } = require(path.join(projectRoot, 'test', 'helpers', 'runtimeAssembly.cjs')); +const runtimeSource = readAssembledRuntime('agent-flow', 'agentFlowRuntime.js'); + +/** Just enough of an element for the legends: attributes, children, click listeners. */ +class FakeElement { + constructor(tag) { + this.tagName = tag; + this.nodeType = 1; + this.attributes = {}; + this.children = []; + this.parentNode = null; + this.listeners = {}; + } + setAttribute(name, value) { this.attributes[name] = value; } + getAttribute(name) { return this.attributes[name]; } + removeAttribute(name) { delete this.attributes[name]; } + appendChild(child) { child.parentNode = this; this.children.push(child); return child; } + removeChild(child) { this.children = this.children.filter((other) => other !== child); child.parentNode = null; } + addEventListener(type, listener) { (this.listeners[type] = this.listeners[type] || []).push(listener); } + removeEventListener() {} + click() { + let stopped = false; + const event = { stopPropagation() { stopped = true; } }; + (this.listeners.click || []).forEach((listener) => listener(event)); + return stopped; + } + all() { return this.children.reduce((list, child) => list.concat([child], child.all()), []); } +} + +function fakeTooltip(options) { + const root = new FakeElement('a-entity'); + return { root, width: options.width, height: 0.6, updates: [] }; +} + +/** The runtime with a host bridge (IDE) or a local room client (VS Code / IDE browser path). */ +function load({ bridge = false, hostname = '127.0.0.1', offline = false } = {}) { + const opened = []; + const sent = []; + const connection = { + sendMessage(type, payload) { sent.push(JSON.parse(JSON.stringify({ type, payload }))); return true; }, + onMessage() { return () => {}; }, + registerEntityRuntime() {}, + getSessionInfoAsync: async () => ({ capabilities: {} }), + isOfflineExport: () => offline, + }; + const sandbox = { + console, Date, Math, JSON, + setTimeout() { return 1; }, + clearTimeout() {}, + location: { hostname }, + document: { + readyState: 'loading', + addEventListener() {}, + createElement: (tag) => new FakeElement(tag), + getElementById() { return null; }, + querySelector() { return null; }, + querySelectorAll() { return []; }, + }, + CodeXRCollaborationRuntime: { getClient: () => connection }, + CodeXRCommonRuntime: { + createTooltip: fakeTooltip, + updateTooltip(tooltip, model, position, options) { + tooltip.height = 1 + (options.footerReserve || 0); + tooltip.updates.push({ model, footerReserve: options.footerReserve || 0 }); + return true; + }, + hideTooltip() {}, + }, + }; + if (bridge) { + sandbox.CodeXRHostBridge = { openInEditor(target) { opened.push(JSON.parse(JSON.stringify(target))); } }; + } + sandbox.window = sandbox; + vm.runInNewContext(runtimeSource, sandbox, { filename: 'agentFlowRuntime.js' }); + return { api: sandbox.CodeXRAgentFlowRuntime.__testing, opened, sent }; +} + +function view() { + const file = (name, extra) => ({ + path: 'src/' + name, name, dir: 'src', loc: 40, floors: [], turns: [], touches: { reads: 0, writes: 0, searches: 0 }, dependents: 0, h: 1, ...extra, + }); + return { + rootEl: new FakeElement('a-entity'), + files: [ + file('a.py', { floors: [ + { name: 'parse', lineStart: 12, lineEnd: 30, bornStep: -1, diedStep: -1 }, + { name: 'gone', lineStart: 40, lineEnd: 44, bornStep: -1, diedStep: 3 }, + ] }), + file('b.py', { deleted: true }), + ], + outside: [false, false], + dataset: { rootName: 'proj' }, + cityState: null, + city: { + getBuildingTop: () => ({ x: 0, y: 1, z: 0 }), + getFloorRects: () => [{ floor: 0, y0: 0, y1: 0.5 }, { floor: 1, y0: 0.5, y1: 1 }], + }, + hoverFile: -1, hoverFloor: -1, hoverStation: null, + }; +} + +const editorButtons = (v) => v.rootEl.all().filter((el) => el.attributes['data-codexr-role'] === 'agent-flow legend open-in-editor'); +const clickable = (el) => /babiaxraycasterclass/.test(el.attributes.class || '') && el.attributes.visible === 'true'; + +test('editor targets: the file, at the function\'s first line for a floor card', () => { + const { api } = load(); + const v = view(); + assert.deepEqual(JSON.parse(JSON.stringify(api.editorTargetOf(v.files[0], -1))), { path: 'src/a.py' }); + assert.deepEqual(JSON.parse(JSON.stringify(api.editorTargetOf(v.files[0], 0))), { path: 'src/a.py', line: 12 }); + assert.deepEqual(JSON.parse(JSON.stringify(api.editorTargetOf(v.files[0], 1))), { path: 'src/a.py' }, 'a removed function has no span left'); + assert.equal(api.editorTargetOf(v.files[1], -1), null, 'a deleted file has nothing to open'); +}); + +test('a pinned function card opens its line through CodeXRHostBridge (IDE)', () => { + const { api, opened, sent } = load({ bridge: true, hostname: 'tauri.localhost' }); + const v = view(); + api.togglePin(v, 0, 0); + const buttons = editorButtons(v); + assert.equal(buttons.length, 2, 'one on the building card, one on the function card'); + assert.ok(buttons.every(clickable), 'both carry the raycaster class (XR laser and 2D cursor)'); + const [building, floor] = buttons; + assert.equal(v.legends.pinned.building.updates.at(-1).footerReserve, 0.3, 'the card reserves the footer the button sits in'); + assert.equal(floor.click(), true, 'the click does not fall through to the city'); + building.click(); + assert.deepEqual(opened, [{ path: 'src/a.py', line: 12 }, { path: 'src/a.py' }]); + assert.deepEqual(sent, []); +}); + +test('without the bridge, a page on this machine asks the analysis server (VS Code)', () => { + const { api, sent } = load(); + const v = view(); + api.togglePin(v, 0, 0); + editorButtons(v)[1].click(); + assert.deepEqual(sent, [{ type: 'open-in-editor', payload: { path: 'src/a.py', line: 12 } }]); +}); + +test('no button for a guest, an offline export, a hover card or a deleted file', () => { + for (const options of [{ hostname: '192.168.1.20' }, { offline: true }]) { + const { api } = load(options); + const v = view(); + api.togglePin(v, 0, 0); + assert.equal(editorButtons(v).length, 0, JSON.stringify(options)); + } + const { api } = load({ bridge: true }); + const v = view(); + api.showTooltip(v, 0, 0); + assert.equal(editorButtons(v).length, 0, 'hover previews never carry buttons'); + api.togglePin(v, 1, -1); + assert.equal(editorButtons(v).length, 0, 'a deleted file'); +}); + +test('unpinning leaves no clickable button behind', () => { + const { api } = load({ bridge: true }); + const v = view(); + api.togglePin(v, 0, 0); + api.togglePin(v, 0, 0); + const buttons = editorButtons(v); + assert.equal(buttons.length, 2); + assert.ok(buttons.every((el) => !clickable(el)), 'hidden and out of the raycaster'); +}); diff --git a/docs/agent-flow/legends.md b/docs/agent-flow/legends.md index 452803a2..26700d1a 100644 --- a/docs/agent-flow/legends.md +++ b/docs/agent-flow/legends.md @@ -30,6 +30,7 @@ A leader line with a marker drops from the card's bottom edge to the pointed flo - Hover elsewhere while pinned: a second, transient card; none over the pinned building itself. - Click on the pinned building: unpins. Click on another building: the pin moves. - The pin refreshes its values on every render (step, seek, toggle) and is dropped with the view (new session, mode change). +- Open in editor (#526): each pinned card (building and, with a floor pinned, function) carries an "Open in editor" button in a footer it reserves; the building opens the file, the function opens it at `lineStart` (a function the session removed opens the file without a line, a deleted file gets no button). Same contract as the drill-down inspector (#16): `CodeXRHostBridge.openInEditor({ path, line })` in the Code-XR IDE, else the room message `open-in-editor` to the analysis server, only from a page on this machine and never in an offline export. Paths are relative to the analysed root, which both hosts resolve and check. Hover cards have no button; only the button carries the raycaster class, and only while it shows. Unit test: `test/analysis/agentFlowOpenInEditor.test.cjs`. ## History, not the end state From 57f40077dee6add78fde6851e3732250c59aaa4e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:43:23 +0000 Subject: [PATCH 30/74] test(ide): read sources with LF line endings so the start-up tests pass on Windows (#518, #519) --- apps/ide/test/benchWait.test.ts | 4 ++-- apps/ide/test/monacoContributions.test.ts | 4 ++-- apps/ide/test/startupLazyChunks.test.ts | 2 +- apps/ide/test/startupWork.test.ts | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/ide/test/benchWait.test.ts b/apps/ide/test/benchWait.test.ts index 9c6a09e5..b5a898ce 100644 --- a/apps/ide/test/benchWait.test.ts +++ b/apps/ide/test/benchWait.test.ts @@ -83,10 +83,10 @@ describe('Benchmark wait (#517)', () => { }); it('is what the bench driver waits with, and reports the first line Monaco drew', () => { - const driver = fs.readFileSync(path.join(IDE_ROOT, 'src/renderer/bench/benchDriver.ts'), 'utf8'); + const driver = fs.readFileSync(path.join(IDE_ROOT, 'src/renderer/bench/benchDriver.ts'), 'utf8').replace(/\r\n/g, '\n'); assert.doesNotMatch(driver, /setTimeout\(poll/); assert.match(driver, /waitFor\(ready, STEP_TIMEOUT_MS, browserWaitHost\(\)\)/); assert.match(driver, /editorFirstViewLineMs = startupMarkTime\('editor-first-view-line'\)/); - assert.match(fs.readFileSync(path.join(IDE_ROOT, 'src-tauri/src/host.rs'), 'utf8'), /spec\.label == MAIN_WINDOW \{\s*builder = builder\.background_throttling\(tauri::utils::config::BackgroundThrottlingPolicy::Disabled\)/); + assert.match(fs.readFileSync(path.join(IDE_ROOT, 'src-tauri/src/host.rs'), 'utf8').replace(/\r\n/g, '\n'), /spec\.label == MAIN_WINDOW \{\s*builder = builder\.background_throttling\(tauri::utils::config::BackgroundThrottlingPolicy::Disabled\)/); }); }); diff --git a/apps/ide/test/monacoContributions.test.ts b/apps/ide/test/monacoContributions.test.ts index de5dffc7..05b7a86d 100644 --- a/apps/ide/test/monacoContributions.test.ts +++ b/apps/ide/test/monacoContributions.test.ts @@ -26,7 +26,7 @@ describe('Unused Monaco contributions (#518)', () => { for (const host of ['index.js', path.join('internal', 'common', 'workers.js')]) { it(`drops every listed contribution from the installed ${host} and keeps the rest`, () => { - const code = fs.readFileSync(path.join(MONACO_VS, host), 'utf8'); + const code = fs.readFileSync(path.join(MONACO_VS, host), 'utf8').replace(/\r\n/g, '\n'); const stripped = strip(code, host); for (const contribution of contributions) { assert.ok(code.includes(contribution), `${host} imports ${contribution}`); @@ -47,7 +47,7 @@ describe('Unused Monaco contributions (#518)', () => { it('drops nothing the IDE uses: no inline completion provider and no option turning a dropped one on', () => { for (const file of [...sources('src/renderer'), ...sources('src/extensionHost')]) { - const code = fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); + const code = fs.readFileSync(path.join(IDE_ROOT, file), 'utf8').replace(/\r\n/g, '\n'); assert.doesNotMatch(code, /registerInlineCompletion|inlineSuggest\s*:|experimentalGpuAcceleration|mouseMiddleClickAction|showMarkSectionHeaders|showRegionSectionHeaders/, file); } }); diff --git a/apps/ide/test/startupLazyChunks.test.ts b/apps/ide/test/startupLazyChunks.test.ts index 8fdf6093..8468eede 100644 --- a/apps/ide/test/startupLazyChunks.test.ts +++ b/apps/ide/test/startupLazyChunks.test.ts @@ -9,7 +9,7 @@ import { needsEditorLanguages } from '../src/renderer/extensions/languageModel.t import { lazyGuidedTour, type LazyTour } from '../src/renderer/tour/lazyTour.ts'; const IDE_ROOT = path.resolve(import.meta.dirname, '..'); -const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); +const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8').replace(/\r\n/g, '\n'); const staticImports = (file: string): string[] => [...read(file).matchAll(/^import (?!type)[^;]* from '([^']+)';$/gm)].map((match) => match[1] ?? ''); const summary = { themes: [], iconThemes: [], languages: [] as string[], grammars: 0, snippets: 0, commands: [], views: [], settings: 0, keybindings: 0, localizations: [] }; diff --git a/apps/ide/test/startupWork.test.ts b/apps/ide/test/startupWork.test.ts index 73e14577..aa28d25a 100644 --- a/apps/ide/test/startupWork.test.ts +++ b/apps/ide/test/startupWork.test.ts @@ -11,7 +11,7 @@ import { SHARED_READS } from '../src/bridge/codexrApi.ts'; import { IPC_CHANNELS, IPC_EVENTS } from '../src/shared/api.ts'; const IDE_ROOT = path.resolve(import.meta.dirname, '..'); -const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8'); +const read = (file: string): string => fs.readFileSync(path.join(IDE_ROOT, file), 'utf8').replace(/\r\n/g, '\n'); function folders(tree: Record): { list: (path: string) => Promise; asked: string[] } { const asked: string[] = []; From 3137a1e50bc962c5823cce9186a0cd3daaee375d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:46:35 +0000 Subject: [PATCH 31/74] feat(ide): per-function turn delta, turn lens and regression chip (#520, #527) O18 (#520): before each prompt the runtime keeps the window's measured functions; after the turn the changed files are re-measured at once (bounded, 20 s) and diffed in the core (core/metrics/functionMetricsDelta) into changed/new/removed functions. TurnMetricDeltaView gains functions[], listed under the turn even without a scene. metricLensTitle takes an optional baseline: the lens shows "CCN 13 (+4 this turn)" until the file is kept, undone or restored. O25 (#527): a pure regression rule in the core flags functions the turn pushed over a Problems limit; the turn shows a warning chip whose "Ask to simplify" drafts (never sends) the core's regressionPrompt in that chat. Strings in en and es. --- .../agentSessions/agentSessionsRuntime.ts | 75 +++++- .../main/agentSessions/turnFunctionDelta.ts | 61 +++++ apps/ide/src/main/analysis/metricDelta.ts | 17 ++ apps/ide/src/main/boot.ts | 2 +- .../main/problems/functionMetricsService.ts | 63 ++++- .../src/renderer/agentFirst/agentFirst.css | 4 + .../src/renderer/agentFirst/agentWorkbench.ts | 4 + .../src/renderer/agentFirst/changesModel.ts | 58 ++++- apps/ide/src/renderer/agentFirst/chatView.ts | 15 +- .../src/renderer/agentFirst/regressionChip.ts | 28 ++ apps/ide/src/renderer/editor/editorGroup.ts | 10 +- apps/ide/src/renderer/editor/metricLens.ts | 16 +- apps/ide/src/renderer/main.ts | 6 +- apps/ide/src/shared/agentSession.ts | 9 + apps/ide/src/shared/i18n/messages.en.ts | 11 + apps/ide/src/shared/i18n/messages.es.ts | 11 + apps/ide/src/shared/problems.ts | 1 + apps/ide/test/functionMetricsDelta.test.ts | 203 +++++++++++++++ .../core/agent-prompts/regressionPrompt.ts | 51 ++++ .../src/core/metrics/functionMetrics.ts | 37 ++- .../src/core/metrics/functionMetricsDelta.ts | 246 ++++++++++++++++++ .../core/metrics/functionMetricsTracker.ts | 43 +++ .../analysis/functionMetricsDelta.test.cjs | 31 +++ 23 files changed, 966 insertions(+), 36 deletions(-) create mode 100644 apps/ide/src/main/agentSessions/turnFunctionDelta.ts create mode 100644 apps/ide/src/renderer/agentFirst/regressionChip.ts create mode 100644 apps/ide/test/functionMetricsDelta.test.ts create mode 100644 apps/vscode-extension/src/core/agent-prompts/regressionPrompt.ts create mode 100644 apps/vscode-extension/src/core/metrics/functionMetricsDelta.ts create mode 100644 apps/vscode-extension/test/analysis/functionMetricsDelta.test.cjs diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 0b9631a7..a10f0b0f 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -20,7 +20,10 @@ import { SessionStore } from './sessionStore.ts'; import { AgentFlowFeed } from './agentFlowFeed.ts'; import { codexrMcpServerSpec } from './codexrMcpSpec.ts'; import { SessionChanges } from '../checkpoints/sessionChanges.ts'; -import { toTurnMetricDeltaView } from '../analysis/metricDelta.ts'; +import { toTurnMetricDeltaView, withFunctionDeltas } from '../analysis/metricDelta.ts'; +import { measureTurnFunctions } from './turnFunctionDelta.ts'; +import type { FunctionMetricsService } from '../problems/functionMetricsService.ts'; +import type { FunctionMetricsSnapshot } from '@codexr/core/metrics/functionMetrics'; import type { AnalysisService } from '../analysis/analysisService.ts'; import type { FileMetrics } from '../agents/tools/analysisQueries.ts'; @@ -85,6 +88,8 @@ export interface AgentSessionsRuntimeOptions { readonly analysisOutput?: (contents: WebContents) => string | null; /** AF9: the window's live analysis, measured before and after each turn. */ readonly analysis?: Pick; + /** #520: the window's per-function metrics, snapshotted before each turn and re-measured after it. */ + readonly functionMetrics?: Pick; /** #456: reads and stores the user's `agents.claude.remoteControl` setting. Absent (the smoke run), chats never start with it. */ readonly claudeRemoteControlSetting?: { get(): Promise; @@ -94,6 +99,8 @@ export interface AgentSessionsRuntimeOptions { /** How long the metric delta waits for the scene to catch up with a turn's edits. */ const METRIC_DELTA_TIMEOUT_MS = 30_000; +/** #520: how long re-measuring a turn's files may take before its function delta is given up. */ +const FUNCTION_DELTA_TIMEOUT_MS = 20_000; export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentSessionsRuntime { const userData = options.isSmoke ? path.join(os.tmpdir(), `codexr-ide-smoke-agent-sessions-${process.pid}`) : app.getPath('userData'); @@ -143,30 +150,73 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS return contents && !contents.isDestroyed() ? contents : null; }; + /** The window that has `root` open (the chat's owner for the analysis). */ + const windowOf = (root: string): WebContents | null => + webContents.getAllWebContents().find((contents) => !contents.isDestroyed() && currentWorkspaceInfo(contents)?.root === root) ?? null; + /** #520: kept or undone files stop showing the last turn's delta in their lenses. */ + const reviewed = (root: string, paths: readonly string[] | 'all'): void => { + const owner = windowOf(root); + if (owner) { + options.functionMetrics?.turnReviewed(owner, root, paths); + } + }; // AF5/AF6: snapshots in shadow repositories outside every project, review bases per chat. - const changes = new SessionChanges({ + const changes = new (class extends SessionChanges { + override async keep(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise { + await super.keep(sessionId, root, paths); + reviewed(root, paths); + } + override async undo(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise { + const written = await super.undo(sessionId, root, paths); + reviewed(root, written); + return written; + } + override async restoreCheckpoint(root: string, checkpointId: string): Promise { + const written = await super.restoreCheckpoint(root, checkpointId); + reviewed(root, written); + return written; + } + })({ storageDir: path.join(userData, 'checkpoints'), bases: new JsonKeyValueStore(path.join(dir, 'review.json')), }); - /** The window that has `root` open (the chat's owner for the analysis). */ - const windowOf = (root: string): WebContents | null => - webContents.getAllWebContents().find((contents) => !contents.isDestroyed() && currentWorkspaceInfo(contents)?.root === root) ?? null; - /** AF9: per chat, the scene's metrics and the checkpoint taken when its running turn started. */ - const turnStarts = new Map(); + /** AF9: per chat, the scene's metrics, the function metrics (#520) and the checkpoint taken when its running turn started. */ + const turnStarts = new Map(); const measureTurn = async (sessionId: string, root: string, turnId: string): Promise => { const start = turnStarts.get(sessionId); turnStarts.delete(sessionId); const owner = windowOf(root); - if (!start?.metrics || !start.checkpointId || !owner || !options.analysis) { + if (!start?.checkpointId || !owner || (!start.metrics && !start.functions)) { return; } const changed = await changes.changedSince(root, start.checkpointId); if (changed.length === 0) { return; } - const { report } = await options.analysis.turnMetricDelta(owner, start.metrics, changed, { timeoutMs: METRIC_DELTA_TIMEOUT_MS }); - const view = toTurnMetricDeltaView(report); + const metrics = start.metrics; + const scene = metrics && options.analysis + ? options.analysis.turnMetricDelta(owner, metrics, changed, { timeoutMs: METRIC_DELTA_TIMEOUT_MS }).then(({ report }) => toTurnMetricDeltaView(report)) + : Promise.resolve(null); + const functionMetrics = options.functionMetrics; + const functions = functionMetrics + ? measureTurnFunctions({ + baseline: start.functions, + root, + changed, + remeasure: (files, signal) => functionMetrics.remeasure(owner, root, files, signal), + exists: (file) => fs.promises.stat(file).then((stat) => stat.isFile(), () => false), + timeoutMs: FUNCTION_DELTA_TIMEOUT_MS, + }).catch((error: unknown) => { + log.warn(`[agent] Could not measure the functions of the turn: ${String(error)}`); + return null; + }) + : Promise.resolve(null); + const [sceneView, deltas] = await Promise.all([scene, functions]); + if (deltas && !owner.isDestroyed()) { + functionMetrics?.setTurnDeltas(owner, root, deltas); + } + const view = withFunctionDeltas(sceneView, deltas); if (view) { service.attachMetricDelta(sessionId, turnId, view); } @@ -179,9 +229,10 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS agentFlow, beforePrompt: async (sessionId, root) => { const checkpoint = await changes.beforePrompt(sessionId, root); - const owner = options.analysis ? windowOf(root) : null; + const owner = options.analysis || options.functionMetrics ? windowOf(root) : null; const metrics = owner && options.analysis ? await options.analysis.sceneMetrics(owner).catch(() => null) : null; - turnStarts.set(sessionId, { metrics, checkpointId: checkpoint?.checkpointId ?? null }); + const functions = owner ? (options.functionMetrics?.measured(owner) ?? null) : null; + turnStarts.set(sessionId, { metrics, functions, checkpointId: checkpoint?.checkpointId ?? null }); return checkpoint; }, afterTurn: async (sessionId, root, turnId) => { diff --git a/apps/ide/src/main/agentSessions/turnFunctionDelta.ts b/apps/ide/src/main/agentSessions/turnFunctionDelta.ts new file mode 100644 index 00000000..b60aeaa0 --- /dev/null +++ b/apps/ide/src/main/agentSessions/turnFunctionDelta.ts @@ -0,0 +1,61 @@ +import path from 'node:path'; +import type { FunctionMetricsSnapshot } from '@codexr/core/metrics/functionMetrics'; +import { diffFunctionMetrics, type FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; + +/** + * #520 (O18): the per-function delta of one agent turn. Before the prompt the + * runtime keeps the window's measured functions (FunctionMetricsService); once + * the turn ends, the files it changed are re-measured right away (the + * tracker's own re-measure on a change on disk is debounced, and skips files + * it never knew, such as the ones the turn created) and the two sides are + * diffed in the core. No scene is needed: only metrics of the folder, which + * the window keeps after its scene closes. + */ + +export interface TurnFile { + readonly relativePath: string; + readonly absolutePath: string; + readonly deleted?: boolean; +} + +export interface TurnFunctionDeltaInput { + /** The window's metrics before the turn (null: nothing to compare with). */ + readonly baseline: FunctionMetricsSnapshot | null; + readonly root: string; + /** Paths the turn changed, relative to `root`. */ + readonly changed: readonly string[]; + /** Re-measures the files and resolves with the window's metrics after them (null: could not). */ + remeasure(files: readonly TurnFile[], signal: AbortSignal): Promise; + exists(absolutePath: string): Promise; + /** How long the re-measure may take before the delta is given up. */ + readonly timeoutMs: number; + /** At most this many files are re-measured (a turn that rewrote the project is summarised by the analysis). */ + readonly maxFiles?: number; +} + +/** The turn's function deltas, worst first; null when there was no baseline of this folder or the re-measure failed or timed out. */ +export async function measureTurnFunctions(input: TurnFunctionDeltaInput): Promise { + const { baseline, root } = input; + if (!baseline || baseline.root !== root) { + return null; + } + const relative = [...new Set(input.changed.map((file) => file.replace(/\\/g, '/')).filter(Boolean))].sort().slice(0, input.maxFiles ?? 40); + if (relative.length === 0) { + return []; + } + const files = await Promise.all(relative.map(async (relativePath): Promise => { + const absolutePath = path.join(root, ...relativePath.split('/')); + return (await input.exists(absolutePath)) ? { relativePath, absolutePath } : { relativePath, absolutePath, deleted: true }; + })); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), input.timeoutMs); + try { + const after = await input.remeasure(files, controller.signal); + if (!after || after.root !== root) { + return null; + } + return diffFunctionMetrics(baseline.files, after.files, relative); + } finally { + clearTimeout(timer); + } +} diff --git a/apps/ide/src/main/analysis/metricDelta.ts b/apps/ide/src/main/analysis/metricDelta.ts index 24b08e05..9b0bd19f 100644 --- a/apps/ide/src/main/analysis/metricDelta.ts +++ b/apps/ide/src/main/analysis/metricDelta.ts @@ -2,6 +2,7 @@ import type { MetricChangeView, MetricDeltaFreshness, TurnMetricDeltaView } from export type { MetricDeltaFreshness } from '../../shared/agentSession.ts'; import { normalize, type FileMetrics } from '../agents/tools/analysisQueries.ts'; +import { functionDeltaSummary, type FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; /** * What one agent turn did to the project's measurements (AF9, #274): the @@ -310,3 +311,19 @@ export function toTurnMetricDeltaView(report: MetricDeltaReport, maxFiles = 30): })); return { summary: report.summary, totals, files, moreFiles: moved.length - files.length }; } + +/** + * #520 (O18): adds a turn's function deltas to its view (at most `max`, worst + * first). A turn the scene did not measure (no scene, or nothing moved in it) + * still gets a view when a function moved, its summary then about functions. + */ +export function withFunctionDeltas(view: TurnMetricDeltaView | null, deltas: readonly FunctionDelta[] | null, max = 20): TurnMetricDeltaView | null { + if (!deltas || deltas.length === 0) { + return view; + } + const functions = deltas.slice(0, max); + const extra = { functions, moreFunctions: deltas.length - functions.length }; + return view + ? { ...view, ...extra } + : { summary: functionDeltaSummary(deltas), totals: [], files: [], moreFiles: 0, ...extra }; +} diff --git a/apps/ide/src/main/boot.ts b/apps/ide/src/main/boot.ts index 0dafcd9e..fb5b44c2 100644 --- a/apps/ide/src/main/boot.ts +++ b/apps/ide/src/main/boot.ts @@ -127,7 +127,7 @@ export async function startServices(options: BootOptions): Promise core.analysis.outputDirectory(contents), analysis: core.analysis, + agentSessions = startAgentSessions({ isSmoke, terminal: terminalHost, profiles: agentServices.profiles, analysisOutput: (contents) => core.analysis.outputDirectory(contents), analysis: core.analysis, functionMetrics: core.metrics, // #456: Claude Code chats on claude.ai, from the user's settings (the smoke run never asks). ...(isSmoke ? {} : { claudeRemoteControlSetting: { diff --git a/apps/ide/src/main/problems/functionMetricsService.ts b/apps/ide/src/main/problems/functionMetricsService.ts index 79bca55e..771021aa 100644 --- a/apps/ide/src/main/problems/functionMetricsService.ts +++ b/apps/ide/src/main/problems/functionMetricsService.ts @@ -1,6 +1,7 @@ import type { WebContents } from '../host/desktop.ts'; import { FunctionMetricsTracker } from '@codexr/core/metrics/functionMetricsTracker'; import { parseFunctionMetrics, type FileFunctionMetrics, type FunctionMetricsSnapshot } from '@codexr/core/metrics/functionMetrics'; +import type { FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; import { IPC_EVENTS } from '../../shared/api.ts'; import { channelLog } from '../log.ts'; import type { PythonEnvironmentService } from '../python/pythonEnvironment.ts'; @@ -18,15 +19,72 @@ const log = channelLog('core'); export class FunctionMetricsService { private readonly python: PythonEnvironmentService; private readonly windows = new Map(); + /** #520: per window, the functions its last agent turn changed (lenses quote them until kept or undone). */ + private readonly turns = new Map(); constructor(python: PythonEnvironmentService) { this.python = python; } + /** The window's metrics, with the last turn's function deltas (#520) when they are about the same folder. */ snapshot(contents: WebContents): FunctionMetricsSnapshot | null { + return this.withTurn(contents, this.windows.get(contents.id)?.snapshot ?? null); + } + + /** #520: the window's metrics as measured, without the turn deltas (the baseline of an agent turn). */ + measured(contents: WebContents): FunctionMetricsSnapshot | null { return this.windows.get(contents.id)?.snapshot ?? null; } + /** + * #520: re-measures the files an agent turn changed, now, and resolves + * with the window's metrics after them; null when the window has no + * metrics of `root` or `signal` aborted first. + */ + remeasure(contents: WebContents, root: string, files: readonly { readonly relativePath: string; readonly absolutePath: string; readonly deleted?: boolean }[], signal?: AbortSignal): Promise { + const tracker = this.windows.get(contents.id); + return tracker ? tracker.remeasure(root, files, signal) : Promise.resolve(null); + } + + /** #520: the functions the window's last agent turn changed in `root` (replacing the previous turn's). */ + setTurnDeltas(contents: WebContents, root: string, deltas: readonly FunctionDelta[]): void { + if (deltas.length === 0 && !this.turns.has(contents.id)) { + return; + } + if (deltas.length === 0) { + this.turns.delete(contents.id); + } else { + this.turns.set(contents.id, { root, deltas }); + } + this.resend(contents); + } + + /** #520: the person kept or undid files (or all of them) of `root`: their lenses stop quoting the turn. */ + turnReviewed(contents: WebContents, root: string, paths: readonly string[] | 'all'): void { + const turn = this.turns.get(contents.id); + if (!turn || turn.root !== root) { + return; + } + const reviewed = paths === 'all' ? null : new Set(paths.map((path) => path.replace(/\\/g, '/'))); + const deltas = reviewed ? turn.deltas.filter((delta) => !reviewed.has(delta.path)) : []; + if (deltas.length === turn.deltas.length) { + return; + } + this.setTurnDeltas(contents, root, deltas); + } + + private withTurn(contents: WebContents, snapshot: FunctionMetricsSnapshot | null): FunctionMetricsSnapshot | null { + const turn = this.turns.get(contents.id); + return snapshot && turn && turn.root === snapshot.root ? { ...snapshot, turnDeltas: turn.deltas } : snapshot; + } + + private resend(contents: WebContents): void { + const snapshot = this.snapshot(contents); + if (snapshot && !contents.isDestroyed()) { + contents.send(IPC_EVENTS.metricsChanged, snapshot); + } + } + /** An analysis of `root` opened its scene in this window: measure every function under it. */ analyse(contents: WebContents, root: string): void { this.trackerOf(contents).analyse(root); @@ -66,6 +124,9 @@ export class FunctionMetricsService { /** The window's folder changed (or the window went): its metrics describe nothing any more. */ folderChanged(contents: WebContents, root: string | null): void { const tracker = this.windows.get(contents.id); + if (this.turns.get(contents.id)?.root !== root) { + this.turns.delete(contents.id); + } if (!tracker || tracker.snapshot?.root === root) { return; } @@ -85,7 +146,7 @@ export class FunctionMetricsService { { onChange: (snapshot) => { if (!contents.isDestroyed()) { - contents.send(IPC_EVENTS.metricsChanged, snapshot); + contents.send(IPC_EVENTS.metricsChanged, this.withTurn(contents, snapshot)); } }, onLog: (level, message) => log[level](message), diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 0b14828f..cb658f65 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -317,6 +317,10 @@ .af-metric-delta-label { font-weight: 600; color: var(--fg); } .af-metric-delta p { margin: 4px 0; } .af-metric-delta-files { margin: 0; padding-left: 18px; font-family: var(--font-mono); font-size: var(--fs-xs); } +.af-metric-delta-functions { margin-bottom: 4px; } +/* #527: a turn that pushed functions over a Problems limit. */ +.af-regression-chip { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 6px; align-self: flex-start; padding: 2px 8px; border: 1px solid var(--warn); border-radius: var(--radius-pill); font-size: var(--fs-xs); } +.af-regression-icon { width: 12px; height: 12px; fill: none; stroke: var(--warn); stroke-width: 2; } .af-link-button.is-danger { color: var(--crit); } .af-link-button:disabled { opacity: 0.5; cursor: default; text-decoration: none; } diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 1c5ac548..d23ecefa 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -1,4 +1,5 @@ import type { AgentSessionMessage, AgentSessionsApi, AgentSessionState, InstallProgress } from '../../shared/agentSession.ts'; +import type { MetricThresholds } from '../../shared/problems.ts'; import type { TerminalCreated } from '../../shared/api.ts'; import type { AttachmentSources } from '../agents/chatAttachments.ts'; import type { CommandRegistry } from '../commands/commandRegistry.ts'; @@ -61,6 +62,8 @@ export interface AgentWorkbenchOptions { openFolder(): void; /** The workspace calls the project instructions section needs (AF11). */ readonly instructions: Omit; + /** #527: the Problems limits, for the regression chip under a chat's turns. */ + metricThresholds?(): MetricThresholds | null; /** Optional hooks of later stories. */ readonly chatHooks?: Pick; } @@ -173,6 +176,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork refreshChanges(state.id); }, runInTerminal: options.runInTerminal, + ...(options.metricThresholds ? { metricThresholds: options.metricThresholds } : {}), ...options.chatHooks, }; } diff --git a/apps/ide/src/renderer/agentFirst/changesModel.ts b/apps/ide/src/renderer/agentFirst/changesModel.ts index 005aa8d9..4fc7d48a 100644 --- a/apps/ide/src/renderer/agentFirst/changesModel.ts +++ b/apps/ide/src/renderer/agentFirst/changesModel.ts @@ -1,5 +1,9 @@ import type { ChangedFileView, MetricChangeView, MetricDeltaFreshness, TurnMetricDeltaView } from '../../shared/agentSession.ts'; import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import { + fileName, formatChange, functionLabel, functionRegressions, isNotableLineChange, type FunctionDelta, type FunctionRegression, +} from '@codexr/core/metrics/functionMetricsDelta'; +import type { MetricThresholds } from '../../shared/problems.ts'; /** * Pure helpers of the review of a chat's changes (AF5, #270), its restores @@ -115,7 +119,9 @@ export function metricDeltaHeadline(delta: TurnMetricDeltaView, max = 3): string return pending; } if (delta.totals.length === 0) { - return delta.summary; + // #520: a turn the scene did not measure, or where only functions moved: its worst functions. + const functions = metricDeltaFunctionLines(delta); + return functions.length > 0 ? functions.slice(0, 2).join('; ') : delta.summary; } return delta.totals.slice(0, max).map(formatMetricChange).join(', '); } @@ -128,3 +134,53 @@ export function metricDeltaFileLines(delta: TurnMetricDeltaView): string[] { } return lines; } + +/** + * #520 (O18): one line per function the turn changed, worst first: + * "route() in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)". + */ +export function functionDeltaLine(delta: FunctionDelta): string { + const where = t('metricDelta.fn.where', { name: functionLabel(delta.name), file: fileName(delta.path) }); + const { before, after } = delta; + if (!before && after) { + return `${where}: ${t('metricDelta.fn.new', { ccn: after.complexity, nloc: after.lineCount })}`; + } + if (before && !after) { + return `${where}: ${t('metricDelta.fn.removed', { ccn: before.complexity })}`; + } + if (!before || !after) { + return where; + } + const parts = [`CCN ${formatChange(before.complexity, after.complexity)}`]; + if (isNotableLineChange(before.lineCount, after.lineCount)) { + parts.push(`NLOC ${formatChange(before.lineCount, after.lineCount)}`); + } + if (before.parameters !== after.parameters) { + parts.push(`${t('metricDelta.fn.params')} ${formatChange(before.parameters, after.parameters)}`); + } + return `${where}: ${parts.join(', ')}`; +} + +export function metricDeltaFunctionLines(delta: TurnMetricDeltaView): string[] { + const lines = (delta.functions ?? []).map(functionDeltaLine); + const more = delta.moreFunctions ?? 0; + if (more > 0) { + lines.push(t('metricDelta.fn.more', { count: more })); + } + return lines; +} + +/** #527 (O25): the functions of a turn's delta that crossed a Problems limit (none without limits). */ +export function turnRegressions(delta: TurnMetricDeltaView, thresholds: MetricThresholds | null): FunctionRegression[] { + return thresholds && delta.functions ? functionRegressions(delta.functions, thresholds) : []; +} + +/** The chip's text: "2 functions over a Problems limit". */ +export function regressionChipLabel(regressions: readonly FunctionRegression[]): string { + return regressions.length === 1 ? t('regression.chipOne') : t('regression.chipMany', { count: regressions.length }); +} + +/** The chip's tooltip: which functions. */ +export function regressionChipTitle(regressions: readonly FunctionRegression[]): string { + return t('regression.chipTitle', { names: regressions.map((regression) => functionLabel(regression.delta.name)).join(', ') }); +} diff --git a/apps/ide/src/renderer/agentFirst/chatView.ts b/apps/ide/src/renderer/agentFirst/chatView.ts index 8f0c0ca5..7ea88fa6 100644 --- a/apps/ide/src/renderer/agentFirst/chatView.ts +++ b/apps/ide/src/renderer/agentFirst/chatView.ts @@ -5,7 +5,9 @@ import { applySessionEvent, type AgentSessionMessage, type AgentSessionState, type AgentSessionsApi, type ConfigOptionView, type PlanEntryView, type PromptAttachment, type ToolContentView, type TranscriptItem, type TurnMetricDeltaView, } from '../../shared/agentSession.ts'; -import { metricDeltaFileLines, metricDeltaHeadline, restorePrompt } from './changesModel.ts'; +import { metricDeltaFileLines, metricDeltaFunctionLines, metricDeltaHeadline, restorePrompt } from './changesModel.ts'; +import { renderRegressionChip } from './regressionChip.ts'; +import type { MetricThresholds } from '../../shared/problems.ts'; import { renderMarkdown } from '../agents/chatMarkdown.ts'; import { createAttachmentBar, type AttachmentSources } from '../agents/chatAttachments.ts'; import { el, icon } from '../dom.ts'; @@ -48,6 +50,8 @@ export interface ChatViewDeps { openChanges?(state: AgentSessionState): void; /** AF9: lets the analysis add its line under a finished turn. */ decorateTurn?(state: AgentSessionState, turnStart: number, footer: HTMLElement): void; + /** #527: the Problems limits, for the regression chip under a turn (no chip without them). */ + metricThresholds?(): MetricThresholds | null; /** #431: runs a program in a terminal of its own in the panel (`TerminalPanel.runTask`), for Continue in terminal. */ runInTerminal?(label: string, start: (cols: number, rows: number) => Promise): Promise; } @@ -559,6 +563,13 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } if (item.metricDelta) { footer.append(renderMetricDelta(item.metricDelta)); + const chip = renderRegressionChip(item.metricDelta, deps.metricThresholds?.() ?? null, (text) => { + insertText(text); + deps.onStatus(t('regression.drafted')); + }); + if (chip) { + footer.append(chip); + } } deps.decorateTurn?.(current, start, footer); return footer; @@ -567,9 +578,11 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView /** AF9: "Complexity max 9 -> 1, LOC -6", the per-file detail folded under it. */ function renderMetricDelta(delta: TurnMetricDeltaView): HTMLElement { const lines = metricDeltaFileLines(delta); + const functions = metricDeltaFunctionLines(delta); return el('details', { className: 'af-metric-delta', attrs: { 'data-testid': 'af-metric-delta' } }, [ el('summary', { attrs: { title: delta.summary } }, [el('span', { className: 'af-metric-delta-label', text: t('chat.metrics') }), el('span', { text: ` ${metricDeltaHeadline(delta)}` })]), el('p', { className: 'muted', text: delta.summary }), + ...(functions.length > 0 ? [el('ul', { className: 'af-metric-delta-files af-metric-delta-functions', attrs: { 'data-testid': 'af-metric-delta-functions' } }, functions.map((line) => el('li', { text: line })))] : []), ...(lines.length > 0 ? [el('ul', { className: 'af-metric-delta-files' }, lines.map((line) => el('li', { text: line })))] : []), ]); } diff --git a/apps/ide/src/renderer/agentFirst/regressionChip.ts b/apps/ide/src/renderer/agentFirst/regressionChip.ts new file mode 100644 index 00000000..e41afdbe --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/regressionChip.ts @@ -0,0 +1,28 @@ +import { regressionPrompt } from '@codexr/core/agent-prompts/regressionPrompt'; +import type { TurnMetricDeltaView } from '../../shared/agentSession.ts'; +import type { MetricThresholds } from '../../shared/problems.ts'; +import { t } from '../../shared/i18n/i18n.ts'; +import { el, icon } from '../dom.ts'; +import { regressionChipLabel, regressionChipTitle, turnRegressions } from './changesModel.ts'; + +const WARNING_ICON = 'M12 3l10 18H2zM12 10v5M12 18v.5'; + +/** + * #527 (O25): the warning chip under a turn whose changes pushed functions + * over a Problems limit, with "Ask to simplify". The button drafts the core's + * prompt (the offending functions, before and after) with `draft`; it is + * never sent. Null when no function crossed a limit. + */ +export function renderRegressionChip(delta: TurnMetricDeltaView, thresholds: MetricThresholds | null, draft: (text: string) => void): HTMLElement | null { + const regressions = turnRegressions(delta, thresholds); + if (regressions.length === 0 || !thresholds) { + return null; + } + const ask = el('button', { className: 'af-link-button', text: t('regression.ask'), attrs: { type: 'button', 'data-testid': 'af-regression-ask' } }); + ask.addEventListener('click', () => draft(regressionPrompt(regressions, thresholds))); + return el('div', { className: 'af-regression-chip', attrs: { role: 'status', title: regressionChipTitle(regressions), 'data-testid': 'af-regression-chip' } }, [ + icon(WARNING_ICON, 'af-regression-icon'), + el('span', { text: regressionChipLabel(regressions) }), + ask, + ]); +} diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index 047343bf..62fbdaa9 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -4,7 +4,7 @@ import { followSystemTheme, monaco } from './monaco.ts'; import { startupMarkFrame, startupMarkOnce } from '../startup/startupMarks.ts'; import { languageName, type EditorStatusState, type EndOfLine, type Indentation, type LanguageInfo } from './editorStatusModel.ts'; import { settingOf, type SettingValues } from '../../shared/settings.ts'; -import type { FileFunctionMetrics, FunctionMetric, MetricThresholds, Problem, ProblemSeverity } from '../../shared/problems.ts'; +import type { FileFunctionMetrics, FunctionDelta, FunctionMetric, MetricThresholds, Problem, ProblemSeverity } from '../../shared/problems.ts'; import type { HotspotIntent } from '../agentFirst/askAgent.ts'; import { installMetricLens } from './metricLens.ts'; import { installGitDecorations, type GitDecorationsHooks } from './gitDecorations.ts'; @@ -271,8 +271,8 @@ export interface EditorGroup { editorProblems(): Problem[]; /** #173: the Code-XR metric problems, drawn as squiggles in the open files and in the ones opened later. */ setMetricProblems(problems: readonly Problem[]): void; - /** #178: the measured functions as lenses and a complexity strip; `enabled` is the setting. */ - setFunctionMetrics(files: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean): void; + /** #178: the measured functions as lenses and a complexity strip; `enabled` is the setting; `turn` the last agent turn's function deltas (#520). */ + setFunctionMetrics(files: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean, turn?: readonly FunctionDelta[]): void; /** #178: a scene is shown beside the code; the editor's context menu offers "Reveal in XR Scene" only then. */ setSceneShown(shown: boolean): void; /** #398: an analysis started or ended, or could start now: the editor's context menu follows. */ @@ -1957,8 +1957,8 @@ export function createEditorGroup( setExecutionPoint(point): void { debugDecorations?.setExecutionPoint(point); }, - setFunctionMetrics(metricFiles: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean): void { - metricLens.update(metricFiles, thresholds, enabled); + setFunctionMetrics(metricFiles: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean, turn?: readonly FunctionDelta[]): void { + metricLens.update(metricFiles, thresholds, enabled, turn); // #514: the "Ask agent" entry of the context menu follows the measured functions. analysisMenu?.refresh(); }, diff --git a/apps/ide/src/renderer/editor/metricLens.ts b/apps/ide/src/renderer/editor/metricLens.ts index 59285750..d7376abb 100644 --- a/apps/ide/src/renderer/editor/metricLens.ts +++ b/apps/ide/src/renderer/editor/metricLens.ts @@ -1,4 +1,5 @@ import { complexityBand, metricLensTitle, type FileFunctionMetrics, type FunctionMetric, type MetricThresholds } from '../../shared/problems.ts'; +import { deltaForFunction, type FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; import { t } from '../../shared/i18n/i18n.ts'; import { monaco } from './monaco.ts'; @@ -15,11 +16,15 @@ import { monaco } from './monaco.ts'; * * #514: beside each function's lens, an "Ask agent" lens drafts a prompt * about it (refactor, the default intent) in the active chat. + * + * #520: a function the last agent turn changed says by how much, "CCN 13 + * (+4 this turn)", until its file is kept or undone in the Changes review + * (the main process then drops it from `turn`). */ export interface MetricLens { - /** The measured functions, the limits, and whether the setting shows them. */ - update(files: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean): void; + /** The measured functions, the limits, whether the setting shows them, and the last agent turn's function deltas (#520). */ + update(files: readonly FileFunctionMetrics[], thresholds: MetricThresholds, enabled: boolean, turn?: readonly FunctionDelta[]): void; /** A model was opened (it gets its strip) or its unsaved state changed (its lenses follow). */ refresh(model: monaco.editor.ITextModel): void; /** A model is about to be disposed. */ @@ -42,6 +47,7 @@ export function installMetricLens(scheme: string, hooks: { let byPath = new Map(); let thresholds: MetricThresholds = { complexity: 0, lines: 0, parameters: 0 }; let enabled = true; + let turn: readonly FunctionDelta[] = []; const strips = new Map(); const changed = new monaco.Emitter(); const pathOf = (model: monaco.editor.ITextModel): string => model.uri.path.replace(/^\//, ''); @@ -80,7 +86,8 @@ export function installMetricLens(scheme: string, hooks: { } const lastLine = model.getLineCount(); const lenses = functions.filter((fn) => fn.lineStart <= lastLine).flatMap((fn): monaco.languages.CodeLens[] => { - const { title, over } = metricLensTitle(fn, thresholds); + const delta = deltaForFunction(turn, pathOf(model), fn); + const { title, over } = metricLensTitle(fn, thresholds, delta ? (delta.before ?? 'new') : null); const range = new monaco.Range(fn.lineStart, 1, fn.lineStart, 1); const metric: monaco.languages.CodeLens = { range, @@ -125,8 +132,9 @@ export function installMetricLens(scheme: string, hooks: { } return { - update(files, nextThresholds, nextEnabled): void { + update(files, nextThresholds, nextEnabled, nextTurn = []): void { byPath = new Map(files.map((file) => [file.path, file.functions])); + turn = nextTurn; thresholds = nextThresholds; enabled = nextEnabled; for (const model of monaco.editor.getModels()) { diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 6c29db1b..ac862f77 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -256,7 +256,7 @@ function editorGroup(): Promise { } editors.setMetricProblems(currentMetricProblems); if (metricThresholds) { - editors.setFunctionMetrics(metricSnapshot?.files ?? [], metricThresholds, metricsInEditor); + editors.setFunctionMetrics(metricSnapshot?.files ?? [], metricThresholds, metricsInEditor, metricSnapshot?.turnDeltas); } startupMark('editor-created'); startupMarkFrame('editor-created'); @@ -823,7 +823,7 @@ function refreshMetricProblems(): void { problemsView.setMetricProblems(currentMetricProblems, metricSnapshot !== null); editors?.setMetricProblems(currentMetricProblems); if (metricThresholds) { - editors?.setFunctionMetrics(metricSnapshot?.files ?? [], metricThresholds, metricsInEditor); + editors?.setFunctionMetrics(metricSnapshot?.files ?? [], metricThresholds, metricsInEditor, metricSnapshot?.turnDeltas); } } function receiveMetrics(snapshot: FunctionMetricsSnapshot | null): void { @@ -1379,6 +1379,8 @@ const agentWorkbench = installAgentWorkbench({ await api.workspace.openRecent(folder); }, runInTerminal: (label, start) => terminal.runTask(label, start), + // #527: the regression chip under a turn quotes the Problems limits in force. + metricThresholds: () => metricThresholds, analyseProject: () => { if (!runView.analyse('project-xr-deep')) { showCodeXr('analyse'); diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index e4eb0709..88b0aca1 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -10,6 +10,7 @@ * extension (1.3.0) can reuse it as is. */ +import type { FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; import type { TerminalCreated } from './api.ts'; // ---- Agents ---------------------------------------------------------------- @@ -287,6 +288,14 @@ export interface TurnMetricDeltaView { * value means the delta is pending (no totals or files are kept then). */ readonly freshness?: MetricDeltaFreshness; + /** + * #520 (O18): the functions the turn added, removed or changed (complexity, + * parameters, or notably its NLOC), worst first, capped. Measured on the + * window's function metrics, so present even without a scene. + */ + readonly functions?: readonly FunctionDelta[]; + /** Functions left out of `functions` by the cap. */ + readonly moreFunctions?: number; } export interface PlanEntryView { diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 719ffebb..cf66d63a 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -738,6 +738,17 @@ export const en = { 'metricDelta.reason.paused': 'the scene shows another analysis', 'metricDelta.reason.timeout': 'the analysis did not catch up in time', 'metricDelta.reason.notFollowing': 'the scene is not following changes', + // O18 (#520): the functions a turn changed; O25 (#527): its regression chip. + 'metricDelta.fn.where': '{name} in {file}', + 'metricDelta.fn.new': 'new, CCN {ccn}, NLOC {nloc}', + 'metricDelta.fn.removed': 'removed (CCN {ccn})', + 'metricDelta.fn.more': 'and {count} more functions', + 'metricDelta.fn.params': 'params', + 'regression.chipOne': '1 function over a Problems limit', + 'regression.chipMany': '{count} functions over a Problems limit', + 'regression.chipTitle': 'This turn pushed these functions over a limit: {names}', + 'regression.ask': 'Ask to simplify', + 'regression.drafted': 'Drafted a prompt to simplify them: review it, then press Send.', // O10 (#512): the scene header's freshness chip and the scene slot's placeholder. 'scene.status.updating': 'Updating…', 'scene.status.updated': 'Updated {elapsed} ago', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 817d5016..0b713356 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -741,6 +741,17 @@ export const es: Readonly> = { 'metricDelta.reason.paused': 'la escena muestra otro análisis', 'metricDelta.reason.timeout': 'el análisis no se puso al día a tiempo', 'metricDelta.reason.notFollowing': 'la escena no sigue los cambios', + // O18 (#520): las funciones que cambió un turno; O25 (#527): su aviso de regresión. + 'metricDelta.fn.where': '{name} en {file}', + 'metricDelta.fn.new': 'nueva, CCN {ccn}, NLOC {nloc}', + 'metricDelta.fn.removed': 'eliminada (CCN {ccn})', + 'metricDelta.fn.more': 'y {count} funciones más', + 'metricDelta.fn.params': 'parámetros', + 'regression.chipOne': '1 función supera un límite de Problemas', + 'regression.chipMany': '{count} funciones superan un límite de Problemas', + 'regression.chipTitle': 'Este turno llevó estas funciones por encima de un límite: {names}', + 'regression.ask': 'Pedir que simplifique', + 'regression.drafted': 'Se ha redactado una petición para simplificarlas: revísala y pulsa Enviar.', // O10 (#512): el indicador de actualización de la escena y el marcador de su espacio. 'scene.status.updating': 'Actualizando...', 'scene.status.updated': 'Actualizada hace {elapsed}', diff --git a/apps/ide/src/shared/problems.ts b/apps/ide/src/shared/problems.ts index 1c568ef8..c20a601f 100644 --- a/apps/ide/src/shared/problems.ts +++ b/apps/ide/src/shared/problems.ts @@ -14,6 +14,7 @@ export { export type { ComplexityBand, FileFunctionMetrics, FunctionMetric, FunctionMetricsSnapshot, MetricThresholds, Problem, ProblemOrigin, ProblemSeverity, } from '@codexr/core/metrics/functionMetrics'; +export type { FunctionDelta } from '@codexr/core/metrics/functionMetricsDelta'; export const PROBLEM_SEVERITIES: readonly ProblemSeverity[] = ['error', 'warning', 'info']; diff --git a/apps/ide/test/functionMetricsDelta.test.ts b/apps/ide/test/functionMetricsDelta.test.ts new file mode 100644 index 00000000..4339eff4 --- /dev/null +++ b/apps/ide/test/functionMetricsDelta.test.ts @@ -0,0 +1,203 @@ +import { afterEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { + deltaForFunction, diffFunctionMetrics, formatFunctionDelta, functionDeltaSummary, functionLabel, functionRegressions, isNotableLineChange, + type FunctionDelta, +} from '@codexr/core/metrics/functionMetricsDelta'; +import { FunctionMetricsTracker } from '@codexr/core/metrics/functionMetricsTracker'; +import { regressionPrompt } from '@codexr/core/agent-prompts/regressionPrompt'; +import { metricLensTitle, type FileFunctionMetrics, type FunctionMetric, type MetricThresholds } from '../src/shared/problems.ts'; +import { withFunctionDeltas } from '../src/main/analysis/metricDelta.ts'; +import { measureTurnFunctions } from '../src/main/agentSessions/turnFunctionDelta.ts'; +import { + functionDeltaLine, metricDeltaFunctionLines, metricDeltaHeadline, regressionChipLabel, turnRegressions, +} from '../src/renderer/agentFirst/changesModel.ts'; +import type { TurnMetricDeltaView } from '../src/shared/agentSession.ts'; +import { setLocale } from '../src/shared/i18n/i18n.ts'; + +/** #520 (O18) and #527 (O25): the per-function delta of an agent turn and its regressions. */ + +const fn = (name: string, lineStart: number, complexity: number, lineCount = 10, parameters = 1): FunctionMetric => + ({ name, lineStart, lineEnd: lineStart + lineCount, complexity, lineCount, parameters }); +const limits: MetricThresholds = { complexity: 10, lines: 50, parameters: 5 }; + +const before: FileFunctionMetrics[] = [ + { path: 'src/api.ts', functions: [fn('route', 10, 9, 40), fn('parse', 60, 3), fn('old', 80, 2)] }, + { path: 'src/other.ts', functions: [fn('untouched', 1, 4)] }, +]; +const after: FileFunctionMetrics[] = [ + { path: 'src/api.ts', functions: [fn('route', 10, 13, 62), fn('parse', 75, 3, 12), fn('helper', 90, 12, 20)] }, + { path: 'src/other.ts', functions: [fn('untouched', 1, 5)] }, +]; + +afterEach(() => setLocale('en')); + +describe('diffFunctionMetrics (#520)', () => { + it('lists changed, new and removed functions of the changed paths, worst first', () => { + const deltas = diffFunctionMetrics(before, after, ['src/api.ts']); + assert.deepEqual(deltas.map((d) => [d.name, d.status]), [['helper', 'added'], ['route', 'changed'], ['old', 'removed']]); + const route = deltas.find((d) => d.name === 'route'); + assert.deepEqual(route?.before, { complexity: 9, lineCount: 40, parameters: 1 }); + assert.deepEqual(route?.after, { complexity: 13, lineCount: 62, parameters: 1 }); + // parse only moved (lines shift, NLOC +2): not a change worth a line. + assert.ok(!deltas.some((d) => d.name === 'parse')); + }); + + it('compares every file without paths, and a folder path covers the files under it', () => { + assert.equal(diffFunctionMetrics(before, after).length, 4); + assert.equal(diffFunctionMetrics(before, after, ['src']).length, 4); + assert.equal(diffFunctionMetrics(before, after, ['src\\other.ts']).length, 1); + assert.deepEqual(diffFunctionMetrics(before, after, ['README.md']), []); + }); + + it('pairs functions of the same name in source order and treats a deleted file as removed functions', () => { + const a = [{ path: 'x.ts', functions: [fn('function', 1, 1), fn('function', 20, 2)] }]; + const b = [{ path: 'x.ts', functions: [fn('function', 1, 1), fn('function', 20, 6)] }]; + assert.deepEqual(diffFunctionMetrics(a, b).map((d) => [d.lineStart, d.status]), [[20, 'changed']]); + assert.deepEqual(diffFunctionMetrics(a, [], ['x.ts']).map((d) => d.status), ['removed', 'removed']); + }); + + it('only calls an NLOC change notable when it is at least 5 lines and a quarter of the function', () => { + assert.equal(isNotableLineChange(40, 62), true); + assert.equal(isNotableLineChange(200, 210), false); + assert.equal(isNotableLineChange(4, 8), false); + assert.equal(isNotableLineChange(0, 5), true); + }); + + it('formats the lines an agent or a log reads', () => { + const deltas = diffFunctionMetrics(before, after, ['src/api.ts']); + assert.deepEqual(deltas.map(formatFunctionDelta), [ + '`helper()` in api.ts: new, CCN 12, NLOC 20', + '`route()` in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)', + '`old()` in api.ts: removed (CCN 2)', + ]); + assert.equal(functionDeltaSummary(deltas), '3 functions changed (1 new, 1 removed): CCN +14'); + assert.equal(functionDeltaSummary([]), 'No function changed.'); + assert.equal(functionLabel('Foo::bar(int)'), 'Foo::bar(int)'); + }); +}); + +describe('the lens of a function the turn changed (#520)', () => { + const deltas = diffFunctionMetrics(before, after, ['src/api.ts']); + + it('finds the delta of the function under the lens, by name and line or by a unique name', () => { + assert.equal(deltaForFunction(deltas, 'src/api.ts', fn('route', 10, 13, 62))?.status, 'changed'); + assert.equal(deltaForFunction(deltas, 'src/api.ts', fn('route', 14, 13, 62))?.status, 'changed'); + assert.equal(deltaForFunction(deltas, 'src/api.ts', fn('parse', 75, 3, 12)), null); + assert.equal(deltaForFunction(deltas, 'src/other.ts', fn('route', 10, 13)), null); + assert.equal(deltaForFunction(undefined, 'src/api.ts', fn('route', 10, 13)), null); + }); + + it('says by how much this turn moved each value', () => { + const route = after[0]?.functions[0] as FunctionMetric; + const baseline = deltaForFunction(deltas, 'src/api.ts', route)?.before ?? null; + assert.equal(metricLensTitle(route, limits, baseline).title, '$(warning) CCN 13 (+4 this turn) > 10 · NLOC 62 (+22 this turn) > 50 · 1 param'); + assert.equal(metricLensTitle(route, { complexity: 0, lines: 0, parameters: 0 }).title, 'CCN 13 · NLOC 62 · 1 param'); + assert.equal(metricLensTitle(fn('helper', 90, 12, 20), { complexity: 0, lines: 0, parameters: 0 }, 'new').title, 'CCN 12 · NLOC 20 · 1 param · new this turn'); + }); +}); + +describe('the turn view (#520)', () => { + const deltas = diffFunctionMetrics(before, after, ['src/api.ts']); + + it('adds the functions to a scene delta, or makes a view of them alone', () => { + assert.equal(withFunctionDeltas(null, []), null); + assert.equal(withFunctionDeltas(null, null), null); + const alone = withFunctionDeltas(null, deltas, 2); + assert.equal(alone?.functions?.length, 2); + assert.equal(alone?.moreFunctions, 1); + assert.match(alone?.summary ?? '', /^3 functions changed/); + const scene: TurnMetricDeltaView = { summary: 's', totals: [{ metric: 'codeLines', before: 1, after: 2 }], files: [], moreFiles: 0 }; + assert.equal(withFunctionDeltas(scene, deltas)?.totals.length, 1); + assert.equal(withFunctionDeltas(scene, deltas)?.functions?.length, 3); + }); + + it('renders one line per function in the chat, in English and Spanish', () => { + const view = withFunctionDeltas(null, deltas, 2) as TurnMetricDeltaView; + assert.deepEqual(metricDeltaFunctionLines(view), [ + 'helper() in api.ts: new, CCN 12, NLOC 20', + 'route() in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)', + 'and 1 more functions', + ]); + assert.equal(metricDeltaHeadline(view), 'helper() in api.ts: new, CCN 12, NLOC 20; route() in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)'); + setLocale('es'); + assert.equal(functionDeltaLine(deltas[2] as FunctionDelta), 'old() en api.ts: eliminada (CCN 2)'); + }); + + it('re-measures the changed files and diffs them against the snapshot before the turn', async () => { + const root = path.resolve('/project'); + const calls: string[] = []; + const tracker = new FunctionMetricsTracker(async (target) => { + calls.push(target); + if (target.endsWith('api.ts')) { + return [{ relativePath: 'src/api.ts', functions: [{ functionName: 'route', lineStart: 10, lineEnd: 70, lineCount: 62, complexity: 13, parameters: 1 }] }]; + } + return []; + }, { onChange: () => undefined }); + // Seed the tracker as an analysis would. + (tracker as unknown as { root: string; files: FileFunctionMetrics[] }).root = root; + (tracker as unknown as { root: string; files: FileFunctionMetrics[] }).files = before; + const baseline = tracker.snapshot; + const deltas = await measureTurnFunctions({ + baseline, + root, + changed: ['src/api.ts', 'src/gone.ts'], + remeasure: (files, signal) => tracker.remeasure(root, files, signal), + exists: async (file) => !file.endsWith('gone.ts'), + timeoutMs: 5000, + }); + assert.deepEqual(calls, [path.join(root, 'src', 'api.ts')]); + assert.deepEqual(deltas?.map((d) => [d.name, d.status]), [['route', 'changed'], ['old', 'removed'], ['parse', 'removed']]); + // The tracker kept the fresh measurement (the Problems panel and the lenses follow). + assert.equal(tracker.snapshot?.files.find((file) => file.path === 'src/api.ts')?.functions[0]?.complexity, 13); + // No baseline of this folder: no delta. + assert.equal(await measureTurnFunctions({ baseline: null, root, changed: ['a.ts'], remeasure: async () => null, exists: async () => true, timeoutMs: 10 }), null); + assert.equal(await tracker.remeasure(path.resolve('/elsewhere'), []), null); + }); + + it('gives the delta up when the re-measure takes longer than its bound', async () => { + const root = path.resolve('/project'); + const deltas = await measureTurnFunctions({ + baseline: { root, files: before }, + root, + changed: ['src/api.ts'], + remeasure: (_files, signal) => new Promise((resolve) => signal.addEventListener('abort', () => resolve(null))), + exists: async () => true, + timeoutMs: 20, + }); + assert.equal(deltas, null); + }); +}); + +describe('regressions over the Problems limits (#527)', () => { + const deltas = diffFunctionMetrics(before, after, ['src/api.ts']); + + it('flags a function that crossed a limit it was within, and a new one born over it', () => { + const regressions = functionRegressions(deltas, limits); + assert.deepEqual(regressions.map((r) => [r.delta.name, r.crossed]), [['helper', ['complexity']], ['route', ['complexity', 'lines']]]); + // Already over the limit before: not this turn's regression. + const worse: FunctionDelta = { path: 'a.ts', name: 'big', lineStart: 1, status: 'changed', before: { complexity: 20, lineCount: 5, parameters: 1 }, after: { complexity: 25, lineCount: 5, parameters: 1 } }; + assert.deepEqual(functionRegressions([worse], limits), []); + // A limit of 0 is off. + assert.deepEqual(functionRegressions(deltas, { complexity: 0, lines: 0, parameters: 0 }), []); + }); + + it('drafts a prompt listing each function with its before and after against the limit', () => { + const text = regressionPrompt(functionRegressions(deltas, limits), limits); + assert.match(text, /^Your last changes pushed these functions over the project's Code-XR limits\./); + assert.match(text, /- `helper` in `src\/api\.ts` \(line 90, new\): CCN 12 \(limit 10\)/); + assert.match(text, /- `route` in `src\/api\.ts` \(line 10\): CCN 9 -> 13 \(limit 10\); NLOC 40 -> 62 \(limit 50\)/); + assert.match(text, /Keep the behaviour and the public signatures unchanged\./); + }); + + it('feeds the chip: none without limits or functions, a count otherwise, en and es', () => { + const view = withFunctionDeltas(null, deltas) as TurnMetricDeltaView; + assert.equal(turnRegressions(view, null).length, 0); + assert.equal(turnRegressions({ summary: '', totals: [], files: [], moreFiles: 0 }, limits).length, 0); + const regressions = turnRegressions(view, limits); + assert.equal(regressionChipLabel(regressions), '2 functions over a Problems limit'); + setLocale('es'); + assert.equal(regressionChipLabel(regressions.slice(0, 1)), '1 función supera un límite de Problemas'); + }); +}); diff --git a/apps/vscode-extension/src/core/agent-prompts/regressionPrompt.ts b/apps/vscode-extension/src/core/agent-prompts/regressionPrompt.ts new file mode 100644 index 00000000..7995083e --- /dev/null +++ b/apps/vscode-extension/src/core/agent-prompts/regressionPrompt.ts @@ -0,0 +1,51 @@ +/** + * #527 (O25): "Ask to simplify". The prompt a host drafts when an agent turn + * pushed functions over the Problems limits (`functionRegressions` in + * core/metrics/functionMetricsDelta.ts): which functions, where, what each + * measured before and after, against which limit, and how to simplify them. + * + * Pure and host-neutral like hotspotPrompt.ts: English Markdown addressed to + * the agent, never sent by the host (the person reads it and presses Send). + */ + +import type { MetricThresholds } from '../metrics/functionMetrics'; +import { + measureValue, regressionLimit, type FunctionRegression, type RegressionMetric, +} from '../metrics/functionMetricsDelta'; +import { codeSpan } from './hotspotPrompt'; + +const LABELS: Readonly> = { + complexity: 'CCN', + lines: 'NLOC', + parameters: 'parameters', +}; + +/** "CCN 9 -> 13 (limit 10)", or "CCN 13 (limit 10)" for a new function. */ +function crossing(regression: FunctionRegression, metric: RegressionMetric, thresholds: MetricThresholds): string { + const { before, after } = regression.delta; + const now = after ? measureValue(metric, after) : 0; + const was = before ? `${measureValue(metric, before)} -> ` : ''; + return `${LABELS[metric]} ${was}${now} (limit ${regressionLimit(metric, thresholds)})`; +} + +/** One Markdown bullet per function: where it is and every limit it crossed. */ +export function regressionLines(regressions: readonly FunctionRegression[], thresholds: MetricThresholds): string[] { + return regressions.map((regression) => { + const { delta } = regression; + const where = `${codeSpan(delta.path)} (line ${delta.lineStart}${delta.before ? '' : ', new'})`; + return `- ${codeSpan(delta.name)} in ${where}: ${regression.crossed.map((metric) => crossing(regression, metric, thresholds)).join('; ')}`; + }); +} + +/** The draft asking the agent to bring the functions back under the limits. */ +export function regressionPrompt(regressions: readonly FunctionRegression[], thresholds: MetricThresholds): string { + const one = regressions.length === 1; + return [ + `Your last changes pushed ${one ? 'this function' : 'these functions'} over the project's Code-XR limits. Simplify ${one ? 'it' : 'them'} to bring ${one ? 'it' : 'them'} back under the limits:`, + '', + ...regressionLines(regressions, thresholds), + '', + 'Keep the behaviour and the public signatures unchanged. Split long functions into smaller, well-named ones, flatten nested conditions and remove duplication where that helps.', + 'Explain each change, and run the project\'s existing tests afterwards if there are any.', + ].join('\n'); +} diff --git a/apps/vscode-extension/src/core/metrics/functionMetrics.ts b/apps/vscode-extension/src/core/metrics/functionMetrics.ts index 263adbb6..9e39b505 100644 --- a/apps/vscode-extension/src/core/metrics/functionMetrics.ts +++ b/apps/vscode-extension/src/core/metrics/functionMetrics.ts @@ -3,11 +3,13 @@ * IDE (its Problems panel, CodeLens and complexity strip, #173 and #178) and * the VS Code extension (the same warnings as diagnostics, the same lenses). * - * Pure on purpose: no `vscode`, no Node, no imports at all, because the IDE + * Pure on purpose: no `vscode`, no Node, no runtime imports, because the IDE * also loads it in its sandboxed renderer. Each app keeps only a thin * adapter that runs the backend's `functions` mode and draws the result. */ +import type { FunctionDelta } from './functionMetricsDelta'; + export type ProblemSeverity = 'error' | 'warning' | 'info'; /** Where a problem comes from, for the source filter. */ @@ -50,6 +52,12 @@ export interface FunctionMetricsSnapshot { /** The folder they describe (absolute). */ readonly root: string; readonly files: readonly FileFunctionMetrics[]; + /** + * #520: the functions the last agent turn changed (`FunctionDelta` of + * functionMetricsDelta.ts), attached by a host until the person keeps or + * undoes the turn's files; the lenses quote their change. + */ + readonly turnDeltas?: readonly FunctionDelta[]; } /** A limit of 0 turns that check off. */ @@ -161,17 +169,28 @@ export function complexityBand(complexity: number): ComplexityBand { return complexity > 25 ? 'critical' : complexity > 10 ? 'high' : 'normal'; } -/** #178: the lens over a function, "CCN 7 · NLOC 42 · 3 params", each value over its limit marked. */ -export function metricLensTitle(fn: FunctionMetric, thresholds: MetricThresholds): { readonly title: string; readonly over: boolean } { - const part = (label: string, value: number, limit: number, unit = ''): { text: string; over: boolean } => { +/** + * #178: the lens over a function, "CCN 7 · NLOC 42 · 3 params", each value over its limit marked. + * #520: with a `baseline` (the function before the last agent turn, or 'new' + * when the turn added it) each value the turn moved says by how much: + * "CCN 13 (+4 this turn)". + */ +export function metricLensTitle( + fn: FunctionMetric, + thresholds: MetricThresholds, + baseline?: { readonly complexity: number; readonly lineCount: number; readonly parameters: number } | 'new' | null, +): { readonly title: string; readonly over: boolean } { + const part = (label: string, value: number, limit: number, was: number | undefined, unit = ''): { text: string; over: boolean } => { const over = limit > 0 && value > limit; - return { text: `${label}${value}${unit}${over ? ` > ${limit}` : ''}`, over }; + const moved = was !== undefined && was !== value ? ` (${value > was ? '+' : ''}${value - was} this turn)` : ''; + return { text: `${label}${value}${unit}${moved}${over ? ` > ${limit}` : ''}`, over }; }; + const before = baseline && baseline !== 'new' ? baseline : undefined; const parts = [ - part('CCN ', fn.complexity, thresholds.complexity), - part('NLOC ', fn.lineCount, thresholds.lines), - part('', fn.parameters, thresholds.parameters, fn.parameters === 1 ? ' param' : ' params'), + part('CCN ', fn.complexity, thresholds.complexity, before?.complexity), + part('NLOC ', fn.lineCount, thresholds.lines, before?.lineCount), + part('', fn.parameters, thresholds.parameters, before?.parameters, fn.parameters === 1 ? ' param' : ' params'), ]; const over = parts.some((p) => p.over); - return { title: `${over ? '$(warning) ' : ''}${parts.map((p) => p.text).join(' · ')}`, over }; + return { title: `${over ? '$(warning) ' : ''}${parts.map((p) => p.text).join(' · ')}${baseline === 'new' ? ' · new this turn' : ''}`, over }; } diff --git a/apps/vscode-extension/src/core/metrics/functionMetricsDelta.ts b/apps/vscode-extension/src/core/metrics/functionMetricsDelta.ts new file mode 100644 index 00000000..0c30f765 --- /dev/null +++ b/apps/vscode-extension/src/core/metrics/functionMetricsDelta.ts @@ -0,0 +1,246 @@ +/** + * #520 (O18): what a change did to each function, and #527 (O25): which of + * those changes pushed a function over a Problems limit. Shared by the Code-XR + * IDE (the turn summary of an agent chat, the "+4 this turn" CodeLens, the + * regression chip) and the VS Code extension, which can diff the same way + * against git HEAD. + * + * Pure on purpose, like functionMetrics.ts: no `vscode`, no Node, no runtime + * imports, because the IDE also loads it in its sandboxed renderer. + */ + +import type { FileFunctionMetrics, FunctionMetric, MetricThresholds } from './functionMetrics'; + +/** The measurements of one function at one side of a change. */ +export interface FunctionMeasure { + readonly complexity: number; + /** Lines of code (NLOC). */ + readonly lineCount: number; + readonly parameters: number; +} + +export type FunctionDeltaStatus = 'added' | 'removed' | 'changed'; + +/** One function a change added, removed or measurably changed. */ +export interface FunctionDelta { + /** Workspace-relative path, with forward slashes. */ + readonly path: string; + readonly name: string; + /** Where the function starts now (where it started, for a removed one). 1-based. */ + readonly lineStart: number; + readonly status: FunctionDeltaStatus; + /** Null for an added function. */ + readonly before: FunctionMeasure | null; + /** Null for a removed function. */ + readonly after: FunctionMeasure | null; +} + +function measure(fn: FunctionMetric): FunctionMeasure { + return { complexity: fn.complexity, lineCount: fn.lineCount, parameters: fn.parameters }; +} + +/** + * Whether a change of NLOC is worth a line of its own: at least 5 lines and + * at least a quarter of what the function had (a 3-line tweak of a long + * function is noise; doubling a short one is not). + */ +export function isNotableLineChange(before: number, after: number): boolean { + const delta = Math.abs(after - before); + return delta >= 5 && delta >= before / 4; +} + +function differs(before: FunctionMeasure, after: FunctionMeasure): boolean { + return before.complexity !== after.complexity + || before.parameters !== after.parameters + || isNotableLineChange(before.lineCount, after.lineCount); +} + +/** A file's functions by name, each list in source order (overloads and anonymous functions share a name). */ +function byName(functions: readonly FunctionMetric[]): Map { + const groups = new Map(); + for (const fn of [...functions].sort((a, b) => a.lineStart - b.lineStart)) { + groups.set(fn.name, [...(groups.get(fn.name) ?? []), fn]); + } + return groups; +} + +function diffFile(path: string, before: readonly FunctionMetric[], after: readonly FunctionMetric[]): FunctionDelta[] { + const was = byName(before); + const now = byName(after); + const out: FunctionDelta[] = []; + for (const name of new Set([...was.keys(), ...now.keys()])) { + const olds = was.get(name) ?? []; + const news = now.get(name) ?? []; + // Same name, same order: the n-th `render` before is the n-th after. + for (let index = 0; index < Math.max(olds.length, news.length); index++) { + const old = olds[index]; + const fresh = news[index]; + if (old && fresh) { + const a = measure(old); + const b = measure(fresh); + if (differs(a, b)) { + out.push({ path, name, lineStart: fresh.lineStart, status: 'changed', before: a, after: b }); + } + } else if (fresh) { + out.push({ path, name, lineStart: fresh.lineStart, status: 'added', before: null, after: measure(fresh) }); + } else if (old) { + out.push({ path, name, lineStart: old.lineStart, status: 'removed', before: measure(old), after: null }); + } + } + } + return out; +} + +const normalize = (path: string): string => path.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, ''); + +/** How much a delta raised the function's complexity (a new function raises it by all of it, a removed one lowers it). */ +export function complexityChange(delta: FunctionDelta): number { + return (delta.after?.complexity ?? 0) - (delta.before?.complexity ?? 0); +} + +/** + * The functions that differ between two measurements of a folder. `paths` + * (relative, a folder standing for every file under it) limits the diff to + * what a change touched; without it every file is compared. A function is + * listed when its complexity or parameter count moved, or its NLOC moved + * notably (`isNotableLineChange`). Sorted worst first: the biggest rise in + * complexity, then path, then position. + */ +export function diffFunctionMetrics( + before: readonly FileFunctionMetrics[], + after: readonly FileFunctionMetrics[], + paths?: readonly string[] | null, +): FunctionDelta[] { + const was = new Map(before.map((file) => [normalize(file.path), file.functions])); + const now = new Map(after.map((file) => [normalize(file.path), file.functions])); + let files = [...new Set([...was.keys(), ...now.keys()])]; + if (paths) { + const wanted = paths.map(normalize).filter(Boolean); + files = files.filter((file) => wanted.some((path) => file === path || file.startsWith(`${path}/`))); + } + return files + .flatMap((file) => diffFile(file, was.get(file) ?? [], now.get(file) ?? [])) + .sort((a, b) => complexityChange(b) - complexityChange(a) || a.path.localeCompare(b.path) || a.lineStart - b.lineStart); +} + +/** The last segment of a path ("src/api.ts" -> "api.ts"). */ +export function fileName(path: string): string { + return normalize(path).split('/').pop() || path; +} + +/** "route()" for a name the backend reports bare; a name that already ends in ")" is kept. */ +export function functionLabel(name: string): string { + const clean = name.replace(/[\u0000-\u001f\u007f`]+/g, ' ').trim() || 'function'; + return clean.endsWith(')') ? clean : `${clean}()`; +} + +const signed = (value: number): string => (value > 0 ? `+${value}` : String(value)); + +/** "9 -> 13 (+4)", or "9" when it did not move. */ +export function formatChange(before: number, after: number): string { + return before === after ? String(after) : `${before} -> ${after} (${signed(after - before)})`; +} + +/** + * One delta as an English line, for an agent, a log or a host without + * translations: "`route()` in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)", + * "`parse()` in api.ts: new, CCN 6", "`old()` in api.ts: removed (CCN 3)". + */ +export function formatFunctionDelta(delta: FunctionDelta): string { + const head = `\`${functionLabel(delta.name)}\` in ${fileName(delta.path)}`; + if (!delta.before && delta.after) { + return `${head}: new, CCN ${delta.after.complexity}, NLOC ${delta.after.lineCount}`; + } + if (delta.before && !delta.after) { + return `${head}: removed (CCN ${delta.before.complexity})`; + } + const a = delta.before as FunctionMeasure; + const b = delta.after as FunctionMeasure; + const parts = [`CCN ${formatChange(a.complexity, b.complexity)}`]; + if (isNotableLineChange(a.lineCount, b.lineCount)) { + parts.push(`NLOC ${formatChange(a.lineCount, b.lineCount)}`); + } + if (a.parameters !== b.parameters) { + parts.push(`params ${formatChange(a.parameters, b.parameters)}`); + } + return `${head}: ${parts.join(', ')}`; +} + +/** One line for a summary: "3 functions changed (1 new): CCN +7". */ +export function functionDeltaSummary(deltas: readonly FunctionDelta[]): string { + if (deltas.length === 0) { + return 'No function changed.'; + } + const added = deltas.filter((delta) => delta.status === 'added').length; + const removed = deltas.filter((delta) => delta.status === 'removed').length; + const kinds = [added > 0 ? `${added} new` : '', removed > 0 ? `${removed} removed` : ''].filter(Boolean); + const ccn = deltas.reduce((sum, delta) => sum + complexityChange(delta), 0); + return `${deltas.length} ${deltas.length === 1 ? 'function' : 'functions'} changed${kinds.length > 0 ? ` (${kinds.join(', ')})` : ''}${ccn !== 0 ? `: CCN ${signed(ccn)}` : ''}`; +} + +/** + * The delta a CodeLens over `fn` (measured now) should quote, from the + * deltas of the last change: the one on the same function (same name, same + * start line, else the only one of that name in the file). Null when the + * function was not changed by it. + */ +export function deltaForFunction(deltas: readonly FunctionDelta[] | undefined, path: string, fn: FunctionMetric): FunctionDelta | null { + if (!deltas || deltas.length === 0) { + return null; + } + const target = normalize(path); + const named = deltas.filter((delta) => delta.status !== 'removed' && normalize(delta.path) === target && delta.name === fn.name); + return named.find((delta) => delta.lineStart === fn.lineStart) ?? (named.length === 1 ? named[0] ?? null : null); +} + +// ---- #527 (O25): regressions over the Problems limits ----------------------- + +export type RegressionMetric = 'complexity' | 'lines' | 'parameters'; + +/** A function a change pushed over at least one limit it was within (or that arrived over it). */ +export interface FunctionRegression { + readonly delta: FunctionDelta; + /** The limits it crossed, in this order: complexity, lines, parameters. */ + readonly crossed: readonly RegressionMetric[]; +} + +const METRIC_OF: Readonly number; readonly limit: (t: MetricThresholds) => number }>> = { + complexity: { value: (m) => m.complexity, limit: (t) => t.complexity }, + lines: { value: (m) => m.lineCount, limit: (t) => t.lines }, + parameters: { value: (m) => m.parameters, limit: (t) => t.parameters }, +}; + +/** + * The rule behind the regression chip: a delta whose function is now over a + * Problems limit (a limit of 0 is off, as in `metricProblems`) and was not + * over it before (a new function counts as within). A function that was + * already over a limit is no regression of this change, even if it grew. + */ +export function functionRegressions(deltas: readonly FunctionDelta[], thresholds: MetricThresholds): FunctionRegression[] { + const out: FunctionRegression[] = []; + for (const delta of deltas) { + const after = delta.after; + if (!after) { + continue; + } + const crossed = (Object.keys(METRIC_OF) as RegressionMetric[]).filter((metric) => { + const { value, limit } = METRIC_OF[metric]; + const max = limit(thresholds); + return max > 0 && value(after) > max && (!delta.before || value(delta.before) <= max); + }); + if (crossed.length > 0) { + out.push({ delta, crossed }); + } + } + return out; +} + +/** The limit a regression crossed for one metric (for messages: "CCN 9 -> 13, limit 10"). */ +export function regressionLimit(metric: RegressionMetric, thresholds: MetricThresholds): number { + return METRIC_OF[metric].limit(thresholds); +} + +/** A measure's value for one metric. */ +export function measureValue(metric: RegressionMetric, value: FunctionMeasure): number { + return METRIC_OF[metric].value(value); +} diff --git a/apps/vscode-extension/src/core/metrics/functionMetricsTracker.ts b/apps/vscode-extension/src/core/metrics/functionMetricsTracker.ts index c7aafd82..e4ea3ee9 100644 --- a/apps/vscode-extension/src/core/metrics/functionMetricsTracker.ts +++ b/apps/vscode-extension/src/core/metrics/functionMetricsTracker.ts @@ -96,6 +96,49 @@ export class FunctionMetricsTracker { }, SAVE_DEBOUNCE_MS)); } + /** + * #520: re-measures these files of `root` now (no debounce) and merges + * them, a file that is gone or has no functions left dropping out; at + * most `concurrency` runs at a time. Resolves with the new snapshot once + * every file was measured or failed, or null when the metrics do not + * describe `root` (or the folder changed meanwhile, or `signal` aborted). + */ + async remeasure(root: string, files: readonly { readonly relativePath: string; readonly absolutePath: string; readonly deleted?: boolean }[], signal?: AbortSignal, concurrency = 3): Promise { + if (this.root !== root) { + return null; + } + const generation = this.generation; + const fresh: FileFunctionMetrics[] = []; + const done: string[] = []; + const queue = [...files]; + const worker = async (): Promise => { + for (let file = queue.shift(); file && !signal?.aborted; file = queue.shift()) { + if (file.deleted) { + done.push(file.relativePath); + continue; + } + try { + const payload = await this.runner(file.absolutePath, 'file', root, signal); + fresh.push(...parseFunctionMetrics(payload).filter((entry) => entry.path === file.relativePath)); + done.push(file.relativePath); + } catch (error) { + if (!signal?.aborted) { + this.hooks.onLog?.('warn', `Could not re-measure ${file.relativePath}: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + }; + await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, files.length)) }, worker)); + if (signal?.aborted || generation !== this.generation) { + return null; + } + if (done.length > 0) { + this.files = mergeFileMetrics(this.files, fresh, done); + this.hooks.onChange(this.snapshot); + } + return this.snapshot; + } + /** The folder changed (or went): the metrics describe nothing any more. */ clear(): void { if (this.root === null) { diff --git a/apps/vscode-extension/test/analysis/functionMetricsDelta.test.cjs b/apps/vscode-extension/test/analysis/functionMetricsDelta.test.cjs new file mode 100644 index 00000000..7450e7e5 --- /dev/null +++ b/apps/vscode-extension/test/analysis/functionMetricsDelta.test.cjs @@ -0,0 +1,31 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { diffFunctionMetrics, formatFunctionDelta, functionRegressions, deltaForFunction } = require('../../out/core/metrics/functionMetricsDelta.js'); +const { metricLensTitle } = require('../../out/core/metrics/functionMetrics.js'); +const { regressionPrompt } = require('../../out/core/agent-prompts/regressionPrompt.js'); + +// #520/#527: the per-function delta and its regression rule live in the core so +// this extension can diff a file against git HEAD with the same rules the +// Code-XR IDE applies to an agent turn (the IDE tests them in depth). + +const fn = (name, lineStart, complexity, lineCount = 10, parameters = 1) => ({ name, lineStart, lineEnd: lineStart + lineCount, complexity, lineCount, parameters }); +const head = [{ path: 'src/api.ts', functions: [fn('route', 10, 9, 40)] }]; +const workingTree = [{ path: 'src/api.ts', functions: [fn('route', 10, 13, 62), fn('helper', 80, 3)] }]; +const limits = { complexity: 10, lines: 50, parameters: 5 }; + +test('the core diffs two measurements per function and formats host-neutral lines (#520)', () => { + const deltas = diffFunctionMetrics(head, workingTree, ['src/api.ts']); + assert.deepEqual(deltas.map(formatFunctionDelta), [ + '`route()` in api.ts: CCN 9 -> 13 (+4), NLOC 40 -> 62 (+22)', + '`helper()` in api.ts: new, CCN 3, NLOC 10', + ]); + const route = workingTree[0].functions[0]; + const baseline = deltaForFunction(deltas, 'src/api.ts', route).before; + assert.match(metricLensTitle(route, { complexity: 0, lines: 0, parameters: 0 }, baseline).title, /^CCN 13 \(\+4 this turn\) · NLOC 62 \(\+22 this turn\)/); +}); + +test('the regression rule flags only the limits a change crossed, and drafts a prompt (#527)', () => { + const regressions = functionRegressions(diffFunctionMetrics(head, workingTree), limits); + assert.deepEqual(regressions.map((r) => [r.delta.name, r.crossed]), [['route', ['complexity', 'lines']]]); + assert.match(regressionPrompt(regressions, limits), /`route` in `src\/api\.ts` \(line 10\): CCN 9 -> 13 \(limit 10\); NLOC 40 -> 62 \(limit 50\)/); +}); From 0b550d7e17426c29b414734837970c2e8c16df91 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:46:47 +0000 Subject: [PATCH 32/74] feat(ide): Code-XR MCP reads a live analysis state file and offers get_functions (#524) The agents' Code-XR MCP server got --analysis once at session/new, so a chat started before the automatic analysis finished answered NO_ANALYSIS for good. The IDE now rewrites a per-project state file atomically when a project scene opens, refreshes or closes ({analysisDir, refreshState, revision, following, updatedAt}); the server reads it on every call (--analysis stays the fallback), starts each answer with the analysis age and refresh state, and warns when the file a call is about changed after the analysis. New get_functions query (per-function CCN, NLOC, parameters, line range for one file, or the top N under a folder) for the MCP server and the built-in agent, from the per-function metrics the IDE already measures: written beside the state file for the MCP server, read from FunctionMetricsService by the built-in agent. --- apps/ide/src/codexrMcp/index.ts | 2 +- apps/ide/src/codexrMcp/server.ts | 74 ++++++- .../agentSessions/agentSessionsRuntime.ts | 32 ++- .../src/main/agentSessions/codexrMcpSpec.ts | 11 +- .../src/main/agentSessions/mcpStateFiles.ts | 138 +++++++++++++ apps/ide/src/main/agents/agentChat.ts | 4 + apps/ide/src/main/agents/agentProfiles.ts | 2 +- apps/ide/src/main/agents/agentsIpc.ts | 9 +- .../src/main/agents/tools/analysisQueries.ts | 91 ++++++++- .../src/main/agents/tools/analysisState.ts | 186 ++++++++++++++++++ .../src/main/agents/tools/analysisTools.ts | 5 +- apps/ide/src/main/agents/tools/toolTypes.ts | 3 + apps/ide/src/main/analysis/analysisService.ts | 37 ++++ apps/ide/src/main/boot.ts | 2 +- apps/ide/src/main/ipc.ts | 2 +- .../main/problems/functionMetricsService.ts | 11 ++ apps/ide/test/agentsChat.test.ts | 7 +- apps/ide/test/codexrMcp.test.ts | 168 +++++++++++++++- 18 files changed, 760 insertions(+), 24 deletions(-) create mode 100644 apps/ide/src/main/agentSessions/mcpStateFiles.ts create mode 100644 apps/ide/src/main/agents/tools/analysisState.ts diff --git a/apps/ide/src/codexrMcp/index.ts b/apps/ide/src/codexrMcp/index.ts index b1c2a06b..bd85383c 100644 --- a/apps/ide/src/codexrMcp/index.ts +++ b/apps/ide/src/codexrMcp/index.ts @@ -7,7 +7,7 @@ import { createCodexrMcpServer, parseArgs } from './server.ts'; * `session/new` as a stdio server run by the IDE's own Node, so no system * Node is needed: * - * out/codexrMcp/index.cjs --root --analysis + * out/codexrMcp/index.cjs --root --analysis [--state ] * * stdout carries the protocol; diagnostics go to stderr only. */ diff --git a/apps/ide/src/codexrMcp/server.ts b/apps/ide/src/codexrMcp/server.ts index 4f5c53c9..d47d4b23 100644 --- a/apps/ide/src/codexrMcp/server.ts +++ b/apps/ide/src/codexrMcp/server.ts @@ -1,11 +1,13 @@ import path from 'node:path'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import * as z from 'zod'; -import { ANALYSIS_QUERIES, NO_ANALYSIS, type AnalysisQuery } from '../main/agents/tools/analysisQueries.ts'; +import fs from 'node:fs'; +import { ANALYSIS_QUERIES, NO_ANALYSIS, normalize, type AnalysisQuery } from '../main/agents/tools/analysisQueries.ts'; +import { analysisPreamble, functionsFileOf, readFunctionsSnapshot, readLiveState, staleFileWarning, type AnalysisLiveState } from '../main/agents/tools/analysisState.ts'; /** * The Code-XR MCP server (AF10): the analysis queries of the built-in agent - * (get_metrics, get_hotspots, get_dependencies, get_evolution), offered over + * (get_metrics, get_hotspots, get_dependencies, get_evolution, get_functions), offered over * the Model Context Protocol to the external agents the IDE starts (Claude * Code, Codex, Gemini CLI over ACP), so they reason over the same * measurements the person sees in XR. @@ -15,6 +17,13 @@ import { ANALYSIS_QUERIES, NO_ANALYSIS, type AnalysisQuery } from '../main/agent * files it opens are those the shared queries read inside the analysis * folder (data.json, dependency-graph.json, evolution/revision-N/), it never * starts an analysis, and it has no network listener. + * + * O22 (#524): with `--state ` the analysis folder is not fixed at + * start-up: the IDE rewrites that file when the scene opens, refreshes or + * closes, and every call reads it, so a chat started before the analysis + * finished sees it once it has. Every answer starts with the analysis' age + * and refresh state, and a call about one file warns when the file changed + * after it was measured. `--analysis` alone (older IDE builds) still works. */ export const CODEXR_MCP_NAME = 'code-xr'; @@ -25,6 +34,8 @@ export interface CodexrMcpOptions { readonly root: string; /** The static folder of the project's XR analysis (absolute), or null when none has run yet. */ readonly analysisDir: string | null; + /** O22 (#524): the IDE's live state file (absolute); when it reads, it wins over `analysisDir`. */ + readonly stateFile?: string | null; } /** The descriptions external agents see: the built-in agent's, saying where they come from. */ @@ -41,7 +52,10 @@ function inputShape(query: AnalysisQuery): Record { return shape; } -/** Parses `--root --analysis `; an empty analysis argument means "no analysis yet". */ +/** + * Parses `--root --analysis [--state ]`; an empty analysis + * argument means "no analysis yet" (until the state file says otherwise). + */ export function parseArgs(argv: readonly string[]): CodexrMcpOptions { const value = (flag: string): string | undefined => { const index = argv.indexOf(flag); @@ -55,13 +69,50 @@ export function parseArgs(argv: readonly string[]): CodexrMcpOptions { if (analysis && !path.isAbsolute(analysis)) { throw new Error('--analysis must be an absolute path or empty.'); } - return { root: path.resolve(root), analysisDir: analysis ? path.resolve(analysis) : null }; + const state = value('--state'); + if (state !== undefined && state !== '' && !path.isAbsolute(state)) { + throw new Error('--state must be an absolute path.'); + } + return { root: path.resolve(root), analysisDir: analysis ? path.resolve(analysis) : null, ...(state ? { stateFile: path.resolve(state) } : {}) }; +} + +async function modifiedAt(file: string): Promise { + try { + return (await fs.promises.stat(file)).mtime; + } catch { + return null; + } +} + +/** The file a call is about (a `path` argument naming a file inside the project), or null. */ +async function fileOfCall(root: string, args: Record): Promise<{ relative: string; modified: Date } | null> { + const relative = typeof args['path'] === 'string' ? normalize(args['path']) : ''; + if (!relative) { + return null; + } + const absolute = path.resolve(root, relative); + const inside = path.relative(root, absolute); + if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) { + return null; + } + try { + const stat = await fs.promises.stat(absolute); + return stat.isFile() ? { relative, modified: stat.mtime } : null; + } catch { + return null; + } +} + +/** The analysis a call reads: the state file's when it reads, else the command line's. */ +async function currentAnalysis(options: CodexrMcpOptions): Promise<{ readonly dir: string | null; readonly state: AnalysisLiveState | null }> { + const state = options.stateFile ? await readLiveState(options.stateFile) : null; + return { dir: state ? state.analysisDir : options.analysisDir, state }; } export function createCodexrMcpServer(options: CodexrMcpOptions): McpServer { const server = new McpServer( { name: CODEXR_MCP_NAME, title: 'Code-XR analysis', version: CODEXR_MCP_VERSION }, - { instructions: `Read-only Code-XR code metrics of the project at ${options.root}: per-file metrics, complexity hot spots, the dependency graph and the Git evolution, from the analysis the person ran in the Code-XR IDE. Paths are relative to the project root.` }, + { instructions: `Read-only Code-XR code metrics of the project at ${options.root}: per-file and per-function metrics, complexity hot spots, the dependency graph and the Git evolution, from the analysis the person ran in the Code-XR IDE. Paths are relative to the project root. Each answer starts with the age of the analysis and whether a refresh is pending.` }, ); for (const query of ANALYSIS_QUERIES) { server.registerTool(query.name, { @@ -71,10 +122,19 @@ export function createCodexrMcpServer(options: CodexrMcpOptions): McpServer { annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, async (args: Record) => { try { - if (!options.analysisDir) { + const { dir, state } = await currentAnalysis(options); + if (!dir) { throw new Error(NO_ANALYSIS); } - return { content: [{ type: 'text' as const, text: await query.run(args, options.analysisDir) }] }; + const functionsFile = options.stateFile ? functionsFileOf(options.stateFile) : null; + const answer = await query.run(args, dir, { functions: () => (functionsFile ? readFunctionsSnapshot(functionsFile) : Promise.resolve(null)) }); + const analysedAt = await modifiedAt(path.join(dir, 'data.json')); + // get_functions is re-measured file by file on save: its own snapshot time is what a file is compared with. + const measuredAt = query.name === 'get_functions' && functionsFile ? (await modifiedAt(functionsFile)) ?? analysedAt : analysedAt; + const file = await fileOfCall(options.root, args); + const warning = file && measuredAt ? staleFileWarning(file.relative, file.modified, measuredAt) : null; + const text = [analysisPreamble(analysedAt, state), ...(warning ? [warning] : []), answer].join('\n'); + return { content: [{ type: 'text' as const, text }] }; } catch (error) { return { content: [{ type: 'text' as const, text: error instanceof Error ? error.message : String(error) }], isError: true }; } diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 0b9631a7..4ccae4fb 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -19,6 +19,7 @@ import { AgentSessionService, type WindowPort } from './agentSessionService.ts'; import { SessionStore } from './sessionStore.ts'; import { AgentFlowFeed } from './agentFlowFeed.ts'; import { codexrMcpServerSpec } from './codexrMcpSpec.ts'; +import { McpStateFiles, type FunctionMetricsInput } from './mcpStateFiles.ts'; import { SessionChanges } from '../checkpoints/sessionChanges.ts'; import { toTurnMetricDeltaView } from '../analysis/metricDelta.ts'; import type { AnalysisService } from '../analysis/analysisService.ts'; @@ -84,7 +85,11 @@ export interface AgentSessionsRuntimeOptions { /** AF10: the static folder of a window's Code-XR analysis, handed to the agents' Code-XR MCP server. */ readonly analysisOutput?: (contents: WebContents) => string | null; /** AF9: the window's live analysis, measured before and after each turn. */ - readonly analysis?: Pick; + readonly analysis?: Pick & Partial>; + /** O22 (#524): the windows' per-function metrics, written beside the MCP state file for get_functions. */ + readonly functionMetrics?: { + onSnapshot(listener: (contents: WebContents, snapshot: FunctionMetricsInput | null) => void): () => void; + }; /** #456: reads and stores the user's `agents.claude.remoteControl` setting. Absent (the smoke run), chats never start with it. */ readonly claudeRemoteControlSetting?: { get(): Promise; @@ -172,6 +177,27 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS } }; + // O22 (#524): the live analysis state each chat's Code-XR MCP server reads on every call, + // so a chat started before the analysis finished (or across a refresh) sees the current one. + const mcpState = new McpStateFiles({ dir: path.join(dir, 'mcp-state'), onError: (message) => log.warn(`[agent] ${message}`) }); + mcpState.reset(); + options.analysis?.onSceneState?.((folder, state) => { + void mcpState.update(folder, state); + }); + /** The folder each window's last function snapshot described (a cleared snapshot names none). */ + const metricsRoots = new Map(); + options.functionMetrics?.onSnapshot((contents, snapshot) => { + const root = snapshot?.root ?? metricsRoots.get(contents.id); + if (snapshot) { + metricsRoots.set(contents.id, snapshot.root); + } else { + metricsRoots.delete(contents.id); + } + if (root) { + void mcpState.updateFunctions(root, snapshot); + } + }); + // Agent Flow (#319): every chat is a live trace source of the XR scene. const agentFlow = new AgentFlowFeed(); const service: AgentSessionService = new AgentSessionService({ @@ -271,7 +297,9 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS } const owner = webContents.getAllWebContents().find((contents) => !contents.isDestroyed() && currentWorkspaceInfo(contents)?.root === root); const analysisDir = owner ? (options.analysisOutput?.(owner) ?? null) : null; - return [codexrMcpServerSpec({ execPath: process.execPath, appPath: app.getAppPath(), root, analysisDir, isPackaged: app.isPackaged })]; + // O22 (#524): until the state file is written, the server falls back to `--analysis`. + void mcpState.ensure(root, analysisDir); + return [codexrMcpServerSpec({ execPath: process.execPath, appPath: app.getAppPath(), root, analysisDir, stateFile: mcpState.stateFile(root), isPackaged: app.isPackaged })]; }, // AF12: chats started in a worktree get it here, outside every project. worktreeStorageDir: path.join(userData, 'worktrees'), diff --git a/apps/ide/src/main/agentSessions/codexrMcpSpec.ts b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts index 3b14aca3..6e6e2819 100644 --- a/apps/ide/src/main/agentSessions/codexrMcpSpec.ts +++ b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts @@ -24,6 +24,12 @@ export interface CodexrMcpSpecOptions { readonly root: string; /** The window's analysis output folder, or null when no analysis has run. */ readonly analysisDir: string | null; + /** + * O22 (#524): the project's live state file, rewritten by the IDE as the + * scene opens, refreshes and closes; the server reads it on every call. + * `--analysis` stays as the fallback until the file is first written. + */ + readonly stateFile?: string | null; readonly isPackaged: boolean; } @@ -46,7 +52,10 @@ export function codexrMcpServerSpec(options: CodexrMcpSpecOptions): CodexrMcpSer return { name: CODEXR_MCP_SERVER_NAME, command: options.execPath, - args: [codexrMcpEntry(options.appPath), '--root', options.root, '--analysis', options.analysisDir ?? ''], + args: [ + codexrMcpEntry(options.appPath), '--root', options.root, '--analysis', options.analysisDir ?? '', + ...(options.stateFile ? ['--state', options.stateFile] : []), + ], env: [], }; } diff --git a/apps/ide/src/main/agentSessions/mcpStateFiles.ts b/apps/ide/src/main/agentSessions/mcpStateFiles.ts new file mode 100644 index 00000000..647b135c --- /dev/null +++ b/apps/ide/src/main/agentSessions/mcpStateFiles.ts @@ -0,0 +1,138 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { writeFileAtomic } from '../workspace/atomicWrite.ts'; +import { NO_SCENE_STATE, functionsFileOf, type AnalysisLiveState, type AnalysisSceneState, type FunctionFile } from '../agents/tools/analysisState.ts'; + +/** + * O22 (#524): the files the agents' Code-XR MCP servers read on every call, + * one pair per project: `.json`, the scene state (analysis folder, + * refresh state, revision), and `.functions.json`, the per-function + * metrics. Rewritten atomically (a reader sees the old file or the new one, + * never half of one), latest first: a write that is waiting is replaced by a + * newer one instead of queueing behind it. + */ + +/** The per-function metrics of a window, as the core's tracker keeps them. */ +export interface FunctionMetricsInput { + /** The folder they describe (absolute); `files[].path` are relative to it. */ + readonly root: string; + readonly files: readonly FunctionFile[]; +} + +export interface McpStateFilesOptions { + readonly dir: string; + readonly write?: (file: string, data: string) => Promise; + readonly now?: () => Date; + readonly onError?: (message: string) => void; +} + +const sameState = (a: AnalysisSceneState, b: AnalysisSceneState): boolean => + a.analysisDir === b.analysisDir && a.refreshState === b.refreshState && a.revision === b.revision && a.following === b.following; + +export class McpStateFiles { + private readonly dir: string; + private readonly write: (file: string, data: string) => Promise; + private readonly now: () => Date; + private readonly onError: (message: string) => void; + /** The last state written per project root. */ + private readonly known = new Map(); + private readonly queued = new Map(); + private readonly running = new Map>(); + + constructor(options: McpStateFilesOptions) { + this.dir = options.dir; + this.write = options.write ?? ((file, data) => writeFileAtomic(file, data)); + this.now = options.now ?? (() => new Date()); + this.onError = options.onError ?? (() => undefined); + } + + /** The state file of the project at `root` (absolute). */ + stateFile(root: string): string { + const id = createHash('sha256').update(path.resolve(root)).digest('hex').slice(0, 16); + return path.join(this.dir, `${id}.json`); + } + + /** Removes an earlier run's files: their analysis folders belong to servers that are gone. */ + reset(): void { + try { + fs.rmSync(this.dir, { recursive: true, force: true }); + } catch (error) { + this.onError(`Could not clear ${this.dir}: ${String(error)}`); + } + this.known.clear(); + } + + /** Writes the scene state of `root` when it changed (null: the project has no scene). */ + update(root: string, state: AnalysisSceneState | null): Promise { + const next = state ?? NO_SCENE_STATE; + const previous = this.known.get(root); + if (previous && sameState(previous, next)) { + return this.running.get(this.stateFile(root)) ?? Promise.resolve(); + } + this.known.set(root, next); + const stamped: AnalysisLiveState = { ...next, updatedAt: this.now().toISOString() }; + return this.schedule(this.stateFile(root), `${JSON.stringify(stamped, null, 2)}\n`); + } + + /** + * A chat's MCP server is about to start: makes sure its state file + * exists and is this run's, written from what the caller knows now when + * no scene event has been heard for `root` yet. + */ + ensure(root: string, analysisDir: string | null): Promise { + if (this.known.has(root)) { + return this.running.get(this.stateFile(root)) ?? Promise.resolve(); + } + return this.update(root, { ...NO_SCENE_STATE, analysisDir }); + } + + /** Writes the per-function metrics of the project at `root`, with paths relative to it. */ + updateFunctions(root: string, metrics: FunctionMetricsInput | null): Promise { + const files: FunctionFile[] = []; + for (const file of metrics?.files ?? []) { + const relative = path.relative(root, path.resolve(metrics?.root ?? root, file.path)); + if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) { + continue; + } + files.push({ path: relative.split(path.sep).join('/'), functions: file.functions }); + } + return this.schedule(functionsFileOf(this.stateFile(root)), JSON.stringify({ updatedAt: this.now().toISOString(), files })); + } + + /** Resolves once every write asked for so far is on disk (or failed). */ + async flush(): Promise { + while (this.running.size > 0) { + await Promise.all([...this.running.values()]); + } + } + + private schedule(file: string, data: string): Promise { + this.queued.set(file, data); + let run = this.running.get(file); + if (!run) { + run = this.drain(file); + this.running.set(file, run); + } + return run; + } + + private async drain(file: string): Promise { + try { + await fs.promises.mkdir(path.dirname(file), { recursive: true }); + for (let data = this.queued.get(file); data !== undefined; data = this.queued.get(file)) { + this.queued.delete(file); + try { + await this.write(file, data); + } catch (error) { + this.onError(`Could not write ${file}: ${String(error)}`); + } + } + } catch (error) { + this.queued.delete(file); + this.onError(`Could not write ${file}: ${String(error)}`); + } finally { + this.running.delete(file); + } + } +} diff --git a/apps/ide/src/main/agents/agentChat.ts b/apps/ide/src/main/agents/agentChat.ts index c6e3ead3..660f2a6f 100644 --- a/apps/ide/src/main/agents/agentChat.ts +++ b/apps/ide/src/main/agents/agentChat.ts @@ -8,6 +8,7 @@ import { parseArguments } from './providers/anthropic.ts'; import { ProviderError, type ChatMessage, type ToolCall } from './providers/types.ts'; import type { ToolCatalog } from './tools/toolCatalog.ts'; import { clip, type AgentTool, type ToolWorkspace } from './tools/toolTypes.ts'; +import type { FunctionsSnapshot } from './tools/analysisState.ts'; import type { UsageLedger } from './usageLedger.ts'; import { addUsage } from '../../shared/usageFormat.ts'; @@ -47,6 +48,8 @@ export interface ChatWindow { readonly workspace: ToolWorkspace | null; /** The static folder of the window's Code-XR analysis (A10). */ analysisOutput?(): string | null; + /** O22 (#524): the window's per-function metrics, for get_functions. */ + functionMetrics?(): FunctionsSnapshot | null; emit(event: AgentChatEvent): void; } @@ -436,6 +439,7 @@ export class AgentChat { workspace: window.workspace, signal, ...(window.analysisOutput ? { analysisOutput: window.analysisOutput } : {}), + ...(window.functionMetrics ? { functionMetrics: window.functionMetrics } : {}), progress: (output) => { const now = Date.now(); if (now - lastProgress >= 200) { diff --git a/apps/ide/src/main/agents/agentProfiles.ts b/apps/ide/src/main/agents/agentProfiles.ts index 6be4560a..6f9959c1 100644 --- a/apps/ide/src/main/agents/agentProfiles.ts +++ b/apps/ide/src/main/agents/agentProfiles.ts @@ -5,7 +5,7 @@ import type { JsonKeyValueStore } from '../core/jsonStore.ts'; const STORE_KEY = 'agents.profiles'; /** The read-only tools every starter gets: workspace (A7) and Code-XR analyses (A10). Risky tools are opt-in. */ -export const READ_TOOLS: readonly string[] = ['list_directory', 'read_file', 'find_files', 'search_text', 'get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution']; +export const READ_TOOLS: readonly string[] = ['list_directory', 'read_file', 'find_files', 'search_text', 'get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution', 'get_functions']; /** The starters every installation begins with (A4); all editable. */ export const STARTER_AGENTS: readonly Omit[] = [ diff --git a/apps/ide/src/main/agents/agentsIpc.ts b/apps/ide/src/main/agents/agentsIpc.ts index 63a48491..d6ee4e49 100644 --- a/apps/ide/src/main/agents/agentsIpc.ts +++ b/apps/ide/src/main/agents/agentsIpc.ts @@ -2,6 +2,7 @@ import type { IpcMainInvokeEvent, WebContents } from '../host/desktop.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent } from '../../shared/agents.ts'; import { currentWorkspaceInfo, workspaceOrNull } from '../workspace/workspaceWindows.ts'; import type { AgentServices } from './agentsRuntime.ts'; +import type { FunctionsSnapshot } from './tools/analysisState.ts'; type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; @@ -11,7 +12,12 @@ type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: un * validated by the services: the renderer is not trusted to send well-formed * data. Chats belong to the folder open in the calling window. */ -export function registerAgentHandlers(handle: Handle, agents: AgentServices, analysisOutput: (contents: WebContents) => string | null): void { +export function registerAgentHandlers( + handle: Handle, + agents: AgentServices, + analysisOutput: (contents: WebContents) => string | null, + functionMetrics?: (contents: WebContents) => FunctionsSnapshot | null, +): void { const { providers, profiles, sessions, chat, tools, mcp, usage } = agents; const folderOf = (event: IpcMainInvokeEvent): string | null => currentWorkspaceInfo(event.sender)?.root ?? null; @@ -37,6 +43,7 @@ export function registerAgentHandlers(handle: Handle, agents: AgentServices, ana handle(AGENT_IPC_CHANNELS.agentsSend, (event, id, text, attachments) => chat.send(folderOf(event), id, text, attachments, { workspace: workspaceOrNull(event.sender), analysisOutput: () => analysisOutput(event.sender), + ...(functionMetrics ? { functionMetrics: () => functionMetrics(event.sender) } : {}), emit: sender(event.sender), })); handle(AGENT_IPC_CHANNELS.agentsStop, (_event, id) => chat.stop(id)); diff --git a/apps/ide/src/main/agents/tools/analysisQueries.ts b/apps/ide/src/main/agents/tools/analysisQueries.ts index 920dcb40..da1ae169 100644 --- a/apps/ide/src/main/agents/tools/analysisQueries.ts +++ b/apps/ide/src/main/agents/tools/analysisQueries.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { clip, numberArg, stringArg } from './toolTypes.ts'; +import type { FunctionRecord, FunctionsSnapshot } from './analysisState.ts'; /** * Code-XR's analysis queries (A10, AF10): the pure, host-free half of the @@ -10,7 +11,9 @@ import { clip, numberArg, stringArg } from './toolTypes.ts'; * never starts an analysis or downloads anything: * - `data.json`: one metrics record per analysed file; * - `dependency-graph.json`: the graph, once the scene's dependency mode ran; - * - `evolution/revision-N/`: the frames of the last project-evolution movie. + * - `evolution/revision-N/`: the frames of the last project-evolution movie; + * - O22 (#524): the per-function metrics the IDE measures beside the scene + * (data.json has per-file records only), handed in as a `QuerySources`. * This is the bridge to the thesis' prediction work: an agent reasons over * the same measurements the person sees in XR. Keeping the definitions here * (name, description, JSON Schema, run) is what keeps both surfaces identical. @@ -173,6 +176,61 @@ export function dependenciesReport(graph: unknown, fileArg: string | undefined, ].join('\n'); } +export const FUNCTION_METRICS = ['complexity', 'lineCount', 'parameters'] as const; +export type FunctionMetricName = (typeof FUNCTION_METRICS)[number]; + +const FUNCTION_METRIC_ALIASES: Readonly> = { + complexity: 'complexity', ccn: 'complexity', cyclomatic: 'complexity', + lines: 'lineCount', linecount: 'lineCount', nloc: 'lineCount', length: 'lineCount', + parameters: 'parameters', params: 'parameters', +}; + +/** The function metric an argument names (`ccn`, `nloc`, `params`...), complexity by default. */ +export function functionMetricOf(name: string | undefined): FunctionMetricName { + if (!name) { + return 'complexity'; + } + const metric = FUNCTION_METRIC_ALIASES[name.toLowerCase()]; + if (!metric) { + throw new Error(`Unknown function metric "${name}". Use complexity (CCN), lines (NLOC) or parameters.`); + } + return metric; +} + +function formatFunction(fn: FunctionRecord): string { + return `${fn.name} (lines ${fn.lineStart}-${fn.lineEnd}): CCN=${fn.complexity}, NLOC=${fn.lineCount}, params=${fn.parameters}`; +} + +/** + * Per-function metrics: every function of one file in source order, or the + * top `limit` functions by `metric` under a folder (or the whole project). + */ +export function functionsReport(snapshot: FunctionsSnapshot, pathArg: string | undefined, metric: FunctionMetricName, limit: number): string { + const scope = normalize(pathArg); + const file = snapshot.files.find((candidate) => normalize(candidate.path) === scope && scope !== ''); + if (file) { + if (file.functions.length === 0) { + return `${file.path}: no functions.`; + } + const ordered = [...file.functions].sort((a, b) => a.lineStart - b.lineStart); + return [`${file.path}: ${ordered.length} functions`, ...ordered.map((fn) => `- ${formatFunction(fn)}`)].join('\n'); + } + const ranked = snapshot.files + .filter((candidate) => inScope(normalize(candidate.path), scope)) + .flatMap((candidate) => candidate.functions.map((fn) => ({ path: normalize(candidate.path), fn }))) + .sort((a, b) => b.fn[metric] - a.fn[metric] || a.path.localeCompare(b.path) || a.fn.lineStart - b.fn.lineStart); + if (ranked.length === 0) { + throw new Error(`No measured function at or under "${scope}". Paths are relative to the project root.`); + } + const top = ranked.slice(0, limit); + return [ + `Top ${top.length} of ${ranked.length} functions by ${metric === 'lineCount' ? 'NLOC' : metric === 'complexity' ? 'CCN' : 'parameters'}${scope ? ` under ${scope}` : ''}:`, + ...top.map(({ path: file, fn }, index) => `${index + 1}. ${file}: ${formatFunction(fn)}`), + ].join('\n'); +} + +export const NO_FUNCTION_METRICS = 'The per-function metrics are not measured yet: the IDE measures them after the analysis opens its scene. Try again in a moment, or use get_metrics for per-file numbers.'; + interface EvolutionFrame { readonly label?: string; readonly date?: string; readonly url?: string } export function evolutionReport(frames: readonly { frame: EvolutionFrame; records: readonly FileMetrics[] }[], fileArg: string | undefined, metric: string): string { @@ -229,6 +287,12 @@ export async function readMetrics(root: string): Promise { } } +/** Where a query finds what is not in the analysis folder (O22, #524). */ +export interface QuerySources { + /** The project's per-function metrics, or null while they are not measured. */ + functions?(): Promise; +} + const metricDescription = `Metric name, e.g. ${KEY_METRICS.slice(0, 7).join(', ')}.`; /** One read-only analysis query: what a tool needs, minus how it finds the analysis folder. */ @@ -244,7 +308,7 @@ export interface AnalysisQuery { /** One line for the chat: what the call asks. */ summary(args: Record): string; /** The answer as text (clipped), from the analysis folder `root`; throws a readable Error. */ - run(args: Record, root: string): Promise; + run(args: Record, root: string, sources?: QuerySources): Promise; } export const ANALYSIS_QUERIES: readonly AnalysisQuery[] = [ @@ -319,4 +383,27 @@ export const ANALYSIS_QUERIES: readonly AnalysisQuery[] = [ return clip(evolutionReport(frames, stringArg(args, 'path', false), stringArg(args, 'metric', false) ?? 'codeLines')); }, }, + { + name: 'get_functions', + title: 'Read per-function metrics', + description: 'Per-function Code-XR metrics (cyclomatic complexity CCN, lines of code NLOC, parameters, line range): every function of one file, or the top functions under a folder or the whole project ranked by a metric. Use it to find the exact functions to refactor.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'A file (all its functions) or a folder (its top functions), relative to the project root; omit for the whole project.' }, + metric: { type: 'string', description: 'Ranking for a folder: complexity (default), lines or parameters.' }, + limit: { type: 'integer', description: 'How many functions for a folder (default 10, max 100).' }, + }, + }, + summary: (args) => `functions of ${normalize(args['path'] as string | undefined) || 'the project'}`, + async run(args, _root, sources) { + const metric = functionMetricOf(stringArg(args, 'metric', false)); + const limit = Math.min(100, Math.max(1, numberArg(args, 'limit') ?? 10)); + const snapshot = await sources?.functions?.() ?? null; + if (!snapshot) { + throw new Error(NO_FUNCTION_METRICS); + } + return clip(functionsReport(snapshot, stringArg(args, 'path', false), metric, limit)); + }, + }, ]; diff --git a/apps/ide/src/main/agents/tools/analysisState.ts b/apps/ide/src/main/agents/tools/analysisState.ts new file mode 100644 index 00000000..f9a85360 --- /dev/null +++ b/apps/ide/src/main/agents/tools/analysisState.ts @@ -0,0 +1,186 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * O22 (#524): the live state of a project's Code-XR analysis, as the IDE + * hands it to the Code-XR MCP server of external agents. An agent's chat + * starts its MCP server once (ACP `session/new`), often before the + * project's automatic analysis has finished; a folder fixed on the command + * line would then read "no analysis" for the whole chat. The IDE instead + * rewrites a small JSON file (atomically) whenever the scene opens, + * refreshes or closes, and the server reads it on every call. + * + * Beside it, `.functions.json` holds the per-function metrics the IDE + * measures for the Problems panel (data.json has per-file records only), + * for the `get_functions` query. + * + * Pure and host-free: the IDE's writer (agentSessions/mcpStateFiles.ts), the + * MCP server (src/codexrMcp) and the tests share it. + */ + +export type AnalysisRefreshState = 'settled' | 'pending' | 'paused'; + +export interface AnalysisLiveState { + /** The static folder of the project's scene (absolute), or null when no scene is open. */ + readonly analysisDir: string | null; + readonly refreshState: AnalysisRefreshState; + /** Moves by at least 1 per finished refresh of the scene's data.json. */ + readonly revision: number; + /** Whether the scene follows changes on disk (off: data.json is not refreshed at all). */ + readonly following: boolean; + /** When the IDE wrote this state (ISO 8601). */ + readonly updatedAt: string; +} + +/** What the IDE knows of a scene, before it is stamped and written. */ +export type AnalysisSceneState = Omit; + +/** The state written when a project has no scene. */ +export const NO_SCENE_STATE: AnalysisSceneState = { analysisDir: null, refreshState: 'settled', revision: 0, following: true }; + +/** One function as `get_functions` reads it (the core's FunctionMetric). */ +export interface FunctionRecord { + readonly name: string; + readonly lineStart: number; + readonly lineEnd: number; + /** Lines of code (NLOC). */ + readonly lineCount: number; + readonly complexity: number; + readonly parameters: number; +} + +export interface FunctionFile { + /** Relative to the project root, with forward slashes. */ + readonly path: string; + readonly functions: readonly FunctionRecord[]; +} + +export interface FunctionsSnapshot { + readonly updatedAt?: string; + readonly files: readonly FunctionFile[]; +} + +const REFRESH_STATES: readonly string[] = ['settled', 'pending', 'paused']; +const MAX_STATE_BYTES = 64 * 1024; +const MAX_FUNCTIONS_BYTES = 64 * 1024 * 1024; + +/** The functions file that goes with a state file. */ +export function functionsFileOf(stateFile: string): string { + return stateFile.replace(/(\.json)?$/i, '.functions.json'); +} + +/** A state file's contents, or null when it is not one (a hand-edited or foreign file reads as absent). */ +export function parseLiveState(text: string): AnalysisLiveState | null { + let value: unknown; + try { + value = JSON.parse(text); + } catch { + return null; + } + if (!value || typeof value !== 'object') { + return null; + } + const record = value as Record; + const analysisDir = record['analysisDir']; + if (analysisDir !== null && (typeof analysisDir !== 'string' || !path.isAbsolute(analysisDir))) { + return null; + } + const refreshState = typeof record['refreshState'] === 'string' && REFRESH_STATES.includes(record['refreshState']) ? record['refreshState'] as AnalysisRefreshState : 'settled'; + const revision = typeof record['revision'] === 'number' && Number.isFinite(record['revision']) ? record['revision'] : 0; + const updatedAt = typeof record['updatedAt'] === 'string' ? record['updatedAt'] : ''; + return { analysisDir, refreshState, revision, following: record['following'] !== false, updatedAt }; +} + +/** The state file, or null when it is missing or not readable as one. */ +export async function readLiveState(file: string): Promise { + try { + const stat = await fs.promises.stat(file); + if (stat.size > MAX_STATE_BYTES) { + return null; + } + return parseLiveState(await fs.promises.readFile(file, 'utf8')); + } catch { + return null; + } +} + +function isFunction(value: unknown): value is FunctionRecord { + if (!value || typeof value !== 'object') { + return false; + } + const record = value as Record; + return typeof record['name'] === 'string' + && ['lineStart', 'lineEnd', 'lineCount', 'complexity', 'parameters'].every((key) => typeof record[key] === 'number' && Number.isFinite(record[key])); +} + +/** A functions snapshot from its JSON, keeping only well-formed entries; null when it is not one. */ +export function parseFunctionsSnapshot(value: unknown): FunctionsSnapshot | null { + if (!value || typeof value !== 'object' || !Array.isArray((value as Record)['files'])) { + return null; + } + const record = value as { files: unknown[]; updatedAt?: unknown }; + const files: FunctionFile[] = []; + for (const file of record.files) { + if (!file || typeof file !== 'object') { + continue; + } + const entry = file as Record; + if (typeof entry['path'] !== 'string' || !Array.isArray(entry['functions'])) { + continue; + } + files.push({ path: entry['path'].replace(/\\/g, '/'), functions: entry['functions'].filter(isFunction) }); + } + return { files, ...(typeof record.updatedAt === 'string' ? { updatedAt: record.updatedAt } : {}) }; +} + +export async function readFunctionsSnapshot(file: string): Promise { + try { + const stat = await fs.promises.stat(file); + if (stat.size > MAX_FUNCTIONS_BYTES) { + return null; + } + return parseFunctionsSnapshot(JSON.parse(await fs.promises.readFile(file, 'utf8'))); + } catch { + return null; + } +} + +const pad = (value: number): string => String(value).padStart(2, '0'); + +/** "14:02" today, "2026-12-04 14:02" on another day (local time). */ +export function formatAnalysisTime(when: Date, now: Date): string { + const time = `${pad(when.getHours())}:${pad(when.getMinutes())}`; + const sameDay = when.getFullYear() === now.getFullYear() && when.getMonth() === now.getMonth() && when.getDate() === now.getDate(); + return sameDay ? time : `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${time}`; +} + +/** + * The line every answer starts with: how old the analysis is and whether a + * refresh is on its way, so an agent knows when the numbers may lag its + * own edits. `analysedAt` is data.json's modification time (the last + * analysis or refresh); `state` is null when the IDE gave no state file. + */ +export function analysisPreamble(analysedAt: Date | null, state: AnalysisLiveState | null, now: Date = new Date()): string { + const parts = [analysedAt ? `Code-XR analysis from ${formatAnalysisTime(analysedAt, now)}` : 'Code-XR analysis']; + if (state) { + if (!state.following) { + parts.push('not following changes on disk (newer edits are not measured)'); + } else if (state.refreshState === 'pending') { + parts.push('refresh pending'); + } else if (state.refreshState === 'paused') { + parts.push('refresh paused while the scene shows another mode'); + } else { + parts.push('up to date'); + } + } + return `[${parts.join('; ')}]`; +} + +/** The warning for a file edited after the analysis measured it, or null when it is not newer. */ +export function staleFileWarning(relativePath: string, modifiedAt: Date, analysedAt: Date, now: Date = new Date()): string | null { + // A second of slack: file systems with coarse timestamps report a file written in the same instant as newer. + if (modifiedAt.getTime() <= analysedAt.getTime() + 1000) { + return null; + } + return `Warning: ${relativePath} changed at ${formatAnalysisTime(modifiedAt, now)}, after this analysis; its numbers may be out of date until the scene refreshes.`; +} diff --git a/apps/ide/src/main/agents/tools/analysisTools.ts b/apps/ide/src/main/agents/tools/analysisTools.ts index f6d920a1..52004e42 100644 --- a/apps/ide/src/main/agents/tools/analysisTools.ts +++ b/apps/ide/src/main/agents/tools/analysisTools.ts @@ -9,7 +9,7 @@ import type { AgentTool, ToolContext } from './toolTypes.ts'; * read-only tool, so it never needs an approval. */ -export { dependenciesReport, evolutionReport, hotspotsReport, metricsReport } from './analysisQueries.ts'; +export { dependenciesReport, evolutionReport, functionsReport, hotspotsReport, metricsReport } from './analysisQueries.ts'; function outputRoot(context: ToolContext): string { if (!context.workspace) { @@ -30,5 +30,6 @@ export const ANALYSIS_TOOLS: readonly AgentTool[] = ANALYSIS_QUERIES.map((query) parameters: query.parameters, preview: (args) => ({ summary: query.summary(args) }), // async, so a missing folder rejects like every other tool failure instead of throwing. - run: async (args, context) => query.run(args, outputRoot(context)), + // O22 (#524): get_functions reads the window's per-function metrics (the Problems panel's). + run: async (args, context) => query.run(args, outputRoot(context), { functions: async () => context.functionMetrics?.() ?? null }), })); diff --git a/apps/ide/src/main/agents/tools/toolTypes.ts b/apps/ide/src/main/agents/tools/toolTypes.ts index 0a38923c..f788211d 100644 --- a/apps/ide/src/main/agents/tools/toolTypes.ts +++ b/apps/ide/src/main/agents/tools/toolTypes.ts @@ -3,6 +3,7 @@ import type { EditReviewRequest, EditReviewResult, ToolInfo } from '../../../sha import type { CompiledQuery } from '../../../shared/searchText.ts'; import type { FileIndex } from '../../workspace/fileIndex.ts'; import type { SearchStats } from '../../workspace/textSearch.ts'; +import type { FunctionsSnapshot } from './analysisState.ts'; /** * The slice of a window's Workspace the agent tools use (A6, A7). Every path @@ -25,6 +26,8 @@ export interface ToolContext { reviewEdit(request: Omit): Promise; /** The static folder of the window's Code-XR analysis (A10), or null without one. */ analysisOutput?(): string | null; + /** O22 (#524): the window's per-function metrics, or null while none are measured. */ + functionMetrics?(): FunctionsSnapshot | null; /** Live output of a long tool (A9), shown in the chat while it runs. */ progress?(text: string): void; } diff --git a/apps/ide/src/main/analysis/analysisService.ts b/apps/ide/src/main/analysis/analysisService.ts index 268cad50..42710047 100644 --- a/apps/ide/src/main/analysis/analysisService.ts +++ b/apps/ide/src/main/analysis/analysisService.ts @@ -27,6 +27,7 @@ import type { PythonEnvironmentService } from '../python/pythonEnvironment.ts'; import { resolveAnalysisTarget } from './analysisTarget.ts'; import { readAnalysedFileCount, watchAnalysedFileCount } from './analysedFiles.ts'; import { readMetrics, type FileMetrics } from '../agents/tools/analysisQueries.ts'; +import type { AnalysisSceneState } from '../agents/tools/analysisState.ts'; import { computeMetricDelta, freshnessOfSettle, type MetricDeltaReport } from './metricDelta.ts'; import { followRefreshStatus, waitUntilSettled, type RefreshPort, type RefreshStatus, type SettleResult } from './sceneRefresh.ts'; import { closeScene, enterSceneXr, sceneSupportsImmersiveXr, showScene } from './sceneView.ts'; @@ -115,6 +116,8 @@ export class AnalysisService { private readonly hooks: { sceneOpened?(contents: WebContents, folder: string): void }; /** AF8: who hears that a window's scene was re-analysed after a change on disk. */ private readonly updateListeners = new Set<(contents: WebContents, event: SceneUpdatedEvent) => void>(); + /** O22 (#524): who hears every change of a folder's scene state (opened, refresh state, closed). */ + private readonly stateListeners = new Set<(folder: string, state: AnalysisSceneState | null) => void>(); constructor(python: PythonEnvironmentService, subscriptions: HostDisposable[], hooks: { sceneOpened?(contents: WebContents, folder: string): void } = {}) { this.python = python; @@ -281,6 +284,30 @@ export class AnalysisService { return () => this.updateListeners.delete(listener); } + /** + * O22 (#524): `listener` hears each change of the scene state of a folder: + * its scene opened, a refresh started or finished, following changes was + * turned on or off (`state`), or its scene went (`null`). The agents' Code-XR + * MCP server reads it from a file the IDE rewrites on each call. + */ + onSceneState(listener: (folder: string, state: AnalysisSceneState | null) => void): () => void { + this.stateListeners.add(listener); + return () => this.stateListeners.delete(listener); + } + + private emitSceneState(folder: string, state: AnalysisSceneState | null): void { + if (!folder) { + return; + } + for (const listener of this.stateListeners) { + try { + listener(folder, state); + } catch (error) { + log.warn(`A scene state listener failed: ${String(error)}`); + } + } + } + /** * AF9: brings the window's scene up to date with the disk: asks the core * to compare the folder with its last analysis now (not waiting for the @@ -413,6 +440,7 @@ export class AnalysisService { } this.scenes.delete(contents.id); previous.unwatch(); + this.emitSceneState(previous.folder, null); const win = contents.isDestroyed() ? null : BrowserWindow.fromWebContents(contents); if (win && !win.isDestroyed()) { closeScene(win); @@ -557,6 +585,7 @@ export class AnalysisService { } this.scenes.delete(id); scene.unwatch(); + this.emitSceneState(scene.folder, null); const contents = webContents.fromId(id); if (!contents || contents.isDestroyed()) { continue; @@ -754,6 +783,9 @@ export class AnalysisService { } }); const sessionId = this.sessionOf(serverId); + const folder = this.ownerFolder; + // O22 (#524): only a project scene's records are relative to the folder (see `sceneMetrics`). + const projectScene = ANALYSIS_KIND_INFO[this.ownerKind].target === 'project'; // AF8, O10 (#512): the scene's refresh state for the window's header, // and each finished re-analysis for whoever listens. let lastFiles = files; @@ -773,6 +805,7 @@ export class AnalysisService { const event: SceneUpdatedEvent = { url: serverUrl, revision: status.revision, files: lastFiles, refresh: status.refresh, mode: status.mode, following }; if (order === published) { contents.send(IPC_EVENTS.analysisSceneUpdated, event); + this.emitSceneState(folder, projectScene ? { analysisDir: this.outputDirectory(contents), refreshState: status.refresh, revision: status.revision, following } : null); } if (refreshed) { for (const listener of this.updateListeners) { @@ -835,6 +868,10 @@ export class AnalysisService { this.hooks.sceneOpened?.(win.webContents, this.ownerFolder); } republish(); + if (!lastStatus) { + // O22 (#524): a scene the core reports no refresh state for is still an analysis to read. + this.emitSceneState(folder, projectScene ? { analysisDir: this.outputDirectory(contents), refreshState: 'settled', revision: 0, following: await this.followsChanges().catch(() => true) } : null); + } await this.loadScene(win, serverId, serverUrl); } } diff --git a/apps/ide/src/main/boot.ts b/apps/ide/src/main/boot.ts index 0dafcd9e..fb5b44c2 100644 --- a/apps/ide/src/main/boot.ts +++ b/apps/ide/src/main/boot.ts @@ -127,7 +127,7 @@ export async function startServices(options: BootOptions): Promise core.analysis.outputDirectory(contents), analysis: core.analysis, + agentSessions = startAgentSessions({ isSmoke, terminal: terminalHost, profiles: agentServices.profiles, analysisOutput: (contents) => core.analysis.outputDirectory(contents), analysis: core.analysis, functionMetrics: core.metrics, // #456: Claude Code chats on claude.ai, from the user's settings (the smoke run never asks). ...(isSmoke ? {} : { claudeRemoteControlSetting: { diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index 7df53569..b583f332 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -314,7 +314,7 @@ export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: handle(IPC_CHANNELS.terminalKill, (event, id) => terminal.kill(event.sender, id)); // The AI agent hub (agents/agentsIpc.ts). - registerAgentHandlers(handle, agents, (contents) => core.analysis.outputDirectory(contents)); + registerAgentHandlers(handle, agents, (contents) => core.analysis.outputDirectory(contents), (contents) => core.metrics.snapshot(contents)); // Epic #265 (AF1): agent-first chats with ACP agents (agentSessions/agentSessionsIpc.ts). registerAgentSessionHandlers(handle, agentSessions); // #17: Source Control (git/gitIpc.ts). diff --git a/apps/ide/src/main/problems/functionMetricsService.ts b/apps/ide/src/main/problems/functionMetricsService.ts index 79bca55e..58d6f6c4 100644 --- a/apps/ide/src/main/problems/functionMetricsService.ts +++ b/apps/ide/src/main/problems/functionMetricsService.ts @@ -18,11 +18,19 @@ const log = channelLog('core'); export class FunctionMetricsService { private readonly python: PythonEnvironmentService; private readonly windows = new Map(); + /** O22 (#524): who hears each new snapshot of a window (the agents' Code-XR MCP server's file). */ + private readonly snapshotListeners = new Set<(contents: WebContents, snapshot: FunctionMetricsSnapshot | null) => void>(); constructor(python: PythonEnvironmentService) { this.python = python; } + /** O22 (#524): `listener` hears each new snapshot of a window's metrics; returns the function that stops it. */ + onSnapshot(listener: (contents: WebContents, snapshot: FunctionMetricsSnapshot | null) => void): () => void { + this.snapshotListeners.add(listener); + return () => this.snapshotListeners.delete(listener); + } + snapshot(contents: WebContents): FunctionMetricsSnapshot | null { return this.windows.get(contents.id)?.snapshot ?? null; } @@ -87,6 +95,9 @@ export class FunctionMetricsService { if (!contents.isDestroyed()) { contents.send(IPC_EVENTS.metricsChanged, snapshot); } + for (const listener of this.snapshotListeners) { + listener(contents, snapshot); + } }, onLog: (level, message) => log[level](message), }, diff --git a/apps/ide/test/agentsChat.test.ts b/apps/ide/test/agentsChat.test.ts index 4751a317..61b9efac 100644 --- a/apps/ide/test/agentsChat.test.ts +++ b/apps/ide/test/agentsChat.test.ts @@ -174,7 +174,7 @@ describe('AgentChat', () => { assert.deepEqual(stored.messages[1]?.usage, { inputTokens: 9, outputTokens: 2 }); assert.equal(body['model'], 'gpt-test'); assert.deepEqual((body['messages'] as unknown[])[0], { role: 'system', content: agent.instructions }); - assert.deepEqual((body['tools'] as Array<{ function: { name: string } }>).map((tool) => tool.function.name), ['list_directory', 'read_file', 'find_files', 'search_text', 'get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution']); + assert.deepEqual((body['tools'] as Array<{ function: { name: string } }>).map((tool) => tool.function.name), ['list_directory', 'read_file', 'find_files', 'search_text', 'get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution', 'get_functions']); assert.equal((await sessions.list('/w'))[0]?.messageCount, 2); }); @@ -487,6 +487,11 @@ describe('Code-XR analysis tools (A10)', () => { await assert.rejects(tool('get_metrics').run({}, context(null)), /No Code-XR analysis is open/); fs.writeFileSync(path.join(root, 'dependency-graph.json'), JSON.stringify(graph)); assert.match(await tool('get_dependencies').run({ path: 'src/b.ts' }, context(root)), /Used by \(1\):\n- src\/a\.ts/); + // O22 (#524): get_functions reads the window's per-function metrics (the Problems panel's). + await assert.rejects(tool('get_functions').run({}, context(root)), /not measured yet/); + const functions = { root, files: [{ path: 'src/a.ts', functions: [{ name: 'parse', lineStart: 3, lineEnd: 20, lineCount: 15, complexity: 7, parameters: 2 }] }] }; + assert.equal(await tool('get_functions').run({ path: 'src/a.ts' }, { ...context(root), functionMetrics: () => functions }), 'src/a.ts: 1 functions\n- parse (lines 3-20): CCN=7, NLOC=15, params=2'); + await assert.rejects(tool('get_functions').run({}, { ...context(null), functionMetrics: () => functions }), /No Code-XR analysis is open/); }); }); diff --git a/apps/ide/test/codexrMcp.test.ts b/apps/ide/test/codexrMcp.test.ts index aaa3dfd2..535159b0 100644 --- a/apps/ide/test/codexrMcp.test.ts +++ b/apps/ide/test/codexrMcp.test.ts @@ -7,7 +7,9 @@ import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; -import { ANALYSIS_QUERIES, NO_ANALYSIS, readEvolution, readMetrics } from '../src/main/agents/tools/analysisQueries.ts'; +import { ANALYSIS_QUERIES, NO_ANALYSIS, NO_FUNCTION_METRICS, functionMetricOf, functionsReport, readEvolution, readMetrics } from '../src/main/agents/tools/analysisQueries.ts'; +import { analysisPreamble, formatAnalysisTime, functionsFileOf, parseFunctionsSnapshot, parseLiveState, readLiveState, staleFileWarning, type FunctionsSnapshot } from '../src/main/agents/tools/analysisState.ts'; +import { McpStateFiles } from '../src/main/agentSessions/mcpStateFiles.ts'; import { ANALYSIS_TOOLS } from '../src/main/agents/tools/analysisTools.ts'; import { createCodexrMcpServer, parseArgs, type CodexrMcpOptions } from '../src/codexrMcp/server.ts'; import { codexrMcpServerSpec } from '../src/main/agentSessions/codexrMcpSpec.ts'; @@ -90,7 +92,7 @@ describe('Code-XR MCP server (AF10)', () => { const client = await connect({ root: base, analysisDir: analysisFolder(true) }); assert.equal(client.getServerVersion()?.name, 'code-xr'); const { tools } = await client.listTools(); - assert.deepEqual(tools.map((tool) => tool.name), ['get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution']); + assert.deepEqual(tools.map((tool) => tool.name), ['get_metrics', 'get_hotspots', 'get_dependencies', 'get_evolution', 'get_functions']); for (const tool of tools) { const query = ANALYSIS_QUERIES.find((candidate) => candidate.name === tool.name)!; assert.equal(tool.description, `[Code-XR] ${query.description}`); @@ -130,6 +132,8 @@ describe('Code-XR MCP server (AF10)', () => { it('parses its command line', () => { const root = path.resolve(base, 'project'); assert.deepEqual(parseArgs(['--root', root, '--analysis', '']), { root, analysisDir: null }); + assert.deepEqual(parseArgs(['--root', root, '--analysis', '', '--state', path.join(root, 's.json')]), { root, analysisDir: null, stateFile: path.join(root, 's.json') }); + assert.throws(() => parseArgs(['--root', root, '--state', 'relative.json']), /--state/); assert.deepEqual(parseArgs(['--root', root, '--analysis', path.join(root, 'out')]), { root, analysisDir: path.join(root, 'out') }); assert.throws(() => parseArgs(['--analysis', root]), /--root/); assert.throws(() => parseArgs(['--root', 'relative']), /--root/); @@ -144,8 +148,8 @@ describe('Code-XR MCP server (AF10)', () => { }); const client = new Client({ name: 'test', version: '0' }); await client.connect(transport); - assert.equal((await client.listTools()).tools.length, 4); - assert.match(text(await client.callTool({ name: 'get_metrics', arguments: { path: 'src/b.ts' } })), /^src\/b\.ts \(TypeScript\): codeLines=40/); + assert.equal((await client.listTools()).tools.length, 5); + assert.match(text(await client.callTool({ name: 'get_metrics', arguments: { path: 'src/b.ts' } })), /^\[Code-XR analysis from [^\]]+\]\nsrc\/b\.ts \(TypeScript\): codeLines=40/); await client.close(); }); }); @@ -161,5 +165,161 @@ describe('codexrMcpServerSpec', () => { }); const dev = codexrMcpServerSpec({ execPath: '/usr/bin/node', appPath: '/repo/apps/ide', root: '/p', analysisDir: null, isPackaged: false }); assert.deepEqual(dev.args, [path.join('/repo/apps/ide', 'out', 'codexrMcp', 'index.cjs'), '--root', '/p', '--analysis', '']); + // O22 (#524): the live state file comes after, so an older server still finds --analysis. + const live = codexrMcpServerSpec({ execPath: '/usr/bin/node', appPath: '/a', root: '/p', analysisDir: null, stateFile: '/data/mcp-state/1.json', isPackaged: false }); + assert.deepEqual(live.args.slice(-2), ['--state', '/data/mcp-state/1.json']); + }); +}); + +/** O22 (#524): a fixture of the IDE's per-function metrics. */ +const functionsFixture: FunctionsSnapshot = { + files: [ + { path: 'src/a.ts', functions: [ + { name: 'parse', lineStart: 30, lineEnd: 80, lineCount: 45, complexity: 14, parameters: 3 }, + { name: 'init', lineStart: 1, lineEnd: 10, lineCount: 8, complexity: 1, parameters: 0 }, + ] }, + { path: 'src\\lib\\b.ts', functions: [{ name: 'walk', lineStart: 5, lineEnd: 40, lineCount: 30, complexity: 9, parameters: 6 }] }, + { path: 'test/a.test.ts', functions: [{ name: 'it', lineStart: 1, lineEnd: 200, lineCount: 190, complexity: 2, parameters: 1 }] }, + ], +}; + +describe('get_functions (O22)', () => { + it('lists one file\'s functions in source order, or the top functions under a folder', () => { + assert.equal(functionsReport(functionsFixture, 'src/a.ts', 'complexity', 10), [ + 'src/a.ts: 2 functions', + '- init (lines 1-10): CCN=1, NLOC=8, params=0', + '- parse (lines 30-80): CCN=14, NLOC=45, params=3', + ].join('\n')); + assert.match(functionsReport(functionsFixture, 'src', 'complexity', 2), /^Top 2 of 3 functions by CCN under src:\n1\. src\/a\.ts: parse [^\n]*\n2\. src\/lib\/b\.ts: walk/); + assert.match(functionsReport(functionsFixture, '', 'lineCount', 1), /^Top 1 of 4 functions by NLOC:\n1\. test\/a\.test\.ts: it/); + assert.match(functionsReport(functionsFixture, './src/lib/', 'parameters', 5), /1\. src\/lib\/b\.ts: walk \(lines 5-40\): CCN=9, NLOC=30, params=6$/); + assert.throws(() => functionsReport(functionsFixture, 'docs', 'complexity', 5), /No measured function at or under "docs"/); + assert.equal(functionMetricOf(undefined), 'complexity'); + assert.equal(functionMetricOf('NLOC'), 'lineCount'); + assert.equal(functionMetricOf('params'), 'parameters'); + assert.throws(() => functionMetricOf('size'), /Unknown function metric/); + }); + it('runs from the sources it is given, and explains when the functions are not measured yet', async () => { + const query = ANALYSIS_QUERIES.find((candidate) => candidate.name === 'get_functions')!; + assert.match(await query.run({ path: 'src/a.ts' }, base, { functions: async () => functionsFixture }), /src\/a\.ts: 2 functions/); + await assert.rejects(query.run({}, base, { functions: async () => null }), { message: NO_FUNCTION_METRICS }); + await assert.rejects(query.run({}, base), { message: NO_FUNCTION_METRICS }); + }); + it('keeps only well-formed entries of a functions file', () => { + const parsed = parseFunctionsSnapshot({ files: [{ path: 'a\\b.ts', functions: [{ name: 'x', lineStart: 1, lineEnd: 2, lineCount: 2, complexity: 1, parameters: 0 }, { name: 'bad' }] }, { path: 3 }, null] }); + assert.deepEqual(parsed, { files: [{ path: 'a/b.ts', functions: [{ name: 'x', lineStart: 1, lineEnd: 2, lineCount: 2, complexity: 1, parameters: 0 }] }] }); + assert.equal(parseFunctionsSnapshot([]), null); + }); +}); + +describe('the live analysis state (O22)', () => { + it('parses the state file defensively', () => { + assert.deepEqual(parseLiveState(JSON.stringify({ analysisDir: path.resolve(base, 'out'), refreshState: 'pending', revision: 4, following: true, updatedAt: 'x' })), + { analysisDir: path.resolve(base, 'out'), refreshState: 'pending', revision: 4, following: true, updatedAt: 'x' }); + assert.deepEqual(parseLiveState('{"analysisDir":null}'), { analysisDir: null, refreshState: 'settled', revision: 0, following: true, updatedAt: '' }); + assert.equal(parseLiveState('{"analysisDir":"relative"}'), null); + assert.equal(parseLiveState('not json'), null); + assert.equal(functionsFileOf(path.join(base, 'abc.json')), path.join(base, 'abc.functions.json')); + }); + it('says how old the analysis is and whether a refresh is pending', () => { + const now = new Date(2026, 11, 5, 15, 30); + const at = new Date(2026, 11, 5, 14, 2); + const state = { analysisDir: base, refreshState: 'pending' as const, revision: 2, following: true, updatedAt: '' }; + assert.equal(analysisPreamble(at, state, now), '[Code-XR analysis from 14:02; refresh pending]'); + assert.equal(analysisPreamble(at, { ...state, refreshState: 'settled' }, now), '[Code-XR analysis from 14:02; up to date]'); + assert.match(analysisPreamble(at, { ...state, following: false }, now), /not following changes on disk/); + assert.match(analysisPreamble(at, { ...state, refreshState: 'paused' }, now), /refresh paused/); + assert.equal(analysisPreamble(at, null, now), '[Code-XR analysis from 14:02]'); + assert.equal(formatAnalysisTime(new Date(2026, 11, 4, 9, 5), now), '2026-12-04 09:05'); + assert.equal(staleFileWarning('src/a.ts', new Date(at.getTime() + 500), at, now), null, 'within the timestamp slack'); + assert.match(staleFileWarning('src/a.ts', new Date(2026, 11, 5, 14, 9), at, now) ?? '', /^Warning: src\/a\.ts changed at 14:09, after this analysis/); + }); + it('the MCP server follows the state file on every call', async () => { + const project = fs.mkdtempSync(path.join(base, 'project-')); + fs.mkdirSync(path.join(project, 'src')); + fs.writeFileSync(path.join(project, 'src', 'a.ts'), 'export {};\n'); + const dir = analysisFolder(false); + const files = new McpStateFiles({ dir: fs.mkdtempSync(path.join(base, 'state-')) }); + const stateFile = files.stateFile(project); + // Started before the analysis finished: no folder on the command line, no state file yet. + const client = await connect({ root: project, analysisDir: null, stateFile }); + assert.equal(text(await client.callTool({ name: 'get_metrics', arguments: {} })), NO_ANALYSIS); + await files.update(project, { analysisDir: dir, refreshState: 'pending', revision: 1, following: true }); + // The analysis is older than the file the agent asks about. + const old = new Date(Date.now() - 3_600_000); + fs.utimesSync(path.join(dir, 'data.json'), old, old); + const answer = text(await client.callTool({ name: 'get_metrics', arguments: { path: 'src/a.ts' } })); + assert.match(answer, /^\[Code-XR analysis from [^\]]+; refresh pending\]\nWarning: src\/a\.ts changed at [^\n]+\nsrc\/a\.ts \(TypeScript\)/); + // A folder is no file: no warning. + assert.doesNotMatch(text(await client.callTool({ name: 'get_metrics', arguments: { path: 'src' } })), /Warning/); + await files.update(project, { analysisDir: dir, refreshState: 'settled', revision: 2, following: true }); + assert.match(text(await client.callTool({ name: 'get_hotspots', arguments: { limit: 1 } })), /^\[Code-XR analysis from [^\]]+; up to date\]\nTop 1 files/); + // get_functions reads the functions file beside the state file. + assert.equal((await client.callTool({ name: 'get_functions', arguments: {} })).isError, true); + await files.updateFunctions(project, { root: project, files: functionsFixture.files }); + assert.match(text(await client.callTool({ name: 'get_functions', arguments: { path: 'src', limit: 1 } })), /Top 1 of 3 functions by CCN under src:\n1\. src\/a\.ts: parse/); + // The scene closed: the state wins over the command line. + await files.update(project, null); + assert.equal(text(await client.callTool({ name: 'get_metrics', arguments: {} })), NO_ANALYSIS); + await client.close(); + // Never written (an older IDE build, or the first write still on its way): --analysis. + const fallback = await connect({ root: project, analysisDir: dir, stateFile: path.join(base, 'never-written.json') }); + assert.match(text(await fallback.callTool({ name: 'get_metrics', arguments: {} })), /^\[Code-XR analysis from [^\];]+\]\nWhole project/); + await fallback.close(); + }); +}); + +describe('McpStateFiles (O22)', () => { + it('writes a project\'s state only when it changed, and resets an earlier run', async () => { + const dir = path.join(base, `writer-${Date.now()}`); + const writes: string[] = []; + const files = new McpStateFiles({ dir, now: () => new Date('2026-12-05T14:02:00Z'), write: async (file, data) => { + writes.push(path.basename(file)); + fs.writeFileSync(file, data); + } }); + const root = path.resolve(base, 'p'); + await files.ensure(root, null); + await files.update(root, { analysisDir: path.resolve(base, 'out'), refreshState: 'settled', revision: 1, following: true }); + await files.update(root, { analysisDir: path.resolve(base, 'out'), refreshState: 'settled', revision: 1, following: true }); + await files.ensure(root, null); + assert.equal(writes.length, 2); + assert.deepEqual(await readLiveState(files.stateFile(root)), { analysisDir: path.resolve(base, 'out'), refreshState: 'settled', revision: 1, following: true, updatedAt: '2026-12-05T14:02:00.000Z' }); + assert.notEqual(files.stateFile(root), files.stateFile(path.resolve(base, 'q'))); + files.reset(); + assert.equal(fs.existsSync(dir), false); + await files.ensure(root, null); + assert.equal((await readLiveState(files.stateFile(root)))?.analysisDir, null); + }); + it('keeps only the newest of the writes that wait', async () => { + const dir = path.join(base, `latest-${Date.now()}`); + const written: string[] = []; + let release: () => void = () => undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const files = new McpStateFiles({ dir, write: async (_file, data) => { + await gate; + written.push(String((JSON.parse(data) as { revision: number }).revision)); + } }); + const root = path.resolve(base, 'p'); + for (let revision = 1; revision <= 4; revision++) { + void files.update(root, { analysisDir: null, refreshState: 'pending', revision, following: true }); + // Let the first write start (and wait at the gate) before the next ones queue. + await new Promise((resolve) => setTimeout(resolve, 5)); + } + release(); + await files.flush(); + assert.deepEqual(written, ['1', '4']); + }); + it('writes the functions with paths relative to the project', async () => { + const dir = path.join(base, `functions-${Date.now()}`); + const files = new McpStateFiles({ dir }); + const root = path.resolve(base, 'p'); + const fn = { name: 'f', lineStart: 1, lineEnd: 3, lineCount: 3, complexity: 2, parameters: 1 }; + await files.updateFunctions(root, { root: path.join(root, 'pkg'), files: [{ path: 'src/a.ts', functions: [fn] }, { path: '../../elsewhere.ts', functions: [fn] }] }); + const snapshot = JSON.parse(fs.readFileSync(functionsFileOf(files.stateFile(root)), 'utf8')) as FunctionsSnapshot; + assert.deepEqual(snapshot.files, [{ path: 'pkg/src/a.ts', functions: [fn] }]); + await files.updateFunctions(root, null); + assert.deepEqual((JSON.parse(fs.readFileSync(functionsFileOf(files.stateFile(root)), 'utf8')) as FunctionsSnapshot).files, []); }); }); From d2c34b56a2a1ebf163af25ac26f809a94aea7162 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:49:52 +0000 Subject: [PATCH 33/74] refactor(core): split the hunk diff into small helpers under the complexity limit (#521) --- .../src/core/agent-review/hunkReview.ts | 80 ++++++++++++------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/apps/vscode-extension/src/core/agent-review/hunkReview.ts b/apps/vscode-extension/src/core/agent-review/hunkReview.ts index 549a09e6..8f3572a0 100644 --- a/apps/vscode-extension/src/core/agent-review/hunkReview.ts +++ b/apps/vscode-extension/src/core/agent-review/hunkReview.ts @@ -55,6 +55,20 @@ export function reviewLines(text: string): string[] { export function splitHunks(base: string, disk: string): ReviewHunk[] { const a = reviewLines(base); const b = reviewLines(disk); + const { start, endA, endB } = commonEnds(a, b); + const n = endA - start; + const m = endB - start; + if (n === 0 && m === 0) { + return []; + } + if (n === 0 || m === 0 || (n + 1) * (m + 1) > MAX_CELLS) { + return [makeHunk(start, a.slice(start, endA), start, b.slice(start, endB))]; + } + return walkHunks(a.slice(start, endA), b.slice(start, endB), start); +} + +/** Where the common prefix ends and the common suffix starts, on both sides. */ +function commonEnds(a: readonly string[], b: readonly string[]): { start: number; endA: number; endB: number } { let start = 0; while (start < a.length && start < b.length && a[start] === b[start]) { start += 1; @@ -65,54 +79,62 @@ export function splitHunks(base: string, disk: string): ReviewHunk[] { endA -= 1; endB -= 1; } - const n = endA - start; - const m = endB - start; - if (n === 0 && m === 0) { - return []; - } - if (n === 0 || m === 0 || (n + 1) * (m + 1) > MAX_CELLS) { - return [makeHunk(start, a.slice(start, endA), start, b.slice(start, endB))]; - } - // Longest common subsequence over the middle, filled from the end so the walk goes forwards. - const width = m + 1; - const table = new Uint32Array((n + 1) * width); - for (let i = n - 1; i >= 0; i -= 1) { - for (let j = m - 1; j >= 0; j -= 1) { - table[i * width + j] = a[start + i] === b[start + j] + return { start, endA, endB }; +} + +/** Longest common subsequence lengths of every suffix pair, filled from the end so the walk goes forwards. */ +function lcsTable(a: readonly string[], b: readonly string[]): Uint32Array { + const width = b.length + 1; + const table = new Uint32Array((a.length + 1) * width); + for (let i = a.length - 1; i >= 0; i -= 1) { + for (let j = b.length - 1; j >= 0; j -= 1) { + table[i * width + j] = a[i] === b[j] ? (table[(i + 1) * width + j + 1] ?? 0) + 1 : Math.max(table[(i + 1) * width + j] ?? 0, table[i * width + j + 1] ?? 0); } } + return table; +} + +/** The hunks of two differing middles (`offset`: their first line in the whole texts). */ +function walkHunks(a: readonly string[], b: readonly string[], offset: number): ReviewHunk[] { + const table = lcsTable(a, b); + const width = b.length + 1; const hunks: ReviewHunk[] = []; let i = 0; let j = 0; - let open: { baseStart: number; diskStart: number; baseLines: string[]; diskLines: string[] } | null = null; - const close = (): void => { - if (open) { - hunks.push(makeHunk(open.baseStart, open.baseLines, open.diskStart, open.diskLines)); - open = null; - } - }; - while (i < n || j < m) { - if (i < n && j < m && a[start + i] === b[start + j]) { - close(); + let open: OpenHunk | null = null; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + open = closeHunk(hunks, open); i += 1; j += 1; continue; } - open ??= { baseStart: start + i, diskStart: start + j, baseLines: [], diskLines: [] }; - if (j < m && (i >= n || (table[i * width + j + 1] ?? 0) >= (table[(i + 1) * width + j] ?? 0))) { - open.diskLines.push(b[start + j] ?? ''); + open ??= { baseStart: offset + i, diskStart: offset + j, baseLines: [], diskLines: [] }; + const takeDisk = j < b.length && (i >= a.length || (table[i * width + j + 1] ?? 0) >= (table[(i + 1) * width + j] ?? 0)); + if (takeDisk) { + open.diskLines.push(b[j] ?? ''); j += 1; } else { - open.baseLines.push(a[start + i] ?? ''); + open.baseLines.push(a[i] ?? ''); i += 1; } } - close(); + closeHunk(hunks, open); return hunks; } +interface OpenHunk { baseStart: number; diskStart: number; baseLines: string[]; diskLines: string[] } + +/** Ends the hunk being collected, if any (returns null, the new state of "the open hunk"). */ +function closeHunk(hunks: ReviewHunk[], open: OpenHunk | null): null { + if (open) { + hunks.push(makeHunk(open.baseStart, open.baseLines, open.diskStart, open.diskLines)); + } + return null; +} + /** * The disk text with the hunks in `ids` put back as they were in the base * (what "Undo" on those hunks writes). Throws `StaleHunkError` for an id that From bebb9269537b157314b7c718921837ab0106a4e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:49:52 +0000 Subject: [PATCH 34/74] feat(ide): per-hunk Keep/Undo and line comments sent back as one drafted prompt in the Changes tab (#521) --- apps/ide/eslint.config.mjs | 4 +- apps/ide/scripts/viteConfigs.mjs | 2 + .../src/renderer/agentFirst/agentFirst.css | 17 ++ .../src/renderer/agentFirst/agentWorkbench.ts | 15 +- .../src/renderer/agentFirst/changesDiff.ts | 228 +++++++++++++++++- .../src/renderer/agentFirst/changesReview.ts | 115 +++++++++ .../src/renderer/agentFirst/changesView.ts | 157 +++++++++++- apps/ide/src/shared/i18n/messages.en.ts | 27 +++ apps/ide/src/shared/i18n/messages.es.ts | 26 ++ apps/ide/test/changesReview.test.ts | 73 ++++++ apps/ide/tsconfig.web.json | 5 +- 11 files changed, 657 insertions(+), 12 deletions(-) create mode 100644 apps/ide/src/renderer/agentFirst/changesReview.ts create mode 100644 apps/ide/test/changesReview.test.ts diff --git a/apps/ide/eslint.config.mjs b/apps/ide/eslint.config.mjs index f6d2f85d..2e0ac13d 100644 --- a/apps/ide/eslint.config.mjs +++ b/apps/ide/eslint.config.mjs @@ -34,8 +34,8 @@ export default [ patterns: [ { group: ['node:*'], message: 'The renderer cannot use Node. Add a member to CodeXRApi instead.' }, { group: ['../main/*', '../sidecar/*', '../bridge/*'], message: 'The renderer may only import src/shared.' }, - // core/metrics, core/xr and core/agent-prompts are the exceptions: pure logic shared with the extension (#173/#178, #19, #514). - { group: ['@codexr/core/*', '!@codexr/core/metrics', '!@codexr/core/xr', '!@codexr/core/agent-prompts', '@codexr/logging/*'], message: 'The core runs in the main process only (#15), except the pure core/metrics, core/xr and core/agent-prompts. Add a member to CodeXRApi instead.' }, + // core/metrics, core/xr, core/agent-prompts and core/agent-review are the exceptions: pure logic shared with the extension (#173/#178, #19, #514, #521). + { group: ['@codexr/core/*', '!@codexr/core/metrics', '!@codexr/core/xr', '!@codexr/core/agent-prompts', '!@codexr/core/agent-review', '@codexr/logging/*'], message: 'The core runs in the main process only (#15), except the pure core/metrics, core/xr, core/agent-prompts and core/agent-review. Add a member to CodeXRApi instead.' }, ], }], 'no-restricted-properties': ['error', diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index f2d5ccf0..424f8401 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -164,6 +164,8 @@ export function rendererConfig(opts = {}) { { find: /^@codexr\/core\/analysis\/languages\//, replacement: `${CORE_SRC}/analysis/languages/` }, // #514: the "Ask agent" prompt templates (pure, type-only imports of core/metrics). { find: /^@codexr\/core\/agent-prompts\//, replacement: `${CORE_SRC}/agent-prompts/` }, + // #521: per-hunk review and the review-comment prompt (pure, no imports). + { find: /^@codexr\/core\/agent-review\//, replacement: `${CORE_SRC}/agent-review/` }, ] }, }; } diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 0b14828f..15815a7b 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -345,6 +345,23 @@ .af-changes-diff-note[hidden] { display: none; } .af-changes-diff-host { flex: 1; min-height: 0; } +/* ---- Hunks and line comments (#521) --------------------------------------- */ +.af-hunk-list { flex: none; max-height: 30%; margin: 0; padding: 2px 0; list-style: none; overflow: auto; border-bottom: 1px solid var(--line); } +.af-hunk-list[hidden] { display: none; } +.af-hunk { display: flex; align-items: center; gap: 10px; padding: 2px 12px; font-size: var(--fs-sm); } +.af-hunk:hover, .af-hunk:focus-within { background: var(--hover); } +.af-hunk-label { padding: 0; border: 0; background: none; color: var(--fg); font: inherit; font-family: var(--font-mono); cursor: pointer; white-space: pre; } +.af-hunk-label:hover { color: var(--accent); } +.af-comment-glyph { cursor: pointer; } +.af-comment-glyph::before { content: ''; position: absolute; left: 5px; top: 5px; width: 9px; height: 7px; border: 1px solid var(--muted); border-radius: var(--radius-sm); } +.af-comment-glyph.has-comment::before { border-color: var(--accent); background: var(--accent); } +.af-comment-box { box-sizing: border-box; display: flex; flex-direction: column; gap: 6px; padding: 8px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--raised); box-shadow: var(--shadow-sm); color: var(--fg); font-family: var(--font-ui); font-size: var(--fs-sm); } +.af-comment-input { box-sizing: border-box; width: 100%; resize: none; padding: 4px 6px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--editor); color: var(--fg); font: inherit; } +.af-comment-input:focus { outline: 1px solid var(--accent); outline-offset: -1px; } +.af-comment-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.af-comment-actions { display: flex; align-items: center; justify-content: flex-end; gap: 12px; } +.af-comment-hint { margin-right: auto; font-size: var(--fs-xs); } + /* ---- Worktree chats (AF12) ------------------------------------------------ */ .af-new-worktree { display: flex; align-items: center; gap: 6px; margin: -2px 12px 0; font-size: var(--fs-sm); color: var(--muted); cursor: pointer; } .af-new-worktree[hidden] { display: none; } diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 1c5ac548..b9cabad7 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -200,7 +200,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork } options.openFile(path); }; - const view = createChangesView(sessionId, { api, openFile, onStatus: options.onStatus }); + // #521: "Send comments" drafts the follow-up in this chat's own composer. + const view = createChangesView(sessionId, { api, openFile, onStatus: options.onStatus, draft: (text) => draftInSession(sessionId, text) }); const set = changesViews.get(sessionId) ?? new Set(); set.add(view); changesViews.set(sessionId, set); @@ -310,6 +311,18 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork return [...views].reverse().find((view) => view.sessionId === sessionId); } + /** #521: like `draftInChat`, but always in this chat (opened, or brought to the front, first). */ + async function draftInSession(sessionId: string, text: string): Promise { + try { + await openChat(sessionId); + } catch { + return false; + } + const view = viewOf(sessionId); + view?.insert(text); + return view !== undefined; + } + async function draftInChat(text: string): Promise { const target = activeChatId ?? lastChatId; if (target && viewOf(target)) { diff --git a/apps/ide/src/renderer/agentFirst/changesDiff.ts b/apps/ide/src/renderer/agentFirst/changesDiff.ts index 42f9f10a..dd5a8f70 100644 --- a/apps/ide/src/renderer/agentFirst/changesDiff.ts +++ b/apps/ide/src/renderer/agentFirst/changesDiff.ts @@ -1,3 +1,5 @@ +import type { editor as MonacoEditor } from 'monaco-editor'; +import { t } from '../../shared/i18n/i18n.ts'; import { monaco } from '../editor/monaco.ts'; /** @@ -6,17 +8,60 @@ import { monaco } from '../editor/monaco.ts'; * lazily by changesView.ts, in the editor's chunk (the tab only exists inside * the editor group, which has already loaded Monaco). The models' URIs carry * the file's path so Monaco picks the language from its extension. + * + * #521: line comments on the disk side. Hovering a line shows a comment + * glyph in its gutter; clicking it (or "Comment on This Line" in the context + * menu, for the keyboard) asks the view for a comment box, which shows inline + * under the line: a view zone keeps the room and an overlay widget, placed + * over it, holds the box, so the editor never takes the box's clicks or keys + * (the same split VS Code's own inline widgets use). */ +export interface CommentZone { + /** 1-based line of the disk side the comment is under. */ + readonly line: number; + readonly text: string; + /** A box to type in (else the saved comment, with Edit and Delete). */ + readonly editing: boolean; +} + +export interface CommentZoneHandlers { + save(line: number, text: string): void; + cancel(line: number): void; + edit(line: number): void; + remove(line: number): void; + /** Whether a key press in the box saves it (per-OS modifier). */ + isSaveKey(event: KeyboardEvent): boolean; + /** The save shortcut as the person types it, for the hint. */ + readonly saveKeyLabel: string; +} + +export interface ChangesDiffHooks { + /** The person asked to comment on a line of the disk side (gutter glyph or context menu). */ + onCommentRequest(line: number): void; +} + export interface ChangesDiff { show(path: string, oldText: string, newText: string): void; + /** Scrolls both sides to a disk line (a hunk picked in the list). */ + reveal(line: number): void; + /** Shows these comments under their lines, replacing the previous ones. */ + setComments(zones: readonly CommentZone[], handlers: CommentZoneHandlers): void; clear(): void; dispose(): void; } let sequence = 0; +const ZONE_GAP_PX = 8; +const FALLBACK_BOX_PX = 96; -export function createChangesDiff(host: HTMLElement): ChangesDiff { +interface ShownZone { + readonly zoneId: string; + readonly widget: MonacoEditor.IOverlayWidget; + readonly box: HTMLElement; +} + +export function createChangesDiff(host: HTMLElement, hooks?: ChangesDiffHooks): ChangesDiff { const editor = monaco.editor.createDiffEditor(host, { automaticLayout: true, readOnly: true, @@ -26,9 +71,168 @@ export function createChangesDiff(host: HTMLElement): ChangesDiff { fontSize: 13, scrollBeyondLastLine: false, }); + const modified = editor.getModifiedEditor(); let models: { original: ReturnType; modified: ReturnType } | null = null; + let zones: ShownZone[] = []; + const hover = modified.createDecorationsCollection(); + const marks = modified.createDecorationsCollection(); + const subscriptions: { dispose(): void }[] = []; + + if (hooks) { + modified.updateOptions({ glyphMargin: true }); + const glyphTypes = new Set([ + monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN, + monaco.editor.MouseTargetType.GUTTER_LINE_NUMBERS, + monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS, + monaco.editor.MouseTargetType.CONTENT_TEXT, + monaco.editor.MouseTargetType.CONTENT_EMPTY, + ]); + subscriptions.push( + modified.onMouseMove((event) => { + const line = event.target.position?.lineNumber; + if (!models || line === undefined || !glyphTypes.has(event.target.type)) { + hover.clear(); + return; + } + hover.set([{ range: new monaco.Range(line, 1, line, 1), options: { glyphMarginClassName: 'af-comment-glyph', glyphMarginHoverMessage: { value: t('changes.comment.add') } } }]); + }), + modified.onMouseLeave(() => hover.clear()), + modified.onMouseDown((event) => { + const line = event.target.position?.lineNumber; + if (models && line !== undefined && event.target.type === monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN) { + hooks.onCommentRequest(line); + } + }), + modified.addAction({ + id: 'codexr.changes.commentOnLine', + label: t('changes.comment.add'), + contextMenuGroupId: 'navigation', + contextMenuOrder: 0, + run: (target) => { + const line = target.getPosition()?.lineNumber; + if (models && line !== undefined) { + hooks.onCommentRequest(line); + } + }, + }), + modified.onDidLayoutChange(() => { + for (const zone of zones) { + sizeBox(zone.box); + modified.layoutOverlayWidget(zone.widget); + } + }), + ); + } + + function sizeBox(box: HTMLElement): void { + const layout = modified.getLayoutInfo(); + box.style.width = `${Math.max(160, layout.contentWidth - layout.verticalScrollbarWidth - 2 * ZONE_GAP_PX)}px`; + } + + function clearZones(): void { + if (zones.length === 0) { + return; + } + const removed = zones; + zones = []; + modified.changeViewZones((accessor) => { + for (const zone of removed) { + accessor.removeZone(zone.zoneId); + } + }); + for (const zone of removed) { + modified.removeOverlayWidget(zone.widget); + } + } + + function addZone(line: number, box: HTMLElement): void { + let top = -1e6; + const id = `codexr.changes.comment.${++sequence}`; + const widget: MonacoEditor.IOverlayWidget = { + getId: () => id, + getDomNode: () => box, + getPosition: () => ({ preference: { top, left: modified.getLayoutInfo().contentLeft + ZONE_GAP_PX } }), + }; + sizeBox(box); + modified.addOverlayWidget(widget); + const height = (box.offsetHeight || FALLBACK_BOX_PX) + ZONE_GAP_PX; + let zoneId = ''; + modified.changeViewZones((accessor) => { + zoneId = accessor.addZone({ + afterLineNumber: line, + heightInPx: height, + domNode: document.createElement('div'), + onDomNodeTop: (value) => { + top = value + ZONE_GAP_PX / 2; + modified.layoutOverlayWidget(widget); + }, + }); + }); + zones.push({ zoneId, widget, box }); + } + + function commentBox(zone: CommentZone, handlers: CommentZoneHandlers): HTMLElement { + const box = document.createElement('div'); + box.className = 'af-comment-box'; + box.dataset['line'] = String(zone.line); + box.setAttribute('role', 'group'); + box.setAttribute('aria-label', t('changes.comment.label', { line: zone.line })); + // The editor's keybindings listen on the document: keys typed here stay here. + box.addEventListener('keydown', (event) => event.stopPropagation()); + const button = (text: string, action: string, run: () => void, danger = false): HTMLButtonElement => { + const element = document.createElement('button'); + element.type = 'button'; + element.className = `af-link-button${danger ? ' is-danger' : ''}`; + element.textContent = text; + element.dataset['action'] = action; + element.addEventListener('click', run); + return element; + }; + const actions = document.createElement('div'); + actions.className = 'af-comment-actions'; + if (zone.editing) { + const input = document.createElement('textarea'); + input.className = 'af-comment-input'; + input.rows = 3; + input.value = zone.text; + input.placeholder = t('changes.comment.placeholder', { line: zone.line }); + input.setAttribute('aria-label', t('changes.comment.label', { line: zone.line })); + const save = (): void => { + if (input.value.trim() === '') { + handlers.cancel(zone.line); + } else { + handlers.save(zone.line, input.value); + } + }; + input.addEventListener('keydown', (event) => { + if (handlers.isSaveKey(event)) { + event.preventDefault(); + save(); + } else if (event.key === 'Escape') { + event.preventDefault(); + handlers.cancel(zone.line); + } + }); + const hint = document.createElement('span'); + hint.className = 'af-comment-hint muted'; + hint.textContent = t('changes.comment.hint', { key: handlers.saveKeyLabel }); + actions.append(hint, button(t('changes.comment.cancel'), 'cancel', () => handlers.cancel(zone.line)), button(t('changes.comment.save'), 'save', save)); + box.append(input, actions); + queueMicrotask(() => input.focus()); + } else { + const text = document.createElement('p'); + text.className = 'af-comment-text'; + text.textContent = zone.text; + actions.append(button(t('changes.comment.edit'), 'edit', () => handlers.edit(zone.line)), button(t('changes.comment.delete'), 'delete', () => handlers.remove(zone.line), true)); + box.append(text, actions); + } + return box; + } function release(): void { + clearZones(); + hover.clear(); + marks.clear(); editor.setModel(null); models?.original.dispose(); models?.modified.dispose(); @@ -46,9 +250,31 @@ export function createChangesDiff(host: HTMLElement): ChangesDiff { models = next; editor.setModel(next); }, + reveal(line) { + modified.revealLineInCenter(Math.max(1, line)); + modified.setPosition({ lineNumber: Math.max(1, line), column: 1 }); + }, + setComments(list, handlers) { + clearZones(); + if (!models) { + return; + } + const lineCount = models.modified.getLineCount(); + const shown = list.filter((zone) => zone.line >= 1 && zone.line <= lineCount); + marks.set(shown.filter((zone) => !zone.editing).map((zone) => ({ + range: new monaco.Range(zone.line, 1, zone.line, 1), + options: { glyphMarginClassName: 'af-comment-glyph has-comment', glyphMarginHoverMessage: { value: t('changes.comment.label', { line: zone.line }) } }, + }))); + for (const zone of shown) { + addZone(zone.line, commentBox(zone, handlers)); + } + }, clear: release, dispose() { release(); + for (const subscription of subscriptions) { + subscription.dispose(); + } editor.dispose(); }, }; diff --git a/apps/ide/src/renderer/agentFirst/changesReview.ts b/apps/ide/src/renderer/agentFirst/changesReview.ts new file mode 100644 index 00000000..3a9a0d33 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/changesReview.ts @@ -0,0 +1,115 @@ +import { hunkAtDiskLine, hunkDiskRange, reviewLines, splitHunks, type ReviewHunk } from '@codexr/core/agent-review/hunkReview'; +import { formatReviewComments, type ReviewComment } from '@codexr/core/agent-review/reviewComments'; +import { t } from '../../shared/i18n/i18n.ts'; +import type { ChangedFileView } from '../../shared/agentSession.ts'; + +/** + * #521 (O19): the logic of the Changes tab's per-hunk review and line + * comments, without DOM so it is unit-tested in Node. The hunks come from the + * core (core/agent-review, shared with the VS Code extension), computed on the + * same two texts the diff shows; the sidecar recomputes them on its own copy + * and refuses ids that no longer match. The comments are kept per chat tab + * until "Send comments" drafts them, as one prompt, in the chat's composer. + */ + +export interface DiffSides { + readonly oldText: string | null; + readonly newText: string | null; +} + +/** The hunks of a file the tab can review part by part (text on both sides), else null (per-file Keep/Undo only). */ +export function reviewableHunks(file: Pick, sides: DiffSides): ReviewHunk[] | null { + if (file.binary || file.status !== 'modified' || sides.oldText === null || sides.newText === null) { + return null; + } + return splitHunks(sides.oldText, sides.newText); +} + +/** The label of a hunk in the list: where it is on disk and how many lines it adds and removes. */ +export function hunkLabel(hunk: ReviewHunk): string { + const [first, last] = hunkDiskRange(hunk); + const where = hunk.diskLines.length === 0 + ? t('changes.hunk.removedAt', { line: first }) + : first === last ? t('changes.hunk.line', { line: first }) : t('changes.hunk.lines', { first, last }); + return `${where} +${hunk.diskLines.length} -${hunk.baseLines.length}`; +} + +/** The line a hunk's comment goes on: its first disk line. */ +export function hunkCommentLine(hunk: ReviewHunk): number { + return hunk.diskStart + 1; +} + +/** An error from keep-hunks or undo-hunks that means "the file changed since you looked" (the tab reloads it). */ +export function isStaleHunkError(message: string): boolean { + return /changed since its changes were shown/.test(message); +} + +export interface LineComment { + readonly id: number; + readonly path: string; + /** 1-based line of the disk side. */ + readonly line: number; + readonly text: string; + /** Quoted in the prompt: the hunk the line was in when the comment was written (null outside every hunk). */ + readonly hunk: Pick | null; + readonly lineText: string | null; +} + +export interface ReviewComments { + /** Adds a comment (or replaces the text of the one already on that line of that file). */ + set(path: string, line: number, text: string, sides: DiffSides): LineComment; + remove(id: number): void; + get(path: string, line: number): LineComment | null; + forPath(path: string): readonly LineComment[]; + readonly count: number; + /** The follow-up prompt with every comment ('' when there is none). */ + prompt(): string; + clear(): void; +} + +export function createReviewComments(): ReviewComments { + let next = 1; + let comments: LineComment[] = []; + return { + set(path, line, text, sides) { + const disk = sides.newText ?? ''; + const hunks = sides.oldText !== null && sides.newText !== null ? splitHunks(sides.oldText, sides.newText) : []; + const hunk = hunkAtDiskLine(hunks, line); + const lineText = reviewLines(disk)[line - 1] ?? null; + const existing = comments.find((entry) => entry.path === path && entry.line === line); + const comment: LineComment = { + id: existing?.id ?? next++, + path, + line, + text, + hunk: hunk ? { baseLines: hunk.baseLines, diskLines: hunk.diskLines } : null, + lineText, + }; + comments = existing ? comments.map((entry) => (entry === existing ? comment : entry)) : [...comments, comment]; + return comment; + }, + remove(id) { + comments = comments.filter((entry) => entry.id !== id); + }, + get(path, line) { + return comments.find((entry) => entry.path === path && entry.line === line) ?? null; + }, + forPath(path) { + return comments.filter((entry) => entry.path === path).sort((a, b) => a.line - b.line); + }, + get count() { + return comments.length; + }, + prompt() { + return formatReviewComments(comments.map((entry): ReviewComment => ({ path: entry.path, line: entry.line, comment: entry.text, hunk: entry.hunk, lineText: entry.lineText }))); + }, + clear() { + comments = []; + }, + }; +} + +/** Whether a key press in a comment box saves it: Cmd+Enter on macOS, Ctrl+Enter elsewhere. */ +export function isSaveKey(event: { readonly key: string; readonly ctrlKey: boolean; readonly metaKey: boolean }, platform: string): boolean { + return event.key === 'Enter' && (platform === 'darwin' ? event.metaKey : event.ctrlKey); +} diff --git a/apps/ide/src/renderer/agentFirst/changesView.ts b/apps/ide/src/renderer/agentFirst/changesView.ts index 98784855..266aa59a 100644 --- a/apps/ide/src/renderer/agentFirst/changesView.ts +++ b/apps/ide/src/renderer/agentFirst/changesView.ts @@ -1,7 +1,11 @@ +import type { ReviewHunk } from '@codexr/core/agent-review/hunkReview'; import type { AgentSessionsApi, ChangedFileView, ChatChanges } from '../../shared/agentSession.ts'; +import { t } from '../../shared/i18n/i18n.ts'; +import { formatKeybinding } from '../commands/keybindings.ts'; import { el, fileIcon } from '../dom.ts'; -import type { ChangesDiff } from './changesDiff.ts'; +import type { ChangesDiff, CommentZone, CommentZoneHandlers } from './changesDiff.ts'; import { changesSummary, nextSelection, statusLetter } from './changesModel.ts'; +import { createReviewComments, hunkCommentLine, hunkLabel, isSaveKey, isStaleHunkError, reviewableHunks, type DiffSides } from './changesReview.ts'; /** * The Changes tab of a chat (AF5, #270): every file the chat changed that @@ -9,12 +13,20 @@ import { changesSummary, nextSelection, statusLetter } from './changesModel.ts'; * selected one (its review base on the left, the disk on the right), and Keep * or Undo per file or for all. It refreshes when the chat reports a new * pending count, and when it is shown again. + * + * #521 (O19): a modified text file is also reviewed hunk by hunk (Keep or + * Undo per part, in a list above the diff), and any line of the disk side can + * carry a comment for the agent (the gutter glyph, the context menu or a + * hunk's Comment button). "Send comments" drafts them, as one follow-up + * prompt, in the chat's composer: the person reads it and presses Send. */ export interface ChangesViewDeps { readonly api: AgentSessionsApi; openFile(path: string): void; onStatus(message: string): void; + /** #521: puts text in this chat's composer without sending it; false when the chat could not be opened. */ + draft?(text: string): Promise; } export interface ChangesView { @@ -24,6 +36,7 @@ export interface ChangesView { } const CONFIRM_MS = 4000; +const PLATFORM = navigator.userAgent.includes('Macintosh') ? 'darwin' : navigator.userAgent.includes('Windows') ? 'win32' : 'linux'; export function createChangesView(sessionId: string, deps: ChangesViewDeps): ChangesView { let files: readonly ChangedFileView[] = []; @@ -33,10 +46,18 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha let diff: ChangesDiff | null = null; let diffLoading: Promise | null = null; let showToken = 0; + // #521: the hunks and both sides of the file on screen, the comments of this tab, the box being typed in. + let hunks: readonly ReviewHunk[] = []; + let sides: DiffSides | null = null; + let sidesPath: string | null = null; + const comments = createReviewComments(); + let editing: { readonly path: string; readonly line: number } | null = null; const summary = el('span', { className: 'af-changes-summary muted', attrs: { 'data-testid': 'af-changes-summary' } }); const keepAll = el('button', { className: 'secondary-button', text: 'Keep all', attrs: { type: 'button', 'data-testid': 'af-changes-keep-all', title: 'Accept every change as it is now' } }); const undoAll = el('button', { className: 'secondary-button is-danger', text: 'Undo all', attrs: { type: 'button', 'data-testid': 'af-changes-undo-all', title: 'Put every file back as it was before the chat changed it' } }); + const sendComments = el('button', { className: 'secondary-button', attrs: { type: 'button', hidden: '', 'data-testid': 'af-changes-send-comments', title: t('changes.comments.sendTitle') } }); + const hunkList = el('ol', { className: 'af-hunk-list', attrs: { hidden: '', 'aria-label': t('changes.hunks.label'), 'data-testid': 'af-changes-hunks' } }); const notice = el('p', { className: 'af-changes-notice muted', attrs: { hidden: '', role: 'status' } }); const list = el('ul', { className: 'af-changes-list', attrs: { 'aria-label': 'Changed files', 'data-testid': 'af-changes-list' } }); const diffTitle = el('span', { className: 'af-changes-diff-title' }); @@ -47,13 +68,14 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha el('header', { className: 'af-changes-header' }, [ el('div', { className: 'af-chat-heading' }, [el('h2', { className: 'af-chat-title', text: 'Changes' }), summary]), el('span', { className: 'af-spacer' }), + sendComments, keepAll, undoAll, ]), notice, el('div', { className: 'af-changes-body' }, [ list, - el('div', { className: 'af-changes-diff' }, [el('div', { className: 'af-changes-diff-head' }, [diffTitle, el('span', { className: 'af-spacer' }), openButton]), diffNote, diffHost]), + el('div', { className: 'af-changes-diff' }, [el('div', { className: 'af-changes-diff-head' }, [diffTitle, el('span', { className: 'af-spacer' }), openButton]), diffNote, hunkList, diffHost]), ]), ]); @@ -62,6 +84,7 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha deps.openFile(selected); } }); + sendComments.addEventListener('click', () => void draftComments()); keepAll.addEventListener('click', () => void act(() => deps.api.keepChanges(sessionId, 'all'), 'Kept every change.')); let undoArmed: ReturnType | null = null; undoAll.addEventListener('click', () => { @@ -99,9 +122,10 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha } function renderButtons(): void { + renderSendComments(); keepAll.disabled = busy || files.length === 0; undoAll.disabled = busy || files.length === 0; - for (const button of list.querySelectorAll('button')) { + for (const button of [...list.querySelectorAll('button'), ...hunkList.querySelectorAll('button')]) { button.disabled = busy; } } @@ -174,7 +198,7 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha function loadDiff(): Promise { diffLoading ??= import('./changesDiff.ts').then(({ createChangesDiff }) => { - const created = createChangesDiff(diffHost); + const created = createChangesDiff(diffHost, { onCommentRequest: openComment }); if (disposed) { created.dispose(); } else { @@ -191,6 +215,9 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha diffTitle.textContent = file ? file.path : ''; openButton.hidden = !file || file.status === 'deleted'; diffNote.hidden = true; + if (!file || file.binary) { + setHunks([], null, null); + } if (!file) { diff?.clear(); return; @@ -202,11 +229,13 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha return; } try { - const [editor, sides] = await Promise.all([loadDiff(), deps.api.changeDiff(sessionId, file.path)]); + const [editor, shown] = await Promise.all([loadDiff(), deps.api.changeDiff(sessionId, file.path)]); if (token !== showToken || disposed) { return; } - editor.show(file.path, sides.oldText ?? '', sides.newText ?? ''); + editor.show(file.path, shown.oldText ?? '', shown.newText ?? ''); + setHunks(reviewableHunks(file, shown) ?? [], shown, file.path); + renderComments(); } catch (error) { if (token === showToken) { diffNote.hidden = false; @@ -215,6 +244,122 @@ export function createChangesView(sessionId: string, deps: ChangesViewDeps): Cha } } + // ---- Hunks (#521) ---------------------------------------------------------- + function setHunks(next: readonly ReviewHunk[], nextSides: DiffSides | null, path: string | null): void { + hunks = next; + sides = nextSides; + sidesPath = path; + hunkList.hidden = hunks.length === 0; + hunkList.replaceChildren(...hunks.map((hunk, index) => { + const jump = el('button', { className: 'af-hunk-label', text: hunkLabel(hunk), attrs: { type: 'button', title: t('changes.hunk.show') } }); + jump.addEventListener('click', () => diff?.reveal(hunkCommentLine(hunk))); + const keep = el('button', { className: 'af-link-button', text: t('changes.hunk.keep'), attrs: { type: 'button', title: t('changes.hunk.keepTitle'), 'data-action': 'keep-hunk' } }); + const undo = el('button', { className: 'af-link-button is-danger', text: t('changes.hunk.undo'), attrs: { type: 'button', title: t('changes.hunk.undoTitle'), 'data-action': 'undo-hunk' } }); + const comment = el('button', { className: 'af-link-button', text: t('changes.hunk.comment'), attrs: { type: 'button', title: t('changes.hunk.commentTitle'), 'data-action': 'comment-hunk' } }); + keep.addEventListener('click', () => void actOnHunk('keep', hunk)); + undo.addEventListener('click', () => void actOnHunk('undo', hunk)); + comment.addEventListener('click', () => { + diff?.reveal(hunkCommentLine(hunk)); + openComment(hunkCommentLine(hunk)); + }); + return el('li', { className: 'af-hunk', attrs: { 'data-hunk': hunk.id, 'data-index': String(index) } }, [jump, el('span', { className: 'af-spacer' }), comment, keep, undo]); + })); + renderButtons(); + } + + async function actOnHunk(kind: 'keep' | 'undo', hunk: ReviewHunk): Promise { + const path = sidesPath; + if (busy || !path) { + return; + } + busy = true; + renderButtons(); + try { + apply(await (kind === 'keep' ? deps.api.keepHunks(sessionId, path, [hunk.id]) : deps.api.undoHunks(sessionId, path, [hunk.id]))); + deps.onStatus(t(kind === 'keep' ? 'changes.hunk.kept' : 'changes.hunk.undone', { path })); + } catch (error) { + const message = errorText(error); + if (isStaleHunkError(message)) { + deps.onStatus(t('changes.hunk.stale', { path })); + void refresh(); + } else { + deps.onStatus(message); + } + } finally { + busy = false; + renderButtons(); + } + } + + // ---- Line comments (#521) ------------------------------------------------ + function openComment(line: number): void { + if (!selected || !sides || sidesPath !== selected) { + return; + } + editing = { path: selected, line }; + renderComments(); + } + + const zoneHandlers: CommentZoneHandlers = { + save(line, text) { + if (sidesPath && sides) { + comments.set(sidesPath, line, text.trim(), sides); + } + editing = null; + renderComments(); + }, + cancel() { + editing = null; + renderComments(); + }, + edit(line) { + openComment(line); + }, + remove(line) { + const existing = sidesPath ? comments.get(sidesPath, line) : null; + if (existing) { + comments.remove(existing.id); + } + renderComments(); + }, + isSaveKey: (event) => isSaveKey(event, PLATFORM), + saveKeyLabel: formatKeybinding('CmdOrCtrl+Enter', PLATFORM), + }; + + function renderComments(): void { + renderSendComments(); + if (!diff || !sidesPath || sidesPath !== selected) { + return; + } + const open = editing?.path === sidesPath ? editing.line : null; + const zones: CommentZone[] = comments.forPath(sidesPath).map((entry) => ({ line: entry.line, text: entry.text, editing: entry.line === open })); + if (open !== null && !zones.some((zone) => zone.line === open)) { + zones.push({ line: open, text: '', editing: true }); + } + diff.setComments(zones, zoneHandlers); + } + + function renderSendComments(): void { + sendComments.hidden = comments.count === 0 || !deps.draft; + sendComments.textContent = t('changes.comments.send', { count: comments.count }); + sendComments.disabled = busy; + } + + async function draftComments(): Promise { + const text = comments.prompt(); + if (!deps.draft || text === '') { + return; + } + if (await deps.draft(text)) { + comments.clear(); + editing = null; + renderComments(); + deps.onStatus(t('changes.comments.drafted')); + } else { + deps.onStatus(t('changes.comments.noChat')); + } + } + async function refresh(): Promise { try { apply(await deps.api.changes(sessionId)); diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 719ffebb..df9e4ef8 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -780,6 +780,33 @@ export const en = { 'askAgent.drafted': 'Drafted a prompt about \'{name}\' in the chat: review it, then press Send.', 'askAgent.noFunction': 'Code-XR has not measured a function here. Analyse the project to measure its functions.', 'askAgent.noHotspot': 'No hotspot yet: analyse the project to measure its functions.', + // #521: the Changes tab, part by part, and line comments for the agent (the drafted prompt stays in English). + 'changes.hunks.label': 'Parts of this change', + 'changes.hunk.line': 'Line {line}', + 'changes.hunk.lines': 'Lines {first}-{last}', + 'changes.hunk.removedAt': 'Removed before line {line}', + 'changes.hunk.show': 'Show this part in the diff', + 'changes.hunk.keep': 'Keep', + 'changes.hunk.keepTitle': 'Accept this part of the change', + 'changes.hunk.undo': 'Undo', + 'changes.hunk.undoTitle': 'Put this part back as it was', + 'changes.hunk.comment': 'Comment', + 'changes.hunk.commentTitle': 'Leave a comment on this part for the agent', + 'changes.hunk.kept': 'Kept a part of {path}.', + 'changes.hunk.undone': 'Undid a part of {path}.', + 'changes.hunk.stale': '{path} changed since its changes were shown; they are shown again.', + 'changes.comment.add': 'Comment on This Line', + 'changes.comment.label': 'Comment on line {line}', + 'changes.comment.placeholder': 'What should the agent do about line {line}?', + 'changes.comment.hint': '{key} to save, Esc to cancel', + 'changes.comment.save': 'Save', + 'changes.comment.cancel': 'Cancel', + 'changes.comment.edit': 'Edit', + 'changes.comment.delete': 'Delete', + 'changes.comments.send': 'Send comments ({count})', + 'changes.comments.sendTitle': 'Put one follow-up message with every comment in the chat box, to read and send', + 'changes.comments.drafted': 'The comments are in the chat box: review them, then press Send.', + 'changes.comments.noChat': 'Could not open the chat to put the comments in.', }; export type MessageKey = keyof typeof en; diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 817d5016..d950ae8c 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -783,4 +783,30 @@ export const es: Readonly> = { 'askAgent.drafted': 'Petición sobre \'{name}\' redactada en el chat: revísala y pulsa Enviar.', 'askAgent.noFunction': 'Code-XR no ha medido ninguna función aquí. Analiza el proyecto para medir sus funciones.', 'askAgent.noHotspot': 'Aún no hay puntos críticos: analiza el proyecto para medir sus funciones.', + 'changes.hunks.label': 'Partes de este cambio', + 'changes.hunk.line': 'Línea {line}', + 'changes.hunk.lines': 'Líneas {first}-{last}', + 'changes.hunk.removedAt': 'Eliminado antes de la línea {line}', + 'changes.hunk.show': 'Mostrar esta parte en el diff', + 'changes.hunk.keep': 'Conservar', + 'changes.hunk.keepTitle': 'Aceptar esta parte del cambio', + 'changes.hunk.undo': 'Deshacer', + 'changes.hunk.undoTitle': 'Dejar esta parte como estaba', + 'changes.hunk.comment': 'Comentar', + 'changes.hunk.commentTitle': 'Dejar un comentario sobre esta parte para el agente', + 'changes.hunk.kept': 'Se conservó una parte de {path}.', + 'changes.hunk.undone': 'Se deshizo una parte de {path}.', + 'changes.hunk.stale': '{path} cambió desde que se mostraron sus cambios; se muestran de nuevo.', + 'changes.comment.add': 'Comentar esta línea', + 'changes.comment.label': 'Comentario en la línea {line}', + 'changes.comment.placeholder': '¿Qué debe hacer el agente con la línea {line}?', + 'changes.comment.hint': '{key} para guardar, Esc para cancelar', + 'changes.comment.save': 'Guardar', + 'changes.comment.cancel': 'Cancelar', + 'changes.comment.edit': 'Editar', + 'changes.comment.delete': 'Eliminar', + 'changes.comments.send': 'Enviar comentarios ({count})', + 'changes.comments.sendTitle': 'Poner en el cuadro del chat un único mensaje de seguimiento con todos los comentarios, para leerlo y enviarlo', + 'changes.comments.drafted': 'Los comentarios están en el cuadro del chat: revísalos y pulsa Enviar.', + 'changes.comments.noChat': 'No se pudo abrir el chat para poner los comentarios.', }; diff --git a/apps/ide/test/changesReview.test.ts b/apps/ide/test/changesReview.test.ts new file mode 100644 index 00000000..7c5fb8bf --- /dev/null +++ b/apps/ide/test/changesReview.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { splitHunks } from '@codexr/core/agent-review/hunkReview'; +import { setLocale } from '../src/shared/i18n/i18n.ts'; +import { createReviewComments, hunkCommentLine, hunkLabel, isSaveKey, isStaleHunkError, reviewableHunks } from '../src/renderer/agentFirst/changesReview.ts'; + +/** #521 (O19): the Changes tab's per-hunk review and line comments, without DOM. */ + +afterEach(() => setLocale('en')); + +const modified = { binary: false, status: 'modified' as const }; + +describe('Changes tab: hunks (#521)', () => { + it('offers part-by-part review only for a modified text file', () => { + const sides = { oldText: 'a\nb\n', newText: 'a\nB\n' }; + assert.equal(reviewableHunks(modified, sides)?.length, 1); + assert.equal(reviewableHunks({ binary: true, status: 'modified' }, sides), null); + assert.equal(reviewableHunks({ binary: false, status: 'added' }, { oldText: null, newText: 'x' }), null); + assert.equal(reviewableHunks({ binary: false, status: 'deleted' }, { oldText: 'x', newText: null }), null); + }); + + it('labels a hunk by its disk lines and its counts, in both languages', () => { + const [one] = splitHunks('a\nb\nc\n', 'a\nB\nc\n'); + const [many] = splitHunks('a\nb\nc\n', 'a\nB1\nB2\nB3\nc\n'); + const [gone] = splitHunks('a\nb\nc\n', 'a\nc\n'); + assert.ok(one && many && gone); + assert.equal(hunkLabel(one), 'Line 2 +1 -1'); + assert.equal(hunkLabel(many), 'Lines 2-4 +3 -1'); + assert.equal(hunkLabel(gone), 'Removed before line 2 +0 -1'); + assert.equal(hunkCommentLine(many), 2); + setLocale('es'); + assert.equal(hunkLabel(many), 'Líneas 2-4 +3 -1'); + }); + + it('recognises the stale-hunk refusal from the sidecar, wrapped or not', () => { + assert.equal(isStaleHunkError('The file changed since its changes were shown. Look at them again before keeping or undoing a part.'), true); + assert.equal(isStaleHunkError('Checkpoints are off'), false); + }); + + it('saves with Cmd+Enter on macOS and Ctrl+Enter elsewhere', () => { + assert.equal(isSaveKey({ key: 'Enter', ctrlKey: false, metaKey: true }, 'darwin'), true); + assert.equal(isSaveKey({ key: 'Enter', ctrlKey: true, metaKey: false }, 'darwin'), false); + assert.equal(isSaveKey({ key: 'Enter', ctrlKey: true, metaKey: false }, 'win32'), true); + assert.equal(isSaveKey({ key: 'Enter', ctrlKey: false, metaKey: false }, 'linux'), false); + }); +}); + +describe('Changes tab: line comments (#521)', () => { + it('keeps one comment per line, quotes its hunk, and drafts one prompt for all files', () => { + const comments = createReviewComments(); + const sides = { oldText: 'one\r\ntwo\r\nthree\r\n', newText: 'one\r\nTWO\r\nthree\r\n' }; + const first = comments.set('src/a.ts', 2, 'Why upper case?', sides); + assert.deepEqual(first.hunk, { baseLines: ['two\r'], diskLines: ['TWO\r'] }); + const replaced = comments.set('src/a.ts', 2, 'Keep it lower case.', sides); + assert.equal(replaced.id, first.id, 'the same line edits its comment'); + const outside = comments.set('src/a.ts', 3, 'Fine.', sides); + assert.equal(outside.hunk, null); + assert.equal(outside.lineText, 'three\r'); + comments.set('lib/b.ts', 1, 'Rename.', { oldText: 'x\n', newText: 'y\n' }); + assert.equal(comments.count, 3); + assert.deepEqual(comments.forPath('src/a.ts').map((entry) => entry.line), [2, 3]); + assert.equal(comments.get('src/a.ts', 3)?.text, 'Fine.'); + const prompt = comments.prompt(); + assert.match(prompt, /^I reviewed your changes/); + assert.ok(prompt.indexOf('1. lib/b.ts:1') < prompt.indexOf('2. src/a.ts:2'), 'sorted by path'); + assert.match(prompt, /2\. src\/a\.ts:2 — Keep it lower case\.\n {3}```diff\n {3}-two\n {3}\+TWO\n {3}```/); + assert.match(prompt, /3\. src\/a\.ts:3 — Fine\.\n {3}```\n {3}three\n {3}```/); + comments.remove(outside.id); + assert.equal(comments.count, 2); + comments.clear(); + assert.equal(comments.prompt(), ''); + }); +}); diff --git a/apps/ide/tsconfig.web.json b/apps/ide/tsconfig.web.json index 2e0e3ae6..99d53cc7 100644 --- a/apps/ide/tsconfig.web.json +++ b/apps/ide/tsconfig.web.json @@ -1,5 +1,5 @@ { - "//": "Renderer: DOM types only. No Node types, so a Node API used here fails the type check. Of the core it may use only the pure core/metrics (#173/#178), core/xr (#19) and core/analysis/languages (#398) and core/agent-prompts (#514).", + "//": "Renderer: DOM types only. No Node types, so a Node API used here fails the type check. Of the core it may use only the pure core/metrics (#173/#178), core/xr (#19) and core/analysis/languages (#398) core/agent-prompts (#514) and core/agent-review (#521).", "extends": "./tsconfig.base.json", "compilerOptions": { "lib": ["ES2023", "DOM", "DOM.Iterable"], @@ -9,7 +9,8 @@ "@codexr/core/metrics/*": ["./.core-types/core/metrics/*"], "@codexr/core/xr/*": ["./.core-types/core/xr/*"], "@codexr/core/analysis/languages/*": ["./.core-types/core/analysis/languages/*"], - "@codexr/core/agent-prompts/*": ["./.core-types/core/agent-prompts/*"] + "@codexr/core/agent-prompts/*": ["./.core-types/core/agent-prompts/*"], + "@codexr/core/agent-review/*": ["./.core-types/core/agent-review/*"] } }, "include": ["src/renderer/**/*.ts", "src/shared/**/*.ts", "src/bridge/**/*.ts", "src/sceneBridge/**/*.ts"] From a7e39a4b21731be97b97bf40e86fc976c9c7fd5a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:53:28 +0000 Subject: [PATCH 35/74] fix(ide): count_of is a Unix test helper, so Windows clippy sees no dead code (#507) --- apps/ide/src-tauri/src/terminal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/ide/src-tauri/src/terminal.rs b/apps/ide/src-tauri/src/terminal.rs index 09ff063d..4b1d48bc 100644 --- a/apps/ide/src-tauri/src/terminal.rs +++ b/apps/ide/src-tauri/src/terminal.rs @@ -279,7 +279,7 @@ impl Terminals { } } - #[cfg(test)] + #[cfg(all(test, unix))] pub fn count_of(&self, owner: &str) -> usize { self.running.lock().unwrap().values().filter(|running| running.owner.as_deref() == Some(owner)).count() } From 6bddfb253167c399e18863f52f5e6083f3cf78bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:54:30 +0000 Subject: [PATCH 36/74] feat(ide): agent cost meter and system notifications (#523) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ACP usage_update.cost is carried to the usage event, the session state and the chat's context meter ("Context 41k / 200k · $0.42"; no figure when the agent reports none), and what each update adds in US dollars is recorded in the usage ledger as reported cost. Cost formatting and the pure shouldNotifySystem decision live in core/agent-prompts/agentActivity.ts. With the window unfocused, a finished, failed or approval-waiting agent also raises an OS notification through tauri-plugin-notification (renderer -> agentSessions.systemNotify -> main checks focus, ownership and bounds the text -> host.notification.show); approvals request user attention. A click focuses the window and opens the chat. New setting agents.systemNotifications (on by default). --- apps/ide/README.md | 1 + apps/ide/src-tauri/Cargo.lock | 164 +++++++++++++++++- apps/ide/src-tauri/Cargo.toml | 2 + apps/ide/src-tauri/src/host.rs | 2 + apps/ide/src-tauri/src/main.rs | 5 + apps/ide/src-tauri/src/notifications.rs | 130 ++++++++++++++ apps/ide/src/bridge/codexrApi.ts | 3 +- apps/ide/src/main/agentSessions/acpMapping.ts | 8 +- .../main/agentSessions/agentSessionService.ts | 34 ++++ .../main/agentSessions/agentSessionsIpc.ts | 2 + .../agentSessions/agentSessionsRuntime.ts | 34 ++++ .../src/main/agentSessions/systemNotices.ts | 35 ++++ apps/ide/src/main/boot.ts | 2 +- .../src/renderer/agentFirst/agentWorkbench.ts | 28 ++- apps/ide/src/renderer/agentFirst/chatView.ts | 9 +- .../src/renderer/agentFirst/sessionsView.ts | 2 +- apps/ide/src/renderer/agents/usageSection.ts | 2 +- apps/ide/src/renderer/main.ts | 4 +- apps/ide/src/shared/agentSession.ts | 43 ++++- apps/ide/src/shared/i18n/messages.en.ts | 5 + apps/ide/src/shared/i18n/messages.es.ts | 5 + apps/ide/src/shared/i18n/settings.es.ts | 4 + apps/ide/src/shared/settings.ts | 3 + apps/ide/src/sidecar/index.ts | 4 +- apps/ide/src/sidecar/rpc.ts | 3 +- apps/ide/src/sidecar/tauriHost.ts | 19 ++ apps/ide/test/agentActivity.test.ts | 87 ++++++++++ apps/ide/test/agentSessions.test.ts | 35 +++- .../src/core/agent-prompts/agentActivity.ts | 123 +++++++++++++ .../test/agent_prompts/agentActivity.test.cjs | 12 ++ 30 files changed, 785 insertions(+), 25 deletions(-) create mode 100644 apps/ide/src-tauri/src/notifications.rs create mode 100644 apps/ide/src/main/agentSessions/systemNotices.ts create mode 100644 apps/ide/test/agentActivity.test.ts create mode 100644 apps/vscode-extension/src/core/agent-prompts/agentActivity.ts create mode 100644 apps/vscode-extension/test/agent_prompts/agentActivity.test.cjs diff --git a/apps/ide/README.md b/apps/ide/README.md index 34b7d428..31eadd27 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -401,6 +401,7 @@ The IDE opens in the **Agent** layout: chats with the person's own coding agents - **First run (AF13, #278):** until the person skips it or has a chat, the editor area's welcome view carries a three-step guide (open a folder, pick an agent and install it or sign in, start the first chat), each step drawn from the window's real state and redrawn as it changes (`gettingStartedView.ts`, its model in `agentSetupModel.ts`). *Skip* or the first chat sets `codexr.agentFirst.onboarded` and it never opens on its own again; *Chat: Show Getting Started* reopens it as a tab (`guide:getting-started`). - **Welcome and guided tour (CI12, #404):** on the first launch, once the window has settled and after the launch animation if one plays, a welcome card offers *Take the tour* or *Skip*; the tour spotlights the activity bar, Chats, the Explorer, the Code-XR view, the editor, the live analysis column, the status bar and the command palette, one card at a time with Next / Back / Skip (Esc skips, the arrows move, the focus stays in the card). Steps whose part is missing in the layout are skipped (the live column in Classic mode without a scene); the side-bar view is shown for its step and restored at the end. The scene's native view is taken off the screen while the tour is open (`ScenePanel.setSuspended`), since nothing can be drawn over it. Taking or skipping it sets `codexr.tour.done` in localStorage; *Help: Start the Guided Tour* (palette and Help menu) opens it again, and `workbench.welcomeTour` (off in the smoke run) stops it opening on its own. Model and placement in `tour/tourModel.ts` (unit-tested in `test/tour.test.ts`), every string in `tour/tourStrings.ts`, the drawing in `tour/tourView.ts`. The Get started guide is untouched and waits in the editor area underneath. - **Signing in (AF14, #297):** a terminal sign-in method runs the agent's login program directly, with no shell, in a terminal tab of its own (`TerminalHost.runProgram`, shown through `TerminalPanel.runTask`), so nothing is typed into the person's shell; the agent is checked again when it ends. For Claude Code the login hint points at the adapter script with `--cli`; the IDE runs the native `claude` binary that ships beside the adapter (`nativeLoginProgram`, or `CLAUDE_CODE_EXECUTABLE`) instead, because on Windows a console program started through the IDE's own GUI executable gets no keyboard or output from the terminal. Any other terminal sign-in that would still run JavaScript through the IDE's executable runs with the system's Node.js on Windows, or says how to run it yourself (`consoleLoginProgram`); the smoke run checks on all three platforms that typing reaches a program in a terminal. *API key* methods (Codex and Gemini CLI mark them with `_meta["api-key"].provider`) open a password field: the key is kept by the OS secret store (`agent-keys.json`, the same `KeyVault` as the built-in agent's keys), handed to that agent alone as its provider's variable (`OPENAI_API_KEY`/`CODEX_API_KEY`, `GEMINI_API_KEY`, `ANTHROPIC_API_KEY`) on every start, dropped if the agent refuses it, and forgotten with *Forget key*. Agent-side sign-ins (ChatGPT, Google) send `initialize` first and get `DISPLAY`/`WAYLAND_DISPLAY` so the agent can open the browser on Linux. *Check* asks `auth/status` again while the agent answers `unknown` (Codex reads its login in the background; Claude Code's own read can time out on a cold start). *Check* asks the agent who is signed in with `auth/status` (an ACP draft that Claude Code's and Codex's adapters answer) and reports *Needs login* or *Signed in as ...*, because Claude Code opens sessions while signed out and only refuses the first prompt. Agents that cannot say are judged by `session/new`. +- **Cost and system notifications (O21, #523):** the context meter of a chat adds the session cost an ACP agent reports in `usage_update.cost` ("Context 41k / 200k · $0.42", formatted with `Intl.NumberFormat` by `core/agent-prompts/agentActivity.ts`); an agent that reports none (a subscription) shows no figure, never $0.00. What each update adds in US dollars is recorded in the usage ledger as reported cost (Agents > Usage and budget); other currencies and units are shown in the chat only. When the window is not focused and an agent finishes, fails or asks for an approval, `agents.systemNotifications` (on by default) adds an operating-system notification beside the in-app toast: the renderer decides (`shouldNotifySystem`, pure), `agentSessions.systemNotify` asks main, which refuses while the window is focused or for another window's chat and bounds the text (`systemNotices.ts`), and the core shows it with `tauri-plugin-notification` (`src-tauri/src/notifications.rs`); approvals also call `request_user_attention` (taskbar flash, Dock bounce, urgency hint). The page never calls the plugin: the app capability grants none of its commands. A click focuses the window and opens the chat where the platform reports clicks (Windows while the toast is on screen, not from the Action Center; macOS; Linux servers with actions); elsewhere the in-app toast's *Open chat* remains. Dev builds: on Windows a build in `target\debug` or `target\release` shows its toasts as PowerShell's, and one elsewhere that is not installed may be dropped (toasts need the installed app's AppUserModelID, `org.codexr.ide`); on macOS `tauri dev` shows them as Terminal's. - **Importing an agent's chats (AF15, #298):** *Import chats* on a ready agent lists the chats it keeps for the open folder (`session/list`, newest first, at most 200, none already in the IDE) and adds the chosen ones; each reads its messages from the agent's `session/load` replay the first time it opens (`historyPending`), then continues the same agent session. The agent reads its own history files; the IDE never opens them. ## VS Code extensions (stream `ide-extensions`, epic #251) diff --git a/apps/ide/src-tauri/Cargo.lock b/apps/ide/src-tauri/Cargo.lock index c5d3c2f6..8918ba2a 100644 --- a/apps/ide/src-tauri/Cargo.lock +++ b/apps/ide/src-tauri/Cargo.lock @@ -547,6 +547,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "chrono" version = "0.4.45" @@ -608,6 +619,7 @@ dependencies = [ "tauri-build", "tauri-plugin-clipboard-manager", "tauri-plugin-dialog", + "tauri-plugin-notification", "tauri-plugin-opener", "tauri-plugin-single-instance", "tokio", @@ -1534,6 +1546,7 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", ] [[package]] @@ -2535,6 +2548,20 @@ version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2", + "objc2-foundation", + "time", + "uuid", +] + [[package]] name = "markup5ever" version = "0.40.0" @@ -2735,6 +2762,20 @@ dependencies = [ "xxhash-rust", ] +[[package]] +name = "notify-rust" +version = "4.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus 6.6.0", +] + [[package]] name = "notify-types" version = "2.3.1" @@ -3436,7 +3477,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", "rand_chacha", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -3446,7 +3498,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -3458,6 +3510,12 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -3645,7 +3703,7 @@ dependencies = [ "bytes", "crc32c", "integer-encoding", - "rand", + "rand 0.8.8", "snap", ] @@ -3728,7 +3786,7 @@ dependencies = [ "hkdf", "num", "once_cell", - "rand", + "rand 0.8.8", "serde", "sha2 0.10.9", "zbus 4.4.0", @@ -4492,6 +4550,26 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-notification" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f" +dependencies = [ + "log", + "notify-rust", + "rand 0.10.4", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "time", + "url", + "zbus 5.19.0", +] + [[package]] name = "tauri-plugin-opener" version = "2.7.3" @@ -4629,6 +4707,17 @@ dependencies = [ "toml", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5999,7 +6088,7 @@ dependencies = [ "hex", "nix 0.29.0", "ordered-stream", - "rand", + "rand 0.8.8", "serde", "serde_repr", "sha1", @@ -6048,6 +6137,33 @@ dependencies = [ "zvariant 5.15.1", ] +[[package]] +name = "zbus" +version = "6.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0ea2f1a9da0558d47969ca08a4bb5397aa0a2d1e700e599c72f2064b2c0abe" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros 6.6.0", + "zbus_utils", + "zcheapstr", + "zruntime", +] + [[package]] name = "zbus_macros" version = "4.4.0" @@ -6076,6 +6192,18 @@ dependencies = [ "zvariant_utils 4.2.0", ] +[[package]] +name = "zbus_macros" +version = "6.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6101224e3a5ff01f23f19510837e30aae926060869781b79f7b230203420c26" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_utils", +] + [[package]] name = "zbus_names" version = "3.0.0" @@ -6098,6 +6226,19 @@ dependencies = [ "zvariant 5.15.1", ] +[[package]] +name = "zbus_utils" +version = "6.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b180774785a9d3ae6695dbf0d0baac91eb4facef62f7be0007d3e3965d86fc6" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] + [[package]] name = "zcheapstr" version = "1.4.0" @@ -6215,6 +6356,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zruntime" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e" +dependencies = [ + "futures-core", + "futures-io", + "rustix", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "zune-core" version = "0.5.4" diff --git a/apps/ide/src-tauri/Cargo.toml b/apps/ide/src-tauri/Cargo.toml index 5c476ae5..c7b42670 100644 --- a/apps/ide/src-tauri/Cargo.toml +++ b/apps/ide/src-tauri/Cargo.toml @@ -24,6 +24,8 @@ tauri-plugin-dialog = "2" tauri-plugin-clipboard-manager = "2" tauri-plugin-opener = "2" tauri-plugin-single-instance = "2" +# #523: system notifications when an agent finishes or needs approval while the window is in the background. +tauri-plugin-notification = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" base64 = "0.22" diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index cd3f5f18..3c0de20d 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -202,6 +202,8 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) window.destroy().map_err(|error| error.to_string())?; Ok(Value::Null) } + // #523: an agent finished or needs approval while the window is in the background. + "notification.show" => crate::notifications::show(app, params), "dialog.open" => open_dialog(app, params), "dialog.save" => save_dialog(app, params), "dialog.message" => message_dialog(app, params), diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index c40c272a..f896e228 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -31,6 +31,7 @@ mod menu; mod message_box; mod migration; mod native; +mod notifications; #[cfg(test)] mod parity; mod permissions; @@ -256,6 +257,8 @@ fn main() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_clipboard_manager::init()) .plugin(tauri_plugin_opener::init()) + // #523: agent notifications while the window is in the background (notifications.rs). + .plugin(tauri_plugin_notification::init()) .manage(sidecar.clone()) .manage(call_order.clone()) .manage(shell.clone()) @@ -307,6 +310,8 @@ fn main() { let layout = layout.clone(); move |app| { trace("setup"); + // #523: a click on an agent notification focuses its window and opens the chat. + notifications::init(app.handle(), sidecar.clone()); // #485: the workspace and terminal channels, answered by the core (native.rs). let webview_only = if set_dmabuf_switch { vec![DMABUF_SWITCH] } else { Vec::new() }; app.manage(Arc::new(Native::new(app.handle().clone(), webview_only, bench, smoke))); diff --git a/apps/ide/src-tauri/src/notifications.rs b/apps/ide/src-tauri/src/notifications.rs new file mode 100644 index 00000000..636eef45 --- /dev/null +++ b/apps/ide/src-tauri/src/notifications.rs @@ -0,0 +1,130 @@ +//! System notifications for the agent chats (#523): when an agent finishes, fails or asks +//! for an approval while the IDE window is in the background, the sidecar asks for a +//! notification (`host.notification.show`), shown with tauri-plugin-notification, and for +//! approvals the window also requests the person's attention (taskbar flash on Windows, +//! Dock bounce on macOS, the urgency hint on Linux). +//! +//! The page never reaches the plugin: the app capability grants none of its commands, so +//! the only way in is `window.codexr` (renderer) -> IPC -> sidecar (which checks the window +//! is not focused) -> here. +//! +//! A click on the notification (`tap`, as far as the platform reports it: Windows only +//! while the toast is on screen, not from the Action Center; Linux when the notification +//! server supports actions) focuses the window and tells the sidecar which chat to open +//! (`notification.click`). +//! +//! Platform notes: on Windows the toast carries the app's AppUserModelID (`identifier` in +//! tauri.conf.json, `org.codexr.ide`), which the installer registers with the Start menu +//! shortcut; a build run from `target\debug` or `target\release` shows its toasts as +//! PowerShell's instead (the plugin's dev fallback), and a build elsewhere that is not +//! installed may have them dropped by Windows. On macOS a dev build (`tauri dev`) shows them +//! as Terminal's. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicI32, Ordering}; +use std::sync::Arc; + +use serde_json::{json, Value}; +use tauri::{AppHandle, Manager, UserAttentionType}; +use tauri_plugin_notification::NotificationExt; + +use crate::sidecar::Sidecar; + +/// The longest title and body shown; the sidecar already bounds them, this is the core's own guard. +const MAX_TITLE: usize = 200; +const MAX_BODY: usize = 1000; +const MAX_CHAT_ID: usize = 200; + +static NEXT_ID: AtomicI32 = AtomicI32::new(1); + +/// `text` cut to `max` characters (never inside a character), with an ellipsis when cut. +pub fn clip(text: &str, max: usize) -> String { + if text.chars().count() <= max { + return text.to_string(); + } + let mut clipped: String = text.chars().take(max.saturating_sub(1)).collect(); + clipped.push('\u{2026}'); + clipped +} + +/// The window and chat a click on one of our notifications leads to, from its `extra` +/// fields; None for any other action or a notification that is not ours. +pub fn click_target(action_id: &str, extra: &HashMap) -> Option<(String, Option)> { + if action_id != "tap" { + return None; + } + let window = extra.get("window").and_then(Value::as_str)?.to_string(); + let chat = extra.get("chat").and_then(Value::as_str).map(str::to_string); + Some((window, chat)) +} + +/// `host.notification.show { window, title, body, chat?, attention? }`. +pub fn show(app: &AppHandle, params: &Value) -> Result { + let label = params.get("window").and_then(Value::as_str).ok_or("missing window")?; + let window = app.get_window(label).ok_or_else(|| format!("no window {label}"))?; + let title = params.get("title").and_then(Value::as_str).ok_or("missing title")?; + let body = params.get("body").and_then(Value::as_str).unwrap_or(""); + let chat = params.get("chat").and_then(Value::as_str).filter(|chat| chat.chars().count() <= MAX_CHAT_ID); + let attention = params.get("attention").and_then(Value::as_bool).unwrap_or(false); + + let mut builder = app + .notification() + .builder() + .id(NEXT_ID.fetch_add(1, Ordering::Relaxed)) + .title(clip(title, MAX_TITLE)) + .body(clip(body, MAX_BODY)) + .extra("window", label); + if let Some(chat) = chat { + builder = builder.extra("chat", chat); + } + builder.show().map_err(|error| error.to_string())?; + if attention { + // Best effort: not every window manager honours it. + let _ = window.request_user_attention(Some(UserAttentionType::Critical)); + } + Ok(Value::Null) +} + +/// Registers, once at start-up, what a click on a notification does (notifications shown +/// before a handler exists report no clicks). +pub fn init(app: &AppHandle, sidecar: Arc) { + let handle = app.clone(); + let _ = app.notification().on_action(move |performed| { + let Some(notification) = performed.notification() else { + return; + }; + let Some((label, chat)) = click_target(performed.action_id(), notification.extra()) else { + return; + }; + if let Some(window) = handle.get_window(&label) { + let _ = window.unminimize(); + let _ = window.set_focus(); + } + sidecar.notify("notification.click", json!({ "window": label, "chat": chat })); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clip_keeps_short_text_and_cuts_on_characters() { + assert_eq!(clip("Agent finished", 20), "Agent finished"); + assert_eq!(clip("abcdef", 4), "abc\u{2026}"); + // Never inside a multi-byte character. + assert_eq!(clip("ñññññ", 3), "ññ\u{2026}"); + } + + #[test] + fn only_a_tap_on_our_notification_leads_somewhere() { + let mut extra = HashMap::new(); + extra.insert("window".to_string(), json!("main")); + extra.insert("chat".to_string(), json!("chat-1")); + assert_eq!(click_target("tap", &extra), Some(("main".to_string(), Some("chat-1".to_string())))); + assert_eq!(click_target("dismiss", &extra), None); + extra.remove("chat"); + assert_eq!(click_target("tap", &extra), Some(("main".to_string(), None))); + assert_eq!(click_target("tap", &HashMap::new()), None); + } +} diff --git a/apps/ide/src/bridge/codexrApi.ts b/apps/ide/src/bridge/codexrApi.ts index 4c89b417..ff30a540 100644 --- a/apps/ide/src/bridge/codexrApi.ts +++ b/apps/ide/src/bridge/codexrApi.ts @@ -5,7 +5,7 @@ import type { FunctionMetricsSnapshot } from '../shared/problems.ts'; import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AnalysisKind, type AutoStartMode, type BenchReport, type CodeXRApi, type HostNotification, type IdeCommand, type KeybindingsReport, type OutputAppended, type ProgressEvent, type PythonEnvStatus, type SceneAddress, type SceneBounds, type SceneFilesEvent, type SceneInfo, type SceneLoadEvent, type SceneUpdatedEvent, type SceneOpenInEditorEvent, type SceneShareEvent, type SearchDoneEvent, type SearchFileEvent, type SearchQuery, type SettingsReport, type TerminalDataEvent, type TerminalExitEvent, type Unsubscribe, type WatchedEntry, type WorkspaceInfo, type WorkspaceTrustInfo } from '../shared/api.ts'; import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS } from '../shared/git.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentProfileInput, type ApprovalDecision, type EditReviewResult, type ChatAttachment, type McpServerInput, type ModelPrice, type BudgetSettings, type ProviderInput } from '../shared/agents.ts'; -import { AGENT_SESSION_CHANNELS, AGENT_SESSION_EVENTS, type AcpAgentDefinition, type AgentSessionMessage, type ImportableSession, type LocalModelInput, type PromptAttachment } from '../shared/agentSession.ts'; +import { AGENT_SESSION_CHANNELS, AGENT_SESSION_EVENTS, type AcpAgentDefinition, type AgentSessionMessage, type ImportableSession, type LocalModelInput, type PromptAttachment, type SystemNoticeRequest } from '../shared/agentSession.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TaskFinished } from '../shared/tasks.ts'; import type { HostUiEvent } from '../shared/extensionHostProtocol.ts'; import type { DocumentEvent, ProvideRequest } from '../shared/extensionLanguageProtocol.ts'; @@ -128,6 +128,7 @@ export function createCodexrApi(ipc: IpcAdapter): CodeXRApi { describeInstall: (presetId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.describeInstall, presetId), install: (presetId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.install, presetId), uninstall: (presetId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.uninstall, presetId), + systemNotify: (sessionId: string, notice: SystemNoticeRequest) => ipc.invoke(AGENT_SESSION_CHANNELS.systemNotify, sessionId, notice), onMessage: (listener: (message: AgentSessionMessage) => void) => ipc.on(AGENT_SESSION_EVENTS.message, listener), }), // #17: only workspace-relative paths and branch names cross; main validates each one. diff --git a/apps/ide/src/main/agentSessions/acpMapping.ts b/apps/ide/src/main/agentSessions/acpMapping.ts index e60c0336..c3cafc55 100644 --- a/apps/ide/src/main/agentSessions/acpMapping.ts +++ b/apps/ide/src/main/agentSessions/acpMapping.ts @@ -1,5 +1,6 @@ import path from 'node:path'; import { pathToFileURL } from 'node:url'; +import { parseAgentCost } from '@codexr/core/agent-prompts/agentActivity'; import type { AuthMethod, AvailableCommand, @@ -222,8 +223,11 @@ export function mapSessionUpdate(update: SessionUpdate, ctx: MappingContext): Se return [{ type: 'config', options: mapConfigOptions(update.configOptions) }]; case 'session_info_update': return typeof update.title === 'string' && update.title.trim() ? [{ type: 'title', title: update.title.trim() }] : []; - case 'usage_update': - return [{ type: 'usage', used: update.used, size: update.size }]; + case 'usage_update': { + // #523: the session's cumulative cost, when the agent reports one. + const cost = parseAgentCost(update.cost); + return [{ type: 'usage', used: update.used, size: update.size, ...(cost ? { cost } : {}) }]; + } case 'notice': { const text = update.description ? `${update.title}: ${update.description}` : update.title; return [{ type: 'notice', id: ctx.newId(), level: noticeLevel(update.severity), text }]; diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 4c2c923c..3bb86174 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -32,6 +32,7 @@ import { type PermissionOptionView, type ProjectSessions, type PromptAttachment, + type SessionCost, type SessionEvent, type SessionSummary, type ToolKind, @@ -77,6 +78,7 @@ import { teleportArgs, type RemoteControlReply, } from '@codexr/core/claude-sessions/claudeSessionContinuity'; +import { newAgentCost } from '@codexr/core/agent-prompts/agentActivity'; import { parsePresetId, type AgentInstaller } from './agentInstaller.ts'; import { AgentTerminals } from './agentTerminals.ts'; import { isSessionId, type SessionStore } from './sessionStore.ts'; @@ -173,6 +175,12 @@ export interface AgentSessionServiceOptions { watch(info: { readonly state: AgentSessionState; readonly root: string; readonly workRoot: string }): number; forget(sessionId: string): void; }; + /** + * #523: the part of a chat's reported cost not recorded yet, in US dollars + * (the usage ledger's unit; other currencies show in the chat only). + * Absent, reported costs are only shown. + */ + readonly recordCost?: (call: { readonly agent: string; readonly provider: string; readonly model: string; readonly reportedCost: number }) => void; /** Starts an agent (tests connect to an in-process agent instead). */ readonly connect?: (launch: AgentLaunch, cwd: string, handlers: AcpClientHandlers) => AcpConnection; /** False in the smoke run: no agent process may start. */ @@ -1228,6 +1236,11 @@ export class AgentSessionService { return { scenes: feed.watch({ state: live.state, root: live.root, workRoot: this.flowRoot(live) }) }; } + /** #523: whether `sessionId` is a chat running in this window (a system notification names only its own chats). */ + ownsChat(window: WindowPort, sessionId: unknown): boolean { + return typeof sessionId === 'string' && this.live.get(sessionId)?.ownerId === window.id; + } + async markRead(window: WindowPort, sessionId: unknown): Promise { this.remember(window); const live = await this.open(window, sessionId); @@ -1546,8 +1559,29 @@ export class AgentSessionService { } } + /** #523: hands the ledger what a cumulative cost adds to the one this chat reported before. */ + private recordCost(state: AgentSessionState, cost: SessionCost): void { + if (!this.options.recordCost || cost.currency.toUpperCase() !== 'USD') { + return; + } + const previous = state.usage?.cost; + const added = newAgentCost(previous && previous.currency.toUpperCase() === 'USD' ? previous.amount : undefined, cost.amount); + if (added <= 0) { + return; + } + const model = state.configOptions.find((option) => option.category === 'model' || option.id === 'model'); + try { + this.options.recordCost({ agent: state.agentName, provider: state.agentName, model: model?.current ?? state.agentRef, reportedCost: added }); + } catch (error) { + this.options.log?.(`Could not record the cost of ${state.id}: ${errorMessage(error)}`); + } + } + private emit(live: Live, event: SessionEvent): void { const updatedAt = this.now(); + if (event.type === 'usage' && event.cost) { + this.recordCost(live.state, event.cost); + } live.state = applySessionEvent(live.state, event, updatedAt); const port = live.ownerId === null ? undefined : this.ports.get(live.ownerId); if (port && !port.isDestroyed()) { diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts index f4207c9e..52ebe315 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -60,4 +60,6 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi handle(C.describeInstall, (event, presetId) => service.describeInstall(portOf(event.sender), presetId)); handle(C.install, (event, presetId) => service.installAgent(portOf(event.sender), presetId, (description) => runtime.confirmInstall(event.sender, description))); handle(C.uninstall, (event, presetId) => service.uninstallAgent(portOf(event.sender), presetId, (packageName, version) => runtime.confirmUninstall(event.sender, packageName, version))); + // #523: only while the calling window is not focused; the text is bounded there. + handle(C.systemNotify, (event, id, notice) => runtime.systemNotify(event.sender, id, notice)); } diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 0b9631a7..99360dc4 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -6,6 +6,7 @@ import { AGENT_SESSION_EVENTS, type InstallDescription } from '../../shared/agen import { JsonKeyValueStore } from '../core/jsonStore.ts'; import { log } from '../log.ts'; import type { AgentProfiles } from '../agents/agentProfiles.ts'; +import type { UsageLedger } from '../agents/usageLedger.ts'; import type { TerminalHost } from '../terminal/terminalHost.ts'; import { terminalEnvironment } from '../terminal/terminalService.ts'; import { isWorkspaceTrusted } from '../trust/workspaceTrust.ts'; @@ -17,6 +18,7 @@ import { safeStorageCipher } from '../agents/safeStorageCipher.ts'; import { AgentInstaller, consentDetail } from './agentInstaller.ts'; import { AgentSessionService, type WindowPort } from './agentSessionService.ts'; import { SessionStore } from './sessionStore.ts'; +import { parseSystemNotice } from './systemNotices.ts'; import { AgentFlowFeed } from './agentFlowFeed.ts'; import { codexrMcpServerSpec } from './codexrMcpSpec.ts'; import { SessionChanges } from '../checkpoints/sessionChanges.ts'; @@ -45,6 +47,8 @@ export interface AgentSessionsRuntime { confirmRemoteControl(contents: WebContents): Promise; /** #431: the confirmation to run `claude --teleport` for a claude.ai session. */ confirmImportFromWeb(contents: WebContents, commandLine: string): Promise; + /** #523: a system notification for a chat of this window, only while the window is not focused. */ + systemNotify(contents: WebContents, sessionId: unknown, notice: unknown): Promise; } const MAX_REGISTRY_RESPONSE = 32 * 1024 * 1024; @@ -85,6 +89,8 @@ export interface AgentSessionsRuntimeOptions { readonly analysisOutput?: (contents: WebContents) => string | null; /** AF9: the window's live analysis, measured before and after each turn. */ readonly analysis?: Pick; + /** #523: the usage ledger (Agents > Usage and budget), where ACP chats' reported costs are recorded. */ + readonly usage?: Pick; /** #456: reads and stores the user's `agents.claude.remoteControl` setting. Absent (the smoke run), chats never start with it. */ readonly claudeRemoteControlSetting?: { get(): Promise; @@ -174,9 +180,16 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS // Agent Flow (#319): every chat is a live trace source of the XR scene. const agentFlow = new AgentFlowFeed(); + const usage = options.usage; const service: AgentSessionService = new AgentSessionService({ review: changes, agentFlow, + // #523: what ACP agents report they spent, as reported cost beside the built-in agent's calls. + ...(usage ? { + recordCost: (call) => { + usage.record({ ...call, inputTokens: 0, outputTokens: 0 }).catch((error: unknown) => log.warn(`[agent] Could not record an agent's cost: ${String(error)}`)); + }, + } : {}), beforePrompt: async (sessionId, root) => { const checkpoint = await changes.beforePrompt(sessionId, root); const owner = options.analysis ? windowOf(root) : null; @@ -285,9 +298,30 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS // A window that opens another folder stops the agents of its previous folder's chats. addFolderChangeListener((contents, root) => service.folderChanged(contents.id, root)); + // #523: a click on a chat's system notification (the core focused the window): the window opens the chat. + app.on('notification-click', (_event: unknown, win: BrowserWindow, chat: string | null) => { + if (chat && !win.isDestroyed() && service.ownsChat(portOf(win.webContents), chat)) { + portOf(win.webContents).send({ kind: 'open-chat', sessionId: chat }); + } + }); + return { service, portOf, + async systemNotify(contents, sessionId, input) { + const win = BrowserWindow.fromWebContents(contents); + const notice = parseSystemNotice(input); + if (!win || !notice || win.isFocused() || !service.ownsChat(portOf(contents), sessionId)) { + return false; + } + try { + await win.showNotification({ ...notice, chat: sessionId as string }); + return true; + } catch (error) { + log.warn(`[agent] Could not show a system notification: ${String(error)}`); + return false; + } + }, async confirmInstall(contents, description) { const update = description.installedVersion !== null; const response = await ask(contents, { diff --git a/apps/ide/src/main/agentSessions/systemNotices.ts b/apps/ide/src/main/agentSessions/systemNotices.ts new file mode 100644 index 00000000..8d3de173 --- /dev/null +++ b/apps/ide/src/main/agentSessions/systemNotices.ts @@ -0,0 +1,35 @@ +import type { SystemNoticeRequest } from '../../shared/agentSession.ts'; + +/** + * #523: a system notification as the renderer asks for it, checked before the + * core shows it: the page is untrusted, so the text is plain, on one line and + * bounded, and anything malformed is refused (null). Pure, unit-tested. + */ + +export const MAX_NOTICE_TITLE = 120; +export const MAX_NOTICE_BODY = 300; + +function plain(value: unknown, max: number): string | null { + if (typeof value !== 'string') { + return null; + } + // Control characters (newlines included) become spaces: one line each, as every OS shows them best. + const text = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim(); + if (!text) { + return null; + } + return text.length > max ? `${text.slice(0, max - 1)}…` : text; +} + +export function parseSystemNotice(value: unknown): SystemNoticeRequest | null { + if (!value || typeof value !== 'object') { + return null; + } + const record = value as Record; + const title = plain(record['title'], MAX_NOTICE_TITLE); + const body = record['body'] === '' ? '' : plain(record['body'], MAX_NOTICE_BODY); + if (title === null || body === null) { + return null; + } + return { title, body, attention: record['attention'] === true }; +} diff --git a/apps/ide/src/main/boot.ts b/apps/ide/src/main/boot.ts index 0dafcd9e..7c386eff 100644 --- a/apps/ide/src/main/boot.ts +++ b/apps/ide/src/main/boot.ts @@ -127,7 +127,7 @@ export async function startServices(options: BootOptions): Promise core.analysis.outputDirectory(contents), analysis: core.analysis, + agentSessions = startAgentSessions({ isSmoke, terminal: terminalHost, profiles: agentServices.profiles, usage: agentServices.usage, analysisOutput: (contents) => core.analysis.outputDirectory(contents), analysis: core.analysis, // #456: Claude Code chats on claude.ai, from the user's settings (the smoke run never asks). ...(isSmoke ? {} : { claudeRemoteControlSetting: { diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 1c5ac548..f0103321 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -18,7 +18,8 @@ import { ONBOARDED_KEY, progressTitle, shouldShowOnboarding } from './agentSetup import { errorText as setupErrorText } from './agentSetup.ts'; import { attentionText } from './sessionsModel.ts'; import { createSessionNoticeTracker } from './sessionNotices.ts'; -import { t } from '../../shared/i18n/i18n.ts'; +import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import { shouldNotifySystem, type AgentNoticeEvent, type AgentNoticeKind } from '@codexr/core/agent-prompts/agentActivity'; import './agentFirst.css'; /** @@ -61,6 +62,8 @@ export interface AgentWorkbenchOptions { openFolder(): void; /** The workspace calls the project instructions section needs (AF11). */ readonly instructions: Omit; + /** #523: the `agents.systemNotifications` setting (absent: on). */ + systemNotifications?(): boolean; /** Optional hooks of later stories. */ readonly chatHooks?: Pick; } @@ -86,6 +89,8 @@ export interface AgentWorkbench { } const MODE_KEY = 'codexr.layout.mode'; +/** #523: the text of a system notification, by what happened. */ +const SYSTEM_NOTICE_KEYS = { approval: 'agents.notify.approval', finished: 'agents.notify.finished', failed: 'agents.notify.failed' } as const satisfies Record; const GUIDE_TAB_ID = 'guide:getting-started'; /** #509: how long a "finished" toast stays when nobody reads it. */ const FINISHED_TOAST_MS = 10_000; @@ -382,6 +387,11 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork installProgress(message); return; } + if (message.kind === 'open-chat') { + // #523: the person clicked the chat's system notification. + void openChat(message.sessionId); + return; + } for (const view of views) { view.handle(message); } @@ -519,6 +529,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork } const { sessionId, event } = message; const visible = activeChatId === sessionId && document.hasFocus(); + notifySystem(sessionId, event); if (event.type === 'permission' && !visible) { notify(sessionId, 'warning', 'An agent is waiting for your approval.'); } else if (event.type === 'turn-end' && !visible && event.stopReason !== 'cancelled') { @@ -533,6 +544,21 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork } } + /** + * #523: with the window in the background, an operating-system notification + * too (main shows it only while the window is not focused; a click sends `open-chat`). + */ + function notifySystem(sessionId: string, event: AgentNoticeEvent): void { + const kind = shouldNotifySystem(event, document.hasFocus(), options.systemNotifications?.() ?? true); + if (!kind) { + return; + } + api.get(sessionId).then((state) => { + const body = t(SYSTEM_NOTICE_KEYS[kind], { agent: state.agentName }); + return api.systemNotify(sessionId, { title: state.title, body, attention: kind === 'approval' }); + }).catch(() => undefined); + } + function notify(sessionId: string, severity: 'info' | 'warning' | 'error', fallback: string): void { // #509: the title is read asynchronously; a chat opened meanwhile drops this toast. const claim = notices.claim(sessionId); diff --git a/apps/ide/src/renderer/agentFirst/chatView.ts b/apps/ide/src/renderer/agentFirst/chatView.ts index 8f0c0ca5..0448c715 100644 --- a/apps/ide/src/renderer/agentFirst/chatView.ts +++ b/apps/ide/src/renderer/agentFirst/chatView.ts @@ -9,7 +9,8 @@ import { metricDeltaFileLines, metricDeltaHeadline, restorePrompt } from './chan import { renderMarkdown } from '../agents/chatMarkdown.ts'; import { createAttachmentBar, type AttachmentSources } from '../agents/chatAttachments.ts'; import { el, icon } from '../dom.ts'; -import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import { getLocale, t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import { formatAgentCost } from '@codexr/core/agent-prompts/agentActivity'; import { createWorktreeBar } from './worktreeBar.ts'; import { branchLabel, branchTitle } from './worktreeModel.ts'; import { @@ -314,8 +315,10 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView setHeaderLabel(changesButton, t('chat.changesCount', { count: state.pendingChanges }), t('chat.changesTitle', { count: state.pendingChanges })); usageMeter.hidden = !state.usage; if (state.usage) { - usageMeter.textContent = t('chat.context', { tokens: formatTokens(state.usage.used, state.usage.size) }); - usageMeter.title = t('chat.contextTitle', { used: state.usage.used.toLocaleString(), size: state.usage.size.toLocaleString() }); + // #523: "Context 41k / 200k · $0.42"; no figure (never $0.00) when the agent reports no cost. + const cost = formatAgentCost(state.usage.cost, getLocale()); + usageMeter.textContent = t('chat.context', { tokens: formatTokens(state.usage.used, state.usage.size) }) + (cost ? ` · ${cost}` : ''); + usageMeter.title = `${t('chat.contextTitle', { used: state.usage.used.toLocaleString(), size: state.usage.size.toLocaleString() })}\n${cost ? t('chat.costTitle', { cost }) : t('chat.costNone')}`; } const worktree = state.worktree; branchBadge.hidden = !worktree; diff --git a/apps/ide/src/renderer/agentFirst/sessionsView.ts b/apps/ide/src/renderer/agentFirst/sessionsView.ts index 88a3a173..d4224dd2 100644 --- a/apps/ide/src/renderer/agentFirst/sessionsView.ts +++ b/apps/ide/src/renderer/agentFirst/sessionsView.ts @@ -618,7 +618,7 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep refreshSoon(); return; } - if (message.kind === 'install-progress') { + if (message.kind === 'install-progress' || message.kind === 'open-chat') { return; } const type = message.event.type; diff --git a/apps/ide/src/renderer/agents/usageSection.ts b/apps/ide/src/renderer/agents/usageSection.ts index 9eebeaca..82fb5448 100644 --- a/apps/ide/src/renderer/agents/usageSection.ts +++ b/apps/ide/src/renderer/agents/usageSection.ts @@ -61,7 +61,7 @@ export function createUsageSection(api: AgentsApi, callbacks: { onStatus(message el('dt', { text: 'Estimated' }), el('dd', { text: usd(total.estimatedCost), attrs: { title: 'Tokens × your price table' } }), el('dt', { text: 'Reported by providers' }), - el('dd', { text: usd(total.reportedCost), attrs: { title: 'What providers such as OpenRouter said they billed' } }), + el('dd', { text: usd(total.reportedCost), attrs: { title: 'What providers such as OpenRouter, and agents chatting over ACP, said they billed. An agent on a subscription reports nothing.' } }), ...(total.unpricedCalls > 0 ? [el('dt', { text: 'Unknown cost' }), el('dd', { text: `${total.unpricedCalls} call${total.unpricedCalls === 1 ? '' : 's'}: add the model to the price table` })] : []), ]), ...(summary.budget.monthlyUsd > 0 ? [el('p', { diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 6c29db1b..7cf59925 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -66,7 +66,7 @@ import { createSettingsView } from './settings/settingsView.ts'; import { createKeybindingsView } from './settings/keybindingsView.ts'; import { KEYBINDINGS_JSON_TAB_ID, menuAccelerators } from './settings/keybindingsModel.ts'; import { - AUTO_SAVE_SETTING, COLOR_THEME_SETTING, isColorTheme, isToggleOn, MINIMAP_SETTING, settingOf, toggledSetting, WORD_WRAP_SETTING, + AUTO_SAVE_SETTING, COLOR_THEME_SETTING, isColorTheme, isToggleOn, MINIMAP_SETTING, settingOf, SYSTEM_NOTIFICATIONS_SETTING, toggledSetting, WORD_WRAP_SETTING, type ColorTheme, type ToggleSetting, } from '../shared/settings.ts'; import { themeChoices } from './settings/settingsModel.ts'; @@ -1353,6 +1353,8 @@ const agentWorkbench = installAgentWorkbench({ api: api.agentSessions, registry, notifications, + // #523: operating-system notifications while the window is in the background. + systemNotifications: () => settingsReport === null || settingOf(settingsReport, SYSTEM_NOTIFICATIONS_SETTING), attachments: { listFiles: async () => (await api.workspace.listFiles()).files, activeSelection: () => { diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index e4eb0709..362f6a9a 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -12,6 +12,13 @@ import type { TerminalCreated } from './api.ts'; +/** #523: an ACP session's cumulative cost, as `usage_update.cost` reports it (core `AgentCost`). */ +export interface SessionCost { + readonly amount: number; + /** An ISO 4217 code ("USD") or another unit ("credits"). */ + readonly currency: string; +} + // ---- Agents ---------------------------------------------------------------- /** The agents the IDE knows how to launch without any configuration (AF2). */ @@ -427,8 +434,12 @@ export interface AgentSessionState extends SessionSummary { readonly commands: readonly SlashCommandView[]; readonly modes: { readonly current: string; readonly available: readonly ModeView[] } | null; readonly configOptions: readonly ConfigOptionView[]; - /** Context window use reported by the agent. */ - readonly usage: { readonly used: number; readonly size: number } | null; + /** + * Context window use reported by the agent, and (#523) the session's + * cumulative cost when the agent reports one (absent: it reports none, + * e.g. a subscription; never shown as zero). + */ + readonly usage: { readonly used: number; readonly size: number; readonly cost?: SessionCost } | null; /** The agent-side session id (ACP), kept to resume with `session/load`. */ readonly agentSessionId: string | null; /** @@ -492,7 +503,7 @@ export type SessionEvent = | { readonly type: 'commands'; readonly commands: readonly SlashCommandView[] } | { readonly type: 'modes'; readonly current: string; readonly available?: readonly ModeView[] } | { readonly type: 'config'; readonly options: readonly ConfigOptionView[] } - | { readonly type: 'usage'; readonly used: number; readonly size: number } + | { readonly type: 'usage'; readonly used: number; readonly size: number; readonly cost?: SessionCost } | { readonly type: 'notice'; readonly id: string; readonly level: 'info' | 'warning' | 'error'; readonly text: string } | { readonly type: 'status'; readonly status: SessionStatus } | { readonly type: 'turn-end'; readonly id: string; readonly stopReason: Extract['stopReason']; readonly at: string } @@ -514,7 +525,17 @@ export type AgentSessionMessage = | { readonly kind: 'event'; readonly sessionId: string; readonly event: SessionEvent; readonly updatedAt: string } | { readonly kind: 'sessions-changed' } | { readonly kind: 'agents-changed' } - | ({ readonly kind: 'install-progress' } & InstallProgress); + | ({ readonly kind: 'install-progress' } & InstallProgress) + /** #523: the person clicked this chat's system notification: open it. */ + | { readonly kind: 'open-chat'; readonly sessionId: string }; + +/** #523: a system notification the renderer asks for (bounded in main, shown only while the window is not focused). */ +export interface SystemNoticeRequest { + readonly title: string; + readonly body: string; + /** Approvals: the window also asks for the person's attention (taskbar, Dock). */ + readonly attention: boolean; +} // ---- Reducer --------------------------------------------------------------- @@ -646,8 +667,11 @@ export function applySessionEvent(state: AgentSessionState, event: SessionEvent, return touch({ modes: { current: event.current, available: event.available ?? state.modes?.available ?? [] } }); case 'config': return touch({ configOptions: event.options }); - case 'usage': - return touch({ usage: { used: event.used, size: event.size } }); + case 'usage': { + // #523: the cost is cumulative; an update that leaves it out keeps the last one reported. + const cost = event.cost ?? state.usage?.cost; + return touch({ usage: { used: event.used, size: event.size, ...(cost ? { cost } : {}) } }); + } case 'notice': return touch({ items: [...items, { kind: 'notice', id: event.id, level: event.level, text: event.text }] }); case 'status': @@ -782,6 +806,7 @@ export const AGENT_SESSION_CHANNELS = { describeInstall: 'codexr:agent-sessions:describe-install', install: 'codexr:agent-sessions:install', uninstall: 'codexr:agent-sessions:uninstall', + systemNotify: 'codexr:agent-sessions:system-notify', } as const; export const AGENT_SESSION_EVENTS = { @@ -912,5 +937,11 @@ export interface AgentSessionsApi { install(presetId: string): Promise; /** AF2: removes an adapter the IDE installed, after a native confirmation. */ uninstall(presetId: string): Promise; + /** + * #523: a system notification for this chat, shown only while this window + * is not focused (main checks); a click on it focuses the window and sends + * `open-chat`. Resolves whether it was shown. + */ + systemNotify(sessionId: string, notice: SystemNoticeRequest): Promise; onMessage(listener: (message: AgentSessionMessage) => void): () => void; } diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 719ffebb..6233bdfe 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -470,6 +470,11 @@ export const en = { 'chat.terminalLabel': 'Claude Code: {title}', 'chat.context': 'Context {tokens}', 'chat.contextTitle': '{used} of {size} tokens of context used', + 'agents.notify.approval': '{agent} needs your approval.', + 'agents.notify.finished': '{agent} finished.', + 'agents.notify.failed': '{agent}\'s turn failed.', + 'chat.costTitle': '{cost} spent in this chat, as the agent reports it', + 'chat.costNone': 'The agent reports no cost (a subscription, or a provider that does not tell)', 'chat.discarded': '{branch} (discarded)', 'chat.conversation': 'Conversation', 'chat.loading': 'Loading the chat', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 817d5016..54332682 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -473,6 +473,11 @@ export const es: Readonly> = { 'chat.terminalLabel': 'Claude Code: {title}', 'chat.context': 'Contexto {tokens}', 'chat.contextTitle': '{used} de {size} tokens de contexto usados', + 'agents.notify.approval': '{agent} necesita tu aprobación.', + 'agents.notify.finished': '{agent} ha terminado.', + 'agents.notify.failed': 'El turno de {agent} ha fallado.', + 'chat.costTitle': '{cost} gastados en este chat, según informa el agente', + 'chat.costNone': 'El agente no informa de ningún coste (una suscripción, o un proveedor que no lo indica)', 'chat.discarded': '{branch} (descartada)', 'chat.conversation': 'Conversación', 'chat.loading': 'Cargando el chat', diff --git a/apps/ide/src/shared/i18n/settings.es.ts b/apps/ide/src/shared/i18n/settings.es.ts index 28a05263..9fc3e316 100644 --- a/apps/ide/src/shared/i18n/settings.es.ts +++ b/apps/ide/src/shared/i18n/settings.es.ts @@ -118,6 +118,10 @@ export const SETTINGS_ES: Readonly> = { description: 'Inicia cada chat de Claude Code con Remote Control, para seguirlo desde claude.ai/code o la app móvil de Claude sin pulsar nada. Preguntar (lo predeterminado) pregunta una vez, en el primer chat de Claude Code. El código sigue ejecutándose en este equipo; los mensajes pasan por los servidores de Anthropic. Necesita iniciar sesión con claude.ai. Dejar de compartir en un chat lo termina para ese chat.', optionLabels: ['Preguntar una vez', 'Siempre', 'Nunca'], }, + 'agents.systemNotifications': { + title: 'Notificaciones del sistema', + description: 'Cuando un agente termina, falla o necesita tu aprobación mientras la ventana del IDE está en segundo plano, muestra una notificación del sistema operativo (al hacer clic se abre el chat). Las aprobaciones además hacen parpadear la barra de tareas o rebotar el Dock. La notificación dentro del IDE se muestra igualmente.', + }, 'git.blame.inline': { title: 'Blame en línea', description: 'Al final de la línea del cursor, muestra quién la cambió por última vez, cuándo y el resumen del commit (de git blame sobre el texto del editor).', diff --git a/apps/ide/src/shared/settings.ts b/apps/ide/src/shared/settings.ts index 68d1bddd..a5d83aeb 100644 --- a/apps/ide/src/shared/settings.ts +++ b/apps/ide/src/shared/settings.ts @@ -36,6 +36,8 @@ const MONO = "ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace"; /** #171: the colour theme. `system` follows the OS, live. */ /** #456: whether Claude Code chats start on claude.ai (Remote Control). */ export const CLAUDE_REMOTE_CONTROL_SETTING = 'agents.claude.remoteControl'; +/** #523: system notifications when an agent finishes, fails or needs approval while the window is in the background. */ +export const SYSTEM_NOTIFICATIONS_SETTING = 'agents.systemNotifications'; export const COLOR_THEME_SETTING = 'workbench.colorTheme'; export const COLOR_THEMES = ['system', 'dark', 'light'] as const; @@ -91,6 +93,7 @@ export const SETTINGS: readonly SettingDefinition[] = [ { key: 'update.checkOnStartup', category: 'Application', title: 'Check For Updates On Start-up', description: 'When the IDE starts, ask GitHub whether a newer Code-XR IDE was released, and offer its page. Off by default: it is a network call. Help > Check for Updates… asks once, whatever this says.', type: 'boolean', default: false, userOnly: true }, // #456: Claude Code chats on claude.ai (Remote Control at start). Asked once when it is `ask`. { key: CLAUDE_REMOTE_CONTROL_SETTING, category: 'Agents', title: 'Continue Claude Code Chats On claude.ai', description: 'Start every Claude Code chat with Remote Control, so you can continue it from claude.ai/code or the Claude mobile app without pressing anything. Ask (the default) asks once, on the first Claude Code chat. The code keeps running on this computer; messages go through Anthropic\'s servers. Needs a claude.ai sign-in. Stop sharing in a chat ends it for that chat.', type: 'enum', options: ['ask', 'always', 'never'], optionLabels: ['Ask once', 'Always', 'Never'], default: 'ask', userOnly: true }, + { key: SYSTEM_NOTIFICATIONS_SETTING, category: 'Agents', title: 'System Notifications', description: 'When an agent finishes, fails or needs your approval while the IDE window is in the background, show an operating-system notification (clicking it opens the chat). Approvals also flash the taskbar or bounce the Dock. The in-app notification shows either way.', type: 'boolean', default: true, userOnly: true }, // #175: Git in the editor. { key: 'git.blame.inline', category: 'Git', title: 'Inline Blame', description: 'At the end of the cursor line, show who last changed it, when, and the commit\'s summary (from git blame on the editor\'s text).', type: 'boolean', default: true }, // #176: Run Current File. Empty means the usual name on PATH (python3, or python on Windows; node). diff --git a/apps/ide/src/sidecar/index.ts b/apps/ide/src/sidecar/index.ts index a97ccad2..52c8dc15 100644 --- a/apps/ide/src/sidecar/index.ts +++ b/apps/ide/src/sidecar/index.ts @@ -2,7 +2,7 @@ import { writeProtocolLine } from './stdio.ts'; import path from 'node:path'; import { LineSplitter, RpcPeer } from './rpc.ts'; -import { app, attachCore, coreRequest, handleInvoke, handleMenuClick, handlePermissionRequest, handleSceneMessage, handleWindowEvent, keyringProblem, safeStorage, startSecrets, TauriBrowserWindow } from './tauriHost.ts'; +import { app, attachCore, coreRequest, handleInvoke, handleMenuClick, handleNotificationClick, handlePermissionRequest, handleSceneMessage, handleWindowEvent, keyringProblem, safeStorage, startSecrets, TauriBrowserWindow } from './tauriHost.ts'; import type { SecretsMigrationHost, SecretsNotice } from './profileMigration.ts'; import { handleWebviewRequest, startWebviewServing, wantsLoopbackWebviews } from './webviews.ts'; import { webviewFrameSources } from '../shared/extensionWebviewProtocol.ts'; @@ -63,6 +63,8 @@ function connect(): RpcPeer { TauriBrowserWindow.getAllWindows()[0]?.focus(); }); peer.onNotification('app.quit', () => app.quit()); + // #523: a click on an agent's system notification. + peer.onNotification('notification.click', handleNotificationClick); const splitter = new LineSplitter((line) => peer.receive(line)); process.stdin.on('data', (chunk: Buffer) => splitter.push(chunk)); // The core is gone: so is the app. diff --git a/apps/ide/src/sidecar/rpc.ts b/apps/ide/src/sidecar/rpc.ts index 163be60b..1e8fb516 100644 --- a/apps/ide/src/sidecar/rpc.ts +++ b/apps/ide/src/sidecar/rpc.ts @@ -6,7 +6,8 @@ * * Core to sidecar: `ipc.invoke { window, url, channel, args }` (a request: a * call of window.codexr), `window.event { window, event, url? }`, - * `app.secondInstance { argv }`, `app.quit` (notifications). + * `app.secondInstance { argv }`, `app.quit`, + * `notification.click { window, chat }` (notifications). * Sidecar to core: `webview.send { window, channel, payload }` (a notification: * an event for one webview), `host.` (requests: dialogs, * clipboard, windows... see tauriHost.ts). diff --git a/apps/ide/src/sidecar/tauriHost.ts b/apps/ide/src/sidecar/tauriHost.ts index 93066e1c..ca01101f 100644 --- a/apps/ide/src/sidecar/tauriHost.ts +++ b/apps/ide/src/sidecar/tauriHost.ts @@ -454,6 +454,16 @@ export class TauriBrowserWindow extends EventEmitter { hostNotify('window.setTitle', { window: this.label, title }); } + /** + * #523: a system notification (notifications.rs), and for `attention` the + * window asks for the person's attention too (taskbar flash, Dock bounce, + * urgency hint). A click on it emits `notification-click` on the app with + * this window and `chat`. + */ + showNotification(notice: { readonly title: string; readonly body: string; readonly chat?: string; readonly attention?: boolean }): Promise { + return hostRequest('notification.show', { window: this.label, ...notice }).then(() => undefined); + } + setDocumentEdited(_edited: boolean): void { // macOS only; nothing to do on Tauri yet. } @@ -543,6 +553,15 @@ export function handleWindowEvent(params: unknown): void { } } +/** #523: the person clicked a system notification (`notification.click`): the core already focused its window. */ +export function handleNotificationClick(params: unknown): void { + const { window: label, chat } = (params ?? {}) as { window?: unknown; chat?: unknown }; + const win = typeof label === 'string' ? windowsByLabel.get(label) : undefined; + if (win && !win.isDestroyed()) { + app.emit('notification-click', {}, win, typeof chat === 'string' ? chat : null); + } +} + // -- IPC -------------------------------------------------------------------------------- type InvokeHandler = (event: IpcEvent, ...args: unknown[]) => unknown; diff --git a/apps/ide/test/agentActivity.test.ts b/apps/ide/test/agentActivity.test.ts new file mode 100644 index 00000000..7fcbc85f --- /dev/null +++ b/apps/ide/test/agentActivity.test.ts @@ -0,0 +1,87 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { agentNoticeKind, formatAgentCost, newAgentCost, parseAgentCost, shouldNotifySystem } from '@codexr/core/agent-prompts/agentActivity'; +import { applySessionEvent, emptySession } from '../src/shared/agentSession.ts'; +import { MAX_NOTICE_BODY, MAX_NOTICE_TITLE, parseSystemNotice } from '../src/main/agentSessions/systemNotices.ts'; +import { SETTINGS, SYSTEM_NOTIFICATIONS_SETTING } from '../src/shared/settings.ts'; + +// #523 (O21): the cost an ACP agent reports and the system notifications of the agent chats. + +describe('the reported cost (#523)', () => { + it('reads usage_update.cost defensively', () => { + assert.deepEqual(parseAgentCost({ amount: 0.42, currency: 'USD' }), { amount: 0.42, currency: 'USD' }); + assert.deepEqual(parseAgentCost({ amount: 3, currency: ' credits ' }), { amount: 3, currency: 'credits' }); + for (const bad of [null, undefined, 'x', {}, { amount: '1', currency: 'USD' }, { amount: Number.NaN, currency: 'USD' }, { amount: -0.1, currency: 'USD' }, { amount: 1, currency: '' }, { amount: 1, currency: 'x'.repeat(40) }]) { + assert.equal(parseAgentCost(bad), undefined, JSON.stringify(bad)); + } + }); + + it('formats money with its currency and never invents a figure', () => { + assert.equal(formatAgentCost({ amount: 0.42, currency: 'USD' }, 'en-US'), '$0.42'); + assert.equal(formatAgentCost({ amount: 0.42, currency: 'usd' }, 'en-US'), '$0.42'); + assert.equal(formatAgentCost({ amount: 12, currency: 'EUR' }, 'en-US'), '€12.00'); + assert.equal(formatAgentCost({ amount: 0.42, currency: 'EUR' }, 'es-ES'), '0,42 €'); + // A cheap session does not read as free. + assert.equal(formatAgentCost({ amount: 0.0042, currency: 'USD' }, 'en-US'), '$0.0042'); + // Units that are not ISO 4217 money keep their name. + assert.equal(formatAgentCost({ amount: 1234.5, currency: 'credits' }, 'en-US'), '1,234.5 credits'); + // Nothing reported: nothing shown (a subscription is not "$0.00"). + assert.equal(formatAgentCost(undefined), undefined); + assert.equal(formatAgentCost(null), undefined); + }); + + it('counts only what a cumulative cost adds, and all of it after a restart', () => { + assert.equal(newAgentCost(undefined, 0.3), 0.3); + assert.equal(Math.round(newAgentCost(0.3, 0.5) * 100) / 100, 0.2); + assert.equal(newAgentCost(0.5, 0.5), 0); + assert.equal(newAgentCost(0.5, 0.1), 0.1); + }); + + it('keeps the last cost in the chat state when an update leaves it out', () => { + const at = '2026-12-05T10:00:00.000Z'; + let state = emptySession({ id: 's', title: 'Chat', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/p', createdAt: at, updatedAt: at }); + state = applySessionEvent(state, { type: 'usage', used: 10, size: 100 }); + assert.deepEqual(state.usage, { used: 10, size: 100 }); + state = applySessionEvent(state, { type: 'usage', used: 20, size: 100, cost: { amount: 0.1, currency: 'USD' } }); + state = applySessionEvent(state, { type: 'usage', used: 30, size: 100 }); + assert.deepEqual(state.usage, { used: 30, size: 100, cost: { amount: 0.1, currency: 'USD' } }); + }); +}); + +describe('system notifications (#523)', () => { + it('shouldNotifySystem: only unfocused, only with the setting on, only finish, failure and approval', () => { + assert.equal(shouldNotifySystem({ type: 'permission' }, false, true), 'approval'); + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'end_turn' }, false, true), 'finished'); + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'max_tokens' }, false, true), 'finished'); + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'error' }, false, true), 'failed'); + // The person stopped it themselves. + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'cancelled' }, false, true), null); + // Focused: the in-app toast is enough. + assert.equal(shouldNotifySystem({ type: 'permission' }, true, true), null); + // Turned off in settings. + assert.equal(shouldNotifySystem({ type: 'permission' }, false, false), null); + for (const type of ['assistant-chunk', 'status', 'usage', 'tool', 'read']) { + assert.equal(shouldNotifySystem({ type }, false, true), null, type); + assert.equal(agentNoticeKind({ type }), null, type); + } + }); + + it('main bounds and flattens what the renderer asks to show', () => { + assert.deepEqual(parseSystemNotice({ title: 'Fix the parser', body: 'Claude Code needs your approval.', attention: true }), { title: 'Fix the parser', body: 'Claude Code needs your approval.', attention: true }); + assert.deepEqual(parseSystemNotice({ title: ' a\nb\u0007 c ', body: '', attention: 'yes' }), { title: 'a b c', body: '', attention: false }); + const long = parseSystemNotice({ title: 'x'.repeat(500), body: 'y'.repeat(5000) }); + assert.equal(long?.title.length, MAX_NOTICE_TITLE); + assert.equal(long?.body.length, MAX_NOTICE_BODY); + assert.ok(long?.title.endsWith('…')); + for (const bad of [null, 'x', {}, { title: '' }, { title: ' ', body: 'b' }, { title: 't', body: 3 }, { title: 1, body: 'b' }]) { + assert.equal(parseSystemNotice(bad), null, JSON.stringify(bad)); + } + }); + + it('can be turned off: a user setting, on by default', () => { + const setting = SETTINGS.find((entry) => entry.key === SYSTEM_NOTIFICATIONS_SETTING); + assert.equal(setting?.type, 'boolean'); + assert.equal(setting?.default, true); + assert.equal(setting?.userOnly, true); + }); +}); diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index 8d77086f..5fcadae4 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -127,6 +127,9 @@ describe('ACP mapping', () => { assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'available_commands_update', availableCommands: [{ name: 'review', description: 'Review', input: { hint: 'what' } }] }, ctx), [{ type: 'commands', commands: [{ name: 'review', description: 'Review', hint: 'what' }] }]); assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'current_mode_update', currentModeId: 'plan' }, ctx), [{ type: 'modes', current: 'plan' }]); assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'usage_update', used: 10, size: 100 }, ctx), [{ type: 'usage', used: 10, size: 100 }]); + // #523: the cumulative cost is carried; a malformed one is dropped. + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'usage_update', used: 10, size: 100, cost: { amount: 0.42, currency: 'USD' } }, ctx), [{ type: 'usage', used: 10, size: 100, cost: { amount: 0.42, currency: 'USD' } }]); + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'usage_update', used: 10, size: 100, cost: { amount: -1, currency: 'USD' } }, ctx), [{ type: 'usage', used: 10, size: 100 }]); assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'session_info_update', title: ' Fix bug ' }, ctx), [{ type: 'title', title: 'Fix bug' }]); assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'notice', severity: 'warning', title: 'Slow', description: 'Rate limited' }, ctx), [{ type: 'notice', id: 'n1', level: 'warning', text: 'Slow: Rate limited' }]); assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'some_future_kind' } as never, ctx), []); @@ -378,6 +381,13 @@ function fakeAgent(log: FakeAgentLog) { if (command === 'auth') { throw RequestError.authRequired(); } + // #523: a cumulative session cost, in the currency `arg` names after the amount ("0.25:USD"). + if (command === 'cost') { + const [amount, currency] = (arg ?? '0:USD').split(':'); + await update(sid, { sessionUpdate: 'usage_update', used: 7, size: 100, cost: { amount: Number(amount), currency: currency ?? 'USD' } }); + await update(sid, { sessionUpdate: 'usage_update', used: 8, size: 100 }); + return { stopReason: 'end_turn' }; + } // #431: as Claude Code's ACP adapter: it lists `/remote-control`, answers it without a // model turn, and relays a message typed on claude.ai as a user_message_chunk. if (command === 'rcready') { @@ -403,7 +413,7 @@ function fakeAgent(log: FakeAgentLog) { }); } -async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges; claude?: boolean; claudeRemoteControl?: AgentSessionServiceOptions['claudeRemoteControl'] } = {}) { +async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges; claude?: boolean; claudeRemoteControl?: AgentSessionServiceOptions['claudeRemoteControl']; recordCost?: AgentSessionServiceOptions['recordCost'] } = {}) { const root = path.join(base, name, 'project'); fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(path.join(root, 'a.txt'), 'one\ntwo\nthree\n'); @@ -449,6 +459,7 @@ async function setup(name: string, options: { trusted?: boolean; afterTurn?: () terminalEnv: { PATH: process.env['PATH'] ?? '' }, cancelGraceMs: 2000, ...(options.claudeRemoteControl ? { claudeRemoteControl: options.claudeRemoteControl } : {}), + ...(options.recordCost ? { recordCost: options.recordCost } : {}), }); return { root, service, window, messages, log, written, ref: `acp:${custom.id}` }; } @@ -513,6 +524,28 @@ describe('AgentSessionService with a fake ACP agent', () => { await service.stopAll(); }); + it('keeps the reported cost and records in the ledger only what each update adds, in US dollars (#523)', async () => { + const recorded: { agent: string; model: string; reportedCost: number }[] = []; + const { service, window, ref } = await setup('cost', { recordCost: (call) => recorded.push({ agent: call.agent, model: call.model, reportedCost: call.reportedCost }) }); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'cost 0.25:USD', []); + // A later update without a cost keeps the last cost reported. + assert.deepEqual((await service.get(window, created.id)).usage, { used: 8, size: 100, cost: { amount: 0.25, currency: 'USD' } }); + await service.prompt(window, created.id, 'cost 0.4:USD', []); + // The same cumulative figure again (a replay) adds nothing. + await service.prompt(window, created.id, 'cost 0.4:USD', []); + assert.deepEqual(recorded.map((call) => Math.round(call.reportedCost * 1000) / 1000), [0.25, 0.15]); + assert.equal(recorded[0]?.model, 'a'); + // Credits are shown in the chat, never added to a dollar ledger. + await service.prompt(window, created.id, 'cost 12:credits', []); + assert.equal(recorded.length, 2); + assert.deepEqual((await service.get(window, created.id)).usage?.cost, { amount: 12, currency: 'credits' }); + assert.equal(service.ownsChat(window, created.id), true); + assert.equal(service.ownsChat({ ...window, id: 2 }, created.id), false); + assert.equal(service.ownsChat(window, 42), false); + await service.stopAll(); + }); + it('asks for permission, waits for the answer and remembers allow_always per agent and tool kind', async () => { const { service, window, ref, log } = await setup('permission'); const created = await service.create(window, ref); diff --git a/apps/vscode-extension/src/core/agent-prompts/agentActivity.ts b/apps/vscode-extension/src/core/agent-prompts/agentActivity.ts new file mode 100644 index 00000000..de286a03 --- /dev/null +++ b/apps/vscode-extension/src/core/agent-prompts/agentActivity.ts @@ -0,0 +1,123 @@ +/** + * #523 (O21): what an agent chat reports about its spend and when it is worth + * interrupting the person for. Two host-neutral pieces a chat UI needs: + * + * - the session cost an ACP agent reports in `usage_update.cost` (cumulative, + * `{ amount, currency }`), read defensively and formatted for the context + * meter ("$0.42"). An agent that reports no cost gets no figure at all: a + * subscription or a provider that does not tell is never shown as "$0.00"; + * - whether an agent event deserves an operating-system notification: only + * when the window is not focused, the person left the setting on, and the + * event is one they have to know about (finished, failed, needs approval). + * + * Pure: no `vscode`, no Node, no DOM and no runtime imports, so the Code-XR + * IDE loads it in its sandboxed renderer and the VS Code extension's chat + * (#214-#216) can reuse it as is. + */ + +/** The cumulative cost of a session as the agent reported it. */ +export interface AgentCost { + readonly amount: number; + /** An ISO 4217 code ("USD", "EUR") or another unit the agent names ("credits"). */ + readonly currency: string; +} + +const MAX_CURRENCY_LENGTH = 32; + +/** The cost of an ACP `usage_update`, or undefined when it carries none or a malformed one. */ +export function parseAgentCost(value: unknown): AgentCost | undefined { + if (!value || typeof value !== 'object') { + return undefined; + } + const record = value as Record; + const amount = record['amount']; + const currency = typeof record['currency'] === 'string' ? record['currency'].trim() : ''; + if (typeof amount !== 'number' || !Number.isFinite(amount) || amount < 0 || !currency || currency.length > MAX_CURRENCY_LENGTH) { + return undefined; + } + return { amount, currency }; +} + +/** Whether `currency` is a three-letter ISO 4217 code Intl can format as money. */ +function isCurrencyCode(currency: string): boolean { + if (!/^[A-Za-z]{3}$/.test(currency)) { + return false; + } + try { + new Intl.NumberFormat('en', { style: 'currency', currency }); + return true; + } catch { + return false; + } +} + +/** + * "$0.42", "0,42 €", "1,234 credits". Money keeps two decimals, and four below + * one cent so a cheap turn does not read as free; other units keep up to two. + * Undefined (nothing to show) when the agent reported no cost. + */ +export function formatAgentCost(cost: AgentCost | null | undefined, locale?: string): string | undefined { + if (!cost) { + return undefined; + } + const small = cost.amount > 0 && cost.amount < 0.01; + if (isCurrencyCode(cost.currency)) { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: cost.currency.toUpperCase(), + minimumFractionDigits: small ? 4 : 2, + maximumFractionDigits: small ? 4 : 2, + }).format(cost.amount); + } + const number = new Intl.NumberFormat(locale, { maximumFractionDigits: small ? 4 : 2 }).format(cost.amount); + return `${number} ${cost.currency}`; +} + +/** + * The part of a cumulative cost not counted yet, for a ledger of calls. A + * figure lower than the last one means the agent started counting again (a + * new process): all of it is new. + */ +export function newAgentCost(previous: number | undefined, current: number): number { + if (previous === undefined || current < previous) { + return current; + } + return current - previous; +} + +/** An agent event as the decision reads it: its type and, for `turn-end`, why the turn stopped. */ +export interface AgentNoticeEvent { + readonly type: string; + readonly stopReason?: string; +} + +export type AgentNoticeKind = 'approval' | 'finished' | 'failed'; + +/** What an event means to the person, or null when it is nothing they need to hear about. */ +export function agentNoticeKind(event: AgentNoticeEvent): AgentNoticeKind | null { + if (event.type === 'permission') { + return 'approval'; + } + if (event.type === 'turn-end') { + if (event.stopReason === 'cancelled') { + // The person stopped it: they know. + return null; + } + return event.stopReason === 'error' ? 'failed' : 'finished'; + } + return null; +} + +/** + * Whether to send an operating-system notification for `event`: the setting is + * on, the window does not have the focus (the in-app toast is enough when it + * does), and the event is a finish, a failure or an approval request. Answers + * the kind, which decides the text and whether the window also asks for the + * person's attention (approvals), or null. + */ +export function shouldNotifySystem(event: AgentNoticeEvent, focused: boolean, enabled: boolean): AgentNoticeKind | null { + if (!enabled || focused) { + return null; + } + return agentNoticeKind(event); +} diff --git a/apps/vscode-extension/test/agent_prompts/agentActivity.test.cjs b/apps/vscode-extension/test/agent_prompts/agentActivity.test.cjs new file mode 100644 index 00000000..53babe4f --- /dev/null +++ b/apps/vscode-extension/test/agent_prompts/agentActivity.test.cjs @@ -0,0 +1,12 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { formatAgentCost, parseAgentCost, shouldNotifySystem } = require('../../out/core/agent-prompts/agentActivity.js'); + +// #523: the cost meter and the system-notification decision live in the core so this extension's chat can reuse them (the IDE tests them in depth). +test('the core formats a reported cost and decides when an agent event deserves a system notification (#523)', () => { + assert.equal(formatAgentCost(parseAgentCost({ amount: 0.42, currency: 'USD' }), 'en-US'), '$0.42'); + assert.equal(formatAgentCost(parseAgentCost(undefined)), undefined); + assert.equal(shouldNotifySystem({ type: 'permission' }, false, true), 'approval'); + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'end_turn' }, true, true), null); + assert.equal(shouldNotifySystem({ type: 'turn-end', stopReason: 'error' }, false, false), null); +}); From 74c42ad9626c1989765ecc675d8354576110462d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:55:39 +0000 Subject: [PATCH 37/74] feat(ide): analysis-aware @ mentions, composer images and the prompt library (#522, #528) O20 (#522): the agent-first composer offers @hotspots, @problems, @diff, @terminal and @metrics: beside @file and @selection. Mention parsing, formatting and the 120k context budget live in the core (core/agent-prompts/contextMentions.ts). The main process resolves hotspots and metrics from the window's analysis and the diff from git in the chat's folder; Problems and terminal output arrive as the window's snapshots and are cleaned and capped there. Images can be pasted or dropped (PNG, JPEG, WebP, GIF, 5 MB, 8 per message) only when the agent advertises promptCapabilities.image, with a thumbnail chip and thumbnails on the sent message. O26 (#528): .codexr/prompts/*.md with name/description front-matter are offered as slash commands after the agent's own (never shadowing them), plus two built-in prompts (/xr-review-turn, /xr-refactor-hotspot). The placeholders {{hotspots}}, {{selection}}, {{problems}}, {{diff}} and {{file}} are expanded in the main process before sending, reusing the mention resolvers. Parser and expander are pure in the core (core/agent-prompts/promptLibrary.ts). --- apps/ide/src/bridge/codexrApi.ts | 1 + apps/ide/src/main/agentSessions/acpMapping.ts | 19 +- .../main/agentSessions/agentSessionService.ts | 178 +++++++++-- .../main/agentSessions/agentSessionsIpc.ts | 1 + .../agentSessions/agentSessionsRuntime.ts | 8 + .../src/main/agentSessions/promptContext.ts | 197 ++++++++++++ .../src/renderer/agentFirst/agentFirst.css | 7 + apps/ide/src/renderer/agentFirst/chatModel.ts | 124 +++++++- apps/ide/src/renderer/agentFirst/chatView.ts | 121 +++++++- .../src/renderer/agents/chatAttachments.ts | 67 +++- apps/ide/src/renderer/main.ts | 5 + .../ide/src/renderer/problems/problemsView.ts | 3 + .../src/renderer/terminal/terminalPanel.ts | 6 + apps/ide/src/renderer/terminal/xtermView.ts | 19 ++ apps/ide/src/shared/agentSession.ts | 64 +++- apps/ide/src/shared/agents.ts | 6 +- apps/ide/src/shared/i18n/messages.en.ts | 14 + apps/ide/src/shared/i18n/messages.es.ts | 14 + apps/ide/test/agentSessions.test.ts | 88 +++++- apps/ide/test/promptContext.test.ts | 292 ++++++++++++++++++ .../src/core/agent-prompts/contextMentions.ts | 231 ++++++++++++++ .../src/core/agent-prompts/promptLibrary.ts | 181 +++++++++++ .../agent_prompts/contextMentions.test.cjs | 24 ++ 23 files changed, 1613 insertions(+), 57 deletions(-) create mode 100644 apps/ide/src/main/agentSessions/promptContext.ts create mode 100644 apps/ide/test/promptContext.test.ts create mode 100644 apps/vscode-extension/src/core/agent-prompts/contextMentions.ts create mode 100644 apps/vscode-extension/src/core/agent-prompts/promptLibrary.ts create mode 100644 apps/vscode-extension/test/agent_prompts/contextMentions.test.cjs diff --git a/apps/ide/src/bridge/codexrApi.ts b/apps/ide/src/bridge/codexrApi.ts index 4c89b417..b15db199 100644 --- a/apps/ide/src/bridge/codexrApi.ts +++ b/apps/ide/src/bridge/codexrApi.ts @@ -105,6 +105,7 @@ export function createCodexrApi(ipc: IpcAdapter): CodeXRApi { rename: (sessionId: string, title: string) => ipc.invoke(AGENT_SESSION_CHANNELS.rename, sessionId, title), remove: (sessionId: string, options?: { readonly removeWorktree?: boolean }) => ipc.invoke(AGENT_SESSION_CHANNELS.remove, sessionId, { removeWorktree: options?.removeWorktree === true }), markRead: (sessionId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.markRead, sessionId), + listPrompts: (sessionId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.listPrompts, sessionId), watchInXr: (sessionId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.watchInXr, sessionId), // AF5/AF6: review and checkpoints; paths are workspace-relative and checked in main. changes: (sessionId: string) => ipc.invoke(AGENT_SESSION_CHANNELS.changes, sessionId), diff --git a/apps/ide/src/main/agentSessions/acpMapping.ts b/apps/ide/src/main/agentSessions/acpMapping.ts index e60c0336..2b978d9e 100644 --- a/apps/ide/src/main/agentSessions/acpMapping.ts +++ b/apps/ide/src/main/agentSessions/acpMapping.ts @@ -348,12 +348,21 @@ export function attachmentLabel(attachment: { readonly kind: 'file' | 'selection : attachment.path; } +/** #522: what a message carries besides files and selections, already resolved and capped. */ +export interface PromptExtras { + /** Context mentions as formatted blocks (`fitContextBlocks`), in order. */ + readonly contexts?: readonly { readonly label: string; readonly text: string }[]; + /** Images, only ever given for an agent that advertises `promptCapabilities.image`. */ + readonly images?: readonly { readonly mimeType: string; readonly data: string }[]; +} + /** * The `session/prompt` content: the message, then each file as an embedded * text resource (when the agent accepts embedded context and the IDE could - * read it) or a `resource_link`, then each selection as text naming its lines. + * read it) or a `resource_link`, then each selection as text naming its lines, + * then (#522) each context mention as a text block and each image as an image block. */ -export function buildPromptBlocks(text: string, attachments: readonly ResolvedAttachment[], embeddedContext: boolean): ContentBlock[] { +export function buildPromptBlocks(text: string, attachments: readonly ResolvedAttachment[], embeddedContext: boolean, extras: PromptExtras = {}): ContentBlock[] { const blocks: ContentBlock[] = [{ type: 'text', text }]; for (const attachment of attachments) { const uri = pathToFileURL(attachment.absolutePath).href; @@ -368,6 +377,12 @@ export function buildPromptBlocks(text: string, attachments: readonly ResolvedAt const lines = attachment.startLine !== undefined ? ` (lines ${attachment.startLine}-${attachment.endLine ?? attachment.startLine})` : ''; blocks.push({ type: 'text', text: `Selection from ${attachment.absolutePath}${lines}:\n\`\`\`\n${attachment.text}\n\`\`\`` }); } + for (const context of extras.contexts ?? []) { + blocks.push({ type: 'text', text: context.text }); + } + for (const image of extras.images ?? []) { + blocks.push({ type: 'image', mimeType: image.mimeType, data: image.data }); + } return blocks; } diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 4c2c923c..3f8ffc3a 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -31,7 +31,8 @@ import { type RemoteControlView, type PermissionOptionView, type ProjectSessions, - type PromptAttachment, + type MessageImageView, + type PromptCommandView, type SessionEvent, type SessionSummary, type ToolKind, @@ -64,6 +65,9 @@ import { type ResolvedAttachment, } from './acpMapping.ts'; import { loginProgram, nativeLoginProgram, type AgentCatalog } from './agentCatalog.ts'; +import { checkPromptImage, findContextMentions, fitContextBlocks, isContextMentionKind, isImageThumbnail, MAX_PROMPT_IMAGES, normalizeMentionPath } from '@codexr/core/agent-prompts/contextMentions'; +import type { PromptTemplate } from '@codexr/core/agent-prompts/promptLibrary'; +import { expandLibraryCommand, promptCommandViews, readPromptLibrary, resolveContext, type ContextRequest, type ContextSources, type PlaceholderSnapshots } from './promptContext.ts'; import { commandLine, isRemoteControlPrompt, @@ -173,6 +177,10 @@ export interface AgentSessionServiceOptions { watch(info: { readonly state: AgentSessionState; readonly root: string; readonly workRoot: string }): number; forget(sessionId: string): void; }; + /** #522: the live data behind `@hotspots`, `@metrics:`, `@diff` and the library's placeholders; absent, they say they are unavailable. */ + readonly contextSources?: ContextSources; + /** #528: the prompt library of a project; default `.codexr/prompts/*.md` on disk plus the built-in prompts. */ + readonly promptLibrary?: (root: string) => Promise; /** Starts an agent (tests connect to an in-process agent instead). */ readonly connect?: (launch: AgentLaunch, cwd: string, handlers: AcpClientHandlers) => AcpConnection; /** False in the smoke run: no agent process may start. */ @@ -228,6 +236,27 @@ interface AgentRuntime { readonly terminals: AgentTerminals; } +/** #522: the renderer's attachments, checked and sorted by what they become. */ +interface ParsedAttachments { + readonly resolved: ResolvedAttachment[]; + readonly labels: string[]; + readonly contexts: ContextRequest[]; + readonly images: { readonly mimeType: string; readonly data: string }[]; + readonly imageViews: MessageImageView[]; + readonly snapshots: { -readonly [K in keyof PlaceholderSnapshots]: PlaceholderSnapshots[K] }; +} + +/** #522/#528: what `prompt` sends and records. */ +interface PreparedMessage { + /** What the agent receives (a library command expanded). */ + readonly text: string; + readonly resolved: readonly ResolvedAttachment[]; + readonly labels: readonly string[]; + readonly contexts: readonly { readonly label: string; readonly text: string }[]; + readonly images: readonly { readonly mimeType: string; readonly data: string }[]; + readonly imageViews: readonly MessageImageView[]; +} + interface Live { state: AgentSessionState; readonly root: string; @@ -1068,25 +1097,28 @@ export class AgentSessionService { } live.turnActive = true; live.cancelRequested = false; - let resolved: ResolvedAttachment[]; - let labels: string[]; + let message: PreparedMessage; try { - ({ resolved, labels } = await this.resolveAttachments(this.workRoot(live), attachments)); + message = await this.prepareMessage(live, text, attachments); } catch (error) { live.turnActive = false; throw error; } + const { resolved, labels } = message; try { const checkpoint = await this.hook('beforePrompt', () => this.options.beforePrompt?.(live.state.id, this.workRoot(live))).then((result) => result?.checkpointId ?? null); const firstMessage = !live.state.items.some((item) => item.kind === 'user'); - this.emit(live, { type: 'user', id: randomUUID(), text, at: this.now(), ...(labels.length ? { attachments: labels } : {}), ...(checkpoint ? { checkpoint } : {}) }); + this.emit(live, { type: 'user', id: randomUUID(), text, at: this.now(), ...(labels.length ? { attachments: [...labels] } : {}), ...(checkpoint ? { checkpoint } : {}), ...(message.imageViews.length ? { images: message.imageViews } : {}) }); if (firstMessage && live.state.title === 'New chat') { this.emit(live, { type: 'title', title: titleFromPrompt(text) }); } this.sessionsChanged(); const agent = await this.ensureAgent(live, window); const embedded = agent.init.agentCapabilities?.promptCapabilities?.embeddedContext === true; - const response = await agent.connection.prompt(agent.sessionId, buildPromptBlocks(text, resolved, embedded)); + if (message.images.length && agent.init.agentCapabilities?.promptCapabilities?.image !== true) { + throw new Error(`${live.state.agentName} does not accept images; the message was not sent.`); + } + const response = await agent.connection.prompt(agent.sessionId, buildPromptBlocks(message.text, resolved, embedded, { contexts: message.contexts, images: message.images })); this.flushTerminalOutput(live); const turnId = randomUUID(); this.emit(live, { type: 'turn-end', id: turnId, stopReason: live.cancelRequested ? 'cancelled' : stopReasonOf(response.stopReason), at: this.now() }); @@ -1228,6 +1260,17 @@ export class AgentSessionService { return { scenes: feed.watch({ state: live.state, root: live.root, workRoot: this.flowRoot(live) }) }; } + /** #528: the chat's project's prompt library, read now (so an edited prompt file shows the next time the list opens). */ + async listPrompts(window: WindowPort, sessionId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + return promptCommandViews(await this.loadPromptLibrary(live.root)); + } + + private loadPromptLibrary(root: string): Promise { + return (this.options.promptLibrary ?? readPromptLibrary)(root); + } + async markRead(window: WindowPort, sessionId: unknown): Promise { this.remember(window); const live = await this.open(window, sessionId); @@ -1710,6 +1753,8 @@ export class AgentSessionService { } const runtime: AgentRuntime = { connection, sessionId, init, terminals }; live.agent = runtime; + // #522: the composer offers images only to an agent that accepts them. + this.emit(live, { type: 'prompt-capabilities', image: init.agentCapabilities?.promptCapabilities?.image === true }); return runtime; } catch (error) { connection.close(); @@ -1901,35 +1946,117 @@ export class AgentSessionService { await this.options.writeText(file, params.content); } - private async resolveAttachments(root: string, input: unknown): Promise<{ resolved: ResolvedAttachment[]; labels: string[] }> { + /** + * The message as the agent gets it (#522, #528): files and selections + * resolved inside the folder, context mentions (chips, and any typed in the + * text) resolved and capped, images checked, and a library command + * expanded with live values. The person's own text is what the transcript keeps. + */ + private async prepareMessage(live: Live, text: string, input: unknown): Promise { + const workRoot = this.workRoot(live); + const parsed = await this.resolveAttachments(workRoot, input); + if (parsed.images.length && live.state.promptImages === false) { + throw new Error(`${live.state.agentName} does not accept images.`); + } + const roots = { root: live.root, workRoot }; + const requests = [...parsed.contexts]; + const labels = [...parsed.labels]; + for (const mention of findContextMentions(text)) { + const request: ContextRequest = mention.kind === 'metrics' ? { context: 'metrics', path: mention.argument ?? '' } : { context: mention.kind }; + if (!requests.some((existing) => existing.context === request.context && (existing.path ?? '') === (request.path ?? ''))) { + requests.push(request); + } + } + const entries = await Promise.all(requests.map((request) => resolveContext(request, roots, this.options.contextSources))); + for (const entry of entries) { + if (!labels.includes(entry.label)) { + labels.push(entry.label); + } + } + let outgoing = text; + if (text.trimStart().startsWith('/')) { + const prompts = await this.loadPromptLibrary(live.root).catch((): PromptTemplate[] => []); + const expanded = await expandLibraryCommand(text, prompts, live.state.commands.map((command) => command.name), roots, this.options.contextSources, parsed.snapshots); + outgoing = expanded.text; + } + return { text: outgoing, resolved: parsed.resolved, labels, contexts: fitContextBlocks(entries), images: parsed.images, imageViews: parsed.imageViews }; + } + + private async resolveAttachments(root: string, input: unknown): Promise { + const parsed: ParsedAttachments = { resolved: [], labels: [], contexts: [], images: [], imageViews: [], snapshots: {} }; if (input === undefined || input === null) { - return { resolved: [], labels: [] }; + return parsed; } if (!Array.isArray(input) || input.length > MAX_ATTACHMENTS) { throw new Error(`At most ${MAX_ATTACHMENTS} attachments.`); } - const resolved: ResolvedAttachment[] = []; - const labels: string[] = []; + const { resolved, labels, contexts, images, imageViews, snapshots } = parsed; for (const raw of input as unknown[]) { - const attachment = raw as Partial | null; - if (!attachment || (attachment.kind !== 'file' && attachment.kind !== 'selection') || typeof attachment.path !== 'string' || !attachment.path || attachment.path.length > 4096) { + const attachment = (raw && typeof raw === 'object' ? raw : null) as Record | null; + if (attachment?.['kind'] === 'image') { + const problem = checkPromptImage(attachment['mimeType'], attachment['data']); + if (problem) { + throw new Error(problem === 'size' ? 'An image is larger than 5 MB.' : problem === 'type' ? 'Only PNG, JPEG, WebP and GIF images can be sent.' : 'Invalid image.'); + } + if (images.length >= MAX_PROMPT_IMAGES) { + throw new Error(`At most ${MAX_PROMPT_IMAGES} images per message.`); + } + images.push({ mimeType: attachment['mimeType'] as string, data: attachment['data'] as string }); + const rawName = attachment['name']; + const name = typeof rawName === 'string' && rawName.trim() ? rawName.trim().slice(0, 200) : `image ${images.length}`; + const thumbnail = attachment['thumbnail']; + imageViews.push({ name, ...(isImageThumbnail(thumbnail) ? { thumbnail } : {}) }); + continue; + } + if (attachment?.['kind'] === 'context') { + const context = attachment['context']; + const snapshot = attachment['text']; + if (!isContextMentionKind(context) || (snapshot !== undefined && (typeof snapshot !== 'string' || snapshot.length > MAX_PROMPT_LENGTH))) { + throw new Error('Invalid context attachment.'); + } + if (attachment['inline'] === true) { + if (context === 'problems' && typeof snapshot === 'string') { + snapshots.problems = snapshot; + } + continue; + } + if (context === 'metrics') { + const file = typeof attachment['path'] === 'string' ? normalizeMentionPath(attachment['path']) : ''; + if (!file || file.length > 4096 || file.split('/').includes('..')) { + throw new Error('Invalid context attachment.'); + } + contexts.push({ context, path: file }); + } else { + contexts.push({ context, ...(typeof snapshot === 'string' ? { text: snapshot } : {}) }); + } + continue; + } + const kind = attachment?.['kind']; + const relative = attachment?.['path']; + if (!attachment || (kind !== 'file' && kind !== 'selection') || typeof relative !== 'string' || !relative || relative.length > 4096) { throw new Error('Invalid attachment.'); } const api = this.platform === 'win32' ? path.win32 : path.posix; - const absolutePath = api.resolve(root, attachment.path); + const absolutePath = api.resolve(root, relative); if (!isSameOrInside(root, absolutePath, this.platform)) { - throw new Error(`${attachment.path} is outside the project folder.`); + throw new Error(`${relative} is outside the project folder.`); } const lineOf = (value: unknown): number | undefined => (typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined); - const startLine = lineOf(attachment.startLine); - const endLine = lineOf(attachment.endLine); - const label = attachmentLabel({ kind: attachment.kind, path: attachment.path, ...(startLine !== undefined ? { startLine } : {}), ...(endLine !== undefined ? { endLine } : {}) }); - labels.push(label); - if (attachment.kind === 'selection') { - if (typeof attachment.text !== 'string' || attachment.text.length > MAX_PROMPT_LENGTH) { + const startLine = lineOf(attachment['startLine']); + const endLine = lineOf(attachment['endLine']); + const inline = attachment['inline'] === true; + if (kind === 'selection') { + const selected = attachment['text']; + if (typeof selected !== 'string' || selected.length > MAX_PROMPT_LENGTH) { throw new Error('A selection needs its text.'); } - resolved.push({ kind: 'selection', absolutePath, relativePath: attachment.path, text: attachment.text, ...(startLine !== undefined ? { startLine } : {}), ...(endLine !== undefined ? { endLine } : {}) }); + if (inline) { + const lines = startLine !== undefined ? ` (lines ${startLine}-${endLine ?? startLine})` : ''; + snapshots.selection = `${relative}${lines}:\n\`\`\`\n${selected}\n\`\`\``; + continue; + } + labels.push(attachmentLabel({ kind, path: relative, ...(startLine !== undefined ? { startLine } : {}), ...(endLine !== undefined ? { endLine } : {}) })); + resolved.push({ kind: 'selection', absolutePath, relativePath: relative, text: selected, ...(startLine !== undefined ? { startLine } : {}), ...(endLine !== undefined ? { endLine } : {}) }); continue; } let text: string | null = null; @@ -1937,9 +2064,14 @@ export class AgentSessionService { if (stat?.isFile() && stat.size <= MAX_EMBEDDED_FILE) { text = await this.options.readText(absolutePath).catch(() => null); } - resolved.push({ kind: 'file', absolutePath, relativePath: attachment.path, text }); + if (inline) { + snapshots.file = text === null ? `${relative} (could not be read, or larger than 256 KB)` : `${relative}:\n\`\`\`\n${text}\n\`\`\``; + continue; + } + labels.push(attachmentLabel({ kind, path: relative })); + resolved.push({ kind: 'file', absolutePath, relativePath: relative, text }); } - return { resolved, labels }; + return parsed; } private queueTerminalOutput(live: Live, terminalId: string, chunk: string, exitCode: number | null | undefined, truncated: boolean): void { diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts index f4207c9e..6df9eee3 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -37,6 +37,7 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi handle(C.rename, (event, id, title) => service.rename(portOf(event.sender), id, title)); handle(C.remove, (event, id, options) => service.remove(portOf(event.sender), id, options)); handle(C.markRead, (event, id) => service.markRead(portOf(event.sender), id)); + handle(C.listPrompts, (event, id) => service.listPrompts(portOf(event.sender), id)); handle(C.watchInXr, (event, id) => service.watchInXr(portOf(event.sender), id)); handle(C.changes, (event, id) => service.changes(portOf(event.sender), id)); handle(C.changeDiff, (event, id, filePath) => service.changeDiff(portOf(event.sender), id, filePath)); diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 0b9631a7..868c5db1 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -19,6 +19,8 @@ import { AgentSessionService, type WindowPort } from './agentSessionService.ts'; import { SessionStore } from './sessionStore.ts'; import { AgentFlowFeed } from './agentFlowFeed.ts'; import { codexrMcpServerSpec } from './codexrMcpSpec.ts'; +import { ideContextSources } from './promptContext.ts'; +import { runGit } from '../git/gitRunner.ts'; import { SessionChanges } from '../checkpoints/sessionChanges.ts'; import { toTurnMetricDeltaView } from '../analysis/metricDelta.ts'; import type { AnalysisService } from '../analysis/analysisService.ts'; @@ -273,6 +275,12 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS const analysisDir = owner ? (options.analysisOutput?.(owner) ?? null) : null; return [codexrMcpServerSpec({ execPath: process.execPath, appPath: app.getAppPath(), root, analysisDir, isPackaged: app.isPackaged })]; }, + // #522/#528: @hotspots, @metrics, @diff and the prompt library's placeholders, from the + // analysis of the window that has the project open and from git in the chat's folder. + contextSources: ideContextSources((root) => { + const owner = windowOf(root); + return owner ? (options.analysisOutput?.(owner) ?? null) : null; + }, runGit), // AF12: chats started in a worktree get it here, outside every project. worktreeStorageDir: path.join(userData, 'worktrees'), spawnAllowed: !options.isSmoke, diff --git a/apps/ide/src/main/agentSessions/promptContext.ts b/apps/ide/src/main/agentSessions/promptContext.ts new file mode 100644 index 00000000..24b8e7c4 --- /dev/null +++ b/apps/ide/src/main/agentSessions/promptContext.ts @@ -0,0 +1,197 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { + cleanTerminalOutput, CONTEXT_BUDGET_CHARS, contextMentionLabel, type ContextMentionKind, +} from '@codexr/core/agent-prompts/contextMentions'; +import { + expandPrompt, matchPromptCommand, MAX_PROMPT_FILE_CHARS, MAX_PROMPT_FILES, mergePromptLibrary, parsePromptFile, PROMPT_LIBRARY_DIR, + type PromptPlaceholder, type PromptTemplate, +} from '@codexr/core/agent-prompts/promptLibrary'; +import type { PromptCommandView } from '../../shared/agentSession.ts'; +import { ANALYSIS_QUERIES, NO_ANALYSIS } from '../agents/tools/analysisQueries.ts'; +import type { GitRunner } from '../git/gitRunner.ts'; + +/** + * #522 (O20) and #528 (O26): the main-process half of a chat's live context. + * The `@hotspots`, `@metrics:` and `@diff` mentions and the prompt + * library's `{{hotspots}}` / `{{diff}}` placeholders are resolved here, from + * the analysis the window has open and from git; `@problems` and `@terminal` + * arrive as the window's snapshots and are only cleaned here. Parsing, + * formatting and the size cap are the core's (`agent-prompts/`), shared with + * the VS Code extension; this file is the IDE's sources behind them, injected + * into the chat service so the tests use fakes. + */ + +/** Where the live data comes from. Each method answers text or throws a readable Error. */ +export interface ContextSources { + /** The project's top files by complexity, from the analysis open on `root`. */ + hotspots(root: string): Promise; + /** One file's (or folder's) metrics, from the analysis open on `root`. */ + metrics(root: string, file: string): Promise; + /** The uncommitted changes of the folder the agent works in. */ + diff(workRoot: string): Promise; +} + +/** The two folders a chat has: its project (the analysis follows it) and the one its agent works in (a worktree, AF12). */ +export interface ContextRoots { + readonly root: string; + readonly workRoot: string; +} + +const MAX_DIFF_CHARS = 100_000; +const HOTSPOT_LIMIT = 10; + +/** + * The IDE's sources: the analysis queries the agents' Code-XR tools use + * (AF10), over the static folder of the window that has the project open, + * and git in the chat's folder. + */ +export function ideContextSources(analysisDir: (root: string) => string | null, git: GitRunner): ContextSources { + const query = async (name: string, root: string, args: Record): Promise => { + const dir = analysisDir(root); + if (!dir) { + throw new Error(NO_ANALYSIS); + } + const found = ANALYSIS_QUERIES.find((candidate) => candidate.name === name); + if (!found) { + throw new Error(`Unknown analysis query ${name}.`); + } + return found.run(args, dir); + }; + return { + hotspots: (root) => query('get_hotspots', root, { limit: HOTSPOT_LIMIT }), + metrics: (root, file) => query('get_metrics', root, { path: file }), + diff: async (workRoot) => gitDiff(git, workRoot), + }; +} + +/** `git diff HEAD` plus the names of untracked files; a repository without commits diffs the index. */ +export async function gitDiff(git: GitRunner, cwd: string): Promise { + const flags = ['--no-ext-diff', '--no-textconv', '--no-color']; + let diff: string; + try { + diff = (await git(cwd, ['diff', ...flags, 'HEAD', '--'])).stdout; + } catch { + try { + diff = (await git(cwd, ['diff', ...flags, '--cached', '--'])).stdout; + } catch { + throw new Error('The project is not a Git repository, so it has no diff.'); + } + } + const untracked = (await git(cwd, ['ls-files', '--others', '--exclude-standard']).catch(() => ({ stdout: '' }))).stdout + .split(/\r?\n/).filter(Boolean); + const parts: string[] = []; + if (diff.trim()) { + parts.push(diff.length > MAX_DIFF_CHARS ? `${diff.slice(0, MAX_DIFF_CHARS)}\n... (diff cut at ${MAX_DIFF_CHARS / 1000}k characters)` : diff.trimEnd()); + } + if (untracked.length) { + parts.push(`Untracked files:\n${untracked.slice(0, 200).map((file) => ` ${file}`).join('\n')}${untracked.length > 200 ? `\n ... and ${untracked.length - 200} more` : ''}`); + } + return parts.length ? parts.join('\n\n') : 'No uncommitted changes.'; +} + +/** One context mention as the attachment the window sent, checked. */ +export interface ContextRequest { + readonly context: ContextMentionKind; + readonly path?: string; + /** `problems` / `terminal`: the window's snapshot. */ + readonly text?: string; +} + +/** + * One mention's `{ label, body }`, never throwing: a source that fails (no + * analysis open, no git) becomes a body saying why, so the message still goes + * and the agent knows what it lacks. + */ +export async function resolveContext(request: ContextRequest, roots: ContextRoots, sources: ContextSources | undefined): Promise<{ readonly label: string; readonly body: string }> { + const label = contextMentionLabel(request.context === 'metrics' ? { kind: 'metrics', argument: request.path ?? '' } : { kind: request.context }); + try { + switch (request.context) { + case 'problems': + return { label, body: (request.text ?? '').trim() || 'No problems are reported.' }; + case 'terminal': + return { label, body: cleanTerminalOutput(request.text ?? '') }; + case 'hotspots': + case 'metrics': + case 'diff': { + if (!sources) { + throw new Error('Live context is not available here.'); + } + const body = request.context === 'hotspots' + ? await sources.hotspots(roots.root) + : request.context === 'diff' ? await sources.diff(roots.workRoot) : await sources.metrics(roots.root, request.path ?? ''); + return { label, body }; + } + } + } catch (error) { + return { label, body: `(unavailable: ${error instanceof Error ? error.message : String(error)})` }; + } +} + +// ---- Prompt library (#528) ---------------------------------------------------- + +/** The project's `.codexr/prompts/*.md` (unreadable or invalid files are skipped), merged with the built-in prompts. */ +export async function readPromptLibrary(root: string): Promise { + const dir = path.join(root, ...PROMPT_LIBRARY_DIR.split('/')); + const entries = await fs.promises.readdir(dir, { withFileTypes: true }).catch(() => []); + const project: PromptTemplate[] = []; + for (const entry of entries.filter((candidate) => candidate.isFile() && /\.md$/i.test(candidate.name)).sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_PROMPT_FILES)) { + const file = path.join(dir, entry.name); + const stat = await fs.promises.stat(file).catch(() => null); + if (!stat || stat.size > MAX_PROMPT_FILE_CHARS * 4) { + continue; + } + const text = await fs.promises.readFile(file, 'utf8').catch(() => null); + const parsed = text === null ? null : parsePromptFile(`${PROMPT_LIBRARY_DIR}/${entry.name}`, text); + if (parsed) { + project.push(parsed); + } + } + return mergePromptLibrary(project); +} + +export function promptCommandViews(prompts: readonly PromptTemplate[]): PromptCommandView[] { + return prompts.map((prompt) => ({ name: prompt.name, description: prompt.description, source: prompt.source, placeholders: prompt.placeholders })); +} + +/** What the window sent for the placeholders it holds (the editor, the Problems panel). */ +export interface PlaceholderSnapshots { + readonly selection?: string; + readonly file?: string; + readonly problems?: string; +} + +/** + * The message as the agent receives it: a library command (`/name input`) + * expanded with live values, or the text unchanged when it runs none. + * `hotspots` and `diff` come from `sources`; the rest from the window's + * snapshots. Every value together stays within the context budget. + */ +export async function expandLibraryCommand( + text: string, + prompts: readonly PromptTemplate[], + agentCommands: readonly string[], + roots: ContextRoots, + sources: ContextSources | undefined, + snapshots: PlaceholderSnapshots, +): Promise<{ readonly text: string; readonly prompt: PromptTemplate | null }> { + const match = matchPromptCommand(text, prompts, agentCommands); + if (!match) { + return { text, prompt: null }; + } + const share = Math.floor(CONTEXT_BUDGET_CHARS / Math.max(1, match.prompt.placeholders.length)); + const values: Partial> = {}; + for (const placeholder of match.prompt.placeholders) { + let value: string | undefined; + if (placeholder === 'hotspots' || placeholder === 'diff') { + const resolved = await resolveContext({ context: placeholder }, roots, sources); + value = resolved.body; + } else { + value = snapshots[placeholder]; + } + if (value !== undefined) { + values[placeholder] = value.length > share ? `${value.slice(0, share)}\n... (truncated to fit the context budget)` : value; + } + } + return { text: expandPrompt(match.prompt, values, match.input), prompt: match.prompt }; +} diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 0b14828f..782d1407 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -249,6 +249,13 @@ .af-send svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; } .af-send[data-action='stop'] svg { fill: currentColor; } .af-slash-name { font-family: var(--font-mono); } +/* #528: a library prompt among the agent's commands. */ +.af-slash-badge { margin-left: 6px; padding: 0 4px; border: 1px solid var(--line); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-xs); } +/* #522: images of a message: a thumbnail in the composer's chip and on the sent message. */ +.chat-chip.is-image { gap: 4px; padding-left: 2px; } +.chat-chip-thumb { width: 20px; height: 20px; object-fit: cover; border-radius: var(--radius-sm); } +.af-user-images { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } +.af-user-image { max-width: 96px; max-height: 96px; border: 1px solid var(--line); border-radius: var(--radius-sm); object-fit: contain; } /* ---- Project instructions (AF11) ---- */ .af-instr-list { list-style: none; margin: 0; padding: 0 4px; } diff --git a/apps/ide/src/renderer/agentFirst/chatModel.ts b/apps/ide/src/renderer/agentFirst/chatModel.ts index 1397548e..780b5ada 100644 --- a/apps/ide/src/renderer/agentFirst/chatModel.ts +++ b/apps/ide/src/renderer/agentFirst/chatModel.ts @@ -1,4 +1,7 @@ -import type { AgentSessionState, PromptAttachment, SlashCommandView, TranscriptItem } from '../../shared/agentSession.ts'; +import type { AgentSessionState, PromptAttachment, PromptCommandView, SlashCommandView, TranscriptItem } from '../../shared/agentSession.ts'; +import type { ChatAttachment } from '../../shared/agents.ts'; +import { contextMentionLabel, findContextMentions, MAX_PROMPT_IMAGE_BYTES, MAX_PROMPT_IMAGES, PROMPT_IMAGE_TYPES } from '@codexr/core/agent-prompts/contextMentions'; +import { matchPromptCommand, type PromptPlaceholder } from '@codexr/core/agent-prompts/promptLibrary'; import { diffLines, splitLines } from '../../shared/lineDiff.ts'; import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; @@ -167,7 +170,16 @@ export function lastUserIndex(items: readonly TranscriptItem[]): number { /** The label of an attachment chip. */ export function attachmentLabel(item: PromptAttachment): string { - return item.kind === 'selection' && item.startLine !== undefined ? `${item.path}:${item.startLine}-${item.endLine ?? item.startLine}` : item.path; + switch (item.kind) { + case 'selection': + return item.startLine !== undefined ? `${item.path}:${item.startLine}-${item.endLine ?? item.startLine}` : item.path; + case 'context': + return contextMentionLabel(item.context === 'metrics' ? { kind: 'metrics', argument: item.path ?? '' } : { kind: item.context }); + case 'image': + return item.name ?? 'image'; + default: + return item.path; + } } /** "12k / 200k" for the context meter. */ @@ -254,3 +266,111 @@ export function chatAnnouncement(prev: AnnouncedState | null, next: AnnouncedSta } return null; } + +// ---- #522 (O20) / #528 (O26): context mentions, images, the prompt library ----- + +/** A slash suggestion: the agent's own command, or (#528) a prompt of the library. */ +export interface SlashSuggestion extends SlashCommandView { + readonly library?: 'builtin' | 'project'; +} + +/** + * #528: the agent's commands, then the library's prompts whose names the + * agent does not already use (its own commands are never shadowed). + */ +export function mergeSlashCommands(agent: readonly SlashCommandView[], prompts: readonly PromptCommandView[]): SlashSuggestion[] { + const taken = new Set(agent.map((command) => command.name.toLowerCase())); + return [ + ...agent, + ...prompts.filter((prompt) => !taken.has(prompt.name.toLowerCase())).map((prompt): SlashSuggestion => ({ name: prompt.name, description: prompt.description, library: prompt.source })), + ]; +} + +/** What the window can snapshot for a message: the editor and the panels (#522, #528). */ +export interface ComposerSnapshots { + selection(): Extract | null; + /** The active editor's file (workspace path), or null. */ + activeFile(): string | null; + /** The Problems panel, formatted (`formatProblems`). */ + problems(): string; + /** The active terminal's recent text. */ + terminal(): string; +} + +/** + * The composer's chips as the `prompt` call's attachments, plus what the text + * needs: `@problems` / `@terminal` (chips or typed) carry the window's + * snapshot, and a library command (#528) gets the snapshots its placeholders + * use as inline attachments (they fill the prompt and are not sent on their own). + */ +export function promptAttachmentsFor(text: string, items: readonly ChatAttachment[], snapshots: ComposerSnapshots, prompts: readonly PromptCommandView[], agentCommands: readonly SlashCommandView[]): PromptAttachment[] { + const out: PromptAttachment[] = []; + const snapshotOf = (context: 'problems' | 'terminal'): string => (context === 'problems' ? snapshots.problems() : snapshots.terminal()); + const hasContext = (context: string, path?: string): boolean => out.some((item) => item.kind === 'context' && !item.inline && item.context === context && (item.path ?? '') === (path ?? '')); + for (const item of items) { + switch (item.kind) { + case 'file': + out.push({ kind: 'file', path: item.path }); + break; + case 'selection': + out.push({ kind: 'selection', path: item.path, startLine: item.startLine, endLine: item.endLine, text: item.text }); + break; + case 'context': + if (!hasContext(item.context, item.path)) { + out.push(item.context === 'problems' || item.context === 'terminal' + ? { kind: 'context', context: item.context, text: snapshotOf(item.context) } + : { kind: 'context', context: item.context, ...(item.path ? { path: item.path } : {}) }); + } + break; + case 'image': + out.push({ kind: 'image', mimeType: item.mimeType, data: item.data, name: item.name, thumbnail: item.thumbnail }); + break; + } + } + for (const mention of findContextMentions(text)) { + if ((mention.kind === 'problems' || mention.kind === 'terminal') && !hasContext(mention.kind)) { + out.push({ kind: 'context', context: mention.kind, text: snapshotOf(mention.kind) }); + } + } + const command = matchPromptCommand(text, prompts.map((prompt) => ({ ...prompt, body: '' })), agentCommands.map((entry) => entry.name)); + for (const placeholder of command?.prompt.placeholders ?? []) { + out.push(...placeholderAttachments(placeholder, snapshots)); + } + return out; +} + +function placeholderAttachments(placeholder: PromptPlaceholder, snapshots: ComposerSnapshots): PromptAttachment[] { + if (placeholder === 'selection') { + const selection = snapshots.selection(); + return selection ? [{ kind: 'selection', path: selection.path, startLine: selection.startLine, endLine: selection.endLine, text: selection.text, inline: true }] : []; + } + if (placeholder === 'file') { + const file = snapshots.activeFile(); + return file ? [{ kind: 'file', path: file, inline: true }] : []; + } + if (placeholder === 'problems') { + return [{ kind: 'context', context: 'problems', text: snapshots.problems(), inline: true }]; + } + // hotspots and diff are resolved by the main process. + return []; +} + +/** #522: why a pasted or dropped file cannot be attached as an image, as a message key, or null. */ +export function imageRejection(type: string, size: number, imagesSoFar: number, agentAcceptsImages: boolean | undefined): MessageKey | null { + if (agentAcceptsImages !== true) { + return 'chat.image.unsupported'; + } + if (!PROMPT_IMAGE_TYPES.includes(type)) { + return 'chat.image.type'; + } + if (size > MAX_PROMPT_IMAGE_BYTES) { + return 'chat.image.size'; + } + return imagesSoFar >= MAX_PROMPT_IMAGES ? 'chat.image.tooMany' : null; +} + +/** #522: a thumbnail's size that keeps the image's proportions within `max` pixels on its longer side (never enlarged). */ +export function thumbnailSize(width: number, height: number, max = 96): { readonly width: number; readonly height: number } { + const scale = Math.min(1, max / Math.max(width, height, 1)); + return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) }; +} diff --git a/apps/ide/src/renderer/agentFirst/chatView.ts b/apps/ide/src/renderer/agentFirst/chatView.ts index 8f0c0ca5..2df56fd1 100644 --- a/apps/ide/src/renderer/agentFirst/chatView.ts +++ b/apps/ide/src/renderer/agentFirst/chatView.ts @@ -3,7 +3,7 @@ import type { ChatAttachment } from '../../shared/agents.ts'; import type { TerminalCreated } from '../../shared/api.ts'; import { applySessionEvent, type AgentSessionMessage, type AgentSessionState, type AgentSessionsApi, type ConfigOptionView, - type PlanEntryView, type PromptAttachment, type ToolContentView, type TranscriptItem, type TurnMetricDeltaView, + type PlanEntryView, type PromptAttachment, type PromptCommandView, type ToolContentView, type TranscriptItem, type TurnMetricDeltaView, } from '../../shared/agentSession.ts'; import { metricDeltaFileLines, metricDeltaHeadline, restorePrompt } from './changesModel.ts'; import { renderMarkdown } from '../agents/chatMarkdown.ts'; @@ -14,8 +14,10 @@ import { createWorktreeBar } from './worktreeBar.ts'; import { branchLabel, branchTitle } from './worktreeModel.ts'; import { changeCounts, chatAnnouncement, chatPhase, composerAction, diffLinesForCard, displayPath, escapeIntent, ESCAPE_STOP_WINDOW_MS, formatTokens, lastUserIndex, - slashSuggestions, starterPrompts, TOOL_ICONS, toolStatusLabel, turnChanges, + imageRejection, mergeSlashCommands, promptAttachmentsFor, slashSuggestions, starterPrompts, thumbnailSize, TOOL_ICONS, toolStatusLabel, turnChanges, + type ComposerSnapshots, type SlashSuggestion, } from './chatModel.ts'; +import { MAX_IMAGE_THUMBNAIL_CHARS } from '@codexr/core/agent-prompts/contextMentions'; /** * One agent chat (AF3, #268): a normal coding chat, the way the person works @@ -259,11 +261,30 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView }); // #487: grows with its text on WebKit too, which has no `field-sizing`. const fitInput = autosizeTextarea(input); - const bar = createAttachmentBar(input, deps.attachments); + const bar = createAttachmentBar(input, { ...deps.attachments, contextMentions: true }); + /** #528: the prompt library of the chat's project, read when the chat loads and each time `/` opens the list. */ + let prompts: readonly PromptCommandView[] = []; + const refreshPrompts = (): void => { + deps.api.listPrompts(sessionId).then((list) => { + prompts = list; + if (!disposed && input.value.startsWith('/')) { + showSlash(); + } + }, () => undefined); + }; + const snapshots: ComposerSnapshots = { + selection: () => { + const selection = deps.attachments.activeSelection(); + return selection?.kind === 'selection' ? selection : null; + }, + activeFile: () => deps.attachments.activeFile?.() ?? null, + problems: () => deps.attachments.problems?.() ?? '', + terminal: () => deps.attachments.terminalOutput?.() ?? '', + }; slashPopupCount += 1; const slashId = `af-slash-${slashPopupCount}`; const slashPopup = el('ul', { className: 'chat-mention af-slash', attrs: { role: 'listbox', id: slashId, hidden: '', 'aria-label': t('chat.commands') } }); - let slashItems: ReturnType = []; + let slashItems: SlashSuggestion[] = []; let slashSelected = 0; // The attachment bar shows and hides its own popup: the combobox follows it. const mentionObserver = new MutationObserver(() => syncCombobox()); @@ -421,9 +442,16 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView const chips = item.attachments?.length ? el('div', { className: 'chat-chips is-static' }, item.attachments.map((label) => el('span', { className: 'chat-chip', attrs: { title: label } }, [el('span', { className: 'chat-chip-label', text: label })]))) : null; + // #522: the images the message carried, as their thumbnails. + const images = item.images?.length + ? el('div', { className: 'af-user-images' }, item.images.map((image) => (image.thumbnail + ? el('img', { className: 'af-user-image', attrs: { src: image.thumbnail, alt: t('chat.image.alt', { name: image.name }), title: image.name } }) + : el('span', { className: 'chat-chip', text: image.name })))) + : null; return el('div', { className: item.remote ? 'af-message is-user is-remote' : 'af-message is-user', attrs: { 'data-testid': 'af-user' } }, [ ...(item.remote ? [el('span', { className: 'af-remote-origin muted', text: t('chat.fromClaude') })] : []), el('p', { className: 'af-user-text', text: item.text }), + ...(images ? [images] : []), ...(chips ? [chips] : []), actions, ]); @@ -751,12 +779,79 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView updateSendButton(); } - function toPromptAttachments(items: readonly ChatAttachment[]): PromptAttachment[] { - return items.map((item) => (item.kind === 'file' - ? { kind: 'file', path: item.path } - : { kind: 'selection', path: item.path, startLine: item.startLine, endLine: item.endLine, text: item.text })); + function toPromptAttachments(text: string, items: readonly ChatAttachment[]): PromptAttachment[] { + return promptAttachmentsFor(text, items, snapshots, prompts, state?.commands ?? []); + } + + // ---- #522: images pasted or dropped into the composer -------------------- + /** A small JPEG/PNG data URL of the image, for its chip and the message in the transcript. */ + async function thumbnailOf(file: Blob): Promise { + const bitmap = await createImageBitmap(file); + try { + const size = thumbnailSize(bitmap.width, bitmap.height); + const canvas = document.createElement('canvas'); + canvas.width = size.width; + canvas.height = size.height; + canvas.getContext('2d')?.drawImage(bitmap, 0, 0, size.width, size.height); + const url = canvas.toDataURL('image/jpeg', 0.7); + return url.length <= MAX_IMAGE_THUMBNAIL_CHARS ? url : canvas.toDataURL('image/jpeg', 0.4); + } finally { + bitmap.close(); + } + } + + function base64Of(file: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + const url = String(reader.result ?? ''); + resolve(url.slice(url.indexOf(',') + 1)); + }; + reader.onerror = () => reject(reader.error ?? new Error('unreadable')); + reader.readAsDataURL(file); + }); + } + + /** Attaches the images among `files`; true when there was at least one image (so the paste or drop is handled). */ + function attachImages(files: readonly File[]): boolean { + const images = files.filter((file) => file.type.startsWith('image/')); + if (images.length === 0) { + return false; + } + for (const file of images) { + const count = bar.items().filter((item) => item.kind === 'image').length; + const rejected = imageRejection(file.type, file.size, count, state?.promptImages); + if (rejected) { + deps.onStatus(t(rejected)); + continue; + } + Promise.all([base64Of(file), thumbnailOf(file)]).then(([data, thumbnail]) => { + if (!disposed) { + bar.restore({ kind: 'image', mimeType: file.type, data, name: file.name || `image-${count + 1}.${file.type.split('/')[1] ?? 'png'}`, thumbnail }); + } + }, () => deps.onStatus(t('chat.image.unreadable'))); + } + return true; } + input.addEventListener('paste', (event) => { + const files = [...(event.clipboardData?.files ?? [])]; + if (attachImages(files)) { + event.preventDefault(); + } + }); + input.addEventListener('dragover', (event) => { + if ([...(event.dataTransfer?.items ?? [])].some((item) => item.kind === 'file' && item.type.startsWith('image/'))) { + event.preventDefault(); + } + }); + input.addEventListener('drop', (event) => { + const files = [...(event.dataTransfer?.files ?? [])]; + if (attachImages(files)) { + event.preventDefault(); + } + }); + function submit(): void { if (!state) { return; @@ -770,7 +865,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView return; } const text = input.value; - const attachments = toPromptAttachments(bar.items()); + const attachments = toPromptAttachments(text, bar.items()); input.value = ''; fitInput(); bar.clear(); @@ -800,13 +895,14 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView } function showSlash(): void { - slashItems = state ? slashSuggestions(input.value, state.commands) : []; + slashItems = state ? slashSuggestions(input.value, mergeSlashCommands(state.commands, prompts)) : []; slashPopup.hidden = slashItems.length === 0; slashSelected = Math.min(slashSelected, Math.max(0, slashItems.length - 1)); slashPopup.replaceChildren(...slashItems.map((command, index) => { const row = el('li', { className: 'chat-mention-row', attrs: { role: 'option', id: `${slashId}-${index}`, 'aria-selected': String(index === slashSelected) } }, [ el('span', { className: 'af-slash-name', text: `/${command.name}` }), el('span', { className: 'muted', text: ` ${command.description}` }), + ...(command.library ? [el('span', { className: 'af-slash-badge', text: t(command.library === 'builtin' ? 'chat.prompt.builtin' : 'chat.prompt.project') })] : []), ]); row.addEventListener('mousedown', (event) => { event.preventDefault(); @@ -854,6 +950,10 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView input.addEventListener('input', () => { slashSelected = 0; + if (input.value === '/') { + // #528: an edited or new prompt file shows the next time the list opens. + refreshPrompts(); + } showSlash(); updateSendButton(); }); @@ -914,6 +1014,7 @@ export function createChatView(sessionId: string, deps: ChatViewDeps): ChatView return; } state = loaded; + refreshPrompts(); rendered.forEach((entry) => entry.node.remove()); rendered.clear(); drawnItems = null; diff --git a/apps/ide/src/renderer/agents/chatAttachments.ts b/apps/ide/src/renderer/agents/chatAttachments.ts index fcd3f297..eb3df136 100644 --- a/apps/ide/src/renderer/agents/chatAttachments.ts +++ b/apps/ide/src/renderer/agents/chatAttachments.ts @@ -1,4 +1,6 @@ import type { ChatAttachment } from '../../shared/agents.ts'; +import { contextMentionSuggestions, metricsFileQuery, type ContextMentionKind } from '@codexr/core/agent-prompts/contextMentions'; +import { t } from '../../shared/i18n/i18n.ts'; import { el, icon } from '../dom.ts'; /** @@ -14,6 +16,14 @@ export interface AttachmentSources { /** The selection in the active editor, if any. */ activeSelection(): ChatAttachment | null; onStatus(message: string): void; + /** #522: also offer the analysis-aware mentions (`@hotspots`, `@problems`, `@diff`, `@terminal`, `@metrics:`). */ + readonly contextMentions?: boolean; + /** #528: the active editor's file (workspace path), for the prompt library's `{{file}}`. */ + activeFile?(): string | null; + /** #522: the Problems panel as text (`formatProblems`), for `@problems` and `{{problems}}`. */ + problems?(): string; + /** #522: the active terminal's recent output, for `@terminal`. */ + terminalOutput?(): string; } export interface AttachmentBar { @@ -32,8 +42,34 @@ const MAX_SUGGESTIONS = 8; const SELECTION = '@selection'; const PAPERCLIP = 'M8 12l6-6a3 3 0 0 1 4 4l-8 8a5 5 0 0 1-7-7l7-7'; +const METRICS_PREFIX = '@metrics:'; + export function labelOf(item: ChatAttachment): string { - return item.kind === 'file' ? item.path : `${item.path}:${item.startLine}-${item.endLine}`; + switch (item.kind) { + case 'file': + return item.path; + case 'selection': + return `${item.path}:${item.startLine}-${item.endLine}`; + case 'context': + return item.context === 'metrics' ? `${METRICS_PREFIX}${item.path ?? ''}` : `@${item.context}`; + case 'image': + return item.name; + } +} + +/** #522: a popup row's text: the special entries are described, files are their paths. */ +function suggestionText(value: string): string { + if (value === SELECTION) { + return '@selection (the editor selection)'; + } + if (value.startsWith(METRICS_PREFIX) && value.length > METRICS_PREFIX.length) { + return t('chat.mention.metricsFile', { file: value.slice(METRICS_PREFIX.length) }); + } + if (value.startsWith('@')) { + const kind = value.slice(1).replace(/:$/, '') as ContextMentionKind; + return t(`chat.mention.${kind}`); + } + return value; } export function createAttachmentBar(input: HTMLTextAreaElement, sources: AttachmentSources): AttachmentBar { @@ -57,7 +93,8 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm renderChips(); input.focus(); }); - return el('span', { className: 'chat-chip', attrs: { title: labelOf(item) } }, [el('span', { className: 'chat-chip-label', text: labelOf(item) }), remove]); + const thumbnail = item.kind === 'image' ? [el('img', { className: 'chat-chip-thumb', attrs: { src: item.thumbnail, alt: t('chat.image.alt', { name: item.name }) } })] : []; + return el('span', { className: item.kind === 'image' ? 'chat-chip is-image' : 'chat-chip', attrs: { title: labelOf(item) } }, [...thumbnail, el('span', { className: 'chat-chip-label', text: labelOf(item) }), remove]); })); }; const add = (item: ChatAttachment): void => { @@ -88,7 +125,7 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm }; const renderPopup = (): void => { popup.replaceChildren(...suggestions.map((value, index) => { - const row = el('li', { className: 'chat-mention-row', text: value === SELECTION ? '@selection (the editor selection)' : value, attrs: { role: 'option', id: `chat-mention-${index}`, 'aria-selected': String(index === selected) } }); + const row = el('li', { className: 'chat-mention-row', text: suggestionText(value), attrs: { role: 'option', id: `chat-mention-${index}`, 'aria-selected': String(index === selected) } }); row.addEventListener('mousedown', (event) => { event.preventDefault(); pick(index); @@ -117,10 +154,17 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm } } } - const query = mention.query.toLowerCase(); + const metricsQuery = sources.contextMentions ? metricsFileQuery(mention.query) : null; + const query = (metricsQuery ?? mention.query).toLowerCase(); const matches = (files ?? []).filter((file) => file.toLowerCase().includes(query)) .sort((a, b) => Number(!a.toLowerCase().split('/').pop()?.startsWith(query)) - Number(!b.toLowerCase().split('/').pop()?.startsWith(query)) || a.length - b.length); - suggestions = [...(SELECTION.slice(1).startsWith(query) ? [SELECTION] : []), ...matches].slice(0, MAX_SUGGESTIONS); + if (metricsQuery !== null) { + // #522: `@metrics:` then the file, chosen from the same list. + suggestions = matches.map((file) => `${METRICS_PREFIX}${file}`).slice(0, MAX_SUGGESTIONS); + } else { + const contexts = sources.contextMentions ? contextMentionSuggestions(query).map((kind) => (kind === 'metrics' ? METRICS_PREFIX : `@${kind}`)) : []; + suggestions = [...(SELECTION.slice(1).startsWith(query) ? [SELECTION] : []), ...contexts, ...matches].slice(0, MAX_SUGGESTIONS); + } selected = 0; renderPopup(); }; @@ -132,10 +176,23 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm return; } const end = input.selectionStart; + if (value === METRICS_PREFIX) { + // #522: keeps `@metrics:` in the box and lists the files to choose from. + input.value = `${input.value.slice(0, mention.start)}${METRICS_PREFIX}${input.value.slice(end)}`; + const caret = mention.start + METRICS_PREFIX.length; + input.setSelectionRange(caret, caret); + input.focus(); + void update(); + return; + } input.value = `${input.value.slice(0, mention.start)}${input.value.slice(end)}`; input.setSelectionRange(mention.start, mention.start); if (value === SELECTION) { addSelection(); + } else if (value.startsWith(METRICS_PREFIX)) { + add({ kind: 'context', context: 'metrics', path: value.slice(METRICS_PREFIX.length) }); + } else if (value.startsWith('@')) { + add({ kind: 'context', context: value.slice(1) as ContextMentionKind }); } else { add({ kind: 'file', path: value }); } diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 6c29db1b..3b81afa5 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -36,6 +36,7 @@ import { displayPath } from './agentFirst/chatModel.ts'; import { createEditReviewer } from './agents/editReview.ts'; import { registerAgentCommands } from './agents/agentCommands.ts'; import { createProblemsView } from './problems/problemsView.ts'; +import { formatProblems } from '@codexr/core/agent-prompts/contextMentions'; import { metricProblems, type FunctionMetricsSnapshot, type MetricThresholds, type Problem } from '../shared/problems.ts'; import type { EditorGroup } from './editor/editorGroup.ts'; import type { CustomEditorInput } from './editor/customEditor.ts'; @@ -1360,6 +1361,10 @@ const agentWorkbench = installAgentWorkbench({ return selection ? { kind: 'selection', ...selection } : null; }, onStatus: (message) => workbench.setStatus(message), + // #522/#528: what @problems, @terminal and the prompt library's {{file}} / {{problems}} send. + activeFile: () => editors?.activeModel()?.path ?? null, + problems: () => formatProblems(problemsView.all()), + terminalOutput: () => terminal.recentOutput(), }, instructions: { listFiles: async () => (await api.workspace.listFiles()).files, diff --git a/apps/ide/src/renderer/problems/problemsView.ts b/apps/ide/src/renderer/problems/problemsView.ts index 98d30e9f..42810a99 100644 --- a/apps/ide/src/renderer/problems/problemsView.ts +++ b/apps/ide/src/renderer/problems/problemsView.ts @@ -35,6 +35,8 @@ export interface ProblemsView { focusFilter(): void; /** #178: shows the panel filtered to these words (a lens's function). */ filterTo(text: string): void; + /** #522: every problem the panel holds (editor, metric and task problems), unfiltered: what `@problems` sends. */ + all(): readonly Problem[]; } export interface ProblemsHooks { @@ -292,5 +294,6 @@ export function createProblemsView(host: PanelHost, hooks: ProblemsHooks): Probl host.show('problems'); render(); }, + all: () => [...editorProblems, ...metricProblems, ...[...taskProblems.values()].flat()], }; } diff --git a/apps/ide/src/renderer/terminal/terminalPanel.ts b/apps/ide/src/renderer/terminal/terminalPanel.ts index a1c167e6..30043764 100644 --- a/apps/ide/src/renderer/terminal/terminalPanel.ts +++ b/apps/ide/src/renderer/terminal/terminalPanel.ts @@ -44,6 +44,8 @@ export interface TerminalPanel { find(): void; /** #499: loads xterm.js now (at idle), so the first terminal does not wait for it; starts nothing. */ preload(): Promise; + /** #522: the active terminal's last `maxLines` lines, '' without one (for `@terminal`). */ + recentOutput(maxLines?: number): string; } export interface TerminalPanelHooks { @@ -458,6 +460,10 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], newTerminal, runTask: (label, start) => openTerminal(start, label), preload: () => xterm().then(() => undefined), + recentOutput(maxLines = 200): string { + const active = activeId === null ? undefined : tabs.get(activeId); + return active ? active.view.recentText(maxLines) : ''; + }, setFontSize(size: number): void { if (size === fontSize) { return; diff --git a/apps/ide/src/renderer/terminal/xtermView.ts b/apps/ide/src/renderer/terminal/xtermView.ts index aa13c20d..83cc91a8 100644 --- a/apps/ide/src/renderer/terminal/xtermView.ts +++ b/apps/ide/src/renderer/terminal/xtermView.ts @@ -28,6 +28,8 @@ export interface XtermView { setFontSize(size: number): void; /** The selected text, or '' (#286: the find widget starts from it). */ selection(): string; + /** #522: the last `maxLines` lines of the scrollback as text (for `@terminal`). */ + recentText(maxLines: number): string; /** * #286: finds `term` in the scrollback and selects the next (or previous) * match; `incremental` keeps the current match while it still matches @@ -254,6 +256,23 @@ export function createXtermView(container: HTMLElement, options: XtermOptions): }, get rows() { return term.rows; }, selection: () => term.getSelection(), + recentText(maxLines: number): string { + const buffer = term.buffer.active; + const lines: string[] = []; + for (let row = Math.max(0, buffer.length - maxLines); row < buffer.length; row += 1) { + const line = buffer.getLine(row); + if (!line) { + continue; + } + const text = line.translateToString(true); + if (line.isWrapped && lines.length > 0) { + lines[lines.length - 1] += text; + } else { + lines.push(text); + } + } + return lines.join('\n'); + }, find(text, findOptions, direction, incremental = false): void { if (disposed) { return; diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index e4eb0709..a746e473 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -11,6 +11,8 @@ */ import type { TerminalCreated } from './api.ts'; +import type { ContextMentionKind } from '@codexr/core/agent-prompts/contextMentions'; +import type { PromptPlaceholder } from '@codexr/core/agent-prompts/promptLibrary'; // ---- Agents ---------------------------------------------------------------- @@ -190,6 +192,8 @@ export type TranscriptItem = readonly checkpoint?: string; /** #431: typed on claude.ai or the Claude mobile app, over Remote Control. */ readonly remote?: boolean; + /** #522: the images the message carried. */ + readonly images?: readonly MessageImageView[]; } | { readonly kind: 'assistant'; readonly id: string; readonly text: string } | { readonly kind: 'thought'; readonly id: string; readonly text: string } @@ -438,6 +442,8 @@ export interface AgentSessionState extends SessionSummary { readonly historyPending?: boolean; /** #431: absent until the agent listed its commands. */ readonly remoteControl?: RemoteControlView; + /** #522: the agent accepts images in a prompt (`promptCapabilities.image`); absent until it started. */ + readonly promptImages?: boolean; } /** #298: a chat the agent keeps in its own history (ACP `session/list`), offered for import. */ @@ -466,7 +472,9 @@ export interface ProjectSessions { * receives the same events and applies the same function. */ export type SessionEvent = - | { readonly type: 'user'; readonly id: string; readonly text: string; readonly at: string; readonly attachments?: readonly string[]; readonly checkpoint?: string; readonly remote?: boolean } + | { readonly type: 'user'; readonly id: string; readonly text: string; readonly at: string; readonly attachments?: readonly string[]; readonly checkpoint?: string; readonly remote?: boolean; readonly images?: readonly MessageImageView[] } + /** #522: what the agent accepts in a prompt (its `promptCapabilities`), learned when it starts. */ + | { readonly type: 'prompt-capabilities'; readonly image: boolean } | { readonly type: 'assistant-chunk'; readonly text: string } | { readonly type: 'thought-chunk'; readonly text: string } | { @@ -554,7 +562,7 @@ export function applySessionEvent(state: AgentSessionState, event: SessionEvent, switch (event.type) { case 'user': return touch({ - items: [...items, { kind: 'user', id: event.id, text: event.text, at: event.at, ...(event.attachments?.length ? { attachments: event.attachments } : {}), ...(event.checkpoint ? { checkpoint: event.checkpoint } : {}), ...(event.remote ? { remote: true } : {}) }], + items: [...items, { kind: 'user', id: event.id, text: event.text, at: event.at, ...(event.attachments?.length ? { attachments: event.attachments } : {}), ...(event.checkpoint ? { checkpoint: event.checkpoint } : {}), ...(event.remote ? { remote: true } : {}), ...(event.images?.length ? { images: event.images } : {}) }], // #431: a message from claude.ai starts a turn the IDE did not send, so no turn-end follows it here. status: event.remote ? state.status : 'running', // A new prompt starts a new plan only when the agent sends one. @@ -642,6 +650,8 @@ export function applySessionEvent(state: AgentSessionState, event: SessionEvent, return touch({ plan: event.entries }); case 'commands': return touch({ commands: event.commands }); + case 'prompt-capabilities': + return state.promptImages === event.image ? state : touch({ promptImages: event.image }); case 'modes': return touch({ modes: { current: event.current, available: event.available ?? state.modes?.available ?? [] } }); case 'config': @@ -729,14 +739,45 @@ export function titleFromPrompt(text: string): string { // ---- IPC ------------------------------------------------------------------- -export interface PromptAttachment { - readonly kind: 'file' | 'selection'; - /** Workspace-relative path. */ - readonly path: string; - readonly startLine?: number; - readonly endLine?: number; - /** The selected text (selection only); files are read by the main process. */ - readonly text?: string; +/** + * What a message carries besides its text. `path` is workspace-relative. + * `inline` (#528): only there to fill a prompt library placeholder + * (`{{selection}}`, `{{file}}`, `{{problems}}`); not sent as a block of its own. + */ +export type PromptAttachment = + | { readonly kind: 'file'; readonly path: string; readonly inline?: boolean } + | { + readonly kind: 'selection'; + readonly path: string; + readonly startLine?: number; + readonly endLine?: number; + /** The selected text; files are read by the main process. */ + readonly text?: string; + readonly inline?: boolean; + } + /** + * #522: an analysis-aware mention, resolved in the main process (`hotspots`, + * `diff`, `metrics` of `path`). `problems` and `terminal` live in the + * window's UI, which sends their `text` as a snapshot; the main process + * cleans, caps and formats it. + */ + | { readonly kind: 'context'; readonly context: ContextMentionKind; readonly path?: string; readonly text?: string; readonly inline?: boolean } + /** #522: a pasted or dropped image (base64), sent only to agents that accept images; `thumbnail` is a small data URL kept on the message. */ + | { readonly kind: 'image'; readonly mimeType: string; readonly data: string; readonly name?: string; readonly thumbnail?: string }; + +/** #528: a prompt of the library, offered as a slash command beside the agent's own. */ +export interface PromptCommandView { + readonly name: string; + readonly description: string; + readonly source: 'builtin' | 'project'; + /** The placeholders its text uses: the window sends the snapshots these need. */ + readonly placeholders: readonly PromptPlaceholder[]; +} + +/** #522: an image of the person's message, as the transcript shows it. */ +export interface MessageImageView { + readonly name: string; + readonly thumbnail?: string; } export const AGENT_SESSION_CHANNELS = { @@ -782,6 +823,7 @@ export const AGENT_SESSION_CHANNELS = { describeInstall: 'codexr:agent-sessions:describe-install', install: 'codexr:agent-sessions:install', uninstall: 'codexr:agent-sessions:uninstall', + listPrompts: 'codexr:agent-sessions:list-prompts', } as const; export const AGENT_SESSION_EVENTS = { @@ -912,5 +954,7 @@ export interface AgentSessionsApi { install(presetId: string): Promise; /** AF2: removes an adapter the IDE installed, after a native confirmation. */ uninstall(presetId: string): Promise; + /** #528: the prompt library of the chat's project (`.codexr/prompts/*.md`) and the built-in prompts, read now. */ + listPrompts(sessionId: string): Promise; onMessage(listener: (message: AgentSessionMessage) => void): () => void; } diff --git a/apps/ide/src/shared/agents.ts b/apps/ide/src/shared/agents.ts index 53cc5a8c..af3b91f3 100644 --- a/apps/ide/src/shared/agents.ts +++ b/apps/ide/src/shared/agents.ts @@ -290,7 +290,11 @@ export interface EditReviewResult { /** Context attached to a message (A6). The main process reads files itself; only the selection's text crosses. */ export type ChatAttachment = | { readonly kind: 'file'; readonly path: string } - | { readonly kind: 'selection'; readonly path: string; readonly startLine: number; readonly endLine: number; readonly text: string }; + | { readonly kind: 'selection'; readonly path: string; readonly startLine: number; readonly endLine: number; readonly text: string } + /** #522: an analysis-aware mention chip of the agent-first composer (`@hotspots`, `@metrics:`...). */ + | { readonly kind: 'context'; readonly context: 'hotspots' | 'problems' | 'diff' | 'terminal' | 'metrics'; readonly path?: string } + /** #522: a pasted or dropped image of the agent-first composer (base64) and its small thumbnail (a data URL). */ + | { readonly kind: 'image'; readonly mimeType: string; readonly data: string; readonly name: string; readonly thumbnail: string }; /** Main -> renderer events of the agent hub; api.ts merges them into IPC_EVENTS. */ export const AGENT_IPC_EVENTS = { diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index 719ffebb..419ef745 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -487,6 +487,20 @@ export const en = { 'chat.placeholder': 'Ask the agent to build, fix or explain something. @ to attach, / for commands.', 'chat.message': 'Message', 'chat.commands': 'Commands', + 'chat.mention.hotspots': '@hotspots: the project\'s complexity hotspots', + 'chat.mention.problems': '@problems: the Problems panel', + 'chat.mention.diff': '@diff: the uncommitted changes', + 'chat.mention.terminal': '@terminal: the terminal\'s recent output', + 'chat.mention.metrics': '@metrics:: one file\'s Code-XR metrics', + 'chat.mention.metricsFile': 'Metrics of {file}', + 'chat.prompt.builtin': 'Built-in prompt', + 'chat.prompt.project': 'Project prompt', + 'chat.image.unsupported': 'This agent does not accept images.', + 'chat.image.type': 'Only PNG, JPEG, WebP and GIF images can be attached.', + 'chat.image.size': 'Images larger than 5 MB cannot be attached.', + 'chat.image.tooMany': 'A message can carry at most 8 images.', + 'chat.image.unreadable': 'The image could not be read.', + 'chat.image.alt': 'Attached image {name}', 'chat.mode': 'Mode', 'chat.agentMode': 'Agent mode', 'chat.send': 'Send', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index 817d5016..2dd61c49 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -490,6 +490,20 @@ export const es: Readonly> = { 'chat.placeholder': 'Pide al agente que construya, corrija o explique algo. @ para adjuntar, / para comandos.', 'chat.message': 'Mensaje', 'chat.commands': 'Comandos', + 'chat.mention.hotspots': '@hotspots: los puntos críticos de complejidad del proyecto', + 'chat.mention.problems': '@problems: el panel Problemas', + 'chat.mention.diff': '@diff: los cambios sin confirmar', + 'chat.mention.terminal': '@terminal: la salida reciente del terminal', + 'chat.mention.metrics': '@metrics:: las métricas de Code-XR de un archivo', + 'chat.mention.metricsFile': 'Métricas de {file}', + 'chat.prompt.builtin': 'Prompt integrado', + 'chat.prompt.project': 'Prompt del proyecto', + 'chat.image.unsupported': 'Este agente no acepta imágenes.', + 'chat.image.type': 'Solo se pueden adjuntar imágenes PNG, JPEG, WebP y GIF.', + 'chat.image.size': 'No se pueden adjuntar imágenes de más de 5 MB.', + 'chat.image.tooMany': 'Un mensaje puede llevar como máximo 8 imágenes.', + 'chat.image.unreadable': 'No se pudo leer la imagen.', + 'chat.image.alt': 'Imagen adjunta {name}', 'chat.mode': 'Modo', 'chat.agentMode': 'Modo del agente', 'chat.send': 'Enviar', diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index 8d77086f..ddc842e6 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -291,7 +291,7 @@ interface FakeAgentLog { } /** A tiny ACP agent: its behaviour is chosen by the prompt's first word. */ -function fakeAgent(log: FakeAgentLog) { +function fakeAgent(log: FakeAgentLog, options: { image?: boolean } = {}) { let client: AgentContext | null = null; const update = (sessionId: string, value: unknown): Promise => (client as AgentContext).notify(methods.client.session.update, { sessionId, update: value as never }); return agent({ name: 'fake' }) @@ -302,7 +302,7 @@ function fakeAgent(log: FakeAgentLog) { log.clientCapabilities = params.clientCapabilities; return { protocolVersion: 1, - agentCapabilities: { loadSession: false, promptCapabilities: { embeddedContext: true } }, + agentCapabilities: { loadSession: false, promptCapabilities: { embeddedContext: true, ...(options.image ? { image: true } : {}) } }, authMethods: [{ id: 'login', name: 'Log in', type: 'terminal', args: ['--login'] }], } as never; }) @@ -403,7 +403,7 @@ function fakeAgent(log: FakeAgentLog) { }); } -async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges; claude?: boolean; claudeRemoteControl?: AgentSessionServiceOptions['claudeRemoteControl'] } = {}) { +async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges; claude?: boolean; claudeRemoteControl?: AgentSessionServiceOptions['claudeRemoteControl']; image?: boolean; contextSources?: AgentSessionServiceOptions['contextSources']; promptLibrary?: AgentSessionServiceOptions['promptLibrary'] } = {}) { const root = path.join(base, name, 'project'); fs.mkdirSync(root, { recursive: true }); fs.writeFileSync(path.join(root, 'a.txt'), 'one\ntwo\nthree\n'); @@ -434,7 +434,9 @@ async function setup(name: string, options: { trusted?: boolean; afterTurn?: () await fs.promises.writeFile(file, content); }, openTerminal: () => Promise.reject(new Error('no terminal in tests')), - connect: (_launch, _cwd, handlers) => AcpConnection.inProcess(fakeAgent(log), handlers), + connect: (_launch, _cwd, handlers) => AcpConnection.inProcess(fakeAgent(log, { image: options.image === true }), handlers), + ...(options.contextSources ? { contextSources: options.contextSources } : {}), + ...(options.promptLibrary ? { promptLibrary: options.promptLibrary } : {}), ...(options.changes ? { review: options.changes, @@ -711,6 +713,84 @@ describe('AgentSessionService with a fake ACP agent', () => { }); }); +describe('Context mentions, images and the prompt library in a chat (#522, #528)', () => { + const sources: NonNullable = { + hotspots: () => Promise.resolve('1. src/b.ts: maxComplexity=27'), + metrics: (_root, file) => Promise.resolve(`${file}: codeLines=3`), + diff: () => Promise.resolve('diff --git a/a.txt b/a.txt'), + }; + const PNG = 'iVBORw0KGgo='; + + it('resolves mentions (chips and typed) into capped context blocks and labels them on the message', async () => { + const { service, window, ref, log } = await setup('mentions', { contextSources: sources }); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'hello, look at @diff', [ + { kind: 'context', context: 'hotspots' }, + { kind: 'context', context: 'metrics', path: 'src\\a.ts' }, + { kind: 'context', context: 'terminal', text: '\u001b[31mFAIL\u001b[0m' }, + ]); + const blocks = log.prompts[0] as { type: string; text?: string }[]; + assert.equal(blocks[0]?.text, 'hello, look at @diff'); + assert.deepEqual(blocks.slice(1).map((block) => block.text), [ + '\n1. src/b.ts: maxComplexity=27\n', + '\nsrc/a.ts: codeLines=3\n', + '\nFAIL\n', + '\ndiff --git a/a.txt b/a.txt\n', + ]); + const user = (await service.get(window, created.id)).items.find((item) => item.kind === 'user'); + assert.ok(user?.kind === 'user'); + assert.deepEqual(user.attachments, ['@hotspots', '@metrics:src/a.ts', '@terminal', '@diff']); + await assert.rejects(service.prompt(window, created.id, 'x', [{ kind: 'context', context: 'metrics', path: '../out.ts' }]), /Invalid context attachment/); + await assert.rejects(service.prompt(window, created.id, 'x', [{ kind: 'context', context: 'nope' }]), /Invalid context attachment/); + await service.stopAll(); + }); + + it('refuses images when the agent does not advertise promptCapabilities.image', async () => { + const { service, window, ref, log } = await setup('no-images'); + const created = await service.create(window, ref); + await waitFor(() => log.clientCapabilities !== undefined, 'the agent to start'); + await service.prompt(window, created.id, 'hello', []); + assert.equal((await service.get(window, created.id)).promptImages, false); + await assert.rejects(service.prompt(window, created.id, 'hello', [{ kind: 'image', mimeType: 'image/png', data: PNG }]), /does not accept images/); + assert.equal(log.prompts.length, 1); + await service.stopAll(); + }); + + it('sends images to an agent that accepts them, checked, with their thumbnails on the message', async () => { + const { service, window, ref, log } = await setup('images', { image: true }); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'hello', [{ kind: 'image', mimeType: 'image/png', data: PNG, name: 'shot.png', thumbnail: 'data:image/jpeg;base64,AAAA' }]); + const state = await service.get(window, created.id); + assert.equal(state.promptImages, true); + assert.deepEqual((log.prompts[0] as { type: string }[]).map((block) => block.type), ['text', 'image']); + const user = state.items.find((item) => item.kind === 'user'); + assert.ok(user?.kind === 'user'); + assert.deepEqual(user.images, [{ name: 'shot.png', thumbnail: 'data:image/jpeg;base64,AAAA' }]); + await assert.rejects(service.prompt(window, created.id, 'x', [{ kind: 'image', mimeType: 'image/svg+xml', data: PNG }]), /Only PNG, JPEG/); + await assert.rejects(service.prompt(window, created.id, 'x', [{ kind: 'image', mimeType: 'image/png', data: 'A'.repeat(7_000_004) }]), /larger than 5 MB/); + await service.stopAll(); + }); + + it('lists the prompt library and expands a command before it is sent, keeping the typed text in the transcript', async () => { + const { service, window, ref, log, root } = await setup('library', { contextSources: sources }); + fs.mkdirSync(path.join(root, '.codexr', 'prompts'), { recursive: true }); + fs.writeFileSync(path.join(root, '.codexr', 'prompts', 'fix.md'), '---\nname: fix\ndescription: Fix the selection\n---\nFix {{selection}} using {{hotspots}}'); + const created = await service.create(window, ref); + const listed = await service.listPrompts(window, created.id); + assert.deepEqual(listed.map((prompt) => `${prompt.name}:${prompt.source}`), ['fix:project', 'xr-refactor-hotspot:builtin', 'xr-review-turn:builtin']); + assert.deepEqual(listed[0]?.placeholders, ['selection', 'hotspots']); + await service.prompt(window, created.id, '/fix quickly', [{ kind: 'selection', path: 'a.txt', startLine: 1, endLine: 1, text: 'one', inline: true }]); + const sent = log.prompts[0] as { type: string; text?: string }[]; + assert.equal(sent.length, 1, 'the inline selection only fills the placeholder'); + assert.equal(sent[0]?.text, 'Fix a.txt (lines 1-1):\n```\none\n``` using 1. src/b.ts: maxComplexity=27\n\nquickly'); + const user = (await service.get(window, created.id)).items.find((item) => item.kind === 'user'); + assert.ok(user?.kind === 'user'); + assert.equal(user.text, '/fix quickly'); + assert.equal(user.attachments, undefined); + await service.stopAll(); + }); +}); + describe('AcpConnection over a real child process', () => { it('spawns an agent, speaks ndjson over its stdio and stops it on close', async () => { const updates: unknown[] = []; diff --git a/apps/ide/test/promptContext.test.ts b/apps/ide/test/promptContext.test.ts new file mode 100644 index 00000000..d9e77d03 --- /dev/null +++ b/apps/ide/test/promptContext.test.ts @@ -0,0 +1,292 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + base64ByteLength, checkPromptImage, cleanTerminalOutput, CONTEXT_BUDGET_CHARS, contextMentionLabel, contextMentionSuggestions, findContextMentions, + fitContextBlocks, formatProblems, isImageThumbnail, MAX_PROMPT_IMAGE_BYTES, metricsFileQuery, parseContextMention, +} from '@codexr/core/agent-prompts/contextMentions'; +import { + BUILTIN_PROMPTS, EMPTY_PLACEHOLDER, expandPrompt, matchPromptCommand, mergePromptLibrary, parseFrontMatter, parsePromptFile, placeholdersOf, +} from '@codexr/core/agent-prompts/promptLibrary'; +import { buildPromptBlocks } from '../src/main/agentSessions/acpMapping.ts'; +import { expandLibraryCommand, gitDiff, ideContextSources, readPromptLibrary, resolveContext, type ContextSources } from '../src/main/agentSessions/promptContext.ts'; +import type { GitRunner } from '../src/main/git/gitRunner.ts'; +import { imageRejection, mergeSlashCommands, promptAttachmentsFor, thumbnailSize, type ComposerSnapshots } from '../src/renderer/agentFirst/chatModel.ts'; +import type { PromptCommandView } from '../src/shared/agentSession.ts'; + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-prompt-context-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +describe('context mentions (#522, core)', () => { + it('parses the five mentions and refuses anything else', () => { + assert.deepEqual(parseContextMention('@hotspots'), { kind: 'hotspots' }); + assert.deepEqual(parseContextMention('Problems'), { kind: 'problems' }); + assert.deepEqual(parseContextMention('@metrics:src\\app.ts'), { kind: 'metrics', argument: 'src/app.ts' }); + assert.deepEqual(parseContextMention('@metrics:./src/a.ts'), { kind: 'metrics', argument: 'src/a.ts' }); + for (const bad of ['@metrics', '@metrics:', '@metrics:../x.ts', '@metrics:/etc/passwd', '@metrics:C:\\x.ts', '@diff:x', '@src/a.ts', '@selection']) { + assert.equal(parseContextMention(bad), null, bad); + } + assert.equal(contextMentionLabel({ kind: 'metrics', argument: 'a.ts' }), '@metrics:a.ts'); + }); + + it('finds mentions typed in a message, once each, never inside a word', () => { + const found = findContextMentions('Look at @hotspots and @diff, then\n@metrics:src/a.ts and @hotspots again; mail@diff is not one'); + assert.deepEqual(found.map(contextMentionLabel), ['@hotspots', '@diff', '@metrics:src/a.ts']); + assert.deepEqual(findContextMentions('(see @metrics:src/a.ts.)').map(contextMentionLabel), ['@metrics:src/a.ts']); + assert.deepEqual(findContextMentions('@hotspots @terminal @hotspots').map(contextMentionLabel), ['@hotspots', '@terminal']); + assert.deepEqual(findContextMentions('mail@diff x@hotspots'), []); + }); + + it('offers the kinds that match what was typed, and files after metrics:', () => { + assert.deepEqual(contextMentionSuggestions(''), ['hotspots', 'problems', 'diff', 'terminal', 'metrics']); + assert.deepEqual(contextMentionSuggestions('M'), ['metrics']); + assert.deepEqual(contextMentionSuggestions('metrics:src'), []); + assert.equal(metricsFileQuery('metrics:src/a'), 'src/a'); + assert.equal(metricsFileQuery('met'), null); + }); + + it('keeps every block within the budget, cutting the one that overflows and naming those left out', () => { + const blocks = fitContextBlocks([ + { label: '@diff', body: 'd'.repeat(600) }, + { label: '@terminal', body: 't'.repeat(2000) }, + { label: '@problems', body: 'p'.repeat(100) }, + ], 1500); + assert.equal(blocks.length, 3); + assert.match(blocks[0]?.text ?? '', /^\nd{600}\n<\/context>$/); + assert.match(blocks[1]?.text ?? '', /truncated to fit/); + assert.match(blocks[2]?.text ?? '', /left out/); + assert.ok(blocks.slice(0, 2).reduce((sum, block) => sum + block.text.length, 0) <= 1500); + assert.equal(CONTEXT_BUDGET_CHARS, 120_000); + }); + + it('formats problems errors first and cleans terminal output', () => { + const text = formatProblems([ + { path: 'b.ts', severity: 'warning', message: 'unused x', startLine: 3, startColumn: 1, source: 'ts', code: '6133' }, + { path: 'a.ts', severity: 'error', message: 'type error', startLine: 9, source: 'ts' }, + ]); + assert.equal(text, '2 problems (1 errors, 1 warnings, 0 infos):\nerror a.ts:9 type error [ts]\nwarning b.ts:3:1 unused x [ts 6133]'); + assert.equal(formatProblems([]), 'No problems are reported.'); + assert.equal(cleanTerminalOutput('\u001b[32mok\u001b[0m\r\nprogress 10%\rprogress 100%\n\n'), 'ok\nprogress 100%'); + assert.equal(cleanTerminalOutput('a\nb\nc', 2), 'b\nc'); + assert.equal(cleanTerminalOutput(''), 'The terminal is empty.'); + }); + + it('checks images: type, base64 and the 5 MB cap; thumbnails must be small data URLs', () => { + assert.equal(checkPromptImage('image/png', 'iVBORw0KGgo='), null); + assert.equal(checkPromptImage('image/svg+xml', 'AAAA'), 'type'); + assert.equal(checkPromptImage('image/png', 'not base64!'), 'data'); + assert.equal(base64ByteLength('AAAA'), 3); + assert.equal(base64ByteLength('AA=='), 1); + const big = 'A'.repeat(Math.ceil((MAX_PROMPT_IMAGE_BYTES + 3) / 3) * 4); + assert.equal(checkPromptImage('image/jpeg', big), 'size'); + assert.ok(isImageThumbnail('data:image/jpeg;base64,AAAA')); + assert.ok(!isImageThumbnail('data:image/svg+xml;base64,AAAA')); + assert.ok(!isImageThumbnail('https://example.com/a.png')); + assert.ok(!isImageThumbnail(`data:image/png;base64,${'A'.repeat(60_000)}`)); + }); +}); + +describe('prompt library (#528, core)', () => { + it('parses front-matter with quotes and CRLF, and placeholders in order', () => { + const parsed = parseFrontMatter('---\r\nname: "review"\r\ndescription: Review it\r\n---\r\nBody {{diff}}\r\n'); + assert.deepEqual(parsed.data, { name: 'review', description: 'Review it' }); + assert.equal(parsed.body, 'Body {{diff}}\n'); + assert.deepEqual(parseFrontMatter('no front matter').data, {}); + assert.deepEqual(placeholdersOf('{{ file }} {{diff}} {{unknown}} {{FILE}} {{hotspots}}'), ['file', 'diff', 'hotspots']); + }); + + it('takes the command name from the front-matter or the file name, and refuses invalid ones', () => { + const fromMatter = parsePromptFile('.codexr/prompts/x.md', '---\nname: /tidy\ndescription: Tidy up\n---\nTidy {{selection}}'); + assert.equal(fromMatter?.name, 'tidy'); + assert.equal(fromMatter?.description, 'Tidy up'); + assert.deepEqual(fromMatter?.placeholders, ['selection']); + const fromFile = parsePromptFile('.codexr\\prompts\\Explain-This.md', '# Explain the file\n\n{{file}}'); + assert.equal(fromFile?.name, 'Explain-This'); + assert.equal(fromFile?.description, 'Explain the file'); + assert.equal(fromFile?.file, '.codexr/prompts/Explain-This.md'); + assert.equal(parsePromptFile('a.md', '---\nname: has space\n---\nx'), null); + assert.equal(parsePromptFile('a.md', '---\nname: ok\n---\n '), null); + }); + + it('ships the two built-in prompts, which a project prompt of the same name replaces', () => { + assert.deepEqual(BUILTIN_PROMPTS.map((prompt) => prompt.name), ['xr-review-turn', 'xr-refactor-hotspot']); + assert.deepEqual(BUILTIN_PROMPTS[0]?.placeholders, ['diff', 'hotspots']); + const own = parsePromptFile('.codexr/prompts/xr-review-turn.md', 'Mine'); + const merged = mergePromptLibrary(own ? [own] : []); + assert.equal(merged.length, 2); + assert.equal(merged.find((prompt) => prompt.name === 'xr-review-turn')?.source, 'project'); + }); + + it('matches a command at the start of the message, never shadowing the agent\'s own', () => { + const prompts = mergePromptLibrary([]); + assert.equal(matchPromptCommand('/xr-refactor-hotspot', prompts)?.prompt.name, 'xr-refactor-hotspot'); + assert.equal(matchPromptCommand('/XR-Review-Turn keep it short ', prompts)?.input, 'keep it short'); + assert.equal(matchPromptCommand('please /xr-review-turn', prompts), null); + assert.equal(matchPromptCommand('/xr-review-turn', prompts, ['xr-review-turn']), null); + assert.equal(matchPromptCommand('/unknown', prompts), null); + }); + + it('expands placeholders literally, notes the missing ones and appends the input', () => { + const text = expandPrompt({ body: 'A {{diff}} B {{selection}} C {{other}}' }, { diff: 'has {{selection}}' }, 'extra'); + assert.equal(text, `A has {{selection}} B ${EMPTY_PLACEHOLDER.selection} C {{other}}\n\nextra`); + }); +}); + +/** A fake analysis and git: what `ideContextSources` reads. */ +function fakeSources(): { sources: ContextSources; calls: string[] } { + const calls: string[] = []; + return { + calls, + sources: { + hotspots: (root) => { + calls.push(`hotspots ${root}`); + return Promise.resolve('1. src/b.ts: maxComplexity=27'); + }, + metrics: (root, file) => { + calls.push(`metrics ${root} ${file}`); + return Promise.resolve(`${file}: codeLines=10`); + }, + diff: (workRoot) => { + calls.push(`diff ${workRoot}`); + return Promise.reject(new Error('The project is not a Git repository, so it has no diff.')); + }, + }, + }; +} + +const ROOTS = { root: '/project', workRoot: '/worktree' }; + +describe('context resolvers (#522, main)', () => { + it('resolves analysis mentions on the project and the diff in the agent\'s folder; failures become a note', async () => { + const { sources, calls } = fakeSources(); + assert.deepEqual(await resolveContext({ context: 'hotspots' }, ROOTS, sources), { label: '@hotspots', body: '1. src/b.ts: maxComplexity=27' }); + assert.deepEqual(await resolveContext({ context: 'metrics', path: 'src/a.ts' }, ROOTS, sources), { label: '@metrics:src/a.ts', body: 'src/a.ts: codeLines=10' }); + const diff = await resolveContext({ context: 'diff' }, ROOTS, sources); + assert.match(diff.body, /^\(unavailable: The project is not a Git repository/); + assert.deepEqual(calls, ['hotspots /project', 'metrics /project src/a.ts', 'diff /worktree']); + assert.equal((await resolveContext({ context: 'terminal', text: '\u001b[1mbuild ok\u001b[0m' }, ROOTS, sources)).body, 'build ok'); + assert.equal((await resolveContext({ context: 'problems', text: '' }, ROOTS, sources)).body, 'No problems are reported.'); + assert.match((await resolveContext({ context: 'hotspots' }, ROOTS, undefined)).body, /unavailable/); + }); + + it('reads hotspots and metrics from the window\'s analysis folder, and says when none is open', async () => { + const dir = path.join(base, 'analysis'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify([ + { relativePath: 'src/a.ts', language: 'TypeScript', maxComplexity: 3, codeLines: 40 }, + { relativePath: 'src\\b.ts', language: 'TypeScript', maxComplexity: 27, codeLines: 120 }, + ])); + const git: GitRunner = () => Promise.reject(new Error('no git')); + const sources = ideContextSources((root) => (root === '/project' ? dir : null), git); + assert.match(await sources.hotspots('/project'), /^Top 2 files by maxComplexity:\n1\. src\/b\.ts: maxComplexity=27/); + assert.match(await sources.metrics('/project', 'src/a.ts'), /^src\/a\.ts \(TypeScript\): .*codeLines=40/); + await assert.rejects(sources.hotspots('/elsewhere'), /No Code-XR analysis is open/); + }); + + it('diffs against HEAD, falls back to the index without commits, and lists untracked files', async () => { + const seen: string[][] = []; + const git: GitRunner = (_cwd, args) => { + seen.push([...args]); + if (args.includes('HEAD')) { + return Promise.reject(new Error('bad revision HEAD')); + } + if (args[0] === 'ls-files') { + return Promise.resolve({ stdout: 'new.ts\r\n', stderr: '', exitCode: 0 }); + } + return Promise.resolve({ stdout: 'diff --git a/a.ts b/a.ts\n+x\n', stderr: '', exitCode: 0 }); + }; + assert.equal(await gitDiff(git, '/p'), 'diff --git a/a.ts b/a.ts\n+x\n\nUntracked files:\n new.ts'); + assert.ok(seen.some((args) => args.includes('--cached'))); + const clean: GitRunner = () => Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }); + assert.equal(await gitDiff(clean, '/p'), 'No uncommitted changes.'); + }); +}); + +describe('prompt library in the main process (#528)', () => { + it('reads .codexr/prompts/*.md, skipping invalid files, merged with the built-ins', async () => { + const root = path.join(base, 'library'); + const dir = path.join(root, '.codexr', 'prompts'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'tidy.md'), '---\nname: tidy\ndescription: Tidy the selection\n---\nTidy this:\n{{selection}}\n'); + fs.writeFileSync(path.join(dir, 'bad.md'), '---\nname: not valid!\n---\nx'); + fs.writeFileSync(path.join(dir, 'notes.txt'), 'ignored'); + const prompts = await readPromptLibrary(root); + assert.deepEqual(prompts.map((prompt) => `${prompt.name}:${prompt.source}`), ['tidy:project', 'xr-refactor-hotspot:builtin', 'xr-review-turn:builtin']); + assert.deepEqual((await readPromptLibrary(path.join(base, 'no-such-folder'))).map((prompt) => prompt.name), ['xr-refactor-hotspot', 'xr-review-turn']); + }); + + it('expands a command with live values from the resolvers and the window\'s snapshots', async () => { + const { sources } = fakeSources(); + const prompts = mergePromptLibrary([parsePromptFile('.codexr/prompts/t.md', '---\nname: t\n---\nH={{hotspots}}\nS={{selection}}\nF={{file}}\nD={{diff}}')!]); + const result = await expandLibraryCommand('/t now', prompts, [], ROOTS, sources, { selection: 'a.ts (lines 1-2):\nx', file: 'a.ts:\ncode' }); + assert.equal(result.prompt?.name, 't'); + assert.equal(result.text, 'H=1. src/b.ts: maxComplexity=27\nS=a.ts (lines 1-2):\nx\nF=a.ts:\ncode\nD=(unavailable: The project is not a Git repository, so it has no diff.)\n\nnow'); + const untouched = await expandLibraryCommand('/compact', prompts, ['compact'], ROOTS, sources, {}); + assert.deepEqual(untouched, { text: '/compact', prompt: null }); + }); +}); + +describe('buildPromptBlocks with context and images (#522)', () => { + it('adds context blocks as text and images as image blocks, after files and selections', () => { + const blocks = buildPromptBlocks('Fix', [{ kind: 'file', absolutePath: '/p/a.ts', relativePath: 'a.ts', text: 'code' }], true, { + contexts: fitContextBlocks([{ label: '@hotspots', body: 'top' }]), + images: [{ mimeType: 'image/png', data: 'AAAA' }], + }); + assert.deepEqual(blocks.map((block) => block.type), ['text', 'resource', 'text', 'image']); + assert.deepEqual(blocks[2], { type: 'text', text: '\ntop\n' }); + assert.deepEqual(blocks[3], { type: 'image', mimeType: 'image/png', data: 'AAAA' }); + assert.deepEqual(buildPromptBlocks('t', [], false).map((block) => block.type), ['text']); + }); +}); + +describe('composer helpers (#522, #528, renderer)', () => { + const prompts: PromptCommandView[] = [ + { name: 'xr-review-turn', description: 'Review', source: 'builtin', placeholders: ['diff', 'hotspots'] }, + { name: 'tidy', description: 'Tidy', source: 'project', placeholders: ['selection', 'file', 'problems'] }, + { name: 'compact', description: 'Mine', source: 'project', placeholders: [] }, + ]; + const snapshots: ComposerSnapshots = { + selection: () => ({ kind: 'selection', path: 'a.ts', startLine: 1, endLine: 2, text: 'x' }), + activeFile: () => 'a.ts', + problems: () => 'P', + terminal: () => 'T', + }; + + it('merges the library after the agent\'s commands without shadowing them', () => { + const merged = mergeSlashCommands([{ name: 'compact', description: 'Agent compact' }], prompts); + assert.deepEqual(merged.map((command) => [command.name, command.library ?? 'agent']), [['compact', 'agent'], ['xr-review-turn', 'builtin'], ['tidy', 'project']]); + }); + + it('snapshots @problems and @terminal (chips or typed), once each', () => { + const out = promptAttachmentsFor('see @terminal and @problems', [{ kind: 'context', context: 'problems' }, { kind: 'context', context: 'metrics', path: 'a.ts' }, { kind: 'file', path: 'b.ts' }], snapshots, prompts, []); + assert.deepEqual(out, [ + { kind: 'context', context: 'problems', text: 'P' }, + { kind: 'context', context: 'metrics', path: 'a.ts' }, + { kind: 'file', path: 'b.ts' }, + { kind: 'context', context: 'terminal', text: 'T' }, + ]); + }); + + it('sends a library command the snapshots its placeholders need, inline', () => { + assert.deepEqual(promptAttachmentsFor('/tidy', [], snapshots, prompts, []), [ + { kind: 'selection', path: 'a.ts', startLine: 1, endLine: 2, text: 'x', inline: true }, + { kind: 'file', path: 'a.ts', inline: true }, + { kind: 'context', context: 'problems', text: 'P', inline: true }, + ]); + assert.deepEqual(promptAttachmentsFor('/xr-review-turn', [], snapshots, prompts, []), []); + assert.deepEqual(promptAttachmentsFor('/tidy', [], snapshots, prompts, [{ name: 'tidy', description: 'agent' }]), []); + }); + + it('gates images on the agent\'s capability, type, size and count; thumbnails keep proportions', () => { + assert.equal(imageRejection('image/png', 10, 0, undefined), 'chat.image.unsupported'); + assert.equal(imageRejection('image/png', 10, 0, false), 'chat.image.unsupported'); + assert.equal(imageRejection('image/bmp', 10, 0, true), 'chat.image.type'); + assert.equal(imageRejection('image/png', 6 * 1024 * 1024, 0, true), 'chat.image.size'); + assert.equal(imageRejection('image/png', 10, 8, true), 'chat.image.tooMany'); + assert.equal(imageRejection('image/webp', 10, 0, true), null); + assert.deepEqual(thumbnailSize(400, 200), { width: 96, height: 48 }); + assert.deepEqual(thumbnailSize(20, 10), { width: 20, height: 10 }); + }); +}); diff --git a/apps/vscode-extension/src/core/agent-prompts/contextMentions.ts b/apps/vscode-extension/src/core/agent-prompts/contextMentions.ts new file mode 100644 index 00000000..2a41b2fe --- /dev/null +++ b/apps/vscode-extension/src/core/agent-prompts/contextMentions.ts @@ -0,0 +1,231 @@ +/** + * #522 (O20): analysis-aware `@` mentions of an agent chat's composer + * (`@hotspots`, `@problems`, `@diff`, `@terminal`, `@metrics:`) and the + * images a message may carry. + * + * Pure and host-neutral on purpose: no `vscode`, no Node, no DOM and no + * runtime imports, so the Code-XR IDE loads it in its renderer and in its main + * process, and the VS Code extension's chat can reuse it as is. A host + * parses what the person typed here, gathers the live data its own way (the + * analysis, git, the Problems panel, the terminal) and formats it here, so + * every host sends the agent the same blocks under the same size cap. + */ + +/** What a context mention attaches. */ +export type ContextMentionKind = 'hotspots' | 'problems' | 'diff' | 'terminal' | 'metrics'; + +export const CONTEXT_MENTION_KINDS: readonly ContextMentionKind[] = ['hotspots', 'problems', 'diff', 'terminal', 'metrics']; + +export function isContextMentionKind(value: unknown): value is ContextMentionKind { + return typeof value === 'string' && (CONTEXT_MENTION_KINDS as readonly string[]).includes(value); +} + +/** One parsed mention: `@metrics:src/a.ts` is `{ kind: 'metrics', argument: 'src/a.ts' }`. */ +export interface ContextMention { + readonly kind: ContextMentionKind; + /** `metrics` only: a project-relative file, with forward slashes. */ + readonly argument?: string; +} + +/** The kinds whose data lives with the host's UI (the Problems panel, the terminal's screen): the UI sends a snapshot. */ +export function isSnapshotKind(kind: ContextMentionKind): boolean { + return kind === 'problems' || kind === 'terminal'; +} + +/** A project-relative path as mentions write it: forward slashes, no leading `./` or `/`. */ +export function normalizeMentionPath(value: string): string { + return value.replace(/\\/g, '/').replace(/^(?:\.\/)+/, '').replace(/^\/+/, '').trim(); +} + +/** + * `@hotspots`, `@problems`, `@diff`, `@terminal` or `@metrics:` (the + * leading `@` optional) as a mention; null for anything else, a file + * mention included. `@metrics` without a file, or with one that climbs out + * of the project (`..`) or is absolute, is not a mention. + */ +export function parseContextMention(token: string): ContextMention | null { + const body = token.startsWith('@') ? token.slice(1) : token; + const colon = body.indexOf(':'); + const name = (colon < 0 ? body : body.slice(0, colon)).toLowerCase(); + if (!isContextMentionKind(name)) { + return null; + } + if (name !== 'metrics') { + return colon < 0 ? { kind: name } : null; + } + const argument = colon < 0 ? null : mentionFile(body.slice(colon + 1)); + return argument ? { kind: 'metrics', argument } : null; +} + +/** A mention's file argument, normalized; null when empty, absolute, too long or climbing out of the project. */ +function mentionFile(raw: string): string | null { + if (/^(?:[a-zA-Z]:)?[\\/]/.test(raw)) { + return null; + } + const argument = normalizeMentionPath(raw); + return argument && argument.length <= 1000 && !argument.split('/').includes('..') ? argument : null; +} + +/** How a mention is written (and the chip's label): `@hotspots`, `@metrics:src/a.ts`. */ +export function contextMentionLabel(mention: ContextMention): string { + return mention.kind === 'metrics' ? `@metrics:${mention.argument ?? ''}` : `@${mention.kind}`; +} + +/** Every context mention written in `text`, each starting the text or after white space, in order, without repeats. */ +export function findContextMentions(text: string): ContextMention[] { + const found: ContextMention[] = []; + const seen = new Set(); + for (const match of text.matchAll(/(?:^|\s)@([^\s@]+)/g)) { + // Punctuation that ends a sentence is not part of the mention: "see @diff, then...". + const mention = parseContextMention((match[1] ?? '').replace(/[.,;:!?)\]}'"]+$/, '')); + if (mention && !seen.has(contextMentionLabel(mention))) { + seen.add(contextMentionLabel(mention)); + found.push(mention); + } + } + return found; +} + +/** + * The context mentions the `@` popup offers for what the person typed after + * the `@`: every kind whose name starts with it (`@m` offers `metrics:`). + * Typing `metrics:` and more offers nothing here: the popup lists files then. + */ +export function contextMentionSuggestions(query: string): ContextMentionKind[] { + const typed = query.toLowerCase(); + if (typed.includes(':')) { + return []; + } + return CONTEXT_MENTION_KINDS.filter((kind) => kind.startsWith(typed)); +} + +/** `metrics:` and what follows it in the popup's query, or null: the person is choosing the file. */ +export function metricsFileQuery(query: string): string | null { + return /^metrics:/i.test(query) ? query.slice('metrics:'.length) : null; +} + +// ---- Formatting under the size cap ----------------------------------------- + +/** The most context one message may carry: about 30k tokens, the same budget as the built-in agent's attachments (A6). */ +export const CONTEXT_BUDGET_CHARS = 120_000; + +const TRUNCATED = '\n... (truncated to fit the context budget)'; + +/** One block for the agent: the source and its text, delimited so the agent tells context from the message. */ +export function formatContextBlock(label: string, body: string): string { + return `\n${body}\n`; +} + +/** + * Formats each `{ label, body }` as a block, in order, all of them within + * `budget` characters together: a body that does not fit is cut (with a note + * saying so) and the ones after it get a one-line "left out" block, so the + * agent always learns what it was given and what it was not. + */ +export function fitContextBlocks(entries: readonly { readonly label: string; readonly body: string }[], budget: number = CONTEXT_BUDGET_CHARS): { readonly label: string; readonly text: string }[] { + const blocks: { label: string; text: string }[] = []; + let left = budget; + for (const entry of entries) { + const full = formatContextBlock(entry.label, entry.body); + if (full.length <= left) { + blocks.push({ label: entry.label, text: full }); + left -= full.length; + continue; + } + const overhead = formatContextBlock(entry.label, TRUNCATED).length; + if (left - overhead >= 200) { + const text = formatContextBlock(entry.label, `${entry.body.slice(0, left - overhead)}${TRUNCATED}`); + blocks.push({ label: entry.label, text }); + left -= text.length; + continue; + } + blocks.push({ label: entry.label, text: formatContextBlock(entry.label, '(left out: the message already carries as much context as it may)') }); + } + return blocks; +} + +/** One problem as a host's Problems panel holds it (the fields every host has). */ +export interface MentionProblem { + readonly path: string; + readonly severity: 'error' | 'warning' | 'info'; + readonly message: string; + /** 1-based. */ + readonly startLine: number; + readonly startColumn?: number; + readonly source?: string; + readonly code?: string | number; +} + +const SEVERITY_RANK = { error: 0, warning: 1, info: 2 } as const; +const CONTEXT_SEVERITIES = ['error', 'warning', 'info'] as const; + +/** `@problems`: errors first, then warnings and infos, by file and line; at most `limit`, saying how many were left out. */ +export function formatProblems(problems: readonly MentionProblem[], limit = 200): string { + if (problems.length === 0) { + return 'No problems are reported.'; + } + const sorted = [...problems].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || a.path.localeCompare(b.path) || a.startLine - b.startLine); + const lines = sorted.slice(0, limit).map((problem) => { + const where = `${problem.path.replace(/\\/g, '/')}:${problem.startLine}${problem.startColumn ? `:${problem.startColumn}` : ''}`; + const origin = [problem.source, problem.code === undefined || problem.code === '' ? '' : String(problem.code)].filter(Boolean).join(' '); + return `${problem.severity} ${where} ${problem.message.replace(/\s+/g, ' ').trim()}${origin ? ` [${origin}]` : ''}`; + }); + const counts = CONTEXT_SEVERITIES.map((severity) => `${problems.filter((problem) => problem.severity === severity).length} ${severity === 'info' ? 'infos' : `${severity}s`}`).join(', '); + return [`${problems.length} problems (${counts}):`, ...lines, ...(sorted.length > limit ? [`... and ${sorted.length - limit} more`] : [])].join('\n'); +} + +/** Terminal escape sequences (colours, cursor moves, titles) a screen draws but an agent should not read. */ +const ANSI = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g; + +/** `@terminal`: the terminal's text without escape sequences, carriage-return overwrites resolved, its last `maxLines` lines. */ +export function cleanTerminalOutput(text: string, maxLines = 200): string { + const lines = text.replace(ANSI, '').replace(/\r\n/g, '\n').split('\n') + .map((line) => line.slice(line.lastIndexOf('\r') + 1).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').trimEnd()); + while (lines.length > 0 && lines[lines.length - 1] === '') { + lines.pop(); + } + const tail = lines.slice(-maxLines); + return tail.length === 0 ? 'The terminal is empty.' : tail.join('\n'); +} + +// ---- Images -------------------------------------------------------------- + +/** The image types a message may carry: what agents accept. */ +export const PROMPT_IMAGE_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp', 'image/gif']; + +/** The largest image a message may carry, decoded. */ +export const MAX_PROMPT_IMAGE_BYTES = 5 * 1024 * 1024; + +/** The most images one message may carry. */ +export const MAX_PROMPT_IMAGES = 8; + +/** The largest thumbnail (a `data:` URL) kept on the person's message in the transcript. */ +export const MAX_IMAGE_THUMBNAIL_CHARS = 48 * 1024; + +/** The bytes a base64 string decodes to (padding counted). */ +export function base64ByteLength(data: string): number { + const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0; + return Math.floor((data.length * 3) / 4) - padding; +} + +/** Why an image cannot be sent, or null when it can. */ +export type ImageProblem = 'type' | 'size' | 'data'; + +export function checkPromptImage(mimeType: unknown, data: unknown): ImageProblem | null { + if (typeof mimeType !== 'string' || !PROMPT_IMAGE_TYPES.includes(mimeType)) { + return 'type'; + } + if (typeof data !== 'string' || data.length === 0 || data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) { + return 'data'; + } + return base64ByteLength(data) > MAX_PROMPT_IMAGE_BYTES ? 'size' : null; +} + +/** A thumbnail the transcript may show: a small base64 `data:` URL of one of the accepted types. */ +export function isImageThumbnail(value: unknown): value is string { + if (typeof value !== 'string' || value.length > MAX_IMAGE_THUMBNAIL_CHARS) { + return false; + } + const match = /^data:(image\/[a-z]+);base64,([A-Za-z0-9+/]+={0,2})$/.exec(value); + return !!match && PROMPT_IMAGE_TYPES.includes(match[1] ?? ''); +} diff --git a/apps/vscode-extension/src/core/agent-prompts/promptLibrary.ts b/apps/vscode-extension/src/core/agent-prompts/promptLibrary.ts new file mode 100644 index 00000000..3723ac0d --- /dev/null +++ b/apps/vscode-extension/src/core/agent-prompts/promptLibrary.ts @@ -0,0 +1,181 @@ +/** + * #528 (O26): the prompt library. A team keeps prompts in + * `.codexr/prompts/*.md`, each a Markdown file with a small front-matter + * (`name`, `description`); a chat offers them as slash commands, and the + * placeholders (`{{hotspots}}`, `{{selection}}`, `{{problems}}`, `{{diff}}`, + * `{{file}}`) are filled from the live analysis and editor just before the + * message goes to the agent. Two prompts ship built in. + * + * Pure and host-neutral on purpose: no `vscode`, no Node, no DOM and no + * runtime imports. The host reads the files and resolves each placeholder + * its own way (the IDE reuses its `@` mention resolvers, #522); this module + * parses, matches and expands. + */ + +/** The live values a prompt may ask for. */ +export type PromptPlaceholder = 'hotspots' | 'selection' | 'problems' | 'diff' | 'file'; + +export const PROMPT_PLACEHOLDERS: readonly PromptPlaceholder[] = ['hotspots', 'selection', 'problems', 'diff', 'file']; + +/** Where the library's prompts live, relative to the project root. */ +export const PROMPT_LIBRARY_DIR = '.codexr/prompts'; + +/** The most prompt files read from the folder, and the largest one. */ +export const MAX_PROMPT_FILES = 100; +export const MAX_PROMPT_FILE_CHARS = 64 * 1024; + +export interface PromptTemplate { + /** The slash command, without the `/`. */ + readonly name: string; + readonly description: string; + /** The text sent, with its `{{placeholders}}`. */ + readonly body: string; + readonly source: 'builtin' | 'project'; + /** Project prompts: the file, relative to the project root. */ + readonly file?: string; + /** The placeholders the body uses, in order of first use. */ + readonly placeholders: readonly PromptPlaceholder[]; +} + +const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i; + +/** A valid command name: letters, digits, `.`, `_` and `-`, starting with a letter or digit. */ +export function isPromptName(value: string): boolean { + return NAME.test(value); +} + +/** + * A `---` front-matter of `key: value` lines (values may be quoted) and the + * text after it. Without one, the data is empty and the body is the whole text. + */ +export function parseFrontMatter(text: string): { readonly data: Readonly>; readonly body: string } { + const normalized = text.replace(/^/, '').replace(/\r\n?/g, '\n'); + const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(normalized); + if (!match) { + return { data: {}, body: normalized }; + } + const data: Record = {}; + for (const line of (match[1] ?? '').split('\n')) { + const pair = /^\s*([A-Za-z][\w-]*)\s*:\s*(.*?)\s*$/.exec(line); + if (!pair) { + continue; + } + data[(pair[1] ?? '').toLowerCase()] = unquote(pair[2] ?? ''); + } + return { data, body: normalized.slice(match[0].length) }; +} + +/** A front-matter value without the quotes around it, if it has a matching pair. */ +function unquote(value: string): string { + return /^(["']).*\1$/.test(value) && value.length >= 2 ? value.slice(1, -1) : value; +} + +/** The placeholders `body` uses, in order of first use, each once (unknown names are left as written). */ +export function placeholdersOf(body: string): PromptPlaceholder[] { + const found: PromptPlaceholder[] = []; + for (const match of body.matchAll(/\{\{\s*([a-z]+)\s*\}\}/gi)) { + const name = (match[1] ?? '').toLowerCase() as PromptPlaceholder; + if (PROMPT_PLACEHOLDERS.includes(name) && !found.includes(name)) { + found.push(name); + } + } + return found; +} + +/** + * One prompt file (`file` relative to the project root, e.g. + * `.codexr/prompts/review.md`): the command name is the front-matter's + * `name`, else the file's name without `.md`. Null when the name is not a + * valid command, or the body is empty. + */ +export function parsePromptFile(file: string, text: string): PromptTemplate | null { + const { data, body } = parseFrontMatter(text.slice(0, MAX_PROMPT_FILE_CHARS)); + const stem = (file.replace(/\\/g, '/').split('/').pop() ?? '').replace(/\.md$/i, ''); + const name = (data['name'] ?? stem).replace(/^\//, '').trim(); + const trimmed = body.trim(); + if (!isPromptName(name) || !trimmed) { + return null; + } + const description = (data['description'] ?? '').trim() || (trimmed.split('\n')[0] ?? '').replace(/^#+\s*/, '').slice(0, 120); + return { name, description, body: trimmed, source: 'project', file: file.replace(/\\/g, '/'), placeholders: placeholdersOf(trimmed) }; +} + +function builtin(name: string, description: string, body: string): PromptTemplate { + return { name, description, body, source: 'builtin', placeholders: placeholdersOf(body) }; +} + +/** The prompts every project has; a project file with the same name replaces one. */ +export const BUILTIN_PROMPTS: readonly PromptTemplate[] = [ + builtin('xr-review-turn', 'Review the changes of the last turn against the project\'s metrics', [ + 'Review the changes you made in your last turn.', + '', + 'The uncommitted changes in the project:', + '{{diff}}', + '', + 'The project\'s complexity hotspots, as Code-XR measures them:', + '{{hotspots}}', + '', + 'For each change: say whether it is correct, whether it made a function more complex or longer than it needs to be, and what you would change. Point at file and line. Do not edit anything yet.', + ].join('\n')), + builtin('xr-refactor-hotspot', 'Refactor the top complexity hotspot of the project', [ + 'Refactor the file at the top of the project\'s complexity hotspots, as Code-XR measures them:', + '{{hotspots}}', + '', + 'Reduce the complexity of its most complex functions without changing their behaviour: extract helpers, simplify conditionals, remove duplication. Keep the public interface. Run the tests if the project has any, and summarise how the complexity changed.', + ].join('\n')), +]; + +/** The library: the built-in prompts, then the project's, a project prompt replacing a built-in one of the same name; sorted by name. */ +export function mergePromptLibrary(project: readonly PromptTemplate[], builtins: readonly PromptTemplate[] = BUILTIN_PROMPTS): PromptTemplate[] { + const byName = new Map(); + for (const prompt of [...builtins, ...project]) { + byName.set(prompt.name.toLowerCase(), prompt); + } + return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +/** + * The library prompt a message runs, or null: the message starts with + * `/name` (then white space or its end) and no command the agent itself + * offers has that name (the agent's own commands are never shadowed). + * `input` is what follows the command. + */ +export function matchPromptCommand(text: string, prompts: readonly PromptTemplate[], agentCommands: readonly string[] = []): { readonly prompt: PromptTemplate; readonly input: string } | null { + const match = /^\/([^\s/]+)(?:\s+([\s\S]*))?$/.exec(text.trim()); + if (!match) { + return null; + } + const name = (match[1] ?? '').toLowerCase(); + if (agentCommands.some((command) => command.toLowerCase() === name)) { + return null; + } + const prompt = prompts.find((candidate) => candidate.name.toLowerCase() === name); + return prompt ? { prompt, input: (match[2] ?? '').trim() } : null; +} + +/** What a placeholder becomes when the host has nothing for it. */ +export const EMPTY_PLACEHOLDER: Readonly> = { + hotspots: '(no Code-XR analysis is open, so there are no hotspots)', + selection: '(nothing is selected in the editor)', + problems: '(no problems are reported)', + diff: '(no uncommitted changes)', + file: '(no file is open in the editor)', +}; + +/** + * The prompt's text with each placeholder replaced by its value (or by the + * `EMPTY_PLACEHOLDER` note), and what the person typed after the command + * appended as a last paragraph. Values are inserted literally: a value that + * itself contains `{{diff}}` is not expanded again. + */ +export function expandPrompt(prompt: Pick, values: Partial>, input = ''): string { + const expanded = prompt.body.replace(/\{\{\s*([a-z]+)\s*\}\}/gi, (whole, raw: string) => { + const name = raw.toLowerCase() as PromptPlaceholder; + if (!PROMPT_PLACEHOLDERS.includes(name)) { + return whole; + } + const value = values[name]; + return value?.trim() ? value : EMPTY_PLACEHOLDER[name]; + }); + return input.trim() ? `${expanded}\n\n${input.trim()}` : expanded; +} diff --git a/apps/vscode-extension/test/agent_prompts/contextMentions.test.cjs b/apps/vscode-extension/test/agent_prompts/contextMentions.test.cjs new file mode 100644 index 00000000..8e444a7d --- /dev/null +++ b/apps/vscode-extension/test/agent_prompts/contextMentions.test.cjs @@ -0,0 +1,24 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { parseContextMention, findContextMentions, fitContextBlocks, checkPromptImage } = require('../../out/core/agent-prompts/contextMentions.js'); +const { parsePromptFile, matchPromptCommand, expandPrompt, mergePromptLibrary, BUILTIN_PROMPTS } = require('../../out/core/agent-prompts/promptLibrary.js'); + +// #522 / #528: the composer's mentions and the prompt library live in the core so this extension's chat can reuse them (the IDE tests them in depth). +test('the core parses context mentions and keeps context blocks within the budget (#522)', () => { + assert.deepEqual(parseContextMention('@metrics:src\\a.ts'), { kind: 'metrics', argument: 'src/a.ts' }); + assert.equal(parseContextMention('@metrics:../a.ts'), null); + assert.deepEqual(findContextMentions('check @hotspots, @diff and mail@terminal').map((mention) => mention.kind), ['hotspots', 'diff']); + const blocks = fitContextBlocks([{ label: '@diff', body: 'x'.repeat(1000) }], 500); + assert.ok(blocks[0].text.length <= 500); + assert.equal(checkPromptImage('image/png', 'AAAA'), null); + assert.equal(checkPromptImage('image/tiff', 'AAAA'), 'type'); +}); + +test('the core parses prompt files and expands their placeholders (#528)', () => { + const prompt = parsePromptFile('.codexr/prompts/review.md', '---\nname: review\ndescription: Review\n---\nReview {{diff}}'); + assert.deepEqual(prompt.placeholders, ['diff']); + const library = mergePromptLibrary([prompt]); + assert.equal(library.length, BUILTIN_PROMPTS.length + 1); + const match = matchPromptCommand('/review now', library); + assert.equal(expandPrompt(match.prompt, { diff: 'D' }, match.input), 'Review D\n\nnow'); +}); From d5d8a714c27d12c4040b7c8f7f96fe1dd8ab5717 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:58:20 +0000 Subject: [PATCH 38/74] fix(ide): drop an unused import after the merge --- apps/ide/src/main/agentSessions/agentSessionService.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 61b06dd6..a1f4dc72 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -31,7 +31,6 @@ import { type RemoteControlView, type PermissionOptionView, type ProjectSessions, - type PromptAttachment, type SessionCost, type MessageImageView, type PromptCommandView, From efd782970b5a2b07d2f4189a7d766be5aa41aab3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 21:59:45 +0000 Subject: [PATCH 39/74] test(extension): register core/agent-review and the new core modules in the guardrails (#521, #522) --- apps/vscode-extension/test/README.md | 3 +- .../test/tooling/folderDependencies.json | 1 + .../test/tooling/guardrail-baseline.json | 30 +++++++++++++++---- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/apps/vscode-extension/test/README.md b/apps/vscode-extension/test/README.md index e892717d..eff1e7e0 100644 --- a/apps/vscode-extension/test/README.md +++ b/apps/vscode-extension/test/README.md @@ -6,7 +6,8 @@ This folder contains the local validation suite for CodeXR. Every `*.test.cjs` below `test/` is collected by `npm run test:unit`, except under `test/runners/`, which the collector skips on purpose. -- `test/agent_prompts`: the host-neutral agent prompt templates of the core (`core/agent-prompts`), shared with the Code-XR IDE (#514). +- `test/agent_prompts`: the host-neutral agent prompt templates, context mentions, prompt library, regression prompt and activity helpers of the core (`core/agent-prompts`), shared with the Code-XR IDE (#514, #522, #523, #527, #528). +- `test/agent_review`: the host-neutral hunk review and review-comment prompt of the core (`core/agent-review`), shared with the Code-XR IDE (#521). - `test/analysis`: the largest group: browser runtimes (tables, charts, mapping UI, modes, dependency graph, historical comparison, project evolution, collaboration), parsers, export, Git services, watchers. - `test/baseline`: the feature baseline of the cleanup epic (#26): a snapshot of everything a user can see, invoke or rely on, and the register of the only removals the maintainer authorized. `node test/baseline/featureSurface.cjs --write` regenerates it and refuses to drop an unauthorized entry. - `test/collaboration`: collaborative XR sessions. diff --git a/apps/vscode-extension/test/tooling/folderDependencies.json b/apps/vscode-extension/test/tooling/folderDependencies.json index dea05663..8d940917 100644 --- a/apps/vscode-extension/test/tooling/folderDependencies.json +++ b/apps/vscode-extension/test/tooling/folderDependencies.json @@ -46,6 +46,7 @@ "platform" ], "core/agent-flow": [], + "core/agent-review": [], "core/agent-prompts": [ "core/metrics" ], diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index ecdcb2e6..0d220c52 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -58,13 +58,19 @@ "src/features/analysis/sections/active-analyses/activeAnalysesCommands.ts" ], "functions.over80Lines": 31, - "complexity.over10": 49, + "complexity.over10": 50, "complexity.over15": 8, "complexity.over20": 0, "complexity.over30": 0, "reachability.unreachable": [ "src/core/agent-flow/acpSessionEvents.ts", + "src/core/agent-prompts/agentActivity.ts", + "src/core/agent-prompts/contextMentions.ts", "src/core/agent-prompts/hotspotPrompt.ts", + "src/core/agent-prompts/promptLibrary.ts", + "src/core/agent-prompts/regressionPrompt.ts", + "src/core/agent-review/hunkReview.ts", + "src/core/agent-review/reviewComments.ts", "src/core/analysis/session/activeAnalyses.ts", "src/core/claude-sessions/claudeSessionContinuity.ts" ], @@ -77,10 +83,10 @@ } }, "informational": { - "src.files": 366, - "src.lines": 61606, - "src.functions": 4428, - "src.unreachableLines": 804, + "src.files": 373, + "src.lines": 62833, + "src.functions": 4545, + "src.unreachableLines": 1722, "console.byFile": { "src/platform/logging/sink.ts": 2 }, @@ -376,6 +382,20 @@ "to": 4, "reason": "#514: core/agent-prompts is the IDE's shared core for the Ask-agent prompt templates; the extension reaches it when its chat lands (#216), the ide branch has only the IDE consumer", "date": "2026-12-05" + }, + { + "metric": "complexity.over10", + "from": 49, + "to": 50, + "reason": "#502 overnight batch 2: core/agent-prompts (context mentions, prompt library, regression prompt, activity helpers) and core/agent-review are the IDE's shared core; the extension reaches them when its chat lands (#214-#216), the ide branch has only the IDE consumer", + "date": "2026-12-05" + }, + { + "metric": "reachability.unreachable", + "from": 4, + "to": 10, + "reason": "#502 overnight batch 2: core/agent-prompts (context mentions, prompt library, regression prompt, activity helpers) and core/agent-review are the IDE's shared core; the extension reaches them when its chat lands (#214-#216), the ide branch has only the IDE consumer", + "date": "2026-12-05" } ] } From 5d015977ccc765e700e9f241cc6660facc2849d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:02:40 +0000 Subject: [PATCH 40/74] feat(ide): agents' commands die with the IDE, even if its Node process crashes (#524) Commands agents run through ACP terminals are their own process group on Unix, and only stopAgent killed them: a sidecar crash left dev servers running. AgentTerminals now reports each command to the Rust core (host.agentProcess.track/untrack, applied in order). The core kills the tracked process groups (SIGTERM, then SIGKILL after a grace) when the sidecar exits unexpectedly, before the fatal dialog, and when the app exits; on Windows each command is assigned to a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, so the system kills it when the core's handle closes. On the Node side stopping a command now escalates to SIGKILL for a group that ignores SIGTERM, a command the shell left in the background stays tracked until it is stopped, and the agents' stopAll in stopServices waits for the process groups to be gone. --- apps/ide/src-tauri/Cargo.lock | 1 + apps/ide/src-tauri/Cargo.toml | 7 +- apps/ide/src-tauri/src/agent_processes.rs | 274 ++++++++++++++++++ apps/ide/src-tauri/src/host.rs | 24 +- apps/ide/src-tauri/src/main.rs | 3 + apps/ide/src-tauri/src/sidecar.rs | 16 + .../main/agentSessions/agentSessionService.ts | 22 +- .../agentSessions/agentSessionsRuntime.ts | 4 +- .../src/main/agentSessions/agentTerminals.ts | 112 ++++++- apps/ide/src/sidecar/tauriHost.ts | 15 + apps/ide/test/agentTerminals.test.ts | 107 +++++++ 11 files changed, 560 insertions(+), 25 deletions(-) create mode 100644 apps/ide/src-tauri/src/agent_processes.rs create mode 100644 apps/ide/test/agentTerminals.test.ts diff --git a/apps/ide/src-tauri/Cargo.lock b/apps/ide/src-tauri/Cargo.lock index c5d3c2f6..6b9baa33 100644 --- a/apps/ide/src-tauri/Cargo.lock +++ b/apps/ide/src-tauri/Cargo.lock @@ -593,6 +593,7 @@ dependencies = [ "icu_collator", "icu_locale_core", "keyring", + "libc", "muda", "notify", "objc2", diff --git a/apps/ide/src-tauri/Cargo.toml b/apps/ide/src-tauri/Cargo.toml index 5c476ae5..ad9b92f1 100644 --- a/apps/ide/src-tauri/Cargo.toml +++ b/apps/ide/src-tauri/Cargo.toml @@ -51,12 +51,17 @@ rusty-leveldb = { version = "4.0.2", default-features = false } # Case-only renames (file index, as Node's lstat) and the default locale (#496). # Message boxes with any number of buttons: TaskDialogIndirect, looked up at run time (#487). # R10 (#488): the earlier builds' secret key, unprotected with DPAPI. -windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_LibraryLoader", "Win32_UI_Controls", "Win32_UI_WindowsAndMessaging"] } +# O22 (#524): agents' commands in a kill-on-close Job Object (JobObjects, Threading for OpenProcess). +windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_UI_Controls", "Win32_UI_WindowsAndMessaging"] } # Screen capture is checked through ScreenCaptureStarting (#487), the versions wry uses. webview2-com = "0.39.1" windows-core = "0.62.2" +[target.'cfg(unix)'.dependencies] +# O22 (#524): agents' commands are killed by process group (killpg) when the sidecar dies. +libc = "0.2" + [target.'cfg(target_os = "linux")'.dependencies] # Message boxes (#487): GtkMessageDialog, the GTK the window already runs on (same version as tauri's). gtk = "0.19.0" diff --git a/apps/ide/src-tauri/src/agent_processes.rs b/apps/ide/src-tauri/src/agent_processes.rs new file mode 100644 index 00000000..26b46044 --- /dev/null +++ b/apps/ide/src-tauri/src/agent_processes.rs @@ -0,0 +1,274 @@ +//! O22 (#524): the commands coding agents run, as the sidecar reports them +//! (`host.agentProcess.track` / `untrack`, src/main/agentSessions/agentTerminals.ts). +//! +//! The sidecar stops them itself when a chat or the app ends, but if the Node +//! process dies nothing would: on Unix every command is its own process group +//! (spawned detached), so a dev server an agent started would outlive the IDE. +//! The core keeps their ids and, when the sidecar exits unexpectedly or the app +//! exits, sends each group SIGTERM, then SIGKILL to what is left after a grace +//! period. On Windows each command is assigned to a Job Object created with +//! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`: the system kills its processes when the +//! core's handle closes, even if the core itself crashes. + +use std::collections::BTreeSet; +use std::sync::Mutex; +use std::time::Duration; + +#[derive(Default)] +pub struct AgentProcesses { + /// The shells' pids, which on Unix are also their process groups' ids. + pids: Mutex>, + #[cfg(windows)] + job: Mutex>, +} + +/// Whether `pid` may be tracked at all: never init, never this process (or, on Unix, its group). +fn acceptable(pid: u32) -> bool { + if pid <= 1 || pid == std::process::id() || pid > i32::MAX as u32 { + return false; + } + #[cfg(unix)] + { + // SAFETY: getpgrp has no preconditions and cannot fail. + let own_group = unsafe { libc::getpgrp() }; + if own_group > 0 && pid == own_group as u32 { + return false; + } + } + true +} + +impl AgentProcesses { + pub fn new() -> Self { + Self::default() + } + + /// Records a command the sidecar started (on Windows, puts it in the kill-on-close job). + pub fn track(&self, pid: u32) -> Result<(), String> { + if !acceptable(pid) { + return Err(format!("refused to track pid {pid}")); + } + #[cfg(windows)] + { + let mut job = self.job.lock().unwrap(); + if job.is_none() { + *job = Some(windows_job::Job::new()?); + } + if let Some(job) = job.as_ref() { + // A process that already ended cannot be opened: nothing to track then. + job.assign(pid)?; + } + } + self.pids.lock().unwrap().insert(pid); + Ok(()) + } + + pub fn untrack(&self, pid: u32) { + self.pids.lock().unwrap().remove(&pid); + } + + #[cfg(test)] + pub fn tracked(&self) -> Vec { + self.pids.lock().unwrap().iter().copied().collect() + } + + /// Kills every tracked command and forgets them; returns how many there were. Blocks for at + /// most about `grace` on Unix (SIGTERM, then SIGKILL to the groups still running). + pub fn kill_all(&self, grace: Duration) -> usize { + let pids: Vec = std::mem::take(&mut *self.pids.lock().unwrap()).into_iter().collect(); + #[cfg(unix)] + unix::kill_groups(&pids, grace); + #[cfg(windows)] + { + let _ = grace; + if let Some(job) = self.job.lock().unwrap().as_ref() { + job.terminate(); + } + } + #[cfg(not(any(unix, windows)))] + let _ = grace; + pids.len() + } +} + +#[cfg(unix)] +mod unix { + use std::time::{Duration, Instant}; + + fn signal_group(pgid: u32, signal: libc::c_int) -> bool { + // SAFETY: kill with a negative pid signals the process group; it only reads its arguments. + unsafe { libc::kill(-(pgid as libc::pid_t), signal) == 0 } + } + + /// Whether any process of the group is left (EPERM: alive, but not ours to signal). + pub fn group_alive(pgid: u32) -> bool { + signal_group(pgid, 0) || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) + } + + pub fn kill_groups(pgids: &[u32], grace: Duration) { + let mut running: Vec = pgids.iter().copied().filter(|&pgid| group_alive(pgid)).collect(); + for &pgid in &running { + signal_group(pgid, libc::SIGTERM); + } + let deadline = Instant::now() + grace; + while !running.is_empty() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(25)); + running.retain(|&pgid| group_alive(pgid)); + } + for &pgid in &running { + eprintln!("[codexr-ide] An agent's command (process group {pgid}) ignored SIGTERM; killing it."); + signal_group(pgid, libc::SIGKILL); + } + } +} + +#[cfg(windows)] +mod windows_job { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + }; + use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; + + /// An unnamed job whose processes the system kills when its last handle closes + /// (this process's, at exit or crash). Kept as an integer: HANDLE is a raw pointer, not Send. + pub struct Job(isize); + + impl Job { + pub fn new() -> Result { + // SAFETY: no security attributes and no name: an unnamed job only this process holds. + let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + if handle.is_null() { + return Err(format!("CreateJobObjectW failed: {}", std::io::Error::last_os_error())); + } + // SAFETY: a plain C struct, valid when zeroed. + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + // SAFETY: `info` lives for the call and the length is its size. + let set = unsafe { + SetInformationJobObject( + handle, + JobObjectExtendedLimitInformation, + std::ptr::from_ref(&info).cast(), + std::mem::size_of::() as u32, + ) + }; + if set == 0 { + let error = std::io::Error::last_os_error(); + // SAFETY: the handle was just created and is closed once. + unsafe { CloseHandle(handle) }; + return Err(format!("SetInformationJobObject failed: {error}")); + } + Ok(Self(handle as isize)) + } + + fn handle(&self) -> HANDLE { + self.0 as HANDLE + } + + /// Puts the process in the job; what it starts from then on joins the job too. + pub fn assign(&self, pid: u32) -> Result<(), String> { + // SAFETY: OpenProcess only reads its arguments; a null handle is checked below. + let process = unsafe { OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid) }; + if process.is_null() { + return Err(format!("OpenProcess({pid}) failed: {}", std::io::Error::last_os_error())); + } + // SAFETY: both handles are valid; the process handle is closed once, right after. + let assigned = unsafe { AssignProcessToJobObject(self.handle(), process) }; + let error = std::io::Error::last_os_error(); + unsafe { CloseHandle(process) }; + if assigned == 0 { + return Err(format!("AssignProcessToJobObject({pid}) failed: {error}")); + } + Ok(()) + } + + pub fn terminate(&self) { + // SAFETY: the handle is valid for the life of `self`. + unsafe { TerminateJobObject(self.handle(), 1) }; + } + } + + impl Drop for Job { + fn drop(&mut self) { + // SAFETY: closed once; closing the last handle kills the job's processes (KILL_ON_JOB_CLOSE). + unsafe { CloseHandle(self.handle()) }; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_refuses_init_and_itself_and_forgets_what_it_is_told() { + let processes = AgentProcesses::new(); + assert!(processes.track(0).is_err()); + assert!(processes.track(1).is_err()); + assert!(processes.track(std::process::id()).is_err()); + assert!(processes.tracked().is_empty()); + processes.untrack(42); + assert_eq!(processes.kill_all(Duration::from_millis(10)), 0); + } + + #[cfg(unix)] + fn spawn_group(script: &str) -> std::process::Child { + use std::os::unix::process::CommandExt; + // Its own process group, as agentTerminals.ts spawns (`detached`). + std::process::Command::new("sh").arg("-c").arg(script).process_group(0).spawn().unwrap() + } + + #[cfg(unix)] + fn wait_gone(child: &mut std::process::Child) -> bool { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while std::time::Instant::now() < deadline { + if child.try_wait().unwrap().is_some() { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false + } + + #[cfg(unix)] + #[test] + fn killing_all_stops_every_tracked_group_and_only_those() { + let processes = AgentProcesses::new(); + let mut tracked = spawn_group("sleep 60"); + let mut untracked = spawn_group("sleep 60"); + let mut forgotten = spawn_group("sleep 60"); + processes.track(tracked.id()).unwrap(); + processes.track(forgotten.id()).unwrap(); + processes.untrack(forgotten.id()); + assert_eq!(processes.tracked(), vec![tracked.id()]); + assert_eq!(processes.kill_all(Duration::from_secs(2)), 1); + assert!(wait_gone(&mut tracked), "the tracked group was killed"); + assert!(processes.tracked().is_empty()); + assert!(untracked.try_wait().unwrap().is_none() && forgotten.try_wait().unwrap().is_none(), "the others still run"); + for child in [&mut untracked, &mut forgotten] { + let _ = child.kill(); + let _ = child.wait(); + } + } + + #[cfg(unix)] + #[test] + fn a_group_that_ignores_sigterm_gets_sigkill_after_the_grace() { + let processes = AgentProcesses::new(); + // The shell ignores SIGTERM, and so does the sleep it runs in the background, in its group. + let mut child = spawn_group("trap '' TERM; sleep 60 & wait"); + std::thread::sleep(Duration::from_millis(200)); + processes.track(child.id()).unwrap(); + let started = std::time::Instant::now(); + processes.kill_all(Duration::from_millis(300)); + assert!(started.elapsed() >= Duration::from_millis(300)); + assert!(wait_gone(&mut child)); + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while unix::group_alive(child.id()) && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert!(!unix::group_alive(child.id()), "the background sleep went with its group"); + } +} diff --git a/apps/ide/src-tauri/src/host.rs b/apps/ide/src-tauri/src/host.rs index cd3f5f18..16a63232 100644 --- a/apps/ide/src-tauri/src/host.rs +++ b/apps/ide/src-tauri/src/host.rs @@ -113,6 +113,11 @@ fn required<'a>(params: &'a Value, key: &str) -> Result<&'a str, String> { str_param(params, key).ok_or_else(|| format!("missing {key}")) } +/// A process id parameter (`pid`), as the sidecar sends it. +fn pid_param(params: &Value) -> Result { + params.get("pid").and_then(Value::as_u64).and_then(|pid| u32::try_from(pid).ok()).ok_or_else(|| "missing pid".to_string()) +} + /// A window by label. Not `get_webview_window`: a window with the scene view beside /// its page holds two webviews, and Tauri no longer sees it as a webview window (#483). fn window_of(app: &AppHandle, params: &Value) -> Result { @@ -139,8 +144,19 @@ pub fn show_fatal(app: &AppHandle, message: &str) { /// a program must reach the pty in the order it was sent; on threads of their own, a line /// and its Enter could swap (#489). Both only queue for the pty's writer or set its size. /// `host.ipc.open` (#499): after the `host.workspace.set` sent before it, so a page's folder calls find the folder. +/// `host.agentProcess.track` / `untrack` (O22, #524): an untrack must never overtake its track; both only +/// update a set (and on Windows assign the process to a job), so they never block. pub fn runs_in_order(method: &str) -> bool { - matches!(method, "host.scene.setBounds" | "host.workspace.set" | "host.ipc.open" | "host.terminal.input" | "host.terminal.resize") + matches!( + method, + "host.scene.setBounds" + | "host.workspace.set" + | "host.ipc.open" + | "host.terminal.input" + | "host.terminal.resize" + | "host.agentProcess.track" + | "host.agentProcess.untrack" + ) } /// The host requests that may block (they wait for the event loop) but must still @@ -240,6 +256,12 @@ pub fn handle(app: &AppHandle, sidecar: &Arc, op: &str, params: &Value) Ok(crate::theme::set(app, theme)) } "secrets.masterKey" => master_key(), + // O22 (#524): the commands coding agents run, killed if the sidecar dies (agent_processes.rs). + "agentProcess.track" => sidecar.agent_processes.track(pid_param(params)?).map(|()| Value::Null), + "agentProcess.untrack" => { + sidecar.agent_processes.untrack(pid_param(params)?); + Ok(Value::Null) + } // #488: the profile migration's marker, and the key the earlier builds' secret store used. "migration.get" => Ok(app.try_state::>().map(|migration| migration.get()).unwrap_or(Value::Null)), "migration.record" => match app.try_state::>() { diff --git a/apps/ide/src-tauri/src/main.rs b/apps/ide/src-tauri/src/main.rs index c40c272a..6126bf04 100644 --- a/apps/ide/src-tauri/src/main.rs +++ b/apps/ide/src-tauri/src/main.rs @@ -18,6 +18,7 @@ // pipes (the smoke run and the benchmark read the result lines from stdout). #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +mod agent_processes; mod assets; mod atomic_file; mod call_order; @@ -367,6 +368,8 @@ fn main() { native.terminals.kill_all(std::time::Duration::from_secs(3)); } sidecar.kill(); + // O22 (#524): and so does every command an agent ran that the sidecar did not stop. + sidecar.kill_agent_processes(); } _ => {} }); diff --git a/apps/ide/src-tauri/src/sidecar.rs b/apps/ide/src-tauri/src/sidecar.rs index 5d538ab1..44c66292 100644 --- a/apps/ide/src-tauri/src/sidecar.rs +++ b/apps/ide/src-tauri/src/sidecar.rs @@ -24,6 +24,7 @@ use tauri::ipc::Channel; use tauri::{AppHandle, Manager}; use tokio::sync::oneshot; +use crate::agent_processes::AgentProcesses; use crate::host; type Pending = HashMap>>; @@ -91,12 +92,16 @@ pub struct Sidecar { /// #506: the sidecar's last stderr lines that did not come from its logger (a crash before /// the log file opened, Node's own fatal errors), appended to the log file if it dies. stderr_tail: Arc>>, + /// O22 (#524): the commands agents ran, killed if the sidecar dies or the app exits. + pub agent_processes: AgentProcesses, } /// How many of the sidecar's last stderr lines are kept for its log (#506). const STDERR_TAIL_LINES: usize = 60; /// The sidecar logger's prefix (src/main/log.ts): those lines are in the log file already. const LOGGER_PREFIX: &str = "[code-xr-ide]"; +/// How long agents' commands get to end on SIGTERM before SIGKILL (O22, #524). +const AGENT_PROCESS_GRACE: Duration = Duration::from_millis(1500); /// The log file's name in the log folder (src/main/logFile.ts `LOG_FILE_NAME`). pub const LOG_FILE_NAME: &str = "sidecar.log"; @@ -157,6 +162,15 @@ impl Sidecar { log_file: Mutex::new(None), interactive: AtomicBool::new(true), stderr_tail: Arc::new(Mutex::new(VecDeque::new())), + agent_processes: AgentProcesses::new(), + } + } + + /// O22 (#524): kills the commands agents ran that the sidecar did not stop (it died, or ran out of time). + pub fn kill_agent_processes(&self) { + let killed = self.agent_processes.kill_all(AGENT_PROCESS_GRACE); + if killed > 0 { + eprintln!("[codexr-ide] Stopped {killed} command(s) coding agents left running."); } } @@ -306,6 +320,8 @@ impl Sidecar { } if !this.is_exiting() { eprintln!("[codexr-ide] The Node sidecar exited unexpectedly ({status})."); + // O22 (#524): before the dialog, which may stay up a long time: no dev server outlives the sidecar. + this.kill_agent_processes(); let status = status.to_string(); // #506: what it printed outside its logger (a crash before the log file opened) goes to the log too. let _ = stderr_done.recv_timeout(Duration::from_millis(500)); diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 4c2c923c..bfa4e51b 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -78,7 +78,7 @@ import { type RemoteControlReply, } from '@codexr/core/claude-sessions/claudeSessionContinuity'; import { parsePresetId, type AgentInstaller } from './agentInstaller.ts'; -import { AgentTerminals } from './agentTerminals.ts'; +import { AgentTerminals, type AgentProcessRegistry } from './agentTerminals.ts'; import { isSessionId, type SessionStore } from './sessionStore.ts'; import { canUseWorktrees, commitAll, createWorktree, mergeIntoCurrent, removeWorktree, worktreeStatus, WorktreeError, type WorktreeInfo } from '../worktrees/worktreeManager.ts'; import { runWorktreeGit } from '../worktrees/worktreeGit.ts'; @@ -182,6 +182,8 @@ export interface AgentSessionServiceOptions { readonly homeDir: string; /** The environment of the commands agents run in terminals. */ readonly terminalEnv: Readonly>; + /** O22 (#524): where the commands agents run are reported, so the Rust core kills them if this process dies. */ + readonly agentProcesses?: AgentProcessRegistry; readonly platform?: NodeJS.Platform; readonly log?: (line: string) => void; readonly now?: () => string; @@ -1481,10 +1483,9 @@ export class AgentSessionService { /** The app quits: every agent stops and every chat is written. */ async stopAll(): Promise { this.stopped = true; - for (const live of this.live.values()) { - this.stopAgent(live); - } - await this.options.store.flush(); + // O22 (#524): the commands agents ran end with them: their process groups are waited for (SIGKILL after a grace). + const stopped = [...this.live.values()].map((live) => this.stopAgent(live)); + await Promise.all([this.options.store.flush(), ...stopped]); } // ---- Internals ------------------------------------------------------------ @@ -1644,11 +1645,12 @@ export class AgentSessionService { root: workRoot, env: this.options.terminalEnv, isInside: (root, candidate) => isSameOrInside(root, candidate, this.platform), + ...(this.options.agentProcesses ? { processes: this.options.agentProcesses } : {}), events: { onOutput: (terminalId, chunk, exitCode, truncated) => this.queueTerminalOutput(live, terminalId, chunk, exitCode, truncated) }, }); const connection = this.connectAgent(resolution.launch, workRoot, this.handlersFor(live, terminals)); connection.onClose((error) => { - terminals.disposeAll(); + void terminals.disposeAll(); if (live.agent?.connection === connection) { live.agent = null; this.cancelPermissions(live); @@ -1744,7 +1746,7 @@ export class AgentSessionService { killTerminal: (params) => terminals.kill(params.terminalId), releaseTerminal: (params) => { this.flushTerminalOutput(live); - terminals.release(params.terminalId); + void terminals.release(params.terminalId); }, }; } @@ -2045,7 +2047,8 @@ export class AgentSessionService { } } - private stopAgent(live: Live): void { + /** Stops the chat's agent; resolves once the commands it ran are gone. */ + private stopAgent(live: Live): Promise { this.cancelPermissions(live); const agent = live.agent; live.agent = null; @@ -2054,12 +2057,13 @@ export class AgentSessionService { this.endRemoteControl(live); } agent?.connection.close(); - agent?.terminals.disposeAll(); + const commands = agent?.terminals.disposeAll() ?? Promise.resolve(); if (live.terminalTimer) { clearTimeout(live.terminalTimer); live.terminalTimer = null; } live.terminalBuffer.clear(); + return commands; } } diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 4ccae4fb..d796e3d2 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -1,4 +1,4 @@ -import { app, BrowserWindow, dialog, net, webContents, type WebContents, type MessageBoxOptions } from '../host/desktop.ts'; +import { agentProcesses, app, BrowserWindow, dialog, net, webContents, type WebContents, type MessageBoxOptions } from '../host/desktop.ts'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -307,6 +307,8 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS probeDir: path.join(dir, 'probe'), homeDir: os.homedir(), terminalEnv: { ...terminalEnvironment(process.env), CI: '1', NO_COLOR: '1', GIT_PAGER: 'cat', PAGER: 'cat' }, + // O22 (#524): the core kills what agents ran if this process dies. + agentProcesses, log: (line) => log.info(`[agent] ${line}`), }); diff --git a/apps/ide/src/main/agentSessions/agentTerminals.ts b/apps/ide/src/main/agentSessions/agentTerminals.ts index 91eb7997..dd6a1a60 100644 --- a/apps/ide/src/main/agentSessions/agentTerminals.ts +++ b/apps/ide/src/main/agentSessions/agentTerminals.ts @@ -12,10 +12,28 @@ import type { TerminalSnapshot } from './acpMapping.ts'; * and listeners for the chat. The command line comes from the agent, so it * runs through a shell; the folder is the project unless the agent names a * folder inside it. + * + * O22 (#524): on Unix each command is its own process group; stopping one + * sends the group SIGTERM, then SIGKILL after `KILL_GRACE_MS`. Every command + * is also reported to the Rust core (`AgentProcessRegistry`), which kills + * what is still running if this Node process dies or the app exits (on + * Windows the core puts the command in a kill-on-close Job Object). */ export const DEFAULT_OUTPUT_LIMIT = 1_000_000; export const MAX_TERMINALS_PER_SESSION = 32; +/** How long a stopped command's process group has to end on SIGTERM before it gets SIGKILL. */ +export const KILL_GRACE_MS = 2000; + +/** + * O22 (#524): where agent commands are reported, so they die with the app + * even when this process cannot stop them (a crash). `pid` is the shell's, + * which on Unix is also the process group's id. + */ +export interface AgentProcessRegistry { + track(pid: number): void; + untrack(pid: number): void; +} export interface TerminalEvents { /** New output (already appended to the terminal's buffer), or the exit with an empty chunk. */ @@ -28,6 +46,8 @@ interface Running { truncated: boolean; readonly limit: number; exit: { exitCode: number | null; signal: string | null } | null; + /** O22 (#524): whether the core still holds its pid (reported once each way). */ + tracked: boolean; readonly exited: Promise; } @@ -64,13 +84,21 @@ export class AgentTerminals { private readonly env: Readonly>; private readonly events: TerminalEvents; private readonly isInside: (root: string, candidate: string) => boolean; + private readonly processes: AgentProcessRegistry | undefined; private nextId = 1; - constructor(options: { readonly root: string; readonly env: Readonly>; readonly events: TerminalEvents; readonly isInside: (root: string, candidate: string) => boolean }) { + constructor(options: { + readonly root: string; + readonly env: Readonly>; + readonly events: TerminalEvents; + readonly isInside: (root: string, candidate: string) => boolean; + readonly processes?: AgentProcessRegistry; + }) { this.root = options.root; this.env = options.env; this.events = options.events; this.isInside = options.isInside; + this.processes = options.processes; } create(params: CreateTerminalRequest): string { @@ -99,11 +127,15 @@ export class AgentTerminals { detached: process.platform !== 'win32', }); const id = `term-${this.nextId++}`; + const pid = child.pid; + if (pid !== undefined) { + this.processes?.track(pid); + } let markExited: () => void = () => undefined; const exited = new Promise((resolve) => { markExited = resolve; }); - const running: Running = { child, output: '', truncated: false, limit, exit: null, exited }; + const running: Running = { child, output: '', truncated: false, limit, exit: null, exited, tracked: pid !== undefined }; this.terminals.set(id, running); const append = (chunk: string): void => { const kept = keepTail(running.output + chunk, running.limit); @@ -120,6 +152,10 @@ export class AgentTerminals { return; } running.exit = { exitCode, signal }; + // The shell ended; what it put in the background (same group) stays tracked until it is stopped. + if (pid !== undefined && (process.platform === 'win32' || !groupAlive(pid))) { + this.untrack(running); + } this.events.onOutput(id, '', exitCode ?? (signal ? 1 : null), running.truncated); markExited(); }; @@ -161,26 +197,57 @@ export class AgentTerminals { } kill(terminalId: string): void { - const running = this.get(terminalId); - if (!running.exit) { - killTree(running.child); - } + void this.stop(this.get(terminalId)); } - release(terminalId: string): void { + /** Stops the command (and its process group) and forgets the terminal; resolves once the group is gone. */ + release(terminalId: string): Promise { const running = this.terminals.get(terminalId); if (!running) { + return Promise.resolve(); + } + this.terminals.delete(terminalId); + return this.stop(running); + } + + /** Releases every terminal; resolves once their process groups are gone (within about `KILL_GRACE_MS`). */ + async disposeAll(): Promise { + await Promise.all([...this.terminals.keys()].map((id) => this.release(id))); + } + + /** SIGTERM to the group, SIGKILL to what is left after the grace period (Unix); `taskkill /t /f` on Windows. */ + private async stop(running: Running): Promise { + const pid = running.child.pid; + if (process.platform === 'win32' || pid === undefined) { + if (!running.exit) { + killTree(running.child); + } + this.untrack(running); return; } - if (!running.exit) { - killTree(running.child); + if (running.exit && !running.tracked) { + // Ended with nothing left in its group: never signal a group id the system may have reused. + return; } - this.terminals.delete(terminalId); + // The shell may be gone while its group lives on (a command it put in the background). + signalGroup(pid, 'SIGTERM'); + const deadline = Date.now() + KILL_GRACE_MS; + while (groupAlive(pid) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 50)); + } + if (groupAlive(pid)) { + signalGroup(pid, 'SIGKILL'); + // A killed shell lingers as a zombie (still in its group) until Node reaps it. + await Promise.race([running.exited, new Promise((resolve) => setTimeout(resolve, 1000))]); + } + this.untrack(running); } - disposeAll(): void { - for (const id of [...this.terminals.keys()]) { - this.release(id); + private untrack(running: Running): void { + const pid = running.child.pid; + if (running.tracked && pid !== undefined) { + running.tracked = false; + this.processes?.untrack(pid); } } @@ -193,6 +260,25 @@ export class AgentTerminals { } } +/** Whether a process of the group `pgid` still runs (Unix). */ +function groupAlive(pgid: number): boolean { + try { + process.kill(-pgid, 0); + return true; + } catch (error) { + // EPERM: the group exists but may not be signalled: it is alive. + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +function signalGroup(pgid: number, signal: NodeJS.Signals): void { + try { + process.kill(-pgid, signal); + } catch { + // Already gone. + } +} + /** Stops the shell and what it started (on Windows, `taskkill /t`). */ function killTree(child: ChildProcess): void { try { diff --git a/apps/ide/src/sidecar/tauriHost.ts b/apps/ide/src/sidecar/tauriHost.ts index 93066e1c..02c5cea9 100644 --- a/apps/ide/src/sidecar/tauriHost.ts +++ b/apps/ide/src/sidecar/tauriHost.ts @@ -707,6 +707,21 @@ interface SaveDialogOptions { readonly filters?: readonly FileFilter[]; } +/** + * O22 (#524): the commands coding agents run (agentTerminals.ts), reported to + * the core so they die with the app even if this process crashes: the core + * kills their process groups on exit (Unix) or holds them in a kill-on-close + * Job Object (Windows). Notifications, applied in order by the core. + */ +export const agentProcesses = { + track(pid: number): void { + hostNotify('agentProcess.track', { pid }); + }, + untrack(pid: number): void { + hostNotify('agentProcess.untrack', { pid }); + }, +}; + /** The dialog calls take an optional parent window first. */ function splitParent(first: unknown, second: T | undefined): { window: string | null; options: T } { if (first instanceof TauriBrowserWindow) { diff --git a/apps/ide/test/agentTerminals.test.ts b/apps/ide/test/agentTerminals.test.ts new file mode 100644 index 00000000..64682522 --- /dev/null +++ b/apps/ide/test/agentTerminals.test.ts @@ -0,0 +1,107 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import os from 'node:os'; +import { AgentTerminals, type AgentProcessRegistry } from '../src/main/agentSessions/agentTerminals.ts'; + +/** O22 (#524): the commands agents run are reported to the core and stopped with their whole process group. */ + +function alive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +function recordingRegistry(): AgentProcessRegistry & { readonly tracked: Set; readonly calls: string[] } { + const tracked = new Set(); + const calls: string[] = []; + return { + tracked, + calls, + track(pid) { + tracked.add(pid); + calls.push(`track ${pid}`); + }, + untrack(pid) { + tracked.delete(pid); + calls.push(`untrack ${pid}`); + }, + }; +} + +function terminals(processes: AgentProcessRegistry, output: (chunk: string) => void = () => undefined): AgentTerminals { + return new AgentTerminals({ + root: os.tmpdir(), + env: { ...process.env } as Record, + isInside: () => true, + processes, + events: { onOutput: (_id, chunk) => output(chunk) }, + }); +} + +const waitFor = async (condition: () => boolean, ms = 5000): Promise => { + const deadline = Date.now() + ms; + while (!condition()) { + if (Date.now() > deadline) { + throw new Error('Timed out.'); + } + await new Promise((resolve) => setTimeout(resolve, 20)); + } +}; + +describe('agent terminals: process cleanup (O22)', { skip: process.platform === 'win32' ? 'POSIX shells and process groups' : false }, () => { + it('reports `sleep 60` to the registry and kills it when the chat stops', async () => { + const registry = recordingRegistry(); + const host = terminals(registry); + const id = host.create({ sessionId: 's', command: 'sleep', args: ['60'] }); + assert.equal(registry.tracked.size, 1); + const [pid] = [...registry.tracked]; + assert.ok(pid !== undefined && alive(pid)); + await host.disposeAll(); + assert.equal(alive(pid), false, 'the shell and its sleep are gone'); + assert.deepEqual(registry.calls, [`track ${pid}`, `untrack ${pid}`]); + assert.throws(() => host.output(id), /Unknown terminal/); + }); + it('keeps a command the shell left in the background tracked until it is stopped', async () => { + const registry = recordingRegistry(); + let output = ''; + const host = terminals(registry, (chunk) => { + output += chunk; + }); + const id = host.create({ sessionId: 's', command: 'sleep 60 > /dev/null 2>&1 & echo started:$!', args: [] }); + const [shell] = [...registry.tracked]; + assert.ok(shell !== undefined); + await host.waitForExit(id); + const sleeper = Number(/started:(\d+)/.exec(output)?.[1]); + assert.ok(sleeper > 0 && alive(sleeper), 'the background sleep outlived its shell'); + // Still in the shell's process group: the core would kill it if the IDE crashed now. + assert.equal(registry.tracked.has(shell), true); + await host.release(id); + await waitFor(() => !alive(sleeper)); + assert.equal(registry.tracked.size, 0); + }); + it('forgets a command that ended with nothing left behind', async () => { + const registry = recordingRegistry(); + const host = terminals(registry); + const id = host.create({ sessionId: 's', command: 'echo', args: ['done'] }); + await host.waitForExit(id); + assert.equal(registry.tracked.size, 0); + await host.release(id); + }); + it('escalates to SIGKILL for a group that ignores SIGTERM', async () => { + const registry = recordingRegistry(); + let output = ''; + const host = terminals(registry, (chunk) => { + output += chunk; + }); + host.create({ sessionId: 's', command: 'trap "" TERM; echo ready; sleep 60', args: [] }); + await waitFor(() => output.includes('ready')); + const [pid] = [...registry.tracked]; + const started = Date.now(); + await host.disposeAll(); + assert.ok(Date.now() - started >= 1500, 'SIGTERM was given its grace period'); + assert.equal(alive(pid!), false); + }); +}); From df8575a0915750e64bdaf22dee0f78034802b5bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:14:41 +0000 Subject: [PATCH 41/74] feat(ide): remember the live analysis column, reopen tab, default key and first-run order (#532) - The hidden state of the live analysis column persists (codexr.layout.dockHidden, parseDockHidden) and survives layout switches; a slim vertical 'Live analysis' tab at the right edge brings it back (accessible button, tooltip with the key). - layout.toggleLiveAnalysis gets Ctrl/Cmd+Alt+B (VS Code's Toggle Secondary Side Bar), free on every OS and in Monaco. - First run: the guided tour waits until the getting-started guide is done, skipped or its tab closed (tour/firstRunGate.ts), and after the launch animation; the guide's new 'Don't show again' also skips the tour. - Strings en/es, unit tests (test/liveAnalysisFirstRun.test.ts). --- .../src/renderer/agentFirst/agentFirst.css | 24 +++- .../src/renderer/agentFirst/agentWorkbench.ts | 69 ++++++++++-- .../agentFirst/agentWorkbenchModel.ts | 20 ++++ .../renderer/agentFirst/gettingStartedView.ts | 7 +- apps/ide/src/renderer/main.ts | 22 +++- apps/ide/src/renderer/tour/firstRunGate.ts | 95 ++++++++++++++++ apps/ide/src/shared/defaultKeybindings.ts | 2 + apps/ide/src/shared/i18n/messages.en.ts | 6 + apps/ide/src/shared/i18n/messages.es.ts | 6 + apps/ide/test/keybindingDefaults.test.ts | 2 +- apps/ide/test/liveAnalysisFirstRun.test.ts | 103 ++++++++++++++++++ docs/ide/keybindings.md | 1 + 12 files changed, 344 insertions(+), 13 deletions(-) create mode 100644 apps/ide/src/renderer/tour/firstRunGate.ts create mode 100644 apps/ide/test/liveAnalysisFirstRun.test.ts diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index d9d28fb4..f2715ed3 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -19,8 +19,27 @@ border-left: 1px solid var(--line); background: var(--panel); } -.workbench.mode-agent.dock-hidden:not(.has-scene) { --dock-col: 0px; } -.workbench.mode-agent.dock-hidden:not(.has-scene) .af-dock { display: none; } +.workbench.mode-agent.dock-hidden:not(.has-scene) { --dock-col: 28px; } +/* #532: a hidden column leaves a slim vertical tab at the right edge that brings it back. */ +.af-dock-reopen { display: none; } +.workbench.mode-agent.dock-hidden:not(.has-scene) .af-dock > :not(.af-dock-reopen) { display: none; } +.workbench.mode-agent.dock-hidden:not(.has-scene) .af-dock-reopen { + flex: 1; + display: flex; + align-items: flex-start; + justify-content: center; + width: 100%; + padding: 12px 0; + border: 0; + background: var(--chrome); + color: var(--muted); + font: inherit; + font-size: var(--fs-sm); + font-weight: 600; + cursor: pointer; +} +.af-dock-reopen:hover { background: var(--hover); color: var(--fg); } +.af-dock-reopen-label { writing-mode: vertical-rl; white-space: nowrap; } @media (max-width: 1100px) { .workbench.mode-agent:not(.has-scene) { --dock-col: 0px; } .workbench.mode-agent:not(.has-scene) .af-dock { display: none; } @@ -290,6 +309,7 @@ .af-guide-title { margin: 0; font-size: var(--fs-xl); } .af-guide-lead { margin: 4px 0 0; font-size: var(--fs-sm); } .af-guide-skip { font-size: var(--fs-sm); } +.af-guide-head-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px 12px; } .af-guide-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; } .af-guide-step { display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 10px; } .af-guide-number { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border: 1px solid var(--line); border-radius: 50%; font-size: var(--fs-sm); color: var(--muted); } diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 6cbdc74f..a61015c3 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -11,7 +11,7 @@ import { closeIcon, el } from '../dom.ts'; import { createChatView, type ChatView, type ChatViewDeps } from './chatView.ts'; import { createSessionsView, type SessionsView } from './sessionsView.ts'; import { createInstructionsView, type InstructionsViewDeps } from './instructionsView.ts'; -import { chatIdOf, chatTabId, parseLayoutMode, type LayoutMode } from './agentWorkbenchModel.ts'; +import { chatIdOf, chatTabId, DOCK_HIDDEN_KEY, dockReopenTitle, formatDockHidden, parseDockHidden, parseLayoutMode, type LayoutMode } from './agentWorkbenchModel.ts'; import { createChangesView, type ChangesView } from './changesView.ts'; import { changesIdOf, changesTabId } from './changesModel.ts'; import { createGettingStartedView, type GettingStartedView } from './gettingStartedView.ts'; @@ -20,6 +20,7 @@ import { errorText as setupErrorText } from './agentSetup.ts'; import { attentionText } from './sessionsModel.ts'; import { createSessionNoticeTracker } from './sessionNotices.ts'; import { t, type MessageKey } from '../../shared/i18n/i18n.ts'; +import type { FirstRunGuidePhase } from '../tour/firstRunGate.ts'; import { shouldNotifySystem, type AgentNoticeEvent, type AgentNoticeKind } from '@codexr/core/agent-prompts/agentActivity'; import './agentFirst.css'; @@ -70,6 +71,14 @@ export interface AgentWorkbenchOptions { metricThresholds?(): MetricThresholds | null; /** #523: the `agents.systemNotifications` setting (absent: on). */ systemNotifications?(): boolean; + /** #532: the key of a command as the palette shows it ('' without one), for tooltips. */ + keyLabel?(commandId: string): string; + /** + * #532: the first-run guide's state, for the guided tour: `absent` (it does not open on its + * own this time), `open`, `closed` (done, skipped or its tab closed) or `dismissed` + * ("Don't show again": no tour either). Reported once the guide's first-run check settles. + */ + onFirstRunGuide?(phase: Exclude): void; /** Optional hooks of later stories. */ readonly chatHooks?: Pick; } @@ -123,8 +132,17 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork const artPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); artPath.setAttribute('d', DOCK_ART); art.append(artPath); - const hideDock = el('button', { className: 'icon-button', attrs: { type: 'button', title: 'Hide the live analysis column', 'aria-label': 'Hide the live analysis column' } }, [closeIcon()]); - hideDock.addEventListener('click', () => setDockHidden(true)); + const hideDock = el('button', { className: 'icon-button', attrs: { type: 'button', title: t('dock.hide'), 'aria-label': t('dock.hide'), 'data-testid': 'af-dock-hide' } }, [closeIcon()]); + hideDock.addEventListener('click', () => { + setDockHidden(true); + reopenDock.focus(); + }); + // #532: a slim vertical tab at the right edge while the column is hidden. + const reopenDock = el('button', { className: 'af-dock-reopen', attrs: { type: 'button', 'data-testid': 'af-dock-reopen' } }, [el('span', { className: 'af-dock-reopen-label', text: t('dock.reopen') })]); + reopenDock.addEventListener('click', () => { + setDockHidden(false); + hideDock.focus(); + }); // CI3: the dock says what is happening instead of "Waiting" while the first analysis runs. const live = el('span', { className: 'af-live', text: t('dock.live.waiting'), attrs: { 'data-state': 'idle', 'data-testid': 'af-dock-live' } }); const dockBar = el('div', { className: 'progress-bar' }); @@ -136,6 +154,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork workbench.dockArea.replaceChildren( el('header', { className: 'af-dock-head' }, [el('span', { text: 'Live analysis' }), live, el('span', { className: 'af-spacer' }), hideDock]), el('div', { className: 'af-dock-body' }, [art, el('h3', { text: 'See your project change while the AI works' }), dockNote, analyse, dockProgress]), + reopenDock, ); function renderDock(): void { const folder = options.hasFolder(); @@ -155,9 +174,20 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork dockBar.style.width = percent === undefined ? '' : `${Math.max(0, Math.min(100, percent))}%`; dockStep.textContent = dockAnalysis?.message ?? ''; } - function setDockHidden(hidden: boolean): void { + function setDockHidden(hidden: boolean, remember = true): void { const shell = workbench.dockArea.parentElement; shell?.classList.toggle('dock-hidden', hidden); + const title = dockReopenTitle(options.keyLabel?.('layout.toggleLiveAnalysis') ?? ''); + reopenDock.title = title; + reopenDock.setAttribute('aria-label', title); + if (!remember) { + return; + } + try { + localStorage.setItem(DOCK_HIDDEN_KEY, formatDockHidden(hidden)); + } catch { + // Remembering the column is a convenience. + } } // ---- Chats as editor tabs (AF3) ---------------------------------------- @@ -448,6 +478,14 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork let hasChat = false; let inlineGuide: GettingStartedView | null = null; let closeGuideTab: (() => void) | null = null; + /** #532: the guide opened on its own at launch and has not closed yet (the tour waits for it). */ + let firstRunGuideOpen = false; + const firstRunGuideClosed = (how: 'closed' | 'dismissed'): void => { + if (firstRunGuideOpen || how === 'dismissed') { + firstRunGuideOpen = false; + options.onFirstRunGuide?.(how); + } + }; const readOnboarded = (): string | null => { try { return localStorage.getItem(ONBOARDED_KEY); @@ -455,7 +493,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork return null; } }; - function finishGuide(): void { + function finishGuide(how: 'closed' | 'dismissed' = 'closed'): void { try { localStorage.setItem(ONBOARDED_KEY, 'true'); } catch { @@ -466,6 +504,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork guides.delete(inlineGuide); inlineGuide = null; } + // Reported before the tab closes, whose own "closed" would let the tour start after a dismissal. + firstRunGuideClosed(how); closeGuideTab?.(); } function createGuide(): GettingStartedView { @@ -489,7 +529,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork finishGuide(); } }, - skip: finishGuide, + skip: () => finishGuide('closed'), + dismiss: () => finishGuide('dismissed'), }); } function guideInput(): CustomEditorInput { @@ -507,6 +548,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork dispose: () => { guides.delete(guide); closeGuideTab = null; + // #532: closing the first-run guide's tab lets the tour start. + firstRunGuideClosed('closed'); }, }; }, @@ -533,8 +576,11 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork // The guide opens on its own only on a first run: never once done or skipped, never for someone with chats. void refreshHasChat().then(() => { if (!shouldShowOnboarding(readOnboarded(), hasChat)) { + options.onFirstRunGuide?.('absent'); return; } + firstRunGuideOpen = true; + options.onFirstRunGuide?.('open'); const welcome = workbench.editorArea.querySelector('[data-testid="welcome"]'); if (welcome?.isConnected) { inlineGuide = createGuide(); @@ -609,8 +655,8 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork // Remembering the mode is a convenience. } workbench.setLayoutMode(next); + // #532: the live analysis column keeps the state the person left it in (its reopen tab is always there). if (next === 'agent') { - setDockHidden(false); workbench.showView('chats'); } sessions.setActive(activeChatId); @@ -640,6 +686,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork setDockHidden(!shell?.classList.contains('dock-hidden')); } }); + setDockHidden(readDockHidden(), false); setMode(mode); instructions.refresh().catch(() => undefined); @@ -677,6 +724,14 @@ function readMode(): LayoutMode { } } +function readDockHidden(): boolean { + try { + return parseDockHidden(localStorage.getItem(DOCK_HIDDEN_KEY)); + } catch { + return parseDockHidden(null); + } +} + function errorText(error: unknown): string { return (error instanceof Error ? error.message : String(error)).replace(/^Error invoking remote method '[^']+': (Error: )?/, ''); } diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbenchModel.ts b/apps/ide/src/renderer/agentFirst/agentWorkbenchModel.ts index 79a430bc..fef1d3f0 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbenchModel.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbenchModel.ts @@ -3,6 +3,8 @@ * the ids of chat tabs. No DOM. */ +import { t } from '../../shared/i18n/i18n.ts'; + export type LayoutMode = 'agent' | 'classic'; /** The remembered layout mode; a new install starts in the Agent layout. */ @@ -25,3 +27,21 @@ export function chatIdOf(tabId: string): string | null { const id = tabId.slice(CHAT_ID_PREFIX.length); return id.length > 0 ? id : null; } + +/** #532: where "the live analysis column is hidden" is remembered (the renderer's localStorage). */ +export const DOCK_HIDDEN_KEY = 'codexr.layout.dockHidden'; + +/** #532: the remembered state of the live analysis column; shown unless it was hidden on purpose. */ +export function parseDockHidden(value: string | null | undefined): boolean { + return value === 'true'; +} + +/** #532: what `DOCK_HIDDEN_KEY` stores for a state. */ +export function formatDockHidden(hidden: boolean): string { + return hidden ? 'true' : 'false'; +} + +/** #532: the reopen tab's tooltip and accessible name, with the toggle's key when it has one. */ +export function dockReopenTitle(key: string): string { + return key ? t('dock.reopenTitleKey', { key }) : t('dock.reopenTitle'); +} diff --git a/apps/ide/src/renderer/agentFirst/gettingStartedView.ts b/apps/ide/src/renderer/agentFirst/gettingStartedView.ts index eeb8a0f4..f3e15992 100644 --- a/apps/ide/src/renderer/agentFirst/gettingStartedView.ts +++ b/apps/ide/src/renderer/agentFirst/gettingStartedView.ts @@ -23,6 +23,8 @@ export interface GettingStartedDeps { startChat(agentRef: string): Promise; /** Skip: the guide does not open on its own again. */ skip(): void; + /** #532: "Don't show again": as Skip, and the guided tour does not start on its own either. */ + dismiss?(): void; } export interface GettingStartedView { @@ -38,13 +40,16 @@ export function createGettingStartedView(deps: GettingStartedDeps): GettingStart const steps = el('ol', { className: 'af-guide-steps' }); const skip = el('button', { className: 'af-link-button af-guide-skip', text: t('guide.skip'), attrs: { type: 'button', title: t('guide.skipTitle'), 'data-testid': 'af-guide-skip' } }); skip.addEventListener('click', () => deps.skip()); + const dismiss = el('button', { className: 'af-link-button af-guide-skip', text: t('guide.dontShow'), attrs: { type: 'button', title: t('guide.dontShowTitle'), 'data-testid': 'af-guide-dont-show' } }); + dismiss.addEventListener('click', () => deps.dismiss?.()); + dismiss.hidden = deps.dismiss === undefined; const element = el('section', { className: 'af-guide', attrs: { 'data-testid': 'af-guide', 'aria-labelledby': 'af-guide-title' } }, [ el('header', { className: 'af-guide-head' }, [ el('div', {}, [ el('h2', { className: 'af-guide-title', text: t('guide.title'), attrs: { id: 'af-guide-title' } }), el('p', { className: 'muted af-guide-lead', text: t('guide.lead') }), ]), - skip, + el('div', { className: 'af-guide-head-actions' }, [skip, dismiss]), ]), steps, ]); diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 26d5d7b0..8055511d 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -13,6 +13,7 @@ import type { AnalysisSubject } from '../shared/analysisKinds.ts'; import { createStartupAnimation } from './startup/launchController.ts'; import { lazyGuidedTour } from './tour/lazyTour.ts'; import { shouldAutoStartTour, TOUR_DONE_KEY, TOUR_SETTING, TOUR_SETTLE_MS } from './tour/tourModel.ts'; +import { createFirstRunGate } from './tour/firstRunGate.ts'; import codeXrLogoUrl from '../../../vscode-extension/resources/icon.svg?url'; import { createScenePanel } from './scenePanel.ts'; import { createCodeXrView } from './codexr/codexrView.ts'; @@ -1352,7 +1353,22 @@ function workspacePathOf(path: string): string { } // #525: the explorer marks the files the chat last shown read and edited. const chatFootprints = createChatFootprintFeed(api.agentSessions, (footprint) => explorer.setChatFootprint(footprint)); +// #532: the guided tour waits for the first-run guide; "Don't show again" there skips the tour too. +const firstRunGate = createFirstRunGate({ + onDismissed: () => { + try { + localStorage.setItem(TOUR_DONE_KEY, 'skipped'); + } catch { + // Without storage the welcome may show again; nothing else depends on it. + } + }, +}); const agentWorkbench = installAgentWorkbench({ + keyLabel: (id) => { + const binding = registry.keybindings(id)[0]; + return binding ? formatKeybinding(binding, platform) : ''; + }, + onFirstRunGuide: (phase) => firstRunGate.guide(phase), workbench, api: api.agentSessions, registry, @@ -1513,11 +1529,13 @@ api.settings.get().then((report) => { return; } // The folder opened at launch starts its analysis (and the animation) in the first moments. - setTimeout(() => startupAnimation.afterAnimation(() => { + // #532: then the first-run guide, if it opened, has to close first; the animation is waited for again + // in case it started meanwhile. + setTimeout(() => firstRunGate.whenTourMayStart(() => startupAnimation.afterAnimation(() => { if (!guidedTour.isOpen && readTourDone() === null) { guidedTour.start(); } - }), TOUR_SETTLE_MS); + })), TOUR_SETTLE_MS); }, () => undefined); // #16: analyses of the open folder, and their scene beside the code. /** CI2/CI3: the title of the analysis this window runs, while it runs; the core's own progress joins its toast. */ diff --git a/apps/ide/src/renderer/tour/firstRunGate.ts b/apps/ide/src/renderer/tour/firstRunGate.ts new file mode 100644 index 00000000..5693a810 --- /dev/null +++ b/apps/ide/src/renderer/tour/firstRunGate.ts @@ -0,0 +1,95 @@ +/** + * #532: the first run in order. The getting-started guide (agentFirst, + * AF13), the guided tour (CI12) and the launch animation (#403) could all + * appear together; the tour now waits until the guide is done, skipped or + * its tab closed, and does not start at all when the guide was dismissed + * with "Don't show again". (The launch animation is waited for by main.ts + * through `startupAnimation.afterAnimation`, and holds an open tour.) + * No DOM: unit-tested (test/firstRunGate.test.ts). + */ + +/** + * The first-run guide as the tour sees it: `pending` until the workbench has + * checked whether it opens on its own, then `absent` (it does not, this + * time), `open`, `closed` (done, skipped or its tab closed) or `dismissed`. + */ +export type FirstRunGuidePhase = 'pending' | 'absent' | 'open' | 'closed' | 'dismissed'; + +export type TourGate = 'wait' | 'go' | 'never'; + +/** What the guide's phase means for a tour that wants to start on its own. */ +export function tourGateOf(phase: FirstRunGuidePhase): TourGate { + switch (phase) { + case 'absent': + case 'closed': + return 'go'; + case 'dismissed': + return 'never'; + default: + return 'wait'; + } +} + +/** The next phase: once the guide has closed or been dismissed, the first run is decided and stays so. */ +export function nextGuidePhase(current: FirstRunGuidePhase, reported: Exclude): FirstRunGuidePhase { + if (current === 'dismissed' || current === 'closed') { + return current; + } + if (current === 'absent' && reported === 'open') { + // A guide opened later from the palette is not the first run's. + return current; + } + return reported; +} + +export interface FirstRunGate { + readonly phase: FirstRunGuidePhase; + /** The agent workbench reports the guide's state. */ + guide(phase: Exclude): void; + /** Runs `start` once the guide lets the tour start (now, if it already does); never after a dismissal. */ + whenTourMayStart(start: () => void): void; +} + +export interface FirstRunGateOptions { + /** The guide was dismissed with "Don't show again" (main.ts marks the tour as skipped). */ + onDismissed?(): void; +} + +export function createFirstRunGate(options: FirstRunGateOptions = {}): FirstRunGate { + let phase: FirstRunGuidePhase = 'pending'; + let waiting: (() => void)[] = []; + const settle = (): void => { + const gate = tourGateOf(phase); + if (gate === 'wait') { + return; + } + const run = waiting; + waiting = []; + if (gate === 'go') { + for (const start of run) { + start(); + } + } + }; + return { + get phase() { + return phase; + }, + guide(reported) { + const before = phase; + phase = nextGuidePhase(phase, reported); + if (phase === 'dismissed' && before !== 'dismissed') { + options.onDismissed?.(); + } + settle(); + }, + whenTourMayStart(start) { + const gate = tourGateOf(phase); + if (gate === 'go') { + start(); + } else if (gate === 'wait') { + waiting.push(start); + } + }, + }; +} diff --git a/apps/ide/src/shared/defaultKeybindings.ts b/apps/ide/src/shared/defaultKeybindings.ts index 4198a417..ae39c600 100644 --- a/apps/ide/src/shared/defaultKeybindings.ts +++ b/apps/ide/src/shared/defaultKeybindings.ts @@ -182,6 +182,8 @@ const DEFAULTS: Readonly> = { 'layout.toggleAgentMode': { keys: ['CmdOrCtrl+Alt+M'] }, // #508: a chord, free on every OS and in Monaco (VS Code leaves Ctrl/Cmd+K Ctrl/Cmd+N unbound too). 'chat.nextNeedingAttention': { keys: ['CmdOrCtrl+K CmdOrCtrl+N'] }, + // #532: VS Code's Toggle Secondary Side Bar key (the live analysis column is the agent layout's right-hand bar); free on every OS and in Monaco. + 'layout.toggleLiveAnalysis': { keys: ['CmdOrCtrl+Alt+B'] }, ...Object.fromEntries(EDITOR_ACTIONS.map((action) => [action.id, { keys: action.keys, ...(action.mac ? { mac: action.mac } : {}), diff --git a/apps/ide/src/shared/i18n/messages.en.ts b/apps/ide/src/shared/i18n/messages.en.ts index d255a873..326ec904 100644 --- a/apps/ide/src/shared/i18n/messages.en.ts +++ b/apps/ide/src/shared/i18n/messages.en.ts @@ -194,6 +194,10 @@ export const en = { 'dock.live.waiting': 'Waiting', 'dock.live.analysing': 'Analysing', 'dock.live.noFolder': 'No folder', + 'dock.hide': 'Hide the live analysis column', + 'dock.reopen': 'Live analysis', + 'dock.reopenTitle': 'Show the live analysis column', + 'dock.reopenTitleKey': 'Show the live analysis column ({key})', 'action.refresh': 'Refresh', 'action.retry': 'Retry', 'action.showOutput': 'Show Output', @@ -296,6 +300,8 @@ export const en = { 'guide.lead': 'Three steps to your first chat with a coding agent on your project.', 'guide.skip': 'Skip', 'guide.skipTitle': 'Close the guide; reopen it with Chat: Show Getting Started', + 'guide.dontShow': "Don't show again", + 'guide.dontShowTitle': 'Close the guide and skip the guided tour; both stay in the command palette', 'guide.mark.done': 'Done', 'guide.mark.next': 'Next', 'guide.mark.then': 'Then', diff --git a/apps/ide/src/shared/i18n/messages.es.ts b/apps/ide/src/shared/i18n/messages.es.ts index fd636122..0163ea13 100644 --- a/apps/ide/src/shared/i18n/messages.es.ts +++ b/apps/ide/src/shared/i18n/messages.es.ts @@ -197,6 +197,10 @@ export const es: Readonly> = { 'dock.live.waiting': 'En espera', 'dock.live.analysing': 'Analizando', 'dock.live.noFolder': 'Sin carpeta', + 'dock.hide': 'Ocultar la columna de análisis en vivo', + 'dock.reopen': 'Análisis en vivo', + 'dock.reopenTitle': 'Mostrar la columna de análisis en vivo', + 'dock.reopenTitleKey': 'Mostrar la columna de análisis en vivo ({key})', 'action.refresh': 'Actualizar', 'action.retry': 'Reintentar', 'action.showOutput': 'Mostrar salida', @@ -299,6 +303,8 @@ export const es: Readonly> = { 'guide.lead': 'Tres pasos hasta tu primer chat con un agente de programación sobre tu proyecto.', 'guide.skip': 'Omitir', 'guide.skipTitle': 'Cerrar la guía; vuelve a abrirla con Chat: Mostrar introducción', + 'guide.dontShow': 'No volver a mostrar', + 'guide.dontShowTitle': 'Cerrar la guía y omitir la visita guiada; ambas siguen en la paleta de comandos', 'guide.mark.done': 'Hecho', 'guide.mark.next': 'Siguiente', 'guide.mark.then': 'Después', diff --git a/apps/ide/test/keybindingDefaults.test.ts b/apps/ide/test/keybindingDefaults.test.ts index 15618233..8809c78b 100644 --- a/apps/ide/test/keybindingDefaults.test.ts +++ b/apps/ide/test/keybindingDefaults.test.ts @@ -24,7 +24,7 @@ const REGISTERED_ELSEWHERE = new Set([ 'workbench.view.debug', 'workbench.action.debug.start', 'workbench.action.debug.pause', 'workbench.action.debug.stepOver', 'workbench.action.debug.stepInto', 'workbench.action.debug.stepOut', 'workbench.action.debug.stop', 'workbench.action.debug.restart', 'editor.debug.action.toggleBreakpoint', 'workbench.debug.action.toggleRepl', 'extensions.showView', 'agents.newChat', 'chat.new', - 'layout.toggleAgentMode', 'chat.nextNeedingAttention', + 'layout.toggleAgentMode', 'chat.nextNeedingAttention', 'layout.toggleLiveAnalysis', ]); function registry(platform = 'linux'): ReturnType { diff --git a/apps/ide/test/liveAnalysisFirstRun.test.ts b/apps/ide/test/liveAnalysisFirstRun.test.ts new file mode 100644 index 00000000..6619c7b2 --- /dev/null +++ b/apps/ide/test/liveAnalysisFirstRun.test.ts @@ -0,0 +1,103 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { dockReopenTitle, formatDockHidden, parseDockHidden } from '../src/renderer/agentFirst/agentWorkbenchModel.ts'; +import { createFirstRunGate, nextGuidePhase, tourGateOf } from '../src/renderer/tour/firstRunGate.ts'; +import { DEFAULT_KEYBINDING_IDS, defaultKeybindings } from '../src/shared/defaultKeybindings.ts'; +import { canonicalKeybinding } from '../src/shared/keybindings.ts'; + +describe('the live analysis column (#532)', () => { + it('is shown unless it was hidden on purpose, and round-trips', () => { + assert.equal(parseDockHidden(null), false); + assert.equal(parseDockHidden(undefined), false); + assert.equal(parseDockHidden('nonsense'), false); + assert.equal(parseDockHidden('false'), false); + assert.equal(parseDockHidden('true'), true); + for (const hidden of [true, false]) { + assert.equal(parseDockHidden(formatDockHidden(hidden)), hidden); + } + }); + + it('names the reopen tab, with its key when it has one', () => { + assert.equal(dockReopenTitle(''), 'Show the live analysis column'); + assert.equal(dockReopenTitle('Ctrl+Alt+B'), 'Show the live analysis column (Ctrl+Alt+B)'); + }); + + it('toggles with Ctrl/Cmd+Alt+B on every OS, a key no other built-in command has', () => { + for (const platform of ['linux', 'win32', 'darwin']) { + const [primary] = defaultKeybindings('layout.toggleLiveAnalysis', platform); + assert.equal(primary, 'CmdOrCtrl+Alt+B'); + const mine = canonicalKeybinding(primary ?? '', platform); + for (const id of DEFAULT_KEYBINDING_IDS.filter((other) => other !== 'layout.toggleLiveAnalysis')) { + for (const binding of defaultKeybindings(id, platform)) { + assert.notEqual(canonicalKeybinding(binding, platform), mine, `${platform}: ${id} has it too`); + assert.notEqual(canonicalKeybinding(binding, platform)?.split(' ')[0], mine, `${platform}: ${id} starts a chord with it`); + } + } + } + }); +}); + +describe('the first run in order (#532)', () => { + it('lets the tour start once the guide is absent or closed, never after a dismissal', () => { + assert.equal(tourGateOf('pending'), 'wait'); + assert.equal(tourGateOf('open'), 'wait'); + assert.equal(tourGateOf('absent'), 'go'); + assert.equal(tourGateOf('closed'), 'go'); + assert.equal(tourGateOf('dismissed'), 'never'); + }); + + it('keeps a decided first run decided', () => { + assert.equal(nextGuidePhase('pending', 'open'), 'open'); + assert.equal(nextGuidePhase('open', 'closed'), 'closed'); + assert.equal(nextGuidePhase('open', 'dismissed'), 'dismissed'); + assert.equal(nextGuidePhase('closed', 'open'), 'closed'); + assert.equal(nextGuidePhase('closed', 'dismissed'), 'closed'); + assert.equal(nextGuidePhase('dismissed', 'closed'), 'dismissed'); + // A guide opened later from the palette does not hold the tour back. + assert.equal(nextGuidePhase('absent', 'open'), 'absent'); + }); + + it('holds the tour until the guide closes', () => { + const gate = createFirstRunGate(); + let started = 0; + gate.whenTourMayStart(() => started++); + assert.equal(started, 0, 'nothing is known about the guide yet'); + gate.guide('open'); + assert.equal(started, 0); + gate.guide('closed'); + assert.equal(started, 1); + gate.guide('closed'); + assert.equal(started, 1, 'it starts once'); + gate.whenTourMayStart(() => started++); + assert.equal(started, 2, 'a late request runs at once'); + }); + + it('starts the tour at once when the guide does not open', () => { + const gate = createFirstRunGate(); + gate.guide('absent'); + let started = false; + gate.whenTourMayStart(() => { + started = true; + }); + assert.equal(started, true); + }); + + it('drops the tour and reports once when the guide is dismissed', () => { + let dismissed = 0; + const gate = createFirstRunGate({ onDismissed: () => dismissed++ }); + let started = false; + gate.whenTourMayStart(() => { + started = true; + }); + gate.guide('open'); + gate.guide('dismissed'); + gate.guide('closed'); + gate.guide('dismissed'); + gate.whenTourMayStart(() => { + started = true; + }); + assert.equal(started, false); + assert.equal(dismissed, 1); + assert.equal(gate.phase, 'dismissed'); + }); +}); diff --git a/docs/ide/keybindings.md b/docs/ide/keybindings.md index 8b286d1c..6aa6c304 100644 --- a/docs/ide/keybindings.md +++ b/docs/ide/keybindings.md @@ -188,6 +188,7 @@ command the registry knows runs from a key. | Agents: New Chat (`agents.newChat`) | VS Code's chat: W/L `Ctrl+Alt+I`; mac `Ctrl+Cmd+I` | `Ctrl+Alt+I` / `Option+Cmd+I` | W/L same; mac **`Ctrl+Cmd+I`** | | Chat: New Chat (`chat.new`, agent layout) | none | `Ctrl+Shift+L` / `Shift+Cmd+L` | same, but while an editor has the focus the key stays Monaco's Select All Occurrences (VS Code's) | | Toggle Agent / Classic Layout (`layout.toggleAgentMode`) | n/a | `Ctrl+Alt+M` / `Option+Cmd+M` | same | +| Toggle Live Analysis Column (`layout.toggleLiveAnalysis`, agent layout) | Toggle Secondary Side Bar: `Ctrl+Alt+B` / `Option+Cmd+B` | none | **`Ctrl+Alt+B` / `Option+Cmd+B`** (#532) | ## VS Code keys the IDE does not have (no command yet) From e732ba0958dbaf63000badd1562746e645fcc3a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 22:18:32 +0000 Subject: [PATCH 42/74] feat(ide): tab-list keys, Focus Latest notification, accessibility support setting and smoke a11y audit (#535) - Settings scope tabs: roving tabindex; Settings, terminal and panel tab lists answer Left/Right/Home/End through a shared pure tablistKeyModel. - Notifications: Focus Latest (Ctrl/Cmd+K Ctrl/Cmd+Shift+N) focuses the newest toast, named by its message; Escape gives the focus back. - editor.accessibilitySupport (auto/on/off) drives Monaco's accessibilitySupport and xterm's screenReaderMode (on only with 'on'). - Smoke run: an accessibility probe on the default workbench, judged by the pure shared/a11yAudit.ts (unnamed interactive elements, duplicate ids, tab lists and trees with more than one tabindex=0). - Chat attachment popups get unique ids (several chats can be open). --- apps/ide/src/main/smoke.ts | 69 +++++++- .../src/renderer/agents/chatAttachments.ts | 12 +- .../renderer/commands/workbenchCommands.ts | 3 + apps/ide/src/renderer/editor/editorGroup.ts | 4 +- apps/ide/src/renderer/main.ts | 4 +- apps/ide/src/renderer/notifications.ts | 62 ++++++- apps/ide/src/renderer/panel/panelHost.ts | 6 +- .../ide/src/renderer/settings/settingsView.ts | 29 +++- apps/ide/src/renderer/tablistKeyModel.ts | 57 +++++++ .../src/renderer/terminal/terminalPanel.ts | 41 ++++- apps/ide/src/renderer/terminal/xtermView.ts | 10 ++ apps/ide/src/shared/a11yAudit.ts | 120 ++++++++++++++ apps/ide/src/shared/defaultKeybindings.ts | 2 + apps/ide/src/shared/i18n/messages.en.ts | 3 + apps/ide/src/shared/i18n/messages.es.ts | 3 + apps/ide/src/shared/i18n/settings.es.ts | 5 + apps/ide/src/shared/settings.ts | 16 ++ apps/ide/test/keyboardA11y.test.ts | 155 ++++++++++++++++++ docs/ide/keybindings.md | 1 + 19 files changed, 584 insertions(+), 18 deletions(-) create mode 100644 apps/ide/src/renderer/tablistKeyModel.ts create mode 100644 apps/ide/src/shared/a11yAudit.ts create mode 100644 apps/ide/test/keyboardA11y.test.ts diff --git a/apps/ide/src/main/smoke.ts b/apps/ide/src/main/smoke.ts index 44707de6..e17cf281 100644 --- a/apps/ide/src/main/smoke.ts +++ b/apps/ide/src/main/smoke.ts @@ -1,6 +1,7 @@ import type { BrowserWindow } from './host/desktop.ts'; import { APP_ORIGIN, originOf } from './security.ts'; import { IPC_EVENTS } from '../shared/api.ts'; +import { auditA11y, INTERACTIVE_SELECTOR, type A11ySnapshot } from '../shared/a11yAudit.ts'; /** * `--codexr-smoke`: start the IDE hidden, probe the security baseline from @@ -489,6 +490,53 @@ const RENDERER_PROBE = `(async () => { }; })()`; +// #535 (O32): what the default workbench shows a screen reader, once start-up is over. Plain data +// only (shared/a11yAudit.ts judges it, unit-tested). Monaco's and xterm.js's own DOM is left out: +// the IDE does not draw it. Only rendered elements count (display:none, hidden and aria-hidden +// subtrees are out of the accessibility tree); ids count wherever they are. +export const A11Y_PROBE = `(async () => { + const wait = async (test, ms) => { + const until = Date.now() + ms; + while (!test() && Date.now() < until) { await new Promise((r) => setTimeout(r, 50)); } + }; + await wait(() => document.querySelector('[data-testid="welcome"][data-ready="true"]'), 10000); + await wait(() => document.querySelector('[data-testid="explorer-tree"] [role="treeitem"]'), 10000); + // Let the idle work of the start (views drawn late, the status bar) settle. + await new Promise((r) => setTimeout(r, 1000)); + const THIRD_PARTY = '.monaco-editor, .monaco-diff-editor, .monaco-aria-container, .xterm, [class^="monaco-"], [class*=" monaco-"]'; + const foreign = (node) => !!node.closest(THIRD_PARTY); + const rendered = (node) => node.getClientRects().length > 0 && !node.closest('[aria-hidden="true"]') && getComputedStyle(node).visibility !== 'hidden'; + const text = (node) => { + const alts = [...node.querySelectorAll('img[alt]')].map((img) => img.getAttribute('alt')).join(' '); + return ((node.textContent || '') + ' ' + alts).trim().slice(0, 80); + }; + const where = (node) => node.getAttribute('data-testid') || (node.id ? '#' + node.id : '') || (typeof node.className === 'string' ? node.className.trim().split(/\\s+/).slice(0, 2).map((name) => '.' + name).join('') : '') || ''; + const elements = [...document.querySelectorAll(${JSON.stringify(INTERACTIVE_SELECTOR)})] + .filter((node) => !foreign(node) && rendered(node)) + .map((node) => ({ + tag: node.tagName.toLowerCase(), + role: node.getAttribute('role'), + type: node.tagName === 'INPUT' ? (node.getAttribute('type') || 'text').toLowerCase() : null, + ariaLabel: node.getAttribute('aria-label'), + labelledByText: (node.getAttribute('aria-labelledby') || '').split(/\\s+/).filter(Boolean).map((id) => document.getElementById(id)?.textContent || '').join(' ').trim(), + text: text(node), + title: node.getAttribute('title'), + labelText: node.labels ? [...node.labels].map((label) => label.textContent || '').join(' ').trim() : '', + value: node.tagName === 'INPUT' ? node.value : null, + where: where(node), + })); + const ids = [...document.querySelectorAll('[id]')].filter((node) => !foreign(node)).map((node) => node.id); + const groups = [...document.querySelectorAll('[role="tablist"], [role="tree"]')] + .filter((node) => !foreign(node) && rendered(node)) + .map((node) => { + const role = node.getAttribute('role'); + const items = [...node.querySelectorAll(role === 'tablist' ? '[role="tab"]' : '[role="treeitem"]')] + .filter((item) => rendered(item) && !item.disabled && item.getAttribute('aria-disabled') !== 'true'); + return { role, where: node.getAttribute('aria-label') || where(node), itemTabIndexes: items.map((item) => item.tabIndex) }; + }); + return { elements, ids, groups }; +})()`; + // Runs after the main process sent the `terminal.toggle` command. Typing goes // through xterm's own input handler (an 'input' event on its textarea, as an // IME or a paste would), so the bytes take the real path: xterm -> bridge -> @@ -575,8 +623,17 @@ const TERMINAL_PROBE = `(async () => { })()`; /** Pure: turns what was observed into a verdict. */ -export function evaluateSmoke(probe: SmokeProbe | null, navigationBlocked: boolean, platform: string, terminal: TerminalProbe | null = null): SmokeResult { +/** + * `a11y`: what the accessibility audit (#535) found on the default workbench, + * one message per problem; null when its probe did not run. + */ +export function evaluateSmoke(probe: SmokeProbe | null, navigationBlocked: boolean, platform: string, terminal: TerminalProbe | null = null, a11y: readonly string[] | null = []): SmokeResult { const failures: string[] = []; + if (a11y === null) { + failures.push('accessibility probe did not run'); + } else { + failures.push(...a11y.map((problem) => `accessibility: ${problem}`)); + } if (!probe) { failures.push('renderer probe did not run'); } else { @@ -641,6 +698,14 @@ export function evaluateSmoke(probe: SmokeProbe | null, navigationBlocked: boole export async function runSmoke(win: BrowserWindow, expectedOrigins: ReadonlySet): Promise { const contents = win.webContents; + // #535 (O32): the accessibility audit first, on the workbench as start-up left it. + let a11y: string[] | null = null; + try { + a11y = auditA11y((await contents.executeJavaScript(A11Y_PROBE)) as A11ySnapshot); + } catch (error) { + process.stderr.write(`[smoke] accessibility probe threw: ${String(error)}\n`); + a11y = null; + } let probe: SmokeProbe | null = null; try { probe = (await contents.executeJavaScript(RENDERER_PROBE)) as SmokeProbe; @@ -665,5 +730,5 @@ export async function runSmoke(win: BrowserWindow, expectedOrigins: ReadonlySet< const origin = originOf(contents.getURL()); const navigationBlocked = origin !== null && (expectedOrigins.has(origin) || origin === APP_ORIGIN); - return evaluateSmoke(probe, navigationBlocked, process.platform, terminal); + return evaluateSmoke(probe, navigationBlocked, process.platform, terminal, a11y); } diff --git a/apps/ide/src/renderer/agents/chatAttachments.ts b/apps/ide/src/renderer/agents/chatAttachments.ts index eb3df136..3db72399 100644 --- a/apps/ide/src/renderer/agents/chatAttachments.ts +++ b/apps/ide/src/renderer/agents/chatAttachments.ts @@ -72,7 +72,11 @@ function suggestionText(value: string): string { return value; } +/** #535: each bar's popup has ids of its own (several chats can be open at once). */ +let attachmentBars = 0; + export function createAttachmentBar(input: HTMLTextAreaElement, sources: AttachmentSources): AttachmentBar { + const popupId = `chat-mention-${++attachmentBars}`; let items: ChatAttachment[] = []; let files: readonly string[] | null = null; let suggestions: string[] = []; @@ -80,8 +84,8 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm let warned = false; const chips = el('div', { className: 'chat-chips', attrs: { 'aria-label': 'Attached', 'data-testid': 'agents-chips' } }); - const popup = el('ul', { className: 'chat-mention', attrs: { role: 'listbox', id: 'chat-mention', hidden: '', 'aria-label': 'Attach a file' } }); - input.setAttribute('aria-controls', 'chat-mention'); + const popup = el('ul', { className: 'chat-mention', attrs: { role: 'listbox', id: popupId, hidden: '', 'aria-label': 'Attach a file' } }); + input.setAttribute('aria-controls', popupId); input.setAttribute('aria-autocomplete', 'list'); const renderChips = (): void => { @@ -125,7 +129,7 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm }; const renderPopup = (): void => { popup.replaceChildren(...suggestions.map((value, index) => { - const row = el('li', { className: 'chat-mention-row', text: suggestionText(value), attrs: { role: 'option', id: `chat-mention-${index}`, 'aria-selected': String(index === selected) } }); + const row = el('li', { className: 'chat-mention-row', text: suggestionText(value), attrs: { role: 'option', id: `${popupId}-${index}`, 'aria-selected': String(index === selected) } }); row.addEventListener('mousedown', (event) => { event.preventDefault(); pick(index); @@ -134,7 +138,7 @@ export function createAttachmentBar(input: HTMLTextAreaElement, sources: Attachm })); popup.hidden = suggestions.length === 0; if (!popup.hidden) { - input.setAttribute('aria-activedescendant', `chat-mention-${selected}`); + input.setAttribute('aria-activedescendant', `${popupId}-${selected}`); } }; const update = async (): Promise => { diff --git a/apps/ide/src/renderer/commands/workbenchCommands.ts b/apps/ide/src/renderer/commands/workbenchCommands.ts index 8e8b7af2..bbd56a48 100644 --- a/apps/ide/src/renderer/commands/workbenchCommands.ts +++ b/apps/ide/src/renderer/commands/workbenchCommands.ts @@ -65,6 +65,8 @@ export interface WorkbenchCommandTargets { hasPanel(): boolean; toggleZenMode(): void; resetLayout(): void; + /** #535 (O32): the keyboard focus to the newest notification. */ + focusLatestNotification(): void; closeEditors(kind: CloseKind): void; cycleEditor(delta: number): void; keepEditor(): void; @@ -179,6 +181,7 @@ export function workbenchCommands(targets: WorkbenchCommandTargets): CommandDefi { id: 'view.toggleMaximizedPanel', category: t('category.view'), title: t('command.view.toggleMaximizedPanel'), enabled: targets.hasPanel, run: targets.toggleMaximizedPanel }, { id: 'view.toggleZenMode', category: t('category.view'), title: t('command.view.toggleZenMode'), run: targets.toggleZenMode }, { id: 'view.resetLayout', category: t('category.view'), title: t('command.view.resetLayout'), run: targets.resetLayout }, + { id: 'notifications.focusLatest', category: t('category.notifications'), title: t('command.notifications.focusLatest'), run: targets.focusLatestNotification }, { id: 'workbench.openSettings', category: t('category.preferences'), title: t('command.workbench.openSettings'), run: targets.openSettings }, { id: 'workbench.selectTheme', category: t('category.preferences'), title: t('command.workbench.selectTheme'), run: targets.selectColorTheme }, { id: 'workbench.openKeybindings', category: t('category.preferences'), title: t('command.workbench.openKeybindings'), run: targets.openKeybindings }, diff --git a/apps/ide/src/renderer/editor/editorGroup.ts b/apps/ide/src/renderer/editor/editorGroup.ts index 7c32dca7..cee08155 100644 --- a/apps/ide/src/renderer/editor/editorGroup.ts +++ b/apps/ide/src/renderer/editor/editorGroup.ts @@ -3,7 +3,7 @@ import { el, fileIcon, icon } from '../dom.ts'; import { followSystemTheme, monaco } from './monaco.ts'; import { startupMarkFrame, startupMarkOnce } from '../startup/startupMarks.ts'; import { languageName, type EditorStatusState, type EndOfLine, type Indentation, type LanguageInfo } from './editorStatusModel.ts'; -import { settingOf, type SettingValues } from '../../shared/settings.ts'; +import { ACCESSIBILITY_SUPPORT_SETTING, accessibilityModes, settingOf, type SettingValues } from '../../shared/settings.ts'; import type { FileFunctionMetrics, FunctionDelta, FunctionMetric, MetricThresholds, Problem, ProblemSeverity } from '../../shared/problems.ts'; import type { HotspotIntent } from '../agentFirst/askAgent.ts'; import { installMetricLens } from './metricLens.ts'; @@ -1896,6 +1896,8 @@ export function createEditorGroup( bracketPairColorization: { enabled: settingOf(snapshot, 'editor.bracketPairColorization.enabled') }, cursorBlinking: settingOf<'blink' | 'smooth' | 'phase' | 'expand' | 'solid'>(snapshot, 'editor.cursorBlinking'), smoothScrolling: settingOf(snapshot, 'editor.smoothScrolling'), + // #535 (O32): editor.accessibilitySupport. + accessibilitySupport: accessibilityModes(settingOf(snapshot, ACCESSIBILITY_SUPPORT_SETTING)).monaco, } as monaco.editor.IEditorOptions; editorOptions = { ...editorOptions, ...options }; for (const group of groups) { diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 26d5d7b0..82c1c063 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -68,7 +68,7 @@ import { createSettingsView } from './settings/settingsView.ts'; import { createKeybindingsView } from './settings/keybindingsView.ts'; import { KEYBINDINGS_JSON_TAB_ID, menuAccelerators } from './settings/keybindingsModel.ts'; import { - AUTO_SAVE_SETTING, COLOR_THEME_SETTING, isColorTheme, isToggleOn, MINIMAP_SETTING, settingOf, SYSTEM_NOTIFICATIONS_SETTING, toggledSetting, WORD_WRAP_SETTING, + ACCESSIBILITY_SUPPORT_SETTING, accessibilityModes, AUTO_SAVE_SETTING, COLOR_THEME_SETTING, isColorTheme, isToggleOn, MINIMAP_SETTING, settingOf, SYSTEM_NOTIFICATIONS_SETTING, toggledSetting, WORD_WRAP_SETTING, type ColorTheme, type ToggleSetting, } from '../shared/settings.ts'; import { themeChoices } from './settings/settingsModel.ts'; @@ -739,6 +739,7 @@ function applySettings(report: SettingsReport): void { showAutoSave(report); offerLanguageReload(report); terminal.setFontSize(settingOf(report, 'terminal.integrated.fontSize')); + terminal.setScreenReaderMode(accessibilityModes(settingOf(report, ACCESSIBILITY_SUPPORT_SETTING)).terminalScreenReader); metricThresholds = { complexity: settingOf(report, 'problems.metrics.maxComplexity'), lines: settingOf(report, 'problems.metrics.maxFunctionLines'), @@ -1226,6 +1227,7 @@ registerWorkbenchCommands(registry, { hasPanel: () => panelHost.visible, toggleZenMode: () => workbench.layout.toggleZen(), resetLayout: () => workbench.layout.reset(), + focusLatestNotification: () => { notifications.focusLatest(); }, openSettings: () => { workbench.showView('settings'); settingsView.focus(); diff --git a/apps/ide/src/renderer/notifications.ts b/apps/ide/src/renderer/notifications.ts index f6e4ca0f..b0e52c15 100644 --- a/apps/ide/src/renderer/notifications.ts +++ b/apps/ide/src/renderer/notifications.ts @@ -56,6 +56,12 @@ export interface NotificationCenter { * be hidden. */ setRightInset(px: number): void; + /** + * #535 (O32): moves the keyboard focus to the newest notification on screen + * (Notifications: Focus Latest); Escape there gives the focus back. False, + * with "No notifications" announced, when there is none. + */ + focusLatest(): boolean; /** How many notifications are on screen (tests, smoke). */ readonly count: number; } @@ -88,6 +94,32 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter }); stack.append(more); + let toastIds = 0; + /** #535: where the focus was before Focus Latest, given back on Escape. */ + let focusBefore: HTMLElement | null = null; + stack.addEventListener('keydown', (event) => { + if (event.key !== 'Escape' || !focusBefore) { + return; + } + const back = focusBefore; + focusBefore = null; + if (back.isConnected) { + event.preventDefault(); + event.stopPropagation(); + back.focus(); + } + }); + stack.addEventListener('focusout', (event) => { + if (!(event.relatedTarget instanceof Node && stack.contains(event.relatedTarget))) { + // The focus left the stack another way (a click, Tab, the toast closed): nothing to give back later. + queueMicrotask(() => { + if (!stack.contains(document.activeElement)) { + focusBefore = null; + } + }); + } + }); + const toasts = (): HTMLElement[] => [...stack.children].filter((child): child is HTMLElement => child !== more && child instanceof HTMLElement); function relayout(): void { @@ -115,18 +147,32 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter /** Removes a toast and lets the folded ones move up. */ function drop(root: HTMLElement): void { + const hadFocus = root.contains(document.activeElement); root.remove(); + if (hadFocus && focusBefore?.isConnected) { + // #535: the toast the keyboard was on closed: back to where Focus Latest came from. + focusBefore.focus(); + } + if (hadFocus) { + focusBefore = null; + } relayout(); } function shell(kind: NotificationSeverity | 'progress', body: Node[], onClose: () => void, pinned = false): HTMLElement { const close = el('button', { className: 'notification-close', attrs: { type: 'button', title: t('contextMenu.close'), 'aria-label': t('notification.close') } }, [closeIcon()]); close.addEventListener('click', onClose); - const root = el('div', { className: `notification is-${kind}`, attrs: { role: kind === 'error' ? 'alert' : 'group', 'data-testid': 'notification' } }, [ + // #535: focusable from the code (Focus Latest), named by its message, so a screen reader reads it on arrival. + const root = el('div', { className: `notification is-${kind}`, attrs: { role: kind === 'error' ? 'alert' : 'group', tabindex: '-1', 'data-testid': 'notification' } }, [ el('span', { className: 'notification-icon', attrs: { 'aria-hidden': 'true' } }), el('div', { className: 'notification-body' }, body), close, ]); + const message = body.find((node): node is HTMLElement => node instanceof HTMLElement && node.classList.contains('notification-message')); + if (message) { + message.id = `notification-message-${++toastIds}`; + root.setAttribute('aria-labelledby', message.id); + } root.dataset['pinned'] = String(pinned); stack.append(root); trim(); @@ -239,6 +285,20 @@ export function createNotificationCenter(host: HTMLElement): NotificationCenter stack.style.right = `${Math.max(0, Math.round(px)) + 12}px`; }, + focusLatest(): boolean { + const latest = toasts().filter((toast) => !toast.hidden).at(-1); + if (!latest) { + announce(t('notification.none')); + return false; + } + const current = document.activeElement; + if (current instanceof HTMLElement && !stack.contains(current) && current !== document.body) { + focusBefore = current; + } + latest.focus(); + return true; + }, + get count(): number { return toasts().length; }, diff --git a/apps/ide/src/renderer/panel/panelHost.ts b/apps/ide/src/renderer/panel/panelHost.ts index 20b56fe1..e3c72d35 100644 --- a/apps/ide/src/renderer/panel/panelHost.ts +++ b/apps/ide/src/renderer/panel/panelHost.ts @@ -1,4 +1,5 @@ import { el, icon } from '../dom.ts'; +import { tablistKeyTarget } from '../tablistKeyModel.ts'; /** * The bottom panel (#174): one frame under the editors holding several views @@ -116,8 +117,9 @@ export function createPanelHost(panel: HTMLElement, hooks: { toggleMaximized?(): tabList.addEventListener('keydown', (event) => { const ids = [...views.keys()]; const index = active === null ? -1 : ids.indexOf(active); - const next = event.key === 'ArrowRight' ? ids[(index + 1) % ids.length] - : event.key === 'ArrowLeft' ? ids[(index - 1 + ids.length) % ids.length] : undefined; + // #535 (O32): Home/End too, from the shared tab-list model. + const target = event.altKey || event.ctrlKey || event.metaKey ? null : tablistKeyTarget(event.key, ids.length, index); + const next = target === null ? undefined : ids[target]; if (next !== undefined) { event.preventDefault(); show(next); diff --git a/apps/ide/src/renderer/settings/settingsView.ts b/apps/ide/src/renderer/settings/settingsView.ts index 6a1990e9..e2294799 100644 --- a/apps/ide/src/renderer/settings/settingsView.ts +++ b/apps/ide/src/renderer/settings/settingsView.ts @@ -3,6 +3,7 @@ import { resolveSettings, type SettingDefinition, type SettingScope, type Settin import { el, icon } from '../dom.ts'; import { t } from '../../shared/i18n/i18n.ts'; import { parseControlValue, settingRows, type SettingRow } from './settingsModel.ts'; +import { tablistKeyTarget, tablistTabStop } from '../tablistKeyModel.ts'; /** * The Settings view (#18, part 2), a side-bar pane like VS Code's settings @@ -46,7 +47,7 @@ export function createSettingsView(container: HTMLElement, api: CodeXRApi['setti attrs: { type: 'search', placeholder: t('settings.search'), 'aria-label': t('settings.search'), 'data-testid': 'settings-filter', spellcheck: 'false' }, }); const scopeButton = (id: SettingScope, label: string): HTMLButtonElement => { - const button = el('button', { className: 'settings-scope', text: label, attrs: { type: 'button', role: 'tab', 'data-scope': id, 'data-testid': `settings-scope-${id}` } }); + const button = el('button', { className: 'settings-scope', text: label, attrs: { type: 'button', role: 'tab', tabindex: '-1', 'data-scope': id, 'data-testid': `settings-scope-${id}` } }); button.addEventListener('click', () => { scope = id; render(); @@ -55,6 +56,24 @@ export function createSettingsView(container: HTMLElement, api: CodeXRApi['setti }; const userTab = scopeButton('user', t('settings.scope.user')); const folderTab = scopeButton('folder', t('settings.scope.folder')); + const scopeTabs = [userTab, folderTab]; + const scopeList = el('div', { className: 'settings-scopes', attrs: { role: 'tablist', 'aria-label': t('settings.scope') } }, scopeTabs); + // #535 (O32): one Tab stop in the scope tabs (roving tabindex); Left/Right/Home/End select and focus. + scopeList.addEventListener('keydown', (event) => { + const index = scopeTabs.findIndex((tab) => tab === event.target); + if (index < 0 || event.altKey || event.ctrlKey || event.metaKey) { + return; + } + const target = tablistKeyTarget(event.key, scopeTabs.length, index, scopeTabs.map((tab) => tab.disabled)); + const tab = target === null ? undefined : scopeTabs[target]; + if (!tab) { + return; + } + event.preventDefault(); + scope = tab.dataset['scope'] === 'folder' ? 'folder' : 'user'; + render(); + tab.focus(); + }); const openFile = el('button', { className: 'link-button settings-open-file', text: t('settings.editFolderFile'), attrs: { type: 'button', 'data-testid': 'settings-open-file' } }); openFile.addEventListener('click', () => hooks.openFolderFile()); const keybindings = el('button', { className: 'link-button', text: t('view.keyboardShortcuts'), attrs: { type: 'button', 'data-testid': 'settings-open-keybindings' } }); @@ -67,7 +86,7 @@ export function createSettingsView(container: HTMLElement, api: CodeXRApi['setti el('h2', { className: 'side-bar-title', text: t('view.settings') }), el('div', { className: 'settings-head' }, [ search, - el('div', { className: 'settings-scopes', attrs: { role: 'tablist', 'aria-label': t('settings.scope') } }, [userTab, folderTab]), + scopeList, scopeNote, openFile, keybindings, @@ -178,11 +197,13 @@ export function createSettingsView(container: HTMLElement, api: CodeXRApi['setti } folderTab.disabled = !hasFolder; folderTab.title = hasFolder ? t('settings.scope.folderTitle') : t('settings.scope.folderNone'); - for (const tab of [userTab, folderTab]) { + const stop = tablistTabStop(scopeTabs.length, scopeTabs.findIndex((tab) => tab.dataset['scope'] === scope), scopeTabs.map((tab) => tab.disabled)); + scopeTabs.forEach((tab, index) => { const selected = tab.dataset['scope'] === scope; tab.setAttribute('aria-selected', String(selected)); + tab.tabIndex = index === stop ? 0 : -1; tab.classList.toggle('is-active', selected); - } + }); scopeNote.textContent = scope === 'user' ? t('settings.scope.userNote') : t('settings.scope.folderNote'); diff --git a/apps/ide/src/renderer/tablistKeyModel.ts b/apps/ide/src/renderer/tablistKeyModel.ts new file mode 100644 index 00000000..37cd23d2 --- /dev/null +++ b/apps/ide/src/renderer/tablistKeyModel.ts @@ -0,0 +1,57 @@ +/** + * #535 (O32): what a key does in a horizontal tab list (the WAI-ARIA tabs + * pattern), shared by the Settings scope tabs, the terminal tabs and the panel + * views. Kept free of the DOM so it is unit-tested, like `treeKeyModel.ts`. + * + * Right/Left move to the next/previous tab and wrap around, Home/End go to the + * first/last. A disabled tab is skipped (it cannot be focused). Any other key, + * or a move that lands where it started: null (the view handles it). + */ + +export function tablistKeyTarget(key: string, count: number, index: number, disabled: readonly boolean[] = []): number | null { + const enabled = (candidate: number): boolean => disabled[candidate] !== true; + const usable = Array.from({ length: Math.max(0, count) }, (_, candidate) => candidate).filter(enabled); + if (usable.length === 0) { + return null; + } + let target: number | undefined; + switch (key) { + case 'Home': target = usable[0]; break; + case 'End': target = usable.at(-1); break; + case 'ArrowRight': + case 'ArrowLeft': { + const step = key === 'ArrowRight' ? 1 : -1; + if (index < 0 || index >= count) { + target = step === 1 ? usable[0] : usable.at(-1); + break; + } + for (let offset = 1; offset <= count; offset++) { + const candidate = (((index + step * offset) % count) + count) % count; + if (enabled(candidate)) { + target = candidate; + break; + } + } + break; + } + default: return null; + } + return target === undefined || target === index ? null : target; +} + +/** + * The tab that holds the list's single Tab stop (roving tabindex): the + * selected one when it can be focused, else the first enabled tab; -1 when + * none can. + */ +export function tablistTabStop(count: number, selected: number, disabled: readonly boolean[] = []): number { + if (selected >= 0 && selected < count && disabled[selected] !== true) { + return selected; + } + for (let candidate = 0; candidate < count; candidate++) { + if (disabled[candidate] !== true) { + return candidate; + } + } + return -1; +} diff --git a/apps/ide/src/renderer/terminal/terminalPanel.ts b/apps/ide/src/renderer/terminal/terminalPanel.ts index 30043764..1c55aaf9 100644 --- a/apps/ide/src/renderer/terminal/terminalPanel.ts +++ b/apps/ide/src/renderer/terminal/terminalPanel.ts @@ -5,6 +5,7 @@ import { createTerminalFind } from './terminalFind.ts'; import { createWorkspaceFileChecker, type ListDirectory } from './terminalLinks.ts'; import type * as XtermModule from './xtermView.ts'; import { startupMark } from '../startup/startupMarks.ts'; +import { tablistKeyTarget } from '../tablistKeyModel.ts'; import type { XtermView } from './xtermView.ts'; /** @@ -38,6 +39,8 @@ export interface TerminalPanel { runTask(label: string, start: (cols: number, rows: number) => Promise): Promise; /** #18: the terminals' font size, for the open ones and the next. */ setFontSize(size: number): void; + /** #535 (O32): xterm's screen-reader mode, for the open terminals and the next. */ + setScreenReaderMode(on: boolean): void; /** #286: the focus is in a terminal (or its find widget): the scope of the terminal's Ctrl+F. */ hasFocus(): boolean; /** #286: opens the find widget on the active terminal. */ @@ -78,6 +81,7 @@ interface TerminalTab { export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], platform: Promise, hooks: TerminalPanelHooks): TerminalPanel { let activeId: number | null = null; let fontSize = 13; + let screenReaderMode = false; let loadingView: Promise | null = null; let firstOpened = false; /** xterm.js and its add-ons, in their own chunk: loaded once, by the first terminal or a preload. */ @@ -135,7 +139,8 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], new ResizeObserver(scheduleFit).observe(body); - function activate(id: number | null): void { + /** `focusView` false: the tab keeps the focus (#535: arrow keys in the tab list). */ + function activate(id: number | null, focusView = true): void { activeId = id; for (const entry of tabs.values()) { const selected = entry.id === id; @@ -149,10 +154,30 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], find.setTarget(active?.view ?? null); if (active) { scheduleFit(); - active.view.focus(); + if (focusView) { + active.view.focus(); + } } } + // #535 (O32): Left/Right/Home/End move between the terminal tabs and show the one reached. + tabList.addEventListener('keydown', (event) => { + const byTab = new Map([...tabs.values()].map((entry) => [entry.tab as Element, entry])); + const order = [...tabList.children].flatMap((child) => byTab.get(child) ?? []); + const index = order.findIndex((entry) => entry.tab === event.target); + if (index < 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { + return; + } + const target = tablistKeyTarget(event.key, order.length, index); + const entry = target === null ? undefined : order[target]; + if (!entry) { + return; + } + event.preventDefault(); + activate(entry.id, false); + entry.tab.focus(); + }); + function uniqueTitle(base: string): string { const titles = new Set([...tabs.values()].map((entry) => entry.label.textContent)); if (!titles.has(base)) { @@ -240,6 +265,7 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], const view: XtermView = createXtermView(host, { platform: os, fontSize, + screenReaderMode, onInput: (data) => { if (id !== null && !tabs.get(id)?.exited) { void api.input(id, data).catch(() => undefined); @@ -278,7 +304,7 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], const terminalId = id; const label = el('span', { className: 'tab-label' }); const close = el('button', { className: 'tab-close', attrs: { type: 'button', 'aria-label': 'Kill terminal', title: 'Kill terminal', tabindex: '-1' } }, [icon(ICONS.close)]); - const tab = el('div', { className: 'terminal-tab', attrs: { role: 'tab', 'data-terminal-id': String(terminalId) } }, [icon(task === null ? ICONS.terminal : ICONS.task, 'terminal-tab-icon'), label, close]); + const tab = el('div', { className: 'terminal-tab', attrs: { role: 'tab', tabindex: '-1', 'aria-selected': 'false', 'data-terminal-id': String(terminalId) } }, [icon(task === null ? ICONS.terminal : ICONS.task, 'terminal-tab-icon'), label, close]); label.textContent = uniqueTitle(task === null ? profileName : `Task - ${task}`); tab.title = `${label.textContent} (double-click to rename)`; host.dataset['terminalId'] = String(terminalId); @@ -464,6 +490,15 @@ export function createTerminalPanel(host: PanelHost, api: CodeXRApi['terminal'], const active = activeId === null ? undefined : tabs.get(activeId); return active ? active.view.recentText(maxLines) : ''; }, + setScreenReaderMode(on: boolean): void { + if (on === screenReaderMode) { + return; + } + screenReaderMode = on; + for (const entry of tabs.values()) { + entry.view.setScreenReaderMode(on); + } + }, setFontSize(size: number): void { if (size === fontSize) { return; diff --git a/apps/ide/src/renderer/terminal/xtermView.ts b/apps/ide/src/renderer/terminal/xtermView.ts index 83cc91a8..736ce1a1 100644 --- a/apps/ide/src/renderer/terminal/xtermView.ts +++ b/apps/ide/src/renderer/terminal/xtermView.ts @@ -26,6 +26,8 @@ export interface XtermView { focus(): void; /** #18: the terminal.integrated.fontSize setting. */ setFontSize(size: number): void; + /** #535 (O32): xterm's screen-reader mode (editor.accessibilitySupport "on"). */ + setScreenReaderMode(on: boolean): void; /** The selected text, or '' (#286: the find widget starts from it). */ selection(): string; /** #522: the last `maxLines` lines of the scrollback as text (for `@terminal`). */ @@ -55,6 +57,8 @@ export interface XtermLinkHooks { export interface XtermOptions { readonly platform: string; readonly fontSize?: number; + /** #535 (O32): start in xterm's screen-reader mode. */ + readonly screenReaderMode?: boolean; onInput(data: string): void; /** #286: the find widget's "n of m"; `index` is -1 when no match is selected. */ onFindResults?(index: number, count: number): void; @@ -106,6 +110,7 @@ export function createXtermView(container: HTMLElement, options: XtermOptions): theme: theme(), fontFamily: "Consolas, 'Cascadia Mono', Menlo, 'DejaVu Sans Mono', 'Liberation Mono', monospace", fontSize: options.fontSize ?? 13, + screenReaderMode: options.screenReaderMode ?? false, cursorBlink: true, scrollback: 5000, // #286: the search addon counts matches through decorations, a "proposed" (not yet @@ -254,6 +259,11 @@ export function createXtermView(container: HTMLElement, options: XtermOptions): setFontSize(size: number): void { term.options.fontSize = size; }, + setScreenReaderMode(on: boolean): void { + if (term.options.screenReaderMode !== on) { + term.options.screenReaderMode = on; + } + }, get rows() { return term.rows; }, selection: () => term.getSelection(), recentText(maxLines: number): string { diff --git a/apps/ide/src/shared/a11yAudit.ts b/apps/ide/src/shared/a11yAudit.ts new file mode 100644 index 00000000..2408f3da --- /dev/null +++ b/apps/ide/src/shared/a11yAudit.ts @@ -0,0 +1,120 @@ +/** + * #535 (O32): the accessibility checks of the smoke run. The page only + * describes what it shows (`A11ySnapshot`, plain data gathered by a script in + * the renderer); this module decides what is wrong with it, so the rules are + * unit-tested without a DOM. + * + * Three rules, all of which a keyboard or screen-reader user runs into: + * - an interactive element (a button, a tab, a tree item, an option, a menu + * item, a form field) needs an accessible name: aria-label, + * aria-labelledby, its text, a title or a