diff --git a/apps/ide/README.md b/apps/ide/README.md index 7fa636bbd..720987d03 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -373,6 +373,22 @@ The parsers (`statusParser.ts`, `blameParser.ts`) are pure and unit-tested on st 3. Register the handler in `src/main/ipc.ts` through `handle()`, which already rejects untrusted frames. Validate every argument: the renderer is untrusted. 4. Add a unit test for any pure logic, and extend the smoke probe if the capability is security-relevant. +## Agent-first workbench (epic #265) + +The IDE opens in the **Agent** layout: chats with the person's own coding agents on the left, the work area (files and chats as tabs) in the middle, and the live Code-XR analysis of the project on the right, so the project's scene changes while the agent works. **Classic** is the VS Code-like workbench as it was; the switch is at the top of the Chats view, in *View > Toggle Agent / Classic Layout* and on Ctrl/Cmd+Alt+M, and it is remembered. The market study behind it is `docs/ide/ai-ide-market-study.md` at the repository root. + +- **Agents over ACP (AF1, #266):** Claude Code, Codex and Gemini CLI are run as separate programs through the [Agent Client Protocol](https://agentclientprotocol.com) (`@agentclientprotocol/sdk`, `src/main/agentSessions/`). Each keeps its own sign-in, so a Claude, ChatGPT or Google subscription (or an API key) stays with the vendor's tool: the IDE never reads or stores a vendor token, and only offers the agent's own login methods (a terminal login runs in an integrated terminal). The catalogue (`agentCatalog.ts`) finds the adapters on PATH (`claude-agent-acp`, `codex-acp`, `gemini --acp`) and says how to install a missing one; nothing is downloaded unless the person installs it (AF2, below). Agents get a minimal environment (their own vendor variables, proxy and CA settings), file access limited to the folder, terminals that run in the folder, and per-tool permission cards (allow once or always, reject). They never start in Restricted Mode (#177). +- **Chats (AF3, AF7, #268, #272):** every chat is an editor tab (`chat:`, through the custom-editor seam of #256), so it sits next to files, splits and comes back after a restart. The Chats view groups chats by project with status dots (working, needs your approval, done, unread), search, rename and delete. A chat streams the reply as Markdown, shows tool calls as cards with diffs and terminal output, the agent's plan, its modes and model options, its slash commands, `@` attachments and context use; messages typed while it works are queued. A finished or blocked chat that is not on screen raises a notification with *Open chat*. The pure logic is in `renderer/agentFirst/*Model.ts`, tested in `test/agentFirst.test.ts`. +- **Live analysis (AF8, #273):** in the Agent layout the right column holds the scene of the folder's analysis, or a placeholder with *Analyse this project* until one opens. The core already re-analyses changed files when anything writes them (its `fs.watch` session watchers), so an agent's edits reach the scene without a save in the editor; the per-change notices go to the status bar only. +- **Code-XR context for agents (AF10, #275):** every chat is given the Code-XR MCP server (below) in `session/new`, so the agent can ask for metrics, hotspots, dependencies and evolution itself. +- **Project instructions (AF11, #276):** the *Project instructions* section of the Chats view shows which of `AGENTS.md`, `CLAUDE.md`, `GEMINI.md` and `.github/copilot-instructions.md` the project has, opens them, and creates a missing one from a short template (CLAUDE.md imports AGENTS.md, so one file serves every agent). Other rule files (Cursor, nested AGENTS.md) are listed too. +- **Checkpoints and worktrees (AF6, AF12, #271, #277):** `src/main/checkpoints/` snapshots the project into a private git directory outside it (`userData/checkpoints`) before each message and computes the files a chat changed (the project's own repository is never touched); `src/main/worktrees/` creates a git worktree and branch per chat outside the project and merges or squashes it back. Every message with a checkpoint has *Restore files to here*, which first lists inline the files it would write, then puts the project back as it was before that message (the conversation is kept; effects of commands, such as network calls or databases, are not undone). +- **Agents in parallel, each in its own worktree (AF12, #277):** under *New chat*, **Separate worktree** (shown only when the window's folder is a trusted git work tree with a commit; the last choice is remembered) starts the chat in a git worktree of its own, on a branch `codexr/agent/-` created from the project's HEAD, stored in `/worktrees//` (outside the project, so its watchers, search and analysis never see a second copy). Uncommitted changes of the project are not in it; the chat says so when there were some. The agent's `cwd`, the `cwd` of `session/new`, the folder it may read and write and the folder its terminals run in are the worktree (the project's sub-folder inside it, when the project is a sub-folder of its repository), never the project; the chat's Changes tab and checkpoints work on the worktree too. The chat and the Chats list show the branch as a badge; the chat header's **Worktree** bar shows the files changed since the base commit (committed or not) and the commits ahead of the base and behind the project's branch, and offers **Commit** (message prefilled from the chat title), **Merge into the current branch** (`--no-ff`) and **Squash into the current branch** (one commit titled after the chat), refused with nothing changed and the reason (conflicts predicted by `git merge-tree`, staged changes, uncommitted changes to files the agent also changed, uncommitted work in the worktree, a detached HEAD), and **Discard worktree** (confirmed inline; removes the folder and deletes the branch, the chat stays read-only). Deleting such a chat asks inline whether its worktree and branch go too. The worktree record (`branch`, `path`, `cwd`, `baseCommit`, `repoRoot`) is kept with the chat by the main process; the renderer names a chat by id only, and main acts on a record only when its path lies in the IDE's worktree folder. The git work itself is `src/main/worktrees/worktreeManager.ts` (hooks off for the agent's own commits, the person's hooks and signing for the final merge, one lock per repository); the wiring is in `agentSessionService.ts`, the bar in `renderer/agentFirst/worktreeBar.ts`, tested in `test/agentWorktrees.test.ts`. Limits: the live analysis, the metric delta per turn and the Code-XR MCP server keep following the main project, not the worktree (its changes show in the scene once merged); file links of a worktree chat do not open in the editor, which shows the main project; worktrees left by a deleted chat (kept on request) are not listed in the IDE yet (`git worktree list` shows them). +- **Review of an agent's changes (AF5, #270):** `SessionChanges` (`src/main/checkpoints/sessionChanges.ts`) makes a chat's first checkpoint its review base (persisted in `userData/agent-sessions/review.json`); the chat header's *Changes (N)* opens a **Changes** tab (`chat-changes:`) with the pending files, their +/- counts, a Monaco side-by-side diff (base left, disk right) and *Keep* / *Undo* per file or for all. Keep moves a file's base to a fresh snapshot; Undo writes it back from its base. Undo and restore are refused while the agent works. The renderer names files only by workspace-relative paths, checked in main, and may restore only checkpoints recorded on the chat's own messages. A project where checkpoints are off (too many files, a timeout) keeps a working chat, with no restore buttons and the reason in the Changes tab. +- **Metric delta per turn (AF9, #274):** when the window has a project scene open, its metrics are read before each message and compared after the turn, once the scene has caught up with the files the turn changed; a short line under the turn ("Complexity max 9 -> 1, LOC -6") unfolds into the per-file detail. Without a scene, or when nothing moved, nothing is shown. +- **Installing agents (AF2, #267):** a missing preset shows *Install*, one the IDE installed shows its version with *Update* and *Remove* (Agents section of the Chats view, and the first-run guide). *Install* reads the npm registry, only then, and shows inline what would be installed: package and version, licence, unpacked size plus the dependencies' size for this platform, repository, publication date, the platform-specific native binaries npm will pick (Claude Code's SDK and Codex each bring one of roughly 400 MB) and which packages run install scripts. A native dialog in the main process, which the page cannot answer, repeats it with the exact npm command; only that starts the download. `src/main/agentSessions/agentInstaller.ts` (Electron-free, tested against a local fake registry and a fake npm) runs the **system npm** (`npm install --prefix /agent-packages --no-audit --no-fund --omit=dev --save-exact --ignore-scripts=false @`, Windows through the `node.exe` + `npm-cli.js` beside `npm.cmd`, never a shell) into a private package.json: nothing global, the person's own npm configuration, proxy and CA apply, and its output streams to a progress notification. Why npm rather than an own downloader: only npm resolves the dependency tree, optional platform packages and lifecycle scripts faithfully, and bundling it would add a large dependency; a missing npm gets a message pointing to nodejs.org. Once installed, the adapter runs on the IDE's own Electron as Node, so chats need no system Node. The registry is read through Electron's `net.fetch` (system proxy settings); the smoke run has no installer and checks that the call is refused. +- **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`). + ## VS Code extensions (stream `ide-extensions`, epic #251) The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in an extension host process per window (`src/extensionHost/`, #259), with their commands in the palette and their messages, pickers, progress and status bar items in the workbench; they see the editor's documents and active editor, and their language features (diagnostics, completion, hover, definitions, code actions, formatting, rename... including language clients built on `vscode-languageclient`) work in Monaco (#260). Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). @@ -390,6 +406,7 @@ The Agents view (activity bar, speech-bubble icon) connects the IDE to LLM provi - **Edits as diffs (A8):** `propose_edit` (`main/agents/tools/editTools.ts`, off by default, ticked per agent) takes exact find/replace pairs (each `find` must be unique in the file) or a whole new content, keeps the file's line endings, and never writes: it emits a `review` event and waits. The window opens `renderer/agents/editReview.ts` over the editor cell, a read-only Monaco diff with the change's hunks (`shared/lineDiff.ts`) to tick or untick, and writes only the accepted ones: into the open tab as one undoable edit saved through the editor's own save path (`EditorGroup.applyAgentEdit`, refused when the tab has unsaved edits), or with `writeFile(path, text, mtime)` so a file changed on disk meanwhile is not overwritten. The agent is told what was applied, partly applied or rejected; Stop counts as a rejection. - **Commands (A9):** `run_command` (`main/agents/tools/commandTool.ts`, off by default) always shows the exact command line on an approval card, then runs it in a pty of the default terminal profile (#137, node-pty via `TerminalHost.commandRunner`) in the project folder, with `-c` / `-Command` / `/c` by shell. It is non-interactive (`CI=1`, no pager, no colour). The output streams into the chat's tool line while it runs, and the model gets the exit code and the output without colours, cut in the middle past 16k characters. A timeout (120 s by default, 600 s at most) or Stop kills it, and so does quitting the IDE. Unlike the terminal panel, these commands do not appear in a terminal tab. - **Code-XR analyses (A10):** `get_metrics`, `get_hotspots`, `get_dependencies` and `get_evolution` (`main/agents/tools/analysisTools.ts`) are read-only and given to the starters. They read what the window's XR analysis already wrote to its scene folder (`AnalysisService.outputDirectory`): `data.json` (one metrics record per file), `dependency-graph.json` (once the scene's dependency mode ran) and the last `evolution/revision-N/` movie. They never start an analysis or download anything; without one they tell the model to ask the person to run it. Their lines in the chat carry an *Open in XR* button that shows the scene. +- **Code-XR analysis as an MCP server (AF10):** the same four queries are offered to external coding agents (Claude Code, Codex, Gemini CLI over ACP) by a stdio MCP server, `src/codexrMcp/` (`@modelcontextprotocol/sdk`). The queries live once, in `main/agents/tools/analysisQueries.ts`; `analysisTools.ts` binds them to the window for the built-in agent and `codexrMcp/server.ts` registers them with the same names and argument schemas, descriptions prefixed `[Code-XR]` and read-only annotations. Vite bundles it on its own into `out/codexrMcp/index.cjs`, which the IDE's own binary runs in Node mode, so no system Node is needed: `main/agentSessions/codexrMcpSpec.ts` builds the `session/new` entry, `{ name: 'code-xr', command: process.execPath, args: [/out/codexrMcp/index.cjs, '--root', , '--analysis', ], env: [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }] }`. Packaged, the bundle stays inside `app.asar` (Electron's Node mode reads asar paths). It opens only `data.json`, `dependency-graph.json` and `evolution/revision-N/data*.json` in the analysis folder, never starts an analysis and has no network listener; without an analysis it answers with the built-in tools' "no analysis" message. To use it from another MCP client by hand, run `npm run ide:build` and register a stdio server with command `/node_modules/electron/dist/electron` (or the installed `code-xr-ide` executable), arguments `/apps/ide/out/codexrMcp/index.cjs --root --analysis ` and environment `ELECTRON_RUN_AS_NODE=1`; for example `claude mcp add code-xr -e ELECTRON_RUN_AS_NODE=1 -- --root --analysis `. - **Supervisor and sub-agents (A11):** `delegate_task` (opt-in per agent) hands a self-contained task to another of the person's agents by name. `AgentChat.runChild` runs it through the same model/tool loop as a chat answer (`loop`), with the child's own profile, a clean context (only the task), the same approval rules (its cards name the sub-agent) and no `delegate_task` of its own, so the run tree is one level deep. The calls of one turn run in parallel, up to the supervisor's `maxParallel` (1-8, default 3, set in the agent form). Each call's line in the chat is the run tree: the sub-agent's status, model, tokens, task, tools and streaming answer, plus a Cancel button (`agents.cancelRun`) that stops that sub-agent alone; Stop stops them all. Sub-agents' tokens are added to the answer's usage. - **MCP servers (A12):** the *MCP servers* section of the Agents view adds local (stdio: a command and its arguments) and remote (Streamable HTTP: a URL and an optional bearer token, kept in the OS secret store) servers. `main/agents/mcp/` holds a small JSON-RPC client (initialize, paged `tools/list`, `tools/call`, cancellation; server requests such as sampling are refused), the two transports (on Windows, `.cmd` launchers such as `npx` go through `cmd.exe` with cross-spawn-style escaping) and `McpRegistry`. A new or changed local command is only saved after the person accepts a native dialog that shows the exact command line. Nothing connects at start-up: a server is contacted when it is saved or refreshed and when an agent calls one of its tools; its tool list is cached so agent forms show it without connecting. Tools appear as `mcp____` in the agent form (with a filter once the list is long) and have risk `network`, so every call goes through the approval card. Server processes are stopped on quit. - **Usage, cost and limits (A13):** `main/agents/usageLedger.ts` records every model call (agent, provider, model, tokens) in `usage.json`, by month. Two costs are kept apart everywhere: the *estimate* (tokens × the person's price table, USD per million tokens, exact model ids or `prefix*`, empty until the person fills it) and the *reported* cost when the provider sends one (OpenRouter's `usage.cost`, read by the OpenAI-compatible adapter). Each answer stores its provider, model and usage, and shows them under it; the chat shows its own total; the *Usage and budget* section shows the month by agent, provider and model, the budget form and the price table. The monthly budget counts each call once (its reported cost, or its estimate when none was reported), warns from a chosen share and, with the hard stop on, refuses new model calls (answers and sub-agents) once it is spent. diff --git a/apps/ide/THIRD_PARTY_NOTICES.md b/apps/ide/THIRD_PARTY_NOTICES.md index 6f6530293..61bc2a02c 100644 --- a/apps/ide/THIRD_PARTY_NOTICES.md +++ b/apps/ide/THIRD_PARTY_NOTICES.md @@ -84,6 +84,17 @@ Usage in this package: - Bundled into the renderer by Vite: sanitises the Markdown preview's HTML before it reaches the page (#179, `src/renderer/editor/markdownPreview.ts`). The same version Monaco already depends on. +## MCP TypeScript SDK (the Code-XR MCP server) + +- Project: `@modelcontextprotocol/sdk` on npm, 1.32.2, by Anthropic, PBC and the Model Context Protocol contributors +- Source: https://github.com/modelcontextprotocol/typescript-sdk +- License: MIT + +Usage in this package: + +- Bundled by Vite into the Code-XR MCP server (`out/codexrMcp/index.cjs`, AF10, `src/codexrMcp/`) that external agents run to query the project's analysis. Only that bundle carries it; the main process has its own small MCP client (`src/main/agents/mcp/`). +- The bundle also carries the SDK's own dependencies: `zod` (4.6.7, MIT, https://github.com/colinhacks/zod), `zod-to-json-schema` (3.25.2, ISC, https://github.com/StefanTerdell/zod-to-json-schema), `ajv` (8.20.0, MIT, https://github.com/ajv-validator/ajv), `ajv-formats` (3.0.1, MIT), `fast-deep-equal` (3.1.3, MIT), `json-schema-traverse` (1.0.0, MIT) and `fast-uri` (3.0.6, BSD-3-Clause, https://github.com/fastify/fast-uri). + ## vscode-textmate (TextMate grammars of extensions) - Project: `vscode-textmate` on npm, 9.3.2, by Microsoft Corporation @@ -168,6 +179,16 @@ Usage in this package: - The text-layer rules in `src/renderer/viewers/viewers.css` are a trimmed copy of the `.textLayer` block of its `web/pdf_viewer.css`. - The optional `@napi-rs/canvas` dependency is only used by PDF.js under Node and is not bundled. +## Agent Client Protocol TypeScript SDK (agent chats) + +- Project: `@agentclientprotocol/sdk` on npm, 2.12.0, by Zed Industries and the Agent Client Protocol contributors +- Source: https://github.com/agentclientprotocol/typescript-sdk +- License: Apache-2.0 + +Usage in this package: + +- Bundled by Vite into the main process: speaks the Agent Client Protocol with the coding agents a chat runs (Claude Code, Codex, Gemini CLI; AF1, `src/main/agentSessions/acpConnection.ts`). The agents themselves are separate programs installed by the person and are not part of this package. + ## xterm.js search and web-links addons (terminal find and links) - Project: `@xterm/addon-search` 0.16.0 and `@xterm/addon-web-links` 0.12.0 on npm, by the xterm.js authors (released with `@xterm/xterm` 6.0.0) diff --git a/apps/ide/package.json b/apps/ide/package.json index faafd09ba..057269f75 100644 --- a/apps/ide/package.json +++ b/apps/ide/package.json @@ -21,6 +21,8 @@ "node": ">=24" }, "devDependencies": { + "@agentclientprotocol/sdk": "2.12.0", + "@modelcontextprotocol/sdk": "1.32.2", "@types/node": "^22.20.7", "@types/vscode": "1.146.0", "@types/yauzl": "3.4.0", diff --git a/apps/ide/scripts/build.mjs b/apps/ide/scripts/build.mjs index 14e0382c9..3131978fd 100644 --- a/apps/ide/scripts/build.mjs +++ b/apps/ide/scripts/build.mjs @@ -5,6 +5,7 @@ import { nodeTargetConfig, rendererConfig } from './viteConfigs.mjs'; await build(nodeTargetConfig('main')); await build(nodeTargetConfig('preload')); await build(nodeTargetConfig('scenePreload')); +await build(nodeTargetConfig('codexrMcp')); await build(nodeTargetConfig('extensionHost')); await build(rendererConfig()); console.log('[code-xr-ide] built into apps/ide/out/'); diff --git a/apps/ide/scripts/dev.mjs b/apps/ide/scripts/dev.mjs index 090c906de..0dfcc1542 100644 --- a/apps/ide/scripts/dev.mjs +++ b/apps/ide/scripts/dev.mjs @@ -43,9 +43,10 @@ function restartElectron() { startElectron(); } -// Watch main, both preloads (the window's and the scene view's, #16) and the extension host (#259); restart Electron after each successful rebuild. -const pending = new Set(['main', 'preload', 'scenePreload', 'extensionHost']); -for (const target of /** @type {const} */ (['main', 'preload', 'scenePreload', 'extensionHost'])) { +// Watch main, both preloads (the window's and the scene view's, #16), the +// MCP server (AF10) and the extension host (#259); restart Electron after each successful rebuild. +const pending = new Set(['main', 'preload', 'scenePreload', 'codexrMcp', 'extensionHost']); +for (const target of /** @type {const} */ (['main', 'preload', 'scenePreload', 'codexrMcp', 'extensionHost'])) { const config = nodeTargetConfig(target, { dev: true }); config.build.watch = {}; const watcher = /** @type {import('vite').Rollup.RollupWatcher} */ (await build(config)); diff --git a/apps/ide/scripts/viteConfigs.mjs b/apps/ide/scripts/viteConfigs.mjs index 192a0855a..871b6d050 100644 --- a/apps/ide/scripts/viteConfigs.mjs +++ b/apps/ide/scripts/viteConfigs.mjs @@ -4,6 +4,8 @@ // out/main/index.cjs main process (Node, CommonJS) // out/preload/index.cjs preload (sandboxed: may only require 'electron') // out/renderer/ renderer (browser, served from codexr://app/) +// out/codexrMcp/index.cjs the Code-XR MCP server for external agents (AF10; +// a separate process run with ELECTRON_RUN_AS_NODE) // out/extensionHost/index.cjs extension host (#259: a Node child process on Electron's own Node) import { builtinModules } from 'node:module'; import path from 'node:path'; @@ -28,7 +30,7 @@ const NODE_EXTERNALS = ['electron', /^electron\//, ...builtinModules, ...builtin */ const MAIN_NATIVE_EXTERNALS = ['node-pty']; -/** @param {'main' | 'preload' | 'scenePreload' | 'extensionHost'} target @param {{ dev?: boolean }} [opts] */ +/** @param {'main' | 'preload' | 'scenePreload' | 'codexrMcp' | 'extensionHost'} target @param {{ dev?: boolean }} [opts] */ export function nodeTargetConfig(target, opts = {}) { return { configFile: false, diff --git a/apps/ide/src/codexrMcp/index.ts b/apps/ide/src/codexrMcp/index.ts new file mode 100644 index 000000000..4552e4ab6 --- /dev/null +++ b/apps/ide/src/codexrMcp/index.ts @@ -0,0 +1,23 @@ +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { createCodexrMcpServer, parseArgs } from './server.ts'; + +/** + * Entry of the Code-XR MCP server (AF10), bundled on its own into + * out/codexrMcp/index.cjs. The IDE hands it to each external agent in ACP + * `session/new` as a stdio server run by the IDE's own binary with + * ELECTRON_RUN_AS_NODE=1, so no system Node is needed: + * + * out/codexrMcp/index.cjs --root --analysis + * + * stdout carries the protocol; diagnostics go to stderr only. + */ + +async function main(): Promise { + const server = createCodexrMcpServer(parseArgs(process.argv.slice(2))); + await server.connect(new StdioServerTransport()); +} + +main().catch((error: unknown) => { + process.stderr.write(`[code-xr-mcp] ${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); +}); diff --git a/apps/ide/src/codexrMcp/server.ts b/apps/ide/src/codexrMcp/server.ts new file mode 100644 index 000000000..4f5c53c91 --- /dev/null +++ b/apps/ide/src/codexrMcp/server.ts @@ -0,0 +1,84 @@ +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'; + +/** + * The Code-XR MCP server (AF10): the analysis queries of the built-in agent + * (get_metrics, get_hotspots, get_dependencies, get_evolution), 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. + * + * Kept apart from the stdio entry (index.ts) so the tests can drive it over + * the SDK's in-memory transport. It is read-only by construction: the only + * 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. + */ + +export const CODEXR_MCP_NAME = 'code-xr'; +export const CODEXR_MCP_VERSION = '0.1.0'; + +export interface CodexrMcpOptions { + /** The project open in the IDE (absolute). Paths in the tools' arguments are relative to it. */ + readonly root: string; + /** The static folder of the project's XR analysis (absolute), or null when none has run yet. */ + readonly analysisDir: string | null; +} + +/** The descriptions external agents see: the built-in agent's, saying where they come from. */ +export function mcpDescription(query: AnalysisQuery): string { + return `[Code-XR] ${query.description}`; +} + +/** The zod shape the SDK wants, built from the query's JSON Schema so both surfaces stay identical. */ +function inputShape(query: AnalysisQuery): Record { + const shape: Record = {}; + for (const [key, property] of Object.entries(query.parameters.properties)) { + shape[key] = (property.type === 'integer' ? z.number().int() : z.string()).optional().describe(property.description); + } + return shape; +} + +/** Parses `--root --analysis `; an empty analysis argument means "no analysis yet". */ +export function parseArgs(argv: readonly string[]): CodexrMcpOptions { + const value = (flag: string): string | undefined => { + const index = argv.indexOf(flag); + return index >= 0 ? argv[index + 1] : undefined; + }; + const root = value('--root'); + if (!root || !path.isAbsolute(root)) { + throw new Error('--root must be an absolute path.'); + } + const analysis = value('--analysis') ?? ''; + 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 }; +} + +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.` }, + ); + for (const query of ANALYSIS_QUERIES) { + server.registerTool(query.name, { + title: query.title, + description: mcpDescription(query), + inputSchema: inputShape(query), + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + }, async (args: Record) => { + try { + if (!options.analysisDir) { + throw new Error(NO_ANALYSIS); + } + return { content: [{ type: 'text' as const, text: await query.run(args, options.analysisDir) }] }; + } catch (error) { + return { content: [{ type: 'text' as const, text: error instanceof Error ? error.message : String(error) }], isError: true }; + } + }); + } + return server; +} diff --git a/apps/ide/src/main/agentSessions/acpConnection.ts b/apps/ide/src/main/agentSessions/acpConnection.ts new file mode 100644 index 000000000..512cc0e27 --- /dev/null +++ b/apps/ide/src/main/agentSessions/acpConnection.ts @@ -0,0 +1,305 @@ +import { spawn, type ChildProcess } from 'node:child_process'; +import { Readable, Writable } from 'node:stream'; +import { + client, + methods, + ndJsonStream, + RequestError, + type AgentApp, + type ClientConnection, + type ContentBlock, + type CreateTerminalRequest, + type CreateTerminalResponse, + type InitializeResponse, + type KillTerminalRequest, + type LoadSessionResponse, + type McpServer, + type NewSessionResponse, + type PromptResponse, + type ReadTextFileRequest, + type ReadTextFileResponse, + type ReleaseTerminalRequest, + type RequestPermissionRequest, + type RequestPermissionResponse, + type SessionUpdate, + type SetSessionConfigOptionResponse, + type TerminalOutputRequest, + type TerminalOutputResponse, + type WaitForTerminalExitRequest, + type WaitForTerminalExitResponse, + type WriteTextFileRequest, +} from '@agentclientprotocol/sdk'; + +/** + * AF1: one Agent Client Protocol connection to one agent process. The IDE is + * the ACP *client*: it spawns the agent (no shell), speaks newline-delimited + * JSON-RPC over the child's stdio through the SDK's stable v1 entry point, + * and answers the agent's requests (files, terminals, permissions) through + * `AcpClientHandlers`, which the service implements per chat. One process per + * chat keeps a crash or a hung agent contained to that chat. + * + * Tests connect the same client to an in-process fake agent (`inProcess`), + * so this file is exercised end to end without spawning anything. + */ + +export const ACP_PROTOCOL_VERSION = 1; + +/** What the agent may ask the IDE for, implemented per chat by the service. */ +export interface AcpClientHandlers { + onUpdate(sessionId: string, update: SessionUpdate): void; + requestPermission(params: RequestPermissionRequest, signal: AbortSignal): Promise; + readTextFile(params: ReadTextFileRequest): Promise; + writeTextFile(params: WriteTextFileRequest): Promise; + createTerminal(params: CreateTerminalRequest): Promise; + terminalOutput(params: TerminalOutputRequest): TerminalOutputResponse; + waitForTerminalExit(params: WaitForTerminalExitRequest, signal: AbortSignal): Promise; + killTerminal(params: KillTerminalRequest): void; + releaseTerminal(params: ReleaseTerminalRequest): void; +} + +/** How to start an agent: an executable (never through a shell), its arguments and its whole environment. */ +export interface AgentLaunch { + readonly command: string; + readonly args: readonly string[]; + readonly env: Readonly>; + /** Windows only: pass `args` to the program unquoted (a `cmd.exe /d /s /c "..."` launch). */ + readonly verbatimArguments?: boolean; +} + +const STDERR_TAIL = 4000; + +/** + * The agent sees why a request was refused ("outside the project folder"), + * not the SDK's generic "Internal error" for a thrown `Error`. + */ +async function answer(run: () => T | Promise): Promise { + try { + return await run(); + } catch (error) { + if (error instanceof RequestError) { + throw error; + } + throw new RequestError(-32603, error instanceof Error ? error.message : String(error)); + } +} + +function clientApp(handlers: AcpClientHandlers) { + return client({ name: 'code-xr-ide' }) + .onNotification(methods.client.session.update, ({ params }) => { + handlers.onUpdate(params.sessionId, params.update); + }) + .onRequest(methods.client.session.requestPermission, ({ params, signal }) => answer(() => handlers.requestPermission(params, signal))) + .onRequest(methods.client.fs.readTextFile, ({ params }) => answer(() => handlers.readTextFile(params))) + .onRequest(methods.client.fs.writeTextFile, ({ params }) => answer(async () => { + await handlers.writeTextFile(params); + return {}; + })) + .onRequest(methods.client.terminal.create, ({ params }) => answer(() => handlers.createTerminal(params))) + .onRequest(methods.client.terminal.output, ({ params }) => answer(() => handlers.terminalOutput(params))) + .onRequest(methods.client.terminal.waitForExit, ({ params, signal }) => answer(() => handlers.waitForTerminalExit(params, signal))) + .onRequest(methods.client.terminal.kill, ({ params }) => answer(() => { + handlers.killTerminal(params); + return {}; + })) + .onRequest(methods.client.terminal.release, ({ params }) => answer(() => { + handlers.releaseTerminal(params); + return {}; + })); +} + +export class AcpConnection { + private readonly connection: ClientConnection; + private readonly child: ChildProcess | null; + private stderr = ''; + private exitError: Error | null = null; + private readonly closeListeners: ((error: Error | null) => void)[] = []; + private closed = false; + + private readonly exited: Promise; + + private constructor(connection: ClientConnection, child: ChildProcess | null) { + this.connection = connection; + this.child = child; + this.exited = child && child.exitCode === null && child.signalCode === null + ? new Promise((resolve) => child.once('exit', () => resolve())) + : Promise.resolve(); + // stdout ends a moment before the process reports its exit: wait for + // it, so the close carries the exit code and the stderr tail. + void connection.closed.then(async () => { + await this.settleExit(); + this.markClosed(this.exitError); + }); + } + + /** Waits (briefly) for the process to report its exit after the stream ended. */ + private async settleExit(): Promise { + if (!this.child || this.exitError) { + return; + } + await Promise.race([this.exited, new Promise((resolve) => setTimeout(resolve, 500).unref())]); + } + + /** A request that failed because the stream closed reports why the agent went away instead. */ + private async explain(request: Promise): Promise { + try { + return await request; + } catch (error) { + if (error instanceof Error && /connection closed/i.test(error.message)) { + await this.settleExit(); + throw this.exitError ?? error; + } + throw error; + } + } + + /** Starts the agent process in `cwd` and connects to its stdio. */ + static spawn(launch: AgentLaunch, cwd: string, handlers: AcpClientHandlers, onLog?: (line: string) => void): AcpConnection { + const child = spawn(launch.command, [...launch.args], { + cwd, + env: { ...launch.env }, + stdio: ['pipe', 'pipe', 'pipe'], + shell: false, + windowsHide: true, + ...(launch.verbatimArguments ? { windowsVerbatimArguments: true } : {}), + }); + const stdin = child.stdin; + const stdout = child.stdout; + if (!stdin || !stdout) { + child.kill(); + throw new Error('The agent process has no standard input or output.'); + } + const stream = ndJsonStream(Writable.toWeb(stdin) as WritableStream, Readable.toWeb(stdout) as ReadableStream); + const connection = new AcpConnection(clientApp(handlers).connect(stream), child); + child.stderr?.setEncoding('utf8'); + child.stderr?.on('data', (chunk: string) => { + connection.stderr = (connection.stderr + chunk).slice(-STDERR_TAIL); + for (const line of chunk.split(/\r?\n/)) { + if (line.trim()) { + onLog?.(line); + } + } + }); + // A failed spawn (ENOENT, EACCES) and an exit both end the connection, + // which rejects whatever request was waiting with the reason. + child.on('error', (error) => connection.fail(new Error(`Could not start ${launch.command}: ${error.message}`))); + child.on('exit', (code, signal) => { + const tail = connection.stderr.trim().split(/\r?\n/).slice(-3).join(' ').trim(); + const how = signal ? `was stopped (${signal})` : `exited with code ${code ?? 'unknown'}`; + connection.fail(new Error(`The agent ${how}.${tail ? ` ${tail}` : ''}`)); + }); + stdin.on('error', () => undefined); + return connection; + } + + /** Connects to an agent app in this process (tests). */ + static inProcess(agent: AgentApp, handlers: AcpClientHandlers): AcpConnection { + return new AcpConnection(clientApp(handlers).connect(agent), null); + } + + get isClosed(): boolean { + return this.closed; + } + + /** The last lines the agent wrote to stderr (its log), for error messages. */ + get stderrTail(): string { + return this.stderr; + } + + onClose(listener: (error: Error | null) => void): void { + if (this.closed) { + listener(this.exitError); + return; + } + this.closeListeners.push(listener); + } + + initialize(): Promise { + return this.explain(this.connection.agent.request(methods.agent.initialize, { + protocolVersion: ACP_PROTOCOL_VERSION, + clientInfo: { name: 'code-xr-ide', title: 'Code-XR IDE', version: '0.1.0' }, + clientCapabilities: { + fs: { readTextFile: true, writeTextFile: true }, + terminal: true, + auth: { terminal: true }, + }, + })); + } + + authenticate(methodId: string): Promise { + return this.explain(this.connection.agent.request(methods.agent.authenticate, { methodId })); + } + + newSession(cwd: string, mcpServers: readonly McpServer[]): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.new, { cwd, mcpServers: [...mcpServers] })); + } + + loadSession(sessionId: string, cwd: string, mcpServers: readonly McpServer[]): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.load, { sessionId, cwd, mcpServers: [...mcpServers] })); + } + + prompt(sessionId: string, prompt: readonly ContentBlock[]): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.prompt, { sessionId, prompt: [...prompt] })); + } + + cancel(sessionId: string): Promise { + return this.connection.agent.notify(methods.agent.session.cancel, { sessionId }); + } + + async setMode(sessionId: string, modeId: string): Promise { + await this.explain(this.connection.agent.request(methods.agent.session.setMode, { sessionId, modeId })); + } + + setConfigOption(sessionId: string, configId: string, value: string | boolean): Promise { + return this.explain(this.connection.agent.request( + methods.agent.session.setConfigOption, + typeof value === 'boolean' ? { sessionId, configId, type: 'boolean', value } : { sessionId, configId, value }, + )); + } + + /** Closes the connection and stops the process. Safe to call more than once. */ + close(): void { + this.connection.close(); + this.killProcess(); + this.markClosed(this.exitError); + } + + private fail(error: Error): void { + this.exitError ??= error; + this.connection.close(error); + this.markClosed(this.exitError); + } + + private killProcess(): void { + const child = this.child; + if (!child || child.exitCode !== null || child.signalCode !== null) { + return; + } + try { + child.kill(); + } catch { + // Already gone. + } + // An agent that ignores SIGTERM is killed for good a moment later. + const timer = setTimeout(() => { + if (child.exitCode === null && child.signalCode === null) { + try { + child.kill('SIGKILL'); + } catch { + // Already gone. + } + } + }, 3000); + timer.unref(); + } + + private markClosed(error: Error | null): void { + if (this.closed) { + return; + } + this.closed = true; + this.killProcess(); + for (const listener of this.closeListeners.splice(0)) { + listener(error); + } + } +} diff --git a/apps/ide/src/main/agentSessions/acpMapping.ts b/apps/ide/src/main/agentSessions/acpMapping.ts new file mode 100644 index 000000000..bedb07bc8 --- /dev/null +++ b/apps/ide/src/main/agentSessions/acpMapping.ts @@ -0,0 +1,351 @@ +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import type { + AuthMethod, + AvailableCommand, + ContentBlock, + SessionConfigOption, + SessionModeState, + SessionUpdate, + StopReason, + ToolCallContent, + ToolCallLocation, + ToolCallUpdate, +} from '@agentclientprotocol/sdk'; +import type { + AuthMethodView, + ConfigOptionView, + ModeView, + PlanEntryView, + SessionEvent, + SlashCommandView, + ToolContentView, + ToolKind, + ToolStatus, + TranscriptItem, +} from '../../shared/agentSession.ts'; + +/** + * AF1: the pure translation between the Agent Client Protocol (v1) and the + * IDE's transcript model (`shared/agentSession.ts`). Every `session/update` + * kind the agent may send becomes zero or more `SessionEvent`s; unknown kinds + * and content the chat cannot show are dropped rather than thrown on, so a + * newer agent never breaks an older IDE. No I/O here: the connection and the + * service feed it, and the unit tests drive it directly. + */ + +/** What a terminal the IDE runs for an agent holds right now (so a tool card shows it at once). */ +export interface TerminalSnapshot { + readonly output: string; + readonly exitCode: number | null; + readonly truncated: boolean; +} + +export interface MappingContext { + /** A fresh id for notices. */ + newId(): string; + /** The output so far of a terminal the IDE runs for this session. */ + terminal?(terminalId: string): TerminalSnapshot | undefined; +} + +const TOOL_KINDS: ReadonlySet = new Set(['read', 'edit', 'delete', 'move', 'search', 'execute', 'think', 'fetch', 'switch_mode', 'other']); +const TOOL_STATUSES: ReadonlySet = new Set(['pending', 'in_progress', 'completed', 'failed']); +const MAX_RAW_INPUT = 8000; + +export function toolKindOf(value: unknown): ToolKind { + return typeof value === 'string' && TOOL_KINDS.has(value) ? (value as ToolKind) : 'other'; +} + +function toolStatusOf(value: unknown): ToolStatus | undefined { + return typeof value === 'string' && TOOL_STATUSES.has(value) ? (value as ToolStatus) : undefined; +} + +/** A content block as chat text: text as is, links as Markdown links, anything else as a short placeholder. */ +export function contentBlockText(block: ContentBlock): string { + switch (block.type) { + case 'text': + return block.text; + case 'resource_link': + return `[${block.title ?? block.name}](${block.uri})`; + case 'resource': + return 'text' in block.resource ? block.resource.text : `[${block.resource.uri}]`; + case 'image': + return '[image]'; + case 'audio': + return '[audio]'; + default: + return ''; + } +} + +export function mapToolContent(content: readonly ToolCallContent[], ctx: MappingContext): ToolContentView[] { + const views: ToolContentView[] = []; + for (const item of content) { + if (item.type === 'content') { + const text = contentBlockText(item.content); + if (text) { + views.push({ type: 'text', text }); + } + } else if (item.type === 'diff') { + views.push({ type: 'diff', path: item.path, oldText: item.oldText ?? null, newText: item.newText }); + } else if (item.type === 'terminal') { + const snapshot = ctx.terminal?.(item.terminalId); + views.push({ + type: 'terminal', + terminalId: item.terminalId, + output: snapshot?.output ?? '', + exitCode: snapshot?.exitCode ?? null, + ...(snapshot?.truncated ? { truncated: true } : {}), + }); + } + } + return views; +} + +function mapLocations(locations: readonly ToolCallLocation[]): { path: string; line?: number }[] { + return locations.map((location) => (typeof location.line === 'number' ? { path: location.path, line: location.line } : { path: location.path })); +} + +/** The tool's raw input as compact JSON for the expanded card, capped. */ +export function rawInputText(value: unknown): string | undefined { + if (value === undefined || value === null) { + return undefined; + } + let text: string; + try { + text = typeof value === 'string' ? value : JSON.stringify(value); + } catch { + return undefined; + } + return text.length > MAX_RAW_INPUT ? `${text.slice(0, MAX_RAW_INPUT)}...` : text; +} + +/** A `tool_call` or `tool_call_update` (also the `toolCall` of a permission request) as a `tool` event. */ +export function toolEvent(update: ToolCallUpdate, ctx: MappingContext, isNew: boolean): Extract { + const status = toolStatusOf(update.status); + const rawInput = rawInputText(update.rawInput); + return { + type: 'tool', + id: update.toolCallId, + ...(typeof update.title === 'string' && update.title ? { title: update.title } : {}), + ...(update.kind ? { toolKind: toolKindOf(update.kind) } : isNew ? { toolKind: 'other' as const } : {}), + ...(status ? { status } : isNew ? { status: 'pending' as const } : {}), + ...(update.locations ? { locations: mapLocations(update.locations) } : {}), + ...(update.content ? { content: mapToolContent(update.content, ctx) } : {}), + ...(rawInput !== undefined ? { rawInput } : {}), + }; +} + +export function mapCommands(commands: readonly AvailableCommand[]): SlashCommandView[] { + return commands.map((command) => ({ + name: command.name, + description: command.description, + ...(command.input && typeof command.input.hint === 'string' ? { hint: command.input.hint } : {}), + })); +} + +export function mapModes(modes: SessionModeState): { current: string; available: ModeView[] } { + return { + current: modes.currentModeId, + available: modes.availableModes.map((mode) => ({ id: mode.id, name: mode.name, ...(mode.description ? { description: mode.description } : {}) })), + }; +} + +/** Config options the chat shows as pickers. A boolean option becomes an On / Off choice (`true` / `false`). */ +export function mapConfigOptions(options: readonly SessionConfigOption[]): ConfigOptionView[] { + const views: ConfigOptionView[] = []; + for (const option of options) { + const base = { id: option.id, name: option.name, ...(option.category ? { category: option.category } : {}) }; + if (option.type === 'boolean') { + views.push({ ...base, current: String(option.currentValue), values: [{ id: 'true', name: 'On' }, { id: 'false', name: 'Off' }] }); + continue; + } + if (option.type !== 'select') { + continue; + } + const values: { id: string; name: string; description?: string }[] = []; + for (const entry of option.options) { + const group = 'group' in entry ? entry.options : [entry]; + for (const value of group) { + values.push({ id: value.value, name: value.name, ...(value.description ? { description: value.description } : {}) }); + } + } + views.push({ ...base, current: option.currentValue, values }); + } + return views; +} + +function noticeLevel(severity: string): 'info' | 'warning' | 'error' { + return severity === 'warning' || severity === 'error' ? severity : 'info'; +} + +/** One `session/update` as the events that change the transcript. */ +export function mapSessionUpdate(update: SessionUpdate, ctx: MappingContext): SessionEvent[] { + switch (update.sessionUpdate) { + case 'agent_message_chunk': { + const text = contentBlockText(update.content); + return text ? [{ type: 'assistant-chunk', text }] : []; + } + case 'agent_thought_chunk': { + const text = contentBlockText(update.content); + return text ? [{ type: 'thought-chunk', text }] : []; + } + case 'tool_call': + return [toolEvent(update, ctx, true)]; + case 'tool_call_update': + return [toolEvent(update, ctx, false)]; + case 'plan': + return [{ type: 'plan', entries: update.entries.map((entry): PlanEntryView => ({ content: entry.content, priority: entry.priority, status: entry.status })) }]; + case 'available_commands_update': + return [{ type: 'commands', commands: mapCommands(update.availableCommands) }]; + case 'current_mode_update': + return [{ type: 'modes', current: update.currentModeId }]; + case 'config_option_update': + 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 'notice': { + const text = update.description ? `${update.title}: ${update.description}` : update.title; + return [{ type: 'notice', id: ctx.newId(), level: noticeLevel(update.severity), text }]; + } + default: + // user_message_chunk (the IDE records the person's messages itself), plan_update and + // subagent updates (capabilities the IDE does not advertise), compaction, and any kind + // a newer protocol adds. + return []; + } +} + +type StopReasonView = Extract['stopReason']; +const STOP_REASONS: ReadonlySet = new Set(['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled']); + +export function stopReasonOf(value: unknown): StopReasonView { + return typeof value === 'string' && STOP_REASONS.has(value) ? (value as StopReasonView) : 'end_turn'; +} + +// ---- Authentication --------------------------------------------------------- + +/** A login method as the agent advertised it, with what the IDE needs to run it. */ +export interface AuthMethodSpec { + readonly view: AuthMethodView; + /** Terminal methods: the arguments to run the agent's own command with. */ + readonly args?: readonly string[]; + /** Terminal methods: a different command to run (the `terminal-auth` hint). */ + readonly command?: string; + readonly env?: Readonly>; +} + +function stringArray(value: unknown): string[] | undefined { + return Array.isArray(value) && value.every((item) => typeof item === 'string') ? (value as string[]) : undefined; +} + +function stringRecord(value: unknown): Record | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined; + } + const entries = Object.entries(value as Record).filter((entry): entry is [string, string] => typeof entry[1] === 'string'); + return Object.fromEntries(entries); +} + +/** + * The agent's `authMethods`: `type: "terminal"` (or a `terminal-auth` hint in + * `_meta`) runs the agent's own login in a terminal, an environment-variable + * method needs a key in the agent's environment, anything else is handled by + * the agent itself through `authenticate`. + */ +export function mapAuthMethods(methods: readonly AuthMethod[] | readonly unknown[] | undefined): AuthMethodSpec[] { + const specs: AuthMethodSpec[] = []; + for (const raw of methods ?? []) { + if (!raw || typeof raw !== 'object') { + continue; + } + const method = raw as Record; + if (typeof method['id'] !== 'string' || typeof method['name'] !== 'string') { + continue; + } + const meta = method['_meta'] && typeof method['_meta'] === 'object' ? (method['_meta'] as Record) : {}; + const hint = meta['terminal-auth'] && typeof meta['terminal-auth'] === 'object' ? (meta['terminal-auth'] as Record) : null; + const declared = method['type']; + const type: AuthMethodView['type'] = declared === 'terminal' || hint ? 'terminal' : declared === 'env_var' || declared === 'env' ? 'env' : 'agent'; + const view: AuthMethodView = { + id: method['id'], + name: method['name'], + type, + ...(typeof method['description'] === 'string' && method['description'] ? { description: method['description'] } : {}), + }; + const args = stringArray(method['args']) ?? stringArray(hint?.['args']); + const env = stringRecord(method['env']) ?? stringRecord(hint?.['env']); + const command = typeof hint?.['command'] === 'string' ? hint['command'] : undefined; + specs.push({ view, ...(args ? { args } : {}), ...(env ? { env } : {}), ...(command ? { command } : {}) }); + } + return specs; +} + +/** JSON-RPC `-32000` is ACP's "authentication required"; some agents only say it in words. */ +export function isAuthRequiredError(error: unknown): boolean { + if (error && typeof error === 'object' && (error as { code?: unknown }).code === -32000) { + return true; + } + const message = errorMessage(error); + return /authenticat|not logged in|log ?in required|sign ?in required|please (log|sign) ?in|unauthori[sz]ed/i.test(message); +} + +export function errorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + if (error && typeof error === 'object' && typeof (error as { message?: unknown }).message === 'string') { + return (error as { message: string }).message; + } + return String(error); +} + +// ---- Prompts and files ------------------------------------------------------ + +/** An attachment after the main process resolved and read it. */ +export type ResolvedAttachment = + | { readonly kind: 'file'; readonly absolutePath: string; readonly relativePath: string; readonly text: string | null } + | { readonly kind: 'selection'; readonly absolutePath: string; readonly relativePath: string; readonly startLine?: number; readonly endLine?: number; readonly text: string }; + +/** The label the transcript shows for an attachment, as the chat's composer writes it. */ +export function attachmentLabel(attachment: { readonly kind: 'file' | 'selection'; readonly path: string; readonly startLine?: number; readonly endLine?: number }): string { + return attachment.kind === 'selection' && attachment.startLine !== undefined + ? `${attachment.path}:${attachment.startLine}-${attachment.endLine ?? attachment.startLine}` + : attachment.path; +} + +/** + * 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. + */ +export function buildPromptBlocks(text: string, attachments: readonly ResolvedAttachment[], embeddedContext: boolean): ContentBlock[] { + const blocks: ContentBlock[] = [{ type: 'text', text }]; + for (const attachment of attachments) { + const uri = pathToFileURL(attachment.absolutePath).href; + if (attachment.kind === 'file') { + if (embeddedContext && attachment.text !== null) { + blocks.push({ type: 'resource', resource: { uri, text: attachment.text, mimeType: 'text/plain' } }); + } else { + blocks.push({ type: 'resource_link', uri, name: path.basename(attachment.absolutePath) }); + } + continue; + } + 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\`\`\`` }); + } + return blocks; +} + +/** `fs/read_text_file`'s `line` (1-based) and `limit`. */ +export function sliceLines(text: string, line?: number | null, limit?: number | null): string { + if ((line === undefined || line === null) && (limit === undefined || limit === null)) { + return text; + } + const lines = text.split('\n'); + const start = Math.max(0, (line ?? 1) - 1); + const end = limit === undefined || limit === null ? lines.length : start + Math.max(0, limit); + return lines.slice(start, end).join('\n'); +} diff --git a/apps/ide/src/main/agentSessions/agentCatalog.ts b/apps/ide/src/main/agentSessions/agentCatalog.ts new file mode 100644 index 000000000..35c0e49e5 --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentCatalog.ts @@ -0,0 +1,415 @@ +import { randomUUID } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { AGENT_PRESET_IDS, type AcpAgentDefinition, type AgentAvailability, type AgentPresetId, type AgentView } from '../../shared/agentSession.ts'; +import type { AgentLaunch } from './acpConnection.ts'; +import type { AuthMethodSpec } from './acpMapping.ts'; + +/** + * AF1/AF2: the agents a chat can use. Three presets the IDE knows how to + * launch (Claude Code, Codex and Gemini CLI, each through the vendor's own + * ACP entry point), the person's custom ACP agents (stored as JSON), and the + * built-in agent's profiles (epic #189), listed for the picker only. + * + * A preset is found, in order, as a package the IDE installed under + * `/agent-packages` (its bin script run by Electron's own Node, + * `ELECTRON_RUN_AS_NODE=1`, so no system Node is needed), or as its command + * on PATH. Nothing is downloaded here: a missing agent says how to install it, + * and agentInstaller.ts installs it on the person's request. + * + * Agents get a minimal environment: the variables a CLI needs to find its + * home, its config and the network, the vendor's own key variables for a + * preset, and the definition's `env`. The IDE never reads or stores the + * agents' OAuth tokens; each vendor's CLI keeps its own. + */ + +interface PresetSpec { + readonly id: AgentPresetId; + readonly name: string; + readonly description: string; + readonly packageName: string; + readonly bin: string; + readonly args: readonly string[]; + /** The vendor's own environment variables (API keys, endpoints) passed through to the agent. */ + readonly passEnv: RegExp; +} + +export const PRESETS: readonly PresetSpec[] = [ + { + id: 'claude', + name: 'Claude Code', + description: 'Anthropic\'s Claude Code through its ACP adapter. Sign in with your Claude account or use an API key.', + packageName: '@agentclientprotocol/claude-agent-acp', + bin: 'claude-agent-acp', + args: [], + passEnv: /^(ANTHROPIC_|CLAUDE_)/i, + }, + { + id: 'codex', + name: 'Codex', + description: 'OpenAI\'s Codex through its ACP adapter. Sign in with ChatGPT or use an API key.', + packageName: '@agentclientprotocol/codex-acp', + bin: 'codex-acp', + args: [], + passEnv: /^(OPENAI_|CODEX_)/i, + }, + { + id: 'gemini', + name: 'Gemini CLI', + description: 'Google\'s Gemini CLI in ACP mode. Sign in with Google or use an API key.', + packageName: '@google/gemini-cli', + bin: 'gemini', + args: ['--acp'], + passEnv: /^(GEMINI_|GOOGLE_)/i, + }, +]; + +/** What every agent may inherit from the IDE's environment. */ +const BASE_ENV = /^(PATH|PATHEXT|HOME|USERPROFILE|HOMEDRIVE|HOMEPATH|APPDATA|LOCALAPPDATA|PROGRAMDATA|SYSTEMROOT|SYSTEMDRIVE|WINDIR|COMSPEC|TEMP|TMP|TMPDIR|LANG|LANGUAGE|LC_ALL|LC_CTYPE|USER|USERNAME|LOGNAME|SHELL|XDG_CONFIG_HOME|XDG_DATA_HOME|XDG_CACHE_HOME|XDG_STATE_HOME|XDG_RUNTIME_DIR|HTTPS?_PROXY|NO_PROXY|ALL_PROXY|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|SSL_CERT_DIR)$/i; + +/** The environment an agent starts with. */ +export function agentEnvironment(base: Readonly>, passEnv: RegExp | null, extra: Readonly>): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(base)) { + if (value !== undefined && (BASE_ENV.test(key) || (passEnv !== null && passEnv.test(key)))) { + env[key] = value; + } + } + return { ...env, ...extra }; +} + +export interface FileProbe { + /** True when `file` exists and can be run (on Windows: exists). */ + isExecutable(file: string): Promise; + readText(file: string): Promise; +} + +export const diskProbe: FileProbe = { + async isExecutable(file) { + try { + const stat = await fs.promises.stat(file); + if (!stat.isFile()) { + return false; + } + if (process.platform !== 'win32') { + await fs.promises.access(file, fs.constants.X_OK); + } + return true; + } catch { + return false; + } + }, + async readText(file) { + try { + return await fs.promises.readFile(file, 'utf8'); + } catch { + return null; + } + }, +}; + +/** Looks `name` up on PATH (with PATHEXT on Windows), as a shell would. */ +export async function findOnPath(name: string, env: Readonly>, platform: NodeJS.Platform, probe: FileProbe): Promise { + const api = platform === 'win32' ? path.win32 : path.posix; + const pathValue = Object.entries(env).find(([key]) => (platform === 'win32' ? key.toUpperCase() === 'PATH' : key === 'PATH'))?.[1] ?? ''; + const extensions = platform === 'win32' + ? ['', ...(Object.entries(env).find(([key]) => key.toUpperCase() === 'PATHEXT')?.[1] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean).map((ext) => ext.toLowerCase())] + : ['']; + for (const dir of pathValue.split(platform === 'win32' ? ';' : ':')) { + if (!dir.trim()) { + continue; + } + for (const ext of extensions) { + if (platform === 'win32' && ext === '' && !/\.[A-Za-z0-9]+$/.test(name)) { + continue; + } + const candidate = api.join(dir.replace(/^"|"$/g, ''), name + ext); + if (await probe.isExecutable(candidate)) { + return candidate; + } + } + } + return null; +} + +/** The bin script a package declares under `binName` (or its only bin). */ +async function packageBin(packageDir: string, binName: string, probe: FileProbe): Promise { + const text = await probe.readText(path.join(packageDir, 'package.json')); + if (text === null) { + return null; + } + let manifest: { bin?: unknown }; + try { + manifest = JSON.parse(text) as { bin?: unknown }; + } catch { + return null; + } + const bin = manifest.bin; + let relative: string | undefined; + if (typeof bin === 'string') { + relative = bin; + } else if (bin && typeof bin === 'object') { + const entries = bin as Record; + const named = entries[binName]; + relative = typeof named === 'string' ? named : (Object.values(entries).find((value): value is string => typeof value === 'string')); + } + return relative ? path.join(packageDir, relative) : null; +} + +export type Resolution = + | { readonly found: true; readonly launch: AgentLaunch; readonly via: string } + | { readonly found: false; readonly detail: string }; + +export interface CatalogOptions { + /** `/agent-packages`: packages the IDE installed (AF2). */ + readonly packagesDir: string; + readonly store: { get(key: string): T | undefined; update(key: string, value: unknown): Promise }; + readonly env: Readonly>; + readonly platform: NodeJS.Platform; + /** Electron's own executable, which runs JavaScript bins with `ELECTRON_RUN_AS_NODE=1`. */ + readonly execPath: string; + readonly probe?: FileProbe; + /** The built-in agent's profiles (epic #189). */ + readonly builtinProfiles: () => Promise; +} + +/** What the last probe or chat learned about an agent. */ +export interface AgentState { + readonly availability: AgentAvailability; + readonly detail?: string; + readonly authMethods?: readonly AuthMethodSpec[]; +} + +const CUSTOM_KEY = 'customAgents'; +const CUSTOM_ID = /^custom-[a-f0-9]{8}$/; +const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; + +/** A custom agent from the renderer, checked field by field. */ +export function parseCustomAgent(input: unknown): Omit { + if (!input || typeof input !== 'object' || Array.isArray(input)) { + throw new Error('Invalid agent.'); + } + const value = input as Record; + const name = typeof value['name'] === 'string' ? value['name'].trim() : ''; + if (!name || name.length > 80) { + throw new Error('An agent needs a name of at most 80 characters.'); + } + const command = typeof value['command'] === 'string' ? value['command'].trim() : ''; + if (!command || command.length > 1024 || command.includes('\0')) { + throw new Error('An agent needs a command: a program name on PATH or an absolute path.'); + } + const rawArgs = value['args'] ?? []; + if (!Array.isArray(rawArgs) || rawArgs.length > 64 || !rawArgs.every((arg) => typeof arg === 'string' && arg.length <= 4096 && !arg.includes('\0'))) { + throw new Error('Arguments must be a list of at most 64 strings.'); + } + const rawEnv = value['env'] ?? {}; + if (!rawEnv || typeof rawEnv !== 'object' || Array.isArray(rawEnv)) { + throw new Error('The environment must be a map of names to values.'); + } + const envEntries = Object.entries(rawEnv as Record); + if (envEntries.length > 64 || !envEntries.every(([key, val]) => ENV_NAME.test(key) && typeof val === 'string' && val.length <= 8192 && !val.includes('\0'))) { + throw new Error('Environment variables need names like MY_VAR and string values.'); + } + const description = typeof value['description'] === 'string' && value['description'].trim() ? value['description'].trim().slice(0, 300) : 'A custom ACP agent.'; + return { + name, + command, + args: rawArgs as string[], + ...(envEntries.length ? { env: Object.fromEntries(envEntries) as Record } : {}), + description, + }; +} + +function isDefinition(value: unknown): value is AcpAgentDefinition { + if (!value || typeof value !== 'object') { + return false; + } + const definition = value as AcpAgentDefinition; + return typeof definition.id === 'string' && CUSTOM_ID.test(definition.id) && typeof definition.name === 'string' && typeof definition.command === 'string' && Array.isArray(definition.args); +} + +/** Quotes one part of a `cmd.exe /d /s /c "..."` line. */ +function cmdQuote(part: string): string { + if (/["%]/.test(part)) { + throw new Error(`Cannot pass ${part} to cmd.exe safely.`); + } + return /[\s&|<>^()]/.test(part) || part === '' ? `"${part}"` : part; +} + +export class AgentCatalog { + private readonly options: CatalogOptions; + private readonly probe: FileProbe; + private readonly states = new Map(); + + constructor(options: CatalogOptions) { + this.options = options; + this.probe = options.probe ?? diskProbe; + } + + customAgents(): AcpAgentDefinition[] { + const raw = this.options.store.get(CUSTOM_KEY); + return Array.isArray(raw) ? raw.filter(isDefinition) : []; + } + + /** The definition behind an `acp:` ref; null for anything else. */ + definition(ref: string): AcpAgentDefinition | null { + if (!ref.startsWith('acp:')) { + return null; + } + const id = ref.slice(4); + const preset = PRESETS.find((candidate) => candidate.id === id); + if (preset) { + return { id: preset.id, name: preset.name, command: preset.bin, args: preset.args, preset: preset.id, description: preset.description }; + } + return this.customAgents().find((agent) => agent.id === id) ?? null; + } + + state(ref: string): AgentState | undefined { + return this.states.get(ref); + } + + setState(ref: string, state: AgentState): void { + const previous = this.states.get(ref); + // A failed `session/new` must not forget the login methods `initialize` advertised. + this.states.set(ref, state.authMethods || !previous?.authMethods ? state : { ...state, authMethods: previous.authMethods }); + } + + /** How to start an agent, or why it cannot be found. */ + async resolve(definition: AcpAgentDefinition): Promise { + const { env, platform, execPath, packagesDir } = this.options; + const preset = definition.preset ? PRESETS.find((candidate) => candidate.id === definition.preset) : undefined; + const agentEnv = (extra: Record = {}): Record => agentEnvironment(env, preset?.passEnv ?? null, { ...(definition.env ?? {}), ...extra }); + const viaNode = (script: string, via: string): Resolution => ({ + found: true, + via, + launch: { command: execPath, args: [script, ...definition.args], env: agentEnv({ ELECTRON_RUN_AS_NODE: '1' }) }, + }); + + if (preset) { + const installed = await packageBin(path.join(packagesDir, 'node_modules', ...preset.packageName.split('/')), preset.bin, this.probe); + if (installed && (await this.probe.readText(installed)) !== null) { + return viaNode(installed, `${preset.packageName} (installed by the IDE)`); + } + } + + const api = platform === 'win32' ? path.win32 : path.posix; + let found: string | null; + if (api.isAbsolute(definition.command)) { + found = (await this.probe.isExecutable(definition.command)) ? definition.command : null; + } else if (/[\\/]/.test(definition.command)) { + return { found: false, detail: `${definition.command} is a relative path; use a program name on PATH or an absolute path.` }; + } else { + found = await findOnPath(definition.command, env, platform, this.probe); + } + if (!found) { + return { + found: false, + detail: preset + ? `${preset.name} is not installed. Press Install, or install it yourself with: npm install -g ${preset.packageName}` + : `${definition.command} was not found. Check the command, or use an absolute path.`, + }; + } + if (platform === 'win32' && /\.(cmd|bat)$/i.test(found)) { + // A .cmd shim cannot be spawned without a shell. An npm shim's script sits next to it. + if (preset) { + const script = await packageBin(api.join(api.dirname(found), 'node_modules', ...preset.packageName.split('/')), preset.bin, this.probe); + if (script && (await this.probe.readText(script)) !== null) { + return viaNode(script, found); + } + } + const line = [found, ...definition.args].map(cmdQuote).join(' '); + return { found: true, via: found, launch: { command: env['ComSpec'] ?? env['COMSPEC'] ?? 'cmd.exe', args: ['/d', '/s', '/c', `"${line}"`], env: agentEnv(), verbatimArguments: true } }; + } + return { found: true, via: found, launch: { command: found, args: [...definition.args], env: agentEnv() } }; + } + + /** AF2: the version of a preset the IDE installed under its own folder, or null. */ + async installedVersion(presetId: AgentPresetId): Promise { + const preset = PRESETS.find((candidate) => candidate.id === presetId); + if (!preset) { + return null; + } + const text = await this.probe.readText(path.join(this.options.packagesDir, 'node_modules', ...preset.packageName.split('/'), 'package.json')); + if (text === null) { + return null; + } + try { + const version = (JSON.parse(text) as { version?: unknown }).version; + return typeof version === 'string' && /^\d+\.\d+\.\d+/.test(version) ? version.slice(0, 64) : null; + } catch { + return null; + } + } + + /** Forgets what probes learned about an agent (after it was installed, updated or removed). */ + forget(ref: string): void { + this.states.delete(ref); + } + + async view(definition: AcpAgentDefinition): Promise { + const ref = `acp:${definition.id}`; + const resolution = await this.resolve(definition); + const state = this.states.get(ref); + const installedVersion = definition.preset ? await this.installedVersion(definition.preset) : null; + const base = { + ...(installedVersion ? { installedVersion } : {}), + ref, + name: definition.name, + kind: 'acp' as const, + description: definition.description, + ...(definition.preset ? { preset: definition.preset } : {}), + ...(state?.authMethods?.length ? { authMethods: state.authMethods.map((method) => method.view) } : {}), + }; + if (!resolution.found) { + return { ...base, availability: 'missing', detail: resolution.detail }; + } + return { ...base, availability: state?.availability ?? 'available', ...(state?.detail ? { detail: state.detail } : {}) }; + } + + /** Every agent for the picker: presets, custom agents, then the built-in agent's profiles. */ + async list(): Promise { + const acp = [...AGENT_PRESET_IDS.map((id) => this.definition(`acp:${id}`)), ...this.customAgents()].filter((definition): definition is AcpAgentDefinition => definition !== null); + const views = await Promise.all(acp.map((definition) => this.view(definition))); + let profiles: readonly { readonly id: string; readonly name: string }[] = []; + try { + profiles = await this.options.builtinProfiles(); + } catch { + profiles = []; + } + for (const profile of profiles) { + views.push({ + ref: `builtin:${profile.id}`, + name: profile.name, + kind: 'builtin', + description: 'The IDE\'s own agent, with a provider and API key set up in the Agents view.', + availability: 'available', + }); + } + return views; + } + + async builtinView(ref: string): Promise { + return (await this.list()).find((view) => view.ref === ref && view.kind === 'builtin') ?? null; + } + + async saveCustom(input: unknown, id?: unknown): Promise { + const parsed = parseCustomAgent(input); + const agents = this.customAgents(); + if (id !== undefined && id !== null && (typeof id !== 'string' || !agents.some((agent) => agent.id === id))) { + throw new Error('That agent no longer exists.'); + } + const definition: AcpAgentDefinition = { ...parsed, id: typeof id === 'string' ? id : `custom-${randomUUID().replace(/-/g, '').slice(0, 8)}` }; + const next = typeof id === 'string' ? agents.map((agent) => (agent.id === id ? definition : agent)) : [...agents, definition]; + await this.options.store.update(CUSTOM_KEY, next); + this.states.delete(`acp:${definition.id}`); + return definition; + } + + async removeCustom(id: unknown): Promise { + if (typeof id !== 'string' || !CUSTOM_ID.test(id)) { + throw new Error('Only a custom agent can be removed.'); + } + await this.options.store.update(CUSTOM_KEY, this.customAgents().filter((agent) => agent.id !== id)); + this.states.delete(`acp:${id}`); + } +} diff --git a/apps/ide/src/main/agentSessions/agentInstaller.ts b/apps/ide/src/main/agentSessions/agentInstaller.ts new file mode 100644 index 000000000..ae547cf0e --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentInstaller.ts @@ -0,0 +1,693 @@ +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { AGENT_PRESET_IDS, type AgentPresetId, type InstallDescription } from '../../shared/agentSession.ts'; +import { PRESETS, diskProbe, findOnPath, type FileProbe } from './agentCatalog.ts'; + +/** + * AF2 (#267): installs a preset's ACP adapter for the person, on request. + * + * Nothing here runs on its own. `describe` reads the npm registry only when + * the person pressed Install (or Update): the version, licence, size, + * repository and publication date of the adapter, its direct dependencies, + * the native binaries they bring for this platform and which packages run + * install scripts. `install` then runs the system's npm, after the person + * confirmed that exact description in a native dialog, into + * `/agent-packages` (a private package.json of the IDE's own): no + * global write, no change to the person's projects or npm configuration. + * + * Why the system npm: an adapter is an npm package whose dependency tree + * (exact versions, optional platform packages, install scripts) only npm + * resolves faithfully. Re-implementing that (registry metadata, semver + * ranges, tarball extraction, `os`/`cpu`/`libc` selection, lifecycle + * scripts) would be a second, weaker npm, and bundling npm would add a large + * dependency the IDE does not otherwise need. A person who runs coding agents + * from npm has Node.js; one who does not gets a clear message pointing to + * nodejs.org. Once installed, the adapter runs with the IDE's own Electron as + * Node (agentCatalog.ts), so only the install needs npm. npm reads the + * person's own configuration (`.npmrc`, proxy, registry, CA), so it works + * behind the same proxy their terminal does. + * + * Electron-free: the registry is read through an injected `fetchJson`, and + * the tests use a local fake registry and a fake npm on PATH. + */ + +export const DEFAULT_REGISTRY = 'https://registry.npmjs.org/'; +export const NODE_DOWNLOAD_URL = 'https://nodejs.org/en/download'; + +/** What a manifest from the registry looks like, as far as this file reads it. */ +interface Manifest { + readonly name?: unknown; + readonly version?: unknown; + readonly license?: unknown; + readonly repository?: unknown; + readonly homepage?: unknown; + readonly dependencies?: unknown; + readonly optionalDependencies?: unknown; + readonly scripts?: unknown; + readonly hasInstallScript?: unknown; + readonly os?: unknown; + readonly cpu?: unknown; + readonly libc?: unknown; + readonly dist?: { readonly unpackedSize?: unknown }; +} + +export interface InstallerOptions { + /** `/agent-packages`. */ + readonly packagesDir: string; + /** GETs a registry URL and returns its JSON; throws on a failed request. */ + readonly fetchJson: (url: string) => Promise; + readonly env: Readonly>; + readonly platform: NodeJS.Platform; + readonly arch: string; + readonly probe?: FileProbe; + /** How long a description stays valid for the install that follows it, ms. */ + readonly descriptionTtlMs?: number; + /** How long npm may run, ms. */ + readonly timeoutMs?: number; + readonly now?: () => number; +} + +export type LineSink = (line: string) => void; + +const MAX_FETCHES = 24; +const MAX_LINE = 400; +const KEEP_LINES = 30; +const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall']; +const OS_TOKENS = /(^|[-_@/])(linux|darwin|macos|win32|windows|freebsd|android|sunos|aix)([-_.]|$)/i; + +const PACKAGE_JSON = { + name: 'codexr-agent-packages', + private: true, + description: 'Coding agent adapters installed by Code-XR IDE at the person\'s request. Managed by the IDE.', + dependencies: {}, +}; + +/** The preset a renderer argument names, or an error. */ +export function parsePresetId(value: unknown): AgentPresetId { + if (typeof value !== 'string' || !(AGENT_PRESET_IDS as readonly string[]).includes(value)) { + throw new Error('Only Claude Code, Codex and Gemini CLI can be installed here.'); + } + return value as AgentPresetId; +} + +/** The registry npm uses, from its environment variables; only https (or a local http one, for tests). */ +export function registryOf(env: Readonly>): string { + const raw = env['npm_config_registry'] ?? env['NPM_CONFIG_REGISTRY'] ?? DEFAULT_REGISTRY; + let url: URL; + try { + url = new URL(raw); + } catch { + return DEFAULT_REGISTRY; + } + const local = url.protocol === 'http:' && (url.hostname === '127.0.0.1' || url.hostname === 'localhost'); + if (url.protocol !== 'https:' && !local) { + return DEFAULT_REGISTRY; + } + return url.href.endsWith('/') ? url.href : `${url.href}/`; +} + +/** `@scope/name` as the registry's path segment. */ +function registryPath(name: string): string { + return name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name); +} + +/** `npm:@openai/codex@0.1.0-linux-x64` -> its real name and spec; other specs unchanged. */ +export function resolveAlias(name: string, spec: string): { readonly name: string; readonly spec: string } { + if (!spec.startsWith('npm:')) { + return { name, spec }; + } + const target = spec.slice(4); + const at = target.lastIndexOf('@'); + return at > 0 ? { name: target.slice(0, at), spec: target.slice(at + 1) } : { name: target, spec: 'latest' }; +} + +const VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/; + +/** True when `spec` is one exact version. */ +export function isExactVersion(spec: string): boolean { + return VERSION.test(spec.trim()); +} + +/** + * Whether `version` satisfies `spec`, for the forms adapters use (exact, + * `^`, `~`, `*`, `x`); null for a range this does not understand. + */ +export function satisfies(version: string, spec: string): boolean | null { + const v = VERSION.exec(version); + const trimmed = spec.trim(); + if (!v) { + return null; + } + if (trimmed === '' || trimmed === '*' || trimmed === 'x' || trimmed === 'latest') { + return !v[4]; + } + const match = /^([~^]|=)?\s*v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?(?:-([0-9A-Za-z.-]+))?$/.exec(trimmed); + if (!match) { + return null; + } + const [major, minor, patch] = [Number(v[1]), Number(v[2]), Number(v[3])]; + const op = match[1] ?? ''; + const sMajor = Number(match[2]); + const sMinor = match[3] === undefined || match[3] === 'x' || match[3] === '*' ? null : Number(match[3]); + const sPatch = match[4] === undefined || match[4] === 'x' || match[4] === '*' ? null : Number(match[4]); + const sPre = match[5]; + if (v[4] && !(sPre && major === sMajor && minor === sMinor && patch === sPatch)) { + // A prerelease only satisfies a range that names a prerelease of the same version. + return false; + } + const cmp = (a: readonly number[], b: readonly number[]): number => { + for (let i = 0; i < a.length; i += 1) { + const d = (a[i] ?? 0) - (b[i] ?? 0); + if (d !== 0) { + return d; + } + } + return 0; + }; + const atLeast = cmp([major, minor, patch], [sMajor, sMinor ?? 0, sPatch ?? 0]) >= 0; + if (op === '^') { + if (!atLeast) { + return false; + } + if (sMajor > 0 || sMinor === null) { + return major === sMajor; + } + if (sMinor > 0 || sPatch === null) { + return major === 0 && minor === sMinor; + } + return major === 0 && minor === 0 && patch === sPatch; + } + if (op === '~') { + return atLeast && major === sMajor && (sMinor === null || minor === sMinor); + } + if (sPre && !v[4]) { + return false; + } + return major === sMajor && (sMinor === null || minor === sMinor) && (sPatch === null || patch === sPatch) && (!sPre || sPre === v[4]); +} + +function stringRecord(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return {}; + } + return Object.fromEntries(Object.entries(value as Record).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); +} + +function sizeOf(manifest: Manifest | null): number | null { + const size = manifest?.dist?.unpackedSize; + return typeof size === 'number' && Number.isFinite(size) && size >= 0 ? size : null; +} + +function licenseOf(manifest: Manifest): string | null { + const license = manifest.license; + if (typeof license === 'string' && license.trim()) { + return license.trim().slice(0, 100); + } + if (license && typeof license === 'object' && typeof (license as { type?: unknown }).type === 'string') { + return String((license as { type: string }).type).slice(0, 100); + } + return null; +} + +/** A repository field as a browsable https URL, or null. */ +export function repositoryUrl(repository: unknown): string | null { + const raw = typeof repository === 'string' ? repository : repository && typeof repository === 'object' ? (repository as { url?: unknown }).url : null; + if (typeof raw !== 'string') { + return null; + } + let url = raw.trim().replace(/^git\+/, '').replace(/\.git$/, ''); + if (/^github:/.test(url) || /^[\w.-]+\/[\w.-]+$/.test(url)) { + url = `https://github.com/${url.replace(/^github:/, '')}`; + } + url = url.replace(/^git:\/\//, 'https://').replace(/^ssh:\/\/git@/, 'https://').replace(/^git@([^:]+):/, 'https://$1/'); + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' ? parsed.href : null; + } catch { + return null; + } +} + +function hasInstallScript(manifest: Manifest): boolean { + const scripts = stringRecord(manifest.scripts); + return manifest.hasInstallScript === true || INSTALL_SCRIPTS.some((name) => name in scripts); +} + +/** The platform an optional dependency name targets, as npm's `os-cpu` naming does. */ +function targetsPlatform(name: string): boolean { + return OS_TOKENS.test(name); +} + +/** How well a platform package's name fits this machine (higher is better, 0 is not at all). */ +export function platformFit(name: string, platform: NodeJS.Platform, arch: string): number { + const lower = name.toLowerCase(); + const os = platform === 'win32' ? ['win32', 'windows'] : platform === 'darwin' ? ['darwin', 'macos'] : [platform]; + if (!os.some((token) => lower.includes(token)) || !lower.includes(arch)) { + return 0; + } + // The glibc build before the musl one: a glibc system is the common case. + return lower.includes('musl') ? 1 : 2; +} + +function lastLines(lines: readonly string[]): string { + return lines.slice(-8).join('\n'); +} + +function stripAnsi(text: string): string { + return text.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, ''); +} + +/** How to start npm without a shell. */ +export interface NpmCommand { + readonly command: string; + readonly prefixArgs: readonly string[]; + /** Where it was found, for messages. */ + readonly path: string; +} + +export class AgentInstaller { + private readonly options: InstallerOptions; + private readonly probe: FileProbe; + private readonly registry: string; + private readonly descriptions = new Map(); + private busy: string | null = null; + + constructor(options: InstallerOptions) { + this.options = options; + this.probe = options.probe ?? diskProbe; + this.registry = registryOf(options.env); + } + + /** The operation running now ("Installing Codex"), or null. */ + get running(): string | null { + return this.busy; + } + + private preset(id: AgentPresetId): (typeof PRESETS)[number] { + const preset = PRESETS.find((candidate) => candidate.id === id); + if (!preset) { + throw new Error('Unknown agent.'); + } + return preset; + } + + private packageDir(packageName: string): string { + return path.join(this.options.packagesDir, 'node_modules', ...packageName.split('/')); + } + + /** The version of a preset's adapter the IDE installed, or null. */ + async installedVersion(presetId: AgentPresetId): Promise { + const text = await this.probe.readText(path.join(this.packageDir(this.preset(presetId).packageName), 'package.json')); + if (text === null) { + return null; + } + try { + const version = (JSON.parse(text) as { version?: unknown }).version; + return typeof version === 'string' && VERSION.test(version) ? version : null; + } catch { + return null; + } + } + + /** Finds npm on PATH; on Windows, the `node.exe` + `npm-cli.js` next to `npm.cmd`, so no shell is needed. */ + async findNpm(): Promise { + const { env, platform } = this.options; + if (platform !== 'win32') { + const found = await findOnPath('npm', env, platform, this.probe); + return found ? { command: found, prefixArgs: [], path: found } : null; + } + const found = await findOnPath('npm', env, platform, this.probe); + if (!found) { + return null; + } + if (/\.exe$/i.test(found)) { + return { command: found, prefixArgs: [], path: found }; + } + const dir = path.win32.dirname(found); + const node = path.win32.join(dir, 'node.exe'); + const cli = path.win32.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'); + if ((await this.probe.isExecutable(node)) && (await this.probe.readText(cli)) !== null) { + return { command: node, prefixArgs: [cli], path: found }; + } + const nodeOnPath = await findOnPath('node', env, platform, this.probe); + if (nodeOnPath && (await this.probe.readText(cli)) !== null) { + return { command: nodeOnPath, prefixArgs: [cli], path: found }; + } + return null; + } + + private async fetchManifest(name: string, spec: string, budget: { left: number }): Promise { + if (budget.left <= 0) { + return null; + } + budget.left -= 1; + const real = resolveAlias(name, spec); + const exact = isExactVersion(real.spec); + const tag = exact ? real.spec.trim().replace(/^v/, '') : 'latest'; + let manifest: Manifest; + try { + const raw = await this.options.fetchJson(`${this.registry}${registryPath(real.name)}/${encodeURIComponent(tag)}`); + if (!raw || typeof raw !== 'object') { + return null; + } + manifest = raw as Manifest; + } catch { + return null; + } + // A range the latest version does not satisfy: npm picks another version, whose details are not known here. + if (!exact && typeof manifest.version === 'string' && satisfies(manifest.version, real.spec) !== true && real.spec !== 'latest') { + return null; + } + return manifest; + } + + /** Reads the registry: the only network access before the person confirms. */ + async describe(presetIdInput: unknown): Promise { + const presetId = parsePresetId(presetIdInput); + const preset = this.preset(presetId); + let raw: unknown; + try { + raw = await this.options.fetchJson(`${this.registry}${registryPath(preset.packageName)}/latest`); + } catch (error) { + throw new Error(`Could not read ${preset.packageName} from ${this.registry}: ${error instanceof Error ? error.message : String(error)}`); + } + const manifest = (raw && typeof raw === 'object' ? raw : {}) as Manifest; + if (manifest.name !== preset.packageName || typeof manifest.version !== 'string' || !VERSION.test(manifest.version)) { + throw new Error(`The registry did not describe ${preset.packageName}.`); + } + const version = manifest.version; + const { platform, arch } = this.options; + const budget = { left: MAX_FETCHES }; + const dependencies = stringRecord(manifest.dependencies); + const optional = stringRecord(manifest.optionalDependencies); + const installScripts = hasInstallScript(manifest) ? [preset.packageName] : []; + const nativeBinaries: { name: string; size: number | null }[] = []; + let dependenciesSize = 0; + let anySize = false; + const addSize = (size: number | null): void => { + if (size !== null) { + dependenciesSize += size; + anySize = true; + } + }; + + const seenBinaries = new Set(); + /** Optional platform packages: npm installs the one that fits; it is listed and its size counted. */ + const platformPackages = async (owner: string, entries: Record): Promise> => { + const platformNames = Object.keys(entries).filter((name) => targetsPlatform(`${name} ${entries[name] ?? ''}`)); + if (platformNames.length < 2) { + return entries; + } + const scored = platformNames + .map((name) => ({ name, fit: platformFit(`${name} ${entries[name] ?? ''}`, platform, arch) })) + .filter((candidate) => candidate.fit > 0) + .sort((a, b) => b.fit - a.fit); + const chosen = scored[0]; + if (chosen && seenBinaries.has(chosen.name)) { + return Object.fromEntries(Object.entries(entries).filter(([name]) => !platformNames.includes(name))); + } + if (chosen) { + seenBinaries.add(chosen.name); + } + let size: number | null = null; + if (chosen) { + const binary = await this.fetchManifest(chosen.name, entries[chosen.name] ?? 'latest', budget); + size = sizeOf(binary); + addSize(size); + if (binary && hasInstallScript(binary)) { + installScripts.push(chosen.name); + } + } + nativeBinaries.push({ name: chosen ? `${owner}: ${chosen.name}` : `${owner}: none of its ${platformNames.length} platform packages fits ${platform}-${arch}`, size }); + return Object.fromEntries(Object.entries(entries).filter(([name]) => !platformNames.includes(name))); + }; + + const rest = await platformPackages(preset.packageName, optional); + const direct = Object.entries({ ...dependencies, ...rest }); + const manifests = await Promise.all(direct.map(([name, spec]) => this.fetchManifest(name, spec, budget))); + for (let i = 0; i < direct.length; i += 1) { + const [name] = direct[i] as [string, string]; + const dependency = manifests[i] ?? null; + if (!dependency) { + continue; + } + addSize(sizeOf(dependency)); + if (hasInstallScript(dependency)) { + installScripts.push(name); + } + const nested = stringRecord(dependency.optionalDependencies); + if (Object.keys(nested).length > 0) { + await platformPackages(name, nested); + } + } + + const installedVersion = await this.installedVersion(presetId); + const description: InstallDescription = { + presetId, + agentName: preset.name, + packageName: preset.packageName, + version, + license: licenseOf(manifest), + unpackedSize: sizeOf(manifest), + dependenciesSize: anySize ? dependenciesSize : null, + repository: repositoryUrl(manifest.repository), + homepage: typeof manifest.homepage === 'string' && /^https:\/\//.test(manifest.homepage) ? manifest.homepage : null, + published: await this.publishedAt(preset.packageName, version, budget), + registry: this.registry, + dependencies: Object.entries({ ...dependencies, ...optional }).map(([name, spec]) => `${name}@${spec}`), + nativeBinaries, + installScripts, + targetDir: this.options.packagesDir, + command: `npm ${this.installArgs(`${preset.packageName}@${version}`).join(' ')}`, + installedVersion, + }; + this.descriptions.set(presetId, { description, at: this.now() }); + return description; + } + + private now(): number { + return this.options.now?.() ?? Date.now(); + } + + /** The publication date, from the full document's `time` (it can be large, so it is read last and optional). */ + private async publishedAt(name: string, version: string, budget: { left: number }): Promise { + if (budget.left <= 0) { + return null; + } + budget.left -= 1; + try { + const doc = (await this.options.fetchJson(`${this.registry}${registryPath(name)}`)) as { time?: Record } | null; + const time = doc?.time?.[version]; + return typeof time === 'string' && !Number.isNaN(Date.parse(time)) ? new Date(time).toISOString() : null; + } catch { + return null; + } + } + + private installArgs(spec: string): string[] { + return ['install', '--prefix', this.options.packagesDir, '--no-audit', '--no-fund', '--omit=dev', '--save-exact', '--ignore-scripts=false', '--loglevel=http', '--progress=false', spec]; + } + + /** The description to confirm: the one just shown, or a fresh one when it is old. */ + async descriptionFor(presetIdInput: unknown): Promise { + const presetId = parsePresetId(presetIdInput); + const cached = this.descriptions.get(presetId); + if (cached && this.now() - cached.at < (this.options.descriptionTtlMs ?? 10 * 60_000)) { + return cached.description; + } + return this.describe(presetId); + } + + /** + * Installs (or updates to) the version `confirm` is shown. Resolves false + * when the person declines; throws with npm's last lines when it fails. + */ + async install(presetIdInput: unknown, confirm: (description: InstallDescription) => Promise, onLine: LineSink): Promise { + const presetId = parsePresetId(presetIdInput); + this.assertIdle(); + const npm = await this.findNpm(); + if (!npm) { + throw new Error(`npm was not found on PATH. Installing an agent needs Node.js, which includes npm: get it from ${NODE_DOWNLOAD_URL}, then restart Code-XR IDE and try again.`); + } + const description = await this.descriptionFor(presetId); + if (!(await confirm(description))) { + return false; + } + this.assertIdle(); + this.busy = `Installing ${description.agentName}`; + try { + await this.ensurePackageJson(); + onLine(`Installing ${description.packageName}@${description.version} into ${description.targetDir}`); + await this.runNpm(npm, this.installArgs(`${description.packageName}@${description.version}`), onLine); + const installed = await this.installedVersion(presetId); + if (installed !== description.version) { + throw new Error(`npm finished but ${description.packageName}@${description.version} is not in ${description.targetDir}.`); + } + this.descriptions.delete(presetId); + return true; + } finally { + this.busy = null; + } + } + + /** Removes an adapter the IDE installed, after `confirm`. */ + async uninstall(presetIdInput: unknown, confirm: (packageName: string, version: string) => Promise, onLine: LineSink): Promise { + const presetId = parsePresetId(presetIdInput); + const preset = this.preset(presetId); + this.assertIdle(); + const version = await this.installedVersion(presetId); + if (!version) { + throw new Error(`${preset.name} was not installed by Code-XR IDE; remove it the way you installed it.`); + } + if (!(await confirm(preset.packageName, version))) { + return false; + } + this.assertIdle(); + this.busy = `Removing ${preset.name}`; + try { + const npm = await this.findNpm(); + if (npm) { + await this.runNpm(npm, ['uninstall', '--prefix', this.options.packagesDir, '--no-audit', '--no-fund', '--loglevel=http', '--progress=false', preset.packageName], onLine); + } + // Without npm (or if it left it behind), the package's own folder goes; its dependencies stay until the next npm run. + await fs.promises.rm(this.packageDir(preset.packageName), { recursive: true, force: true }); + await this.dropDependency(preset.packageName); + this.descriptions.delete(presetId); + onLine(`Removed ${preset.packageName}@${version}.`); + return true; + } finally { + this.busy = null; + } + } + + private assertIdle(): void { + if (this.busy) { + throw new Error(`${this.busy} is still running; wait for it to finish.`); + } + } + + private async ensurePackageJson(): Promise { + await fs.promises.mkdir(this.options.packagesDir, { recursive: true }); + const file = path.join(this.options.packagesDir, 'package.json'); + if ((await this.probe.readText(file)) === null) { + await fs.promises.writeFile(file, `${JSON.stringify(PACKAGE_JSON, null, 2)}\n`, 'utf8'); + } + } + + private async dropDependency(packageName: string): Promise { + const file = path.join(this.options.packagesDir, 'package.json'); + const text = await this.probe.readText(file); + if (text === null) { + return; + } + try { + const json = JSON.parse(text) as { dependencies?: Record }; + if (json.dependencies && packageName in json.dependencies) { + delete json.dependencies[packageName]; + await fs.promises.writeFile(file, `${JSON.stringify(json, null, 2)}\n`, 'utf8'); + } + } catch { + // A package.json the IDE cannot read is left alone. + } + } + + /** The environment npm runs with: the person's own (proxy, npm config, CA), without Electron's switches. */ + private npmEnv(): Record { + const env: Record = {}; + for (const [key, value] of Object.entries(this.options.env)) { + if (value !== undefined && !/^ELECTRON_/i.test(key) && key.toUpperCase() !== 'NODE_OPTIONS') { + env[key] = value; + } + } + return { ...env, NO_UPDATE_NOTIFIER: '1', npm_config_update_notifier: 'false', npm_config_color: 'false' }; + } + + private runNpm(npm: NpmCommand, args: readonly string[], onLine: LineSink): Promise { + return new Promise((resolve, reject) => { + const tail: string[] = []; + let child: ReturnType; + try { + child = spawn(npm.command, [...npm.prefixArgs, ...args], { cwd: this.options.packagesDir, env: this.npmEnv(), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + } catch (error) { + reject(new Error(`Could not start npm (${npm.path}): ${error instanceof Error ? error.message : String(error)}`)); + return; + } + const timer = setTimeout(() => { + child.kill(); + reject(new Error(`npm took longer than ${Math.round((this.options.timeoutMs ?? 20 * 60_000) / 60_000)} minutes and was stopped.\n${lastLines(tail)}`)); + }, this.options.timeoutMs ?? 20 * 60_000); + const reader = (): ((chunk: Buffer) => void) => { + let pending = ''; + return (chunk) => { + pending += chunk.toString('utf8'); + const lines = pending.split(/\r?\n|\r/); + pending = lines.pop() ?? ''; + for (const raw of lines) { + const line = stripAnsi(raw).trimEnd().slice(0, MAX_LINE); + if (line.trim()) { + tail.push(line); + if (tail.length > KEEP_LINES) { + tail.shift(); + } + onLine(line); + } + } + }; + }; + child.stdout?.on('data', reader()); + child.stderr?.on('data', reader()); + child.on('error', (error) => { + clearTimeout(timer); + reject(new Error(`Could not start npm (${npm.path}): ${error.message}`)); + }); + child.on('close', (code, signal) => { + clearTimeout(timer); + if (code === 0) { + resolve(); + } else { + reject(new Error(`npm failed (${signal ?? `exit code ${String(code)}`}).${tail.length ? `\n${lastLines(tail)}` : ''}`)); + } + }); + }); + } +} + +/** "3.4 MB". */ +export function formatBytes(bytes: number): string { + if (bytes < 1024) { + return `${bytes} B`; + } + const units = ['KB', 'MB', 'GB']; + let value = bytes / 1024; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[unit] ?? 'GB'}`; +} + +/** The text of the consent dialog: what will be downloaded, from where, and what runs. */ +export function consentDetail(description: InstallDescription): string { + const size = [ + description.unpackedSize !== null ? `${formatBytes(description.unpackedSize)} (the adapter)` : 'unknown (the registry does not say)', + description.dependenciesSize !== null ? `at least ${formatBytes(description.dependenciesSize)} more for its dependencies on this platform` : null, + ].filter(Boolean).join(', '); + const lines = [ + `Package: ${description.packageName}@${description.version}${description.installedVersion ? ` (installed now: ${description.installedVersion})` : ''}`, + `Licence: ${description.license ?? 'not stated'}`, + `Size once unpacked: ${size}`, + `Source: ${description.registry}${description.repository ? `\nRepository: ${description.repository}` : ''}`, + ...(description.published ? [`Published: ${description.published.slice(0, 10)}`] : []), + ...(description.dependencies.length ? [`Dependencies: ${description.dependencies.join(', ')}`] : []), + ...(description.nativeBinaries.length ? [`Native binaries (one per platform, npm picks yours): ${description.nativeBinaries.map((binary) => `${binary.name}${binary.size !== null ? ` (${formatBytes(binary.size)})` : ''}`).join('; ')}`] : []), + description.installScripts.length ? `Install scripts will run for: ${description.installScripts.join(', ')}` : 'Install scripts: none declared by the adapter or its direct dependencies.', + '', + `Code-XR IDE will run, with your npm configuration and network settings:\n${description.command}`, + `Into: ${description.targetDir} (nothing is installed globally).`, + '', + `The adapter then runs as ${description.agentName}'s agent with your permissions, inside the project folders you trust. Only install software you trust.`, + ]; + return lines.join('\n'); +} diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts new file mode 100644 index 000000000..b8d68626e --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -0,0 +1,1479 @@ +import { randomUUID } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { + InitializeResponse, + McpServer, + ReadTextFileRequest, + ReadTextFileResponse, + RequestPermissionRequest, + RequestPermissionResponse, + SessionConfigOption, + SessionModeState, + SessionUpdate, + WriteTextFileRequest, +} from '@agentclientprotocol/sdk'; +import { + applySessionEvent, + emptySession, + summarize, + titleFromPrompt, + type AgentSessionMessage, + type AgentSessionState, + type AgentView, + type ChangeDiffView, + type ChatChanges, + type InstallDescription, + type LoginTerminal, + type PermissionOptionView, + type ProjectSessions, + type PromptAttachment, + type SessionEvent, + type SessionSummary, + type ToolKind, + type TurnMetricDeltaView, + type SessionWorktree, + type WorktreeAvailabilityView, + type WorktreeCommitView, + type WorktreeMergeView, + type WorktreeStatusView, +} from '../../shared/agentSession.ts'; +import { normalizeProjectPath } from '../checkpoints/checkpointStore.ts'; +import { isSameOrInside } from '../trust/trustModel.ts'; +import { AcpConnection, type AcpClientHandlers, type AgentLaunch } from './acpConnection.ts'; +import { + attachmentLabel, + buildPromptBlocks, + errorMessage, + isAuthRequiredError, + mapAuthMethods, + mapConfigOptions, + mapModes, + mapSessionUpdate, + sliceLines, + stopReasonOf, + toolEvent, + toolKindOf, + type MappingContext, + type ResolvedAttachment, +} from './acpMapping.ts'; +import type { AgentCatalog } from './agentCatalog.ts'; +import { parsePresetId, type AgentInstaller } from './agentInstaller.ts'; +import { AgentTerminals } 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'; + +/** + * AF1: the agent-first chat in the main process. It owns the authoritative + * state of every open chat, starts one ACP agent process per chat when the + * chat first needs it (in the chat's project folder, only when that folder is + * trusted), turns the agent's `session/update`s into `SessionEvent`s, applies + * them with the shared reducer and streams them to the window that owns the + * chat, and answers the agent's requests: files inside the project, terminals + * shown in tool cards, and permissions the person answers in the chat + * (`allow_always` / `reject_always` are remembered per agent and tool kind). + * + * A chat belongs to the folder open in the window that created it; another + * window can read it but only a window with that folder open can continue it. + * No Electron here: windows are `WindowPort`s and everything the IDE provides + * (files, terminals, trust, checkpoints, MCP servers) is injected, so the + * whole flow is unit-tested against an in-process fake agent. + */ + +/** The window side of a chat: where its events go. `id` is the webContents id. */ +export interface WindowPort { + readonly id: number; + send(message: AgentSessionMessage): void; + isDestroyed(): boolean; +} + +export interface KeyValueStore { + get(key: string): T | undefined; + update(key: string, value: unknown): Promise; +} + +export interface AgentSessionServiceOptions { + readonly catalog: AgentCatalog; + /** AF2: installs presets' adapters on request; absent in the smoke run (no download may happen). */ + readonly installer?: AgentInstaller; + readonly store: SessionStore; + /** Where `allow_always` / `reject_always` answers are kept. */ + readonly decisions: KeyValueStore; + /** The folder open in the window, or null. */ + readonly rootOf: (window: WindowPort) => string | null; + readonly isTrusted: (window: WindowPort) => boolean; + /** The text the agent reads for a file: the window's unsaved buffer when the IDE has one, else the disk. */ + readonly readText: (absolutePath: string) => Promise; + readonly writeText: (absolutePath: string, content: string) => Promise; + /** + * Runs an agent's login command in a new terminal of the window (terminal + * login methods): resolves once it runs, with a promise of its exit code. + */ + readonly openTerminal: (window: WindowPort, request: { readonly command: string; readonly args: readonly string[]; readonly cwd: string; readonly env: Readonly>; readonly title: string }) => Promise<{ readonly terminal: LoginTerminal; readonly exited: Promise }>; + /** The MCP servers every chat gets in `session/new` and `session/load` (the IDE's own server). Default none. */ + readonly mcpServers?: (workspaceRoot: string | null) => readonly McpServer[]; + /** Takes a checkpoint before a prompt is sent (AF6); its id is recorded on the person's message. */ + readonly beforePrompt?: (sessionId: string, workspaceRoot: string) => Promise<{ readonly checkpointId: string } | null>; + /** + * After each turn: how many files the agent changed that still await + * review (AF5), sent as `pending-changes`. `turnId` is the id of the + * turn-end item, for `attachMetricDelta` (AF9). + */ + readonly afterTurn?: (sessionId: string, workspaceRoot: string, turnId: string) => Promise; + /** + * AF12: the IDE's own folder for chat worktrees (`/worktrees`), + * outside every project; absent, a chat cannot have a worktree. + */ + readonly worktreeStorageDir?: string; + /** The review of a chat's changes and its checkpoints (AF5, AF6); absent, the review calls refuse. */ + readonly review?: ChangeReview; + /** 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. */ + readonly spawnAllowed: boolean; + /** An empty folder of the IDE's own where agents are probed and logged in. */ + readonly probeDir: string; + readonly homeDir: string; + /** The environment of the commands agents run in terminals. */ + readonly terminalEnv: Readonly>; + readonly platform?: NodeJS.Platform; + readonly log?: (line: string) => void; + readonly now?: () => string; + /** How long an agent has to start (`initialize` plus `session/new`), ms. */ + readonly startTimeoutMs?: number; + /** How long a cancelled turn may take to end before the agent is stopped, ms. */ + readonly cancelGraceMs?: number; +} + +/** What the chat needs from the checkpoints (AF5, AF6): `SessionChanges` in the IDE. Paths are project-relative. */ +export interface ChangeReview { + pending(sessionId: string, root: string): Promise; + 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; + previewRestore(root: string, checkpointId: string): Promise; + restoreCheckpoint(root: string, checkpointId: string): Promise; + forget?(sessionId: string): Promise; +} + +const MAX_REVIEW_PATHS = 5000; + +/** Paths from the renderer: an array of project-relative paths (normalised), or 'all'. */ +function reviewPaths(value: unknown): readonly string[] | 'all' { + if (value === 'all') { + return 'all'; + } + if (!Array.isArray(value) || value.length === 0 || value.length > MAX_REVIEW_PATHS) { + throw new Error('Invalid list of files.'); + } + return [...new Set(value.map((entry) => normalizeProjectPath(requireString(entry, 'file path'))))]; +} + +interface PendingPermission { + readonly options: readonly PermissionOptionView[]; + readonly toolKind: ToolKind; + readonly resolve: (response: RequestPermissionResponse) => void; +} + +interface AgentRuntime { + readonly connection: AcpConnection; + readonly sessionId: string; + readonly init: InitializeResponse; + readonly terminals: AgentTerminals; +} + +interface Live { + state: AgentSessionState; + readonly root: string; + ownerId: number | null; + agent: AgentRuntime | null; + starting: Promise | null; + turnActive: boolean; + cancelRequested: boolean; + cancelTimer: ReturnType | null; + replaying: boolean; + configRaw: readonly SessionConfigOption[]; + readonly permissions: Map; + readonly terminalBuffer: Map; + terminalTimer: ReturnType | null; +} + +const DECISIONS_KEY = 'decisions'; +const MAX_PROMPT_LENGTH = 200_000; +const MAX_ATTACHMENTS = 50; +const MAX_EMBEDDED_FILE = 256 * 1024; +const MAX_READ_FILE = 10 * 1024 * 1024; +const TERMINAL_FLUSH_MS = 50; +const LOGIN_TIMEOUT_MS = 10 * 60_000; + +/** Fails with `message` when `promise` takes longer than `ms`. */ +function withTimeout(promise: Promise, ms: number, message: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(message)), ms); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (error: unknown) => { + clearTimeout(timer); + reject(error instanceof Error ? error : new Error(errorMessage(error))); + }, + ); + }); +} + +function requireString(value: unknown, what: string, max = 4096): string { + if (typeof value !== 'string' || !value || value.length > max) { + throw new Error(`Invalid ${what}.`); + } + return value; +} + +async function isDirectory(dir: string): Promise { + return (await fs.promises.stat(dir).catch(() => null))?.isDirectory() === true; +} + +/** AF12: the project's current branch (where a merge lands), or null when detached or unknown. */ +async function currentBranch(repoRoot: string): Promise { + try { + const result = await runWorktreeGit(repoRoot, ['symbolic-ref', '-q', '--short', 'HEAD'], { okExitCodes: [1] }); + return result.exitCode === 0 ? result.stdout.trim() || null : null; + } catch { + return null; + } +} + +/** A handler set that refuses everything: probes and logins never run a turn. */ +const REFUSING_HANDLERS: AcpClientHandlers = { + onUpdate: () => undefined, + requestPermission: () => Promise.resolve({ outcome: { outcome: 'cancelled' } }), + readTextFile: () => Promise.reject(new Error('No project is open for this agent.')), + writeTextFile: () => Promise.reject(new Error('No project is open for this agent.')), + createTerminal: () => Promise.reject(new Error('No project is open for this agent.')), + terminalOutput: () => { + throw new Error('Unknown terminal.'); + }, + waitForTerminalExit: () => Promise.reject(new Error('Unknown terminal.')), + killTerminal: () => undefined, + releaseTerminal: () => undefined, +}; + +export class AgentSessionService { + private readonly options: AgentSessionServiceOptions; + private readonly live = new Map(); + private readonly ports = new Map(); + private readonly platform: NodeJS.Platform; + private readonly now: () => string; + private sessionsChangedTimer: ReturnType | null = null; + private stopped = false; + private storageReal: string | null | undefined = undefined; + + constructor(options: AgentSessionServiceOptions) { + this.options = options; + this.platform = options.platform ?? process.platform; + this.now = options.now ?? (() => new Date().toISOString()); + } + + // ---- Agents ------------------------------------------------------------- + + listAgents(window: WindowPort): Promise { + this.remember(window); + return this.options.catalog.list(); + } + + async probeAgent(window: WindowPort, ref: unknown): Promise { + this.remember(window); + const agentRef = requireString(ref, 'agent', 200); + const builtin = agentRef.startsWith('builtin:') ? await this.options.catalog.builtinView(agentRef) : null; + if (builtin) { + return builtin; + } + const definition = this.options.catalog.definition(agentRef); + if (!definition) { + throw new Error('Unknown agent.'); + } + const resolution = await this.options.catalog.resolve(definition); + if (!resolution.found || !this.options.spawnAllowed) { + return this.options.catalog.view(definition); + } + const connection = await this.openScratchConnection(resolution.launch); + try { + await this.checkLogin(agentRef, connection); + } finally { + connection.close(); + } + this.broadcast({ kind: 'agents-changed' }); + return this.options.catalog.view(definition); + } + + async saveCustomAgent(window: WindowPort, input: unknown, id: unknown, confirm: (commandLine: string) => Promise): Promise { + this.remember(window); + const existing = typeof id === 'string' ? this.options.catalog.customAgents().find((agent) => agent.id === id) : undefined; + const parsedLine = (() => { + const value = input as { command?: unknown; args?: unknown } | null; + const parts = [String(value?.command ?? ''), ...(Array.isArray(value?.args) ? value.args.map(String) : [])]; + return parts.map((part) => (/\s|^$/.test(part) ? `"${part}"` : part)).join(' '); + })(); + // The command line came from the page: the person confirms it in a dialog the page cannot answer, + // unless it is exactly what was confirmed before. + const unchanged = existing && JSON.stringify([existing.command, existing.args, existing.env ?? {}]) === JSON.stringify([(input as { command?: unknown })?.command, (input as { args?: unknown })?.args ?? [], (input as { env?: unknown })?.env ?? {}]); + if (!unchanged && !(await confirm(parsedLine))) { + throw new Error('The agent was not saved.'); + } + const definition = await this.options.catalog.saveCustom(input, id); + this.broadcast({ kind: 'agents-changed' }); + return this.options.catalog.view(definition); + } + + async removeCustomAgent(window: WindowPort, id: unknown): Promise { + this.remember(window); + await this.options.catalog.removeCustom(id); + this.broadcast({ kind: 'agents-changed' }); + } + + async login(window: WindowPort, ref: unknown, methodId: unknown): Promise { + this.remember(window); + const agentRef = requireString(ref, 'agent', 200); + const method = requireString(methodId, 'login method', 200); + const definition = this.options.catalog.definition(agentRef); + if (!definition) { + throw new Error('Only an ACP agent signs in here; the built-in agent uses the keys of the Agents view.'); + } + if (!this.options.spawnAllowed) { + throw new Error('Agents cannot start in this mode.'); + } + const resolution = await this.options.catalog.resolve(definition); + if (!resolution.found) { + throw new Error(resolution.detail); + } + if (!this.options.catalog.state(agentRef)?.authMethods) { + await this.probeAgent(window, agentRef); + } + const spec = this.options.catalog.state(agentRef)?.authMethods?.find((candidate) => candidate.view.id === method); + if (!spec) { + throw new Error('The agent does not offer that login method.'); + } + if (spec.view.type === 'env') { + throw new Error(`${spec.view.name}: put the key in the agent's environment (a custom agent's environment, or the environment the IDE starts with), then try again.`); + } + if (spec.view.type === 'terminal') { + const launch = resolution.launch; + const command = spec.command ?? launch.command; + const args = spec.command ? (spec.args ?? []) : [...launch.args, ...(spec.args ?? [])]; + const cwd = this.options.rootOf(window) ?? this.options.homeDir; + const opened = await this.options.openTerminal(window, { command, args, cwd, env: { ...launch.env, ...(spec.env ?? {}) }, title: `${definition.name}: ${spec.view.name}` }); + // Once the login command ends, the agent is probed again; the picker hears `agents-changed`. + void opened.exited + .then(() => this.probeAgent(window, agentRef)) + .catch((error: unknown) => this.options.log?.(`Could not check ${definition.name} after its login: ${errorMessage(error)}`)); + return opened.terminal; + } + const connection = await this.openScratchConnection(resolution.launch); + try { + await withTimeout(connection.authenticate(method), LOGIN_TIMEOUT_MS, 'The login took too long.'); + await this.checkLogin(agentRef, connection); + } finally { + connection.close(); + } + this.broadcast({ kind: 'agents-changed' }); + return null; + } + + // ---- Installing presets (AF2) ------------------------------------------ + + private requireInstaller(): AgentInstaller { + if (!this.options.installer) { + throw new Error('Installing agents is not available in this mode.'); + } + return this.options.installer; + } + + /** What installing a preset would download: read from the registry now, because the person asked. */ + describeInstall(window: WindowPort, presetId: unknown): Promise { + this.remember(window); + const id = parsePresetId(presetId); + return this.requireInstaller().describe(id); + } + + /** + * Installs or updates a preset after `confirm` (a native dialog the page + * cannot answer) accepted the description. npm's output streams to every + * window as `install-progress`; the agents list hears `agents-changed`. + */ + async installAgent(window: WindowPort, presetIdInput: unknown, confirm: (description: InstallDescription) => Promise): Promise { + this.remember(window); + const presetId = parsePresetId(presetIdInput); + const installer = this.requireInstaller(); + const progress = (extra: { line?: string; done?: boolean; error?: string }): void => this.broadcast({ kind: 'install-progress', presetId, action: 'install', ...extra }); + let started = false; + try { + const done = await installer.install(presetId, async (description) => { + started = await confirm(description); + return started; + }, (line) => progress({ line })); + if (started) { + progress({ done: true }); + } + return done; + } catch (error) { + if (started) { + progress({ done: true, error: errorMessage(error) }); + } + throw error; + } finally { + if (started) { + this.options.catalog.forget(`acp:${presetId}`); + this.broadcast({ kind: 'agents-changed' }); + } + } + } + + /** Removes a preset the IDE installed, after `confirm`. */ + async uninstallAgent(window: WindowPort, presetIdInput: unknown, confirm: (packageName: string, version: string) => Promise): Promise { + this.remember(window); + const presetId = parsePresetId(presetIdInput); + const installer = this.requireInstaller(); + const progress = (extra: { line?: string; done?: boolean; error?: string }): void => this.broadcast({ kind: 'install-progress', presetId, action: 'uninstall', ...extra }); + let started = false; + try { + const done = await installer.uninstall(presetId, async (packageName, version) => { + started = await confirm(packageName, version); + return started; + }, (line) => progress({ line })); + if (started) { + progress({ done: true }); + } + return done; + } catch (error) { + if (started) { + progress({ done: true, error: errorMessage(error) }); + } + throw error; + } finally { + if (started) { + this.options.catalog.forget(`acp:${presetId}`); + this.broadcast({ kind: 'agents-changed' }); + } + } + } + + /** Starts an agent in the IDE's own empty folder, initialised and recorded in the catalogue. */ + private async openScratchConnection(launch: AgentLaunch): Promise { + await fs.promises.mkdir(this.options.probeDir, { recursive: true }); + const connection = this.connectAgent(launch, this.options.probeDir, REFUSING_HANDLERS); + return connection; + } + + /** `initialize` then `session/new`: ready, needs a login, or failing (and why). */ + private async checkLogin(agentRef: string, connection: AcpConnection): Promise { + const timeout = this.options.startTimeoutMs ?? 60_000; + let init: InitializeResponse; + try { + init = await withTimeout(connection.initialize(), timeout, 'The agent did not answer initialize in time.'); + } catch (error) { + this.options.catalog.setState(agentRef, { availability: 'error', detail: errorMessage(error) }); + return; + } + const authMethods = mapAuthMethods(init.authMethods ?? []); + try { + await withTimeout(connection.newSession(this.options.probeDir, []), timeout, 'The agent did not open a session in time.'); + this.options.catalog.setState(agentRef, { availability: 'ready', authMethods }); + } catch (error) { + this.options.catalog.setState(agentRef, isAuthRequiredError(error) + ? { availability: 'needs-login', detail: 'Log in to use this agent.', authMethods } + : { availability: 'error', detail: errorMessage(error), authMethods }); + } + } + + private connectAgent(launch: AgentLaunch, cwd: string, handlers: AcpClientHandlers): AcpConnection { + if (!this.options.spawnAllowed || this.stopped) { + throw new Error('Agents cannot start in this mode.'); + } + return this.options.connect ? this.options.connect(launch, cwd, handlers) : AcpConnection.spawn(launch, cwd, handlers, (line) => this.options.log?.(line)); + } + + // ---- Chats -------------------------------------------------------------- + + async listProjects(window: WindowPort): Promise { + this.remember(window); + return this.options.store.listProjects(this.options.rootOf(window), (summary) => { + const live = this.live.get(summary.id); + return live ? summarize(live.state) : summary; + }); + } + + async get(window: WindowPort, sessionId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + return live.state; + } + + async create(window: WindowPort, agentRef: unknown, createOptions?: unknown): Promise { + this.remember(window); + const ref = requireString(agentRef, 'agent', 200); + if (ref.startsWith('builtin:')) { + throw new Error('Use the Agents view for the built-in agent for now.'); + } + const root = this.options.rootOf(window); + if (!root) { + throw new Error('Open a folder to start a chat.'); + } + const definition = this.options.catalog.definition(ref); + if (!definition) { + throw new Error('Unknown agent.'); + } + const wantsWorktree = !!createOptions && typeof createOptions === 'object' && (createOptions as { worktree?: unknown }).worktree === true; + const id = randomUUID(); + let worktree: SessionWorktree | null = null; + let dirty = false; + if (wantsWorktree) { + // AF12: git creates the worktree with no hook of the repository; still, only a trusted folder gets one. + if (!this.options.isTrusted(window)) { + throw new Error('This folder is in Restricted Mode. Trust it to start a chat in its own worktree.'); + } + const created = await this.worktreeCall(() => createWorktree({ projectRoot: root, storageDir: this.requireWorktreeStorage(), sessionId: id, label: definition.name })); + worktree = { branch: created.branch, path: created.path, cwd: created.cwd, baseCommit: created.baseCommit, repoRoot: created.repoRoot }; + dirty = created.dirty; + } + const at = this.now(); + const state = emptySession({ id, title: 'New chat', agentRef: ref, agentName: definition.name, workspaceRoot: root, createdAt: at, updatedAt: at, ...(worktree ? { worktree } : {}) }); + const live = this.track(state, root, window.id); + if (worktree && dirty) { + this.emit(live, { type: 'notice', id: randomUUID(), level: 'info', text: `This chat works on the branch ${worktree.branch}, started from the project's last commit. Your uncommitted changes in the project are not in its worktree.` }); + } + await this.options.store.saveNow(live.state); + this.sessionsChanged(); + // The agent starts now, so its modes, models and commands are there before the first message. + if (this.options.spawnAllowed && this.options.isTrusted(window)) { + void this.ensureAgent(live, window).catch((error: unknown) => this.reportStartFailure(live, error)); + } + return live.state; + } + + async prompt(window: WindowPort, sessionId: unknown, text: unknown, attachments: unknown): Promise { + this.remember(window); + if (typeof text !== 'string' || text.length > MAX_PROMPT_LENGTH || (!text.trim() && !(Array.isArray(attachments) && attachments.length))) { + throw new Error('A message needs text of at most 200,000 characters.'); + } + const live = await this.open(window, sessionId); + this.assertContinuable(live, window); + if (live.turnActive) { + throw new Error('The agent is still answering; wait for it or stop it first.'); + } + live.turnActive = true; + live.cancelRequested = false; + let resolved: ResolvedAttachment[]; + let labels: string[]; + try { + ({ resolved, labels } = await this.resolveAttachments(this.workRoot(live), attachments)); + } catch (error) { + live.turnActive = false; + throw error; + } + 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 } : {}) }); + 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)); + this.flushTerminalOutput(live); + const turnId = randomUUID(); + this.emit(live, { type: 'turn-end', id: turnId, stopReason: live.cancelRequested ? 'cancelled' : stopReasonOf(response.stopReason), at: this.now() }); + await this.reportPendingChanges(live, turnId); + } catch (error) { + this.flushTerminalOutput(live); + this.cancelPermissions(live); + const turnId = randomUUID(); + if (live.cancelRequested) { + this.emit(live, { type: 'turn-end', id: turnId, stopReason: 'cancelled', at: this.now() }); + } else { + this.reportFailure(live, error); + this.emit(live, { type: 'turn-end', id: turnId, stopReason: 'error', at: this.now() }); + } + await this.reportPendingChanges(live, turnId); + } finally { + live.turnActive = false; + live.cancelRequested = false; + if (live.cancelTimer) { + clearTimeout(live.cancelTimer); + live.cancelTimer = null; + } + await this.options.store.saveNow(live.state).catch((error: unknown) => this.options.log?.(`Could not save chat ${live.state.id}: ${errorMessage(error)}`)); + this.sessionsChanged(); + } + } + + async cancel(window: WindowPort, sessionId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + if (!live.turnActive) { + return; + } + live.cancelRequested = true; + // ACP: after session/cancel the client answers every pending permission with `cancelled`. + this.cancelPermissions(live); + const agent = live.agent; + if (!agent) { + return; + } + await agent.connection.cancel(agent.sessionId).catch(() => undefined); + // An agent that does not end the turn is stopped; the next message starts it again. + live.cancelTimer ??= setTimeout(() => { + live.cancelTimer = null; + if (live.turnActive && live.agent === agent) { + agent.connection.close(); + } + }, this.options.cancelGraceMs ?? 15_000); + } + + async respondPermission(window: WindowPort, sessionId: unknown, requestId: unknown, optionId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + const id = requireString(requestId, 'request', 200); + const option = requireString(optionId, 'option', 200); + const pending = live.permissions.get(id); + if (!pending) { + throw new Error('That request was already answered.'); + } + const chosen = pending.options.find((candidate) => candidate.id === option); + if (!chosen) { + throw new Error('That option is not one the agent offered.'); + } + if (chosen.kind === 'allow_always' || chosen.kind === 'reject_always') { + await this.rememberDecision(live.state.agentRef, pending.toolKind, chosen.kind === 'allow_always' ? 'allow' : 'reject'); + } + this.settlePermission(live, id, { outcome: { outcome: 'selected', optionId: chosen.id } }, chosen.id); + } + + async setMode(window: WindowPort, sessionId: unknown, modeId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + const mode = requireString(modeId, 'mode', 200); + this.assertContinuable(live, window); + const agent = await this.ensureAgent(live, window); + await agent.connection.setMode(agent.sessionId, mode); + this.emit(live, { type: 'modes', current: mode }); + } + + async setConfigOption(window: WindowPort, sessionId: unknown, optionId: unknown, valueId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + const configId = requireString(optionId, 'option', 200); + const value = requireString(valueId, 'value', 400); + this.assertContinuable(live, window); + const agent = await this.ensureAgent(live, window); + const raw = live.configRaw.find((option) => option.id === configId); + const response = await agent.connection.setConfigOption(agent.sessionId, configId, raw?.type === 'boolean' ? value === 'true' : value); + live.configRaw = response.configOptions; + this.emit(live, { type: 'config', options: mapConfigOptions(response.configOptions) }); + } + + async rename(window: WindowPort, sessionId: unknown, title: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + const next = typeof title === 'string' ? title.replace(/\s+/g, ' ').trim() : ''; + if (!next || next.length > 200) { + throw new Error('A chat title needs 1 to 200 characters.'); + } + this.emit(live, { type: 'title', title: next }); + await this.options.store.saveNow(live.state); + this.sessionsChanged(); + return summarize(live.state); + } + + async remove(window: WindowPort, sessionId: unknown, removeOptions?: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + const removeWorktreeToo = !!removeOptions && typeof removeOptions === 'object' && (removeOptions as { removeWorktree?: unknown }).removeWorktree === true; + const worktree = live.state.worktree; + if (removeWorktreeToo && worktree && !worktree.removed) { + // AF12: the worktree goes first, so a refusal keeps the chat that names it. + if (this.options.rootOf(window) !== live.root) { + throw new Error(`This chat belongs to ${live.root}; open that folder to remove its worktree.`); + } + this.stopAgent(live); + await this.worktreeCall(() => removeWorktree(this.worktreeInfo(live), { deleteBranch: true })); + } + this.stopAgent(live); + this.live.delete(live.state.id); + await this.options.store.remove(live.root, live.state.id); + await this.hook('review.forget', () => this.options.review?.forget?.(live.state.id)); + this.sessionsChanged(); + } + + async markRead(window: WindowPort, sessionId: unknown): Promise { + this.remember(window); + const live = await this.open(window, sessionId); + if (!live.state.unread) { + return; + } + this.emit(live, { type: 'read' }); + this.sessionsChanged(); + } + + // ---- Review of changes and checkpoints (AF5, AF6, AF9) --------------------- + + async changes(window: WindowPort, sessionId: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, false); + return this.refreshChanges(live, review); + } + + async changeDiff(window: WindowPort, sessionId: unknown, filePath: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, false); + const relative = normalizeProjectPath(requireString(filePath, 'file path')); + const { oldText, newText } = await review.diff(live.state.id, this.workRoot(live), relative); + return { path: relative, oldText, newText }; + } + + async keepChanges(window: WindowPort, sessionId: unknown, paths: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, true); + await review.keep(live.state.id, this.workRoot(live), reviewPaths(paths)); + return this.refreshChanges(live, review); + } + + async undoChanges(window: WindowPort, sessionId: unknown, paths: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, true); + await review.undo(live.state.id, this.workRoot(live), reviewPaths(paths)); + 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)); + } + + async restoreCheckpoint(window: WindowPort, sessionId: unknown, checkpointId: unknown): Promise { + const { live, review } = await this.reviewOf(window, sessionId, true); + const written = await review.restoreCheckpoint(this.workRoot(live), this.checkpointOf(live, checkpointId)); + await this.refreshChanges(live, review).catch((error: unknown) => this.options.log?.(`Could not refresh the changes of ${live.state.id}: ${errorMessage(error)}`)); + return written; + } + + /** AF9: attaches a metric delta to one of the chat's finished turns (quietly ignored once the chat is gone). */ + attachMetricDelta(sessionId: string, turnId: string, delta: TurnMetricDeltaView): void { + const live = this.live.get(sessionId); + if (!live || !live.state.items.some((item) => item.kind === 'turn-end' && item.id === turnId)) { + return; + } + this.emit(live, { type: 'metric-delta', turnId, delta }); + } + + /** Only a checkpoint recorded on one of the chat's own messages can be restored. */ + private checkpointOf(live: Live, checkpointId: unknown): string { + const id = requireString(checkpointId, 'checkpoint', 128); + if (!live.state.items.some((item) => item.kind === 'user' && item.checkpoint === id)) { + throw new Error('That checkpoint is not part of this chat.'); + } + return id; + } + + // ---- Worktrees (AF12) ------------------------------------------------------- + + /** Whether a new chat of the window's folder can have its own worktree. */ + async worktreeAvailability(window: WindowPort): Promise { + this.remember(window); + const root = this.options.rootOf(window); + if (!root) { + return { ok: false, message: 'Open a folder to start a chat in a worktree.' }; + } + if (!this.options.worktreeStorageDir) { + return { ok: false, message: 'Worktrees are not available here.' }; + } + if (!this.options.isTrusted(window)) { + return { ok: false, message: 'Trust this folder to start chats in their own worktree.' }; + } + const availability = await canUseWorktrees(root); + return availability.ok ? { ok: true, message: null } : { ok: false, message: availability.message }; + } + + async worktreeStatus(window: WindowPort, sessionId: unknown): Promise { + const { live, worktree } = await this.worktreeOf(window, sessionId); + const into = await currentBranch(worktree.repoRoot); + if (worktree.removed) { + return { branch: worktree.branch, into, exists: false, removed: true, files: [], ahead: 0, behind: 0, hasUncommitted: false }; + } + const status = await this.worktreeCall(() => worktreeStatus(this.worktreeInfo(live))); + return { + branch: worktree.branch, + into, + exists: status.exists, + removed: false, + files: status.files.map((file) => ({ path: file.path, status: file.status, committed: file.committed, uncommitted: file.uncommitted })), + ahead: status.ahead, + behind: status.behind, + hasUncommitted: status.hasUncommitted, + }; + } + + async worktreeCommit(window: WindowPort, sessionId: unknown, message: unknown): Promise { + const { live } = await this.worktreeOf(window, sessionId, true); + const text = typeof message === 'string' ? message.trim() : ''; + if (!text || text.length > 10_000 || text.includes('\0')) { + throw new Error('A commit needs a message of at most 10,000 characters.'); + } + const result = await this.worktreeCall(() => commitAll(this.worktreeInfo(live), text)); + return { commit: result?.commit ?? null, fileCount: result?.fileCount ?? 0 }; + } + + async worktreeMerge(window: WindowPort, sessionId: unknown, strategy: unknown): Promise { + const { live } = await this.worktreeOf(window, sessionId, true); + if (strategy !== 'merge' && strategy !== 'squash') { + throw new Error('Unknown merge strategy.'); + } + // The merge into the person's branch runs their hooks: only in a trusted folder. + if (!this.options.isTrusted(window)) { + throw new Error('This folder is in Restricted Mode. Trust it to merge an agent\'s branch into it.'); + } + const message = strategy === 'squash' ? live.state.title : undefined; + const result = await this.worktreeCall(() => mergeIntoCurrent(this.worktreeInfo(live), { strategy, message })); + return { strategy: result.strategy, into: result.into, commit: result.commit, nothingToMerge: result.nothingToMerge }; + } + + /** Removes the chat's worktree and deletes its branch; the chat stays, read-only. */ + async worktreeDiscard(window: WindowPort, sessionId: unknown): Promise { + const { live, worktree } = await this.worktreeOf(window, sessionId, true); + this.stopAgent(live); + await this.worktreeCall(() => removeWorktree(this.worktreeInfo(live), { deleteBranch: true })); + this.emit(live, { type: 'worktree', worktree: { ...worktree, removed: true } }); + this.setPendingCount(live, 0); + await this.hook('review.forget', () => this.options.review?.forget?.(live.state.id)); + await this.options.store.saveNow(live.state); + this.sessionsChanged(); + } + + /** The chat and its worktree, for a worktree call of a window that has the chat's folder open. */ + private async worktreeOf(window: WindowPort, sessionId: unknown, mutating = false): Promise<{ live: Live; worktree: SessionWorktree }> { + this.remember(window); + const live = await this.open(window, sessionId); + if (this.options.rootOf(window) !== live.root) { + throw new Error(`This chat belongs to ${live.root}; open that folder to manage its worktree.`); + } + const worktree = live.state.worktree; + if (!worktree) { + throw new Error('This chat does not have a worktree.'); + } + if (mutating) { + if (worktree.removed) { + throw new Error('The worktree of this chat was discarded.'); + } + if (live.turnActive) { + throw new Error('The agent is still working. Stop it or wait for it to finish, then try again.'); + } + } + this.checkWorktreeLocation(worktree); + return { live, worktree }; + } + + /** What worktreeManager needs, rebuilt from the chat's stored record (never from the page). */ + private worktreeInfo(live: Live): WorktreeInfo { + const worktree = live.state.worktree; + if (!worktree) { + throw new Error('This chat does not have a worktree.'); + } + this.checkWorktreeLocation(worktree); + return { sessionId: live.state.id, label: live.state.title, repoRoot: worktree.repoRoot, path: worktree.path, cwd: worktree.cwd, branch: worktree.branch, baseCommit: worktree.baseCommit, createdAt: 0 }; + } + + /** A worktree record is only acted on when it lies in the IDE's own worktree folder. */ + private checkWorktreeLocation(worktree: SessionWorktree): void { + const storage = this.options.worktreeStorageDir; + const inside = (dir: string): boolean => isSameOrInside(dir, worktree.path, this.platform) && path.resolve(worktree.path) !== path.resolve(dir); + if (!storage || !(inside(path.resolve(storage)) || inside(this.realStorageDir(storage))) || !isSameOrInside(worktree.path, worktree.cwd, this.platform)) { + throw new Error('The worktree of this chat is not one the IDE created.'); + } + } + + private realStorageDir(storage: string): string { + if (this.storageReal === undefined) { + try { + this.storageReal = fs.realpathSync.native(storage); + } catch { + // Not created yet: try again next time. + return path.resolve(storage); + } + } + return this.storageReal ?? path.resolve(storage); + } + + private requireWorktreeStorage(): string { + if (!this.options.worktreeStorageDir) { + throw new Error('Worktrees are not available here.'); + } + return this.options.worktreeStorageDir; + } + + /** Runs a worktreeManager call; its refusals reach the page as plain errors with the files involved. */ + private async worktreeCall(run: () => Promise): Promise { + try { + return await run(); + } catch (error) { + if (error instanceof WorktreeError) { + const files = error.files.length === 0 ? '' : ` Files: ${error.files.slice(0, 8).join(', ')}${error.files.length > 8 ? ` and ${error.files.length - 8} more` : ''}.`; + throw new Error(`${error.message}${files}`); + } + throw new Error(errorMessage(error)); + } + } + + /** The folder the chat's agent works in: its worktree (AF12), or the project. */ + private workRoot(live: Live): string { + const worktree = live.state.worktree; + if (!worktree) { + return live.root; + } + if (worktree.removed) { + throw new Error('The worktree of this chat was discarded, so it cannot continue. Start a new chat.'); + } + this.checkWorktreeLocation(worktree); + return worktree.cwd; + } + + // ---- Windows and shutdown ------------------------------------------------- + + /** A window closed: its chats' agents stop (a running turn ends in error and is saved). */ + windowClosed(windowId: number): void { + this.ports.delete(windowId); + for (const live of this.live.values()) { + if (live.ownerId === windowId) { + this.stopAgent(live); + live.ownerId = null; + } + } + } + + /** A window opened another folder: agents of chats of the previous folder stop. */ + folderChanged(windowId: number, root: string | null): void { + for (const live of this.live.values()) { + if (live.ownerId === windowId && live.root !== root) { + this.stopAgent(live); + live.ownerId = null; + } + } + } + + /** 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(); + } + + // ---- Internals ------------------------------------------------------------ + + private remember(window: WindowPort): void { + this.ports.set(window.id, window); + } + + private track(state: AgentSessionState, root: string, ownerId: number | null): Live { + const live: Live = { + state, + root, + ownerId, + agent: null, + starting: null, + turnActive: false, + cancelRequested: false, + cancelTimer: null, + replaying: false, + configRaw: [], + permissions: new Map(), + terminalBuffer: new Map(), + terminalTimer: null, + }; + this.live.set(state.id, live); + return live; + } + + /** The chat, loaded from disk when it is not open yet; the calling window becomes its owner when it has the chat's folder. */ + private async open(window: WindowPort, sessionId: unknown): Promise { + if (!isSessionId(sessionId)) { + throw new Error('Invalid chat.'); + } + const root = this.options.rootOf(window); + let live = this.live.get(sessionId); + if (!live) { + const state = await this.options.store.find(sessionId, root); + if (!state || !state.workspaceRoot) { + throw new Error('That chat no longer exists.'); + } + live = this.live.get(sessionId) ?? this.track(state, state.workspaceRoot, null); + } + if (root !== null && live.root === root) { + live.ownerId = window.id; + } else if (live.ownerId === null) { + live.ownerId = window.id; + } + return live; + } + + private assertContinuable(live: Live, window: WindowPort): void { + if (this.options.rootOf(window) !== live.root) { + throw new Error(`This chat belongs to ${live.root}; open that folder to continue it.`); + } + if (live.state.worktree?.removed) { + throw new Error('The worktree of this chat was discarded, so it cannot continue. Start a new chat.'); + } + } + + private emit(live: Live, event: SessionEvent): void { + const updatedAt = this.now(); + live.state = applySessionEvent(live.state, event, updatedAt); + const port = live.ownerId === null ? undefined : this.ports.get(live.ownerId); + if (port && !port.isDestroyed()) { + port.send({ kind: 'event', sessionId: live.state.id, event, updatedAt }); + } + this.options.store.save(live.state); + if (event.type === 'title' || event.type === 'status' || event.type === 'permission' || event.type === 'pending-changes') { + this.sessionsChanged(); + } + } + + private broadcast(message: AgentSessionMessage): void { + for (const [id, port] of this.ports) { + if (port.isDestroyed()) { + this.ports.delete(id); + } else { + port.send(message); + } + } + } + + /** The sessions sidebar of every window refreshes, at most once per 100 ms. */ + private sessionsChanged(): void { + if (this.sessionsChangedTimer) { + return; + } + this.sessionsChangedTimer = setTimeout(() => { + this.sessionsChangedTimer = null; + this.broadcast({ kind: 'sessions-changed' }); + }, 100); + this.sessionsChangedTimer.unref?.(); + } + + private ensureAgent(live: Live, window: WindowPort): Promise { + if (live.agent && !live.agent.connection.isClosed) { + return Promise.resolve(live.agent); + } + live.starting ??= this.startAgent(live, window).finally(() => { + live.starting = null; + }); + return live.starting; + } + + private async startAgent(live: Live, window: WindowPort): Promise { + const { catalog } = this.options; + if (!this.options.spawnAllowed) { + throw new Error('Agents cannot start in this mode.'); + } + if (this.options.rootOf(window) !== live.root) { + throw new Error(`This chat belongs to ${live.root}; open that folder to continue it.`); + } + if (!this.options.isTrusted(window)) { + throw new Error('This folder is in Restricted Mode. Trust it to let a coding agent work in it.'); + } + const agentRef = live.state.agentRef; + const definition = catalog.definition(agentRef); + if (!definition) { + throw new Error('The agent of this chat no longer exists.'); + } + const resolution = await catalog.resolve(definition); + if (!resolution.found) { + throw new Error(resolution.detail); + } + // AF12: a worktree chat's agent works, reads, writes and runs commands in its worktree only. + const workRoot = this.workRoot(live); + if (live.state.worktree && !(await isDirectory(workRoot))) { + throw new Error(`The worktree of this chat is missing (${workRoot}). Discard it from the Worktree bar and start a new chat.`); + } + const terminals = new AgentTerminals({ + root: workRoot, + env: this.options.terminalEnv, + isInside: (root, candidate) => isSameOrInside(root, candidate, this.platform), + 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(); + if (live.agent?.connection === connection) { + live.agent = null; + this.cancelPermissions(live); + if (error && !live.turnActive && !this.stopped) { + this.emit(live, { type: 'notice', id: randomUUID(), level: 'warning', text: `${errorMessage(error)} It starts again with the next message.` }); + } + } + }); + const timeout = this.options.startTimeoutMs ?? 60_000; + try { + const init = await withTimeout(connection.initialize(), timeout, 'The agent did not answer initialize in time.'); + const authMethods = mapAuthMethods(init.authMethods ?? []); + catalog.setState(agentRef, { availability: catalog.state(agentRef)?.availability ?? 'available', authMethods }); + // AF12: the analysis follows the project, not a chat's worktree, so the MCP server gets the project. + const mcpServers = [...((await this.hook('mcpServers', () => this.options.mcpServers?.(live.root))) ?? [])]; + const previous = live.state.agentSessionId; + let sessionId: string | null = null; + if (previous && init.agentCapabilities?.loadSession) { + live.replaying = true; + try { + const loaded = await withTimeout(connection.loadSession(previous, workRoot, mcpServers), timeout, 'The agent did not reopen the chat in time.'); + sessionId = previous; + this.applySessionSetup(live, loaded.modes, loaded.configOptions); + } catch (error) { + if (isAuthRequiredError(error)) { + throw error; + } + this.emit(live, { type: 'notice', id: randomUUID(), level: 'info', text: `${definition.name} could not reopen its earlier session (${errorMessage(error)}); it starts a new one and does not remember the earlier messages.` }); + } finally { + live.replaying = false; + } + } + if (!sessionId) { + const created = await withTimeout(connection.newSession(workRoot, mcpServers), timeout, 'The agent did not open a session in time.'); + sessionId = created.sessionId; + const hadHistory = live.state.items.some((item) => item.kind === 'turn-end'); + if (hadHistory && !(previous && init.agentCapabilities?.loadSession)) { + this.emit(live, { type: 'notice', id: randomUUID(), level: 'info', text: `${definition.name} cannot reopen earlier sessions, so it starts a new one and does not remember the earlier messages of this chat.` }); + } + this.emit(live, { type: 'agent-session', agentSessionId: sessionId }); + this.applySessionSetup(live, created.modes, created.configOptions); + } + const previousState = catalog.state(agentRef)?.availability; + catalog.setState(agentRef, { availability: 'ready', authMethods }); + if (previousState !== 'ready') { + this.broadcast({ kind: 'agents-changed' }); + } + const runtime: AgentRuntime = { connection, sessionId, init, terminals }; + live.agent = runtime; + return runtime; + } catch (error) { + connection.close(); + throw error; + } + } + + private applySessionSetup(live: Live, modes: SessionModeState | null | undefined, configOptions: readonly SessionConfigOption[] | null | undefined): void { + if (modes) { + const mapped = mapModes(modes); + this.emit(live, { type: 'modes', current: mapped.current, available: mapped.available }); + } + if (configOptions) { + live.configRaw = configOptions; + this.emit(live, { type: 'config', options: mapConfigOptions(configOptions) }); + } + } + + private handlersFor(live: Live, terminals: AgentTerminals): AcpClientHandlers { + const ctx: MappingContext = { newId: () => randomUUID(), terminal: (id) => terminals.snapshot(id) }; + return { + onUpdate: (_sessionId, update) => this.onUpdate(live, update, ctx), + requestPermission: (params, signal) => this.onPermission(live, params, signal, ctx), + readTextFile: (params) => this.onReadText(live, params), + writeTextFile: (params) => this.onWriteText(live, params), + createTerminal: (params) => { + this.flushTerminalOutput(live); + return Promise.resolve({ terminalId: terminals.create(params) }); + }, + terminalOutput: (params) => terminals.output(params.terminalId), + waitForTerminalExit: (params, signal) => terminals.waitForExit(params.terminalId, signal), + killTerminal: (params) => terminals.kill(params.terminalId), + releaseTerminal: (params) => { + this.flushTerminalOutput(live); + terminals.release(params.terminalId); + }, + }; + } + + private onUpdate(live: Live, update: SessionUpdate, ctx: MappingContext): void { + if (live.replaying && !['available_commands_update', 'current_mode_update', 'config_option_update', 'usage_update'].includes(update.sessionUpdate)) { + // `session/load` replays the history the IDE already has. + return; + } + if (update.sessionUpdate === 'config_option_update') { + live.configRaw = update.configOptions; + } + if (update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update') { + this.flushTerminalOutput(live); + } + for (const event of mapSessionUpdate(update, ctx)) { + this.emit(live, event); + } + } + + private async onPermission(live: Live, params: RequestPermissionRequest, signal: AbortSignal, ctx: MappingContext): Promise { + const toolCall = params.toolCall; + const existing = live.state.items.find((item) => item.kind === 'tool' && item.id === toolCall.toolCallId); + const card = toolEvent(toolCall, ctx, !existing); + if (!existing || Object.keys(card).length > 2) { + this.emit(live, card); + } + const toolKind = toolCall.kind ? toolKindOf(toolCall.kind) : existing?.kind === 'tool' ? existing.toolKind : 'other'; + const options: PermissionOptionView[] = params.options.map((option) => ({ id: option.optionId, name: option.name, kind: option.kind })); + const remembered = this.decisionFor(live.state.agentRef, toolKind); + if (remembered) { + const kinds = remembered === 'allow' ? ['allow_always', 'allow_once'] : ['reject_always', 'reject_once']; + const option = kinds.map((kind) => options.find((candidate) => candidate.kind === kind)).find((candidate) => candidate !== undefined); + if (option) { + return { outcome: { outcome: 'selected', optionId: option.id } }; + } + } + if (live.cancelRequested || signal.aborted) { + return { outcome: { outcome: 'cancelled' } }; + } + const id = randomUUID(); + const title = (typeof toolCall.title === 'string' && toolCall.title) || (existing?.kind === 'tool' ? existing.title : '') || 'The agent asks for permission'; + this.emit(live, { type: 'permission', id, title, options, toolCallId: toolCall.toolCallId }); + return new Promise((resolve) => { + live.permissions.set(id, { options, toolKind, resolve }); + signal.addEventListener('abort', () => this.settlePermission(live, id, { outcome: { outcome: 'cancelled' } }, 'cancelled'), { once: true }); + }); + } + + private settlePermission(live: Live, id: string, response: RequestPermissionResponse, outcome: string): void { + const pending = live.permissions.get(id); + if (!pending) { + return; + } + live.permissions.delete(id); + this.emit(live, { type: 'permission-resolved', id, outcome }); + pending.resolve(response); + } + + private cancelPermissions(live: Live): void { + for (const id of [...live.permissions.keys()]) { + this.settlePermission(live, id, { outcome: { outcome: 'cancelled' } }, 'cancelled'); + } + } + + private decisionFor(agentRef: string, toolKind: ToolKind): 'allow' | 'reject' | null { + const all = this.options.decisions.get>>(DECISIONS_KEY) ?? {}; + const value = all[agentRef]?.[toolKind]; + return value === 'allow' || value === 'reject' ? value : null; + } + + private async rememberDecision(agentRef: string, toolKind: ToolKind, decision: 'allow' | 'reject'): Promise { + const all = this.options.decisions.get>>(DECISIONS_KEY) ?? {}; + await this.options.decisions.update(DECISIONS_KEY, { ...all, [agentRef]: { ...(all[agentRef] ?? {}), [toolKind]: decision } }); + } + + /** An absolute path the agent named, refused unless it is inside the chat's project (symbolic links followed). */ + private async insideRoot(live: Live, requested: unknown): Promise { + if (typeof requested !== 'string' || !requested || requested.includes('\0')) { + throw new Error('Invalid path.'); + } + const api = this.platform === 'win32' ? path.win32 : path.posix; + if (!api.isAbsolute(requested)) { + throw new Error(`Paths must be absolute: ${requested}`); + } + const target = api.resolve(requested); + const root = this.workRoot(live); + const refuse = (): Error => new Error(`${requested} is outside the ${live.state.worktree ? 'chat\'s worktree' : 'project folder'} ${root}; agents only read and write inside it.`); + if (!isSameOrInside(root, target, this.platform)) { + throw refuse(); + } + // A link inside the project must not lead outside it: check the real path of the nearest existing ancestor. + let existing = target; + for (;;) { + try { + const real = await fs.promises.realpath(existing); + const realRoot = await fs.promises.realpath(root).catch(() => root); + if (!isSameOrInside(realRoot, real, this.platform)) { + throw refuse(); + } + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + const parent = api.dirname(existing); + if (parent === existing) { + break; + } + existing = parent; + } + } + return target; + } + + private async onReadText(live: Live, params: ReadTextFileRequest): Promise { + const file = await this.insideRoot(live, params.path); + const stat = await fs.promises.stat(file).catch(() => null); + if (stat && stat.size > MAX_READ_FILE) { + throw new Error(`${params.path} is larger than 10 MB.`); + } + const text = await this.options.readText(file); + return { content: sliceLines(text, params.line, params.limit) }; + } + + private async onWriteText(live: Live, params: WriteTextFileRequest): Promise { + const file = await this.insideRoot(live, params.path); + if (typeof params.content !== 'string') { + throw new Error('Invalid content.'); + } + await this.options.writeText(file, params.content); + } + + private async resolveAttachments(root: string, input: unknown): Promise<{ resolved: ResolvedAttachment[]; labels: string[] }> { + if (input === undefined || input === null) { + return { resolved: [], labels: [] }; + } + if (!Array.isArray(input) || input.length > MAX_ATTACHMENTS) { + throw new Error(`At most ${MAX_ATTACHMENTS} attachments.`); + } + const resolved: ResolvedAttachment[] = []; + const labels: string[] = []; + 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) { + throw new Error('Invalid attachment.'); + } + const api = this.platform === 'win32' ? path.win32 : path.posix; + const absolutePath = api.resolve(root, attachment.path); + if (!isSameOrInside(root, absolutePath, this.platform)) { + throw new Error(`${attachment.path} 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) { + 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 } : {}) }); + continue; + } + let text: string | null = null; + const stat = await fs.promises.stat(absolutePath).catch(() => null); + 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 }); + } + return { resolved, labels }; + } + + private queueTerminalOutput(live: Live, terminalId: string, chunk: string, exitCode: number | null | undefined, truncated: boolean): void { + const buffered = live.terminalBuffer.get(terminalId) ?? { output: '', truncated: false }; + buffered.output += chunk; + buffered.truncated ||= truncated; + if (exitCode !== undefined) { + buffered.exitCode = exitCode; + } + live.terminalBuffer.set(terminalId, buffered); + if (exitCode !== undefined) { + this.flushTerminalOutput(live); + return; + } + live.terminalTimer ??= setTimeout(() => this.flushTerminalOutput(live), TERMINAL_FLUSH_MS); + } + + private flushTerminalOutput(live: Live): void { + if (live.terminalTimer) { + clearTimeout(live.terminalTimer); + live.terminalTimer = null; + } + for (const [terminalId, buffered] of live.terminalBuffer) { + this.emit(live, { + type: 'terminal-output', + terminalId, + output: buffered.output, + ...(buffered.exitCode !== undefined ? { exitCode: buffered.exitCode } : {}), + ...(buffered.truncated ? { truncated: true } : {}), + }); + } + live.terminalBuffer.clear(); + } + + /** Runs an optional hook of another feature; its failure is logged and never fails the chat. */ + private async hook(name: string, run: () => T | Promise | undefined): Promise { + try { + return (await run()) ?? null; + } catch (error) { + this.options.log?.(`The ${name} hook failed: ${errorMessage(error)}`); + return null; + } + } + + private async reportPendingChanges(live: Live, turnId: string): Promise { + const count = await this.hook('afterTurn', () => this.options.afterTurn?.(live.state.id, this.workRoot(live), turnId)); + this.setPendingCount(live, count); + } + + private setPendingCount(live: Live, count: number | null): void { + if (typeof count === 'number' && Number.isInteger(count) && count >= 0 && count !== live.state.pendingChanges) { + this.emit(live, { type: 'pending-changes', count }); + } + } + + /** The review calls: the window must have the chat's folder open, and the review must exist. */ + private async reviewOf(window: WindowPort, sessionId: unknown, mutating: boolean): Promise<{ live: Live; review: ChangeReview }> { + this.remember(window); + const live = await this.open(window, sessionId); + this.assertContinuable(live, window); + const review = this.options.review; + if (!review) { + throw new Error('Checkpoints are not available here.'); + } + if (mutating && live.turnActive) { + throw new Error('The agent is still working. Stop it or wait for it to finish, then try again.'); + } + return { live, review }; + } + + /** Refreshes the chat's pending count after a review action and returns the list. */ + private async refreshChanges(live: Live, review: ChangeReview): Promise { + const changes = await review.pending(live.state.id, this.workRoot(live)); + if (changes.disabledReason === null) { + this.setPendingCount(live, changes.files.length); + } + return changes; + } + + private reportFailure(live: Live, error: unknown): void { + if (isAuthRequiredError(error)) { + this.markNeedsLogin(live); + this.emit(live, { type: 'notice', id: randomUUID(), level: 'error', text: `${live.state.agentName} needs you to log in. Choose Log in for it in the agent picker, then send the message again.` }); + return; + } + this.emit(live, { type: 'notice', id: randomUUID(), level: 'error', text: errorMessage(error) }); + } + + /** A chat's agent could not start in the background (no turn was running). */ + private reportStartFailure(live: Live, error: unknown): void { + if (!this.live.has(live.state.id)) { + return; + } + this.reportFailure(live, error); + } + + private markNeedsLogin(live: Live): void { + const agentRef = live.state.agentRef; + const state = this.options.catalog.state(agentRef); + if (state?.availability !== 'needs-login') { + this.options.catalog.setState(agentRef, { availability: 'needs-login', detail: 'Log in to use this agent.' }); + this.broadcast({ kind: 'agents-changed' }); + } + } + + private stopAgent(live: Live): void { + this.cancelPermissions(live); + const agent = live.agent; + live.agent = null; + agent?.connection.close(); + agent?.terminals.disposeAll(); + if (live.terminalTimer) { + clearTimeout(live.terminalTimer); + live.terminalTimer = null; + } + live.terminalBuffer.clear(); + } +} diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts new file mode 100644 index 000000000..6ec5a43df --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -0,0 +1,49 @@ +import type { IpcMainInvokeEvent } from 'electron'; +import { AGENT_SESSION_CHANNELS } from '../../shared/agentSession.ts'; +import type { AgentSessionsRuntime } from './agentSessionsRuntime.ts'; + +type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; + +/** + * AF1: the main-process side of `window.codexr.agentSessions`, registered + * through ipc.ts's `handle` so the trusted-frame check applies. The renderer + * is not trusted: every argument goes to the service as `unknown` and is + * validated there, and the calling window (never an id the page sends) decides + * which folder a chat belongs to. Only the documented members are returned. + */ +export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessionsRuntime): void { + const { service, portOf } = runtime; + const C = AGENT_SESSION_CHANNELS; + handle(C.listAgents, (event) => service.listAgents(portOf(event.sender))); + handle(C.probeAgent, (event, ref) => service.probeAgent(portOf(event.sender), ref)); + handle(C.saveCustomAgent, (event, input, id) => service.saveCustomAgent(portOf(event.sender), input, id, (line) => runtime.confirmCustomAgent(event.sender, line))); + handle(C.removeCustomAgent, (event, id) => service.removeCustomAgent(portOf(event.sender), id)); + handle(C.login, (event, ref, methodId) => service.login(portOf(event.sender), ref, methodId)); + handle(C.listProjects, (event) => service.listProjects(portOf(event.sender))); + handle(C.get, (event, id) => service.get(portOf(event.sender), id)); + handle(C.create, (event, ref, options) => service.create(portOf(event.sender), ref, options)); + handle(C.prompt, (event, id, text, attachments) => service.prompt(portOf(event.sender), id, text, attachments)); + handle(C.cancel, (event, id) => service.cancel(portOf(event.sender), id)); + handle(C.respondPermission, (event, id, requestId, optionId) => service.respondPermission(portOf(event.sender), id, requestId, optionId)); + handle(C.setMode, (event, id, modeId) => service.setMode(portOf(event.sender), id, modeId)); + handle(C.setConfigOption, (event, id, optionId, valueId) => service.setConfigOption(portOf(event.sender), id, optionId, valueId)); + 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.changes, (event, id) => service.changes(portOf(event.sender), id)); + 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.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. + handle(C.worktreeAvailability, (event) => service.worktreeAvailability(portOf(event.sender))); + handle(C.worktreeStatus, (event, id) => service.worktreeStatus(portOf(event.sender), id)); + handle(C.worktreeCommit, (event, id, message) => service.worktreeCommit(portOf(event.sender), id, message)); + handle(C.worktreeMerge, (event, id, strategy) => service.worktreeMerge(portOf(event.sender), id, strategy)); + handle(C.worktreeDiscard, (event, id) => service.worktreeDiscard(portOf(event.sender), id)); + // AF2: the registry is read only on request; installing and removing ask natively first. + 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))); +} diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts new file mode 100644 index 000000000..68742c3ae --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -0,0 +1,279 @@ +import { app, BrowserWindow, dialog, net, webContents, type WebContents } from 'electron'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { AGENT_SESSION_EVENTS, type InstallDescription } from '../../shared/agentSession.ts'; +import { shellCommand, shellKind } from '../../shared/tasks.ts'; +import { JsonKeyValueStore } from '../core/jsonStore.ts'; +import { log } from '../log.ts'; +import type { AgentProfiles } from '../agents/agentProfiles.ts'; +import type { TerminalHost } from '../terminal/terminalHost.ts'; +import { terminalEnvironment } from '../terminal/terminalService.ts'; +import { isWorkspaceTrusted } from '../trust/workspaceTrust.ts'; +import { addFolderChangeListener, currentWorkspaceInfo } from '../workspace/workspaceWindows.ts'; +import { AgentCatalog } from './agentCatalog.ts'; +import { AgentInstaller, consentDetail } from './agentInstaller.ts'; +import { AgentSessionService, type WindowPort } from './agentSessionService.ts'; +import { loginCommandLine } from './agentTerminals.ts'; +import { SessionStore } from './sessionStore.ts'; +import { codexrMcpServerSpec } from './codexrMcpSpec.ts'; +import { SessionChanges } from '../checkpoints/sessionChanges.ts'; +import { toTurnMetricDeltaView } from '../analysis/metricDelta.ts'; +import type { AnalysisService } from '../analysis/analysisService.ts'; +import type { FileMetrics } from '../agents/tools/analysisQueries.ts'; + +/** + * AF1: builds the agent-first chat service and wires it into Electron: the + * user-data folders, the window of each call (`WindowPort`), workspace trust, + * the integrated terminal for terminal logins, and the end of windows and of + * the app. The smoke run keeps its data in a throwaway folder and may not + * start any agent process. + */ +export interface AgentSessionsRuntime { + readonly service: AgentSessionService; + /** The window of an IPC call, as the service addresses it. */ + portOf(contents: WebContents): WindowPort; + /** Asks the person, in a native dialog the page cannot answer, to confirm a custom agent's command line. */ + confirmCustomAgent(contents: WebContents, commandLine: string): Promise; + /** AF2: the consent to download and install an adapter, in a native dialog showing exactly what. */ + confirmInstall(contents: WebContents, description: InstallDescription): Promise; + /** AF2: the confirmation to remove an adapter the IDE installed. */ + confirmUninstall(contents: WebContents, packageName: string, version: string): Promise; +} + +const MAX_REGISTRY_RESPONSE = 32 * 1024 * 1024; + +/** + * AF2: one registry GET through Chromium's network stack (`net.fetch`), so the + * system's proxy and certificate settings apply as they do in the browser. + */ +async function fetchRegistryJson(url: string): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 30_000); + try { + const response = await net.fetch(url, { signal: controller.signal, headers: { accept: 'application/json' } }); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`.trim()); + } + const text = await response.text(); + if (text.length > MAX_REGISTRY_RESPONSE) { + throw new Error('The registry answer is too large.'); + } + return JSON.parse(text) as unknown; + } finally { + clearTimeout(timer); + } +} + +async function ask(contents: WebContents, options: Electron.MessageBoxOptions): Promise { + const owner = BrowserWindow.fromWebContents(contents); + const { response } = owner ? await dialog.showMessageBox(owner, options) : await dialog.showMessageBox(options); + return response; +} + +export interface AgentSessionsRuntimeOptions { + readonly isSmoke: boolean; + readonly terminal: TerminalHost; + readonly profiles: AgentProfiles; + /** 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; +} + +/** How long the metric delta waits for the scene to catch up with a turn's edits. */ +const METRIC_DELTA_TIMEOUT_MS = 30_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'); + const dir = path.join(userData, 'agent-sessions'); + const packagesDir = path.join(userData, 'agent-packages'); + const catalog = new AgentCatalog({ + packagesDir, + store: new JsonKeyValueStore(path.join(dir, 'agents.json')), + env: process.env, + platform: process.platform, + execPath: process.execPath, + builtinProfiles: () => options.profiles.list(), + }); + + const ports = new Map(); + const portOf = (contents: WebContents): WindowPort => { + let port = ports.get(contents.id); + if (!port) { + const id = contents.id; + port = { + id, + send: (message) => { + if (!contents.isDestroyed()) { + contents.send(AGENT_SESSION_EVENTS.message, message); + } + }, + isDestroyed: () => contents.isDestroyed(), + }; + ports.set(id, port); + // A window's agents stop with it: closed, crashed or reloaded (a reloaded page lost its chat views). + contents.once('destroyed', () => { + ports.delete(id); + service.windowClosed(id); + }); + contents.on('render-process-gone', () => service.windowClosed(id)); + } + return port; + }; + const contentsOf = (port: WindowPort): WebContents | null => { + const contents = webContents.fromId(port.id); + return contents && !contents.isDestroyed() ? contents : null; + }; + + // AF5/AF6: snapshots in shadow repositories outside every project, review bases per chat. + const changes = new SessionChanges({ + 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(); + + 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) { + 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); + if (view) { + service.attachMetricDelta(sessionId, turnId, view); + } + }; + + const service: AgentSessionService = new AgentSessionService({ + review: changes, + beforePrompt: async (sessionId, root) => { + const checkpoint = await changes.beforePrompt(sessionId, root); + const owner = options.analysis ? windowOf(root) : null; + const metrics = owner && options.analysis ? await options.analysis.sceneMetrics(owner).catch(() => null) : null; + turnStarts.set(sessionId, { metrics, checkpointId: checkpoint?.checkpointId ?? null }); + return checkpoint; + }, + afterTurn: async (sessionId, root, turnId) => { + // The delta waits for the scene to refresh: it never holds the chat up. + void measureTurn(sessionId, root, turnId).catch((error: unknown) => log.warn(`[agent] Could not measure the turn: ${String(error)}`)); + return changes.afterTurn(sessionId, root); + }, + catalog, + // The smoke run may not download anything: no installer, so every install call is refused. + ...(options.isSmoke ? {} : { installer: new AgentInstaller({ packagesDir, fetchJson: fetchRegistryJson, env: process.env, platform: process.platform, arch: process.arch }) }), + store: new SessionStore(dir), + decisions: new JsonKeyValueStore(path.join(dir, 'permissions.json')), + rootOf: (port) => { + const contents = contentsOf(port); + return contents ? (currentWorkspaceInfo(contents)?.root ?? null) : null; + }, + isTrusted: (port) => { + const contents = contentsOf(port); + return contents ? isWorkspaceTrusted(contents) : false; + }, + // The main process holds no editor buffers (they live in the renderer's Monaco + // models), so agents read the saved file; unsaved edits stay the person's own. + readText: (file) => fs.promises.readFile(file, 'utf8'), + // Written straight to disk: the explorer's and the editor's file watchers + // reload clean tabs and mark edited ones as changed on disk. + writeText: async (file, content) => { + await fs.promises.mkdir(path.dirname(file), { recursive: true }); + await fs.promises.writeFile(file, content, 'utf8'); + }, + openTerminal: async (port, request) => { + const contents = contentsOf(port); + if (!contents) { + throw new Error('The window closed.'); + } + const shell = await options.terminal.defaultShellPath(); + const kind = shellKind(shell); + const line = loginCommandLine(kind, shellCommand(shell, [request.command, ...request.args]), request.env, terminalEnvironment(process.env)); + let markExited: (code: number) => void = () => undefined; + const exited = new Promise((resolve) => { + markExited = resolve; + }); + const created = await options.terminal.runCommand(contents, line, request.cwd, 100, 30, { onExit: (_id, exitCode) => markExited(exitCode) }); + return { terminal: { terminalId: created.id, title: request.title, cwd: created.cwd }, exited }; + }, + // AF10: every chat gets the Code-XR MCP server, so the agent can query the + // project's metrics, hotspots, dependencies and evolution itself. + mcpServers: (root) => { + if (!root) { + return []; + } + 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 })]; + }, + // AF12: chats started in a worktree get it here, outside every project. + worktreeStorageDir: path.join(userData, 'worktrees'), + spawnAllowed: !options.isSmoke, + probeDir: path.join(dir, 'probe'), + homeDir: os.homedir(), + terminalEnv: { ...terminalEnvironment(process.env), CI: '1', NO_COLOR: '1', GIT_PAGER: 'cat', PAGER: 'cat' }, + log: (line) => log.info(`[agent] ${line}`), + }); + + // A window that opens another folder stops the agents of its previous folder's chats. + addFolderChangeListener((contents, root) => service.folderChanged(contents.id, root)); + + return { + service, + portOf, + async confirmInstall(contents, description) { + const update = description.installedVersion !== null; + const response = await ask(contents, { + type: 'question', + title: update ? `Update ${description.agentName}` : `Install ${description.agentName}`, + message: update + ? `Update ${description.agentName} from ${description.installedVersion ?? '?'} to ${description.version}?` + : `Download and install ${description.agentName} (${description.packageName}@${description.version})?`, + detail: consentDetail(description), + buttons: [update ? 'Update' : 'Install', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }); + return response === 0; + }, + async confirmUninstall(contents, packageName, version) { + const response = await ask(contents, { + type: 'warning', + title: 'Remove coding agent', + message: `Remove ${packageName}@${version}?`, + detail: `It is deleted from ${packagesDir}. Your sign-in, settings and chats are kept; you can install it again at any time.`, + buttons: ['Remove', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }); + return response === 0; + }, + async confirmCustomAgent(contents, commandLine) { + const owner = BrowserWindow.fromWebContents(contents); + const confirm: Electron.MessageBoxOptions = { + type: 'warning', + title: 'Add coding agent', + message: 'Save this coding agent?', + detail: `Chats with it will start this command in your project folder, with your permissions:\n\n${commandLine}\n\nOnly add agents you trust.`, + buttons: ['Save Agent', 'Cancel'], + defaultId: 1, + cancelId: 1, + noLink: true, + }; + const { response } = owner ? await dialog.showMessageBox(owner, confirm) : await dialog.showMessageBox(confirm); + return response === 0; + }, + }; +} diff --git a/apps/ide/src/main/agentSessions/agentTerminals.ts b/apps/ide/src/main/agentSessions/agentTerminals.ts new file mode 100644 index 000000000..a7abb2b48 --- /dev/null +++ b/apps/ide/src/main/agentSessions/agentTerminals.ts @@ -0,0 +1,232 @@ +import { spawn, type ChildProcess } from 'node:child_process'; +import path from 'node:path'; +import type { CreateTerminalRequest, TerminalOutputResponse, WaitForTerminalExitResponse } from '@agentclientprotocol/sdk'; +import type { TerminalSnapshot } from './acpMapping.ts'; + +/** + * AF1: the ACP `terminal/*` methods. An agent asks the IDE to run a command + * (`terminal/create`) instead of running it itself, so the person sees the + * command and its output live in the tool card. Each terminal is a child + * process with its output kept up to the agent's `outputByteLimit` (the + * oldest output is dropped first, at a character boundary), its exit status, + * 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. + */ + +export const DEFAULT_OUTPUT_LIMIT = 1_000_000; +export const MAX_TERMINALS_PER_SESSION = 32; + +export interface TerminalEvents { + /** New output (already appended to the terminal's buffer), or the exit with an empty chunk. */ + onOutput(terminalId: string, chunk: string, exitCode: number | null | undefined, truncated: boolean): void; +} + +interface Running { + readonly child: ChildProcess; + output: string; + truncated: boolean; + readonly limit: number; + exit: { exitCode: number | null; signal: string | null } | null; + readonly exited: Promise; +} + +/** The last `limit` bytes of `text` (UTF-8), cut at a character boundary. */ +export function keepTail(text: string, limit: number): { text: string; truncated: boolean } { + if (Buffer.byteLength(text, 'utf8') <= limit) { + return { text, truncated: false }; + } + const bytes = Buffer.from(text, 'utf8'); + let start = bytes.length - limit; + // Skip UTF-8 continuation bytes so the result starts on a character. + while (start < bytes.length && ((bytes[start] ?? 0) & 0xc0) === 0x80) { + start++; + } + return { text: bytes.subarray(start).toString('utf8'), truncated: true }; +} + +/** Quotes one argument for the platform's shell when it needs it. */ +function quoteArg(arg: string, platform: NodeJS.Platform): string { + if (arg !== '' && /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(arg)) { + return arg; + } + return platform === 'win32' ? `"${arg.replace(/"/g, '""')}"` : `'${arg.replace(/'/g, `'\\''`)}'`; +} + +/** The command line a terminal runs: the agent's command as written, then its arguments quoted. */ +export function terminalCommandLine(command: string, args: readonly string[], platform: NodeJS.Platform = process.platform): string { + return [command, ...args.map((arg) => quoteArg(arg, platform))].join(' '); +} + +export class AgentTerminals { + private readonly terminals = new Map(); + private readonly root: string; + private readonly env: Readonly>; + private readonly events: TerminalEvents; + private readonly isInside: (root: string, candidate: string) => boolean; + private nextId = 1; + + constructor(options: { readonly root: string; readonly env: Readonly>; readonly events: TerminalEvents; readonly isInside: (root: string, candidate: string) => boolean }) { + this.root = options.root; + this.env = options.env; + this.events = options.events; + this.isInside = options.isInside; + } + + create(params: CreateTerminalRequest): string { + if (typeof params.command !== 'string' || !params.command.trim()) { + throw new Error('terminal/create needs a command.'); + } + if (this.terminals.size >= MAX_TERMINALS_PER_SESSION) { + throw new Error(`At most ${MAX_TERMINALS_PER_SESSION} terminals per chat; release one first.`); + } + const cwd = params.cwd ? path.resolve(this.root, params.cwd) : this.root; + if (!this.isInside(this.root, cwd)) { + throw new Error(`Commands run inside the project folder; ${cwd} is outside it.`); + } + const env: Record = { ...this.env }; + for (const variable of params.env ?? []) { + env[variable.name] = variable.value; + } + const limit = typeof params.outputByteLimit === 'number' && params.outputByteLimit > 0 ? Math.min(params.outputByteLimit, DEFAULT_OUTPUT_LIMIT) : DEFAULT_OUTPUT_LIMIT; + const child = spawn(terminalCommandLine(params.command, params.args ?? []), { + cwd, + env, + shell: true, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + // Its own process group, so a kill reaches what the shell started too. + detached: process.platform !== 'win32', + }); + const id = `term-${this.nextId++}`; + let markExited: () => void = () => undefined; + const exited = new Promise((resolve) => { + markExited = resolve; + }); + const running: Running = { child, output: '', truncated: false, limit, exit: null, exited }; + this.terminals.set(id, running); + const append = (chunk: string): void => { + const kept = keepTail(running.output + chunk, running.limit); + running.output = kept.text; + running.truncated ||= kept.truncated; + this.events.onOutput(id, chunk, undefined, running.truncated); + }; + child.stdout?.setEncoding('utf8'); + child.stderr?.setEncoding('utf8'); + child.stdout?.on('data', append); + child.stderr?.on('data', append); + const finish = (exitCode: number | null, signal: string | null): void => { + if (running.exit) { + return; + } + running.exit = { exitCode, signal }; + this.events.onOutput(id, '', exitCode ?? (signal ? 1 : null), running.truncated); + markExited(); + }; + child.on('error', (error) => { + append(`${error.message}\n`); + finish(127, null); + }); + child.on('close', (code, signal) => finish(code, signal)); + return id; + } + + snapshot(terminalId: string): TerminalSnapshot | undefined { + const running = this.terminals.get(terminalId); + return running ? { output: running.output, exitCode: running.exit ? (running.exit.exitCode ?? 1) : null, truncated: running.truncated } : undefined; + } + + output(terminalId: string): TerminalOutputResponse { + const running = this.get(terminalId); + return { + output: running.output, + truncated: running.truncated, + ...(running.exit ? { exitStatus: { exitCode: running.exit.exitCode, signal: running.exit.signal } } : {}), + }; + } + + async waitForExit(terminalId: string, signal?: AbortSignal): Promise { + const running = this.get(terminalId); + if (!running.exit) { + await new Promise((resolve, reject) => { + const onAbort = (): void => reject(new Error('Cancelled.')); + signal?.addEventListener('abort', onAbort, { once: true }); + void running.exited.then(() => { + signal?.removeEventListener('abort', onAbort); + resolve(); + }); + }); + } + return { exitCode: running.exit?.exitCode ?? null, signal: running.exit?.signal ?? null }; + } + + kill(terminalId: string): void { + const running = this.get(terminalId); + if (!running.exit) { + killTree(running.child); + } + } + + release(terminalId: string): void { + const running = this.terminals.get(terminalId); + if (!running) { + return; + } + if (!running.exit) { + killTree(running.child); + } + this.terminals.delete(terminalId); + } + + disposeAll(): void { + for (const id of [...this.terminals.keys()]) { + this.release(id); + } + } + + private get(terminalId: string): Running { + const running = this.terminals.get(terminalId); + if (!running) { + throw new Error(`Unknown terminal ${terminalId}.`); + } + return running; + } +} + +/** Stops the shell and what it started (on Windows, `taskkill /t`). */ +function killTree(child: ChildProcess): void { + try { + if (process.platform === 'win32' && child.pid !== undefined) { + spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' }).on('error', () => undefined); + } else if (child.pid !== undefined) { + process.kill(-child.pid, 'SIGTERM'); + } else { + child.kill(); + } + } catch { + // Already gone. + } +} + +/** + * The line a terminal login runs in the person's default shell: the agent's + * login command with each argument quoted for that shell, preceded by the + * variables the shell does not already have (`ELECTRON_RUN_AS_NODE` for an + * agent the IDE runs with its own Node, a login method's own variables). + */ +export function loginCommandLine(shell: 'posix' | 'cmd' | 'powershell', quoted: string, env: Readonly>, shellEnv: Readonly>): string { + const extra = Object.entries(env).filter(([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && shellEnv[key] !== value); + if (extra.length === 0) { + return quoted; + } + if (shell === 'powershell') { + return `${extra.map(([key, value]) => `$env:${key}='${value.replace(/'/g, "''")}'`).join('; ')}; ${quoted}`; + } + if (shell === 'cmd') { + if (extra.some(([, value]) => /["%&|<>^]/.test(value))) { + throw new Error('A login variable cannot be passed to cmd.exe safely.'); + } + return `${extra.map(([key, value]) => `set "${key}=${value}"`).join(' && ')} && ${quoted}`; + } + return `env ${extra.map(([key, value]) => `${key}='${value.replace(/'/g, `'\\''`)}'`).join(' ')} ${quoted}`; +} diff --git a/apps/ide/src/main/agentSessions/codexrMcpSpec.ts b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts new file mode 100644 index 000000000..b96409e2c --- /dev/null +++ b/apps/ide/src/main/agentSessions/codexrMcpSpec.ts @@ -0,0 +1,54 @@ +import path from 'node:path'; + +/** + * The stdio MCP server spec that hands Code-XR's analysis to an external + * agent (AF10). The IDE passes it in ACP `session/new` (`mcpServers`), and + * the agent (Claude Code, Codex, Gemini CLI) starts the server itself. + * + * The server is the IDE's own bundle out/codexrMcp/index.cjs, run by the + * IDE's own binary in Node mode (ELECTRON_RUN_AS_NODE=1): no system Node is + * needed, and ACP wants an absolute command, which `execPath` is. + * + * Packaged, `appPath` (app.getAppPath()) is resources/app.asar and the bundle + * stays inside the archive: Electron's patched fs loads a script from an asar + * in Node mode too (checked by running the built bundle from a packed + * app.asar), so it needs no asarUnpack entry and both layouts resolve the + * same way. `isPackaged` is accepted so a caller passes the whole picture + * and a future layout difference has a place to go. + */ + +export interface CodexrMcpSpecOptions { + /** process.execPath of the IDE: Electron itself, or the packaged executable. */ + readonly execPath: string; + /** app.getAppPath(): the folder (or app.asar) that holds out/. */ + readonly appPath: string; + /** The project open in the window (absolute). */ + readonly root: string; + /** The window's analysis output folder, or null when no analysis has run. */ + readonly analysisDir: string | null; + readonly isPackaged: boolean; +} + +/** ACP's McpServerStdio: `env` is a list of name/value pairs, not a map. */ +export interface CodexrMcpServerSpec { + readonly name: string; + readonly command: string; + readonly args: string[]; + readonly env: { name: string; value: string }[]; +} + +export const CODEXR_MCP_SERVER_NAME = 'code-xr'; + +/** The bundle's path inside `appPath` (see the build target in scripts/viteConfigs.mjs). */ +export function codexrMcpEntry(appPath: string): string { + return path.join(appPath, 'out', 'codexrMcp', 'index.cjs'); +} + +export function codexrMcpServerSpec(options: CodexrMcpSpecOptions): CodexrMcpServerSpec { + return { + name: CODEXR_MCP_SERVER_NAME, + command: options.execPath, + args: [codexrMcpEntry(options.appPath), '--root', options.root, '--analysis', options.analysisDir ?? ''], + env: [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }], + }; +} diff --git a/apps/ide/src/main/agentSessions/sessionStore.ts b/apps/ide/src/main/agentSessions/sessionStore.ts new file mode 100644 index 000000000..8ecafb366 --- /dev/null +++ b/apps/ide/src/main/agentSessions/sessionStore.ts @@ -0,0 +1,279 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { summarize, type AgentSessionState, type ProjectSessions, type SessionSummary, type SessionWorktree } from '../../shared/agentSession.ts'; + +/** + * AF1/AF7: the chats, on disk. One JSON file per chat under + * `//.json`, where the project key is the first 24 hex + * characters of the SHA-256 of the project folder (folder names can hold any + * character and any length), plus `projects.json`, the index of projects + * with their name and last use. Every write goes through a temporary file and + * a rename, so a crash never leaves a chat half written. Writes of one chat + * are debounced while the agent streams; `flush` writes at once. + * + * A chat read back from disk was not running any more: whatever state it was + * saved in, it comes back idle (or in error), with no permission waiting. + */ + +export const MAX_PROJECTS = 15; +const DEFAULT_DEBOUNCE_MS = 400; +const SESSION_ID = /^[A-Za-z0-9_-]{1,80}$/; + +interface ProjectEntry { + readonly root: string; + readonly name: string; + readonly lastUsed: string; +} + +export function projectKey(root: string): string { + return createHash('sha256').update(root).digest('hex').slice(0, 24); +} + +export function isSessionId(value: unknown): value is string { + return typeof value === 'string' && SESSION_ID.test(value); +} + +async function writeAtomic(file: string, text: string): Promise { + await fs.promises.mkdir(path.dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + await fs.promises.writeFile(temporary, text, 'utf8'); + await fs.promises.rename(temporary, file); +} + +/** A stored chat as it should look once loaded: nothing can still be running. */ +export function settled(state: AgentSessionState): AgentSessionState { + if (state.status !== 'running' && state.status !== 'awaiting' && !state.items.some((item) => item.kind === 'permission' && item.outcome === undefined)) { + return state; + } + return { + ...state, + status: state.status === 'error' ? 'error' : 'idle', + items: state.items.map((item) => (item.kind === 'permission' && item.outcome === undefined ? { ...item, outcome: 'cancelled' } : item)), + }; +} + +function isState(value: unknown): value is AgentSessionState { + if (!value || typeof value !== 'object') { + return false; + } + const state = value as Partial; + return isSessionId(state.id) && typeof state.title === 'string' && typeof state.agentRef === 'string' && Array.isArray(state.items) && typeof state.updatedAt === 'string'; +} + +/** AF12: a stored worktree record, or undefined when it is missing or malformed. */ +function worktreeOf(value: unknown): SessionWorktree | undefined { + if (!value || typeof value !== 'object') { + return undefined; + } + const record = value as Partial>; + const { branch, path: top, cwd, baseCommit, repoRoot } = record; + if (typeof branch !== 'string' || typeof top !== 'string' || typeof cwd !== 'string' || typeof baseCommit !== 'string' || typeof repoRoot !== 'string') { + return undefined; + } + return { branch, path: top, cwd, baseCommit, repoRoot, ...(record.removed === true ? { removed: true } : {}) }; +} + +/** Fills fields an older file may lack, so the reducer never meets `undefined`. */ +function normalize(state: AgentSessionState): AgentSessionState { + const { worktree: storedWorktree, ...rest } = state; + const worktree = worktreeOf(storedWorktree); + return settled({ + ...rest, + ...(worktree ? { worktree } : {}), + agentName: typeof state.agentName === 'string' ? state.agentName : state.agentRef, + workspaceRoot: typeof state.workspaceRoot === 'string' ? state.workspaceRoot : null, + createdAt: typeof state.createdAt === 'string' ? state.createdAt : state.updatedAt, + unread: state.unread === true, + pendingChanges: typeof state.pendingChanges === 'number' ? state.pendingChanges : 0, + plan: Array.isArray(state.plan) ? state.plan : [], + commands: Array.isArray(state.commands) ? state.commands : [], + modes: state.modes ?? null, + configOptions: Array.isArray(state.configOptions) ? state.configOptions : [], + usage: state.usage ?? null, + agentSessionId: typeof state.agentSessionId === 'string' ? state.agentSessionId : null, + }); +} + +export class SessionStore { + private readonly dir: string; + private readonly debounceMs: number; + private readonly pending = new Map }>(); + private writing: Promise = Promise.resolve(); + private projectsCache: ProjectEntry[] | null = null; + + constructor(dir: string, options: { readonly debounceMs?: number } = {}) { + this.dir = dir; + this.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS; + } + + private fileOf(root: string, id: string): string { + return path.join(this.dir, projectKey(root), `${id}.json`); + } + + /** Saves a chat, at most once per debounce period while it keeps changing. */ + save(state: AgentSessionState): void { + if (!state.workspaceRoot || !isSessionId(state.id)) { + return; + } + const existing = this.pending.get(state.id); + if (existing) { + existing.state = state; + return; + } + const timer = setTimeout(() => void this.flush(state.id), this.debounceMs); + timer.unref?.(); + this.pending.set(state.id, { state, timer }); + } + + /** Writes a chat now (and any debounced write of it). */ + async saveNow(state: AgentSessionState): Promise { + const existing = this.pending.get(state.id); + if (existing) { + clearTimeout(existing.timer); + this.pending.delete(state.id); + } + await this.write(state); + } + + /** Writes a chat's debounced change now; every chat when `id` is omitted. */ + async flush(id?: string): Promise { + const ids = id === undefined ? [...this.pending.keys()] : [id]; + const writes: Promise[] = []; + for (const key of ids) { + const entry = this.pending.get(key); + if (!entry) { + continue; + } + clearTimeout(entry.timer); + this.pending.delete(key); + writes.push(this.write(entry.state)); + } + await Promise.all(writes); + await this.writing; + } + + private write(state: AgentSessionState): Promise { + const root = state.workspaceRoot; + if (!root) { + return Promise.resolve(); + } + const text = `${JSON.stringify(state)}\n`; + this.writing = this.writing.catch(() => undefined).then(async () => { + await writeAtomic(this.fileOf(root, state.id), text); + await this.touchProject(root, state.updatedAt); + }); + return this.writing; + } + + async load(root: string, id: string): Promise { + if (!isSessionId(id)) { + return null; + } + const pending = this.pending.get(id); + if (pending && pending.state.workspaceRoot === root) { + return pending.state; + } + try { + const parsed: unknown = JSON.parse(await fs.promises.readFile(this.fileOf(root, id), 'utf8')); + return isState(parsed) ? normalize({ ...parsed, workspaceRoot: root }) : null; + } catch { + return null; + } + } + + /** Finds a chat in any known project, `preferredRoot` first. */ + async find(id: string, preferredRoot: string | null): Promise { + const roots = (await this.projects()).map((project) => project.root); + const ordered = preferredRoot ? [preferredRoot, ...roots.filter((root) => root !== preferredRoot)] : roots; + for (const root of ordered) { + const state = await this.load(root, id); + if (state) { + return state; + } + } + return null; + } + + async remove(root: string, id: string): Promise { + const pending = this.pending.get(id); + if (pending) { + clearTimeout(pending.timer); + this.pending.delete(id); + } + await this.writing.catch(() => undefined); + await fs.promises.rm(this.fileOf(root, id), { force: true }); + } + + /** The chats of one project, newest first. */ + async list(root: string): Promise { + let names: string[]; + try { + names = await fs.promises.readdir(path.join(this.dir, projectKey(root))); + } catch { + names = []; + } + const ids = new Set(names.filter((name) => name.endsWith('.json')).map((name) => name.slice(0, -5)).filter(isSessionId)); + for (const entry of this.pending.values()) { + if (entry.state.workspaceRoot === root) { + ids.add(entry.state.id); + } + } + const states = await Promise.all([...ids].map((id) => this.load(root, id))); + return states + .filter((state): state is AgentSessionState => state !== null) + .map(summarize) + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + } + + /** Recent projects and their chats: `currentRoot` first, then the others by last use, at most `MAX_PROJECTS`. */ + async listProjects(currentRoot: string | null, overrides?: (summary: SessionSummary) => SessionSummary): Promise { + await this.writing.catch(() => undefined); + const known = await this.projects(); + const others = known.filter((project) => project.root !== currentRoot).sort((a, b) => b.lastUsed.localeCompare(a.lastUsed)); + const roots: { root: string; name: string; current: boolean }[] = []; + if (currentRoot) { + roots.push({ root: currentRoot, name: path.basename(currentRoot) || currentRoot, current: true }); + } + for (const project of others) { + roots.push({ root: project.root, name: project.name, current: false }); + } + const result: ProjectSessions[] = []; + for (const project of roots.slice(0, MAX_PROJECTS)) { + const sessions = await this.list(project.root); + if (!project.current && sessions.length === 0) { + continue; + } + result.push({ ...project, sessions: overrides ? sessions.map(overrides) : sessions }); + } + return result; + } + + private async projects(): Promise { + if (this.projectsCache) { + return this.projectsCache; + } + try { + const parsed: unknown = JSON.parse(await fs.promises.readFile(path.join(this.dir, 'projects.json'), 'utf8')); + this.projectsCache = Array.isArray(parsed) + ? parsed.filter((entry): entry is ProjectEntry => !!entry && typeof entry === 'object' && typeof (entry as ProjectEntry).root === 'string' && typeof (entry as ProjectEntry).name === 'string' && typeof (entry as ProjectEntry).lastUsed === 'string') + : []; + } catch { + this.projectsCache = []; + } + return this.projectsCache; + } + + private async touchProject(root: string, at: string): Promise { + const projects = await this.projects(); + const existing = projects.find((project) => project.root === root); + if (existing && existing.lastUsed >= at) { + return; + } + const next = [{ root, name: path.basename(root) || root, lastUsed: at }, ...projects.filter((project) => project.root !== root)] + .sort((a, b) => b.lastUsed.localeCompare(a.lastUsed)) + .slice(0, 100); + this.projectsCache = next; + await writeAtomic(path.join(this.dir, 'projects.json'), `${JSON.stringify(next, null, 2)}\n`); + } +} diff --git a/apps/ide/src/main/agents/tools/analysisQueries.ts b/apps/ide/src/main/agents/tools/analysisQueries.ts new file mode 100644 index 000000000..24bcdc5b1 --- /dev/null +++ b/apps/ide/src/main/agents/tools/analysisQueries.ts @@ -0,0 +1,322 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { clip, numberArg, stringArg } from './toolTypes.ts'; + +/** + * Code-XR's analysis queries (A10, AF10): the pure, Electron-free half of the + * analysis tools, shared by the built-in agent (analysisTools.ts) and by the + * Code-XR MCP server that external agents get (src/codexrMcp). Each query + * reads only what an XR analysis already wrote into its static folder and + * 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. + * 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. + */ + +export interface FileMetrics { + readonly relativePath: string; + readonly language?: string; + readonly [metric: string]: unknown; +} + +/** The metrics agents are pointed at first (all of a record's numeric fields stay available). */ +export const KEY_METRICS = [ + 'totalLines', 'codeLines', 'commentRatio', 'functionCount', 'classCount', + 'maxComplexity', 'cyclomaticComplexityNumber', 'highComplexityFunctions', 'criticalComplexityFunctions', + 'maxFunctionLines', 'averageFunctionLines', 'maxFunctionParameters', 'averageFunctionNestingDepth', + 'maxCognitiveComplexity', 'averageMaintainabilityIndex', 'totalHalsteadBugs', +] as const; + +const MAX_JSON_BYTES = 64 * 1024 * 1024; + +export const NO_ANALYSIS = 'No Code-XR analysis is open in this window. Ask the person to run "Analyse Project (XR)" from the Analysis view first; agents cannot start one.'; + +async function readJson(file: string): Promise { + const stat = await fs.promises.stat(file); + if (stat.size > MAX_JSON_BYTES) { + throw new Error(`${path.basename(file)} is too large to read.`); + } + return JSON.parse(await fs.promises.readFile(file, 'utf8')) as unknown; +} + +function recordsOf(data: unknown): FileMetrics[] { + return Array.isArray(data) + ? data.filter((item): item is FileMetrics => !!item && typeof item === 'object' && typeof (item as Record)['relativePath'] === 'string') + .map((item) => ({ ...item, relativePath: item.relativePath.replace(/\\/g, '/') })) + : []; +} + +export const normalize = (value: string | undefined): string => (value ?? '').replace(/\\/g, '/').replace(/^\.?\/+/, '').replace(/\/+$/, ''); + +function inScope(file: string, scope: string): boolean { + return !scope || file === scope || file.startsWith(`${scope}/`); +} + +function numeric(record: FileMetrics, metric: string): number | null { + const value = record[metric]; + return typeof value === 'number' && Number.isFinite(value) ? value : null; +} + +const round = (value: number): number => Math.round(value * 100) / 100; + +/** Totals and averages over `records`: what "how big / how complex is this folder" asks. */ +export function summarize(records: readonly FileMetrics[]): Record { + const summary: Record = { files: records.length }; + for (const metric of KEY_METRICS) { + const values = records.map((record) => numeric(record, metric)).filter((value): value is number => value !== null); + if (values.length === 0) { + continue; + } + const sum = values.reduce((a, b) => a + b, 0); + if (/Ratio|average|cyclomaticComplexityNumber/.test(metric)) { + summary[`avg ${metric}`] = round(sum / values.length); + } else { + summary[`total ${metric}`] = round(sum); + summary[`max ${metric}`] = Math.max(...values); + } + } + return summary; +} + +function formatRecord(record: FileMetrics): string { + const parts = KEY_METRICS.map((metric) => [metric, numeric(record, metric)] as const) + .filter(([, value]) => value !== null) + .map(([metric, value]) => `${metric}=${value}`); + return `${record.relativePath}${record.language ? ` (${record.language})` : ''}: ${parts.join(', ')}`; +} + +function formatSummary(summary: Record): string { + return Object.entries(summary).map(([key, value]) => `${key}: ${value}`).join('\n'); +} + +export function metricsReport(records: readonly FileMetrics[], scopeArg: string | undefined): string { + const scope = normalize(scopeArg); + const exact = records.find((record) => record.relativePath === scope); + if (exact) { + return formatRecord(exact); + } + const inside = records.filter((record) => inScope(record.relativePath, scope)); + if (inside.length === 0) { + throw new Error(`The analysis has no file at or under "${scope}". Paths are relative to the project root.`); + } + const byLanguage = new Map(); + for (const record of inside) { + byLanguage.set(record.language ?? 'unknown', (byLanguage.get(record.language ?? 'unknown') ?? 0) + 1); + } + return [ + `${scope || 'Whole project'}: ${inside.length} analysed files`, + `languages: ${[...byLanguage].sort((a, b) => b[1] - a[1]).map(([language, count]) => `${language} ${count}`).join(', ')}`, + formatSummary(summarize(inside)), + ].join('\n'); +} + +export function hotspotsReport(records: readonly FileMetrics[], metric: string, limit: number, scopeArg: string | undefined): string { + const scope = normalize(scopeArg); + const ranked = records + .filter((record) => inScope(record.relativePath, scope)) + .map((record) => ({ record, value: numeric(record, metric) })) + .filter((entry): entry is { record: FileMetrics; value: number } => entry.value !== null) + .sort((a, b) => b.value - a.value) + .slice(0, limit); + if (ranked.length === 0) { + const known = Object.keys(records[0] ?? {}).filter((key) => typeof records[0]?.[key] === 'number'); + throw new Error(`No file has the metric "${metric}". Known metrics: ${known.join(', ')}.`); + } + return [`Top ${ranked.length} files by ${metric}${scope ? ` under ${scope}` : ''}:`, ...ranked.map(({ record, value }, index) => `${index + 1}. ${record.relativePath}: ${metric}=${value} | ${formatRecord(record).split(': ').slice(1).join(': ')}`)].join('\n'); +} + +interface GraphNode { readonly id: string; readonly relativePath?: string; readonly label?: string; readonly external?: boolean; readonly metrics?: Record } +interface GraphEdge { readonly source: string; readonly target: string; readonly kind?: string; readonly occurrences?: number } + +export function dependenciesReport(graph: unknown, fileArg: string | undefined, limit: number): string { + const record = (graph && typeof graph === 'object' ? graph : {}) as { nodes?: GraphNode[]; edges?: GraphEdge[] }; + const nodes = Array.isArray(record.nodes) ? record.nodes : []; + const edges = Array.isArray(record.edges) ? record.edges : []; + const nameOf = (id: string): string => { + const node = nodes.find((candidate) => candidate.id === id); + return node?.relativePath ?? node?.label ?? id; + }; + const file = normalize(fileArg); + if (!file) { + const ranked = nodes.filter((node) => !node.external && node.metrics) + .sort((a, b) => (b.metrics?.['degree'] ?? 0) - (a.metrics?.['degree'] ?? 0)) + .slice(0, limit); + const cycles = nodes.filter((node) => (node.metrics?.['cycleSize'] ?? 0) > 1).map((node) => node.relativePath ?? node.label); + return [ + `${nodes.length} nodes, ${edges.length} edges.`, + `Most connected (fanIn/fanOut):`, + ...ranked.map((node) => `- ${node.relativePath ?? node.label}: fanIn=${node.metrics?.['fanIn'] ?? 0}, fanOut=${node.metrics?.['fanOut'] ?? 0}`), + cycles.length > 0 ? `In dependency cycles: ${cycles.slice(0, limit).join(', ')}${cycles.length > limit ? ` and ${cycles.length - limit} more` : ''}` : 'No dependency cycles.', + ].join('\n'); + } + const node = nodes.find((candidate) => normalize(candidate.relativePath) === file); + if (!node) { + throw new Error(`"${file}" is not in the dependency graph.`); + } + const describe = (list: readonly GraphEdge[], end: 'source' | 'target'): string[] => { + const grouped = new Map(); + for (const edge of list) { + const other = nameOf(edge[end]); + grouped.set(other, [...(grouped.get(other) ?? []), edge.kind ?? 'uses']); + } + return [...grouped].slice(0, limit).map(([other, kinds]) => `- ${other} (${[...new Set(kinds)].join(', ')})`); + }; + const outgoing = edges.filter((edge) => edge.source === node.id); + const incoming = edges.filter((edge) => edge.target === node.id); + return [ + `${file}: ${Object.entries(node.metrics ?? {}).map(([key, value]) => `${key}=${value}`).join(', ')}`, + `Depends on (${outgoing.length}):`, ...describe(outgoing, 'target'), + `Used by (${incoming.length}):`, ...describe(incoming, 'source'), + ].join('\n'); +} + +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 { + const file = normalize(fileArg); + const lines = frames.map(({ frame, records }) => { + const when = [frame.date, frame.label].filter(Boolean).join(' '); + if (file) { + const inside = records.filter((record) => inScope(record.relativePath, file)); + if (inside.length === 0) { + return `- ${when}: (not present)`; + } + const values = inside.map((record) => numeric(record, metric)).filter((value): value is number => value !== null); + const total = values.reduce((a, b) => a + b, 0); + return `- ${when}: ${metric}=${round(inside.length === 1 ? total : total)}${inside.length > 1 ? ` over ${inside.length} files` : ''}`; + } + const summary = summarize(records); + return `- ${when}: files=${summary['files']}, codeLines=${summary['total codeLines'] ?? '?'}, avg complexity=${summary['avg cyclomaticComplexityNumber'] ?? '?'}, max complexity=${summary['max maxComplexity'] ?? '?'}`; + }); + return [`Project evolution, ${frames.length} snapshots (oldest first)${file ? ` for ${file}` : ''}:`, ...lines].join('\n'); +} + +/** The last project-evolution movie under `root`, oldest frame first. */ +export async function readEvolution(root: string): Promise<{ frame: EvolutionFrame; records: FileMetrics[] }[] | null> { + const dir = path.join(root, 'evolution'); + let revisions: number[]; + try { + revisions = (await fs.promises.readdir(dir)).map((name) => /^revision-(\d+)$/.exec(name)?.[1]).filter((value): value is string => !!value).map(Number); + } catch { + return null; + } + const latest = Math.max(...revisions); + if (!Number.isFinite(latest)) { + return null; + } + const manifest = (await readJson(path.join(dir, `revision-${latest}`, 'manifest.json'))) as { frames?: EvolutionFrame[] }; + const frames = Array.isArray(manifest.frames) ? manifest.frames : []; + const out: { frame: EvolutionFrame; records: FileMetrics[] }[] = []; + for (const [index, frame] of frames.entries()) { + const name = path.basename(frame.url ?? `data${index + 1}.json`); + if (!/^data\d+\.json$/.test(name)) { + continue; + } + out.push({ frame, records: recordsOf(await readJson(path.join(dir, `revision-${latest}`, name))) }); + } + return out; +} + +/** The metric records of the analysis in `root`; a missing or unreadable data.json reads as "no analysis". */ +export async function readMetrics(root: string): Promise { + try { + return recordsOf(await readJson(path.join(root, 'data.json'))); + } catch { + throw new Error(NO_ANALYSIS); + } +} + +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. */ +export interface AnalysisQuery { + readonly name: string; + readonly title: string; + readonly description: string; + /** JSON Schema of the arguments: every property optional, strings and integers only. */ + readonly parameters: { + readonly type: 'object'; + readonly properties: Readonly>; + }; + /** 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; +} + +export const ANALYSIS_QUERIES: readonly AnalysisQuery[] = [ + { + name: 'get_metrics', + title: 'Read Code-XR metrics', + description: 'Code-XR metrics (lines, functions, complexity, cognitive complexity, maintainability, parameters, nesting) for one file, or totals and averages for a folder or the whole project, from the analysis open in the IDE.', + parameters: { type: 'object', properties: { path: { type: 'string', description: 'A file or folder relative to the project root; "" for the whole project.' } } }, + summary: (args) => `metrics of ${normalize(args['path'] as string | undefined) || 'the project'}`, + async run(args, root) { + return clip(metricsReport(await readMetrics(root), stringArg(args, 'path', false))); + }, + }, + { + name: 'get_hotspots', + title: 'Find complexity hot spots', + description: 'The files that rank highest on a Code-XR metric (default maxComplexity), optionally under a folder: where to look first for risky code.', + parameters: { + type: 'object', + properties: { + metric: { type: 'string', description: metricDescription }, + limit: { type: 'integer', description: 'How many files (default 10, max 50).' }, + path: { type: 'string', description: 'Only files under this folder.' }, + }, + }, + summary: (args) => `top files by ${String(args['metric'] ?? 'maxComplexity')}`, + async run(args, root) { + const metric = stringArg(args, 'metric', false) ?? 'maxComplexity'; + const limit = Math.min(50, Math.max(1, numberArg(args, 'limit') ?? 10)); + return clip(hotspotsReport(await readMetrics(root), metric, limit, stringArg(args, 'path', false))); + }, + }, + { + name: 'get_dependencies', + title: 'Read the dependency graph', + description: 'From Code-XR\'s dependency graph: for a file, what it depends on and what uses it; without a file, the most connected files and any cycles. Needs the dependency graph mode to have run in the XR scene.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'A file relative to the project root; omit for the overview.' }, + limit: { type: 'integer', description: 'How many entries per list (default 20, max 100).' }, + }, + }, + summary: (args) => `dependencies of ${normalize(args['path'] as string | undefined) || 'the project'}`, + async run(args, root) { + let graph: unknown; + try { + graph = await readJson(path.join(root, 'dependency-graph.json')); + } catch { + throw new Error('The dependency graph has not been computed for this analysis. Ask the person to open the Dependency graph mode in the XR scene once.'); + } + return clip(dependenciesReport(graph, stringArg(args, 'path', false), Math.min(100, Math.max(1, numberArg(args, 'limit') ?? 20)))); + }, + }, + { + name: 'get_evolution', + title: 'Read the project\'s evolution', + description: 'How metrics changed across the Git history snapshots of Code-XR\'s last project-evolution movie: the whole project, or one metric for a file or folder. Needs the Project evolution mode to have run in the XR scene.', + parameters: { + type: 'object', + properties: { + path: { type: 'string', description: 'A file or folder; omit for project totals.' }, + metric: { type: 'string', description: `${metricDescription} Used with path; default codeLines.` }, + }, + }, + summary: (args) => `evolution of ${normalize(args['path'] as string | undefined) || 'the project'}`, + async run(args, root) { + const frames = await readEvolution(root); + if (!frames || frames.length === 0) { + throw new Error('No project-evolution movie has been computed for this analysis. Ask the person to run Project evolution in the XR scene once.'); + } + return clip(evolutionReport(frames, stringArg(args, 'path', false), stringArg(args, 'metric', false) ?? 'codeLines')); + }, + }, +]; diff --git a/apps/ide/src/main/agents/tools/analysisTools.ts b/apps/ide/src/main/agents/tools/analysisTools.ts index 92257b4d9..f6d920a1b 100644 --- a/apps/ide/src/main/agents/tools/analysisTools.ts +++ b/apps/ide/src/main/agents/tools/analysisTools.ts @@ -1,221 +1,15 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { clip, numberArg, stringArg, type AgentTool, type ToolContext } from './toolTypes.ts'; +import { ANALYSIS_QUERIES, NO_ANALYSIS } from './analysisQueries.ts'; +import type { AgentTool, ToolContext } from './toolTypes.ts'; /** - * Code-XR's analyses as agent tools (A10). They read what the window's XR - * analysis already produced, in the scene's static folder, and never start - * an analysis or download 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. - * This is the bridge to the thesis' prediction work: an agent reasons over - * the same measurements the person sees in XR. + * Code-XR's analyses as tools of the built-in agent (A10). The queries + * themselves live in analysisQueries.ts, shared with the Code-XR MCP server + * that external agents get (AF10); this file only binds them to the window: + * the analysis folder comes from the ToolContext, and every query is a + * read-only tool, so it never needs an approval. */ -export interface FileMetrics { - readonly relativePath: string; - readonly language?: string; - readonly [metric: string]: unknown; -} - -/** The metrics agents are pointed at first (all of a record's numeric fields stay available). */ -export const KEY_METRICS = [ - 'totalLines', 'codeLines', 'commentRatio', 'functionCount', 'classCount', - 'maxComplexity', 'cyclomaticComplexityNumber', 'highComplexityFunctions', 'criticalComplexityFunctions', - 'maxFunctionLines', 'averageFunctionLines', 'maxFunctionParameters', 'averageFunctionNestingDepth', - 'maxCognitiveComplexity', 'averageMaintainabilityIndex', 'totalHalsteadBugs', -] as const; - -const MAX_JSON_BYTES = 64 * 1024 * 1024; - -const NO_ANALYSIS = 'No Code-XR analysis is open in this window. Ask the person to run "Analyse Project (XR)" from the Analysis view first; agents cannot start one.'; - -async function readJson(file: string): Promise { - const stat = await fs.promises.stat(file); - if (stat.size > MAX_JSON_BYTES) { - throw new Error(`${path.basename(file)} is too large to read.`); - } - return JSON.parse(await fs.promises.readFile(file, 'utf8')) as unknown; -} - -function recordsOf(data: unknown): FileMetrics[] { - return Array.isArray(data) - ? data.filter((item): item is FileMetrics => !!item && typeof item === 'object' && typeof (item as Record)['relativePath'] === 'string') - .map((item) => ({ ...item, relativePath: item.relativePath.replace(/\\/g, '/') })) - : []; -} - -const normalize = (value: string | undefined): string => (value ?? '').replace(/\\/g, '/').replace(/^\.?\/+/, '').replace(/\/+$/, ''); - -function inScope(file: string, scope: string): boolean { - return !scope || file === scope || file.startsWith(`${scope}/`); -} - -function numeric(record: FileMetrics, metric: string): number | null { - const value = record[metric]; - return typeof value === 'number' && Number.isFinite(value) ? value : null; -} - -const round = (value: number): number => Math.round(value * 100) / 100; - -/** Totals and averages over `records`: what "how big / how complex is this folder" asks. */ -export function summarize(records: readonly FileMetrics[]): Record { - const summary: Record = { files: records.length }; - for (const metric of KEY_METRICS) { - const values = records.map((record) => numeric(record, metric)).filter((value): value is number => value !== null); - if (values.length === 0) { - continue; - } - const sum = values.reduce((a, b) => a + b, 0); - if (/Ratio|average|cyclomaticComplexityNumber/.test(metric)) { - summary[`avg ${metric}`] = round(sum / values.length); - } else { - summary[`total ${metric}`] = round(sum); - summary[`max ${metric}`] = Math.max(...values); - } - } - return summary; -} - -function formatRecord(record: FileMetrics): string { - const parts = KEY_METRICS.map((metric) => [metric, numeric(record, metric)] as const) - .filter(([, value]) => value !== null) - .map(([metric, value]) => `${metric}=${value}`); - return `${record.relativePath}${record.language ? ` (${record.language})` : ''}: ${parts.join(', ')}`; -} - -function formatSummary(summary: Record): string { - return Object.entries(summary).map(([key, value]) => `${key}: ${value}`).join('\n'); -} - -export function metricsReport(records: readonly FileMetrics[], scopeArg: string | undefined): string { - const scope = normalize(scopeArg); - const exact = records.find((record) => record.relativePath === scope); - if (exact) { - return formatRecord(exact); - } - const inside = records.filter((record) => inScope(record.relativePath, scope)); - if (inside.length === 0) { - throw new Error(`The analysis has no file at or under "${scope}". Paths are relative to the project root.`); - } - const byLanguage = new Map(); - for (const record of inside) { - byLanguage.set(record.language ?? 'unknown', (byLanguage.get(record.language ?? 'unknown') ?? 0) + 1); - } - return [ - `${scope || 'Whole project'}: ${inside.length} analysed files`, - `languages: ${[...byLanguage].sort((a, b) => b[1] - a[1]).map(([language, count]) => `${language} ${count}`).join(', ')}`, - formatSummary(summarize(inside)), - ].join('\n'); -} - -export function hotspotsReport(records: readonly FileMetrics[], metric: string, limit: number, scopeArg: string | undefined): string { - const scope = normalize(scopeArg); - const ranked = records - .filter((record) => inScope(record.relativePath, scope)) - .map((record) => ({ record, value: numeric(record, metric) })) - .filter((entry): entry is { record: FileMetrics; value: number } => entry.value !== null) - .sort((a, b) => b.value - a.value) - .slice(0, limit); - if (ranked.length === 0) { - const known = Object.keys(records[0] ?? {}).filter((key) => typeof records[0]?.[key] === 'number'); - throw new Error(`No file has the metric "${metric}". Known metrics: ${known.join(', ')}.`); - } - return [`Top ${ranked.length} files by ${metric}${scope ? ` under ${scope}` : ''}:`, ...ranked.map(({ record, value }, index) => `${index + 1}. ${record.relativePath}: ${metric}=${value} | ${formatRecord(record).split(': ').slice(1).join(': ')}`)].join('\n'); -} - -interface GraphNode { readonly id: string; readonly relativePath?: string; readonly label?: string; readonly external?: boolean; readonly metrics?: Record } -interface GraphEdge { readonly source: string; readonly target: string; readonly kind?: string; readonly occurrences?: number } - -export function dependenciesReport(graph: unknown, fileArg: string | undefined, limit: number): string { - const record = (graph && typeof graph === 'object' ? graph : {}) as { nodes?: GraphNode[]; edges?: GraphEdge[] }; - const nodes = Array.isArray(record.nodes) ? record.nodes : []; - const edges = Array.isArray(record.edges) ? record.edges : []; - const nameOf = (id: string): string => { - const node = nodes.find((candidate) => candidate.id === id); - return node?.relativePath ?? node?.label ?? id; - }; - const file = normalize(fileArg); - if (!file) { - const ranked = nodes.filter((node) => !node.external && node.metrics) - .sort((a, b) => (b.metrics?.['degree'] ?? 0) - (a.metrics?.['degree'] ?? 0)) - .slice(0, limit); - const cycles = nodes.filter((node) => (node.metrics?.['cycleSize'] ?? 0) > 1).map((node) => node.relativePath ?? node.label); - return [ - `${nodes.length} nodes, ${edges.length} edges.`, - `Most connected (fanIn/fanOut):`, - ...ranked.map((node) => `- ${node.relativePath ?? node.label}: fanIn=${node.metrics?.['fanIn'] ?? 0}, fanOut=${node.metrics?.['fanOut'] ?? 0}`), - cycles.length > 0 ? `In dependency cycles: ${cycles.slice(0, limit).join(', ')}${cycles.length > limit ? ` and ${cycles.length - limit} more` : ''}` : 'No dependency cycles.', - ].join('\n'); - } - const node = nodes.find((candidate) => normalize(candidate.relativePath) === file); - if (!node) { - throw new Error(`"${file}" is not in the dependency graph.`); - } - const describe = (list: readonly GraphEdge[], end: 'source' | 'target'): string[] => { - const grouped = new Map(); - for (const edge of list) { - const other = nameOf(edge[end]); - grouped.set(other, [...(grouped.get(other) ?? []), edge.kind ?? 'uses']); - } - return [...grouped].slice(0, limit).map(([other, kinds]) => `- ${other} (${[...new Set(kinds)].join(', ')})`); - }; - const outgoing = edges.filter((edge) => edge.source === node.id); - const incoming = edges.filter((edge) => edge.target === node.id); - return [ - `${file}: ${Object.entries(node.metrics ?? {}).map(([key, value]) => `${key}=${value}`).join(', ')}`, - `Depends on (${outgoing.length}):`, ...describe(outgoing, 'target'), - `Used by (${incoming.length}):`, ...describe(incoming, 'source'), - ].join('\n'); -} - -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 { - const file = normalize(fileArg); - const lines = frames.map(({ frame, records }) => { - const when = [frame.date, frame.label].filter(Boolean).join(' '); - if (file) { - const inside = records.filter((record) => inScope(record.relativePath, file)); - if (inside.length === 0) { - return `- ${when}: (not present)`; - } - const values = inside.map((record) => numeric(record, metric)).filter((value): value is number => value !== null); - const total = values.reduce((a, b) => a + b, 0); - return `- ${when}: ${metric}=${round(inside.length === 1 ? total : total)}${inside.length > 1 ? ` over ${inside.length} files` : ''}`; - } - const summary = summarize(records); - return `- ${when}: files=${summary['files']}, codeLines=${summary['total codeLines'] ?? '?'}, avg complexity=${summary['avg cyclomaticComplexityNumber'] ?? '?'}, max complexity=${summary['max maxComplexity'] ?? '?'}`; - }); - return [`Project evolution, ${frames.length} snapshots (oldest first)${file ? ` for ${file}` : ''}:`, ...lines].join('\n'); -} - -/** The last project-evolution movie under `root`, oldest frame first. */ -async function readEvolution(root: string): Promise<{ frame: EvolutionFrame; records: FileMetrics[] }[] | null> { - const dir = path.join(root, 'evolution'); - let revisions: number[]; - try { - revisions = (await fs.promises.readdir(dir)).map((name) => /^revision-(\d+)$/.exec(name)?.[1]).filter((value): value is string => !!value).map(Number); - } catch { - return null; - } - const latest = Math.max(...revisions); - if (!Number.isFinite(latest)) { - return null; - } - const manifest = (await readJson(path.join(dir, `revision-${latest}`, 'manifest.json'))) as { frames?: EvolutionFrame[] }; - const frames = Array.isArray(manifest.frames) ? manifest.frames : []; - const out: { frame: EvolutionFrame; records: FileMetrics[] }[] = []; - for (const [index, frame] of frames.entries()) { - const name = path.basename(frame.url ?? `data${index + 1}.json`); - if (!/^data\d+\.json$/.test(name)) { - continue; - } - out.push({ frame, records: recordsOf(await readJson(path.join(dir, `revision-${latest}`, name))) }); - } - return out; -} +export { dependenciesReport, evolutionReport, hotspotsReport, metricsReport } from './analysisQueries.ts'; function outputRoot(context: ToolContext): string { if (!context.workspace) { @@ -228,95 +22,13 @@ function outputRoot(context: ToolContext): string { return root; } -async function readMetrics(root: string): Promise { - try { - return recordsOf(await readJson(path.join(root, 'data.json'))); - } catch { - throw new Error(NO_ANALYSIS); - } -} - -const metricDescription = `Metric name, e.g. ${KEY_METRICS.slice(0, 7).join(', ')}.`; - -export const ANALYSIS_TOOLS: readonly AgentTool[] = analysisTools(); - -function analysisTools(): AgentTool[] { - return [ - { - name: 'get_metrics', - title: 'Read Code-XR metrics', - description: 'Code-XR metrics (lines, functions, complexity, cognitive complexity, maintainability, parameters, nesting) for one file, or totals and averages for a folder or the whole project, from the analysis open in the IDE.', - risk: 'read', - parameters: { type: 'object', properties: { path: { type: 'string', description: 'A file or folder relative to the project root; "" for the whole project.' } } }, - preview: (args) => ({ summary: `metrics of ${normalize(args['path'] as string | undefined) || 'the project'}` }), - async run(args, context) { - return clip(metricsReport(await readMetrics(outputRoot(context)), stringArg(args, 'path', false))); - }, - }, - { - name: 'get_hotspots', - title: 'Find complexity hot spots', - description: 'The files that rank highest on a Code-XR metric (default maxComplexity), optionally under a folder: where to look first for risky code.', - risk: 'read', - parameters: { - type: 'object', - properties: { - metric: { type: 'string', description: metricDescription }, - limit: { type: 'integer', description: 'How many files (default 10, max 50).' }, - path: { type: 'string', description: 'Only files under this folder.' }, - }, - }, - preview: (args) => ({ summary: `top files by ${String(args['metric'] ?? 'maxComplexity')}` }), - async run(args, context) { - const metric = stringArg(args, 'metric', false) ?? 'maxComplexity'; - const limit = Math.min(50, Math.max(1, numberArg(args, 'limit') ?? 10)); - return clip(hotspotsReport(await readMetrics(outputRoot(context)), metric, limit, stringArg(args, 'path', false))); - }, - }, - { - name: 'get_dependencies', - title: 'Read the dependency graph', - description: 'From Code-XR\'s dependency graph: for a file, what it depends on and what uses it; without a file, the most connected files and any cycles. Needs the dependency graph mode to have run in the XR scene.', - risk: 'read', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'A file relative to the project root; omit for the overview.' }, - limit: { type: 'integer', description: 'How many entries per list (default 20, max 100).' }, - }, - }, - preview: (args) => ({ summary: `dependencies of ${normalize(args['path'] as string | undefined) || 'the project'}` }), - async run(args, context) { - const root = outputRoot(context); - let graph: unknown; - try { - graph = await readJson(path.join(root, 'dependency-graph.json')); - } catch { - throw new Error('The dependency graph has not been computed for this analysis. Ask the person to open the Dependency graph mode in the XR scene once.'); - } - return clip(dependenciesReport(graph, stringArg(args, 'path', false), Math.min(100, Math.max(1, numberArg(args, 'limit') ?? 20)))); - }, - }, - { - name: 'get_evolution', - title: 'Read the project\'s evolution', - description: 'How metrics changed across the Git history snapshots of Code-XR\'s last project-evolution movie: the whole project, or one metric for a file or folder. Needs the Project evolution mode to have run in the XR scene.', - risk: 'read', - parameters: { - type: 'object', - properties: { - path: { type: 'string', description: 'A file or folder; omit for project totals.' }, - metric: { type: 'string', description: `${metricDescription} Used with path; default codeLines.` }, - }, - }, - preview: (args) => ({ summary: `evolution of ${normalize(args['path'] as string | undefined) || 'the project'}` }), - async run(args, context) { - const frames = await readEvolution(outputRoot(context)); - if (!frames || frames.length === 0) { - throw new Error('No project-evolution movie has been computed for this analysis. Ask the person to run Project evolution in the XR scene once.'); - } - return clip(evolutionReport(frames, stringArg(args, 'path', false), stringArg(args, 'metric', false) ?? 'codeLines')); - }, - }, - ]; -} +export const ANALYSIS_TOOLS: readonly AgentTool[] = ANALYSIS_QUERIES.map((query): AgentTool => ({ + name: query.name, + title: query.title, + description: query.description, + risk: 'read', + 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)), +})); diff --git a/apps/ide/src/main/analysis/analysisService.ts b/apps/ide/src/main/analysis/analysisService.ts index 7a58462a6..b19b98254 100644 --- a/apps/ide/src/main/analysis/analysisService.ts +++ b/apps/ide/src/main/analysis/analysisService.ts @@ -3,6 +3,9 @@ import { createHash } from 'node:crypto'; import path from 'node:path'; import { AnalysisOrchestrator } from '@codexr/core/analysis/analysisOrchestrator'; import { AnalysisConfigurationStorage } from '@codexr/core/analysis/configuration/analysisConfigurationStorage'; +import { analysisRefreshCoordinator } from '@codexr/core/analysis/refresh/analysisRefreshCoordinator'; +import { UnifiedSessionRegistry } from '@codexr/core/analysis/session/sessionRegistry'; +import { SessionWatcherManager } from '@codexr/core/analysis/watchers/sessionWatcherManager'; import { CollaborationProfileManager } from '@codexr/core/collaboration/collaborationProfileManager'; import { getHost } from '@codexr/core/host/hostRegistry'; import { EXTENSION_MODE, type CoreContext } from '@codexr/core/host/hostPaths'; @@ -18,6 +21,9 @@ import { channelLog } from '../log.ts'; import type { PythonEnvironmentService } from '../python/pythonEnvironment.ts'; import { resolveInWorkspace } from '../workspace/workspacePath.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 { closeScene, enterSceneXr, sceneSupportsImmersiveXr, showScene } from './sceneView.ts'; import { unsupportedXrMessage } from './sceneXrPolicy.ts'; import { sceneTargetToWorkspacePath } from './sceneEditorTarget.ts'; @@ -42,6 +48,18 @@ const log = channelLog('core'); const AUTO_START_KEY = 'ide.analysis.autoStartOnOpen'; const DEFAULT_AUTO_START: AutoStartMode = 'xr-deep'; +/** AF9: how long a turn's delta waits for the core's re-analysis to catch up with the disk. */ +const DEFAULT_SETTLE_TIMEOUT_MS = 60_000; +/** + * AF9: a change the core's own watcher is still hashing has updated its file + * tracker but not yet queued its refresh; a short pause after our reconcile + * lets that refresh be queued before "settled" is read. + */ +const RECONCILE_GRACE_MS = 250; + +/** Why a scene could not be brought up to date with the disk. */ +export type SceneSettleResult = SettleResult | 'no-scene' | 'not-following'; + const NO_WORKSPACE: AnalysisStartResult = { ok: false, reason: 'no-workspace', message: 'Open a folder first.' }; function isFileKind(kind: AnalysisKind): kind is FileAnalysisKind { @@ -56,6 +74,8 @@ interface WindowScene { /** What was analysed: the folder itself, or one file of it. */ readonly target: string; readonly serverId: string; + /** The core's analysis session behind the server (AF8), when the registry names it. */ + readonly sessionId: string | undefined; readonly url: string; /** The sharing state last sent to the window (#155), to send changes only. */ share: SceneShareState; @@ -77,6 +97,8 @@ export class AnalysisService { private readonly scenes = new Map(); private readonly python: PythonEnvironmentService; 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>(); constructor(python: PythonEnvironmentService, subscriptions: HostDisposable[], hooks: { sceneOpened?(contents: WebContents, folder: string): void } = {}) { this.python = python; @@ -143,6 +165,90 @@ export class AnalysisService { return mode; } + /** + * AF8: whether an open scene follows changes on disk (the core's + * auto-analysis setting, shared with the extension; on by default). The + * core reads it on every change, so turning it off takes effect at once; + * turning it on reaches a scene launched while it was off only when that + * scene is analysed again (the core starts no watcher for it). + */ + async followsChanges(): Promise { + return AnalysisConfigurationStorage.getInstance(this.context).getAutoAnalysisEnabled(); + } + + async setFollowsChanges(enabled: boolean): Promise { + await AnalysisConfigurationStorage.getInstance(this.context).setAutoAnalysisEnabled(enabled); + return enabled; + } + + /** + * 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 + * function that stops it. + */ + onSceneUpdated(listener: (contents: WebContents, event: SceneUpdatedEvent) => void): () => void { + this.updateListeners.add(listener); + return () => this.updateListeners.delete(listener); + } + + /** + * 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 + * file watcher), then waits for the refresh it queued. Never throws. + */ + async settleScene(contents: WebContents, timeoutMs = DEFAULT_SETTLE_TIMEOUT_MS): Promise { + const scene = this.scenes.get(contents.id); + if (!scene?.sessionId || !getActiveServerRegistry().getServer(scene.serverId)) { + return 'no-scene'; + } + const { sessionId } = scene; + try { + if (!await this.followsChanges()) { + return 'not-following'; + } + await SessionWatcherManager.reconcileSession(sessionId); + } catch (error) { + log.warn(`Could not reconcile the analysis of ${scene.target}: ${String(error)}`); + } + await new Promise((resolve) => setTimeout(resolve, RECONCILE_GRACE_MS)); + return waitUntilSettled(refreshPort(sessionId), timeoutMs); + } + + /** + * AF9: the metric records of the window's project scene (one per analysed + * file), or null without one. Taken at the start of an agent's turn, they + * are the `before` of `turnMetricDelta`. + */ + async sceneMetrics(contents: WebContents): Promise { + const scene = this.scenes.get(contents.id); + const dir = this.outputDirectory(contents); + // A single file's analysis records its functions, not files: no per-file delta there. + if (!scene || !dir || isFileKind(scene.kind)) { + return null; + } + try { + return await readMetrics(dir); + } catch { + return null; + } + } + + /** + * 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). + */ + async turnMetricDelta( + contents: WebContents, + before: readonly FileMetrics[] | null, + changedPaths?: readonly string[] | null, + 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) }; + } + /** * `auto` marks an analysis the person did not click for (#139, a folder * just opened). It reuses a scene that is still being served for the same @@ -373,6 +479,15 @@ export class AnalysisService { } } + /** The core's analysis session a server serves: named in its registration, else found by server id. */ + private sessionOf(serverId: string): string | undefined { + const named = getActiveServerRegistry().getServer(serverId)?.metadata?.sessionId; + if (typeof named === 'string' && named) { + return named; + } + return UnifiedSessionRegistry.getInstance(this.context).getAllSessions().find((session) => session.serverId === serverId)?.id; + } + private liveScene(win: BrowserWindow): WindowScene { const scene = this.scenes.get(win.webContents.id); if (!scene || !getActiveServerRegistry().getServer(scene.serverId)) { @@ -427,13 +542,32 @@ export class AnalysisService { const single = isFileKind(this.ownerKind); const files = single ? 1 : await readAnalysedFileCount(server?.htmlFile); const contents = win.webContents; - const unwatch = watchAnalysedFileCount(single ? undefined : server?.htmlFile, files, (count) => { + const unwatchCount = watchAnalysedFileCount(single ? undefined : server?.htmlFile, files, (count) => { if (!contents.isDestroyed()) { contents.send(IPC_EVENTS.analysisSceneFilesChanged, { url: serverUrl, files: count } satisfies SceneFilesEvent); } }); + 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 }; + for (const listener of this.updateListeners) { + listener(contents, event); + } + }); + }) + : () => undefined; + const unwatch = (): void => { + unwatchCount(); + unfollow(); + }; win.once('closed', unwatch); - this.scenes.set(win.webContents.id, { folder: this.ownerFolder, kind: this.ownerKind, target: this.ownerTarget, serverId, 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 }); 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); @@ -458,3 +592,11 @@ export class AnalysisService { await showScene(win, serverUrl); } } + +/** The core's refresh state of one analysis session, as `sceneRefresh.ts` reads it. */ +function refreshPort(sessionId: string): RefreshPort { + return { + view: () => analysisRefreshCoordinator.getViewState(sessionId), + onChange: (listener) => analysisRefreshCoordinator.onStateChanged(sessionId, () => listener()), + }; +} diff --git a/apps/ide/src/main/analysis/metricDelta.ts b/apps/ide/src/main/analysis/metricDelta.ts new file mode 100644 index 000000000..e89c26f59 --- /dev/null +++ b/apps/ide/src/main/analysis/metricDelta.ts @@ -0,0 +1,268 @@ +import type { MetricChangeView, TurnMetricDeltaView } from '../../shared/agentSession.ts'; +import { normalize, type FileMetrics } from '../agents/tools/analysisQueries.ts'; + +/** + * What one agent turn did to the project's measurements (AF9, #274): the + * metric records of the analysis before the turn and after it, compared file + * by file for the paths the turn changed, plus project totals. Pure: the + * records come from `readMetrics` (an XR analysis' `data.json`, one record per + * analysed file, paths relative to the analysed folder). + */ + +/** The metrics a delta reports per file: size, structure and complexity. */ +export const DELTA_METRICS = [ + 'codeLines', 'totalLines', 'functionCount', 'classCount', + 'maxComplexity', 'cyclomaticComplexityNumber', 'highComplexityFunctions', 'criticalComplexityFunctions', + 'maxCognitiveComplexity', 'averageMaintainabilityIndex', +] as const; + +export type DeltaMetric = typeof DELTA_METRICS[number]; + +export interface MetricChange { + readonly before: number | null; + readonly after: number | null; + /** `after - before`, a missing side counting as 0 (a new file adds all its lines). */ + readonly delta: number; +} + +/** + * - `added` / `removed`: the analysis gained or lost the file; + * - `changed` / `unchanged`: in both, with or without a metric change; + * - `not-analysed`: a changed path the analysis never measured (a README, a + * language it does not cover, an ignored folder). + */ +export type FileDeltaStatus = 'added' | 'removed' | 'changed' | 'unchanged' | 'not-analysed'; + +export interface FileMetricDelta { + readonly path: string; + readonly status: FileDeltaStatus; + readonly language?: string; + /** Only the metrics that moved (every present one for an added or removed file). */ + readonly metrics: Partial>; +} + +export interface MetricTotals { + readonly files: number; + readonly codeLines: number; + readonly totalLines: number; + readonly functionCount: number; + readonly classCount: number; + readonly highComplexityFunctions: number; + readonly criticalComplexityFunctions: number; + /** The highest `maxComplexity` of any file, or null when no record has one. */ + readonly maxComplexity: number | null; + /** The mean of the files' mean complexity (`cyclomaticComplexityNumber`), or null. */ + readonly avgComplexity: number | null; +} + +/** + * - `ok`: both analyses were readable; + * - `no-baseline`: there was no analysis before the turn (only `totals.after`); + * - `no-analysis`: there is no analysis after it (nothing to compare). + */ +export type MetricDeltaStatus = 'ok' | 'no-baseline' | 'no-analysis'; + +export interface MetricDeltaReport { + readonly status: MetricDeltaStatus; + readonly files: readonly FileMetricDelta[]; + readonly totals: { + readonly before: MetricTotals | null; + readonly after: MetricTotals | null; + /** after - before for each total both sides have; empty unless `ok`. */ + readonly delta: Partial>; + }; + /** One line for a chat or a header: what moved, or that nothing did. */ + readonly summary: string; +} + +const round = (value: number): number => Math.round(value * 100) / 100; + +function numeric(record: FileMetrics | undefined, metric: string): number | null { + const value = record?.[metric]; + return typeof value === 'number' && Number.isFinite(value) ? value : null; +} + +function byPath(records: readonly FileMetrics[]): Map { + return new Map(records.map((record) => [normalize(record.relativePath), record])); +} + +export function metricTotals(records: readonly FileMetrics[]): MetricTotals { + const sum = (metric: string): number => round(records.reduce((total, record) => total + (numeric(record, metric) ?? 0), 0)); + const values = (metric: string): number[] => records.map((record) => numeric(record, metric)).filter((value): value is number => value !== null); + const maxima = values('maxComplexity'); + const means = values('cyclomaticComplexityNumber'); + return { + files: records.length, + codeLines: sum('codeLines'), + totalLines: sum('totalLines'), + functionCount: sum('functionCount'), + classCount: sum('classCount'), + highComplexityFunctions: sum('highComplexityFunctions'), + criticalComplexityFunctions: sum('criticalComplexityFunctions'), + maxComplexity: maxima.length > 0 ? Math.max(...maxima) : null, + avgComplexity: means.length > 0 ? round(means.reduce((a, b) => a + b, 0) / means.length) : null, + }; +} + +function fileDelta(file: string, before: FileMetrics | undefined, after: FileMetrics | undefined): FileMetricDelta { + const metrics: Partial> = {}; + for (const metric of DELTA_METRICS) { + const was = numeric(before, metric); + const now = numeric(after, metric); + if ((was === null && now === null) || (before && after && was === now)) { + continue; + } + metrics[metric] = { before: was, after: now, delta: round((now ?? 0) - (was ?? 0)) }; + } + const status: FileDeltaStatus = !before ? 'added' : !after ? 'removed' : Object.keys(metrics).length > 0 ? 'changed' : 'unchanged'; + const language = after?.language ?? before?.language; + return language === undefined ? { path: file, status, metrics } : { path: file, status, language, metrics }; +} + +/** The record paths a changed path stands for: the file itself, or every analysed file under a changed folder. */ +function expand(changed: string, before: Map, after: Map): string[] { + if (before.has(changed) || after.has(changed)) { + return [changed]; + } + const prefix = `${changed}/`; + const inside = new Set([...before.keys(), ...after.keys()].filter((file) => changed !== '' && file.startsWith(prefix))); + return [...inside].sort(); +} + +function sameRecord(a: FileMetrics, b: FileMetrics): boolean { + return DELTA_METRICS.every((metric) => numeric(a, metric) === numeric(b, metric)); +} + +function totalsDelta(before: MetricTotals, after: MetricTotals): Partial> { + const delta: Partial> = {}; + for (const key of Object.keys(after) as (keyof MetricTotals)[]) { + const was = before[key]; + const now = after[key]; + if (was !== null && now !== null) { + delta[key] = round(now - was); + } + } + return delta; +} + +const signed = (value: number): string => (value > 0 ? `+${value}` : String(value)); + +function describe(files: readonly FileMetricDelta[], before: MetricTotals, after: MetricTotals, delta: Partial>): string { + const count = (status: FileDeltaStatus): number => files.filter((file) => file.status === status).length; + const moved = files.filter((file) => file.status !== 'unchanged' && file.status !== 'not-analysed'); + const parts: string[] = []; + if (delta.codeLines) { + parts.push(`code lines ${signed(delta.codeLines)} (${before.codeLines} -> ${after.codeLines})`); + } + if (delta.functionCount) { + parts.push(`functions ${signed(delta.functionCount)}`); + } + if (before.maxComplexity !== after.maxComplexity) { + parts.push(`max complexity ${before.maxComplexity ?? '-'} -> ${after.maxComplexity ?? '-'}`); + } + if (before.avgComplexity !== after.avgComplexity) { + parts.push(`avg complexity ${before.avgComplexity ?? '-'} -> ${after.avgComplexity ?? '-'}`); + } + if (delta.highComplexityFunctions) { + parts.push(`high-complexity functions ${signed(delta.highComplexityFunctions)}`); + } + if (delta.criticalComplexityFunctions) { + parts.push(`critical functions ${signed(delta.criticalComplexityFunctions)}`); + } + if (moved.length === 0 && parts.length === 0) { + return 'No metric changes.'; + } + const kinds = (['added', 'removed', 'changed'] as const).filter((status) => count(status) > 0).map((status) => `${count(status)} ${status}`); + const head = `${moved.length} ${moved.length === 1 ? 'file' : 'files'}${kinds.length > 0 ? ` (${kinds.join(', ')})` : ''}`; + return parts.length > 0 ? `${head}: ${parts.join(', ')}` : head; +} + +/** + * Compares two analyses. `changedPaths` (relative to the analysed folder, a + * folder standing for every file under it) limits the per-file list to what + * the turn touched, so a touched file whose metrics did not move is listed as + * `unchanged`; without it every file whose metrics differ is listed. The + * totals always cover the whole project. + */ +export function computeMetricDelta( + before: readonly FileMetrics[] | null | undefined, + after: readonly FileMetrics[] | null | undefined, + changedPaths?: readonly string[] | null, +): 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.' }; + } + 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.` }; + } + const was = byPath(before); + const now = byPath(after); + const files: FileMetricDelta[] = []; + if (changedPaths) { + const seen = new Set(); + for (const changed of [...new Set(changedPaths.map((file) => normalize(file)))].sort()) { + const covered = expand(changed, was, now); + if (covered.length === 0) { + if (changed) { + files.push({ path: changed, status: 'not-analysed', metrics: {} }); + } + continue; + } + for (const file of covered.filter((candidate) => !seen.has(candidate))) { + seen.add(file); + files.push(fileDelta(file, was.get(file), now.get(file))); + } + } + } else { + for (const file of [...new Set([...was.keys(), ...now.keys()])].sort()) { + const a = was.get(file); + const b = now.get(file); + if (!a || !b || !sameRecord(a, b)) { + files.push(fileDelta(file, a, b)); + } + } + } + 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) }; +} + +/** The report as text for an agent or a log: the summary, then one line per file. */ +export function formatMetricDelta(report: MetricDeltaReport): string { + const lines = [report.summary]; + for (const file of report.files) { + const changes = Object.entries(file.metrics).map(([metric, change]) => `${metric} ${change.before ?? '-'} -> ${change.after ?? '-'} (${signed(change.delta)})`); + lines.push(`- ${file.path} [${file.status}]${changes.length > 0 ? `: ${changes.join(', ')}` : ''}`); + } + return lines.join('\n'); +} + +/** The project totals a chat shows, in the order it shows them. */ +const VIEW_TOTALS: readonly (keyof MetricTotals)[] = [ + 'maxComplexity', 'avgComplexity', 'codeLines', 'functionCount', 'classCount', 'highComplexityFunctions', 'criticalComplexityFunctions', 'files', +]; + +/** + * 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. + */ +export function toTurnMetricDeltaView(report: MetricDeltaReport, maxFiles = 30): TurnMetricDeltaView | null { + const { before, after } = report.totals; + if (report.status !== 'ok' || !before || !after) { + return null; + } + 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) { + return null; + } + const files = moved.slice(0, maxFiles).map((file) => ({ + path: file.path, + status: file.status, + changes: Object.entries(file.metrics).map(([metric, change]) => ({ metric, before: change.before, after: change.after })), + })); + return { summary: report.summary, totals, files, moreFiles: moved.length - files.length }; +} diff --git a/apps/ide/src/main/analysis/sceneRefresh.ts b/apps/ide/src/main/analysis/sceneRefresh.ts new file mode 100644 index 000000000..948d9bc91 --- /dev/null +++ b/apps/ide/src/main/analysis/sceneRefresh.ts @@ -0,0 +1,121 @@ +/** + * Following the core's re-analysis of an open scene (AF8 #273, AF9 #274). + * + * The core already re-analyses a project scene when its files change on disk, + * whoever wrote them (the editor, a terminal, an agent's CLI): every launch + * starts a session watcher (`fs.watch` per folder of the project), whose + * changes go through the core's `analysisRefreshCoordinator`, which runs one + * refresh at a time per mode and once more if changes arrived meanwhile. So + * the IDE does not watch the folder itself. What it needs is to know when a + * refresh finished (to tell the renderer) and to wait for the analysis to + * catch up with the disk (to measure an agent's turn). Both read the + * coordinator's view state, through this pure, Electron-free module. + */ + +/** The fields of the core's `AnalysisViewState` this module reads. */ +export interface RefreshView { + readonly mode: string; + readonly status: string; + readonly sourceRevision: number; + readonly appliedRevision: Readonly>>; + readonly modeRevision: Readonly>>; +} + +/** + * - `settled`: `data.json` reflects every change the core has seen; + * - `pending`: a refresh is running or queued; + * - `paused`: the scene shows another mode (dependency graph, history, + * 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'; + +/** `data.json` is the classic view's dataset, the coordinator's `single` mode. */ +const DATA_MODE = 'single'; + +export function refreshState(view: RefreshView): RefreshState { + if (view.mode !== DATA_MODE) { + return 'paused'; + } + if (view.status === 'error') { + // A failed refresh keeps its changes pending and waits for the next one: nothing to wait for now. + return 'settled'; + } + const applied = view.appliedRevision[DATA_MODE] ?? 0; + return applied >= view.sourceRevision && view.status !== 'updating' && view.status !== 'loading' ? 'settled' : 'pending'; +} + +/** The classic view's refresh count, which the core bumps once per finished refresh. */ +export function dataRevision(view: RefreshView): number { + return view.modeRevision[DATA_MODE] ?? 0; +} + +/** How the IDE reaches one session's refresh state (the core in the app, a fake in the tests). */ +export interface RefreshPort { + view(): RefreshView; + /** Calls `listener` on every state change; returns the function that stops it. */ + onChange(listener: () => void): () => void; +} + +export type SettleResult = RefreshState | 'timeout'; + +/** + * Resolves once the session is no longer `pending` (settled or paused), or + * with `timeout` after `timeoutMs`. Never rejects. + */ +export function waitUntilSettled(port: RefreshPort, timeoutMs: number): Promise { + return new Promise((resolve) => { + let done = false; + let stop: () => void = () => undefined; + let timer: NodeJS.Timeout | undefined; + const finish = (result: SettleResult): void => { + if (done) { + return; + } + done = true; + stop(); + if (timer) { + clearTimeout(timer); + } + resolve(result); + }; + const check = (): void => { + const state = refreshState(port.view()); + if (state !== 'pending') { + finish(state); + } + }; + stop = port.onChange(check); + timer = setTimeout(() => finish('timeout'), timeoutMs); + check(); + }); +} + +/** + * Calls `onRefreshed(revision)` each time the classic view finishes a refresh + * (its revision moves past the last one seen). Returns the function that stops it. + */ +export function followRefreshes(port: RefreshPort, onRefreshed: (revision: number) => void): () => void { + let last = dataRevision(port.view()); + return port.onChange(() => { + const revision = dataRevision(port.view()); + if (revision > last) { + last = revision; + onRefreshed(revision); + } + }); +} + +/** + * 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). + */ +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; +} diff --git a/apps/ide/src/main/checkpoints/checkpointStore.ts b/apps/ide/src/main/checkpoints/checkpointStore.ts new file mode 100644 index 000000000..05dfcc9cb --- /dev/null +++ b/apps/ide/src/main/checkpoints/checkpointStore.ts @@ -0,0 +1,783 @@ +import { execFile } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +/** + * Snapshots of a project's working tree in a shadow git repository the IDE + * owns (epic #265: AF5 review of the agent's changes, AF6 checkpoints per turn). + * + * Why git and why a shadow repository: a snapshot per turn has to catch every + * change, including the ones an agent makes through shell commands, so it must + * capture the tree itself rather than record the edits that went through the + * IDE. Git does that with content-addressed storage (an unchanged file costs + * nothing) and a stat cache (an unchanged tree is fast to re-snapshot). The + * repository lives outside the project, in `storageDir`, and the project's own + * `.git` is never read as a repository or written: every call runs with its + * own `GIT_DIR`, `GIT_WORK_TREE=projectRoot` and a private `GIT_INDEX_FILE`. + * + * Hardening, because a project must not run anything of its choosing through + * this (see docs/ide/market-study/group-d-protocols.md, section 4 "Pitfalls"): + * system and global config are not read, hooks point at an empty directory, + * gpg signing, fsmonitor and the LFS filters are off, and an + * `info/attributes` file in the shadow repository (which outranks every + * `.gitattributes`) unsets `text`, `eol`, `filter`, `ident` and + * `working-tree-encoding`, so the bytes of a file (CRLF included) are stored + * and restored exactly. Commits are made with `commit-tree`, which runs no hook. + * + * What is not snapshotted: whatever the project's `.gitignore` files and + * `.git/info/exclude` ignore, a default list (`node_modules/`, build output, + * virtual environments, logs), files larger than `maxFileBytes`, and nested git + * repositories (a sub-folder with its own `.git`), which are excluded rather + * than having their `.git` renamed, as Cline does, because a crash mid-rename + * would break the user's repository. A project with more than `maxFiles` + * files, or a snapshot that times out, turns checkpoints off with a + * `disabledReason` the IDE can show. + * + * Restores write through `fs` (a temporary file then a rename), never through + * `git checkout`, so only the named paths are touched and an ignored file is + * never deleted. Every operation on one project is serialized by an in-process + * lock keyed on the shadow repository. Pure Node, no Electron, so the VS Code + * extension can reuse it. + */ + +export interface CheckpointStoreOptions { + /** Directory holding the shadow repositories (one per project), e.g. `userData/checkpoints`. */ + readonly storageDir: string; + /** The project whose working tree is snapshotted. */ + readonly projectRoot: string; + /** The git executable. Default `git`, looked up on PATH (`git.exe` on Windows). */ + readonly git?: string | undefined; + /** Files larger than this are not snapshotted. Default 5 MB. */ + readonly maxFileBytes?: number | undefined; + /** More files than this turns checkpoints off. Default 20,000. */ + readonly maxFiles?: number | undefined; + /** Timeout of each git call. A snapshot that times out turns checkpoints off. Default 60 s. */ + readonly timeoutMs?: number | undefined; +} + +export interface Checkpoint { + /** The commit sha in the shadow repository. */ + readonly id: string; + readonly label: string; + /** Milliseconds since the epoch. */ + readonly createdAt: number; + /** Files in the snapshot. */ + readonly fileCount: number; +} + +export type ChangeStatus = 'added' | 'modified' | 'deleted'; + +export interface ChangedFile { + /** Relative to the project root, with forward slashes. */ + readonly path: string; + readonly status: ChangeStatus; + readonly additions: number; + readonly deletions: number; + /** True when git sees binary content: additions and deletions are then 0. */ + readonly binary: boolean; +} + +export interface DiffText { + /** The content at the checkpoint, or null when the file did not exist there. */ + readonly oldText: string | null; + /** The content on disk now, or null when the file does not exist. */ + readonly newText: string | null; +} + +export const DEFAULT_MAX_FILE_BYTES = 5 * 1024 * 1024; +export const DEFAULT_MAX_FILES = 20_000; +export const DEFAULT_CHECKPOINT_TIMEOUT_MS = 60_000; + +/** Excluded in every project, on top of its own ignore rules. */ +export const DEFAULT_EXCLUDES: readonly string[] = [ + 'node_modules/', '.git/', 'dist/', 'out/', 'build/', '.venv/', 'venv/', '__pycache__/', '*.log', +]; + +/** The ref that keeps the chain of checkpoints alive in the shadow repository. */ +const CHECKPOINT_REF = 'refs/codexr/checkpoints'; +const INDEX_NAME = 'codexr-index'; +const HOOKS_DIR_NAME = 'codexr-no-hooks'; +const EMPTY_CONFIG_NAME = 'codexr-empty-gitconfig'; +const ATTRIBUTES = '* -text !eol -filter -ident -working-tree-encoding\n'; +const MAX_OUTPUT_BYTES = 512 * 1024 * 1024; +/** Upper bound of blob bytes requested from one `cat-file --batch` call. */ +const BATCH_BYTES = 64 * 1024 * 1024; +const STAT_CONCURRENCY = 128; +const COMMIT_ID = /^[0-9a-f]{4,64}$/i; + +/** Thrown by a git call that ran past its timeout. */ +export class CheckpointTimeoutError extends Error { + constructor(args: readonly string[], timeoutMs: number) { + super(`git ${args[0] ?? ''} took longer than ${Math.round(timeoutMs / 1000)} s.`); + this.name = 'CheckpointTimeoutError'; + } +} + +/** Thrown when the project cannot be snapshotted; `message` is the reason to show. */ +export class CheckpointsDisabledError extends Error { + constructor(reason: string) { + super(reason); + this.name = 'CheckpointsDisabledError'; + } +} + +interface RunOptions { + readonly input?: string | Buffer | undefined; + readonly okExitCodes?: readonly number[] | undefined; + /** Without a work tree and an index: for `init` and object reads. */ + readonly bare?: boolean | undefined; +} + +interface RunResult { + readonly stdout: Buffer; + readonly exitCode: number; +} + +interface TreeEntry { + readonly mode: string; + readonly sha: string; + readonly size: number; +} + +interface StagedTree { + readonly tree: string; + readonly fileCount: number; +} + +/** One promise chain per shadow repository: every operation on a project runs alone. */ +const projectLocks = new Map>(); + +function withProjectLock(key: string, task: () => Promise): Promise { + const previous = projectLocks.get(key) ?? Promise.resolve(); + const result = previous.then(task); + const settled = result.then(() => undefined, () => undefined); + projectLocks.set(key, settled); + void settled.then(() => { + if (projectLocks.get(key) === settled) { + projectLocks.delete(key); + } + }); + return result; +} + +/** The shadow repository's directory name: a hash of the resolved project root (case-folded on Windows). */ +export function shadowRepoName(projectRoot: string): string { + const resolved = path.resolve(projectRoot); + const key = process.platform === 'win32' ? resolved.toLowerCase() : resolved; + return `${createHash('sha256').update(key).digest('hex').slice(0, 24)}.git`; +} + +/** + * Checks a project-relative path from a caller and returns it with forward + * slashes. Absolute paths, `..`, and anything inside a `.git` are refused. + */ +export function normalizeProjectPath(relativePath: string): string { + const posix = relativePath.replace(/\\/g, '/').replace(/^\.\/+/, ''); + if (posix === '' || posix.includes('\0')) { + throw new Error(`Invalid project path: "${relativePath}".`); + } + if (posix.startsWith('/') || /^[a-zA-Z]:/.test(posix)) { + throw new Error(`A checkpoint path must be relative to the project: "${relativePath}".`); + } + const segments = posix.split('/').filter((segment) => segment !== '' && segment !== '.'); + if (segments.length === 0) { + throw new Error(`Invalid project path: "${relativePath}".`); + } + for (const segment of segments) { + if (segment === '..') { + throw new Error(`A checkpoint path cannot leave the project: "${relativePath}".`); + } + if (segment.toLowerCase() === '.git') { + throw new Error(`A checkpoint never touches a .git folder: "${relativePath}".`); + } + } + return segments.join('/'); +} + +/** Splits NUL-terminated git output into its records. */ +function splitNul(output: Buffer | string): string[] { + const text = typeof output === 'string' ? output : output.toString('utf8'); + return text.split('\0').filter((record) => record !== ''); +} + +function isNotFound(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code; + return code === 'ENOENT' || code === 'ENOTDIR'; +} + +/** Lines of the project's own `.git/info/exclude`, following a `.git` file (worktrees). */ +async function readProjectExclude(projectRoot: string): Promise { + const dotGit = path.join(projectRoot, '.git'); + let gitDir = dotGit; + try { + const stat = await fs.stat(dotGit); + if (stat.isFile()) { + const pointer = /^gitdir:\s*(.+)$/m.exec(await fs.readFile(dotGit, 'utf8')); + if (!pointer?.[1]) { + return []; + } + gitDir = path.resolve(projectRoot, pointer[1].trim()); + const common = await fs.readFile(path.join(gitDir, 'commondir'), 'utf8').catch(() => null); + if (common !== null) { + gitDir = path.resolve(gitDir, common.trim()); + } + } + const content = await fs.readFile(path.join(gitDir, 'info', 'exclude'), 'utf8'); + return content.split(/\r?\n/).filter((line) => line.trim() !== '' && !line.startsWith('#')); + } catch { + return []; + } +} + +/** `mode` of a written file: the tree's executable bit, on top of the current or default permissions. */ +function fileMode(treeMode: string, currentMode: number): number { + const base = currentMode & 0o777; + return treeMode === '100755' ? base | 0o111 : base & ~0o111; +} + +export class CheckpointStore { + readonly projectRoot: string; + /** The shadow repository. */ + readonly gitDir: string; + private readonly indexFile: string; + private readonly gitExecutable: string; + private readonly maxFileBytes: number; + private readonly maxFiles: number; + private readonly timeoutMs: number; + private readonly env: NodeJS.ProcessEnv; + private readonly configArgs: readonly string[]; + private initialized = false; + private disposed = false; + private disabled: string | null = null; + + constructor(options: CheckpointStoreOptions) { + this.projectRoot = path.resolve(options.projectRoot); + this.gitDir = path.join(path.resolve(options.storageDir), shadowRepoName(this.projectRoot)); + this.indexFile = path.join(this.gitDir, INDEX_NAME); + this.gitExecutable = options.git ?? 'git'; + this.maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES; + this.maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES; + this.timeoutMs = options.timeoutMs ?? DEFAULT_CHECKPOINT_TIMEOUT_MS; + this.env = this.buildEnvironment(); + this.configArgs = [ + '-c', `core.hooksPath=${path.join(this.gitDir, HOOKS_DIR_NAME)}`, + '-c', 'commit.gpgsign=false', + '-c', 'core.autocrlf=false', + '-c', 'core.safecrlf=false', + '-c', 'core.longpaths=true', + '-c', 'core.symlinks=false', + '-c', 'core.fsmonitor=false', + '-c', 'core.quotepath=false', + '-c', 'core.untrackedCache=false', + '-c', 'filter.lfs.smudge=', + '-c', 'filter.lfs.process=', + '-c', 'filter.lfs.clean=', + '-c', 'filter.lfs.required=false', + '-c', 'advice.addEmbeddedRepo=false', + '-c', 'gc.auto=0', + '-c', 'maintenance.auto=false', + '-c', 'user.name=Code-XR', + '-c', 'user.email=checkpoints@code-xr.local', + '--no-pager', + ]; + } + + /** Why checkpoints are off for this project, or null while they work. */ + get disabledReason(): string | null { + return this.disabled; + } + + /** Turns checkpoints back on after a timeout or a too-large project (the next snapshot re-checks). */ + clearDisabled(): void { + this.disabled = null; + } + + /** + * Snapshots the working tree. Returns null, with `disabledReason` set, when + * the project is too large or the snapshot times out. + */ + snapshot(label: string): Promise { + return this.locked(async () => { + if (this.disabled !== null) { + return null; + } + let staged: StagedTree; + try { + staged = await this.stageWorkingTree(); + } catch (error) { + if (error instanceof CheckpointsDisabledError) { + return null; + } + throw error; + } + const parent = await this.currentHead(); + const args = ['commit-tree', staged.tree, ...(parent ? ['-p', parent] : []), '-F', '-']; + const message = label.trim() === '' ? 'Checkpoint' : label; + const id = (await this.run(args, { input: message })).stdout.toString('utf8').trim(); + await this.run(['update-ref', CHECKPOINT_REF, id]); + return { id, label: message, createdAt: Date.now(), fileCount: staged.fileCount }; + }); + } + + /** Files that differ between checkpoint `baseId` and the working tree as it is now. */ + changes(baseId: string): Promise { + return this.locked(async () => { + const base = await this.resolveCommit(baseId); + const { tree } = await this.stageOrThrow(); + return this.diffTrees(base, tree); + }); + } + + /** The content of `filePath` at a checkpoint (utf8), or null when it did not exist there. */ + fileAt(commitId: string, filePath: string): Promise { + return this.locked(async () => { + const content = await this.readBlob(await this.resolveCommit(commitId), normalizeProjectPath(filePath)); + return content === null ? null : content.toString('utf8'); + }); + } + + /** Old (checkpoint) and new (disk) text of one file, for the review UI. */ + diffText(commitId: string, filePath: string): Promise { + return this.locked(async () => { + const relative = normalizeProjectPath(filePath); + const old = await this.readBlob(await this.resolveCommit(commitId), relative); + const current = await fs.readFile(this.absolute(relative)).catch((error: unknown) => { + if (isNotFound(error) || (error as NodeJS.ErrnoException).code === 'EISDIR') { + return null; + } + throw error; + }); + return { oldText: old === null ? null : old.toString('utf8'), newText: current === null ? null : current.toString('utf8') }; + }); + } + + /** Puts each file back as it was at the checkpoint, deleting the ones that did not exist there. */ + restoreFiles(commitId: string, paths: readonly string[]): Promise { + return this.locked(async () => { + const commit = await this.resolveCommit(commitId); + const relative = [...new Set(paths.map(normalizeProjectPath))]; + await this.writeFromCommit(commit, relative); + }); + } + + /** Restores every snapshotted file that differs from the checkpoint; returns the paths changed. */ + restoreAll(commitId: string): Promise { + return this.locked(async () => { + const paths = await this.pathsToRestore(commitId); + await this.writeFromCommit(await this.resolveCommit(commitId), paths); + return paths; + }); + } + + /** What `restoreAll` would change, without writing anything. */ + previewRestore(commitId: string): Promise { + return this.locked(() => this.pathsToRestore(commitId)); + } + + /** Waits for the running operation, then refuses any new one. The shadow repository stays on disk. */ + async dispose(): Promise { + if (this.disposed) { + return; + } + await withProjectLock(this.gitDir, async () => { + this.disposed = true; + }); + } + + // ---- internals ----------------------------------------------------------------- + + private locked(task: () => Promise): Promise { + if (this.disposed) { + return Promise.reject(new Error('The checkpoint store was disposed.')); + } + return withProjectLock(this.gitDir, async () => { + if (this.disposed) { + throw new Error('The checkpoint store was disposed.'); + } + await this.ensureInitialized(); + return task(); + }); + } + + private buildEnvironment(): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + // An inherited GIT_DIR, GIT_INDEX_FILE or GIT_CONFIG_* would redirect every call. + if (!key.toUpperCase().startsWith('GIT_')) { + env[key] = value; + } + } + delete env['ELECTRON_RUN_AS_NODE']; + delete env['NODE_OPTIONS']; + env['GIT_CONFIG_NOSYSTEM'] = '1'; + env['GIT_CONFIG_GLOBAL'] = path.join(this.gitDir, EMPTY_CONFIG_NAME); + env['GIT_TERMINAL_PROMPT'] = '0'; + env['LC_ALL'] = 'C'; + return env; + } + + /** Runs git with the shadow repository, the project as work tree and the private index. */ + private run(args: readonly string[], options: RunOptions = {}): Promise { + const env: NodeJS.ProcessEnv = { ...this.env }; + if (!options.bare) { + env['GIT_DIR'] = this.gitDir; + env['GIT_WORK_TREE'] = this.projectRoot; + env['GIT_INDEX_FILE'] = this.indexFile; + } + const fullArgs = [...this.configArgs, ...args]; + return new Promise((resolve, reject) => { + const child = execFile(this.gitExecutable, fullArgs, { + cwd: options.bare ? undefined : this.projectRoot, + env, + timeout: this.timeoutMs, + maxBuffer: MAX_OUTPUT_BYTES, + windowsHide: true, + encoding: 'buffer', + }, (error, stdout, stderr) => { + if (!error) { + resolve({ stdout, exitCode: 0 }); + return; + } + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT') { + reject(new Error(`Checkpoints need git, and "${this.gitExecutable}" was not found.`)); + return; + } + if ((error as { killed?: boolean }).killed) { + reject(new CheckpointTimeoutError(args, this.timeoutMs)); + return; + } + const exitCode = typeof code === 'number' ? code : -1; + if ((options.okExitCodes ?? []).includes(exitCode)) { + resolve({ stdout, exitCode }); + return; + } + const message = stderr.toString('utf8').trim(); + reject(new Error(`Checkpoint git ${args[0] ?? ''} failed${message ? `: ${message}` : ` (exit code ${exitCode}).`}`)); + }); + child.stdin?.on('error', () => undefined); + child.stdin?.end(options.input ?? ''); + }); + } + + private async ensureInitialized(): Promise { + if (this.initialized) { + return; + } + const head = path.join(this.gitDir, 'HEAD'); + const exists = await fs.access(head).then(() => true, () => false); + await fs.mkdir(this.gitDir, { recursive: true }); + await fs.writeFile(path.join(this.gitDir, EMPTY_CONFIG_NAME), '', { flag: 'a' }); + await fs.mkdir(path.join(this.gitDir, HOOKS_DIR_NAME), { recursive: true }); + if (!exists) { + await this.run(['init', '--bare', '--quiet', this.gitDir], { bare: true }); + // Bare at creation (nothing is checked out next to it), a work tree in use. + await this.run(['--git-dir', this.gitDir, 'config', 'core.bare', 'false'], { bare: true }); + await this.run(['--git-dir', this.gitDir, 'config', 'core.logAllRefUpdates', 'false'], { bare: true }); + await fs.writeFile(path.join(this.gitDir, 'codexr-project.json'), `${JSON.stringify({ projectRoot: this.projectRoot }, null, 2)}\n`); + } + await fs.mkdir(path.join(this.gitDir, 'info'), { recursive: true }); + await fs.writeFile(path.join(this.gitDir, 'info', 'attributes'), ATTRIBUTES); + this.initialized = true; + } + + /** Rewrites `info/exclude`: the defaults, the project's own exclude file, and the shadow repo if it sits inside the project. */ + private async writeExcludes(): Promise { + const lines = ['# Written by Code-XR checkpoints; rewritten before every snapshot.', ...DEFAULT_EXCLUDES]; + const inside = path.relative(this.projectRoot, path.dirname(this.gitDir)); + if (inside === '' || (!inside.startsWith('..') && !path.isAbsolute(inside))) { + lines.push(`/${path.relative(this.projectRoot, this.gitDir).split(path.sep).join('/')}/`); + } + lines.push(...await readProjectExclude(this.projectRoot)); + const file = path.join(this.gitDir, 'info', 'exclude'); + const content = `${lines.join('\n')}\n`; + const current = await fs.readFile(file, 'utf8').catch(() => null); + if (current !== content) { + await fs.writeFile(file, content); + } + } + + /** + * Brings the private index in line with the working tree and writes it as a + * tree. Throws `CheckpointsDisabledError` (with `disabledReason` set) when the + * project is too large or git times out. + */ + private async stageWorkingTree(): Promise { + try { + await this.writeExcludes(); + const listed = splitNul((await this.run(['ls-files', '-z', '--cached', '--others', '--exclude-standard'])).stdout); + // Untracked nested repositories are listed as their folder, with a trailing slash. + const nested = listed.filter((entry) => entry.endsWith('/')); + const files = listed.filter((entry) => !entry.endsWith('/')); + if (files.length > this.maxFiles) { + return this.disable(`This project is too large for checkpoints (more than ${this.maxFiles.toLocaleString('en-US')} files).`); + } + const large = await this.largeFiles(files); + const pathspecs = ['.', ...[...nested, ...large].map((entry) => `:(exclude,literal)${entry}`)]; + await this.run(['add', '--all', '--pathspec-from-file=-', '--pathspec-file-nul'], { input: `${pathspecs.join('\0')}\0` }); + const tree = (await this.run(['write-tree'])).stdout.toString('utf8').trim(); + const fileCount = splitNul((await this.run(['ls-files', '-z'])).stdout).length; + return { tree, fileCount }; + } catch (error) { + if (error instanceof CheckpointTimeoutError) { + // A killed git can leave its lock behind; nothing else of ours runs now (project lock). + await fs.rm(`${this.indexFile}.lock`, { force: true }); + return this.disable(`Checkpoints are off: a snapshot of this project took longer than ${Math.round(this.timeoutMs / 1000)} s.`); + } + throw error; + } + } + + private async stageOrThrow(): Promise { + if (this.disabled !== null) { + throw new CheckpointsDisabledError(this.disabled); + } + return this.stageWorkingTree(); + } + + private disable(reason: string): never { + this.disabled = reason; + throw new CheckpointsDisabledError(reason); + } + + /** The listed files larger than `maxFileBytes` (missing ones are skipped: they were deleted). */ + private async largeFiles(files: readonly string[]): Promise { + const large: string[] = []; + for (let start = 0; start < files.length; start += STAT_CONCURRENCY) { + const chunk = files.slice(start, start + STAT_CONCURRENCY); + const sizes = await Promise.all(chunk.map((file) => fs.lstat(this.absolute(file)).then((stat) => (stat.isFile() ? stat.size : 0), () => 0))); + sizes.forEach((size, index) => { + const file = chunk[index]; + if (size > this.maxFileBytes && file !== undefined) { + large.push(file); + } + }); + } + return large; + } + + private async currentHead(): Promise { + const result = await this.run(['rev-parse', '--verify', '--quiet', CHECKPOINT_REF], { okExitCodes: [1] }); + const sha = result.stdout.toString('utf8').trim(); + return result.exitCode === 0 && sha !== '' ? sha : null; + } + + /** Validates a checkpoint id and returns its full sha. */ + private async resolveCommit(commitId: string): Promise { + if (!COMMIT_ID.test(commitId)) { + throw new Error(`Not a checkpoint id: "${commitId}".`); + } + const result = await this.run(['rev-parse', '--verify', '--quiet', `${commitId}^{commit}`], { okExitCodes: [1, 128] }); + const sha = result.stdout.toString('utf8').trim(); + if (result.exitCode !== 0 || sha === '') { + throw new Error(`Checkpoint ${commitId} does not exist in this project's history.`); + } + return sha; + } + + private async diffTrees(base: string, tree: string): Promise { + const statusOutput = splitNul((await this.run(['diff-tree', '-r', '-z', '--no-renames', '--name-status', base, tree])).stdout); + const numstatOutput = splitNul((await this.run(['diff-tree', '-r', '-z', '--no-renames', '--numstat', base, tree])).stdout); + const counts = new Map(); + for (const record of numstatOutput) { + const match = /^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(record); + if (match?.[3] !== undefined) { + const binary = match[1] === '-'; + counts.set(match[3], { additions: binary ? 0 : Number(match[1]), deletions: binary ? 0 : Number(match[2]), binary }); + } + } + const changes: ChangedFile[] = []; + for (let index = 0; index + 1 < statusOutput.length; index += 2) { + const letter = statusOutput[index] ?? ''; + const filePath = statusOutput[index + 1] ?? ''; + const status: ChangeStatus = letter.startsWith('A') ? 'added' : letter.startsWith('D') ? 'deleted' : 'modified'; + const count = counts.get(filePath) ?? { additions: 0, deletions: 0, binary: false }; + changes.push({ path: filePath, status, ...count }); + } + return changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + } + + private async pathsToRestore(commitId: string): Promise { + const commit = await this.resolveCommit(commitId); + const { tree } = await this.stageOrThrow(); + const output = await this.run(['diff-tree', '-r', '-z', '--no-renames', '--name-only', commit, tree]); + return splitNul(output.stdout).sort(); + } + + /** One file's blob at a commit, or null when the path is not a file there. */ + private async readBlob(commit: string, relative: string): Promise { + const entry = (await this.treeEntries(commit, [relative])).get(relative); + if (!entry) { + return null; + } + return (await this.readBlobs([entry.sha])).get(entry.sha) ?? null; + } + + /** Blob entries of a commit's tree, limited to `only` when given. */ + private async treeEntries(commit: string, only?: readonly string[]): Promise> { + const wanted = only ? new Set(only) : null; + const output = splitNul((await this.run(['ls-tree', '-r', '-z', '-l', '--full-tree', commit])).stdout); + const entries = new Map(); + for (const record of output) { + const match = /^(\d+) (\w+) ([0-9a-f]+) +(-|\d+)\t(.*)$/s.exec(record); + if (match?.[5] === undefined || match[2] !== 'blob' || (wanted && !wanted.has(match[5]))) { + continue; + } + entries.set(match[5], { mode: match[1] ?? '100644', sha: match[3] ?? '', size: Number(match[4]) || 0 }); + } + return entries; + } + + /** Reads blobs through `cat-file --batch`, as raw bytes. */ + private async readBlobs(shas: readonly string[]): Promise> { + const blobs = new Map(); + if (shas.length === 0) { + return blobs; + } + const output = (await this.run(['cat-file', '--batch'], { input: `${shas.join('\n')}\n`, bare: false })).stdout; + let offset = 0; + while (offset < output.length) { + const newline = output.indexOf(0x0a, offset); + if (newline < 0) { + break; + } + const header = output.subarray(offset, newline).toString('utf8'); + const match = /^([0-9a-f]+) (\w+) (\d+)$/.exec(header); + if (!match?.[1] || !match[3]) { + // " missing": no body follows. + offset = newline + 1; + continue; + } + const size = Number(match[3]); + blobs.set(match[1], output.subarray(newline + 1, newline + 1 + size)); + offset = newline + 1 + size + 1; + } + return blobs; + } + + private absolute(relative: string): string { + return path.join(this.projectRoot, ...relative.split('/')); + } + + /** Writes each path as it is in `commit`, or deletes it when the commit does not have it. */ + private async writeFromCommit(commit: string, paths: readonly string[]): Promise { + if (paths.length === 0) { + return; + } + const entries = await this.treeEntries(commit, paths); + const toDelete = paths.filter((relative) => !entries.has(relative)); + const toWrite = paths.filter((relative) => entries.has(relative)); + for (const relative of toDelete) { + await this.deleteFile(relative); + } + let batch: string[] = []; + let batchBytes = 0; + const flush = async (): Promise => { + const unique = [...new Set(batch.map((relative) => entries.get(relative)?.sha ?? ''))]; + const blobs = await this.readBlobs(unique); + for (const relative of batch) { + const entry = entries.get(relative); + const content = entry ? blobs.get(entry.sha) : undefined; + if (!entry || content === undefined) { + throw new Error(`Checkpoint ${commit.slice(0, 12)} has no content for ${relative}.`); + } + await this.writeFile(relative, entry.mode, content); + } + batch = []; + batchBytes = 0; + }; + for (const relative of toWrite) { + const size = entries.get(relative)?.size ?? 0; + if (batch.length > 0 && batchBytes + size > BATCH_BYTES) { + await flush(); + } + batch.push(relative); + batchBytes += size; + } + if (batch.length > 0) { + await flush(); + } + } + + private async deleteFile(relative: string): Promise { + const target = this.absolute(relative); + const stat = await fs.lstat(target).catch((error: unknown) => { + if (isNotFound(error)) { + return null; + } + throw error; + }); + if (stat === null) { + return; + } + if (stat.isDirectory()) { + throw new Error(`Cannot restore ${relative}: it is a folder now.`); + } + await fs.unlink(target); + await this.removeEmptyParents(path.dirname(target)); + } + + /** Removes folders left empty by a deletion, up to (not including) the project root. */ + private async removeEmptyParents(directory: string): Promise { + let current = directory; + while (current !== this.projectRoot && current.startsWith(this.projectRoot + path.sep)) { + const removed = await fs.rmdir(current).then(() => true, () => false); + if (!removed) { + return; + } + current = path.dirname(current); + } + } + + /** Writes a file's bytes through a temporary sibling and a rename; recreates a symbolic link where the platform allows it. */ + private async writeFile(relative: string, treeMode: string, content: Buffer): Promise { + const target = this.absolute(relative); + await fs.mkdir(path.dirname(target), { recursive: true }); + const current = await fs.lstat(target).catch((error: unknown) => { + if (isNotFound(error)) { + return null; + } + throw error; + }); + if (current?.isDirectory()) { + throw new Error(`Cannot restore ${relative}: it is a folder now.`); + } + if (treeMode === '120000') { + const linkTarget = content.toString('utf8'); + if (current?.isSymbolicLink() && (await fs.readlink(target)) === linkTarget) { + return; + } + await fs.rm(target, { force: true }); + await fs.symlink(linkTarget, target); + return; + } + if (current?.isFile()) { + const existing = await fs.readFile(target); + if (existing.equals(content) && fileMode(treeMode, current.mode) === (current.mode & 0o777)) { + return; + } + } + const temporary = `${target}.codexr-${randomBytes(6).toString('hex')}.tmp`; + // An existing file keeps its permissions (executable bit from the tree); a new one gets the umask's. + const existingMode = current?.isFile() ? fileMode(treeMode, current.mode) : null; + try { + await fs.writeFile(temporary, content, { mode: existingMode ?? (treeMode === '100755' ? 0o777 : 0o666) }); + if (current?.isSymbolicLink()) { + await fs.rm(target, { force: true }); + } + await fs.rename(temporary, target); + } catch (error) { + await fs.rm(temporary, { force: true }); + if ((error as NodeJS.ErrnoException).code === 'EPERM' || (error as NodeJS.ErrnoException).code === 'EBUSY') { + // Windows refuses to rename over a file another process holds open; write in place instead. + await fs.writeFile(target, content); + return; + } + throw error; + } + if (existingMode !== null && process.platform !== 'win32') { + await fs.chmod(target, existingMode); + } + } +} diff --git a/apps/ide/src/main/checkpoints/reviewBase.ts b/apps/ide/src/main/checkpoints/reviewBase.ts new file mode 100644 index 000000000..37eb57099 --- /dev/null +++ b/apps/ide/src/main/checkpoints/reviewBase.ts @@ -0,0 +1,120 @@ +/** + * The review base of a chat session (AF5, #270): which checkpoint each file's + * pending changes are measured against. Pure data, no git, so the session store + * can persist it as JSON and the tests need no repository. + * + * The model is one session-wide base checkpoint plus per-file overrides: + * + * - When a session starts reviewing, its base is a snapshot of the tree + * (`createReviewBase`). Pending changes are `changes(baseId)`. + * - "Keep" on one file: the caller takes a fresh snapshot and records it as + * that file's own base (`keepFile`). The file then shows as pending again + * only if it changes after the keep. + * - "Keep all": a fresh snapshot becomes the session base and the overrides go + * (`keepAll`). + * - "Undo" on one file restores it from `baseFor(state, path)`; the base does + * not move, so the file simply stops differing. + * + * With overrides, the pending list is assembled per base: query + * `changes(base)` for every id in `basesToQuery(state)`, then keep, from each + * result, only the files whose own base is that id (`mergePendingChanges`). + */ + +export interface ReviewBaseState { + /** The checkpoint every file is compared against unless it has its own. */ + readonly baseId: string; + /** Per-file bases (posix project-relative path → checkpoint id), set by "Keep" on one file. */ + readonly fileBases: Readonly>; +} + +export function createReviewBase(baseId: string): ReviewBaseState { + return { baseId, fileBases: {} }; +} + +/** The checkpoint `filePath` is compared against. */ +export function baseFor(state: ReviewBaseState, filePath: string): string { + return Object.hasOwn(state.fileBases, filePath) ? state.fileBases[filePath] ?? state.baseId : state.baseId; +} + +/** "Keep" one file: from now on it is compared against `checkpointId` (a snapshot taken at the keep). */ +export function keepFile(state: ReviewBaseState, filePath: string, checkpointId: string): ReviewBaseState { + if (checkpointId === state.baseId) { + const { [filePath]: _removed, ...rest } = state.fileBases; + return { baseId: state.baseId, fileBases: rest }; + } + return { baseId: state.baseId, fileBases: { ...state.fileBases, [filePath]: checkpointId } }; +} + +/** "Keep" several files against the same new snapshot. */ +export function keepFiles(state: ReviewBaseState, filePaths: readonly string[], checkpointId: string): ReviewBaseState { + return filePaths.reduce((current, filePath) => keepFile(current, filePath, checkpointId), state); +} + +/** "Keep all": `checkpointId` becomes the base of every file. */ +export function keepAll(_state: ReviewBaseState, checkpointId: string): ReviewBaseState { + return createReviewBase(checkpointId); +} + +/** Every checkpoint id `changes()` must be asked about, the session base first. */ +export function basesToQuery(state: ReviewBaseState): string[] { + return [...new Set([state.baseId, ...Object.values(state.fileBases)])]; +} + +/** All checkpoint ids the state refers to (what a pruning pass must keep). */ +export function referencedCheckpoints(state: ReviewBaseState): string[] { + return basesToQuery(state); +} + +/** + * Assembles the pending list from `changes(base)` per base: each file comes + * from the result of its own base, and the list is sorted by path. + */ +export function mergePendingChanges(state: ReviewBaseState, changesByBase: ReadonlyMap): T[] { + const pending: T[] = []; + for (const [base, changes] of changesByBase) { + for (const change of changes) { + if (baseFor(state, change.path) === base) { + pending.push(change); + } + } + } + return pending.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); +} + +export function serializeReviewBase(state: ReviewBaseState): string { + return JSON.stringify({ baseId: state.baseId, fileBases: state.fileBases }); +} + +/** Reads a persisted state back; returns null for anything malformed rather than trusting it. */ +export function parseReviewBase(value: unknown): ReviewBaseState | null { + let data = value; + if (typeof data === 'string') { + try { + data = JSON.parse(data) as unknown; + } catch { + return null; + } + } + if (typeof data !== 'object' || data === null) { + return null; + } + const { baseId, fileBases } = data as { baseId?: unknown; fileBases?: unknown }; + if (typeof baseId !== 'string' || baseId === '') { + return null; + } + const bases: Record = {}; + if (fileBases !== undefined) { + if (typeof fileBases !== 'object' || fileBases === null || Array.isArray(fileBases)) { + return null; + } + for (const [filePath, id] of Object.entries(fileBases)) { + if (typeof id !== 'string' || id === '') { + return null; + } + if (id !== baseId) { + bases[filePath] = id; + } + } + } + return { baseId, fileBases: bases }; +} diff --git a/apps/ide/src/main/checkpoints/sessionChanges.ts b/apps/ide/src/main/checkpoints/sessionChanges.ts new file mode 100644 index 000000000..e59c6d99c --- /dev/null +++ b/apps/ide/src/main/checkpoints/sessionChanges.ts @@ -0,0 +1,200 @@ +import path from 'node:path'; +import { CheckpointStore, normalizeProjectPath, type ChangedFile, type CheckpointStoreOptions, type DiffText } from './checkpointStore.ts'; +import { + baseFor, basesToQuery, createReviewBase, keepAll, keepFiles, mergePendingChanges, parseReviewBase, type ReviewBaseState, +} from './reviewBase.ts'; + +/** + * The review of a chat's changes (AF5, #270) and its checkpoints per turn + * (AF6, #271), on top of `CheckpointStore` (the snapshots) and `reviewBase` + * (what each file is compared against): + * + * - `beforePrompt` snapshots the project before every message; the chat's + * first snapshot becomes its review base, so "pending" means "changed since + * this chat started, and not kept or undone since". + * - `pending` lists those files; `diff` gives the two sides of one of them. + * - `keep` accepts files as they are (a fresh snapshot becomes their base); + * `undo` writes them back from their base, after which they no longer differ. + * - `previewRestore` / `restoreCheckpoint` put the whole project back as it + * was before one message (the conversation is not touched). + * + * One `CheckpointStore` per project root, its shadow repositories under + * `storageDir` (outside every project); the review base of each chat is + * persisted in `bases`. A project whose checkpoints are off (too many files, a + * timeout, no git) degrades to "no checkpoint": `beforePrompt` returns null and + * `pending` reports the reason. No Electron, so it is unit-tested on temp + * folders. + */ + +export interface ReviewBaseStore { + get(key: string): T | undefined; + /** undefined removes the key. */ + update(key: string, value: unknown): Promise; +} + +export interface SessionChangesOptions { + /** Where the shadow repositories live (userData/checkpoints). */ + readonly storageDir: string; + /** The persisted review bases, keyed by chat id. */ + readonly bases: ReviewBaseStore; + /** Extra options for each store (git executable, limits, timeout); tests use them. */ + readonly store?: Omit; +} + +export interface PendingChanges { + readonly files: readonly ChangedFile[]; + readonly disabledReason: string | null; +} + +const CHECKPOINT_ID = /^[0-9a-f]{40,64}$/; + +export class SessionChanges { + private readonly options: SessionChangesOptions; + private readonly stores = new Map(); + + constructor(options: SessionChangesOptions) { + this.options = options; + } + + /** The store of a project, created on first use. */ + storeFor(root: string): CheckpointStore { + const key = path.resolve(root); + let store = this.stores.get(key); + if (!store) { + store = new CheckpointStore({ ...this.options.store, storageDir: this.options.storageDir, projectRoot: key }); + this.stores.set(key, store); + } + return store; + } + + /** The chat's review base, or null before its first checkpoint. */ + reviewBase(sessionId: string): ReviewBaseState | null { + return parseReviewBase(this.options.bases.get(sessionId)); + } + + /** + * Snapshots the project before a message. The chat's first snapshot is + * its review base. Null when checkpoints are off for the project. + */ + async beforePrompt(sessionId: string, root: string, label = 'Before a message'): Promise<{ readonly checkpointId: string } | null> { + const checkpoint = await this.storeFor(root).snapshot(label); + if (!checkpoint) { + return null; + } + if (!this.reviewBase(sessionId)) { + await this.saveBase(sessionId, createReviewBase(checkpoint.id)); + } + return { checkpointId: checkpoint.id }; + } + + /** How many files await review after a turn; null when the chat has no review base or checkpoints are off. */ + async afterTurn(sessionId: string, root: string): Promise { + if (!this.reviewBase(sessionId)) { + return null; + } + const pending = await this.pending(sessionId, root); + return pending.disabledReason !== null ? null : pending.files.length; + } + + /** The files the chat changed that still await review, sorted by path. */ + async pending(sessionId: string, root: string): Promise { + const store = this.storeFor(root); + const state = this.reviewBase(sessionId); + if (store.disabledReason !== null) { + return { files: [], disabledReason: store.disabledReason }; + } + if (!state) { + return { files: [], disabledReason: null }; + } + const byBase = new Map(); + for (const base of basesToQuery(state)) { + byBase.set(base, await store.changes(base)); + } + return { files: mergePendingChanges(state, byBase), disabledReason: null }; + } + + /** The files the project has changed since a checkpoint (all of them, not only the pending ones). */ + async changedSince(root: string, checkpointId: string): Promise { + const store = this.storeFor(root); + if (store.disabledReason !== null) { + return []; + } + return (await store.changes(checkCheckpointId(checkpointId))).map((change) => change.path); + } + + /** One file at its review base and on disk now. */ + async diff(sessionId: string, root: string, filePath: string): Promise { + const relative = normalizeProjectPath(filePath); + const state = this.requireBase(sessionId); + return this.storeFor(root).diffText(baseFor(state, relative), relative); + } + + /** Accepts files as they are now: a fresh snapshot becomes their base ("all": every file's). */ + async keep(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise { + const state = this.requireBase(sessionId); + const store = this.storeFor(root); + const checkpoint = await store.snapshot('Kept changes'); + if (!checkpoint) { + throw new Error(`Checkpoints are off for this project: ${store.disabledReason ?? 'unknown reason'}.`); + } + const next = paths === 'all' ? keepAll(state, checkpoint.id) : keepFiles(state, [...new Set(paths.map(normalizeProjectPath))], checkpoint.id); + await this.saveBase(sessionId, next); + } + + /** Writes files back as they were at their base ("all": every pending file). Returns the paths written. */ + async undo(sessionId: string, root: string, paths: readonly string[] | 'all'): Promise { + const state = this.requireBase(sessionId); + const store = this.storeFor(root); + const targets = paths === 'all' ? (await this.pending(sessionId, root)).files.map((file) => file.path) : [...new Set(paths.map(normalizeProjectPath))]; + const groups = new Map(); + for (const target of targets) { + const base = baseFor(state, target); + groups.set(base, [...(groups.get(base) ?? []), target]); + } + for (const [base, group] of groups) { + await store.restoreFiles(base, group); + } + return targets; + } + + /** What `restoreCheckpoint` would write. */ + previewRestore(root: string, checkpointId: string): Promise { + return this.storeFor(root).previewRestore(checkCheckpointId(checkpointId)); + } + + /** Puts every snapshotted file back as it was at the checkpoint; returns the paths written. */ + restoreCheckpoint(root: string, checkpointId: string): Promise { + return this.storeFor(root).restoreAll(checkCheckpointId(checkpointId)); + } + + /** A chat was deleted: its review base goes (the snapshots stay in the shadow repository). */ + async forget(sessionId: string): Promise { + if (this.options.bases.get(sessionId) !== undefined) { + await this.options.bases.update(sessionId, undefined); + } + } + + async dispose(): Promise { + await Promise.all([...this.stores.values()].map((store) => store.dispose())); + this.stores.clear(); + } + + private requireBase(sessionId: string): ReviewBaseState { + const state = this.reviewBase(sessionId); + if (!state) { + throw new Error('This chat has no checkpoint to compare with yet.'); + } + return state; + } + + private saveBase(sessionId: string, state: ReviewBaseState): Promise { + return this.options.bases.update(sessionId, { baseId: state.baseId, fileBases: state.fileBases }); + } +} + +function checkCheckpointId(value: string): string { + if (!CHECKPOINT_ID.test(value)) { + throw new Error('Invalid checkpoint.'); + } + return value; +} diff --git a/apps/ide/src/main/index.ts b/apps/ide/src/main/index.ts index 6e6dcc46b..c91abcbfe 100644 --- a/apps/ide/src/main/index.ts +++ b/apps/ide/src/main/index.ts @@ -29,6 +29,7 @@ import { initRecentFolders, openRecentFolder, recentFolderList, setWorkspace } f import { chooseStartupFolder } from './workspace/startupFolder.ts'; import { createTerminalHost, type TerminalHost } from './terminal/terminalHost.ts'; import { startAgents, type AgentServices } from './agents/agentsRuntime.ts'; +import { startAgentSessions, type AgentSessionsRuntime } from './agentSessions/agentSessionsRuntime.ts'; import { setScenePreloadPath } from './analysis/sceneView.ts'; import { appIconPath } from './appIcon.ts'; import { createLspHost, type LspHost } from './lsp/lspHost.ts'; @@ -81,11 +82,14 @@ if (!isSmoke && !app.requestSingleInstanceLock()) { let terminals: TerminalHost | null = null; // A12: MCP server processes likewise. let agentServices: AgentServices | null = null; +// AF1: coding agents (one process per chat) likewise; their chats are written first. +let agentSessions: AgentSessionsRuntime | null = null; // #21: so do the language servers. let languageServers: LspHost | null = null; app.on('will-quit', () => { 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(); @@ -120,6 +124,8 @@ async function start(): Promise { const keybindingsFile = path.join(app.getPath('userData'), KEYBINDINGS_FILE_NAME); const keybindings = isSmoke ? new KeybindingsService(memoryStorage(), null) : new KeybindingsService(fileStorage(keybindingsFile), keybindingsFile); agentServices = startAgents({ isSmoke, commandRunner: terminalHost.commandRunner }); + // The smoke run may never start an agent: the service refuses to spawn there. + agentSessions = startAgentSessions({ isSmoke, terminal: terminalHost, profiles: agentServices.profiles, analysisOutput: (contents) => core.analysis.outputDirectory(contents), analysis: core.analysis }); // #177: workspace trust decisions, in the user-data folder (in memory for the smoke run). const trustFile = isSmoke ? null : new JsonKeyValueStore(path.join(app.getPath('userData'), 'workspace-trust.json')); let smokeTrust: unknown = []; @@ -145,7 +151,7 @@ async function start(): Promise { const extensionHosts = new ExtensionHostManager({ service: extensions, hostScript: EXTENSION_HOST_PATH, isDevelopment }); extensions.attachHost((handle) => extensionHosts.register(handle)); app.on('will-quit', () => void extensionHosts.stopAll()); - registerIpcHandlers(origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp, extensions); + registerIpcHandlers(origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp, agentSessions, extensions); // #171: the stored theme, before the first window paints. applyColorTheme((await settings.snapshot(null)).effective[COLOR_THEME_SETTING]); installApplicationMenu(isDevelopment); diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index a6f4d4172..a3f6cb867 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -4,6 +4,8 @@ import { ALLOWED_IPC_CHANNELS, AUTO_START_MODES, FILE_ANALYSIS_KINDS, IPC_CHANNE import type { TerminalHost } from './terminal/terminalHost.ts'; import type { AgentServices } from './agents/agentsRuntime.ts'; import { registerAgentHandlers } from './agents/agentsIpc.ts'; +import { registerAgentSessionHandlers } from './agentSessions/agentSessionsIpc.ts'; +import type { AgentSessionsRuntime } from './agentSessions/agentSessionsRuntime.ts'; import { registerGitHandlers } from './git/gitIpc.ts'; import type { LspHost } from './lsp/lspHost.ts'; import { registerLspHandlers } from './lsp/lspIpc.ts'; @@ -33,7 +35,7 @@ type Handler = (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown; * through `handle`, which refuses calls from frames outside the trusted * origins, so a handler never has to check its caller itself. */ -export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: boolean, core: CoreServices, terminal: TerminalHost, settings: SettingsService, keybindings: KeybindingsService, output: OutputService, agents: AgentServices, lsp: LspHost, extensions: ExtensionsService): void { +export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: boolean, core: CoreServices, terminal: TerminalHost, settings: SettingsService, keybindings: KeybindingsService, output: OutputService, agents: AgentServices, lsp: LspHost, agentSessions: AgentSessionsRuntime, extensions: ExtensionsService): void { const registered = new Set(); const handle = (channel: string, handler: Handler): void => { if (!ALLOWED_IPC_CHANNELS.has(channel)) { @@ -247,6 +249,8 @@ export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: // The AI agent hub (agents/agentsIpc.ts). registerAgentHandlers(handle, agents, (contents) => core.analysis.outputDirectory(contents)); + // Epic #265 (AF1): agent-first chats with ACP agents (agentSessions/agentSessionsIpc.ts). + registerAgentSessionHandlers(handle, agentSessions); // #17: Source Control (git/gitIpc.ts). registerGitHandlers(handle); // #21: language servers (lsp/lspIpc.ts). diff --git a/apps/ide/src/main/smoke.ts b/apps/ide/src/main/smoke.ts index c554d2551..63ecb08a9 100644 --- a/apps/ide/src/main/smoke.ts +++ b/apps/ide/src/main/smoke.ts @@ -30,6 +30,8 @@ export interface SmokeProbe { /** #17: Source Control answered for the smoke folder and refused a path out of it. */ readonly gitStatusState: string | null; readonly gitTraversalRefused: boolean; + /** AF2: the smoke run may not download anything; reading what an agent install would fetch is refused. */ + readonly agentInstallRefused: boolean; /** #177: the folder's trust before and after the smoke run trusted it, and Git while it was not trusted. */ readonly trust: { readonly before?: string; readonly shieldShown?: boolean; readonly restrictedGit?: string; readonly tasksRefused?: boolean; readonly debugRefused?: boolean; readonly remoteRefused?: boolean; readonly after?: string; readonly error?: string } | null; /** #14: package.json opened from the explorer in a Monaco tab, with no CSP violation on the way. */ @@ -162,6 +164,8 @@ const RENDERER_PROBE = `(async () => { try { gitStatusState = (await window.codexr.git.status()).state; } catch { gitStatusState = null; } let gitTraversalRefused = false; try { await window.codexr.git.headContent('../package.json'); } catch { gitTraversalRefused = true; } + let agentInstallRefused = false; + try { await window.codexr.agentSessions.describeInstall('claude'); } catch (e) { agentInstallRefused = /not available in this mode/.test(String(e)); } document.querySelector('[data-testid="explorer-tree"] [data-path="package.json"]')?.click(); const editorUntil = Date.now() + 15000; const editorReady = () => document.querySelector('.editor-tab[data-path="package.json"][aria-selected="true"]') && document.querySelector('.monaco-editor .view-line'); @@ -412,6 +416,7 @@ const RENDERER_PROBE = `(async () => { gitStatusState, trust, gitTraversalRefused, + agentInstallRefused, editorOpened, fileIconsShown, fileIconsBroken, @@ -538,6 +543,7 @@ export function evaluateSmoke(probe: SmokeProbe | null, navigationBlocked: boole failures.push(`workspace trust did not gate Git, tasks or debugging, or did not take the answer (got ${JSON.stringify(probe.trust)})`); } if (!probe.gitTraversalRefused) { failures.push('git.headContent followed a path out of the folder'); } + if (!probe.agentInstallRefused) { failures.push('the smoke run could reach the npm registry to install an agent'); } if (!probe.editorOpened) { failures.push('package.json did not open in a Monaco editor tab'); } if (probe.fileIconsShown === 0) { failures.push('the explorer and the tabs showed no file icon'); } if (probe.fileIconsBroken.length > 0) { failures.push(`file icons did not load: ${probe.fileIconsBroken.join(', ')}`); } diff --git a/apps/ide/src/main/worktrees/worktreeGit.ts b/apps/ide/src/main/worktrees/worktreeGit.ts new file mode 100644 index 000000000..020071119 --- /dev/null +++ b/apps/ide/src/main/worktrees/worktreeGit.ts @@ -0,0 +1,88 @@ +import { execFile } from 'node:child_process'; +import { BASE_ARGS, DEFAULT_GIT_TIMEOUT_MS, GitCommandError, GitNotFoundError, gitEnvironment } from '../git/gitRunner.ts'; + +/** + * The git runner of the agent worktrees (AF12, #277). + * + * It reuses the Source Control runner's conventions (src/main/git/gitRunner.ts): + * `execFile`, never a shell; the same hardening options (`BASE_ARGS`: no + * fsmonitor, literal pathspecs, no pager); the same error classes; and the same + * environment (`gitEnvironment`: no prompt, no Electron switches). On top of + * that it drops every inherited `GIT_*` variable before `gitEnvironment` adds + * its own: an inherited `GIT_DIR`, `GIT_WORK_TREE` or `GIT_INDEX_FILE` (set + * when the IDE itself is launched from a git hook, for example) would point + * every call at the wrong repository, and a worktree is precisely a second + * work tree of one repository. + * + * It is a separate runner rather than `runGit` because the worktree code needs + * per-call `-c` options (the empty hooks directory, the fallback identity) + * placed before the subcommand, and that inherited-env stripping, which the + * Source Control view does not do today. + */ + +export interface WorktreeGitResult { + readonly stdout: string; + readonly stderr: string; + readonly exitCode: number; +} + +export interface WorktreeGitOptions { + /** `-c key=value` pairs placed before the subcommand, for this call only. */ + readonly config?: readonly string[] | undefined; + /** Exit codes that are not failures. */ + readonly okExitCodes?: readonly number[] | undefined; + readonly timeoutMs?: number | undefined; +} + +const MAX_OUTPUT_BYTES = 64 * 1024 * 1024; + +/** The process environment without any inherited `GIT_*` variable, then hardened by `gitEnvironment`. */ +export function worktreeGitEnvironment(base: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + const clean: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(base)) { + if (!key.toUpperCase().startsWith('GIT_')) { + clean[key] = value; + } + } + return gitEnvironment(clean); +} + +export function runWorktreeGit(cwd: string, args: readonly string[], options: WorktreeGitOptions = {}): Promise { + const config: string[] = []; + for (const pair of options.config ?? []) { + config.push('-c', pair); + } + const fullArgs = [...BASE_ARGS, ...config, ...args]; + return new Promise((resolve, reject) => { + const child = execFile('git', fullArgs, { + cwd, + env: worktreeGitEnvironment(process.env), + timeout: options.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, + maxBuffer: MAX_OUTPUT_BYTES, + windowsHide: true, + encoding: 'utf8', + }, (error, stdout, stderr) => { + if (!error) { + resolve({ stdout, stderr, exitCode: 0 }); + return; + } + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT') { + reject(new GitNotFoundError()); + return; + } + const exitCode = typeof code === 'number' ? code : -1; + if ((options.okExitCodes ?? []).includes(exitCode)) { + resolve({ stdout, stderr, exitCode }); + return; + } + if ((error as { killed?: boolean }).killed) { + reject(new GitCommandError(args, exitCode, `git ${args[0] ?? ''} timed out.`)); + return; + } + reject(new GitCommandError(args, exitCode, stderr)); + }); + child.stdin?.on('error', () => undefined); + child.stdin?.end(''); + }); +} diff --git a/apps/ide/src/main/worktrees/worktreeManager.ts b/apps/ide/src/main/worktrees/worktreeManager.ts new file mode 100644 index 000000000..25ff85dcf --- /dev/null +++ b/apps/ide/src/main/worktrees/worktreeManager.ts @@ -0,0 +1,698 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { GitCommandError, GitNotFoundError } from '../git/gitRunner.ts'; +import { runWorktreeGit, type WorktreeGitOptions, type WorktreeGitResult } from './worktreeGit.ts'; +import { + agentBranchName, isAgentBranch, isSafeSessionId, parseNameStatus, parseNulList, parsePorcelain, parseWorktreeList, repoHash, + type WorktreeChangeStatus, +} from './worktreeModel.ts'; + +/** + * Agent worktrees (AF12, #277): a chat can run in its own `git worktree`, on + * its own branch, so several agents work on one project in parallel without + * writing over each other's files, and the person then merges or discards + * each result. Pure Node, no Electron; the IPC layer wraps these functions. + * + * Lifecycle: + * canUseWorktrees(projectRoot) the folder is in a work tree with a commit + * createWorktree({...}) branch `codexr/agent/-` from HEAD, + * worktree at `storageDir//` + * worktreeStatus(info) what the agent changed since baseCommit + * commitAll(info, message) `add -A` + commit inside the worktree + * mergeIntoCurrent(info, {...}) into the main tree's current branch + * removeWorktree(info, {...}) worktree remove --force + prune (+ branch -D) + * listWorktrees(projectRoot) ours only, after a restart + * + * Choices: + * - The worktree starts from HEAD, not from the main tree's uncommitted + * state; `createWorktree` reports `dirty` so the UI can say that those + * changes are not in the agent's copy. + * - Worktrees live outside the project (in `storageDir`, e.g. userData), so the + * project's file watchers, search and analyses never see a second copy of + * it. The folder is keyed on a hash of the repository's common git + * directory, so a project opened from a sub-folder and all of its worktrees + * share one place. A JSON sidecar next to each worktree + * (`.json`) keeps `baseCommit`, the label and the sub-folder, so + * `listWorktrees` returns complete records after a restart; without it the + * base falls back to the merge base with the main tree's HEAD. + * - Hooks. What the IDE does on the agent's behalf runs none of the + * repository's hooks: `worktree add` (post-checkout) and the worktree + * commits (pre-commit, prepare-commit-msg, commit-msg, post-commit) run + * with `core.hooksPath` pointing at an empty directory the IDE owns, and the + * commits also pass `--no-verify`. `--no-verify` alone is not enough: it + * skips neither prepare-commit-msg nor post-commit. Those commits are also + * unsigned (`commit.gpgsign=false`): they are scratch history on a throwaway + * branch, and a signing prompt would hang an unattended agent. The final + * merge into the person's branch is theirs, so it runs with their hooks and + * their signing configuration, as if they had typed it. + * - Identity: worktree commits use the repository's own `user.name` and + * `user.email` (local or global config). When either is missing, that one + * commit is made as `Code-XR agent ` via `-c`; no + * configuration file is ever written. + * - Merge safety: the merge refuses, before touching anything, when the main + * tree has staged changes, uncommitted changes to a file the branch also + * changes, an operation in progress, a detached HEAD, or when + * `git merge-tree --write-tree` predicts a conflict. If the real merge + * still fails (an older git without merge-tree, a hook that rejects), it is + * undone with `merge --abort` / `reset --merge`, which keeps the person's + * unrelated uncommitted edits, and the error says why. `merge` makes a + * merge commit (`--no-ff`, so the agent's work stays one visible unit); + * `squash` makes one ordinary commit. + * - Environment: inherited `GIT_*` variables, `ELECTRON_RUN_AS_NODE` and + * `NODE_OPTIONS` are dropped (worktreeGit.ts). Paths go through `path`; + * what git prints (forward slashes, also on Windows) is resolved before it + * is compared, and file paths reported to callers stay git's POSIX form. + * - Mutating calls on one repository are serialized by an in-process lock, so + * two chats finishing together cannot interleave two merges. + */ + +export type WorktreeErrorCode = + | 'git-missing' + | 'not-a-repo' + | 'bare-repo' + | 'no-commits' + | 'invalid-argument' + | 'storage-inside-project' + | 'already-exists' + | 'worktree-missing' + | 'branch-missing' + | 'branch-changed' + | 'not-ours' + | 'detached-head' + | 'operation-in-progress' + | 'staged-changes' + | 'dirty-overlap' + | 'uncommitted-in-worktree' + | 'conflicts' + | 'merge-failed'; + +/** Every refusal of this module; `files` lists the paths involved (POSIX, repository-relative) when there are any. */ +export class WorktreeError extends Error { + readonly code: WorktreeErrorCode; + readonly files: readonly string[]; + constructor(code: WorktreeErrorCode, message: string, files: readonly string[] = []) { + super(message); + this.name = 'WorktreeError'; + this.code = code; + this.files = files; + } +} + +export type WorktreeAvailability = + | { readonly ok: true; readonly repoRoot: string; readonly head: string } + | { readonly ok: false; readonly reason: 'git-missing' | 'not-a-repo' | 'bare-repo' | 'no-commits'; readonly message: string }; + +/** Everything needed to act on one agent worktree; the caller keeps it with the chat. */ +export interface WorktreeInfo { + readonly sessionId: string; + readonly label: string; + /** Top of the main work tree, where merges land. */ + readonly repoRoot: string; + /** Top of the agent's worktree. */ + readonly path: string; + /** Where the agent should run: `path` plus the project's sub-folder inside the repository. */ + readonly cwd: string; + readonly branch: string; + /** The commit the branch started from. */ + readonly baseCommit: string; + /** Milliseconds since the epoch. */ + readonly createdAt: number; +} + +export interface CreateWorktreeOptions { + readonly projectRoot: string; + /** Directory owned by the IDE, outside every project (e.g. `userData/worktrees`). */ + readonly storageDir: string; + readonly sessionId: string; + /** Human label (the chat title); becomes the branch slug. */ + readonly label: string; +} + +export interface CreatedWorktree extends WorktreeInfo { + /** The main tree had uncommitted changes (tracked or untracked), which the worktree does not have. */ + readonly dirty: boolean; +} + +export interface WorktreeFileChange { + /** Repository-relative, forward slashes. */ + readonly path: string; + readonly status: WorktreeChangeStatus; + /** Changed by a commit on the branch. */ + readonly committed: boolean; + /** Changed in the worktree and not committed yet. */ + readonly uncommitted: boolean; +} + +export interface WorktreeStatus { + readonly exists: boolean; + readonly files: readonly WorktreeFileChange[]; + /** Commits on the branch since baseCommit. */ + readonly ahead: number; + /** Commits on the main tree's HEAD that the branch does not have. */ + readonly behind: number; + readonly hasUncommitted: boolean; +} + +export interface CommitResult { + readonly commit: string; + readonly fileCount: number; + /** The fallback identity was used because the repository has none configured. */ + readonly fallbackIdentity: boolean; +} + +export type MergeStrategy = 'merge' | 'squash'; + +export interface MergeOptions { + readonly strategy: MergeStrategy; + /** Commit message; defaults to git's own for a merge, and a summary line for a squash. */ + readonly message?: string | undefined; +} + +export interface MergeResult { + readonly strategy: MergeStrategy; + /** The branch merged into. */ + readonly into: string; + /** The new HEAD of the main tree; null when there was nothing to merge. */ + readonly commit: string | null; + readonly nothingToMerge: boolean; +} + +export interface RemoveOptions { + /** Also delete the branch (`branch -D`: a squashed branch never counts as merged). */ + readonly deleteBranch: boolean; +} + +export interface RemoveResult { + readonly removedWorktree: boolean; + readonly deletedBranch: boolean; +} + +export interface ListedWorktree { + readonly info: WorktreeInfo; + /** HEAD of the worktree. */ + readonly head: string | null; + readonly locked: boolean; + /** Git reports the folder as gone; `removeWorktree` cleans it up. */ + readonly prunable: boolean; + /** The sidecar was missing: label, cwd and baseCommit were reconstructed. */ + readonly recovered: boolean; +} + +/** Hooks and checks can take time on the final merge. */ +const MERGE_TIMEOUT_MS = 120_000; +const FALLBACK_NAME = 'Code-XR agent'; +const FALLBACK_EMAIL = 'agent@code-xr.invalid'; +const EMPTY_HOOKS_DIR = '.no-hooks'; +const SIDECAR_VERSION = 1; + +interface RepoContext { + readonly repoRoot: string; + readonly commonDir: string; + /** The project folder relative to repoRoot, OS separators; '' at the top. */ + readonly subdir: string; +} + +// --------------------------------------------------------------------------- +// Public API + +export async function canUseWorktrees(projectRoot: string): Promise { + try { + const inside = await git(projectRoot, ['rev-parse', '--is-inside-work-tree'], { okExitCodes: [128] }); + if (inside.exitCode === 128) { + return { ok: false, reason: 'not-a-repo', message: 'This folder is not inside a git repository.' }; + } + if (inside.stdout.trim() !== 'true') { + return { ok: false, reason: 'bare-repo', message: 'This folder is not a git work tree (a bare repository or a .git folder).' }; + } + const head = await git(projectRoot, ['rev-parse', '--verify', '-q', 'HEAD^{commit}'], { okExitCodes: [1] }); + if (head.exitCode !== 0 || !head.stdout.trim()) { + return { ok: false, reason: 'no-commits', message: 'The repository has no commit yet; an agent worktree starts from the current commit.' }; + } + const context = await repoContext(projectRoot); + return { ok: true, repoRoot: context.repoRoot, head: head.stdout.trim() }; + } catch (error) { + if (error instanceof GitNotFoundError) { + return { ok: false, reason: 'git-missing', message: 'Agent worktrees need git, and git was not found on PATH.' }; + } + throw error; + } +} + +export async function createWorktree(options: CreateWorktreeOptions): Promise { + const { projectRoot, sessionId, label } = options; + if (!isSafeSessionId(sessionId)) { + throw new WorktreeError('invalid-argument', `"${sessionId}" cannot name a worktree folder.`); + } + const availability = await canUseWorktrees(projectRoot); + if (!availability.ok) { + throw new WorktreeError(availability.reason, availability.message); + } + const context = await repoContext(projectRoot); + const storageDir = path.resolve(options.storageDir); + if (isInside(storageDir, context.repoRoot)) { + throw new WorktreeError('storage-inside-project', 'Agent worktrees must be stored outside the repository.'); + } + return withRepoLock(context.commonDir, async () => { + const repoDir = path.join(storageDir, repoHash(context.commonDir)); + await fs.mkdir(repoDir, { recursive: true }); + // Registered by its real path, so later comparisons with git's output hold (macOS /var -> /private/var). + const realRepoDir = await fs.realpath(repoDir); + const worktreePath = path.join(realRepoDir, sessionId); + if (await exists(worktreePath)) { + throw new WorktreeError('already-exists', `A worktree for this chat already exists at ${worktreePath}.`); + } + const baseCommit = (await git(context.repoRoot, ['rev-parse', '--verify', 'HEAD^{commit}'])).stdout.trim(); + const dirty = (await mainTreeStatus(context.repoRoot)).length > 0; + const branch = await freshBranchName(context.repoRoot, label); + const hooks = await emptyHooksDir(realRepoDir); + try { + await git(context.repoRoot, ['worktree', 'add', '-b', branch, '--', worktreePath, baseCommit], { + config: [`core.hooksPath=${hooks}`], + timeoutMs: MERGE_TIMEOUT_MS, + }); + } catch (error) { + // `worktree add -b` can leave the branch behind when the checkout fails. + await git(context.repoRoot, ['branch', '-D', branch], { okExitCodes: [1] }).catch(() => undefined); + await git(context.repoRoot, ['worktree', 'prune']).catch(() => undefined); + throw error; + } + const info: WorktreeInfo = { + sessionId, + label, + repoRoot: context.repoRoot, + path: worktreePath, + cwd: context.subdir ? path.join(worktreePath, context.subdir) : worktreePath, + branch, + baseCommit, + createdAt: Date.now(), + }; + await writeSidecar(info); + return { ...info, dirty }; + }); +} + +export async function worktreeStatus(info: WorktreeInfo): Promise { + const behind = await countCommits(info.repoRoot, `${info.branch}..HEAD`).catch(() => 0); + if (!(await isWorktreeFolder(info.path))) { + const ahead = await countCommits(info.repoRoot, `${info.baseCommit}..${info.branch}`).catch(() => 0); + return { exists: false, files: [], ahead, behind, hasUncommitted: false }; + } + const committed = parseNameStatus((await git(info.path, ['diff', '--name-status', '-z', '--no-renames', info.baseCommit, 'HEAD', '--'])).stdout); + const net = parseNameStatus((await git(info.path, ['diff', '--name-status', '-z', '--no-renames', info.baseCommit, '--'])).stdout); + const untracked = parseNulList((await git(info.path, ['ls-files', '--others', '--exclude-standard', '-z'])).stdout); + for (const file of untracked) { + net.set(file, 'added'); + } + const uncommitted = new Set(parsePorcelain((await git(info.path, statusArgs())).stdout).map((entry) => entry.path)); + const paths = new Set([...net.keys(), ...committed.keys()]); + const files = [...paths].sort().map((file): WorktreeFileChange => ({ + path: file, + status: net.get(file) ?? committed.get(file) ?? 'modified', + committed: committed.has(file), + uncommitted: uncommitted.has(file), + })); + const ahead = await countCommits(info.path, `${info.baseCommit}..HEAD`); + return { exists: true, files, ahead, behind, hasUncommitted: uncommitted.size > 0 }; +} + +/** Stages everything in the worktree and commits it; null when there is nothing to commit. */ +export async function commitAll(info: WorktreeInfo, message: string): Promise { + if (!message.trim() || message.includes('\0')) { + throw new WorktreeError('invalid-argument', 'A commit needs a message.'); + } + await assertWorktreeOnBranch(info); + await git(info.path, ['add', '-A', '--', '.']); + const staged = parseNulList((await git(info.path, ['diff', '--cached', '--name-only', '-z', '--no-renames'])).stdout); + if (staged.length === 0) { + return null; + } + const name = await configValue(info.path, 'user.name'); + const email = await configValue(info.path, 'user.email'); + const fallbackIdentity = !name || !email; + const config = [`core.hooksPath=${await emptyHooksDir(path.dirname(info.path))}`, 'commit.gpgsign=false']; + if (fallbackIdentity) { + config.push(`user.name=${FALLBACK_NAME}`, `user.email=${FALLBACK_EMAIL}`); + } + await git(info.path, ['commit', '--no-verify', '-q', '-m', message], { config, timeoutMs: MERGE_TIMEOUT_MS }); + const commit = (await git(info.path, ['rev-parse', 'HEAD'])).stdout.trim(); + return { commit, fileCount: staged.length, fallbackIdentity }; +} + +export async function mergeIntoCurrent(info: WorktreeInfo, options: MergeOptions): Promise { + const { strategy } = options; + if (strategy !== 'merge' && strategy !== 'squash') { + throw new WorktreeError('invalid-argument', `Unknown merge strategy "${String(strategy)}".`); + } + if (!isAgentBranch(info.branch)) { + throw new WorktreeError('not-ours', `${info.branch} is not an agent branch.`); + } + const context = await repoContext(info.repoRoot); + return withRepoLock(context.commonDir, async () => { + const root = context.repoRoot; + const branchRef = `refs/heads/${info.branch}`; + if ((await git(root, ['rev-parse', '--verify', '-q', branchRef], { okExitCodes: [1] })).exitCode !== 0) { + throw new WorktreeError('branch-missing', `The branch ${info.branch} no longer exists.`); + } + if (await isWorktreeFolder(info.path)) { + const pending = parsePorcelain((await git(info.path, statusArgs())).stdout).map((entry) => entry.path); + if (pending.length > 0) { + throw new WorktreeError('uncommitted-in-worktree', 'The agent\'s worktree has uncommitted changes. Commit or discard them before merging.', pending); + } + } + const current = await git(root, ['symbolic-ref', '-q', '--short', 'HEAD'], { okExitCodes: [1] }); + const into = current.stdout.trim(); + if (current.exitCode !== 0 || !into) { + throw new WorktreeError('detached-head', 'The project is not on a branch (detached HEAD). Check out a branch before merging.'); + } + if (into === info.branch) { + throw new WorktreeError('invalid-argument', 'The project already has the agent branch checked out.'); + } + await assertNoOperationInProgress(root); + + const ahead = await countCommits(root, `HEAD..${branchRef}`); + if (ahead === 0) { + return { strategy, into, commit: null, nothingToMerge: true }; + } + const branchFiles = new Set(parseNulList((await git(root, ['diff', '--name-only', '-z', '--no-renames', `HEAD...${branchRef}`, '--'])).stdout)); + const mainStatus = await mainTreeStatus(root); + const staged = mainStatus.filter((entry) => entry.staged).map((entry) => entry.path); + if (staged.length > 0) { + throw new WorktreeError('staged-changes', 'The project has staged changes. Commit or unstage them before merging an agent\'s work.', staged); + } + const overlap = mainStatus.map((entry) => entry.path).filter((file) => branchFiles.has(file)); + if (overlap.length > 0) { + throw new WorktreeError( + 'dirty-overlap', + 'The project has uncommitted changes to files the agent also changed. Commit, stash or discard them before merging.', + overlap, + ); + } + const predicted = await predictConflicts(root, branchRef); + if (predicted && predicted.length > 0) { + throw new WorktreeError('conflicts', `Merging ${info.branch} into ${into} would conflict. Nothing was changed.`, predicted); + } + + if (strategy === 'merge') { + const message = options.message?.trim() || `Merge branch '${info.branch}'`; + try { + await git(root, ['merge', '--no-ff', '--no-edit', '-m', message, branchRef], { timeoutMs: MERGE_TIMEOUT_MS }); + } catch (error) { + const conflicted = await conflictedFiles(root); + await git(root, ['merge', '--abort'], { okExitCodes: [128] }).catch(() => git(root, ['reset', '--merge'])); + throw mergeFailure(error, conflicted, info.branch, into); + } + } else { + const message = options.message?.trim() || `Squashed changes from ${info.branch}`; + try { + await git(root, ['merge', '--squash', branchRef], { timeoutMs: MERGE_TIMEOUT_MS }); + } catch (error) { + const conflicted = await conflictedFiles(root); + await git(root, ['reset', '--merge']); + throw mergeFailure(error, conflicted, info.branch, into); + } + try { + await git(root, ['commit', '-q', '-m', message], { timeoutMs: MERGE_TIMEOUT_MS }); + } catch (error) { + await git(root, ['reset', '--merge']); + throw mergeFailure(error, [], info.branch, into); + } + } + const commit = (await git(root, ['rev-parse', 'HEAD'])).stdout.trim(); + return { strategy, into, commit, nothingToMerge: false }; + }); +} + +export async function removeWorktree(info: WorktreeInfo, options: RemoveOptions): Promise { + if (!isAgentBranch(info.branch)) { + throw new WorktreeError('not-ours', `${info.branch} is not an agent branch; it is never deleted.`); + } + const context = await repoContext(info.repoRoot); + return withRepoLock(context.commonDir, async () => { + const root = context.repoRoot; + const entries = await worktreeEntries(root); + const target = await comparablePath(info.path); + let registered = null; + for (const entry of entries) { + if (await comparablePath(entry.path) === target) { + registered = entry; + } + } + if (registered && registered.branch !== null && !isAgentBranch(registered.branch)) { + throw new WorktreeError('not-ours', `The worktree at ${info.path} is on ${registered.branch}, not on an agent branch.`); + } + let removedWorktree = false; + // Only a folder git itself registered as a worktree is ever deleted. + if (registered && !registered.prunable) { + await git(root, ['worktree', 'remove', '--force', '--', registered.path], { timeoutMs: MERGE_TIMEOUT_MS }); + removedWorktree = true; + } + await git(root, ['worktree', 'prune']); + if (registered && registered.prunable) { + removedWorktree = true; + } + let deletedBranch = false; + if (options.deleteBranch) { + const branchRef = `refs/heads/${info.branch}`; + if ((await git(root, ['rev-parse', '--verify', '-q', branchRef], { okExitCodes: [1] })).exitCode === 0) { + await git(root, ['branch', '-D', info.branch]); + deletedBranch = true; + } + } + await fs.rm(sidecarPath(info.path), { force: true }); + return { removedWorktree, deletedBranch }; + }); +} + +/** The agent worktrees of the repository `projectRoot` belongs to (branch prefix `codexr/agent/`). */ +export async function listWorktrees(projectRoot: string): Promise { + const context = await repoContext(projectRoot); + const listed: ListedWorktree[] = []; + for (const entry of await worktreeEntries(context.repoRoot)) { + if (entry.bare || entry.branch === null || !isAgentBranch(entry.branch)) { + continue; + } + const worktreePath = path.resolve(entry.path); + const sidecar = await readSidecar(worktreePath, entry.branch); + if (sidecar) { + listed.push({ info: { ...sidecar, repoRoot: context.repoRoot }, head: entry.head, locked: entry.locked, prunable: entry.prunable, recovered: false }); + continue; + } + const base = await git(context.repoRoot, ['merge-base', 'HEAD', `refs/heads/${entry.branch}`], { okExitCodes: [1] }); + const info: WorktreeInfo = { + sessionId: path.basename(worktreePath), + label: entry.branch.slice(entry.branch.lastIndexOf('/') + 1), + repoRoot: context.repoRoot, + path: worktreePath, + cwd: context.subdir ? path.join(worktreePath, context.subdir) : worktreePath, + branch: entry.branch, + baseCommit: base.stdout.trim() || (entry.head ?? ''), + createdAt: 0, + }; + listed.push({ info, head: entry.head, locked: entry.locked, prunable: entry.prunable, recovered: true }); + } + return listed; +} + +// --------------------------------------------------------------------------- +// Internals + +function git(cwd: string, args: readonly string[], options: WorktreeGitOptions = {}): Promise { + return runWorktreeGit(cwd, args, options); +} + +const repoLocks = new Map>(); + +/** Runs `task` after every earlier task on the same repository has settled. */ +function withRepoLock(key: string, task: () => Promise): Promise { + const previous = repoLocks.get(key) ?? Promise.resolve(); + const next = previous.then(task, task); + const settled = next.then(() => undefined, () => undefined); + repoLocks.set(key, settled); + void settled.then(() => { + if (repoLocks.get(key) === settled) { + repoLocks.delete(key); + } + }); + return next; +} + +async function repoContext(projectRoot: string): Promise { + let stdout: string; + try { + ({ stdout } = await git(projectRoot, ['rev-parse', '--show-toplevel', '--path-format=absolute', '--git-common-dir'])); + } catch (error) { + if (error instanceof GitCommandError) { + throw new WorktreeError('not-a-repo', 'This folder is not inside a git work tree.'); + } + throw error; + } + const [top, common] = stdout.replace(/\r/g, '').split('\n'); + if (!top || !common) { + throw new WorktreeError('not-a-repo', 'This folder is not inside a git work tree.'); + } + const repoRoot = path.resolve(top); + const realProject = await fs.realpath(projectRoot).catch(() => path.resolve(projectRoot)); + const realRepo = await fs.realpath(repoRoot).catch(() => repoRoot); + const subdir = isInside(realProject, realRepo) ? path.relative(realRepo, realProject) : ''; + return { repoRoot, commonDir: await fs.realpath(path.resolve(common)).catch(() => path.resolve(common)), subdir }; +} + +function statusArgs(): string[] { + return ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames']; +} + +async function mainTreeStatus(root: string): Promise> { + return parsePorcelain((await git(root, statusArgs())).stdout); +} + +async function freshBranchName(root: string, label: string): Promise { + for (let attempt = 0; attempt < 8; attempt += 1) { + const branch = agentBranchName(label); + const exists = await git(root, ['rev-parse', '--verify', '-q', `refs/heads/${branch}`], { okExitCodes: [1] }); + if (exists.exitCode !== 0) { + return branch; + } + } + throw new WorktreeError('already-exists', 'Could not find a free agent branch name.'); +} + +async function emptyHooksDir(parent: string): Promise { + // Session ids start with a letter or digit, so this name never collides with a worktree. + const dir = path.join(parent, EMPTY_HOOKS_DIR); + await fs.mkdir(dir, { recursive: true }); + return dir; +} + +async function countCommits(cwd: string, range: string): Promise { + const { stdout } = await git(cwd, ['rev-list', '--count', range, '--']); + return Number.parseInt(stdout.trim(), 10) || 0; +} + +async function configValue(cwd: string, key: string): Promise { + const { stdout } = await git(cwd, ['config', '--get', key], { okExitCodes: [1] }); + return stdout.trim(); +} + +async function assertWorktreeOnBranch(info: WorktreeInfo): Promise { + if (!(await isWorktreeFolder(info.path))) { + throw new WorktreeError('worktree-missing', `The agent worktree at ${info.path} no longer exists.`); + } + const current = await git(info.path, ['symbolic-ref', '-q', '--short', 'HEAD'], { okExitCodes: [1] }); + if (current.stdout.trim() !== info.branch) { + throw new WorktreeError('branch-changed', `The agent worktree is no longer on ${info.branch}; nothing was committed.`); + } +} + +async function assertNoOperationInProgress(root: string): Promise { + for (const ref of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD']) { + if ((await git(root, ['rev-parse', '--verify', '-q', ref], { okExitCodes: [1] })).exitCode === 0) { + throw new WorktreeError('operation-in-progress', 'The project has a merge, cherry-pick or revert in progress. Finish or abort it first.'); + } + } + for (const dir of ['rebase-merge', 'rebase-apply']) { + const gitPath = (await git(root, ['rev-parse', '--git-path', dir])).stdout.trim(); + if (gitPath && await exists(path.resolve(root, gitPath))) { + throw new WorktreeError('operation-in-progress', 'The project has a rebase in progress. Finish or abort it first.'); + } + } +} + +/** + * Conflicted paths of merging `branchRef` into HEAD, computed without touching + * the index or the work tree (`merge-tree --write-tree`, git 2.38+); null when + * this git cannot tell, and the real merge is then the check. + */ +async function predictConflicts(root: string, branchRef: string): Promise { + try { + const result = await git(root, ['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', 'HEAD', branchRef], { okExitCodes: [1] }); + if (result.exitCode === 0) { + return []; + } + const fields = result.stdout.split('\0'); + const files: string[] = []; + for (const field of fields.slice(1)) { + if (field === '') { + break; + } + files.push(field); + } + return [...new Set(files)]; + } catch (error) { + if (error instanceof GitCommandError) { + return null; + } + throw error; + } +} + +async function conflictedFiles(root: string): Promise { + const result = await git(root, ['diff', '--name-only', '-z', '--diff-filter=U'], { okExitCodes: [1, 128] }).catch(() => null); + return result ? [...new Set(parseNulList(result.stdout))] : []; +} + +function mergeFailure(error: unknown, conflicted: readonly string[], branch: string, into: string): WorktreeError { + if (conflicted.length > 0) { + return new WorktreeError('conflicts', `Merging ${branch} into ${into} conflicted; the merge was aborted.`, conflicted); + } + const detail = error instanceof Error ? error.message : String(error); + return new WorktreeError('merge-failed', `Merging ${branch} into ${into} failed and was undone: ${detail}`); +} + +async function worktreeEntries(root: string): Promise> { + try { + return parseWorktreeList((await git(root, ['worktree', 'list', '--porcelain', '-z'])).stdout); + } catch (error) { + if (!(error instanceof GitCommandError)) { + throw error; + } + // git before 2.36 has no -z: the same records, newline-separated. + const { stdout } = await git(root, ['worktree', 'list', '--porcelain']); + return parseWorktreeList(stdout.replace(/\r/g, '').replace(/\n/g, '\0')); + } +} + +/** A worktree folder: it exists and has the `.git` file `worktree add` writes. */ +async function isWorktreeFolder(worktreePath: string): Promise { + return exists(path.join(worktreePath, '.git')); +} + +async function exists(target: string): Promise { + return fs.access(target).then(() => true, () => false); +} + +function isInside(child: string, parent: string): boolean { + const relative = path.relative(parent, child); + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); +} + +/** A path in a form two spellings of one folder compare equal in (real path, case-folded where the file system is). */ +async function comparablePath(target: string): Promise { + const resolved = await fs.realpath(path.resolve(target)).catch(() => path.resolve(target)); + return process.platform === 'win32' || process.platform === 'darwin' ? resolved.toLowerCase() : resolved; +} + +function sidecarPath(worktreePath: string): string { + return `${path.resolve(worktreePath)}.json`; +} + +async function writeSidecar(info: WorktreeInfo): Promise { + const target = sidecarPath(info.path); + const temporary = `${target}.tmp`; + const { sessionId, label, path: worktreePath, cwd, branch, baseCommit, createdAt } = info; + await fs.writeFile(temporary, JSON.stringify({ version: SIDECAR_VERSION, sessionId, label, path: worktreePath, cwd, branch, baseCommit, createdAt }, null, 2)); + await fs.rename(temporary, target); +} + +async function readSidecar(worktreePath: string, branch: string): Promise | null> { + try { + const raw = JSON.parse(await fs.readFile(sidecarPath(worktreePath), 'utf8')) as Record; + const { sessionId, label, cwd, baseCommit, createdAt } = raw; + if (raw['version'] !== SIDECAR_VERSION || raw['branch'] !== branch || typeof sessionId !== 'string' || typeof label !== 'string' + || typeof cwd !== 'string' || typeof baseCommit !== 'string' || typeof createdAt !== 'number') { + return null; + } + return { sessionId, label, path: worktreePath, cwd, branch, baseCommit, createdAt }; + } catch { + return null; + } +} diff --git a/apps/ide/src/main/worktrees/worktreeModel.ts b/apps/ide/src/main/worktrees/worktreeModel.ts new file mode 100644 index 000000000..6a0e28d6f --- /dev/null +++ b/apps/ide/src/main/worktrees/worktreeModel.ts @@ -0,0 +1,153 @@ +import { createHash, randomBytes } from 'node:crypto'; + +/** + * Pure helpers of the agent worktrees (AF12, #277): branch and folder naming, + * and the parsers of the git outputs worktreeManager.ts reads. No I/O, so it + * is unit-tested without git. + */ + +/** Every branch the IDE creates for an agent starts with this; nothing else is ever listed, merged or deleted. */ +export const AGENT_BRANCH_PREFIX = 'codexr/agent/'; + +const MAX_SLUG_LENGTH = 32; + +/** `label` reduced to lowercase ASCII words joined by `-`, at most 32 characters; `agent` when nothing is left. */ +export function slugify(label: string): string { + const slug = label + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, MAX_SLUG_LENGTH) + .replace(/-+$/g, ''); + return slug || 'agent'; +} + +/** Six hex characters: unique enough among one person's parallel agents, short enough to read. */ +export function shortId(): string { + return randomBytes(3).toString('hex'); +} + +export function agentBranchName(label: string, id: string = shortId()): string { + return `${AGENT_BRANCH_PREFIX}${slugify(label)}-${id}`; +} + +export function isAgentBranch(branch: string): boolean { + return branch.startsWith(AGENT_BRANCH_PREFIX) && branch.length > AGENT_BRANCH_PREFIX.length; +} + +/** + * The session id becomes a folder name and the worktree's name inside + * `.git/worktrees/`, so it must be one safe path segment on every platform. + */ +export function isSafeSessionId(sessionId: string): boolean { + return /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sessionId) && !sessionId.endsWith('.') && !sessionId.includes('..'); +} + +/** + * Names the folder of one repository's worktrees: a hash of its common git + * directory, so every worktree of one repository (and a project opened from a + * sub-folder) lands in the same place. Case-folded where the file system is. + */ +export function repoHash(commonGitDir: string, platform: NodeJS.Platform = process.platform): string { + const normalized = platform === 'win32' || platform === 'darwin' ? commonGitDir.toLowerCase() : commonGitDir; + return createHash('sha256').update(normalized).digest('hex').slice(0, 16); +} + +/** One entry of `git worktree list --porcelain -z`. */ +export interface WorktreeListEntry { + readonly path: string; + readonly head: string | null; + /** Short branch name (`refs/heads/` removed); null when detached or bare. */ + readonly branch: string | null; + readonly bare: boolean; + readonly locked: boolean; + readonly prunable: boolean; +} + +export function parseWorktreeList(stdout: string): WorktreeListEntry[] { + const entries: WorktreeListEntry[] = []; + let current: { path: string; head: string | null; branch: string | null; bare: boolean; locked: boolean; prunable: boolean } | null = null; + for (const field of stdout.split('\0')) { + if (field === '') { + if (current) { + entries.push(current); + } + current = null; + continue; + } + const space = field.indexOf(' '); + const key = space === -1 ? field : field.slice(0, space); + const value = space === -1 ? '' : field.slice(space + 1); + if (key === 'worktree') { + if (current) { + entries.push(current); + } + current = { path: value, head: null, branch: null, bare: false, locked: false, prunable: false }; + continue; + } + if (!current) { + continue; + } + if (key === 'HEAD') { + current.head = value; + } else if (key === 'branch') { + current.branch = value.startsWith('refs/heads/') ? value.slice('refs/heads/'.length) : value; + } else if (key === 'bare') { + current.bare = true; + } else if (key === 'locked') { + current.locked = true; + } else if (key === 'prunable') { + current.prunable = true; + } + } + if (current) { + entries.push(current); + } + return entries; +} + +export type WorktreeChangeStatus = 'added' | 'modified' | 'deleted'; + +/** `git diff --name-status -z --no-renames`: status letter, NUL, path, NUL, repeated. */ +export function parseNameStatus(stdout: string): Map { + const changes = new Map(); + const fields = stdout.split('\0'); + for (let i = 0; i + 1 < fields.length; i += 2) { + const letter = fields[i] ?? ''; + const file = fields[i + 1] ?? ''; + if (!file) { + continue; + } + changes.set(file, letter.startsWith('A') ? 'added' : letter.startsWith('D') ? 'deleted' : 'modified'); + } + return changes; +} + +/** One entry of `git status --porcelain=v1 -z --no-renames`. */ +export interface PorcelainEntry { + readonly path: string; + /** Something is recorded in the index (relative to HEAD). */ + readonly staged: boolean; + readonly untracked: boolean; +} + +export function parsePorcelain(stdout: string): PorcelainEntry[] { + const entries: PorcelainEntry[] = []; + for (const field of stdout.split('\0')) { + if (field.length < 4) { + continue; + } + const x = field[0] ?? ' '; + const y = field[1] ?? ' '; + const untracked = x === '?' && y === '?'; + entries.push({ path: field.slice(3), staged: !untracked && x !== ' ' && x !== '!', untracked }); + } + return entries; +} + +/** NUL-separated paths (`--name-only -z`, `ls-files -z`). */ +export function parseNulList(stdout: string): string[] { + return stdout.split('\0').filter((entry) => entry !== ''); +} diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index eb2ddcd94..dbf2d61c2 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -6,6 +6,7 @@ import type { FunctionMetricsSnapshot } from '../shared/problems.ts'; import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AutoStartMode, type FileAnalysisKind, type ProjectAnalysisKind, 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 { 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 PromptAttachment } 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'; @@ -70,6 +71,42 @@ const api: CodeXRApi = Object.freeze({ savePrices: (prices: readonly ModelPrice[]) => ipcRenderer.invoke(AGENT_IPC_CHANNELS.agentsSavePrices, prices), saveBudget: (budget: BudgetSettings) => ipcRenderer.invoke(AGENT_IPC_CHANNELS.agentsSaveBudget, budget), }), + // AF1: chats with coding agents over ACP; main validates every argument and runs the agents. + agentSessions: Object.freeze({ + listAgents: () => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.listAgents), + probeAgent: (ref: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.probeAgent, ref), + saveCustomAgent: (input: Omit, id?: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.saveCustomAgent, input, id), + removeCustomAgent: (id: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.removeCustomAgent, id), + login: (ref: string, methodId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.login, ref, methodId), + listProjects: () => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.listProjects), + get: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.get, sessionId), + create: (agentRef: string, options?: { readonly worktree?: boolean }) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.create, agentRef, { worktree: options?.worktree === true }), + prompt: (sessionId: string, text: string, attachments?: readonly PromptAttachment[]) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.prompt, sessionId, text, attachments ?? []), + cancel: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.cancel, sessionId), + respondPermission: (sessionId: string, requestId: string, optionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.respondPermission, sessionId, requestId, optionId), + setMode: (sessionId: string, modeId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.setMode, sessionId, modeId), + setConfigOption: (sessionId: string, optionId: string, valueId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.setConfigOption, sessionId, optionId, valueId), + rename: (sessionId: string, title: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.rename, sessionId, title), + remove: (sessionId: string, options?: { readonly removeWorktree?: boolean }) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.remove, sessionId, { removeWorktree: options?.removeWorktree === true }), + markRead: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.markRead, sessionId), + // AF5/AF6: review and checkpoints; paths are workspace-relative and checked in main. + changes: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.changes, sessionId), + changeDiff: (sessionId: string, path: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.changeDiff, sessionId, path), + keepChanges: (sessionId: string, paths: readonly string[] | 'all') => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.keepChanges, sessionId, paths), + undoChanges: (sessionId: string, paths: readonly string[] | 'all') => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.undoChanges, sessionId, paths), + previewRestore: (sessionId: string, checkpointId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.previewRestore, sessionId, checkpointId), + restoreCheckpoint: (sessionId: string, checkpointId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.restoreCheckpoint, sessionId, checkpointId), + // AF12: a chat's worktree is named by the chat id only; main looks up its path. + worktreeAvailability: () => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.worktreeAvailability), + worktreeStatus: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.worktreeStatus, sessionId), + worktreeCommit: (sessionId: string, message: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.worktreeCommit, sessionId, message), + worktreeMerge: (sessionId: string, strategy: 'merge' | 'squash') => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.worktreeMerge, sessionId, strategy), + worktreeDiscard: (sessionId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.worktreeDiscard, sessionId), + describeInstall: (presetId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.describeInstall, presetId), + install: (presetId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.install, presetId), + uninstall: (presetId: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.uninstall, presetId), + onMessage: (listener: (message: AgentSessionMessage) => void) => subscribe(AGENT_SESSION_EVENTS.message, listener), + }), // #17: only workspace-relative paths and branch names cross; main validates each one. git: Object.freeze({ status: () => ipcRenderer.invoke(GIT_IPC_CHANNELS.gitStatus), diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css new file mode 100644 index 000000000..14d1b12da --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -0,0 +1,322 @@ +/* The agent-first workbench (epic #265): the Agent layout mode (AF4), the + chats column (AF7), the coding chat (AF3) and the live analysis dock (AF8). + Colours come from the workbench's variables, so light and dark follow. */ + +/* ---- Agent layout (AF4) -------------------------------------------------- */ +.af-dock { display: none; } +.workbench.mode-agent:not(.has-scene):not(.zen) { + grid-template-columns: var(--activity-col) var(--side-col) minmax(0, 1fr) var(--dock-col, min(40%, 520px)); + grid-template-areas: + 'activity side editor scene' + 'activity side panel scene' + 'status status status status'; +} +.workbench.mode-agent:not(.has-scene):not(.zen) .af-dock { + grid-area: scene; + display: flex; + flex-direction: column; + min-width: 0; + 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; } +@media (max-width: 1100px) { + .workbench.mode-agent:not(.has-scene) { --dock-col: 0px; } + .workbench.mode-agent:not(.has-scene) .af-dock { display: none; } +} +.af-dock-head { display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--line); font-weight: 600; } +.af-dock-body { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 24px; text-align: center; } +.af-dock-body p { margin: 0; max-width: 340px; line-height: 1.5; } +.af-dock-body .primary-button { width: auto; margin: 0; } +.af-dock-art { width: 72px; height: 72px; opacity: 0.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: 12px; 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); } + +/* ---- Chats column (AF7) -------------------------------------------------- */ +.af-sessions { display: flex; flex-direction: column; gap: 8px; padding: 10px 0 12px; min-height: 100%; } +.af-mode-switch { display: flex; margin: 0 12px; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; } +.af-mode-button { flex: 1; padding: 4px 8px; border: 0; background: none; color: var(--muted); font: inherit; font-size: 12px; cursor: pointer; } +.af-mode-button + .af-mode-button { border-left: 1px solid var(--line); } +.af-mode-button.is-active { background: var(--hover); color: var(--fg); font-weight: 600; } +.af-mode-button:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.af-new-row { display: flex; gap: 6px; margin: 0 12px; } +.af-new-chat { display: inline-flex; align-items: center; justify-content: center; gap: 6px; width: auto; margin: 0; flex: 0 0 auto; white-space: nowrap; padding-inline: 12px; } +.af-new-chat svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; } +.af-new-agent { flex: 1 1 0; min-width: 0; } +.af-search { margin: 0 12px; width: calc(100% - 24px); } +.af-section-title { display: flex; align-items: center; justify-content: space-between; margin: 6px 12px 0; font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); cursor: default; } +.af-agents > summary { list-style: none; cursor: pointer; } +.af-agents > summary::-webkit-details-marker { display: none; } +.af-projects { display: flex; flex-direction: column; gap: 2px; } +.af-project-head { display: flex; align-items: center; gap: 6px; width: 100%; padding: 4px 12px; border: 0; background: none; color: var(--fg); font: inherit; font-weight: 600; text-align: left; cursor: pointer; } +.af-project-head:hover { background: var(--hover); } +.af-project-head svg { width: 14px; height: 14px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linejoin: round; } +.af-project-head[aria-expanded='true'] .af-project-chevron { transform: rotate(90deg); } +.af-project-head.is-current .af-project-icon { stroke: var(--accent); } +.af-project-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-project-count { font-weight: 400; font-size: 11px; } +.af-project-open { margin: 0 0 2px 32px; font-size: 12px; } +.af-session-list { list-style: none; margin: 0; padding: 0; } +.af-session { display: flex; align-items: center; gap: 8px; min-height: 40px; padding: 4px 8px 4px 28px; cursor: pointer; } +.af-session:hover { background: var(--hover); } +.af-session.is-active { background: var(--hover); box-shadow: inset 2px 0 var(--accent); } +.af-session:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.af-session-main { display: flex; flex-direction: column; flex: 1; min-width: 0; } +.af-session-title, .af-session-sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-session.is-unread .af-session-title { font-weight: 600; } +.af-session-sub { font-size: 11px; } +.af-session-actions { display: flex; visibility: hidden; } +.af-session:hover .af-session-actions, .af-session:focus-within .af-session-actions { visibility: visible; } +.af-rename { flex: 1; min-width: 0; } +.af-confirm { display: flex; align-items: center; gap: 6px; padding: 6px 8px 6px 28px; font-size: 12px; } +.af-confirm span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--line); } +.af-dot[data-status='running'] { background: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent); animation: af-pulse 1.4s ease-in-out infinite; } +.af-dot[data-status='awaiting'] { background: var(--warn); } +.af-dot[data-status='error'] { background: var(--crit); } +.af-dot[data-status='idle'][data-unread='true'] { background: var(--fg); } +@keyframes af-pulse { 50% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--accent) 10%, transparent); } } +@media (prefers-reduced-motion: reduce) { .af-dot[data-status='running'] { animation: none; } } +.af-badge { flex: none; padding: 0 6px; border: 1px solid var(--line); border-radius: 10px; font-size: 10px; line-height: 16px; color: var(--muted); white-space: nowrap; } +.af-badge[data-availability='ready'] { color: var(--accent); border-color: var(--accent); } +.af-badge[data-availability='needs-login'] { color: var(--warn); border-color: var(--warn); } +.af-badge[data-availability='error'] { color: var(--crit); border-color: var(--crit); } +.af-pending { color: var(--warn); border-color: var(--warn); } +.af-agent-list { list-style: none; margin: 4px 0 0; padding: 0; } +.af-agent { display: grid; gap: 2px; padding: 6px 12px; border-bottom: 1px solid var(--line); } +.af-agent-main { display: flex; align-items: center; gap: 8px; } +.af-agent-name { flex: 1; min-width: 0; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-agent-detail { margin: 0; font-size: 12px; overflow-wrap: anywhere; } +.af-agent-actions { display: flex; flex-wrap: wrap; gap: 4px; } +.af-agent-actions:empty { display: none; } +.af-small-button { padding: 2px 8px; font-size: 12px; } +.af-agents-note { margin: 6px 12px 0; font-size: 11px; line-height: 1.4; } +.secondary-button.is-danger { color: var(--crit); border-color: color-mix(in srgb, var(--crit) 50%, var(--line)); } +.af-link-button { display: inline-flex; align-items: center; gap: 4px; padding: 0; border: 0; background: none; color: var(--accent); font: inherit; cursor: pointer; } +.af-link-button:hover { text-decoration: underline; } +.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); } +.af-chat-heading { flex: 1; min-width: 0; } +.af-chat-title { margin: 0; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-chat-sub { display: flex; align-items: center; gap: 8px; font-size: 12px; } +.af-status-pill { padding: 0 6px; border-radius: 8px; font-size: 11px; 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: 11px; white-space: nowrap; } +.af-usage[hidden] { display: none; } +.af-header-button { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 1px solid var(--warn); border-radius: 4px; background: none; color: var(--fg); font: inherit; font-size: 12px; cursor: pointer; } +.af-header-button[hidden] { display: none; } +.af-header-button svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 1.6; } +.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-empty { margin: auto 0; text-align: center; padding: 24px; } +.af-empty[hidden] { display: none; } +.af-empty h3 { margin: 0 0 8px; font-size: 18px; } +.af-empty p { margin: 0 auto; max-width: 480px; line-height: 1.5; } +.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: 10px; background: var(--hover); } +.af-user-text { margin: 0; white-space: pre-wrap; } +.af-message-actions { display: flex; gap: 8px; margin-top: 4px; font-size: 12px; } +.af-message-actions:empty { display: none; } +.af-message-body > :first-child { margin-top: 0; } +.af-message-body > :last-child { margin-bottom: 0; } +.af-message.is-streaming .af-message-body::after { content: '\258D'; color: var(--accent); } +.af-thought { border-left: 2px solid var(--line); padding-left: 10px; color: var(--muted); font-size: 12px; } +.af-thought summary { cursor: pointer; } +.af-thought-body { white-space: pre-wrap; margin-top: 4px; } +.af-tool { border: 1px solid var(--line); border-radius: 6px; background: var(--panel); min-width: 0; } +.af-tool[data-status='failed'] { border-color: color-mix(in srgb, var(--crit) 60%, var(--line)); } +.af-tool-head { display: flex; align-items: center; gap: 8px; padding: 5px 10px; cursor: pointer; list-style: none; font-size: 12px; min-width: 0; } +.af-tool-head::-webkit-details-marker { display: none; } +.af-tool-head svg { width: 14px; height: 14px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linejoin: round; stroke-linecap: round; } +.af-tool-chevron { color: var(--muted); transition: transform 0.1s; } +.af-tool[open] .af-tool-chevron { transform: rotate(90deg); } +.af-tool-icon { color: var(--accent); } +.af-tool-title { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; } +.af-tool-status { margin-left: auto; flex: none; color: var(--muted); } +.af-tool-status[data-status='in_progress'] { color: var(--accent); } +.af-tool-status[data-status='failed'] { color: var(--crit); } +.af-tool-body { padding: 0 10px 8px; display: grid; gap: 8px; min-width: 0; } +.af-tool-body:empty { display: none; } +.af-tool-text { font-size: 12px; } +.af-tool-raw, .af-terminal-output { margin: 0; padding: 8px; max-height: 280px; overflow: auto; border-radius: 4px; background: var(--editor); font: 12px/1.45 ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; } +.af-terminal-exit { margin: 2px 0 0; font-size: 11px; } +.af-terminal-exit.is-error { color: var(--crit); } +.af-file-link { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0; border: 0; background: none; color: var(--accent); font: 12px ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; cursor: pointer; } +.af-file-link:hover { text-decoration: underline; } +.af-diff-block { border: 1px solid var(--line); border-radius: 4px; overflow: hidden; } +.af-diff-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 3px 8px; border-bottom: 1px solid var(--line); background: var(--editor); } +.af-diff-counts { font-size: 11px; white-space: nowrap; } +.is-add { color: #3fb950; } +.is-remove { color: var(--crit); } +@media (prefers-color-scheme: light) { .is-add { color: #1a7f37; } } +.af-diff { margin: 0; max-height: 360px; overflow: auto; background: var(--editor); font: 12px/1.45 ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; } +.af-diff-line { display: block; padding: 0 8px; white-space: pre; } +.af-diff-line.is-add { background: color-mix(in srgb, #3fb950 14%, transparent); color: var(--fg); } +.af-diff-line.is-remove { background: color-mix(in srgb, var(--crit) 14%, transparent); color: var(--fg); } +.af-diff-line.is-gap { color: var(--muted); background: var(--panel); text-align: center; font-size: 11px; } +.af-permission { display: grid; gap: 8px; padding: 10px 12px; border: 1px solid var(--warn); border-radius: 6px; background: color-mix(in srgb, var(--warn) 8%, var(--panel)); } +.af-permission.is-resolved { border-color: var(--line); background: var(--panel); } +.af-permission-title { margin: 0; font-weight: 600; overflow-wrap: anywhere; } +.af-permission-actions { display: flex; flex-wrap: wrap; gap: 6px; } +.af-permission-actions .primary-button { width: auto; margin: 0; } +.af-notice { margin: 0; padding: 6px 10px; border-radius: 4px; background: var(--panel); font-size: 12px; overflow-wrap: anywhere; } +.af-notice.is-warning { border-left: 3px solid var(--warn); } +.af-notice.is-error { border-left: 3px solid var(--crit); } +.af-turn-end { display: grid; gap: 4px; font-size: 12px; } +.af-turn-end:empty { display: none; } +.af-turn-files { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; padding: 6px 10px; border: 1px dashed var(--line); border-radius: 6px; } +.af-turn-file { display: inline-flex; align-items: center; gap: 6px; min-width: 0; } +.af-stop { margin: 0; } +.af-stop.is-error { color: var(--crit); } +.af-plan { margin: 0 max(16px, calc((100% - 860px) / 2)); border: 1px solid var(--line); border-bottom: 0; border-radius: 6px 6px 0 0; background: var(--panel); font-size: 12px; } +.af-plan[hidden] { display: none; } +.af-plan-summary { padding: 5px 10px; cursor: pointer; font-weight: 600; } +.af-plan-list { list-style: none; margin: 0; padding: 0 10px 8px; display: grid; gap: 2px; max-height: 160px; overflow: auto; } +.af-plan-entry { display: flex; gap: 6px; } +.af-plan-entry[data-status='completed'] { color: var(--muted); text-decoration: line-through; } +.af-plan-entry[data-status='in_progress'] { color: var(--accent); } +.af-plan-mark { flex: none; width: 12px; text-align: center; } +.af-composer { display: grid; gap: 6px; margin: 0 max(16px, calc((100% - 860px) / 2)) 14px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.af-composer:focus-within { border-color: var(--accent); } +.af-input-wrap { position: relative; display: grid; } +.af-input { min-height: 44px; max-height: 40vh; padding: 2px 0; border: 0; background: none; color: var(--fg); font: inherit; line-height: 1.5; resize: none; field-sizing: content; } +.af-input:focus { outline: none; } +.af-queue { margin: 0; font-size: 11px; } +.af-queue[hidden] { display: none; } +.af-composer-row { display: flex; align-items: center; gap: 6px; min-width: 0; flex-wrap: wrap; } +.af-options { display: contents; } +.af-spacer { flex: 1; } +.af-select { max-width: 180px; height: 24px; padding: 0 4px; border: 1px solid var(--line); border-radius: 4px; background: var(--editor); color: var(--fg); font: inherit; font-size: 12px; } +.af-select[hidden] { display: none; } +.af-send { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border: 0; border-radius: 7px; background: var(--accent); color: var(--status-fg); cursor: pointer; } +.af-send:disabled { opacity: 0.4; cursor: default; } +.af-send[data-action='stop'] { background: var(--fg); color: var(--editor); } +.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: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; } + +/* ---- Project instructions (AF11) ---- */ +.af-instr-list { list-style: none; margin: 0; padding: 0 4px; } +.af-instr { display: flex; align-items: center; gap: 8px; padding: 4px 8px; border-radius: 4px; } +.af-instr:hover { background: var(--hover); } +.af-instr-main { display: flex; flex-direction: column; min-width: 0; flex: 1; } +.af-instr-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.af-instr[data-exists="false"] .af-instr-name { opacity: 0.7; } +.af-instr-empty { padding: 4px 8px; } + +/* ---- Installing agents (AF2) ---- */ +.af-agent-setup { display: grid; gap: 6px; } +.af-agent-setup:has(.af-agent-actions:empty):has(.af-install[hidden]) { display: none; } +.af-agent-version { font-size: 11px; white-space: nowrap; } +.af-install { display: grid; gap: 6px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--editor); font-size: 12px; } +.af-install[hidden] { display: none; } +.af-install-title { margin: 0; font-weight: 600; } +.af-install-list { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 10px; margin: 0; } +.af-install-list dt { color: var(--muted); } +.af-install-list dd { margin: 0; overflow-wrap: anywhere; } +.af-install-note { margin: 0; line-height: 1.4; } +.af-install-actions { display: flex; flex-wrap: wrap; gap: 6px; } +.af-install-actions .primary-button { width: auto; margin: 0; } +.af-install-error { margin: 0; color: var(--crit); white-space: pre-wrap; overflow-wrap: anywhere; } + +/* ---- First run (AF13) ---- */ +.af-guide { width: min(640px, 100%); margin: 24px auto 0; padding: 16px 20px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); text-align: left; } +.af-guide-tab { height: 100%; overflow: auto; padding: 24px 16px; background: var(--editor); } +.af-guide-tab .af-guide { margin-top: 0; } +.af-guide-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 12px; } +.af-guide-title { margin: 0; font-size: 16px; } +.af-guide-lead { margin: 4px 0 0; font-size: 12px; } +.af-guide-skip { font-size: 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: 12px; color: var(--muted); } +.af-guide-step[data-state='current'] .af-guide-number { border-color: var(--accent); color: var(--accent); font-weight: 600; } +.af-guide-step[data-state='done'] .af-guide-number { background: var(--accent); border-color: var(--accent); color: var(--status-fg); } +.af-guide-body { display: grid; gap: 6px; min-width: 0; } +.af-guide-step-title { display: flex; align-items: center; gap: 8px; margin: 1px 0 0; font-size: 13px; } +.af-guide-state { padding: 0 6px; border: 1px solid var(--line); border-radius: 8px; font-size: 10px; font-weight: 400; line-height: 16px; color: var(--muted); } +.af-guide-step[data-state='current'] .af-guide-state { color: var(--accent); border-color: var(--accent); } +.af-guide-step[data-state='todo'] .af-guide-step-title { color: var(--muted); } +.af-guide-text { margin: 0; font-size: 12px; line-height: 1.45; } +.af-guide-actions { display: flex; flex-wrap: wrap; gap: 6px; } +.af-guide-actions .primary-button { width: auto; margin: 0; } +.af-guide-agents { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.af-guide-agent { display: grid; gap: 4px; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; } +.af-guide-agent-main { display: flex; align-items: center; gap: 8px; cursor: pointer; } +.af-guide-agent-main input:disabled + .af-agent-name { color: var(--muted); } + +/* Plan markers drawn in CSS (sources stay free of symbol characters). */ +.af-plan-mark::before { content: '\25CB'; } +.af-plan-mark[data-status="in_progress"]::before { content: '\25B8'; } +.af-plan-mark[data-status="completed"]::before { content: '\2713'; } + +/* ---- Restore, metric delta and the Changes tab (AF5, AF6, AF9) ------------- */ +.af-message-actions { flex-wrap: wrap; } +.af-restore-confirm { flex-basis: 100%; display: grid; gap: 6px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); } +.af-restore-confirm[hidden] { display: none; } +.af-restore-confirm p { margin: 0; } +.af-restore-files { margin: 0; padding-left: 18px; max-height: 140px; overflow: auto; font-family: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; font-size: 11px; } +.af-restore-actions { display: flex; gap: 8px; } +.af-metric-delta summary { cursor: pointer; color: var(--muted); } +.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: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; font-size: 11px; } +.af-link-button.is-danger { color: var(--crit); } +.af-link-button:disabled { opacity: 0.5; cursor: default; text-decoration: none; } + +.af-changes { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--editor); } +.af-changes-header { display: flex; align-items: center; gap: 10px; padding: 8px 16px; border-bottom: 1px solid var(--line); } +.af-changes-summary { font-size: 12px; } +.af-changes-notice { margin: 0; padding: 8px 16px; border-bottom: 1px solid var(--line); font-size: 12px; } +.af-changes-notice[hidden] { display: none; } +.af-changes-body { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(220px, 32%) minmax(0, 1fr); } +.af-changes-list { margin: 0; padding: 4px 0; list-style: none; overflow: auto; border-right: 1px solid var(--line); } +.af-changes-row { display: flex; align-items: center; gap: 6px; padding: 3px 12px; font-size: 13px; cursor: pointer; white-space: nowrap; } +.af-changes-row:hover { background: var(--hover); } +.af-changes-row.is-selected { background: var(--hover); box-shadow: inset 2px 0 var(--accent); } +.af-changes-row:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.af-changes-status { flex: none; width: 12px; font-size: 11px; font-weight: 700; text-align: center; color: var(--warn); } +.af-changes-status[data-status='added'] { color: #3fb950; } +.af-changes-status[data-status='deleted'] { color: var(--crit); } +.af-changes-name { overflow: hidden; text-overflow: ellipsis; } +.af-changes-folder { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 11px; } +.af-changes-actions { display: none; gap: 8px; font-size: 12px; } +.af-changes-row:hover .af-changes-actions, .af-changes-row.is-selected .af-changes-actions, .af-changes-row:focus-within .af-changes-actions { display: inline-flex; } +.af-changes-diff { display: flex; flex-direction: column; min-width: 0; min-height: 0; } +.af-changes-diff-head { display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-bottom: 1px solid var(--line); font-size: 12px; } +.af-changes-diff-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; } +.af-changes-diff-note { margin: 0; padding: 8px 12px; font-size: 12px; } +.af-changes-diff-note[hidden] { display: none; } +.af-changes-diff-host { flex: 1; min-height: 0; } +@media (prefers-color-scheme: light) { .af-changes-status[data-status='added'] { color: #1a7f37; } } + +/* ---- Worktree chats (AF12) ------------------------------------------------ */ +.af-new-worktree { display: flex; align-items: center; gap: 6px; margin: -2px 12px 0; font-size: 12px; color: var(--muted); cursor: pointer; } +.af-new-worktree[hidden] { display: none; } +.af-new-worktree input { margin: 0; } +.af-branch { max-width: 160px; overflow: hidden; text-overflow: ellipsis; color: var(--accent); border-color: var(--accent); } +.af-branch[hidden] { display: none; } +.af-branch.is-removed { color: var(--muted); border-color: var(--line); text-decoration: line-through; } +.af-header-button.is-quiet { border-color: var(--line); } +.af-confirm.has-worktree { flex-wrap: wrap; } +.af-confirm-worktree { flex-basis: 100%; display: flex; align-items: center; gap: 6px; color: var(--muted); } +.af-confirm-worktree input { margin: 0; } +.af-worktree { display: grid; gap: 6px; padding: 8px 16px; border-bottom: 1px solid var(--line); background: var(--panel); font-size: 12px; } +.af-worktree[hidden], .af-worktree [hidden] { display: none; } +.af-worktree-summary { margin: 0; } +.af-worktree-files { margin: 0; padding-left: 16px; font-family: var(--mono, monospace); font-size: 11px; overflow-wrap: anywhere; } +.af-worktree-files:empty { display: none; } +.af-worktree-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.af-worktree-message { flex: 1 1 200px; min-width: 0; } +.af-worktree-hint { font-size: 11px; } +.af-worktree-confirm { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; padding: 6px 8px; border: 1px solid var(--crit); border-radius: 4px; } +.af-worktree-confirm span { flex: 1 1 200px; } +.af-worktree-error { margin: 0; padding: 6px 8px; border-left: 3px solid var(--crit); background: var(--editor); overflow-wrap: anywhere; } diff --git a/apps/ide/src/renderer/agentFirst/agentSetup.ts b/apps/ide/src/renderer/agentFirst/agentSetup.ts new file mode 100644 index 000000000..fc4a6d041 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/agentSetup.ts @@ -0,0 +1,161 @@ +import type { AgentSessionsApi, AgentView, InstallDescription } from '../../shared/agentSession.ts'; +import { el } from '../dom.ts'; +import { describeRows, isUpToDate, setupActions } from './agentSetupModel.ts'; + +/** + * The actions of one agent (AF1, AF2 #267), shared by the Agents section of + * the Chats view and the first-run guide (AF13 #278): sign in, check, and for + * the presets Install, Update and Remove. + * + * Install and Update first read the registry (only now, because the person + * pressed the button) and show inline what would be installed; the install + * itself then asks again in a native dialog of the main process, which the + * page cannot answer, and only that dialog starts the download. + */ + +export interface AgentSetupDeps { + readonly api: AgentSessionsApi; + onStatus(message: string): void; + /** Shows the terminal panel (terminal sign-ins). */ + showTerminal?(): void; + /** Reloads the agents (and probes them when asked). */ + refresh(probe: boolean): Promise; + /** One agent's new view, after a check. */ + replace(view: AgentView): void; +} + +/** The buttons of an agent and, below them, the slot where an install description opens. */ +export function agentActions(agent: AgentView, deps: AgentSetupDeps): HTMLElement { + const buttons = el('span', { className: 'af-agent-actions' }); + const panel = el('div', { className: 'af-install', attrs: { hidden: '', 'data-testid': 'af-install' } }); + const button = (text: string, title: string, run: (self: HTMLButtonElement) => void, extra = ''): HTMLButtonElement => { + const self = el('button', { className: `secondary-button af-small-button${extra}`, text, attrs: { type: 'button', title, 'data-action': text.toLowerCase() } }); + self.addEventListener('click', (event) => { + event.stopPropagation(); + run(self); + }); + buttons.append(self); + return self; + }; + + for (const action of setupActions(agent)) { + if (action === 'login') { + for (const method of (agent.authMethods ?? []).slice(0, 3)) { + button(method.name, method.description ?? method.name, () => { + deps.api.login(agent.ref, method.id) + .then(() => { + if (method.type === 'terminal') { + deps.showTerminal?.(); + deps.onStatus(`${agent.name}: finish the sign-in in the terminal, then press Check.`); + } else { + deps.onStatus(`${agent.name}: signed in.`); + } + return deps.refresh(true); + }) + .catch((error: unknown) => deps.onStatus(errorText(error))); + }); + } + } else if (action === 'check') { + button('Check', 'Start the agent once to see whether it is ready', (self) => { + self.disabled = true; + self.textContent = 'Checking...'; + deps.api.probeAgent(agent.ref) + .then((view) => deps.replace(view)) + .catch((error: unknown) => { + deps.onStatus(errorText(error)); + self.disabled = false; + self.textContent = 'Check'; + }); + }); + } else if (action === 'install' || action === 'update') { + const label = action === 'install' ? 'Install' : 'Update'; + button(label, action === 'install' ? `See what installing ${agent.name} downloads, then confirm` : `See whether a newer ${agent.name} exists`, (self) => { + if (!agent.preset) { + return; + } + const presetId = agent.preset; + self.disabled = true; + self.textContent = 'Reading the registry...'; + deps.api.describeInstall(presetId) + .then((description) => showDescription(panel, description, deps, () => { + self.disabled = false; + self.textContent = label; + })) + .catch((error: unknown) => { + self.disabled = false; + self.textContent = label; + showError(panel, `Could not read what ${agent.name} would install: ${errorText(error)}`); + }); + }, action === 'install' ? ' af-install-button' : ''); + } else if (action === 'remove') { + button('Remove', `Remove ${agent.name} (${agent.installedVersion ?? ''}) from the IDE's folder`, (self) => { + if (!agent.preset) { + return; + } + self.disabled = true; + deps.api.uninstall(agent.preset) + .then((removed) => { + deps.onStatus(removed ? `${agent.name} was removed.` : 'Nothing was removed.'); + return deps.refresh(false); + }) + .catch((error: unknown) => showError(panel, `Could not remove ${agent.name}: ${errorText(error)}`)) + .finally(() => { + self.disabled = false; + }); + }, ' is-danger'); + } + } + return el('div', { className: 'af-agent-setup' }, [buttons, panel]); +} + +function showError(panel: HTMLElement, message: string): void { + panel.hidden = false; + panel.replaceChildren(el('p', { className: 'af-install-error', text: message, attrs: { role: 'alert' } })); +} + +function showDescription(panel: HTMLElement, description: InstallDescription, deps: AgentSetupDeps, reset: () => void): void { + const upToDate = isUpToDate(description); + const list = el('dl', { className: 'af-install-list' }, describeRows(description).flatMap(([term, value]) => [el('dt', { text: term }), el('dd', { text: value })])); + const go = el('button', { className: 'primary-button af-small-button', text: description.installedVersion ? `Update to ${description.version}...` : 'Install...', attrs: { type: 'button', 'data-testid': 'af-install-confirm', title: 'Code-XR IDE asks you to confirm in a dialog before downloading anything' } }); + go.disabled = upToDate; + const cancel = el('button', { className: 'secondary-button af-small-button', text: upToDate ? 'Close' : 'Cancel', attrs: { type: 'button' } }); + const note = el('p', { className: 'muted af-install-note', text: upToDate + ? `${description.agentName} ${description.version} is the latest version.` + : 'Installed into the IDE\'s own folder with your npm, nothing global. You confirm once more before the download starts.' }); + const close = (): void => { + panel.hidden = true; + panel.replaceChildren(); + reset(); + }; + cancel.addEventListener('click', (event) => { + event.stopPropagation(); + close(); + }); + go.addEventListener('click', (event) => { + event.stopPropagation(); + go.disabled = true; + cancel.disabled = true; + go.textContent = 'Waiting for your confirmation...'; + deps.api.install(description.presetId) + .then((installed) => { + deps.onStatus(installed ? `${description.agentName} ${description.version} is installed.` : 'The install was cancelled; nothing was downloaded.'); + close(); + return installed ? deps.refresh(true) : undefined; + }) + .catch((error: unknown) => { + reset(); + showError(panel, `${description.agentName} was not installed: ${errorText(error)}`); + }); + }); + panel.hidden = false; + panel.replaceChildren( + el('p', { className: 'af-install-title', text: description.installedVersion ? `Update ${description.agentName} (${description.installedVersion} installed)` : `Install ${description.agentName}` }), + list, + note, + el('div', { className: 'af-install-actions' }, [go, cancel]), + ); +} + +export 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/agentSetupModel.ts b/apps/ide/src/renderer/agentFirst/agentSetupModel.ts new file mode 100644 index 000000000..c3fd02bb5 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/agentSetupModel.ts @@ -0,0 +1,152 @@ +import type { AgentView, InstallDescription, InstallProgress } from '../../shared/agentSession.ts'; + +/** + * Pure helpers of setting agents up: the install actions of the agents list + * (AF2, #267) and the first-run guide (AF13, #278). No DOM. + */ + +export type SetupAction = 'install' | 'update' | 'remove' | 'login' | 'check'; + +/** What an agent row offers: install a missing preset; update or remove one the IDE installed; sign in and check. */ +export function setupActions(agent: AgentView): SetupAction[] { + if (agent.kind !== 'acp') { + return []; + } + if (agent.availability === 'missing') { + return agent.preset ? ['install'] : []; + } + const actions: SetupAction[] = []; + if (agent.availability === 'needs-login' || (agent.authMethods?.length ?? 0) > 0) { + actions.push('login'); + } + actions.push('check'); + if (agent.preset && agent.installedVersion) { + actions.push('update', 'remove'); + } + return actions; +} + +/** "3.4 MB". */ +export function formatSize(bytes: number): string { + if (bytes < 1024) { + return `${bytes} B`; + } + const units = ['KB', 'MB', 'GB']; + let value = bytes / 1024; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[unit] ?? 'GB'}`; +} + +/** The rows of the inline description shown before the native consent dialog. */ +export function describeRows(description: InstallDescription): [string, string][] { + const rows: [string, string][] = [ + ['Package', `${description.packageName}@${description.version}`], + ['Licence', description.license ?? 'Not stated'], + ['Size', description.unpackedSize === null + ? 'Unknown' + : `${formatSize(description.unpackedSize)}${description.dependenciesSize !== null ? ` + at least ${formatSize(description.dependenciesSize)} of dependencies` : ''}`], + ['Source', description.repository ?? description.registry], + ]; + if (description.published) { + rows.push(['Published', description.published.slice(0, 10)]); + } + if (description.nativeBinaries.length > 0) { + rows.push(['Native binaries', description.nativeBinaries.map((binary) => `${binary.name}${binary.size !== null ? ` (${formatSize(binary.size)})` : ''}`).join('; ')]); + } + rows.push(['Install scripts', description.installScripts.length ? description.installScripts.join(', ') : 'None declared']); + rows.push(['Runs', description.command]); + return rows; +} + +/** True when the installed version is already the one the registry offers. */ +export function isUpToDate(description: InstallDescription): boolean { + return description.installedVersion !== null && description.installedVersion === description.version; +} + +/** The progress notification of an install or removal. */ +export function progressTitle(progress: Pick, agentName: string): string { + return progress.action === 'install' ? `Installing ${agentName}` : `Removing ${agentName}`; +} + +// ---- First run (AF13) ------------------------------------------------------- + +export const ONBOARDED_KEY = 'codexr.agentFirst.onboarded'; + +export type StepState = 'done' | 'current' | 'todo'; + +export interface OnboardingInput { + readonly hasFolder: boolean; + readonly agents: readonly AgentView[]; + /** The agent the person picked in the guide, if any. */ + readonly chosen: string | null; + readonly hasChat: boolean; +} + +export interface OnboardingStep { + readonly id: 'folder' | 'agent' | 'chat'; + readonly title: string; + readonly state: StepState; + readonly text: string; +} + +/** An ACP agent a chat can start with (signed in or not yet known). */ +export function isUsable(agent: AgentView): boolean { + return agent.kind === 'acp' && (agent.availability === 'ready' || agent.availability === 'available'); +} + +/** The agent the guide starts a chat with: the chosen one if usable, else the first ready, else the first usable. */ +export function guideAgent(input: Pick): AgentView | null { + const usable = input.agents.filter(isUsable); + return usable.find((agent) => agent.ref === input.chosen) ?? usable.find((agent) => agent.availability === 'ready') ?? usable[0] ?? null; +} + +/** The three steps and where the person is: each done step reflects real state, the first open one is current. */ +export function onboardingSteps(input: OnboardingInput): OnboardingStep[] { + const agent = guideAgent(input); + const needsLogin = input.agents.some((candidate) => candidate.kind === 'acp' && candidate.availability === 'needs-login'); + const installed = input.agents.some((candidate) => candidate.kind === 'acp' && candidate.availability !== 'missing'); + const done = { folder: input.hasFolder, agent: agent !== null, chat: input.hasChat }; + const steps: Omit[] = [ + { + id: 'folder', + title: 'Open a project folder', + text: done.folder ? 'A folder is open. Agents work inside it, and only once you trust it.' : 'Agents read and change the files of the folder you open, nothing outside it.', + }, + { + id: 'agent', + title: 'Pick a coding agent', + text: agent + ? `${agent.name} is ${agent.availability === 'ready' ? 'ready' : 'installed'}.` + : needsLogin + ? 'Sign in to an agent with its own login: your subscription or API key stays with the vendor\'s tool.' + : installed + ? 'Check an agent to see whether it is ready.' + : 'Install Claude Code, Codex or Gemini CLI. Nothing is downloaded until you confirm.', + }, + { + id: 'chat', + title: 'Start your first chat', + text: done.chat ? 'You have a chat. Open it from the Chats view.' : 'Ask the agent to explain, fix or build something in this project.', + }, + ]; + let current = false; + return steps.map((step) => { + if (done[step.id]) { + return { ...step, state: 'done' }; + } + if (!current) { + current = true; + return { ...step, state: 'current' }; + } + return { ...step, state: 'todo' }; + }); +} + +/** Whether the guide opens on its own: never once onboarded, and never for someone who already chatted. */ +export function shouldShowOnboarding(onboarded: string | null, hasChat: boolean): boolean { + return onboarded !== 'true' && !hasChat; +} diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts new file mode 100644 index 000000000..971ad2b03 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -0,0 +1,529 @@ +import type { AgentSessionMessage, AgentSessionsApi, AgentSessionState, InstallProgress } from '../../shared/agentSession.ts'; +import type { AttachmentSources } from '../agents/chatAttachments.ts'; +import type { CommandRegistry } from '../commands/commandRegistry.ts'; +import type { CustomEditorInput } from '../editor/customEditor.ts'; +import type { EditorGroup } from '../editor/editorGroup.ts'; +import type { NotificationCenter } from '../notifications.ts'; +import type { Workbench } from '../workbench.ts'; +import { 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 { createChangesView, type ChangesView } from './changesView.ts'; +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 './agentFirst.css'; + +/** + * The agent-first workbench (epic #265), installed by main.ts on top of the + * classic one: + * - AF4 (#269): the Agent / Classic layout modes. Agent keeps the Chats view + * on the left and the live analysis column on the right (the scene, or a + * placeholder until one opens); Classic is the workbench as it was. The + * choice is remembered; Ctrl/Cmd+Alt+M switches. + * - AF7 (#272): the Chats view (sessionsView.ts) and notifications when a + * chat that is not on screen finishes or needs an approval. + * - AF3 (#268): every chat is an editor tab (`chat:`) through the + * editor group's custom-editor seam, so chats sit next to files, split and + * come back after a restart. + * - AF2 (#267): installs and removals of agents report as progress + * notifications. + * - AF13 (#278): the first-run guide, in the editor area's welcome view on a + * first run, or as a tab (`guide:getting-started`) from the command palette. + */ + +export interface AgentWorkbenchOptions { + readonly workbench: Workbench; + readonly api: AgentSessionsApi; + readonly registry: CommandRegistry; + readonly notifications: NotificationCenter; + readonly attachments: AttachmentSources; + editorGroup(): Promise; + openFile(path: string, line?: number): void; + copy(text: string): void; + onStatus(message: string): void; + /** Opens a recent folder in this window (resolves once it is open). */ + openProject(root: string): Promise; + showTerminal(): void; + /** Runs the XR analysis of the open folder (the dock's button). */ + analyseProject(): void; + /** Whether a folder is open in this window. */ + hasFolder(): boolean; + /** Asks for a folder to open in this window (File > Open Folder). */ + openFolder(): void; + /** The workspace calls the project instructions section needs (AF11). */ + readonly instructions: Omit; + /** Optional hooks of later stories. */ + readonly chatHooks?: Pick; +} + +export interface AgentWorkbench { + readonly sessions: SessionsView; + openChat(sessionId: string): Promise; + newChat(agentRef?: 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. */ + resolveCustomEditor(id: string): CustomEditorInput | null; + /** The folder of the window changed: chats of the old folder close, the list reloads. */ + folderChanged(): void; +} + +const MODE_KEY = 'codexr.layout.mode'; +const GUIDE_TAB_ID = 'guide:getting-started'; +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 { + const { workbench, api } = options; + const views = new Set(); + let activeChatId: string | null = null; + let mode: LayoutMode = readMode(); + + // ---- Dock placeholder (AF8) -------------------------------------------- + const analyse = el('button', { className: 'primary-button', text: 'Analyse this project', attrs: { type: 'button', 'data-testid': 'af-dock-analyse' } }); + analyse.addEventListener('click', () => options.analyseProject()); + const dockNote = el('p', { className: 'muted' }); + const art = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + art.setAttribute('viewBox', '0 0 24 24'); + art.setAttribute('class', 'af-dock-art'); + art.setAttribute('aria-hidden', 'true'); + 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', text: '×', attrs: { type: 'button', title: 'Hide the live analysis column', 'aria-label': 'Hide the live analysis column' } }); + hideDock.addEventListener('click', () => setDockHidden(true)); + workbench.dockArea.replaceChildren( + el('header', { className: 'af-dock-head' }, [el('span', { text: 'Live analysis' }), el('span', { className: 'af-live', text: 'Waiting', attrs: { 'data-state': 'idle' } }), 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]), + ); + function renderDock(): void { + const folder = options.hasFolder(); + dockNote.textContent = folder + ? 'The XR scene of this project appears here and follows every file the agent changes. It starts on its own when a folder opens, once the analysis environment is ready.' + : 'Open a folder to analyse it. Its XR scene, LivePanel or dependency graph stays in this column while you chat with the agent.'; + analyse.hidden = !folder; + } + function setDockHidden(hidden: boolean): void { + const shell = workbench.dockArea.parentElement; + shell?.classList.toggle('dock-hidden', hidden); + } + + // ---- Chats as editor tabs (AF3) ---------------------------------------- + function chatDeps(): ChatViewDeps { + return { + api, + attachments: options.attachments, + openFile: options.openFile, + copy: options.copy, + onStatus: options.onStatus, + onDidChange: (state) => { + for (const view of views) { + if (view.sessionId === state.id) { + titleSetters.get(view)?.(state.title); + } + } + }, + // AF5/AF6: the review of the chat's changes and its checkpoints. + openChanges: (state) => void openChanges(state.id, state.title), + previewRestore: (state, checkpointId) => api.previewRestore(state.id, checkpointId), + restoreCheckpoint: async (state, checkpointId) => { + const written = await api.restoreCheckpoint(state.id, checkpointId); + options.onStatus(written.length === 0 ? 'Nothing to restore.' : `Restored ${written.length} file${written.length === 1 ? '' : 's'}.`); + refreshChanges(state.id); + }, + ...options.chatHooks, + }; + } + + // ---- Changes tabs (AF5) -------------------------------------------------- + const changesViews = new Map>(); + function refreshChanges(sessionId: string): void { + for (const view of changesViews.get(sessionId) ?? []) { + view.refresh().catch(() => undefined); + } + } + + function changesInput(sessionId: string, chatTitle = 'Chat'): CustomEditorInput { + return { + id: changesTabId(sessionId), + title: `Changes: ${chatTitle}`, + iconName: 'changes.diff', + create(context) { + // AF12: the files of a worktree chat are in its worktree, not in the folder the editor shows. + let worktreePath: string | null = null; + const openFile = (path: string): void => { + if (worktreePath) { + options.onStatus(`${path} is in this chat's worktree (${worktreePath}). The editor shows the main project; merge the branch to bring it in.`); + return; + } + options.openFile(path); + }; + const view = createChangesView(sessionId, { api, openFile, onStatus: options.onStatus }); + const set = changesViews.get(sessionId) ?? new Set(); + set.add(view); + changesViews.set(sessionId, set); + api.get(sessionId).then((state) => { + worktreePath = state.worktree?.path ?? null; + context.setTitle(`Changes: ${state.title}`); + }, (error: unknown) => { + if (/That chat no longer exists/.test(errorText(error))) { + context.close(); + } + }); + return { + element: view.element, + onShow: () => void view.refresh(), + dispose: () => { + view.dispose(); + set.delete(view); + if (set.size === 0) { + changesViews.delete(sessionId); + } + }, + }; + }, + }; + } + + async function openChanges(sessionId: string, chatTitle?: string): Promise { + const group = await options.editorGroup(); + await group.openCustom(changesInput(sessionId, chatTitle), { preview: false }); + } + const titleSetters = new WeakMap void>(); + const tabClosers = new Map void>(); + + function chatInput(sessionId: string, title = 'Chat'): CustomEditorInput { + return { + id: chatTabId(sessionId), + title, + iconName: 'chat.md', + create(context) { + const view = createChatView(sessionId, chatDeps()); + // A restored tab whose chat was deleted (here or in another window) closes itself. + api.get(sessionId).catch((error: unknown) => { + if (/That chat no longer exists/.test(errorText(error))) { + context.close(); + } + }); + views.add(view); + titleSetters.set(view, (next) => context.setTitle(next)); + tabClosers.set(sessionId, () => context.close()); + return { + element: view.element, + onShow: () => { + activeChatId = sessionId; + sessions.setActive(sessionId); + api.markRead(sessionId).catch(() => undefined); + }, + onHide: () => { + if (activeChatId === sessionId) { + activeChatId = null; + sessions.setActive(null); + } + }, + focus: () => view.focus(), + dispose: () => { + view.dispose(); + views.delete(view); + tabClosers.delete(sessionId); + }, + }; + }, + }; + } + + // Registered by main.ts when the editor group is created (it loads Monaco, + // so it must not be created here at startup): restored chat tabs resolve through it. + function resolveCustomEditor(id: string): CustomEditorInput | null { + if (id === GUIDE_TAB_ID) { + return guideInput(); + } + const sessionId = chatIdOf(id); + if (sessionId) { + return chatInput(sessionId); + } + const changesOf = changesIdOf(id); + return changesOf ? changesInput(changesOf) : null; + } + + async function openChat(sessionId: string): Promise { + const group = await options.editorGroup(); + let title = 'Chat'; + try { + title = (await api.get(sessionId)).title; + } catch { + // The view reports the error itself. + } + await group.openCustom(chatInput(sessionId, title), { preview: false }); + } + + // ---- 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), + openChatInProject: (root, id) => { + options.openProject(root).then(() => openChat(id)).catch((error: unknown) => options.onStatus(errorText(error))); + }, + openProject: (root) => { + options.openProject(root).catch((error: unknown) => options.onStatus(errorText(error))); + }, + activeChat: () => activeChatId, + onStatus: options.onStatus, + mode: () => mode, + setMode, + showTerminal: options.showTerminal, + extraSections: [instructions.element], + 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; + }, + }); + 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')); + workbench.editorStatus.parentElement?.prepend(attention); + + // ---- Messages from the main process ------------------------------------- + const lastSeen = new Map(); + api.onMessage((message: AgentSessionMessage) => { + if (message.kind === 'install-progress') { + installProgress(message); + return; + } + for (const view of views) { + view.handle(message); + } + if (message.kind === 'event' && (message.event.type === 'pending-changes' || message.event.type === 'turn-end')) { + refreshChanges(message.sessionId); + } + sessions.handle(message); + notifyIfHidden(message); + if (message.kind === 'sessions-changed') { + refreshHasChat(); + } + }); + + // ---- Installing agents (AF2) -------------------------------------------- + function installProgress(progress: InstallProgress): void { + const name = sessions.agents().find((agent) => agent.preset === progress.presetId)?.name ?? progress.presetId; + const key = `agent-install-${progress.presetId}`; + if (!progress.done) { + options.notifications.progress(key, { title: progressTitle(progress, name), message: progress.line }); + return; + } + options.notifications.endProgress(key); + if (progress.error) { + options.notifications.notify('error', progress.action === 'install' ? `${name} could not be installed.` : `${name} could not be removed.`, { detail: progress.error }); + } else { + options.notifications.notify('info', progress.action === 'install' ? `${name} is installed. Sign in or start a chat.` : `${name} was removed.`); + } + } + + // ---- First run (AF13) --------------------------------------------------- + const guides = new Set(); + let hasChat = false; + let inlineGuide: GettingStartedView | null = null; + let closeGuideTab: (() => void) | null = null; + const readOnboarded = (): string | null => { + try { + return localStorage.getItem(ONBOARDED_KEY); + } catch { + return null; + } + }; + function finishGuide(): void { + try { + localStorage.setItem(ONBOARDED_KEY, 'true'); + } catch { + // Without storage the guide may show again; nothing else depends on it. + } + inlineGuide?.element.remove(); + if (inlineGuide) { + guides.delete(inlineGuide); + inlineGuide = null; + } + closeGuideTab?.(); + } + function createGuide(): GettingStartedView { + return createGettingStartedView({ + setup: { + api, + onStatus: options.onStatus, + showTerminal: options.showTerminal, + refresh: (probe) => sessions.refreshAgents(probe), + replace: () => void sessions.refreshAgents(false), + }, + hasFolder: options.hasFolder, + hasChat: () => hasChat, + agents: () => sessions.agents(), + openFolder: options.openFolder, + startChat: async (ref) => { + const before = hasChat; + await sessions.newChat(ref); + await refreshHasChat(); + if (hasChat && !before) { + finishGuide(); + } + }, + skip: finishGuide, + }); + } + function guideInput(): CustomEditorInput { + return { + id: GUIDE_TAB_ID, + title: 'Getting Started', + iconName: 'guide.md', + create(context) { + const guide = createGuide(); + guides.add(guide); + closeGuideTab = () => context.close(); + return { + element: el('div', { className: 'af-guide-tab' }, [guide.element]), + onShow: () => guide.render(), + dispose: () => { + guides.delete(guide); + closeGuideTab = null; + }, + }; + }, + }; + } + function renderGuides(): void { + for (const guide of guides) { + guide.render(); + } + } + async function refreshHasChat(): Promise { + try { + hasChat = (await api.listProjects()).some((project) => project.sessions.length > 0); + } catch { + // Keeps the last answer. + } + renderGuides(); + } + async function showGettingStarted(): Promise { + const group = await options.editorGroup(); + group.openCustom(guideInput(), { preview: false }); + } + sessions.onAgentsChange(() => renderGuides()); + // 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)) { + return; + } + const welcome = workbench.editorArea.querySelector('[data-testid="welcome"]'); + if (welcome?.isConnected) { + inlineGuide = createGuide(); + guides.add(inlineGuide); + welcome.append(inlineGuide.element); + } else { + void showGettingStarted(); + } + }); + + function notifyIfHidden(message: AgentSessionMessage): void { + if (message.kind !== 'event') { + return; + } + const { sessionId, event } = message; + const visible = activeChatId === sessionId && document.hasFocus(); + 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') { + notify(sessionId, event.stopReason === 'error' ? 'error' : 'info', event.stopReason === 'error' ? 'An agent\'s turn failed.' : 'An agent finished.'); + } + if (event.type === 'status') { + lastSeen.set(sessionId, event.status); + } + } + + 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) }], + }); + }).catch(() => options.notifications.notify(severity, fallback)); + } + + // ---- Layout mode (AF4) -------------------------------------------------- + function setMode(next: LayoutMode): void { + mode = next; + try { + localStorage.setItem(MODE_KEY, next); + } catch { + // Remembering the mode is a convenience. + } + workbench.setLayoutMode(next); + if (next === 'agent') { + setDockHidden(false); + workbench.showView('chats'); + } + sessions.setActive(activeChatId); + renderDock(); + } + + options.registry.register({ id: 'layout.toggleAgentMode', category: 'View', title: 'Toggle Agent / Classic Layout', keybinding: 'CmdOrCtrl+Alt+M', run: () => setMode(mode === 'agent' ? 'classic' : 'agent') }); + options.registry.register({ id: 'layout.agentMode', category: 'View', title: 'Agent Layout (Chats, Work Area, Live Analysis)', run: () => setMode('agent') }); + options.registry.register({ id: 'layout.classicMode', category: 'View', title: 'Classic Layout', run: () => setMode('classic') }); + options.registry.register({ id: 'chat.new', category: 'Chat', title: 'New Chat', keybinding: 'CmdOrCtrl+Shift+L', run: () => void sessions.newChat() }); + options.registry.register({ id: 'chat.showGettingStarted', category: 'Chat', title: 'Show Getting Started', run: () => { + showGettingStarted().catch((error: unknown) => options.onStatus(setupErrorText(error))); + } }); + options.registry.register({ id: 'chat.showChats', category: 'Chat', title: 'Show Chats', run: () => workbench.showView('chats') }); + options.registry.register({ id: 'chat.searchChats', category: 'Chat', title: 'Search Chats', run: () => { + workbench.showView('chats'); + sessions.focusSearch(); + } }); + options.registry.register({ id: 'layout.toggleLiveAnalysis', category: 'View', title: 'Toggle Live Analysis Column', run: () => { + const shell = workbench.dockArea.parentElement; + setDockHidden(!shell?.classList.contains('dock-hidden')); + } }); + + setMode(mode); + instructions.refresh().catch(() => undefined); + + return { + sessions, + openChat, + newChat: (agentRef?: string) => sessions.newChat(agentRef), + setMode, + resolveCustomEditor, + get mode() { + return mode; + }, + folderChanged(): void { + renderDock(); + renderGuides(); + if (mode === 'agent') { + workbench.showView('chats'); + } + sessions.refresh().catch(() => undefined); + instructions.refresh().catch(() => undefined); + }, + }; +} + +function readMode(): LayoutMode { + try { + return parseLayoutMode(localStorage.getItem(MODE_KEY)); + } catch { + return parseLayoutMode(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 new file mode 100644 index 000000000..79a430bca --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/agentWorkbenchModel.ts @@ -0,0 +1,27 @@ +/** + * Pure helpers of the agent-first workbench (AF3, AF4): the layout modes and + * the ids of chat tabs. No DOM. + */ + +export type LayoutMode = 'agent' | 'classic'; + +/** The remembered layout mode; a new install starts in the Agent layout. */ +export function parseLayoutMode(value: string | null | undefined): LayoutMode { + return value === 'classic' ? 'classic' : 'agent'; +} + +/** Chat tabs live in the editor group under ids with this scheme. */ +export const CHAT_ID_PREFIX = 'chat:'; + +export function chatTabId(sessionId: string): string { + return `${CHAT_ID_PREFIX}${sessionId}`; +} + +/** The session behind a chat tab id, or null for any other tab. */ +export function chatIdOf(tabId: string): string | null { + if (!tabId.startsWith(CHAT_ID_PREFIX)) { + return null; + } + const id = tabId.slice(CHAT_ID_PREFIX.length); + return id.length > 0 ? id : null; +} diff --git a/apps/ide/src/renderer/agentFirst/changesDiff.ts b/apps/ide/src/renderer/agentFirst/changesDiff.ts new file mode 100644 index 000000000..42f9f10ad --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/changesDiff.ts @@ -0,0 +1,55 @@ +import { monaco } from '../editor/monaco.ts'; + +/** + * The Monaco side-by-side diff of the Changes tab (AF5, #270): read-only, + * the file at its review base on the left and on disk on the right. Imported + * 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. + */ + +export interface ChangesDiff { + show(path: string, oldText: string, newText: string): void; + clear(): void; + dispose(): void; +} + +let sequence = 0; + +export function createChangesDiff(host: HTMLElement): ChangesDiff { + const editor = monaco.editor.createDiffEditor(host, { + automaticLayout: true, + readOnly: true, + originalEditable: false, + renderSideBySide: true, + fontFamily: "ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace", + fontSize: 13, + scrollBeyondLastLine: false, + }); + let models: { original: ReturnType; modified: ReturnType } | null = null; + + function release(): void { + editor.setModel(null); + models?.original.dispose(); + models?.modified.dispose(); + models = null; + } + + return { + show(path, oldText, newText) { + const id = ++sequence; + const next = { + original: monaco.editor.createModel(oldText, undefined, monaco.Uri.from({ scheme: 'codexr-review-base', path: `/${id}/${path}` })), + modified: monaco.editor.createModel(newText, undefined, monaco.Uri.from({ scheme: 'codexr-review-disk', path: `/${id}/${path}` })), + }; + release(); + models = next; + editor.setModel(next); + }, + clear: release, + dispose() { + release(); + editor.dispose(); + }, + }; +} diff --git a/apps/ide/src/renderer/agentFirst/changesModel.ts b/apps/ide/src/renderer/agentFirst/changesModel.ts new file mode 100644 index 000000000..c7272cf1c --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/changesModel.ts @@ -0,0 +1,110 @@ +import type { ChangedFileView, MetricChangeView, TurnMetricDeltaView } from '../../shared/agentSession.ts'; + +/** + * Pure helpers of the review of a chat's changes (AF5, #270), its restores + * (AF6, #271) and the metric delta under a turn (AF9, #274). No DOM. + */ + +/** The Changes tab of a chat lives in the editor group under this scheme. */ +export const CHANGES_ID_PREFIX = 'chat-changes:'; + +export function changesTabId(sessionId: string): string { + return `${CHANGES_ID_PREFIX}${sessionId}`; +} + +/** The session behind a Changes tab id, or null for any other tab. */ +export function changesIdOf(tabId: string): string | null { + if (!tabId.startsWith(CHANGES_ID_PREFIX)) { + return null; + } + const id = tabId.slice(CHANGES_ID_PREFIX.length); + return id.length > 0 ? id : null; +} + +/** One letter per status, as Source Control shows them. */ +export function statusLetter(status: ChangedFileView['status']): 'A' | 'M' | 'D' { + return status === 'added' ? 'A' : status === 'deleted' ? 'D' : 'M'; +} + +/** "3 files, +40 -12". */ +export function changesSummary(files: readonly ChangedFileView[]): string { + if (files.length === 0) { + return 'No pending changes.'; + } + const additions = files.reduce((sum, file) => sum + file.additions, 0); + const deletions = files.reduce((sum, file) => sum + file.deletions, 0); + return `${files.length} file${files.length === 1 ? '' : 's'}, +${additions} -${deletions}`; +} + +/** + * The file to show after the list changed: the one shown before if it is + * still pending, else the one at the same position, else the first. + */ +export function nextSelection(files: readonly ChangedFileView[], previous: string | null, previousIndex = 0): string | null { + if (files.length === 0) { + return null; + } + if (previous !== null && files.some((file) => file.path === previous)) { + return previous; + } + return files[Math.min(Math.max(previousIndex, 0), files.length - 1)]?.path ?? null; +} + +/** What the inline confirmation of "Restore files to here" says. */ +export function restorePrompt(paths: readonly string[]): string { + if (paths.length === 0) { + return 'The files are already as they were before this message.'; + } + return `Restore ${paths.length} file${paths.length === 1 ? '' : 's'} to how they were before this message? The conversation is kept.`; +} + +const METRIC_LABELS: Readonly> = { + maxComplexity: 'Complexity max', + avgComplexity: 'Complexity avg', + cyclomaticComplexityNumber: 'Complexity avg', + maxCognitiveComplexity: 'Cognitive max', + averageMaintainabilityIndex: 'Maintainability', + codeLines: 'LOC', + totalLines: 'Lines', + functionCount: 'Functions', + classCount: 'Classes', + highComplexityFunctions: 'High-complexity functions', + criticalComplexityFunctions: 'Critical functions', + files: 'Analysed files', +}; + +/** Metrics shown as "before -> after" (levels), the others as a signed difference (counts). */ +const LEVELS = new Set(['maxComplexity', 'avgComplexity', 'cyclomaticComplexityNumber', 'maxCognitiveComplexity', 'averageMaintainabilityIndex']); + +export function metricLabel(metric: string): string { + return METRIC_LABELS[metric] ?? metric; +} + +const round = (value: number): number => Math.round(value * 100) / 100; + +/** "Complexity max 9 -> 1" or "LOC -6". */ +export function formatMetricChange(change: MetricChangeView): string { + const label = metricLabel(change.metric); + if (LEVELS.has(change.metric) || change.before === null || change.after === null) { + return `${label} ${change.before ?? '-'} -> ${change.after ?? '-'}`; + } + const delta = round(change.after - change.before); + return `${label} ${delta > 0 ? '+' : ''}${delta}`; +} + +/** 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 { + if (delta.totals.length === 0) { + return delta.summary; + } + return delta.totals.slice(0, max).map(formatMetricChange).join(', '); +} + +/** One line per file for the details: "src/a.ts (changed): Complexity max 9 -> 1, LOC -6". */ +export function metricDeltaFileLines(delta: TurnMetricDeltaView): string[] { + const lines = delta.files.map((file) => `${file.path} (${file.status})${file.changes.length > 0 ? `: ${file.changes.map(formatMetricChange).join(', ')}` : ''}`); + if (delta.moreFiles > 0) { + lines.push(`and ${delta.moreFiles} more file${delta.moreFiles === 1 ? '' : 's'}`); + } + return lines; +} diff --git a/apps/ide/src/renderer/agentFirst/changesView.ts b/apps/ide/src/renderer/agentFirst/changesView.ts new file mode 100644 index 000000000..987848552 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/changesView.ts @@ -0,0 +1,243 @@ +import type { AgentSessionsApi, ChangedFileView, ChatChanges } from '../../shared/agentSession.ts'; +import { el, fileIcon } from '../dom.ts'; +import type { ChangesDiff } from './changesDiff.ts'; +import { changesSummary, nextSelection, statusLetter } from './changesModel.ts'; + +/** + * The Changes tab of a chat (AF5, #270): every file the chat changed that + * still awaits review, with its status and line counts, a Monaco diff of the + * 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. + */ + +export interface ChangesViewDeps { + readonly api: AgentSessionsApi; + openFile(path: string): void; + onStatus(message: string): void; +} + +export interface ChangesView { + readonly element: HTMLElement; + refresh(): Promise; + dispose(): void; +} + +const CONFIRM_MS = 4000; + +export function createChangesView(sessionId: string, deps: ChangesViewDeps): ChangesView { + let files: readonly ChangedFileView[] = []; + let selected: string | null = null; + let busy = false; + let disposed = false; + let diff: ChangesDiff | null = null; + let diffLoading: Promise | null = null; + let showToken = 0; + + 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 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' }); + const openButton = el('button', { className: 'af-link-button', text: 'Open file', attrs: { type: 'button', hidden: '' } }); + const diffNote = el('p', { className: 'af-changes-diff-note muted', attrs: { hidden: '' } }); + const diffHost = el('div', { className: 'af-changes-diff-host', attrs: { 'data-testid': 'af-changes-diff' } }); + const element = el('section', { className: 'af-changes', attrs: { 'data-testid': 'af-changes', 'data-session': sessionId } }, [ + 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' }), + 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]), + ]), + ]); + + openButton.addEventListener('click', () => { + if (selected) { + deps.openFile(selected); + } + }); + keepAll.addEventListener('click', () => void act(() => deps.api.keepChanges(sessionId, 'all'), 'Kept every change.')); + let undoArmed: ReturnType | null = null; + undoAll.addEventListener('click', () => { + if (!undoArmed) { + undoAll.textContent = `Undo ${files.length} file${files.length === 1 ? '' : 's'}?`; + undoArmed = setTimeout(disarmUndo, CONFIRM_MS); + return; + } + disarmUndo(); + void act(() => deps.api.undoChanges(sessionId, 'all'), 'Undid every change.'); + }); + function disarmUndo(): void { + if (undoArmed) { + clearTimeout(undoArmed); + } + undoArmed = null; + undoAll.textContent = 'Undo all'; + } + + async function act(run: () => Promise, done: string): Promise { + if (busy) { + return; + } + busy = true; + renderButtons(); + try { + apply(await run()); + deps.onStatus(done); + } catch (error) { + deps.onStatus(errorText(error)); + } finally { + busy = false; + renderButtons(); + } + } + + function renderButtons(): void { + keepAll.disabled = busy || files.length === 0; + undoAll.disabled = busy || files.length === 0; + for (const button of list.querySelectorAll('button')) { + button.disabled = busy; + } + } + + function apply(changes: ChatChanges): void { + if (disposed) { + return; + } + const previousIndex = selected === null ? 0 : Math.max(0, files.findIndex((file) => file.path === selected)); + files = changes.files; + summary.textContent = changesSummary(files); + notice.hidden = changes.disabledReason === null && files.length > 0; + notice.textContent = changes.disabledReason !== null + ? `Checkpoints are off for this project: ${changes.disabledReason}` + : 'Nothing to review: the files are as you last kept them.'; + const next = nextSelection(files, selected, previousIndex); + renderList(next); + renderButtons(); + if (next !== selected || next === null) { + select(next); + } else { + void showDiff(next); + } + } + + function renderList(active: string | null): void { + list.replaceChildren(...files.map((file) => { + const slash = file.path.lastIndexOf('/'); + const name = file.path.slice(slash + 1); + const folder = slash >= 0 ? file.path.slice(0, slash) : ''; + const keep = el('button', { className: 'af-link-button', text: 'Keep', attrs: { type: 'button', title: `Accept the change to ${file.path}`, 'data-action': 'keep' } }); + const undo = el('button', { className: 'af-link-button is-danger', text: 'Undo', attrs: { type: 'button', title: `Put ${file.path} back as it was`, 'data-action': 'undo' } }); + keep.addEventListener('click', (event) => { + event.stopPropagation(); + void act(() => deps.api.keepChanges(sessionId, [file.path]), `Kept ${file.path}.`); + }); + undo.addEventListener('click', (event) => { + event.stopPropagation(); + void act(() => deps.api.undoChanges(sessionId, [file.path]), `Undid the change to ${file.path}.`); + }); + const row = el('li', { + className: `af-changes-row${file.path === active ? ' is-selected' : ''}`, + attrs: { 'data-path': file.path, 'data-status': file.status, tabindex: '0', role: 'button', 'aria-label': `${file.path}, ${file.status}` }, + }, [ + el('span', { className: 'af-changes-status', text: statusLetter(file.status), attrs: { 'data-status': file.status, title: file.status } }), + fileIcon(name, 'file'), + el('span', { className: 'af-changes-name', text: name, attrs: { title: file.path } }), + el('span', { className: 'af-changes-folder muted', text: folder }), + el('span', { className: 'af-diff-counts' }, file.binary ? [el('span', { className: 'muted', text: 'binary' })] : [el('span', { className: 'is-add', text: `+${file.additions}` }), el('span', { className: 'is-remove', text: ` -${file.deletions}` })]), + el('span', { className: 'af-changes-actions' }, [keep, undo]), + ]); + row.addEventListener('click', () => select(file.path)); + row.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + select(file.path); + } + }); + return row; + })); + } + + function select(filePath: string | null): void { + selected = filePath; + for (const row of list.querySelectorAll('.af-changes-row')) { + row.classList.toggle('is-selected', row.dataset['path'] === filePath); + } + void showDiff(filePath); + } + + function loadDiff(): Promise { + diffLoading ??= import('./changesDiff.ts').then(({ createChangesDiff }) => { + const created = createChangesDiff(diffHost); + if (disposed) { + created.dispose(); + } else { + diff = created; + } + return created; + }); + return diffLoading; + } + + async function showDiff(filePath: string | null): Promise { + const token = ++showToken; + const file = files.find((candidate) => candidate.path === filePath) ?? null; + diffTitle.textContent = file ? file.path : ''; + openButton.hidden = !file || file.status === 'deleted'; + diffNote.hidden = true; + if (!file) { + diff?.clear(); + return; + } + if (file.binary) { + diff?.clear(); + diffNote.hidden = false; + diffNote.textContent = 'A binary file: no text diff to show.'; + return; + } + try { + const [editor, sides] = await Promise.all([loadDiff(), deps.api.changeDiff(sessionId, file.path)]); + if (token !== showToken || disposed) { + return; + } + editor.show(file.path, sides.oldText ?? '', sides.newText ?? ''); + } catch (error) { + if (token === showToken) { + diffNote.hidden = false; + diffNote.textContent = `Could not show the change: ${errorText(error)}`; + } + } + } + + async function refresh(): Promise { + try { + apply(await deps.api.changes(sessionId)); + } catch (error) { + notice.hidden = false; + notice.textContent = errorText(error); + } + } + + summary.textContent = 'Loading...'; + renderButtons(); + + return { + element, + refresh, + dispose(): void { + disposed = true; + disarmUndo(); + diff?.dispose(); + }, + }; +} + +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/chatModel.ts b/apps/ide/src/renderer/agentFirst/chatModel.ts new file mode 100644 index 000000000..c2cf94d8d --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/chatModel.ts @@ -0,0 +1,176 @@ +import type { AgentSessionState, PromptAttachment, SlashCommandView, TranscriptItem } from '../../shared/agentSession.ts'; +import { diffLines, splitLines } from '../../shared/lineDiff.ts'; + +/** + * Pure helpers of the agent-first chat (AF3): what the composer suggests, + * how a tool card summarises itself, how a diff is drawn as lines. No DOM, so + * they are unit-tested in Node and the chat view stays a thin renderer. + */ + +/** The slash commands that match what the person typed (`/` at the start of the message). */ +export function slashSuggestions(text: string, commands: readonly SlashCommandView[], limit = 8): SlashCommandView[] { + const match = /^\/([\w:.-]*)$/.exec(text); + if (!match) { + return []; + } + const typed = (match[1] ?? '').toLowerCase(); + return commands + .filter((command) => command.name.toLowerCase().startsWith(typed)) + .slice(0, limit); +} + +/** A tool card's one-line status for screen readers and the collapsed card. */ +export function toolStatusLabel(status: Extract['status']): string { + switch (status) { + case 'pending': + return 'Waiting'; + case 'in_progress': + return 'Running'; + case 'completed': + return 'Done'; + case 'failed': + return 'Failed'; + } +} + +/** SVG path data (24x24) per tool kind. */ +export const TOOL_ICONS: Readonly['toolKind'], string>> = { + read: 'M4 4h11l5 5v11H4zM14 4v6h6', + edit: 'M4 20h4L19 9l-4-4L4 16zM14 6l4 4', + delete: 'M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13', + move: 'M4 12h14M13 6l6 6-6 6', + search: 'M10.5 4a6.5 6.5 0 1 0 0 13a6.5 6.5 0 1 0 0-13zM15.5 15.5L21 21', + execute: 'M4 5h16v14H4zM7 9l3 3-3 3M12 15h5', + think: 'M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5V16h8v-2.5A6 6 0 0 0 12 3z', + fetch: 'M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18zM3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18', + switch_mode: 'M7 7h13M17 4l3 3-3 3M17 17H4M7 14l-3 3 3 3', + other: 'M12 8v4M12 16h.01M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z', +}; + +export type DiffLine = { readonly kind: 'context' | 'add' | 'remove' | 'gap'; readonly text: string }; + +/** + * The lines of a compact unified diff: changed lines with `context` lines + * around them, and a `gap` line where unchanged lines are skipped. Capped so + * a rewritten 5,000-line file does not freeze the chat. + */ +export function diffLinesForCard(oldText: string | null, newText: string, context = 2, maxLines = 400): DiffLine[] { + const before = oldText ?? ''; + const lines: DiffLine[] = []; + if (oldText === null) { + for (const text of splitLines(newText)) { + lines.push({ kind: 'add', text }); + } + return cap(lines, maxLines); + } + const original = splitLines(before); + const hunks = diffLines(before, newText); + let cursor = 0; + hunks.forEach((hunk, hunkIndex) => { + const start = Math.max(cursor, hunk.originalStart - context); + if (start > cursor && lines.length > 0) { + lines.push({ kind: 'gap', text: '' }); + } else if (start > 0 && lines.length === 0) { + lines.push({ kind: 'gap', text: '' }); + } + for (let index = start; index < hunk.originalStart; index += 1) { + lines.push({ kind: 'context', text: original[index] ?? '' }); + } + for (const text of original.slice(hunk.originalStart, hunk.originalStart + hunk.originalCount)) { + lines.push({ kind: 'remove', text }); + } + for (const text of hunk.lines) { + lines.push({ kind: 'add', text }); + } + const after = hunk.originalStart + hunk.originalCount; + // Trailing context stops where the next hunk starts, or a line would show twice. + const end = Math.min(original.length, after + context, hunks[hunkIndex + 1]?.originalStart ?? Number.POSITIVE_INFINITY); + for (let index = after; index < end; index += 1) { + lines.push({ kind: 'context', text: original[index] ?? '' }); + } + cursor = Math.max(end, after); + }); + if (cursor < original.length && lines.length > 0) { + lines.push({ kind: 'gap', text: '' }); + } + return cap(lines, maxLines); +} + +function cap(lines: DiffLine[], maxLines: number): DiffLine[] { + if (lines.length <= maxLines) { + return lines; + } + return [...lines.slice(0, maxLines), { kind: 'gap', text: `${lines.length - maxLines} more lines` }]; +} + +/** Added and removed line counts of a change, for the "+3 -1" labels. */ +export function changeCounts(oldText: string | null, newText: string): { readonly added: number; readonly removed: number } { + if (oldText === null) { + return { added: splitLines(newText).length, removed: 0 }; + } + let added = 0; + let removed = 0; + for (const hunk of diffLines(oldText, newText)) { + added += hunk.lines.length; + removed += hunk.originalCount; + } + return { added, removed }; +} + +/** A path for display: relative to the project when it is inside it, with forward slashes. */ +export function displayPath(path: string, root: string | null): string { + const normalized = path.replace(/\\/g, '/'); + if (!root) { + return normalized; + } + const base = root.replace(/\\/g, '/').replace(/\/+$/, ''); + return normalized.toLowerCase().startsWith(`${base.toLowerCase()}/`) ? normalized.slice(base.length + 1) : normalized; +} + +/** What the composer's send button does right now. */ +export function composerAction(state: Pick, text: string): 'send' | 'queue' | 'stop' | 'none' { + const running = state.status === 'running' || state.status === 'awaiting'; + if (text.trim()) { + return running ? 'queue' : 'send'; + } + return running ? 'stop' : 'none'; +} + +/** The files a turn changed, from its tool cards' diffs, newest version of each file last wins. */ +export function turnChanges(items: readonly TranscriptItem[], fromIndex: number): { readonly path: string; readonly oldText: string | null; readonly newText: string }[] { + const byPath = new Map(); + for (const item of items.slice(fromIndex)) { + if (item.kind !== 'tool') { + continue; + } + for (const block of item.content) { + if (block.type !== 'diff') { + continue; + } + const previous = byPath.get(block.path); + byPath.set(block.path, { path: block.path, oldText: previous ? previous.oldText : block.oldText, newText: block.newText }); + } + } + return [...byPath.values()]; +} + +/** Index of the last user message (the start of the current turn), or -1. */ +export function lastUserIndex(items: readonly TranscriptItem[]): number { + for (let index = items.length - 1; index >= 0; index -= 1) { + if (items[index]?.kind === 'user') { + return index; + } + } + return -1; +} + +/** 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; +} + +/** "12k / 200k" for the context meter. */ +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)}`; +} diff --git a/apps/ide/src/renderer/agentFirst/chatView.ts b/apps/ide/src/renderer/agentFirst/chatView.ts new file mode 100644 index 000000000..aa07e8aa0 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/chatView.ts @@ -0,0 +1,729 @@ +import type { ChatAttachment } from '../../shared/agents.ts'; +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 { renderMarkdown } from '../agents/chatMarkdown.ts'; +import { createAttachmentBar, type AttachmentSources } from '../agents/chatAttachments.ts'; +import { el, icon } from '../dom.ts'; +import { createWorktreeBar } from './worktreeBar.ts'; +import { branchLabel, branchTitle } from './worktreeModel.ts'; +import { + changeCounts, composerAction, diffLinesForCard, displayPath, formatTokens, lastUserIndex, slashSuggestions, TOOL_ICONS, toolStatusLabel, turnChanges, +} from './chatModel.ts'; + +/** + * One agent chat (AF3, #268): a normal coding chat, the way the person works + * with Claude Code, Codex, Gemini CLI or the built-in agent. It is drawn in an + * editor tab of the agent-first workbench: + * - the transcript: the person's messages, the agent's Markdown answers, its + * thinking (collapsed), a card per tool call (read, edit, run...) with its + * diff or terminal output, and approval cards; + * - the agent's plan, pinned above the composer as a checklist; + * - the composer: `@` attachments, the agent's slash commands, its modes and + * options (model, reasoning...), Send, Stop, and messages queued while the + * agent works. + * The state is the shared `AgentSessionState`; every change arrives as a + * `SessionEvent` and goes through the same reducer the main process uses. + */ + +export interface ChatViewDeps { + readonly api: AgentSessionsApi; + readonly attachments: AttachmentSources; + openFile(path: string, line?: number): void; + copy(text: string): void; + onStatus(message: string): void; + /** Called whenever the title or status changes, so the tab and the sessions list follow. */ + onDidChange?(state: AgentSessionState): void; + /** AF6: puts the project's files back as they were before a message. */ + restoreCheckpoint?(state: AgentSessionState, checkpointId: string): Promise; + /** AF6: the files a restore would write, for the inline confirmation (without it, the restore runs at once). */ + previewRestore?(state: AgentSessionState, checkpointId: string): Promise; + /** AF5: opens the review of the chat's pending changes. */ + openChanges?(state: AgentSessionState): void; + /** AF9: lets the analysis add its line under a finished turn. */ + decorateTurn?(state: AgentSessionState, turnStart: number, footer: HTMLElement): void; +} + +export interface ChatView { + readonly element: HTMLElement; + readonly sessionId: string; + readonly state: AgentSessionState | null; + /** 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). */ + insert(text: string): void; + reload(): Promise; + dispose(): void; +} + +const ICONS = { + send: 'M5 12h14M13 6l6 6-6 6', + stop: 'M7 7h10v10H7z', + changes: 'M6 3v12M6 15a3 3 0 1 0 0 6a3 3 0 1 0 0-6zM18 9a3 3 0 1 0 0-6a3 3 0 1 0 0 6zM18 9c0 6-12 3-12 6', + restore: 'M4 12a8 8 0 1 0 3-6.2M4 4v5h5', + copy: 'M8 8h11v12H8zM5 16V4h11', + chevron: 'M9 6l6 6-6 6', + branch: 'M6 3v12M6 15a3 3 0 1 0 0 6a3 3 0 1 0 0-6zM18 9a3 3 0 1 0 0-6a3 3 0 1 0 0 6zM18 9c0 4-4 5-12 6', +} as const; + +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; + + // ---- Header ------------------------------------------------------------ + const title = el('h2', { className: 'af-chat-title', text: 'Chat' }); + 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' })]); + changesButton.addEventListener('click', () => { + if (state) { + deps.openChanges?.(state); + } + }); + const usageMeter = el('span', { className: 'af-usage muted', attrs: { hidden: '', 'data-testid': 'af-chat-usage' } }); + // 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' })]); + worktreeButton.addEventListener('click', () => { + worktreeBar.toggle(); + worktreeButton.setAttribute('aria-expanded', String(worktreeBar.isOpen)); + }); + const header = el('header', { className: 'af-chat-header' }, [ + el('div', { className: 'af-chat-heading' }, [title, el('div', { className: 'af-chat-sub' }, [agentLabel, branchBadge, statusPill])]), + usageMeter, + worktreeButton, + changesButton, + ]); + + // ---- 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.' }), + ]); + transcript.append(empty); + let stickToBottom = true; + transcript.addEventListener('scroll', () => { + stickToBottom = transcript.scrollHeight - transcript.scrollTop - transcript.clientHeight < 40; + }); + + // ---- Plan -------------------------------------------------------------- + const planList = el('ol', { className: 'af-plan-list' }); + const planSummary = el('summary', { className: 'af-plan-summary' }); + 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' } }); + const bar = createAttachmentBar(input, deps.attachments); + const slashPopup = el('ul', { className: 'chat-mention af-slash', attrs: { role: 'listbox', hidden: '', 'aria-label': 'Commands' } }); + let slashItems: ReturnType = []; + let slashSelected = 0; + 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 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 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, 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]); + + // ---- Rendering --------------------------------------------------------- + function schedule(): void { + if (frame || disposed) { + return; + } + frame = requestAnimationFrame(() => { + frame = 0; + render(); + }); + } + + function render(): void { + if (!state) { + return; + } + title.textContent = state.title; + agentLabel.textContent = state.agentName; + statusPill.textContent = statusText(state); + statusPill.dataset['status'] = state.status; + changesButton.hidden = state.pendingChanges === 0 || !deps.openChanges; + changesButton.lastElementChild!.textContent = `Changes (${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`; + } + const worktree = state.worktree; + branchBadge.hidden = !worktree; + worktreeButton.hidden = !worktree; + if (worktree) { + branchBadge.textContent = worktree.removed ? `${branchLabel(worktree)} (discarded)` : branchLabel(worktree); + branchBadge.title = branchTitle(worktree); + worktreeBar.update(state); + } + renderItems(state); + markStreaming(state); + renderPlan(state.plan); + renderControls(state); + updateSendButton(); + if (stickToBottom) { + transcript.scrollTop = transcript.scrollHeight; + } + } + + /** The caret sits on the reply being written, and only while the turn runs (rendered nodes are cached). */ + function markStreaming(current: AgentSessionState): void { + for (const node of transcript.querySelectorAll('.af-message.is-streaming')) { + node.classList.remove('is-streaming'); + } + const last = current.items.at(-1); + if (last?.kind === 'assistant' && current.status === 'running') { + rendered.get(`assistant:${last.id}`)?.node.classList.add('is-streaming'); + } + } + + function renderItems(current: AgentSessionState): void { + empty.hidden = current.items.length > 0; + const seen = new Set(); + let previous: Node = empty; + current.items.forEach((item, index) => { + const key = `${item.kind}:${item.id}`; + seen.add(key); + const cached = rendered.get(key); + let node: HTMLElement; + if (cached && cached.item === item) { + node = cached.node; + } else { + node = renderItem(item, index, current); + if (cached) { + cached.node.replaceWith(node); + } + rendered.set(key, { item, node }); + } + if (previous.nextSibling !== node) { + transcript.insertBefore(node, previous.nextSibling); + } + previous = node; + }); + for (const [key, entry] of rendered) { + if (!seen.has(key)) { + entry.node.remove(); + rendered.delete(key); + } + } + } + + function renderItem(item: TranscriptItem, index: number, current: AgentSessionState): HTMLElement { + switch (item.kind) { + 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 checkpoint = item.checkpoint; + const confirmBox = el('div', { className: 'af-restore-confirm', attrs: { hidden: '', role: 'group', 'aria-label': 'Restore files', 'data-testid': 'af-restore-confirm' } }); + restore.addEventListener('click', () => { + if (state) { + restore.disabled = true; + confirmRestore(state, checkpoint, confirmBox).finally(() => { + restore.disabled = false; + }); + } + }); + actions.append(restore, confirmBox); + } + 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; + return el('div', { className: 'af-message is-user', attrs: { 'data-testid': 'af-user' } }, [ + el('p', { className: 'af-user-text', text: item.text }), + ...(chips ? [chips] : []), + actions, + ]); + } + case 'assistant': { + const body = el('div', { className: 'af-message-body' }); + body.append(renderMarkdown(item.text, { copy: deps.copy })); + return el('div', { className: 'af-message is-assistant', attrs: { 'data-testid': 'af-assistant' } }, [body]); + } + case 'thought': + return el('details', { className: 'af-thought' }, [ + el('summary', { text: 'Thinking' }), + el('div', { className: 'af-thought-body', text: item.text }), + ]); + case 'tool': + return renderTool(item, current); + case 'permission': + return renderPermission(item); + case 'notice': + return el('p', { className: `af-notice is-${item.level}`, text: item.text, attrs: { role: item.level === 'error' ? 'alert' : 'note' } }); + case 'turn-end': + return renderTurnEnd(item, index, current); + } + } + + function renderTool(item: Extract, current: AgentSessionState): HTMLElement { + const location = item.locations[0]; + const head = el('summary', { className: 'af-tool-head' }, [ + icon(ICONS.chevron, 'af-tool-chevron'), + icon(TOOL_ICONS[item.toolKind], 'af-tool-icon'), + el('span', { className: 'af-tool-title', text: item.title }), + ...(location ? [fileLink(location.path, location.line, workRootOf(current))] : []), + el('span', { className: 'af-tool-status', text: toolStatusLabel(item.status), attrs: { 'data-status': item.status } }), + ]); + const body = el('div', { className: 'af-tool-body' }); + for (const block of item.content) { + body.append(renderToolContent(block, workRootOf(current))); + } + if (item.rawInput && item.content.length === 0) { + body.append(el('pre', { className: 'af-tool-raw', text: item.rawInput })); + } + // Edits and running commands open by default: they are what the person reviews. + const open = item.content.some((block) => block.type === 'diff' || block.type === 'terminal') || item.status === 'failed'; + const card = el('details', { className: 'af-tool', attrs: { 'data-kind': item.toolKind, 'data-status': item.status, 'data-testid': 'af-tool' } }, [head, body]); + card.open = open; + return card; + } + + function renderToolContent(block: ToolContentView, root: string | null): HTMLElement { + switch (block.type) { + case 'text': { + const wrap = el('div', { className: 'af-tool-text' }); + wrap.append(renderMarkdown(block.text, { copy: deps.copy })); + return wrap; + } + case 'diff': { + const counts = changeCounts(block.oldText, block.newText); + const lines = diffLinesForCard(block.oldText, block.newText); + const pre = el('pre', { className: 'af-diff' }, lines.map((line) => el('span', { + className: `af-diff-line is-${line.kind}`, + text: line.kind === 'gap' ? (line.text || '...') : `${line.kind === 'add' ? '+' : line.kind === 'remove' ? '-' : ' '} ${line.text}`, + }))); + return el('div', { className: 'af-diff-block' }, [ + el('div', { className: 'af-diff-head' }, [ + fileLink(block.path, undefined, root), + el('span', { className: 'af-diff-counts' }, [el('span', { className: 'is-add', text: `+${counts.added}` }), el('span', { className: 'is-remove', text: ` -${counts.removed}` })]), + ]), + pre, + ]); + } + 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)' : ''}` })] : []), + ]); + } + } + + function renderPermission(item: Extract): HTMLElement { + const card = el('div', { className: 'af-permission', attrs: { role: 'group', 'aria-label': item.title, 'data-testid': 'af-permission' } }, [ + el('p', { className: 'af-permission-title', text: item.title }), + ]); + 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}` })); + return card; + } + const buttons = el('div', { className: 'af-permission-actions' }, item.options.map((option) => { + const button = el('button', { + className: option.kind.startsWith('allow') ? (option.kind === 'allow_once' ? 'primary-button' : 'secondary-button') : 'secondary-button is-danger', + text: option.name, + attrs: { type: 'button', 'data-kind': option.kind }, + }); + button.addEventListener('click', () => { + for (const other of buttons.querySelectorAll('button')) { + other.disabled = true; + } + deps.api.respondPermission(sessionId, item.id, option.id).catch((error: unknown) => deps.onStatus(errorText(error))); + }); + return button; + })); + card.append(buttons); + return card; + } + + function renderTurnEnd(item: Extract, index: number, current: AgentSessionState): HTMLElement { + const footer = el('div', { className: 'af-turn-end', attrs: { 'data-reason': item.stopReason } }); + let start = 0; + for (let cursor = index - 1; cursor >= 0; cursor -= 1) { + if (current.items[cursor]?.kind === 'user') { + start = cursor; + break; + } + } + 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:` }), + ...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]; + if (reason) { + footer.append(el('p', { className: `af-stop muted${item.stopReason === 'error' ? ' is-error' : ''}`, text: reason })); + } + if (item.metricDelta) { + footer.append(renderMetricDelta(item.metricDelta)); + } + deps.decorateTurn?.(current, start, footer); + return footer; + } + + /** AF9: "Complexity max 9 -> 1, LOC -6", the per-file detail folded under it. */ + 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('p', { className: 'muted', text: delta.summary }), + ...(lines.length > 0 ? [el('ul', { className: 'af-metric-delta-files' }, lines.map((line) => el('li', { text: line })))] : []), + ]); + } + + /** AF6: lists what a restore would write, inline under the message, and restores on confirmation. */ + async function confirmRestore(current: AgentSessionState, checkpoint: string, box: HTMLElement): Promise { + if (!deps.previewRestore) { + await deps.restoreCheckpoint?.(current, checkpoint).catch((error: unknown) => deps.onStatus(errorText(error))); + return; + } + let paths: readonly string[]; + try { + paths = await deps.previewRestore(current, checkpoint); + } catch (error) { + deps.onStatus(errorText(error)); + return; + } + const close = (): void => { + box.hidden = true; + box.replaceChildren(); + }; + const cancel = el('button', { className: 'secondary-button', text: paths.length === 0 ? 'Close' : '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' } }); + confirm.addEventListener('click', () => { + confirm.disabled = true; + cancel.disabled = true; + (deps.restoreCheckpoint?.(current, checkpoint) ?? Promise.resolve()) + .then(close, (error: unknown) => { + deps.onStatus(errorText(error)); + confirm.disabled = false; + cancel.disabled = false; + }); + }); + const shown = paths.slice(0, 20); + box.replaceChildren( + 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` })] : []), + ])] : []), + el('div', { className: 'af-restore-actions' }, paths.length === 0 ? [cancel] : [confirm, cancel]), + ); + box.hidden = false; + (paths.length === 0 ? cancel : confirm).focus(); + } + + 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}` } }); + 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.`); + return; + } + deps.openFile(path, line); + }); + return link; + } + + function renderPlan(entries: readonly PlanEntryView[]): void { + plan.hidden = entries.length === 0; + if (entries.length === 0) { + return; + } + const done = entries.filter((entry) => entry.status === 'completed').length; + planSummary.textContent = `Plan: ${done} of ${entries.length} done`; + 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 }), + ]))); + } + + let renderedModes = ''; + let renderedOptions = ''; + function renderControls(current: AgentSessionState): void { + const modesKey = JSON.stringify(current.modes); + if (modesKey !== renderedModes) { + renderedModes = modesKey; + modeSelect.hidden = !current.modes || current.modes.available.length === 0; + modeSelect.replaceChildren(...(current.modes?.available ?? []).map((mode) => { + const option = el('option', { text: mode.name, attrs: { value: mode.id, title: mode.description ?? '' } }); + option.selected = mode.id === current.modes?.current; + return option; + })); + } + const optionsKey = JSON.stringify(current.configOptions); + if (optionsKey !== renderedOptions) { + renderedOptions = optionsKey; + optionsSlot.replaceChildren(...current.configOptions.map((option) => configSelect(option))); + } + } + + function configSelect(option: ConfigOptionView): HTMLSelectElement { + const select = el('select', { className: 'af-select', attrs: { 'aria-label': option.name, title: option.name, 'data-option': option.id } }); + select.append(...option.values.map((value) => { + const node = el('option', { text: value.name, attrs: { value: value.id, title: value.description ?? '' } }); + node.selected = value.id === option.current; + return node; + })); + select.addEventListener('change', () => { + deps.api.setConfigOption(sessionId, option.id, select.value).catch((error: unknown) => deps.onStatus(errorText(error))); + }); + return select; + } + + modeSelect.addEventListener('change', () => { + deps.api.setMode(sessionId, modeSelect.value).catch((error: unknown) => deps.onStatus(errorText(error))); + }); + + // ---- Composer behaviour ------------------------------------------------ + 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'; + sendButton.setAttribute('aria-label', label); + sendButton.title = action === 'stop' ? 'Stop (Esc)' : action === 'queue' ? label : 'Send (Enter)'; + 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.`; + } + + 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 submit(): void { + if (!state) { + return; + } + const action = composerAction(state, input.value); + if (action === 'stop') { + deps.api.cancel(sessionId).catch((error: unknown) => deps.onStatus(errorText(error))); + return; + } + if (action === 'none') { + return; + } + const text = input.value; + const attachments = toPromptAttachments(bar.items()); + input.value = ''; + bar.clear(); + hideSlash(); + stickToBottom = true; + if (action === 'queue') { + queue.push({ text, attachments }); + updateSendButton(); + return; + } + send(text, attachments); + } + + function send(text: string, attachments: PromptAttachment[]): void { + deps.api.prompt(sessionId, text, attachments).catch((error: unknown) => deps.onStatus(errorText(error))); + } + + function drainQueue(): void { + if (!state || state.status === 'running' || state.status === 'awaiting') { + return; + } + const next = queue.shift(); + if (next) { + send(next.text, next.attachments); + } + updateSendButton(); + } + + function showSlash(): void { + slashItems = state ? slashSuggestions(input.value, state.commands) : []; + 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) } }, [ + el('span', { className: 'af-slash-name', text: `/${command.name}` }), + el('span', { className: 'muted', text: ` ${command.description}` }), + ]); + row.addEventListener('mousedown', (event) => { + event.preventDefault(); + pickSlash(index); + }); + return row; + })); + } + + function hideSlash(): void { + slashItems = []; + slashPopup.hidden = true; + } + + function pickSlash(index: number): void { + const command = slashItems[index]; + if (command) { + input.value = `/${command.name} `; + hideSlash(); + input.focus(); + updateSendButton(); + } + } + + input.addEventListener('input', () => { + slashSelected = 0; + showSlash(); + updateSendButton(); + }); + input.addEventListener('keydown', (event) => { + if (!slashPopup.hidden && slashItems.length > 0) { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); + slashSelected = (slashSelected + (event.key === 'ArrowDown' ? 1 : slashItems.length - 1)) % slashItems.length; + showSlash(); + return; + } + if (event.key === 'Tab' || (event.key === 'Enter' && !event.shiftKey)) { + event.preventDefault(); + pickSlash(slashSelected); + return; + } + if (event.key === 'Escape') { + event.preventDefault(); + hideSlash(); + return; + } + } + if (bar.handleKey(event)) { + return; + } + if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + 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))); + } + }); + sendButton.addEventListener('click', submit); + + // ---- Lifecycle --------------------------------------------------------- + async function reload(): Promise { + const loaded = await deps.api.get(sessionId); + if (disposed) { + return; + } + state = loaded; + rendered.forEach((entry) => entry.node.remove()); + rendered.clear(); + render(); + deps.onDidChange?.(state); + if (state.unread) { + deps.api.markRead(sessionId).catch(() => undefined); + } + } + + reload().catch((error: unknown) => { + transcript.append(el('p', { className: 'af-notice is-error', text: `Could not open this chat: ${errorText(error)}` })); + }); + + return { + element, + sessionId, + get state() { + return state; + }, + handle(message: AgentSessionMessage): void { + if (message.kind !== 'event' || message.sessionId !== sessionId || !state) { + return; + } + const before = state; + state = applySessionEvent(state, message.event, message.updatedAt); + if (message.event.type === 'turn-end') { + // The person is looking at this chat: what just finished is read. + if (element.isConnected) { + deps.api.markRead(sessionId).catch(() => undefined); + } + queueMicrotask(drainQueue); + } + if (before.title !== state.title || before.status !== state.status || before.pendingChanges !== state.pendingChanges) { + deps.onDidChange?.(state); + } + schedule(); + }, + focus(): void { + input.focus(); + }, + insert(text: string): void { + input.value = input.value ? `${input.value}\n${text}` : text; + input.focus(); + updateSendButton(); + }, + reload, + dispose(): void { + disposed = true; + if (frame) { + cancelAnimationFrame(frame); + } + }, + }; +} + +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.', +}; + +/** AF12: the folder the agent's paths are relative to: its worktree, or the project. */ +function workRootOf(state: AgentSessionState): string | null { + return state.worktree ? state.worktree.cwd : state.workspaceRoot; +} + +function statusText(state: AgentSessionState): string { + switch (state.status) { + case 'idle': + return 'Ready'; + case 'running': + return 'Working'; + case 'awaiting': + return 'Needs your approval'; + case 'error': + return 'Error'; + } +} + +function errorText(error: unknown): string { + return (error instanceof Error ? error.message : String(error)).replace(/^Error invoking remote method '[^']+': (Error: )?/, ''); +} + +export { lastUserIndex }; diff --git a/apps/ide/src/renderer/agentFirst/gettingStartedView.ts b/apps/ide/src/renderer/agentFirst/gettingStartedView.ts new file mode 100644 index 000000000..557fac9e7 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/gettingStartedView.ts @@ -0,0 +1,119 @@ +import type { AgentView } from '../../shared/agentSession.ts'; +import { el } from '../dom.ts'; +import { agentActions, type AgentSetupDeps } from './agentSetup.ts'; +import { availabilityLabel } from './sessionsModel.ts'; +import { guideAgent, isUsable, onboardingSteps, type OnboardingStep } from './agentSetupModel.ts'; + +/** + * The first-run guide (AF13, #278): from an empty window to a first chat in + * three steps (open a folder, pick an agent and install it or sign in, start + * the chat), each drawn from the real state of the window and redrawn when it + * changes. Shown in the editor area on the first run, skippable, and opened + * again with "Chat: Show Getting Started". + */ + +export interface GettingStartedDeps { + readonly setup: AgentSetupDeps; + hasFolder(): boolean; + hasChat(): boolean; + agents(): readonly AgentView[]; + openFolder(): void; + /** Starts the first chat with an agent; the guide is done. */ + startChat(agentRef: string): Promise; + /** Skip: the guide does not open on its own again. */ + skip(): void; +} + +export interface GettingStartedView { + readonly element: HTMLElement; + /** Redraws from the current state (folder, agents, chats). */ + render(): void; +} + +const MARK: Record = { done: 'Done', current: 'Next', todo: 'Then' }; + +export function createGettingStartedView(deps: GettingStartedDeps): GettingStartedView { + let chosen: string | null = null; + const steps = el('ol', { className: 'af-guide-steps' }); + const skip = el('button', { className: 'af-link-button af-guide-skip', text: 'Skip', attrs: { type: 'button', title: 'Close the guide; reopen it with Chat: Show Getting Started', 'data-testid': 'af-guide-skip' } }); + skip.addEventListener('click', () => deps.skip()); + 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: 'Get started', attrs: { id: 'af-guide-title' } }), + el('p', { className: 'muted af-guide-lead', text: 'Three steps to your first chat with a coding agent on your project.' }), + ]), + skip, + ]), + steps, + ]); + + function folderBody(step: OnboardingStep): HTMLElement[] { + if (step.state === 'done') { + return []; + } + const open = el('button', { className: 'primary-button af-small-button', text: 'Open Folder...', attrs: { type: 'button', 'data-testid': 'af-guide-open-folder' } }); + open.addEventListener('click', () => deps.openFolder()); + return [el('div', { className: 'af-guide-actions' }, [open])]; + } + + function agentBody(): HTMLElement[] { + const agents = deps.agents().filter((agent) => agent.kind === 'acp' && agent.preset); + if (agents.length === 0) { + return [el('p', { className: 'muted', text: 'Looking for agents...' })]; + } + const selected = guideAgent({ agents: deps.agents(), chosen })?.ref ?? null; + return [el('ul', { className: 'af-guide-agents' }, agents.map((agent) => { + const radio = el('input', { attrs: { type: 'radio', name: 'af-guide-agent', value: agent.ref, 'aria-label': `Use ${agent.name}` } }); + radio.checked = agent.ref === selected; + radio.disabled = !isUsable(agent); + radio.addEventListener('change', () => { + chosen = agent.ref; + render(); + }); + return el('li', { className: 'af-guide-agent', attrs: { 'data-availability': agent.availability, 'data-ref': agent.ref } }, [ + el('label', { className: 'af-guide-agent-main' }, [ + radio, + el('span', { className: 'af-agent-name', text: agent.name }), + el('span', { className: 'af-badge', attrs: { 'data-availability': agent.availability }, text: availabilityLabel(agent) }), + ]), + ...(agent.detail && agent.availability !== 'available' && agent.availability !== 'ready' ? [el('p', { className: 'muted af-agent-detail', text: agent.detail })] : []), + agentActions(agent, deps.setup), + ]); + }))]; + } + + function chatBody(step: OnboardingStep): HTMLElement[] { + const agent = guideAgent({ agents: deps.agents(), chosen }); + const start = el('button', { className: 'primary-button af-small-button', text: agent ? `Start a chat with ${agent.name}` : 'Start a chat', attrs: { type: 'button', 'data-testid': 'af-guide-start' } }); + start.disabled = !agent || !deps.hasFolder(); + start.title = !deps.hasFolder() ? 'Open a folder first' : !agent ? 'Install or sign in to an agent first' : ''; + start.addEventListener('click', () => { + if (agent) { + start.disabled = true; + deps.startChat(agent.ref).finally(() => { + start.disabled = false; + }); + } + }); + return step.state === 'done' && deps.hasChat() ? [] : [el('div', { className: 'af-guide-actions' }, [start])]; + } + + function render(): void { + const all = onboardingSteps({ hasFolder: deps.hasFolder(), agents: deps.agents(), chosen, hasChat: deps.hasChat() }); + steps.replaceChildren(...all.map((step, index) => el('li', { className: 'af-guide-step', attrs: { 'data-state': step.state, 'data-step': step.id } }, [ + el('span', { className: 'af-guide-number', text: String(index + 1), attrs: { 'aria-hidden': 'true' } }), + el('div', { className: 'af-guide-body' }, [ + el('h3', { className: 'af-guide-step-title' }, [ + el('span', { text: step.title }), + el('span', { className: 'af-guide-state', text: MARK[step.state] }), + ]), + el('p', { className: 'muted af-guide-text', text: step.text }), + ...(step.id === 'folder' ? folderBody(step) : step.id === 'agent' ? agentBody() : chatBody(step)), + ]), + ]))); + } + + render(); + return { element, render }; +} diff --git a/apps/ide/src/renderer/agentFirst/instructionsModel.ts b/apps/ide/src/renderer/agentFirst/instructionsModel.ts new file mode 100644 index 000000000..70d4fc0e3 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/instructionsModel.ts @@ -0,0 +1,75 @@ +/** + * Project instructions for agents (AF11, #276): the files each agent reads on + * its own at the start of a chat, so the person writes the project's rules + * once and every agent follows them. No DOM. + * + * AGENTS.md is the shared format (read by Codex, Gemini CLI with its + * `contextFileName` setting, and most other agents). Claude Code reads + * CLAUDE.md, which can import AGENTS.md with an `@AGENTS.md` line, so one + * file serves both. + */ + +export interface InstructionFileKind { + /** Workspace path, `/`-separated. */ + readonly path: string; + readonly label: string; + /** Which agents read it. */ + readonly readBy: string; + /** The starting text when the person creates it from the panel. */ + readonly template: string; +} + +export const AGENTS_TEMPLATE = `# AGENTS.md + +Instructions for AI coding agents working on this project. + +## Project +- What it is and who uses it. + +## Commands +- Install: +- Build: +- Test: + +## Conventions +- Code style and naming. +- Where new code goes. + +## Rules +- Run the tests before saying a change is done. +- Never commit secrets. +`; + +export const INSTRUCTION_FILES: readonly InstructionFileKind[] = [ + { path: 'AGENTS.md', label: 'AGENTS.md', readBy: 'Codex, Gemini CLI and most agents', template: AGENTS_TEMPLATE }, + { path: 'CLAUDE.md', label: 'CLAUDE.md', readBy: 'Claude Code', template: '# CLAUDE.md\n\n@AGENTS.md\n' }, + { path: 'GEMINI.md', label: 'GEMINI.md', readBy: 'Gemini CLI', template: '# GEMINI.md\n\nFollow the instructions in AGENTS.md.\n' }, + { path: '.github/copilot-instructions.md', label: 'Copilot instructions', readBy: 'GitHub Copilot', template: '# Copilot instructions\n\nFollow the instructions in AGENTS.md.\n' }, +]; + +export interface InstructionEntry extends InstructionFileKind { + readonly exists: boolean; +} + +/** The known instruction files with whether the project has each (paths compared case-insensitively). */ +export function instructionEntries(files: readonly string[]): InstructionEntry[] { + const present = new Set(files.map((file) => file.replace(/\\/g, '/').toLowerCase())); + return INSTRUCTION_FILES.map((kind) => ({ ...kind, exists: present.has(kind.path.toLowerCase()) })); +} + +/** Other rule files found in the project (Cursor rules, nested AGENTS.md...), shown read-only. */ +export function otherRuleFiles(files: readonly string[], limit = 20): string[] { + const known = new Set(INSTRUCTION_FILES.map((kind) => kind.path.toLowerCase())); + return files + .map((file) => file.replace(/\\/g, '/')) + .filter((file) => !known.has(file.toLowerCase())) + .filter((file) => /(^|\/)(agents|claude|gemini)\.md$/i.test(file) || /^\.cursor\/rules\/.+\.mdc?$/i.test(file) || /^\.cursorrules$/i.test(file) || /^\.windsurfrules$/i.test(file) || /^\.github\/instructions\/.+\.md$/i.test(file)) + .sort() + .slice(0, limit); +} + +/** 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('/'); + return index < 0 ? { parent: '', name: path } : { parent: path.slice(0, index), name: path.slice(index + 1) }; +} diff --git a/apps/ide/src/renderer/agentFirst/instructionsView.ts b/apps/ide/src/renderer/agentFirst/instructionsView.ts new file mode 100644 index 000000000..e8950065d --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/instructionsView.ts @@ -0,0 +1,98 @@ +import { el } from '../dom.ts'; +import { instructionEntries, otherRuleFiles, splitWorkspacePath, type InstructionEntry } from './instructionsModel.ts'; + +/** + * The "Project instructions" section of the Chats view (AF11, #276): which + * instruction files the open project has, a click to open one, and a click + * to create a missing one from a short template. The agents read these files + * themselves; Code-XR only helps write them. + */ + +export interface InstructionsViewDeps { + listFiles(): Promise; + createEntry(parent: string, name: string, kind: 'file' | 'directory'): Promise; + writeFile(path: string, text: string): Promise; + openFile(path: string): void; + hasFolder(): boolean; + onStatus(message: string): void; +} + +export interface InstructionsView { + readonly element: HTMLElement; + refresh(): Promise; +} + +export function createInstructionsView(deps: InstructionsViewDeps): InstructionsView { + const list = el('ul', { className: 'af-instr-list', attrs: { 'data-testid': 'af-instructions' } }); + const note = el('p', { className: 'muted af-agents-note', text: 'Write the project\'s rules once: every agent reads its file at the start of a chat.' }); + const element = el('details', { className: 'af-agents af-instructions' }, [ + el('summary', { className: 'af-section-title' }, [el('span', { text: 'Project instructions' })]), + list, + note, + ]); + let generation = 0; + + async function create(entry: InstructionEntry): Promise { + const { parent, name } = splitWorkspacePath(entry.path); + try { + if (parent) { + await deps.createEntry('', parent, 'directory').catch(() => undefined); + } + const path = await deps.createEntry(parent, name, 'file'); + await deps.writeFile(path, entry.template); + deps.openFile(path); + await refresh(); + } catch (error) { + deps.onStatus(`Could not create ${entry.path}: ${error instanceof Error ? error.message : String(error)}`); + } + } + + async function refresh(): Promise { + const mine = ++generation; + if (!deps.hasFolder()) { + list.replaceChildren(el('li', { className: 'muted af-instr-empty', text: 'Open a folder to see its instructions.' })); + return; + } + let files: readonly string[] = []; + try { + files = await deps.listFiles(); + } catch { + files = []; + } + if (mine !== generation) { + return; + } + const rows = instructionEntries(files).map((entry) => { + const action = el('button', { + className: 'af-link-button', + text: entry.exists ? 'Open' : 'Create', + attrs: { type: 'button', 'data-testid': `af-instr-${entry.exists ? 'open' : 'create'}`, title: entry.exists ? `Open ${entry.path}` : `Create ${entry.path} from a template` }, + }); + action.addEventListener('click', () => { + if (entry.exists) { + deps.openFile(entry.path); + } else { + void create(entry); + } + }); + return el('li', { className: 'af-instr', attrs: { 'data-exists': String(entry.exists) } }, [ + el('span', { className: 'af-instr-main' }, [ + el('span', { className: 'af-instr-name', text: entry.label }), + el('span', { className: 'af-session-sub muted', text: `Read by ${entry.readBy}` }), + ]), + action, + ]); + }); + for (const path of otherRuleFiles(files)) { + const open = el('button', { className: 'af-link-button', text: 'Open', attrs: { type: 'button' } }); + open.addEventListener('click', () => deps.openFile(path)); + rows.push(el('li', { className: 'af-instr', attrs: { 'data-exists': 'true' } }, [ + el('span', { className: 'af-instr-main' }, [el('span', { className: 'af-instr-name', text: path })]), + open, + ])); + } + list.replaceChildren(...rows); + } + + return { element, refresh }; +} diff --git a/apps/ide/src/renderer/agentFirst/sessionsModel.ts b/apps/ide/src/renderer/agentFirst/sessionsModel.ts new file mode 100644 index 000000000..8ed3ffd10 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/sessionsModel.ts @@ -0,0 +1,101 @@ +import type { AgentView, ProjectSessions, SessionStatus, SessionSummary } from '../../shared/agentSession.ts'; + +/** + * Pure helpers of the sessions sidebar (AF7, #272): filtering chats by a + * search, the label and order of statuses, short relative times. No DOM. + */ + +/** The projects whose name or chats match the query; a matching project keeps all its chats. */ +export function filterProjects(projects: readonly ProjectSessions[], query: string): ProjectSessions[] { + const needle = query.trim().toLowerCase(); + if (!needle) { + return [...projects]; + } + const result: ProjectSessions[] = []; + for (const project of projects) { + if (project.name.toLowerCase().includes(needle)) { + result.push(project); + continue; + } + const sessions = project.sessions.filter((session) => session.title.toLowerCase().includes(needle) || session.agentName.toLowerCase().includes(needle)); + if (sessions.length > 0) { + result.push({ ...project, sessions }); + } + } + return result; +} + +/** 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', + }; + return session.unread && session.status === 'idle' ? 'Done, not read yet' : base[session.status]; +} + +/** "now", "5 min", "3 h", "2 d", or a date for older chats. */ +export function shortTime(iso: string, nowMs: number): string { + const then = Date.parse(iso); + if (!Number.isFinite(then)) { + return ''; + } + const seconds = Math.max(0, Math.round((nowMs - then) / 1000)); + if (seconds < 60) { + return 'now'; + } + if (seconds < 3600) { + return `${Math.floor(seconds / 60)} min`; + } + if (seconds < 86_400) { + return `${Math.floor(seconds / 3600)} h`; + } + if (seconds < 7 * 86_400) { + return `${Math.floor(seconds / 86_400)} d`; + } + return new Date(then).toISOString().slice(0, 10); +} + +/** 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 } { + let running = 0; + let waiting = 0; + let unread = 0; + for (const project of projects) { + for (const session of project.sessions) { + if (session.status === 'running') { + running += 1; + } else if (session.status === 'awaiting') { + waiting += 1; + } + if (session.unread) { + unread += 1; + } + } + } + return { running, waiting, unread }; +} + +/** The agent a new chat uses by default: the last one used if still usable, else the first usable one. */ +export function defaultAgent(agents: readonly AgentView[], lastUsed: string | null): AgentView | null { + const usable = agents.filter((agent) => agent.kind === 'acp' && agent.availability !== 'missing'); + return usable.find((agent) => agent.ref === lastUsed) ?? usable.find((agent) => agent.kind === 'acp') ?? usable[0] ?? null; +} + +/** A short description of an agent's state for the agents list. */ +export function availabilityLabel(agent: AgentView): string { + switch (agent.availability) { + case 'missing': + return 'Not installed'; + case 'available': + return 'Installed'; + case 'ready': + return 'Ready'; + case 'needs-login': + return 'Needs login'; + case 'error': + return 'Error'; + } +} diff --git a/apps/ide/src/renderer/agentFirst/sessionsView.ts b/apps/ide/src/renderer/agentFirst/sessionsView.ts new file mode 100644 index 000000000..e02a851e2 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/sessionsView.ts @@ -0,0 +1,474 @@ +import type { AgentSessionMessage, AgentSessionsApi, AgentView, ProjectSessions, SessionSummary } from '../../shared/agentSession.ts'; +import { el, icon } from '../dom.ts'; +import { attentionCounts, availabilityLabel, defaultAgent, filterProjects, shortTime, statusLabel } from './sessionsModel.ts'; +import { agentActions, type AgentSetupDeps } from './agentSetup.ts'; +import { branchLabel, branchTitle, parseWorktreeChoice } from './worktreeModel.ts'; + +/** + * The left column of the agent-first workbench (AF7, #272): the person's + * projects and, under each, its chats with what they are doing (working, + * waiting for an approval, done and not read, failed). Above them, the + * Agent / Classic switch (AF4) and New chat with its agent picker; below, the + * agents the IDE can run and whether each is installed and signed in (AF1, + * AF2). Everything goes through `window.codexr.agentSessions`. + */ + +export interface SessionsViewDeps { + readonly api: AgentSessionsApi; + /** Opens a chat of the window's own folder. */ + openChat(sessionId: string): void; + /** Opens a chat of another project: the window switches folder first. */ + openChatInProject(root: string, sessionId: string): void; + /** Opens another project (from the recent list). */ + openProject(root: string): void; + /** The chat open in the active tab, highlighted in the list. */ + activeChat(): string | null; + onStatus(message: string): void; + /** AF4: the current layout mode and how to change it. */ + 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; + /** Opens a terminal running an agent's login command is handled in main; this shows the terminal panel. */ + showTerminal?(): void; + /** Shows the Agents view, where the IDE's own agents chat (epic #189). */ + openBuiltinAgents?(): void; + /** A chat was deleted: its tab closes. */ + onRemoved?(sessionId: string): void; + /** Sections shown under the agents list (the project instructions of AF11). */ + readonly extraSections?: readonly HTMLElement[]; +} + +export interface SessionsView { + refresh(): Promise; + handle(message: AgentSessionMessage): void; + /** "New chat" with the default agent, or the given one. */ + newChat(agentRef?: string): Promise; + /** Redraws the highlight of the active chat. */ + setActive(sessionId: string | null): void; + agents(): readonly AgentView[]; + /** Reloads the agents list (and starts each installed one once to check it, when `probe`). */ + refreshAgents(probe?: boolean): Promise; + /** Called whenever the agents list changes (the first-run guide follows it). */ + onAgentsChange(listener: (agents: readonly AgentView[]) => void): void; + focusSearch(): void; +} + +const LAST_AGENT_KEY = 'codexr.agentFirst.lastAgent'; +/** AF12: the last state of "Separate worktree". */ +const WORKTREE_CHOICE_KEY = 'codexr.agentFirst.separateWorktree'; +const ICONS = { + plus: 'M12 5v14M5 12h14', + trash: 'M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13', + edit: 'M4 20h4L19 9l-4-4L4 16zM14 6l4 4', + refresh: 'M20 12a8 8 0 1 1-3-6.2M20 4v5h-5', + folder: 'M3 6h7l2 2h9v11H3z', + chevron: 'M9 6l6 6-6 6', +} as const; + +export function createSessionsView(container: HTMLElement, deps: SessionsViewDeps): SessionsView { + let projects: readonly ProjectSessions[] = []; + let agents: readonly AgentView[] = []; + let query = ''; + let active: string | null = null; + const collapsed = new Set(); + let refreshTimer = 0; + + const lastAgent = (): string | null => { + try { + return localStorage.getItem(LAST_AGENT_KEY); + } catch { + return null; + } + }; + const rememberAgent = (ref: string): void => { + try { + localStorage.setItem(LAST_AGENT_KEY, ref); + } catch { + // Storage is a convenience only. + } + }; + + const storedWorktreeChoice = (): boolean => { + try { + return parseWorktreeChoice(localStorage.getItem(WORKTREE_CHOICE_KEY)); + } catch { + return false; + } + }; + const rememberWorktreeChoice = (on: boolean): void => { + try { + localStorage.setItem(WORKTREE_CHOICE_KEY, on ? '1' : '0'); + } catch { + // Storage is a convenience only. + } + }; + + // ---- Mode switch (AF4) ------------------------------------------------- + const agentModeButton = el('button', { className: 'af-mode-button', text: 'Agent', attrs: { type: 'button', 'data-mode': 'agent', title: 'Agent layout: chats, work area and live analysis (Ctrl+Alt+M)' } }); + const classicModeButton = el('button', { className: 'af-mode-button', text: 'Classic', attrs: { type: 'button', 'data-mode': 'classic', title: 'Classic layout: the VS Code-like workbench (Ctrl+Alt+M)' } }); + const modeSwitch = el('div', { className: 'af-mode-switch', attrs: { role: 'group', 'aria-label': 'Layout', 'data-testid': 'af-mode-switch' } }, [agentModeButton, classicModeButton]); + for (const button of [agentModeButton, classicModeButton]) { + button.addEventListener('click', () => { + deps.setMode(button.dataset['mode'] as 'agent' | 'classic'); + renderMode(); + }); + } + function renderMode(): void { + const mode = deps.mode(); + for (const button of [agentModeButton, classicModeButton]) { + const on = button.dataset['mode'] === mode; + button.classList.toggle('is-active', on); + button.setAttribute('aria-pressed', String(on)); + } + } + + // ---- New chat ---------------------------------------------------------- + const agentSelect = el('select', { className: 'af-select af-new-agent', attrs: { 'aria-label': 'Agent for a new chat', 'data-testid': 'af-new-agent' } }); + const newChatButton = el('button', { className: 'primary-button af-new-chat', attrs: { type: 'button', 'data-testid': 'af-new-chat' } }, [icon(ICONS.plus), el('span', { text: 'New chat' })]); + newChatButton.addEventListener('click', () => void newChat(agentSelect.value || undefined)); + + // AF12: "Separate worktree", offered only when the window's folder can have one; the choice is remembered. + const worktreeBox = el('input', { attrs: { type: 'checkbox', 'data-testid': 'af-new-worktree' } }); + worktreeBox.checked = storedWorktreeChoice(); + worktreeBox.addEventListener('change', () => rememberWorktreeChoice(worktreeBox.checked)); + const worktreeOption = el('label', { + className: 'af-new-worktree', + attrs: { hidden: '', title: 'Run the new chat\'s agent in its own git worktree and branch, outside the project, so several agents can work in parallel. Merge or discard its work from the chat\'s Worktree bar.' }, + }, [worktreeBox, el('span', { text: 'Separate worktree' })]); + /** The folder the availability was read for, so it is read again only when the folder changes. */ + let worktreeRoot: string | null | undefined; + let worktreeAvailable = false; + async function refreshWorktreeAvailability(root: string | null): Promise { + if (root === worktreeRoot) { + return; + } + worktreeRoot = root; + const availability = root ? await deps.api.worktreeAvailability().catch(() => ({ ok: false, message: null })) : { ok: false, message: null }; + if (worktreeRoot !== root) { + return; + } + worktreeAvailable = availability.ok; + worktreeOption.hidden = !availability.ok; + } + // Trust or the repository (a first commit) may change while the folder stays: read it again on focus. + window.addEventListener('focus', () => { + const root = worktreeRoot; + worktreeRoot = undefined; + void refreshWorktreeAvailability(root ?? null); + }); + + 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('input', () => { + query = search.value; + renderProjects(); + }); + + // ---- Lists ------------------------------------------------------------- + const projectList = el('div', { className: 'af-projects', attrs: { 'data-testid': 'af-projects' } }); + 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)); + const agentsSection = el('details', { className: 'af-agents', attrs: { open: '' } }, [ + el('summary', { className: 'af-section-title' }, [el('span', { text: 'Agents' }), agentsRefresh]), + agentList, + el('p', { className: 'muted af-agents-note', text: 'Claude Code, Codex and Gemini CLI run with their own sign-in: your subscription or API key stays with the vendor\'s tool, and Code-XR never sees its tokens.' }), + ]); + + container.replaceChildren(el('div', { className: 'af-sessions' }, [ + modeSwitch, + el('div', { className: 'af-new-row' }, [newChatButton, agentSelect]), + worktreeOption, + search, + el('h3', { className: 'af-section-title', text: 'Projects' }), + projectList, + agentsSection, + ...(deps.extraSections ?? []), + ])); + renderMode(); + + const agentListeners: ((list: readonly AgentView[]) => void)[] = []; + const setupDeps: AgentSetupDeps = { + api: deps.api, + onStatus: deps.onStatus, + ...(deps.showTerminal ? { showTerminal: deps.showTerminal } : {}), + refresh: (probe) => refreshAgents(probe), + replace: (view) => { + agents = agents.map((other) => (other.ref === view.ref ? view : other)); + renderAgents(); + }, + }; + + function iconButton(label: string, path: string, onClick: () => void): HTMLButtonElement { + const button = el('button', { className: 'icon-button', attrs: { type: 'button', title: label, 'aria-label': label } }, [icon(path)]); + button.addEventListener('click', (event) => { + event.preventDefault(); + event.stopPropagation(); + onClick(); + }); + return button; + } + + function renderAgents(): void { + const chosen = agentSelect.value || defaultAgent(agents, lastAgent())?.ref || ''; + // The IDE's own agents (epic #189) keep their chat in the Agents view for now. + agentSelect.replaceChildren(...agents.filter((agent) => agent.kind === 'acp').map((agent) => { + const option = el('option', { text: agent.availability === 'missing' ? `${agent.name} (not installed)` : agent.name, attrs: { value: agent.ref } }); + option.disabled = agent.availability === 'missing'; + option.selected = agent.ref === chosen; + return option; + })); + newChatButton.disabled = !agents.some((agent) => agent.kind === 'acp' && agent.availability !== 'missing'); + const builtins = agents.filter((agent) => agent.kind === 'builtin'); + const builtinRow: HTMLElement[] = []; + if (builtins.length > 0) { + const open = el('button', { className: 'secondary-button af-small-button', text: 'Open', attrs: { type: 'button', title: 'Chat with these agents in the Agents view' } }); + open.addEventListener('click', () => deps.openBuiltinAgents?.()); + builtinRow.push(el('li', { className: 'af-agent', attrs: { 'data-availability': 'available', 'data-ref': 'builtin' } }, [ + el('div', { className: 'af-agent-main' }, [el('span', { className: 'af-agent-name', text: 'IDE agents' }), el('span', { className: 'af-badge', text: String(builtins.length) })]), + el('p', { className: 'muted af-agent-detail', text: `${builtins.map((agent) => agent.name).join(', ')}: the IDE's own agents, with a provider and API key set up in the Agents view.` }), + ...(deps.openBuiltinAgents ? [el('span', { className: 'af-agent-actions' }, [open])] : []), + ])); + } + agentList.replaceChildren(...agents.filter((agent) => agent.kind === 'acp').map((agent) => el('li', { className: 'af-agent', attrs: { 'data-availability': agent.availability, 'data-ref': agent.ref } }, [ + el('div', { className: 'af-agent-main' }, [ + el('span', { className: 'af-agent-name', text: agent.name }), + ...(agent.installedVersion ? [el('span', { className: 'af-agent-version muted', text: agent.installedVersion, attrs: { title: 'Installed by Code-XR IDE' } })] : []), + el('span', { className: 'af-badge', attrs: { 'data-availability': agent.availability }, text: availabilityLabel(agent) }), + ]), + el('p', { className: 'muted af-agent-detail', text: agent.detail ?? agent.description }), + agentActions(agent, setupDeps), + ])), ...builtinRow); + for (const listener of agentListeners) { + listener(agents); + } + } + + function renderProjects(): void { + const now = Date.now(); + 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(...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)))); + } + 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 { + 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)})` }, + }, [ + 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(' · ') }), + ]), + ...(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)), + ]), + ]); + const open = (): void => { + if (project.current) { + deps.openChat(session.id); + } else { + deps.openChatInProject(project.root, session.id); + } + }; + row.addEventListener('click', open); + row.addEventListener('keydown', (event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + open(); + } else if (event.key === 'F2') { + event.preventDefault(); + rename(session); + } else if (event.key === 'Delete') { + event.preventDefault(); + remove(session); + } + }); + return row; + } + + function rename(session: SessionSummary): void { + const row = projectList.querySelector(`[data-session="${CSS.escape(session.id)}"] .af-session-title`); + if (!row) { + return; + } + const field = el('input', { className: 'agents-input af-rename', attrs: { value: session.title, 'aria-label': 'Chat title' } }); + row.replaceWith(field); + field.focus(); + field.select(); + let done = false; + const finish = (save: boolean): void => { + if (done) { + return; + } + done = true; + 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))); + } else { + renderProjects(); + } + }; + field.addEventListener('click', (event) => event.stopPropagation()); + field.addEventListener('keydown', (event) => { + event.stopPropagation(); + if (event.key === 'Enter') { + finish(true); + } else if (event.key === 'Escape') { + finish(false); + } + }); + field.addEventListener('blur', () => finish(true)); + } + + function remove(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) { + return; + } + const yes = el('button', { className: 'secondary-button is-danger af-small-button', text: 'Delete', attrs: { type: 'button' } }); + const no = el('button', { className: 'secondary-button af-small-button', text: 'Cancel', attrs: { type: 'button' } }); + // AF12: a chat with a live worktree asks whether its worktree and branch go too (on by default). + 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' : ''}` }, [ + 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, + ]); + row.replaceWith(confirm); + yes.focus(); + yes.addEventListener('click', () => { + deps.api.remove(session.id, { removeWorktree: hasWorktree && alsoWorktree.checked }).then(() => { + deps.onRemoved?.(session.id); + return refresh(); + }).catch((error: unknown) => deps.onStatus(errorText(error))); + }); + no.addEventListener('click', () => renderProjects()); + } + + async function refreshAgents(probe = false): Promise { + agents = await deps.api.listAgents(); + renderAgents(); + if (probe) { + for (const agent of agents.filter((candidate) => candidate.kind === 'acp' && candidate.availability !== 'missing')) { + deps.api.probeAgent(agent.ref).then((view) => { + agents = agents.map((other) => (other.ref === view.ref ? view : other)); + renderAgents(); + }).catch(() => undefined); + } + } + } + + async function refresh(): Promise { + projects = await deps.api.listProjects(); + renderProjects(); + void refreshWorktreeAvailability(projects.find((project) => project.current)?.root ?? null); + deps.onAttention?.(attentionCounts(projects)); + } + + function refreshSoon(): void { + if (refreshTimer) { + return; + } + refreshTimer = window.setTimeout(() => { + refreshTimer = 0; + refresh().catch(() => undefined); + }, 250); + } + + async function newChat(agentRef?: string): Promise { + const ref = agentRef ?? defaultAgent(agents, lastAgent())?.ref; + if (!ref) { + deps.onStatus('No agent is installed yet. See the Agents section of the chats column.'); + return; + } + rememberAgent(ref); + try { + const session = await deps.api.create(ref, { worktree: worktreeAvailable && worktreeBox.checked }); + await refresh(); + deps.openChat(session.id); + } catch (error) { + deps.onStatus(errorText(error)); + } + } + + refreshAgents().catch((error: unknown) => deps.onStatus(`Agents unavailable: ${errorText(error)}`)); + refresh().catch((error: unknown) => deps.onStatus(`Chats unavailable: ${errorText(error)}`)); + + return { + refresh, + handle(message: AgentSessionMessage): void { + if (message.kind === 'agents-changed') { + refreshAgents().catch(() => undefined); + return; + } + if (message.kind === 'sessions-changed') { + refreshSoon(); + return; + } + if (message.kind === 'install-progress') { + return; + } + const type = message.event.type; + if (type === 'status' || type === 'turn-end' || type === 'title' || type === 'permission' || type === 'permission-resolved' || type === 'pending-changes' || type === 'user' || type === 'read') { + refreshSoon(); + } + }, + newChat, + setActive(sessionId: string | null): void { + active = sessionId; + for (const row of projectList.querySelectorAll('.af-session')) { + row.classList.toggle('is-active', row.dataset['session'] === sessionId); + } + renderMode(); + }, + agents: () => agents, + refreshAgents, + onAgentsChange(listener): void { + agentListeners.push(listener); + }, + focusSearch(): void { + search.focus(); + }, + }; +} + +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/worktreeBar.ts b/apps/ide/src/renderer/agentFirst/worktreeBar.ts new file mode 100644 index 000000000..50128c0d0 --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/worktreeBar.ts @@ -0,0 +1,192 @@ +import type { AgentSessionsApi, AgentSessionState, WorktreeStatusView } from '../../shared/agentSession.ts'; +import { el } from '../dom.ts'; +import { mergeOutcome, suggestedCommitMessage, worktreeActions, worktreeSummary } from './worktreeModel.ts'; + +/** + * AF12 (#277): the Worktree bar of a chat that runs in its own git worktree, + * opened from the chat header. It shows what the agent changed on its branch + * (files, commits ahead, commits the project's branch has that it does not), + * and offers Commit (message prefilled from the chat title), Merge or Squash + * into the project's current branch, and Discard worktree (confirmed inline). + * Every call names the chat by id; the main process looks up the worktree. + * Refusals (conflicts, uncommitted changes overlapping the agent's files...) + * are shown in the bar as the main process words them. + */ + +export interface WorktreeBar { + readonly element: HTMLElement; + /** Shows or hides the bar; shown, it reads the status. */ + toggle(open?: boolean): void; + readonly isOpen: boolean; + /** The chat changed (a turn ended, the worktree was discarded): re-reads the status when the bar is open. */ + update(state: AgentSessionState): void; +} + +export interface WorktreeBarDeps { + readonly api: AgentSessionsApi; + onStatus(message: string): void; +} + +export function createWorktreeBar(sessionId: string, deps: WorktreeBarDeps): WorktreeBar { + let state: AgentSessionState | null = null; + let status: WorktreeStatusView | null = null; + let busy = false; + let loading: Promise | null = null; + let messageTouched = false; + + const summary = el('p', { className: 'af-worktree-summary', attrs: { 'data-testid': 'af-worktree-summary' }, text: 'Reading the worktree...' }); + const files = el('ul', { className: 'af-worktree-files muted' }); + const message = el('input', { className: 'agents-input af-worktree-message', attrs: { type: 'text', 'aria-label': 'Commit message', placeholder: 'Commit message', 'data-testid': 'af-worktree-message' } }); + message.addEventListener('input', () => { + messageTouched = true; + render(); + }); + const commit = button('Commit', 'secondary-button af-small-button', 'af-worktree-commit'); + const merge = button('Merge', 'secondary-button af-small-button', 'af-worktree-merge'); + const squash = button('Squash', 'secondary-button af-small-button', 'af-worktree-squash'); + const discard = button('Discard worktree', 'secondary-button is-danger af-small-button', 'af-worktree-discard'); + const confirmText = el('span'); + const confirmYes = button('Discard', 'secondary-button is-danger af-small-button', 'af-worktree-discard-yes'); + const confirmNo = button('Cancel', 'secondary-button af-small-button', 'af-worktree-discard-no'); + const confirm = el('div', { className: 'af-worktree-confirm', attrs: { hidden: '', role: 'group', 'aria-label': 'Discard worktree' } }, [confirmText, confirmYes, confirmNo]); + const error = el('p', { className: 'af-worktree-error', attrs: { hidden: '', role: 'alert', 'data-testid': 'af-worktree-error' } }); + const hint = el('span', { className: 'muted af-worktree-hint' }); + const element = el('div', { className: 'af-worktree', attrs: { hidden: '', role: 'region', 'aria-label': 'Worktree', 'data-testid': 'af-worktree' } }, [ + summary, + files, + el('div', { className: 'af-worktree-row' }, [message, commit]), + el('div', { className: 'af-worktree-row' }, [merge, squash, hint, el('span', { className: 'af-spacer' }), discard]), + confirm, + error, + ]); + + function button(text: string, className: string, testId: string): HTMLButtonElement { + return el('button', { className, text, attrs: { type: 'button', 'data-testid': testId } }); + } + + function agentBusy(): boolean { + return state?.status === 'running' || state?.status === 'awaiting'; + } + + function render(): void { + const actions = worktreeActions(status, busy || agentBusy()); + summary.textContent = status ? worktreeSummary(status) : 'Reading the worktree...'; + const shown = status?.files.slice(0, 8) ?? []; + files.replaceChildren(...shown.map((file) => el('li', { text: `${file.status === 'added' ? 'A' : file.status === 'deleted' ? 'D' : 'M'} ${file.path}${file.uncommitted ? '' : ' (committed)'}` }))); + if (status && status.files.length > shown.length) { + files.append(el('li', { text: `and ${status.files.length - shown.length} more` })); + } + const into = status?.into ?? 'the project'; + merge.textContent = `Merge into ${into}`; + squash.textContent = `Squash into ${into}`; + merge.title = 'A merge commit (--no-ff) on the project\'s current branch; refused, with nothing changed, if it would conflict.'; + squash.title = 'One ordinary commit with all of the agent\'s changes, titled after the chat.'; + commit.disabled = !actions.commit || !message.value.trim(); + merge.disabled = !actions.merge; + squash.disabled = !actions.merge; + discard.disabled = !actions.discard; + hint.textContent = status && !status.removed && actions.mergeHint ? actions.mergeHint : ''; + const editable = !!status && !status.removed && status.exists; + message.disabled = !editable; + for (const node of [message, commit, merge, squash, discard]) { + node.hidden = !!status?.removed; + } + if (!messageTouched && state) { + message.value = suggestedCommitMessage(state.title); + } + } + + function showError(text: string | null): void { + error.hidden = text === null; + error.textContent = text ?? ''; + } + + async function load(): Promise { + loading ??= deps.api.worktreeStatus(sessionId).then((next) => { + status = next; + showError(null); + }, (failure: unknown) => { + showError(errorText(failure)); + }).finally(() => { + loading = null; + render(); + }); + return loading; + } + + async function run(action: () => Promise): Promise { + if (busy) { + return; + } + busy = true; + showError(null); + render(); + try { + const done = await action(); + if (done) { + deps.onStatus(done); + } + } catch (failure) { + showError(errorText(failure)); + } finally { + busy = false; + await load(); + } + } + + commit.addEventListener('click', () => void run(async () => { + const result = await deps.api.worktreeCommit(sessionId, message.value); + messageTouched = false; + return result.commit ? `Committed ${result.fileCount} file${result.fileCount === 1 ? '' : 's'} on the agent's branch.` : 'Nothing to commit.'; + })); + for (const [node, strategy] of [[merge, 'merge'], [squash, 'squash']] as const) { + node.addEventListener('click', () => void run(async () => mergeOutcome(await deps.api.worktreeMerge(sessionId, strategy)))); + } + discard.addEventListener('click', () => { + confirmText.textContent = `Remove this worktree and delete the branch ${status?.branch ?? ''}? Work that is not merged is lost.`; + confirm.hidden = false; + confirmNo.focus(); + }); + confirmNo.addEventListener('click', () => { + confirm.hidden = true; + }); + confirmYes.addEventListener('click', () => { + confirm.hidden = true; + void run(async () => { + await deps.api.worktreeDiscard(sessionId); + return 'The worktree and its branch were removed.'; + }); + }); + + return { + element, + get isOpen() { + return !element.hidden; + }, + toggle(open?: boolean): void { + const next = open ?? element.hidden; + element.hidden = !next; + if (next) { + render(); + void load(); + } else { + confirm.hidden = true; + } + }, + update(next: AgentSessionState): void { + const before = state; + state = next; + const finished = before !== null && (before.status === 'running' || before.status === 'awaiting') && next.status !== 'running' && next.status !== 'awaiting'; + const discarded = before?.worktree?.removed !== next.worktree?.removed; + if (!element.hidden && (finished || discarded)) { + void load(); + } else { + render(); + } + }, + }; +} + +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/worktreeModel.ts b/apps/ide/src/renderer/agentFirst/worktreeModel.ts new file mode 100644 index 000000000..92d3d5f4c --- /dev/null +++ b/apps/ide/src/renderer/agentFirst/worktreeModel.ts @@ -0,0 +1,94 @@ +import type { SessionWorktree, WorktreeStatusView } from '../../shared/agentSession.ts'; + +/** + * AF12 (#277): the pure logic of a worktree chat's badge and Worktree bar. + * No DOM, so it is unit-tested in test/agentFirst.test.ts. + */ + +const AGENT_BRANCH_PREFIX = 'codexr/agent/'; + +/** The branch as the badge shows it: without the `codexr/agent/` prefix every agent branch has. */ +export function branchLabel(worktree: Pick): string { + return worktree.branch.startsWith(AGENT_BRANCH_PREFIX) ? worktree.branch.slice(AGENT_BRANCH_PREFIX.length) : worktree.branch; +} + +/** The badge's tooltip. */ +export function branchTitle(worktree: SessionWorktree): string { + return worktree.removed + ? `This chat worked on the branch ${worktree.branch}; its worktree was discarded.` + : `This chat's agent works in its own worktree on the branch ${worktree.branch} (${worktree.path}).`; +} + +function plural(count: number, one: string, many = `${one}s`): string { + return `${count} ${count === 1 ? one : many}`; +} + +/** One line: what changed on the branch, and how it stands against the project's branch. */ +export function worktreeSummary(status: WorktreeStatusView): string { + if (status.removed) { + return 'The worktree was discarded; this chat is kept read-only.'; + } + if (!status.exists) { + return `The worktree folder is missing. ${status.ahead > 0 ? `The branch still has ${plural(status.ahead, 'commit')}; merge it or discard it.` : 'Discard it to clean up.'}`; + } + const parts: string[] = []; + if (status.files.length === 0) { + parts.push('No changes yet'); + } else { + const uncommitted = status.files.filter((file) => file.uncommitted).length; + parts.push(`${plural(status.files.length, 'file')} changed${uncommitted > 0 ? ` (${uncommitted} uncommitted)` : ''}`); + } + parts.push(`${plural(status.ahead, 'commit')} ahead`); + if (status.behind > 0) { + parts.push(`${status.behind} behind ${status.into ?? 'the project'}`); + } + return parts.join(', '); +} + +export interface WorktreeActions { + readonly commit: boolean; + readonly merge: boolean; + readonly discard: boolean; + /** Why Merge and Squash are off, when they are. */ + readonly mergeHint: string | null; +} + +/** Which buttons of the bar are enabled; `busy` while the agent works or an action runs. */ +export function worktreeActions(status: WorktreeStatusView | null, busy: boolean): WorktreeActions { + if (!status || status.removed) { + return { commit: false, merge: false, discard: false, mergeHint: null }; + } + let mergeHint: string | null = null; + if (status.into === null) { + mergeHint = 'The project is not on a branch (detached HEAD).'; + } else if (status.hasUncommitted) { + mergeHint = 'Commit the agent\'s changes first.'; + } else if (status.ahead === 0) { + mergeHint = 'Nothing to merge yet.'; + } + return { + commit: !busy && status.exists && status.hasUncommitted, + merge: !busy && mergeHint === null, + discard: !busy, + mergeHint, + }; +} + +/** The commit message the bar suggests: the chat's title. */ +export function suggestedCommitMessage(title: string): string { + const line = title.replace(/\s+/g, ' ').trim(); + return line && line !== 'New chat' ? line : 'Changes by the agent'; +} + +/** What the person reads after a merge or a squash. */ +export function mergeOutcome(result: { readonly strategy: 'merge' | 'squash'; readonly into: string; readonly nothingToMerge: boolean }): string { + if (result.nothingToMerge) { + return `Nothing to merge: ${result.into} already has these changes.`; + } + return result.strategy === 'merge' ? `Merged into ${result.into}.` : `Squashed into ${result.into} as one commit.`; +} + +/** Whether the person's last "Separate worktree" choice is on (stored as '1'). */ +export function parseWorktreeChoice(stored: string | null): boolean { + return stored === '1'; +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index db828709b..7e57a94ce 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -14,6 +14,8 @@ import { createTerminalPanel } from './terminal/terminalPanel.ts'; 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 { displayPath } from './agentFirst/chatModel.ts'; import { createEditReviewer } from './agents/editReview.ts'; import { registerAgentCommands } from './agents/agentCommands.ts'; import { createProblemsView } from './problems/problemsView.ts'; @@ -118,7 +120,9 @@ function editorGroup(): Promise { onStatus: (message) => workbench.setStatus(message), git: { baseline: (path) => api.git.baseline(path), blame: (path, contents) => api.git.blame(path, contents) }, debug: debug.decorations, - onActiveChange: (path) => { + onActiveChange: (tabId) => { + // AF3: a chat (or another custom tab) is not a file of the folder. + const path = tabId && !isSchemeId(tabId) ? tabId : null; document.title = path ? `${path.split('/').pop()} - Code-XR` : 'Code-XR'; activeFile = path; scheduleSessionSave(); @@ -149,6 +153,8 @@ function editorGroup(): Promise { editors.setSceneShown(!workbench.sceneArea.hidden); // #256: PDFs and images open in viewer tabs. editors.registerCustomEditor(fileViewerResolver(api.workspace)); + // Epic #265 (AF3): chats are editor tabs too. + editors.registerCustomEditor((id) => agentWorkbench.resolveCustomEditor(id)); outline = createOutlineController({ editors, view: outlineView, @@ -500,6 +506,7 @@ function folderOpened(root: string): void { } api.workspace.onDidChange((workspace) => { + agentFolderChanged(workspace?.root ?? null); if (workspace) { folderOpened(workspace.root); } else { @@ -519,6 +526,7 @@ api.workspace.current().then( (workspace) => { runView.setHasFolder(workspace !== null); folderIsOpen = workspace !== null; + agentFolderChanged(workspace?.root ?? null); if (workspace) { runView.folderOpened(workspace.root); } @@ -1042,6 +1050,58 @@ const agentsView = createAgentsView(workbench.agentsView, api.agents, { }); agentsView.refresh().catch((error: unknown) => workbench.setStatus(`Agents unavailable: ${String(error)}`)); +// Epic #265: the agent-first workbench (Chats view, chat tabs, Agent and Classic layouts). +let agentRoot: string | null = null; +/** A path from an agent (absolute) as the workspace path the editor opens. */ +function workspacePathOf(path: string): string { + return displayPath(path, agentRoot); +} +const agentWorkbench = installAgentWorkbench({ + workbench, + api: api.agentSessions, + registry, + notifications, + attachments: { + listFiles: async () => (await api.workspace.listFiles()).files, + activeSelection: () => { + const selection = editors?.activeSelection(); + return selection ? { kind: 'selection', ...selection } : null; + }, + onStatus: (message) => workbench.setStatus(message), + }, + instructions: { + listFiles: async () => (await api.workspace.listFiles()).files, + createEntry: (parent, name, kind) => api.workspace.createEntry(parent, name, kind), + writeFile: (path, text) => api.workspace.writeFile(path, text), + }, + editorGroup, + openFile: (path, line) => { + const target = workspacePathOf(path); + void editorGroup().then((group) => (line === undefined ? group.open(target) : group.openAt(target, line, 1, 0))); + }, + copy: (text) => { + navigator.clipboard.writeText(text).then(() => workbench.setStatus('Copied to the clipboard.'), () => workbench.setStatus('Could not copy.')); + }, + onStatus: (message) => workbench.setStatus(message), + openProject: async (folder) => { + await api.workspace.openRecent(folder); + }, + showTerminal: () => terminal.show(), + analyseProject: () => { + if (!runView.analyse('xr-deep')) { + workbench.showView('analysis'); + } + }, + hasFolder: () => folderIsOpen, + openFolder: () => { + registry.execute('workspace.openFolder'); + }, +}); +function agentFolderChanged(root: string | null): void { + agentRoot = root; + agentWorkbench.folderChanged(); +} + const pythonView = createPythonView(workbench.analysisView, api.python, { onStatus: (status) => { workbench.setPythonStatus(pythonStatusText(status), status.message, status.state); @@ -1086,6 +1146,11 @@ api.python.status().then((status) => { }, (error: unknown) => workbench.setStatus(`Could not check Python: ${String(error)}`)); api.app.onNotification((notification) => { workbench.setStatus(notification.message); + // Epic #265: the scene re-analyses on every change an agent makes; a toast + // per save would bury the chat, and the scene itself shows the update. + if (notification.severity === 'info' && /Code-XR re-analysis updated/.test(notification.message)) { + return; + } notifications.notify(notification.severity, notification.message, notification.severity === 'error' ? { actions: [showOutputAction('core')] } : {}); }); // #153: the core's long tasks (the Python set-up steps, the language parsers...) as progress notifications. diff --git a/apps/ide/src/renderer/workbench.ts b/apps/ide/src/renderer/workbench.ts index 14575bd65..be299bc0d 100644 --- a/apps/ide/src/renderer/workbench.ts +++ b/apps/ide/src/renderer/workbench.ts @@ -21,6 +21,8 @@ interface ActivityItem { } const ACTIVITY: readonly ActivityItem[] = [ + // #272 (AF7): the agent-first workbench's chats, grouped by project (agentFirst/sessionsView.ts). + { id: 'chats', label: 'Chats', icon: 'M4 5h16v11H9l-5 4zM8 9h8M8 12h5' }, { id: 'explorer', label: 'Explorer', icon: 'M3 6h7l2 2h9v11H3z' }, // #165: search across the workspace (search/searchView.ts). { id: 'search', label: 'Search', icon: 'M10.5 4a6.5 6.5 0 1 0 0 13a6.5 6.5 0 1 0 0-13zM15.5 15.5L21 21' }, @@ -39,7 +41,7 @@ const ACTIVITY: readonly ActivityItem[] = [ ]; /** `keybindings` has no activity item of its own: it is part of Settings (#18, part 3). `ext:`: an extension's view container (#261). */ -export type ViewId = 'explorer' | 'search' | 'scm' | 'debug' | 'analysis' | 'xr' | 'agents' | 'extensions' | 'settings' | 'keybindings' | `ext:${string}`; +export type ViewId = 'chats' | 'explorer' | 'search' | 'scm' | 'debug' | 'analysis' | 'xr' | 'agents' | 'extensions' | 'settings' | 'keybindings' | `ext:${string}`; /** #261: an extension's view container in the activity bar. */ export interface ExtensionViewContainer { @@ -61,6 +63,13 @@ export interface Workbench { readonly scmView: HTMLElement; /** #180: the Run and Debug view's pane of the side bar. */ readonly debugView: HTMLElement; + /** #272 (AF7): the Chats view's pane (projects and their agent chats). */ + readonly chatsView: HTMLElement; + /** #269 (AF4): the right-hand dock's placeholder, shown in Agent mode while no scene is open. */ + readonly dockArea: HTMLElement; + /** #269 (AF4): the layout mode; Agent keeps the analysis column on the right even before a scene opens. */ + readonly layoutMode: 'agent' | 'classic'; + setLayoutMode(mode: 'agent' | 'classic'): void; /** The status bar's slot for the current branch (#17), at its left. */ readonly branchStatus: HTMLElement; /** #177: the Restricted Mode item, at the start of the status bar (trustView.ts fills it). */ @@ -148,6 +157,7 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null const debugView = el('div', { className: 'side-pane-main', attrs: { 'data-testid': 'debug-view' } }); const scmPane = el('div', { className: 'side-pane has-sections', attrs: { 'data-view': 'scm' } }, [scmView, extensionSections.scm]); const debugPane = el('div', { className: 'side-pane has-sections', attrs: { 'data-view': 'debug' } }, [debugView, extensionSections.debug]); + const chatsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'chats', 'data-testid': 'chats-view' } }); const analysisView = el('div', { className: 'side-pane', attrs: { 'data-view': 'analysis', 'data-testid': 'analysis-view' } }); const xrView = el('div', { className: 'side-pane', attrs: { 'data-view': 'xr' } }, [ el('h2', { className: 'side-bar-title', text: 'XR scene' }), @@ -157,8 +167,8 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null const extensionsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'extensions', 'data-testid': 'extensions-view' } }); const settingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'settings', 'data-testid': 'settings-view' } }); const keybindingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'keybindings', 'data-testid': 'keybindings-view' } }); - const panes = new Map([['explorer', explorerPane], ['search', searchView], ['scm', scmPane], ['debug', debugPane], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['extensions', extensionsView], ['settings', settingsView], ['keybindings', keybindingsView]]); - const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [explorerPane, searchView, scmPane, debugPane, analysisView, xrView, agentsView, extensionsView, settingsView, keybindingsView]); + const panes = new Map([['chats', chatsView], ['explorer', explorerPane], ['search', searchView], ['scm', scmPane], ['debug', debugPane], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['extensions', extensionsView], ['settings', settingsView], ['keybindings', keybindingsView]]); + const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [chatsView, explorerPane, searchView, scmPane, debugPane, analysisView, xrView, agentsView, extensionsView, settingsView, keybindingsView]); const labels = new Map(ACTIVITY.map((item) => [item.id as ViewId, item.label])); const viewListeners = new Set<(id: ViewId | null) => void>(); let shownView: ViewId | null = null; @@ -273,7 +283,10 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null // #137: the bottom panel (hidden until the terminal opens). const panel = el('section', { className: 'panel', attrs: { hidden: '' } }); - const shell = el('div', { className: 'workbench' }, [activityBar, sideBarFrame, editorArea, panel, sceneArea, statusBar]); + // #269 (AF4): in Agent mode the scene column is always there; until a scene opens it holds this placeholder. + const dockArea = el('section', { className: 'af-dock', attrs: { 'aria-label': 'Live analysis', 'data-testid': 'af-dock' } }); + const shell = el('div', { className: 'workbench' }, [activityBar, sideBarFrame, editorArea, panel, sceneArea, dockArea, statusBar]); + let layoutMode: 'agent' | 'classic' = 'classic'; root.replaceChildren(shell); const layout = createLayout({ shell, sideBar: sideBarFrame, panel, sceneArea }, storage); showView('explorer', false); @@ -285,6 +298,15 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null searchView, scmView, debugView, + chatsView, + dockArea, + get layoutMode() { + return layoutMode; + }, + setLayoutMode(mode: 'agent' | 'classic'): void { + layoutMode = mode; + shell.classList.toggle('mode-agent', mode === 'agent'); + }, branchStatus, trustStatus, isViewVisible: (id: ViewId) => !panes.get(id)?.hidden && layout.sideBarVisible && !layout.zen, diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts new file mode 100644 index 000000000..843752829 --- /dev/null +++ b/apps/ide/src/shared/agentSession.ts @@ -0,0 +1,731 @@ +/** + * The agent-first chat (epic #265): one transcript model for every coding + * agent the IDE hosts, whether it runs over the Agent Client Protocol (AF1, + * Claude Code / Codex / Gemini CLI and any custom ACP agent) or is the IDE's + * own built-in agent (epic #189). + * + * Pure data plus a pure reducer, shared by the main process (which keeps the + * authoritative state and persists it) and the renderer (which applies the + * same events to draw the chat). No Electron, no DOM, no `vscode`: the VS Code + * extension (1.3.0) can reuse it as is. + */ + +// ---- Agents ---------------------------------------------------------------- + +/** The agents the IDE knows how to launch without any configuration (AF2). */ +export const AGENT_PRESET_IDS = ['claude', 'codex', 'gemini'] as const; +export type AgentPresetId = (typeof AGENT_PRESET_IDS)[number]; + +/** An ACP agent the person can start a chat with. */ +export interface AcpAgentDefinition { + readonly id: string; + readonly name: string; + /** The executable, resolved without a shell. For presets, set by the catalogue. */ + readonly command: string; + readonly args: readonly string[]; + /** Extra environment (never secrets: keys come from the key vault at spawn time). */ + readonly env?: Readonly>; + readonly preset?: AgentPresetId; + /** One line: what the agent is and how it bills ("Uses your Claude subscription or an API key"). */ + readonly description: string; +} + +export type AgentAvailability = + /** Its command was not found (preset not installed, custom path wrong). */ + | 'missing' + /** Found; not known yet whether it is signed in. */ + | 'available' + /** Started and answered `initialize` + `session/new`. */ + | 'ready' + /** `session/new` failed asking for authentication. */ + | 'needs-login' + | 'error'; + +/** An agent as the chat's agent picker shows it. */ +export interface AgentView { + /** `acp:` or `builtin:`. */ + readonly ref: string; + readonly name: string; + readonly kind: 'acp' | 'builtin'; + readonly description: string; + readonly availability: AgentAvailability; + /** Why it is missing or failing, in a sentence. */ + readonly detail?: string; + readonly preset?: AgentPresetId; + /** The login methods the agent advertised (ACP `authMethods`), shown with the vendor's wording. */ + readonly authMethods?: readonly AuthMethodView[]; + /** AF2: the version of a preset the IDE installed itself (under its own folder); absent otherwise. */ + readonly installedVersion?: string; +} + +/** + * AF2: what installing a preset's ACP adapter means, read from the npm + * registry only when the person asks to install it, and shown before anything + * is downloaded. + */ +export interface InstallDescription { + readonly presetId: AgentPresetId; + readonly agentName: string; + readonly packageName: string; + readonly version: string; + readonly license: string | null; + /** The package's own unpacked size, bytes (null when the registry does not say). */ + readonly unpackedSize: number | null; + /** Its dependencies' sizes for this platform that could be read, bytes (a lower bound). */ + readonly dependenciesSize: number | null; + readonly repository: string | null; + readonly homepage: string | null; + /** When this version was published (ISO), when the registry says. */ + readonly published: string | null; + readonly registry: string; + /** Direct dependencies, `name@spec`. */ + readonly dependencies: readonly string[]; + /** Platform-specific packages (native binaries) npm will pick one of, with their size here when known. */ + readonly nativeBinaries: readonly { readonly name: string; readonly size: number | null }[]; + /** Packages among the adapter and its direct dependencies that run install scripts. */ + readonly installScripts: readonly string[]; + /** The folder it goes to, and the command that installs it. */ + readonly targetDir: string; + readonly command: string; + /** The version installed by the IDE now, if any (an update). */ + readonly installedVersion: string | null; +} + +/** AF2: a line of an install's output, or its end. */ +export interface InstallProgress { + readonly presetId: AgentPresetId; + readonly action: 'install' | 'uninstall'; + readonly line?: string; + readonly done?: boolean; + readonly error?: string; +} + +export interface AuthMethodView { + readonly id: string; + readonly name: string; + readonly description?: string; + /** `terminal`: the IDE runs the agent's own login in a terminal; `agent`: the agent opens the browser itself. */ + readonly type: 'terminal' | 'agent' | 'env'; +} + +// ---- Transcript ------------------------------------------------------------ + +export type ToolKind = 'read' | 'edit' | 'delete' | 'move' | 'search' | 'execute' | 'think' | 'fetch' | 'switch_mode' | 'other'; +export type ToolStatus = 'pending' | 'in_progress' | 'completed' | 'failed'; + +export type ToolContentView = + | { readonly type: 'text'; readonly text: string } + /** A file change: `oldText` null for a new file. Paths are absolute, as ACP sends them. */ + | { readonly type: 'diff'; readonly path: string; readonly oldText: string | null; readonly newText: string } + | { readonly type: 'terminal'; readonly terminalId: string; readonly output: string; readonly exitCode: number | null; readonly truncated?: boolean }; + +export interface PermissionOptionView { + readonly id: string; + readonly name: string; + readonly kind: 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always'; +} + +export type TranscriptItem = + | { + readonly kind: 'user'; + readonly id: string; + readonly text: string; + readonly at: string; + /** Labels of attached context ("src/app.ts", "app.ts:10-24"). */ + readonly attachments?: readonly string[]; + /** The checkpoint taken just before this message (AF6), if any. */ + readonly checkpoint?: string; + } + | { readonly kind: 'assistant'; readonly id: string; readonly text: string } + | { readonly kind: 'thought'; readonly id: string; readonly text: string } + | { + readonly kind: 'tool'; + /** The ACP `toolCallId`. */ + readonly id: string; + readonly title: string; + readonly toolKind: ToolKind; + readonly status: ToolStatus; + readonly locations: readonly { readonly path: string; readonly line?: number }[]; + readonly content: readonly ToolContentView[]; + /** The raw input as compact JSON, for the expanded card. */ + readonly rawInput?: string; + } + | { + readonly kind: 'permission'; + /** The request id the answer is sent back with. */ + readonly id: string; + readonly toolCallId?: string; + readonly title: string; + readonly options: readonly PermissionOptionView[]; + /** The option chosen, or 'cancelled' when the turn ended first. Absent while waiting. */ + readonly outcome?: string; + } + | { readonly kind: 'notice'; readonly id: string; readonly level: 'info' | 'warning' | 'error'; readonly text: string } + | { + readonly kind: 'turn-end'; + readonly id: string; + readonly stopReason: 'end_turn' | 'max_tokens' | 'max_turn_requests' | 'refusal' | 'cancelled' | 'error'; + readonly at: string; + /** What the turn did to the live analysis' metrics (AF9), when a scene was open and something moved. */ + readonly metricDelta?: TurnMetricDeltaView; + }; + +// ---- Review of changes (AF5, AF6) and metric deltas (AF9) ------------------ + +/** One file a chat changed that still awaits review. */ +export interface ChangedFileView { + /** Workspace-relative, forward slashes. */ + readonly path: string; + readonly status: 'added' | 'modified' | 'deleted'; + readonly additions: number; + readonly deletions: number; + readonly binary: boolean; +} + +/** The pending changes of a chat; `disabledReason` set (and `files` empty) when checkpoints are off for its project. */ +export interface ChatChanges { + readonly files: readonly ChangedFileView[]; + readonly disabledReason: string | null; +} + +/** The two sides of one file: the review base and the disk now. Null for a side where the file does not exist. */ +export interface ChangeDiffView { + readonly path: string; + readonly oldText: string | null; + readonly newText: string | null; +} + +/** One metric of a file or of the project, before and after a turn. */ +export interface MetricChangeView { + readonly metric: string; + readonly before: number | null; + readonly after: number | null; +} + +/** 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 ..."). */ + readonly summary: string; + /** Project totals that moved. */ + readonly totals: readonly MetricChangeView[]; + /** Files the turn changed, with the metrics that moved (capped). */ + readonly files: readonly { readonly path: string; readonly status: string; readonly changes: readonly MetricChangeView[] }[]; + /** Files left out of `files` by the cap. */ + readonly moreFiles: number; +} + +export interface PlanEntryView { + readonly content: string; + readonly priority: 'high' | 'medium' | 'low'; + readonly status: 'pending' | 'in_progress' | 'completed'; +} + +export interface SlashCommandView { + readonly name: string; + readonly description: string; + /** Placeholder for the text after the command, when it takes some. */ + readonly hint?: string; +} + +export interface ModeView { + readonly id: string; + readonly name: string; + readonly description?: string; +} + +/** An agent setting with a fixed list of values (ACP config options: model, mode, thought level...). */ +export interface ConfigOptionView { + readonly id: string; + readonly name: string; + readonly category?: string; + readonly current: string; + readonly values: readonly { readonly id: string; readonly name: string; readonly description?: string }[]; +} + +export type SessionStatus = + /** Waiting for the person. */ + | 'idle' + /** The agent is working on a prompt. */ + | 'running' + /** The agent asked for a permission and waits. */ + | 'awaiting' + /** The last turn failed, or the agent could not start. */ + | 'error'; + +export interface SessionSummary { + readonly id: string; + readonly title: string; + /** `acp:` or `builtin:`. */ + readonly agentRef: string; + readonly agentName: string; + /** The project folder the chat belongs to. */ + readonly workspaceRoot: string | null; + readonly createdAt: string; + readonly updatedAt: string; + readonly status: SessionStatus; + /** Something happened that the person has not seen yet (AF7). */ + readonly unread: boolean; + /** Files the agent changed in this chat that are still pending review (AF5). */ + readonly pendingChanges: number; + /** AF12: the git worktree the chat's agent works in, when the chat was started in one. */ + readonly worktree?: SessionWorktree; +} + +/** + * AF12 (#277): a chat started with "Separate worktree" runs its agent in a git + * worktree of its own, on its own branch, outside the project. Written by the + * main process only; the renderer shows it and names the chat by id, never by + * these paths. + */ +export interface SessionWorktree { + /** `codexr/agent/-`. */ + readonly branch: string; + /** Top of the worktree (under `/worktrees`). */ + readonly path: string; + /** Where the agent works: `path` plus the project's sub-folder inside the repository. */ + readonly cwd: string; + /** The commit the branch started from. */ + readonly baseCommit: string; + /** Top of the project's main work tree, where merges land. */ + readonly repoRoot: string; + /** The worktree and its branch were discarded: the chat is kept, read-only. */ + readonly removed?: boolean; +} + +/** AF12: whether the window's folder can give a chat its own worktree. */ +export interface WorktreeAvailabilityView { + readonly ok: boolean; + /** Why not, when `ok` is false. */ + readonly message: string | null; +} + +/** AF12: what a worktree chat's agent changed, for the chat header's Worktree bar. */ +export interface WorktreeStatusView { + readonly branch: string; + /** The project's current branch (where Merge and Squash land), or null when it is detached. */ + readonly into: string | null; + /** False when the worktree folder is gone (discarded, or deleted outside the IDE). */ + readonly exists: boolean; + readonly removed: boolean; + /** Repository-relative, forward slashes. */ + readonly files: readonly { readonly path: string; readonly status: 'added' | 'modified' | 'deleted'; readonly committed: boolean; readonly uncommitted: boolean }[]; + /** Commits on the branch since it started. */ + readonly ahead: number; + /** Commits on the project's branch that the agent's branch does not have. */ + readonly behind: number; + readonly hasUncommitted: boolean; +} + +export interface WorktreeCommitView { + /** Null when there was nothing to commit. */ + readonly commit: string | null; + readonly fileCount: number; +} + +export interface WorktreeMergeView { + readonly strategy: 'merge' | 'squash'; + readonly into: string; + readonly commit: string | null; + readonly nothingToMerge: boolean; +} + +export interface AgentSessionState extends SessionSummary { + readonly items: readonly TranscriptItem[]; + readonly plan: readonly PlanEntryView[]; + 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; + /** The agent-side session id (ACP), kept to resume with `session/load`. */ + readonly agentSessionId: string | null; +} + +/** A project and its chats, for the sessions sidebar (AF7). */ +export interface ProjectSessions { + readonly root: string; + readonly name: string; + /** True for the folder open in the calling window. */ + readonly current: boolean; + readonly sessions: readonly SessionSummary[]; +} + +// ---- Events ---------------------------------------------------------------- + +/** + * What changes a session. The main process produces them (from ACP + * `session/update` notifications, from the built-in agent, or from the + * person's actions) and applies them with `applySessionEvent`; the renderer + * 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 type: 'assistant-chunk'; readonly text: string } + | { readonly type: 'thought-chunk'; readonly text: string } + | { + readonly type: 'tool'; + readonly id: string; + readonly title?: string; + readonly toolKind?: ToolKind; + readonly status?: ToolStatus; + readonly locations?: readonly { readonly path: string; readonly line?: number }[]; + /** Replaces the card's content when present (ACP semantics). */ + readonly content?: readonly ToolContentView[]; + readonly rawInput?: string; + } + /** Appends output to one terminal shown in a tool card (the IDE runs the terminal itself). */ + | { readonly type: 'terminal-output'; readonly terminalId: string; readonly output: string; readonly exitCode?: number | null; readonly truncated?: boolean } + | { readonly type: 'permission'; readonly id: string; readonly toolCallId?: string; readonly title: string; readonly options: readonly PermissionOptionView[] } + | { readonly type: 'permission-resolved'; readonly id: string; readonly outcome: string } + | { readonly type: 'plan'; readonly entries: readonly PlanEntryView[] } + | { 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: '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 } + | { readonly type: 'title'; readonly title: string } + | { readonly type: 'agent-session'; readonly agentSessionId: string } + | { readonly type: 'pending-changes'; readonly count: number } + /** AF9: attaches the metric delta of the turn that ended with `turnId`. */ + | { readonly type: 'metric-delta'; readonly turnId: string; readonly delta: TurnMetricDeltaView } + /** AF12: the chat's worktree was created or discarded. */ + | { readonly type: 'worktree'; readonly worktree: SessionWorktree } + | { readonly type: 'read' }; + +/** Main -> renderer: an event for one session, or a session list change. */ +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); + +// ---- Reducer --------------------------------------------------------------- + +const MAX_TERMINAL_OUTPUT = 64_000; + +function replaceLast(items: readonly T[], value: T): T[] { + const copy = items.slice(); + copy[copy.length - 1] = value; + return copy; +} + +/** A new, empty session. */ +export function emptySession(summary: Omit): AgentSessionState { + return { + ...summary, + status: 'idle', + unread: false, + pendingChanges: 0, + items: [], + plan: [], + commands: [], + modes: null, + configOptions: [], + usage: null, + agentSessionId: null, + }; +} + +/** + * Applies one event. Pure: returns a new state and never mutates the old one, + * so the renderer can compare references to redraw only what changed. + */ +export function applySessionEvent(state: AgentSessionState, event: SessionEvent, updatedAt: string = state.updatedAt): AgentSessionState { + const items = state.items; + const last = items[items.length - 1]; + const touch = (next: Partial): AgentSessionState => ({ ...state, ...next, updatedAt }); + 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 } : {}) }], + status: 'running', + // A new prompt starts a new plan only when the agent sends one. + }); + case 'assistant-chunk': + if (last?.kind === 'assistant') { + return touch({ items: replaceLast(items, { ...last, text: last.text + event.text }) }); + } + return touch({ items: [...items, { kind: 'assistant', id: `a${items.length}`, text: event.text }] }); + case 'thought-chunk': + if (last?.kind === 'thought') { + return touch({ items: replaceLast(items, { ...last, text: last.text + event.text }) }); + } + return touch({ items: [...items, { kind: 'thought', id: `t${items.length}`, text: event.text }] }); + case 'tool': { + const index = items.findIndex((item) => item.kind === 'tool' && item.id === event.id); + if (index < 0) { + const card: TranscriptItem = { + kind: 'tool', + id: event.id, + title: event.title ?? 'Tool', + toolKind: event.toolKind ?? 'other', + status: event.status ?? 'pending', + locations: event.locations ?? [], + content: event.content ?? [], + ...(event.rawInput !== undefined ? { rawInput: event.rawInput } : {}), + }; + return touch({ items: [...items, card] }); + } + const old = items[index] as Extract; + const updated: TranscriptItem = { + ...old, + ...(event.title !== undefined ? { title: event.title } : {}), + ...(event.toolKind !== undefined ? { toolKind: event.toolKind } : {}), + ...(event.status !== undefined ? { status: event.status } : {}), + ...(event.locations !== undefined ? { locations: event.locations } : {}), + ...(event.content !== undefined ? { content: mergeTerminalOutput(old.content, event.content) } : {}), + ...(event.rawInput !== undefined ? { rawInput: event.rawInput } : {}), + }; + const copy = items.slice(); + copy[index] = updated; + return touch({ items: copy }); + } + case 'terminal-output': { + let changed = false; + const copy = items.map((item) => { + if (item.kind !== 'tool' || !item.content.some((block) => block.type === 'terminal' && block.terminalId === event.terminalId)) { + return item; + } + changed = true; + return { + ...item, + content: item.content.map((block) => { + if (block.type !== 'terminal' || block.terminalId !== event.terminalId) { + return block; + } + const output = block.output + event.output; + const truncated = output.length > MAX_TERMINAL_OUTPUT; + return { + ...block, + output: truncated ? output.slice(output.length - MAX_TERMINAL_OUTPUT) : output, + exitCode: event.exitCode === undefined ? block.exitCode : event.exitCode, + ...(truncated || block.truncated || event.truncated ? { truncated: true } : {}), + }; + }), + }; + }); + return changed ? touch({ items: copy }) : state; + } + case 'permission': + return touch({ + items: [...items, { kind: 'permission', id: event.id, title: event.title, options: event.options, ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}) }], + status: 'awaiting', + }); + case 'permission-resolved': { + const copy = items.map((item) => (item.kind === 'permission' && item.id === event.id ? { ...item, outcome: event.outcome } : item)); + const stillWaiting = copy.some((item) => item.kind === 'permission' && item.outcome === undefined); + return touch({ items: copy, status: stillWaiting ? 'awaiting' : state.status === 'awaiting' ? 'running' : state.status }); + } + case 'plan': + return touch({ plan: event.entries }); + case 'commands': + return touch({ commands: event.commands }); + case 'modes': + 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 'notice': + return touch({ items: [...items, { kind: 'notice', id: event.id, level: event.level, text: event.text }] }); + case 'status': + return touch({ status: event.status }); + case 'turn-end': { + // Any permission still open was cancelled with the turn. + const closed = items.map((item) => (item.kind === 'permission' && item.outcome === undefined ? { ...item, outcome: 'cancelled' } : item)); + return touch({ + items: [...closed, { kind: 'turn-end', id: event.id, stopReason: event.stopReason, at: event.at }], + status: event.stopReason === 'error' ? 'error' : 'idle', + unread: true, + }); + } + case 'title': + return touch({ title: event.title }); + case 'agent-session': + return touch({ agentSessionId: event.agentSessionId }); + case 'pending-changes': + return touch({ pendingChanges: event.count }); + case 'metric-delta': { + const index = items.findIndex((item) => item.kind === 'turn-end' && item.id === event.turnId); + const target = items[index]; + if (!target || target.kind !== 'turn-end') { + return state; + } + const copy = items.slice(); + copy[index] = { ...target, metricDelta: event.delta }; + return { ...state, items: copy }; + } + case 'worktree': + return touch({ worktree: event.worktree }); + case 'read': + return state.unread ? { ...state, unread: false } : state; + } +} + +/** ACP replaces a tool card's content; keep the output the IDE already streamed into its terminals. */ +function mergeTerminalOutput(old: readonly ToolContentView[], next: readonly ToolContentView[]): readonly ToolContentView[] { + return next.map((block) => { + if (block.type !== 'terminal') { + return block; + } + const previous = old.find((candidate) => candidate.type === 'terminal' && candidate.terminalId === block.terminalId); + return previous && previous.type === 'terminal' && previous.output.length > block.output.length ? { ...block, output: previous.output, exitCode: block.exitCode ?? previous.exitCode } : block; + }); +} + +/** The summary of a session, for lists. */ +export function summarize(state: AgentSessionState): SessionSummary { + return { + id: state.id, + title: state.title, + agentRef: state.agentRef, + agentName: state.agentName, + workspaceRoot: state.workspaceRoot, + createdAt: state.createdAt, + updatedAt: state.updatedAt, + status: state.status, + unread: state.unread, + pendingChanges: state.pendingChanges, + ...(state.worktree ? { worktree: state.worktree } : {}), + }; +} + +/** A chat's first title: the start of the first message, on one line. */ +export function titleFromPrompt(text: string): string { + const line = text.replace(/\s+/g, ' ').trim(); + if (!line) { + return 'New chat'; + } + return line.length > 60 ? `${line.slice(0, 57).trimEnd()}...` : line; +} + +// ---- 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; +} + +export const AGENT_SESSION_CHANNELS = { + listAgents: 'codexr:agent-sessions:list-agents', + probeAgent: 'codexr:agent-sessions:probe-agent', + saveCustomAgent: 'codexr:agent-sessions:save-custom-agent', + removeCustomAgent: 'codexr:agent-sessions:remove-custom-agent', + login: 'codexr:agent-sessions:login', + listProjects: 'codexr:agent-sessions:list-projects', + get: 'codexr:agent-sessions:get', + create: 'codexr:agent-sessions:create', + prompt: 'codexr:agent-sessions:prompt', + cancel: 'codexr:agent-sessions:cancel', + respondPermission: 'codexr:agent-sessions:respond-permission', + setMode: 'codexr:agent-sessions:set-mode', + setConfigOption: 'codexr:agent-sessions:set-config-option', + rename: 'codexr:agent-sessions:rename', + remove: 'codexr:agent-sessions:remove', + markRead: 'codexr:agent-sessions:mark-read', + changes: 'codexr:agent-sessions:changes', + changeDiff: 'codexr:agent-sessions:change-diff', + keepChanges: 'codexr:agent-sessions:keep-changes', + undoChanges: 'codexr:agent-sessions:undo-changes', + previewRestore: 'codexr:agent-sessions:preview-restore', + restoreCheckpoint: 'codexr:agent-sessions:restore-checkpoint', + worktreeAvailability: 'codexr:agent-sessions:worktree-availability', + worktreeStatus: 'codexr:agent-sessions:worktree-status', + worktreeCommit: 'codexr:agent-sessions:worktree-commit', + worktreeMerge: 'codexr:agent-sessions:worktree-merge', + worktreeDiscard: 'codexr:agent-sessions:worktree-discard', + describeInstall: 'codexr:agent-sessions:describe-install', + install: 'codexr:agent-sessions:install', + uninstall: 'codexr:agent-sessions:uninstall', +} as const; + +export const AGENT_SESSION_EVENTS = { + message: 'codexr:agent-sessions:message', +} as const; + +/** The integrated terminal a terminal login method runs in (see `AgentSessionsApi.login`). */ +export interface LoginTerminal { + readonly terminalId: number; + readonly title: string; + readonly cwd: string; +} + +/** What `window.codexr.agentSessions` offers the renderer. */ +export interface AgentSessionsApi { + /** Every agent a chat can use: ACP presets and custom agents, and the built-in agent's profiles. */ + listAgents(): Promise; + /** Starts the agent once to learn whether it is installed and signed in (no prompt is sent). */ + probeAgent(ref: string): Promise; + saveCustomAgent(input: Omit, id?: string): Promise; + removeCustomAgent(id: string): Promise; + /** + * Runs one of the agent's login methods. An `agent` method resolves once + * the agent finished its own login (it may open the browser). A `terminal` + * method resolves as soon as the agent's login command runs in a new + * integrated terminal of this window, with that terminal's id (the id the + * terminal API and its data/exit events use) so the window can show it; + * the agent is probed again when the command exits (`agents-changed`). + */ + login(ref: string, methodId: string): Promise; + /** Recent projects and their chats, the window's own folder first. */ + listProjects(): Promise; + get(sessionId: string): Promise; + /** + * A new chat in the folder open in this window; with `worktree`, in a git + * worktree and branch of its own (AF12), refused when the folder cannot have one. + */ + create(agentRef: string, options?: { readonly worktree?: boolean }): Promise; + /** Sends a message; events stream through `onMessage`. Resolves when the turn ends. */ + prompt(sessionId: string, text: string, attachments?: readonly PromptAttachment[]): Promise; + cancel(sessionId: string): Promise; + respondPermission(sessionId: string, requestId: string, optionId: string): Promise; + setMode(sessionId: string, modeId: string): Promise; + setConfigOption(sessionId: string, optionId: string, valueId: string): Promise; + rename(sessionId: string, title: string): Promise; + /** Deletes a chat; with `removeWorktree`, also its worktree and branch (AF12), else they are kept. */ + remove(sessionId: string, options?: { readonly removeWorktree?: boolean }): Promise; + markRead(sessionId: string): Promise; + /** AF5: the files the chat changed that still await review. */ + changes(sessionId: string): Promise; + /** AF5: one pending file, as it was at its review base and as it is on disk. */ + changeDiff(sessionId: string, path: string): Promise; + /** AF5: accepts these files (or all) as they are now: they stop being pending. */ + 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; + /** 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. */ + restoreCheckpoint(sessionId: string, checkpointId: string): Promise; + /** AF12: whether a new chat of this window's folder can have its own worktree. */ + worktreeAvailability(): Promise; + /** AF12: what the chat's agent changed on its branch, ahead/behind the project's branch. */ + worktreeStatus(sessionId: string): Promise; + /** AF12: commits everything in the chat's worktree on its branch. */ + worktreeCommit(sessionId: string, message: string): Promise; + /** AF12: merges (`--no-ff`) or squashes the chat's branch into the project's current branch; refused with the reason when it is not safe. */ + worktreeMerge(sessionId: string, strategy: 'merge' | 'squash'): Promise; + /** AF12: removes the chat's worktree and deletes its branch; the chat is kept, read-only. */ + worktreeDiscard(sessionId: string): Promise; + /** + * AF2: reads from the npm registry what installing a preset's adapter + * would download (the only network call, made because the person asked). + */ + describeInstall(presetId: string): Promise; + /** + * AF2: installs (or updates to the latest version) a preset's adapter into + * the IDE's own folder, after the person confirms in a native dialog. + * Output streams as `install-progress`; resolves false when declined. + */ + install(presetId: string): Promise; + /** AF2: removes an adapter the IDE installed, after a native confirmation. */ + uninstall(presetId: string): Promise; + onMessage(listener: (message: AgentSessionMessage) => void): () => void; +} diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index 920e9b398..a229bd549 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -15,6 +15,7 @@ import type { FileFunctionMetrics, FunctionMetricsSnapshot } from './problems.ts */ import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentsApi } from './agents.ts'; +import { AGENT_SESSION_CHANNELS, AGENT_SESSION_EVENTS, type AgentSessionsApi } from './agentSession.ts'; import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS, type GitApi } from './git.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspApi } from './lsp.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TasksApi } from './tasks.ts'; @@ -350,6 +351,8 @@ export type Unsubscribe = () => void; export interface CodeXRApi { /** The AI agent hub: providers, keys, chats (contract in agents.ts). */ readonly agents: AgentsApi; + /** Epic #265 (AF1): agent-first chats with coding agents over ACP (contract in agentSession.ts). */ + readonly agentSessions: AgentSessionsApi; /** #17: Source Control for the open folder (contract in git.ts). */ readonly git: GitApi; /** #176: the folder's tasks and Run Current File; command lines are built in the main process. */ @@ -679,6 +682,8 @@ export const IPC_CHANNELS = { terminalKill: 'codexr:terminal:kill', // The AI agent hub keeps its own channel list in agents.ts. ...AGENT_IPC_CHANNELS, + // AF1: the agent-first chat keeps its own channel list in agentSession.ts. + ...AGENT_SESSION_CHANNELS, // #17: Source Control keeps its own channel list in git.ts. ...GIT_IPC_CHANNELS, // #21: the language client keeps its own channel list in lsp.ts. @@ -716,6 +721,7 @@ export const IPC_EVENTS = { outputAppended: 'codexr:output:appended', metricsChanged: 'codexr:problems:metrics-changed', ...AGENT_IPC_EVENTS, + agentSessionMessage: AGENT_SESSION_EVENTS.message, ...GIT_IPC_EVENTS, ...LSP_IPC_EVENTS, ...TASK_IPC_EVENTS, diff --git a/apps/ide/test/agentFirst.test.ts b/apps/ide/test/agentFirst.test.ts new file mode 100644 index 000000000..58fd615b7 --- /dev/null +++ b/apps/ide/test/agentFirst.test.ts @@ -0,0 +1,218 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { AgentView, ProjectSessions, SessionSummary, TranscriptItem } from '../src/shared/agentSession.ts'; +import { applySessionEvent, emptySession, summarize, titleFromPrompt } from '../src/shared/agentSession.ts'; +import { + attachmentLabel, changeCounts, composerAction, diffLinesForCard, displayPath, formatTokens, lastUserIndex, slashSuggestions, turnChanges, +} from '../src/renderer/agentFirst/chatModel.ts'; +import { attentionCounts, defaultAgent, filterProjects, shortTime, statusLabel } from '../src/renderer/agentFirst/sessionsModel.ts'; +import { chatIdOf, chatTabId, parseLayoutMode } from '../src/renderer/agentFirst/agentWorkbenchModel.ts'; +import { + changesIdOf, changesSummary, changesTabId, formatMetricChange, metricDeltaFileLines, metricDeltaHeadline, nextSelection, restorePrompt, statusLetter, +} from '../src/renderer/agentFirst/changesModel.ts'; + +function summary(overrides: Partial = {}): SessionSummary { + return { + id: 's1', title: 'Fix login', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/p', + createdAt: '2026-11-27T10:00:00.000Z', updatedAt: '2026-11-27T10:00:00.000Z', status: 'idle', unread: false, pendingChanges: 0, + ...overrides, + }; +} + +function agent(overrides: Partial): AgentView { + return { ref: 'acp:x', name: 'X', kind: 'acp', description: '', availability: 'ready', ...overrides }; +} + +describe('agent workbench model', () => { + it('defaults to the Agent layout and remembers Classic', () => { + assert.equal(parseLayoutMode(null), 'agent'); + assert.equal(parseLayoutMode('nonsense'), 'agent'); + assert.equal(parseLayoutMode('classic'), 'classic'); + }); + + it('round-trips chat tab ids and ignores other tabs', () => { + assert.equal(chatIdOf(chatTabId('abc')), 'abc'); + assert.equal(chatIdOf('/home/me/file.ts'), null); + assert.equal(chatIdOf('chat:'), null); + }); +}); + +describe('chat model', () => { + it('suggests slash commands only for a leading slash', () => { + const commands = [{ name: 'review', description: '' }, { name: 'compact', description: '' }]; + assert.deepEqual(slashSuggestions('/re', commands).map((c) => c.name), ['review']); + assert.deepEqual(slashSuggestions('/', commands).length, 2); + assert.deepEqual(slashSuggestions('hi /re', commands), []); + }); + + it('draws a compact diff with context and gaps', () => { + const before = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].join('\n'); + const after = ['a', 'b', 'c', 'd', 'E', 'f', 'g', 'h'].join('\n'); + const lines = diffLinesForCard(before, after, 1); + assert.deepEqual(lines.map((l) => l.kind), ['gap', 'context', 'remove', 'add', 'context', 'gap']); + assert.deepEqual(changeCounts(before, after), { added: 1, removed: 1 }); + assert.deepEqual(diffLinesForCard(null, 'x\ny').map((l) => l.kind), ['add', 'add']); + assert.deepEqual(changeCounts(null, 'x\ny'), { added: 2, removed: 0 }); + }); + + it('never shows a line twice when two hunks are close', () => { + const before = ['export function total() {', ' let sum = 0;', ' loop();', '}'].join('\n'); + const after = ['function helper() {}', '', 'export function total() {', ' return helper();', '}'].join('\n'); + const texts = diffLinesForCard(before, after).filter((line) => line.kind !== 'add').map((line) => line.text); + assert.equal(texts.filter((text) => text === ' let sum = 0;').length, 1); + }); + + it('caps a huge diff', () => { + const lines = diffLinesForCard(null, Array.from({ length: 1000 }, (_, i) => String(i)).join('\n'), 2, 10); + assert.equal(lines.length, 11); + assert.equal(lines.at(-1)?.text, '990 more lines'); + }); + + it('shows paths relative to the project', () => { + assert.equal(displayPath('/p/src/a.ts', '/p'), 'src/a.ts'); + assert.equal(displayPath('C:\\P\\src\\a.ts', 'c:\\p\\'), 'src/a.ts'); + assert.equal(displayPath('/other/a.ts', '/p'), '/other/a.ts'); + }); + + it('picks the composer action', () => { + assert.equal(composerAction({ status: 'idle' }, 'hi'), 'send'); + assert.equal(composerAction({ status: 'running' }, 'hi'), 'queue'); + assert.equal(composerAction({ status: 'awaiting' }, ' '), 'stop'); + assert.equal(composerAction({ status: 'idle' }, ''), 'none'); + }); + + it('collects the files a turn changed, keeping the first old text', () => { + const items: TranscriptItem[] = [ + { kind: 'user', id: 'u1', text: 'go', at: '' }, + { kind: 'tool', id: 't1', title: 'Edit', toolKind: 'edit', status: 'completed', locations: [], content: [{ type: 'diff', path: 'a.ts', oldText: 'v0', newText: 'v1' }] }, + { kind: 'tool', id: 't2', title: 'Edit', toolKind: 'edit', status: 'completed', locations: [], content: [{ type: 'diff', path: 'a.ts', oldText: 'v1', newText: 'v2' }] }, + ]; + assert.equal(lastUserIndex(items), 0); + assert.deepEqual(turnChanges(items, 0), [{ path: 'a.ts', oldText: 'v0', newText: 'v2' }]); + }); + + it('labels attachments and token use', () => { + assert.equal(attachmentLabel({ kind: 'selection', path: 'a.ts', startLine: 3, endLine: 9 }), 'a.ts:3-9'); + assert.equal(attachmentLabel({ kind: 'file', path: 'a.ts' }), 'a.ts'); + assert.equal(formatTokens(12_400, 200_000), '12k / 200k'); + assert.equal(formatTokens(900, 1_000_000), '900 / 1M'); + }); +}); + +describe('sessions model', () => { + const projects: ProjectSessions[] = [ + { root: '/p', name: 'shop', current: true, sessions: [summary({ id: 'a', status: 'running' }), summary({ id: 'b', title: 'Write tests', status: 'awaiting', unread: true })] }, + { root: '/q', name: 'blog', current: false, sessions: [summary({ id: 'c', title: 'Fix CSS', agentName: 'Codex' })] }, + ]; + + it('filters by project, title and agent', () => { + assert.equal(filterProjects(projects, '').length, 2); + assert.deepEqual(filterProjects(projects, 'shop')[0]?.sessions.length, 2); + assert.deepEqual(filterProjects(projects, 'tests').map((p) => p.sessions.map((s) => s.id)), [['b']]); + assert.deepEqual(filterProjects(projects, 'codex').map((p) => p.name), ['blog']); + }); + + it('counts what needs attention', () => { + assert.deepEqual(attentionCounts(projects), { running: 1, waiting: 1, unread: 1 }); + }); + + it('labels statuses', () => { + assert.equal(statusLabel({ status: 'idle', unread: true }), 'Done, not read yet'); + assert.equal(statusLabel({ status: 'awaiting', unread: true }), 'Needs your approval'); + }); + + it('writes short relative times', () => { + const now = Date.parse('2026-11-27T12:00:00.000Z'); + assert.equal(shortTime('2026-11-27T11:59:30.000Z', now), 'now'); + assert.equal(shortTime('2026-11-27T11:55:00.000Z', now), '5 min'); + assert.equal(shortTime('2026-11-27T09:00:00.000Z', now), '3 h'); + assert.equal(shortTime('2026-11-25T12:00:00.000Z', now), '2 d'); + assert.equal(shortTime('2026-10-01T12:00:00.000Z', now), '2026-10-01'); + assert.equal(shortTime('bad', now), ''); + }); + + it('chooses the default agent', () => { + const agents = [agent({ ref: 'builtin:x', kind: 'builtin' }), agent({ ref: 'acp:claude' }), agent({ ref: 'acp:codex', availability: 'missing' })]; + assert.equal(defaultAgent(agents, 'acp:codex')?.ref, 'acp:claude'); + assert.equal(defaultAgent(agents, 'builtin:x')?.ref, 'acp:claude'); + assert.equal(defaultAgent([], null), null); + }); +}); + +describe('session events', () => { + it('streams chunks, waits on a permission and ends the turn unread', () => { + let state = emptySession({ id: 's', title: 'New chat', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/p', createdAt: '', updatedAt: '' }); + state = applySessionEvent(state, { type: 'assistant-chunk', text: 'Hel' }); + state = applySessionEvent(state, { type: 'assistant-chunk', text: 'lo' }); + assert.equal(state.items.filter((item) => item.kind === 'assistant').length, 1); + assert.equal(titleFromPrompt(' Fix the login\nbug please '), 'Fix the login bug please'); + const s = summarize(state); + assert.equal(s.id, 's'); + }); +}); + +describe('instructions model', async () => { + const { instructionEntries, otherRuleFiles, splitWorkspacePath } = await import('../src/renderer/agentFirst/instructionsModel.ts'); + + it('marks which instruction files the project has', () => { + const entries = instructionEntries(['agents.md', 'src/a.ts']); + assert.equal(entries.find((entry) => entry.path === 'AGENTS.md')?.exists, true); + assert.equal(entries.find((entry) => entry.path === 'CLAUDE.md')?.exists, false); + }); + + it('finds other rule files', () => { + assert.deepEqual(otherRuleFiles(['AGENTS.md', 'pkg/AGENTS.md', '.cursor/rules/style.mdc', 'README.md', '.cursorrules']), ['.cursor/rules/style.mdc', '.cursorrules', 'pkg/AGENTS.md']); + }); + + it('splits a workspace path', () => { + assert.deepEqual(splitWorkspacePath('.github/copilot-instructions.md'), { parent: '.github', name: 'copilot-instructions.md' }); + assert.deepEqual(splitWorkspacePath('AGENTS.md'), { parent: '', name: 'AGENTS.md' }); + }); +}); + +describe('changes model (AF5, AF6, AF9)', () => { + const file = (path: string, status: 'added' | 'modified' | 'deleted' = 'modified', additions = 1, deletions = 0) => ({ path, status, additions, deletions, binary: false }); + + it('names Changes tabs apart from chat tabs', () => { + assert.equal(changesTabId('s1'), 'chat-changes:s1'); + assert.equal(changesIdOf('chat-changes:s1'), 's1'); + assert.equal(changesIdOf('chat-changes:'), null); + assert.equal(changesIdOf('chat:s1'), null); + assert.equal(chatIdOf(changesTabId('s1')), null, 'a Changes tab is not a chat tab'); + }); + + it('summarises the list and keeps the selection sensible as files go', () => { + assert.equal(changesSummary([]), 'No pending changes.'); + assert.equal(changesSummary([file('a', 'modified', 3, 1), file('b', 'added', 2, 0)]), '2 files, +5 -1'); + assert.equal(changesSummary([file('a')]), '1 file, +1 -0'); + assert.deepEqual(['added', 'modified', 'deleted'].map((status) => statusLetter(status as 'added')), ['A', 'M', 'D']); + const files = [file('a'), file('b'), file('c')]; + assert.equal(nextSelection(files, 'b', 1), 'b'); + assert.equal(nextSelection([file('a'), file('c')], 'b', 1), 'c', 'the next file takes the place of the one kept'); + assert.equal(nextSelection([file('a')], 'c', 2), 'a'); + assert.equal(nextSelection(files, null), 'a'); + assert.equal(nextSelection([], 'a'), null); + }); + + it('words the restore confirmation', () => { + assert.match(restorePrompt(['a.ts', 'b.ts']), /^Restore 2 files /); + assert.match(restorePrompt(['a.ts']), /^Restore 1 file /); + assert.match(restorePrompt([]), /already as they were/); + }); + + it('formats a metric delta compactly, levels as before -> after and counts as a difference', () => { + assert.equal(formatMetricChange({ metric: 'maxComplexity', before: 9, after: 1 }), 'Complexity max 9 -> 1'); + assert.equal(formatMetricChange({ metric: 'codeLines', before: 20, after: 14 }), 'LOC -6'); + assert.equal(formatMetricChange({ metric: 'functionCount', before: 2, after: 3 }), 'Functions +1'); + assert.equal(formatMetricChange({ metric: 'codeLines', before: null, after: 10 }), 'LOC - -> 10'); + const delta = { + summary: '2 files (1 changed, 1 added)', + totals: [{ metric: 'maxComplexity', before: 9, after: 1 }, { metric: 'codeLines', before: 20, after: 14 }, { metric: 'functionCount', before: 2, after: 3 }, { metric: 'classCount', before: 0, after: 1 }], + files: [{ path: 'src/a.ts', status: 'changed', changes: [{ metric: 'maxComplexity', before: 9, after: 1 }] }, { path: 'src/b.ts', status: 'added', changes: [] }], + moreFiles: 2, + }; + assert.equal(metricDeltaHeadline(delta), 'Complexity max 9 -> 1, LOC -6, Functions +1'); + assert.equal(metricDeltaHeadline({ ...delta, totals: [] }), delta.summary); + assert.deepEqual(metricDeltaFileLines(delta), ['src/a.ts (changed): Complexity max 9 -> 1', 'src/b.ts (added)', 'and 2 more files']); + }); +}); diff --git a/apps/ide/test/agentInstaller.test.ts b/apps/ide/test/agentInstaller.test.ts new file mode 100644 index 000000000..4ceafab58 --- /dev/null +++ b/apps/ide/test/agentInstaller.test.ts @@ -0,0 +1,305 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import type { AddressInfo } from 'node:net'; +import type { AgentView, InstallDescription } from '../src/shared/agentSession.ts'; +import { + AgentInstaller, consentDetail, isExactVersion, parsePresetId, platformFit, registryOf, repositoryUrl, resolveAlias, satisfies, +} from '../src/main/agentSessions/agentInstaller.ts'; +import { + describeRows, guideAgent, isUpToDate, onboardingSteps, progressTitle, setupActions, shouldShowOnboarding, +} from '../src/renderer/agentFirst/agentSetupModel.ts'; + +/** + * AF2 (#267): the installer against a fake npm registry on localhost and a + * fake `npm` on PATH, so nothing reaches the network. AF13 (#278): the pure + * model of the first-run guide. + */ + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-agent-installer-')); +const posix = process.platform !== 'win32'; + +const DOCS: Record = { + '/@agentclientprotocol%2Fcodex-acp/latest': { + name: '@agentclientprotocol/codex-acp', + version: '2.12.1', + license: 'Apache-2.0', + repository: { type: 'git', url: 'git+https://github.com/agentclientprotocol/codex-acp.git' }, + dependencies: { '@openai/codex': '^0.172.0', zod: '4.0.0' }, + dist: { unpackedSize: 2_000_000 }, + }, + '/@agentclientprotocol%2Fcodex-acp': { time: { '2.12.1': '2026-11-20T10:00:00.000Z' } }, + '/@openai%2Fcodex/latest': { + name: '@openai/codex', + version: '0.172.3', + dist: { unpackedSize: 10_000 }, + optionalDependencies: { + '@openai/codex-linux-x64': 'npm:@openai/codex@0.172.3-linux-x64', + '@openai/codex-darwin-arm64': 'npm:@openai/codex@0.172.3-darwin-arm64', + '@openai/codex-win32-x64': 'npm:@openai/codex@0.172.3-win32-x64', + }, + }, + '/@openai%2Fcodex/0.172.3-linux-x64': { name: '@openai/codex', version: '0.172.3-linux-x64', os: ['linux'], cpu: ['x64'], dist: { unpackedSize: 400_000_000 } }, + '/zod/4.0.0': { name: 'zod', version: '4.0.0', dist: { unpackedSize: 1_000 }, scripts: { postinstall: 'node setup.js' } }, +}; + +let server: http.Server; +let registry = ''; +const requests: string[] = []; + +const FAKE_NPM = `#!/usr/bin/env node +const fs = require('node:fs'); +const path = require('node:path'); +const args = process.argv.slice(2); +fs.appendFileSync(process.env.FAKE_NPM_LOG, JSON.stringify(args) + '\\n'); +if (process.env.FAKE_NPM_FAIL) { + console.error('npm error code E404'); + console.error('npm error 404 Not Found'); + process.exit(1); +} +const prefix = args[args.indexOf('--prefix') + 1]; +const spec = args[args.length - 1]; +if (args[0] === 'install') { + const at = spec.lastIndexOf('@'); + const name = spec.slice(0, at); + const dir = path.join(prefix, 'node_modules', ...name.split('/')); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name, version: spec.slice(at + 1), bin: { x: 'index.js' } })); + console.log('npm http fetch GET 200 ' + name); + console.log('added 3 packages in 1s'); +} else if (args[0] === 'uninstall') { + fs.rmSync(path.join(prefix, 'node_modules', ...spec.split('/')), { recursive: true, force: true }); + console.log('removed 3 packages in 1s'); +} +`; + +function makeInstaller(name: string, extraEnv: Record = {}, withNpm = true): { installer: AgentInstaller; packagesDir: string; log: string } { + const dir = path.join(base, name); + const bin = path.join(dir, 'bin'); + fs.mkdirSync(bin, { recursive: true }); + const log = path.join(dir, 'npm.log'); + if (withNpm) { + fs.writeFileSync(path.join(bin, 'npm'), FAKE_NPM, { mode: 0o755 }); + } + const packagesDir = path.join(dir, 'agent-packages'); + const installer = new AgentInstaller({ + packagesDir, + fetchJson: async (url) => { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status}`); + } + return response.json() as Promise; + }, + env: { PATH: `${bin}${path.delimiter}${path.dirname(process.execPath)}`, npm_config_registry: registry, FAKE_NPM_LOG: log, ELECTRON_RUN_AS_NODE: '1', ...extraEnv }, + platform: 'linux', + arch: 'x64', + timeoutMs: 30_000, + }); + return { installer, packagesDir, log }; +} + +before(async () => { + server = http.createServer((request, response) => { + requests.push(request.url ?? ''); + const doc = DOCS[request.url ?? '']; + response.writeHead(doc ? 200 : 404, { 'content-type': 'application/json' }); + response.end(JSON.stringify(doc ?? { error: 'Not found' })); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + registry = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; +}); + +after(() => { + server.close(); + fs.rmSync(base, { recursive: true, force: true }); +}); + +describe('agent installer: describing (AF2)', () => { + it('reads nothing until asked, then the version, licence, size, source, native binary and install scripts', async () => { + const { installer, packagesDir } = makeInstaller('describe'); + assert.equal(requests.length, 0); + const description = await installer.describe('codex'); + assert.equal(description.packageName, '@agentclientprotocol/codex-acp'); + assert.equal(description.version, '2.12.1'); + assert.equal(description.license, 'Apache-2.0'); + assert.equal(description.unpackedSize, 2_000_000); + assert.equal(description.repository, 'https://github.com/agentclientprotocol/codex-acp'); + assert.equal(description.published, '2026-11-20T10:00:00.000Z'); + assert.equal(description.registry, registry); + assert.deepEqual(description.nativeBinaries, [{ name: '@openai/codex: @openai/codex-linux-x64', size: 400_000_000 }]); + assert.equal(description.dependenciesSize, 10_000 + 1_000 + 400_000_000); + assert.deepEqual(description.installScripts, ['zod']); + assert.equal(description.targetDir, packagesDir); + assert.match(description.command, /^npm install --prefix .+ --omit=dev .*@agentclientprotocol\/codex-acp@2\.12\.1$/); + assert.equal(description.installedVersion, null); + assert.ok(requests.includes('/@openai%2Fcodex/0.172.3-linux-x64')); + const detail = consentDetail(description); + for (const part of ['@agentclientprotocol/codex-acp@2.12.1', 'Apache-2.0', '1.9 MB', 'https://github.com/agentclientprotocol/codex-acp', 'codex-linux-x64 (381 MB)', 'Install scripts will run for: zod', 'nothing is installed globally']) { + assert.ok(detail.includes(part), `consent text lacks ${part}:\n${detail}`); + } + }); + + it('refuses anything but the three presets', async () => { + const { installer } = makeInstaller('refuse'); + assert.throws(() => parsePresetId('../evil'), /Only Claude Code, Codex and Gemini CLI/); + await assert.rejects(installer.describe({ id: 'codex' }), /Only Claude Code/); + }); + + it('says plainly when the registry cannot be read', async () => { + const { installer } = makeInstaller('unreachable'); + await assert.rejects(installer.describe('claude'), /Could not read @agentclientprotocol\/claude-agent-acp from http:\/\/127\.0\.0\.1/); + }); +}); + +describe('agent installer: installing and removing (AF2)', { skip: !posix && 'the fake npm is a POSIX script' }, () => { + it('installs nothing when the person declines', async () => { + const { installer, log } = makeInstaller('decline'); + let shown: InstallDescription | null = null; + const done = await installer.install('codex', async (description) => { + shown = description; + return false; + }, () => undefined); + assert.equal(done, false); + assert.equal((shown as InstallDescription | null)?.version, '2.12.1'); + assert.equal(fs.existsSync(log), false, 'npm must not run'); + }); + + it('installs the confirmed version into its private folder, streaming npm output, then removes it', async () => { + const { installer, packagesDir, log } = makeInstaller('install'); + const lines: string[] = []; + assert.equal(await installer.install('codex', async () => true, (line) => lines.push(line)), true); + assert.equal(await installer.installedVersion('codex'), '2.12.1'); + const manifest = JSON.parse(fs.readFileSync(path.join(packagesDir, 'package.json'), 'utf8')) as { private?: boolean }; + assert.equal(manifest.private, true); + assert.ok(lines.some((line) => line.includes('added 3 packages')), lines.join('\n')); + const args = JSON.parse(fs.readFileSync(log, 'utf8').trim()) as string[]; + assert.deepEqual(args.slice(0, 3), ['install', '--prefix', packagesDir]); + assert.ok(args.includes('--ignore-scripts=false') && args.includes('--no-audit') && args.includes('--omit=dev')); + assert.equal(args.at(-1), '@agentclientprotocol/codex-acp@2.12.1'); + assert.ok(!args.some((arg) => arg === '-g' || arg === '--global')); + + // An update describes the installed version too. + assert.equal((await installer.describe('codex')).installedVersion, '2.12.1'); + + let asked = ''; + assert.equal(await installer.uninstall('codex', async (name, version) => { + asked = `${name}@${version}`; + return true; + }, () => undefined), true); + assert.equal(asked, '@agentclientprotocol/codex-acp@2.12.1'); + assert.equal(await installer.installedVersion('codex'), null); + await assert.rejects(installer.uninstall('codex', async () => true, () => undefined), /was not installed by Code-XR IDE/); + }); + + it('reports npm\'s own error lines when it fails', async () => { + const { installer } = makeInstaller('fail', { FAKE_NPM_FAIL: '1' }); + await assert.rejects(installer.install('codex', async () => true, () => undefined), /npm failed \(exit code 1\)\.\n[\s\S]*404 Not Found/); + assert.equal(installer.running, null); + }); + + it('points to nodejs.org when npm is missing, before asking anything', async () => { + const { installer } = makeInstaller('no-npm', { PATH: path.join(base, 'no-npm', 'bin') }, false); + let asked = false; + await assert.rejects(installer.install('codex', async () => { + asked = true; + return true; + }, () => undefined), /npm was not found on PATH.*https:\/\/nodejs\.org/); + assert.equal(asked, false); + }); +}); + +describe('agent installer: helpers', () => { + it('matches the version ranges adapters use', () => { + assert.equal(satisfies('0.172.3', '^0.172.0'), true); + assert.equal(satisfies('0.173.0', '^0.172.0'), false); + assert.equal(satisfies('4.6.7', '^4.0.0'), true); + assert.equal(satisfies('5.0.0', '^4.0.0'), false); + assert.equal(satisfies('2.9.4', '~2.9.1'), true); + assert.equal(satisfies('2.10.0', '~2.9.1'), false); + assert.equal(satisfies('1.2.3', '1.2.3'), true); + assert.equal(satisfies('1.2.4-beta.1', '^1.2.0'), false); + assert.equal(satisfies('1.2.3', '>=1 <2'), null); + assert.equal(isExactVersion('0.3.331'), true); + assert.equal(isExactVersion('^1.0.0'), false); + }); + + it('reads aliases, repositories, platforms and registries', () => { + assert.deepEqual(resolveAlias('@openai/codex-linux-x64', 'npm:@openai/codex@0.1.0-linux-x64'), { name: '@openai/codex', spec: '0.1.0-linux-x64' }); + assert.deepEqual(resolveAlias('zod', '^4'), { name: 'zod', spec: '^4' }); + assert.equal(repositoryUrl('github:owner/repo'), 'https://github.com/owner/repo'); + assert.equal(repositoryUrl({ url: 'git@github.com:owner/repo.git' }), 'https://github.com/owner/repo'); + assert.equal(repositoryUrl({ url: 'http://example.com/x' }), null); + assert.equal(platformFit('@x/sdk-linux-x64', 'linux', 'x64'), 2); + assert.equal(platformFit('@x/sdk-linux-x64-musl', 'linux', 'x64'), 1); + assert.equal(platformFit('@x/sdk-win32-x64', 'linux', 'x64'), 0); + assert.equal(platformFit('@x/sdk-darwin-arm64', 'darwin', 'arm64'), 2); + assert.equal(registryOf({}), 'https://registry.npmjs.org/'); + assert.equal(registryOf({ npm_config_registry: 'https://mirror.example/npm' }), 'https://mirror.example/npm/'); + assert.equal(registryOf({ npm_config_registry: 'http://mirror.example/' }), 'https://registry.npmjs.org/'); + }); +}); + +// ---- Renderer models (AF2 actions, AF13 first run) ---------------------------- + +function agent(overrides: Partial): AgentView { + return { ref: 'acp:claude', name: 'Claude Code', kind: 'acp', description: '', availability: 'ready', preset: 'claude', ...overrides }; +} + +describe('agent setup model', () => { + it('offers Install for a missing preset, Update and Remove for one the IDE installed', () => { + assert.deepEqual(setupActions(agent({ availability: 'missing' })), ['install']); + const { preset: _preset, ...custom } = agent({ availability: 'missing', ref: 'acp:custom-12345678' }); + assert.deepEqual(setupActions(custom), []); + assert.deepEqual(setupActions(agent({ availability: 'available' })), ['check']); + assert.deepEqual(setupActions(agent({ availability: 'needs-login', authMethods: [{ id: 'a', name: 'Log in', type: 'terminal' }], installedVersion: '1.0.0' })), ['login', 'check', 'update', 'remove']); + assert.deepEqual(setupActions(agent({ kind: 'builtin', ref: 'builtin:x' })), []); + }); + + it('describes an install in rows and knows when it is up to date', () => { + const description: InstallDescription = { + presetId: 'claude', agentName: 'Claude Code', packageName: '@agentclientprotocol/claude-agent-acp', version: '1.0.0', license: null, + unpackedSize: 3_364_087, dependenciesSize: null, repository: null, homepage: null, published: null, registry: 'https://registry.npmjs.org/', + dependencies: [], nativeBinaries: [], installScripts: [], targetDir: '/data/agent-packages', command: 'npm install x', installedVersion: '1.0.0', + }; + const rows = Object.fromEntries(describeRows(description)); + assert.equal(rows['Licence'], 'Not stated'); + assert.equal(rows['Size'], '3.2 MB'); + assert.equal(rows['Source'], 'https://registry.npmjs.org/'); + assert.equal(rows['Install scripts'], 'None declared'); + assert.equal(isUpToDate(description), true); + assert.equal(isUpToDate({ ...description, version: '1.1.0' }), false); + assert.equal(progressTitle({ action: 'uninstall' }, 'Codex'), 'Removing Codex'); + }); + + it('walks the three first-run steps from the real state', () => { + const missing = [agent({ availability: 'missing' }), agent({ ref: 'acp:codex', name: 'Codex', preset: 'codex', availability: 'missing' })]; + let steps = onboardingSteps({ hasFolder: false, agents: missing, chosen: null, hasChat: false }); + assert.deepEqual(steps.map((step) => step.state), ['current', 'todo', 'todo']); + assert.match(steps[1]?.text ?? '', /Nothing is downloaded until you confirm/); + + steps = onboardingSteps({ hasFolder: true, agents: missing, chosen: null, hasChat: false }); + assert.deepEqual(steps.map((step) => step.state), ['done', 'current', 'todo']); + + const login = [agent({ availability: 'needs-login' })]; + assert.match(onboardingSteps({ hasFolder: true, agents: login, chosen: null, hasChat: false })[1]?.text ?? '', /Sign in/); + + const usable = [agent({ availability: 'available' }), agent({ ref: 'acp:codex', name: 'Codex', preset: 'codex', availability: 'ready' })]; + assert.equal(guideAgent({ agents: usable, chosen: null })?.ref, 'acp:codex', 'a ready agent before an unchecked one'); + assert.equal(guideAgent({ agents: usable, chosen: 'acp:claude' })?.ref, 'acp:claude'); + steps = onboardingSteps({ hasFolder: true, agents: usable, chosen: 'acp:claude', hasChat: false }); + assert.deepEqual(steps.map((step) => step.state), ['done', 'done', 'current']); + assert.deepEqual(onboardingSteps({ hasFolder: true, agents: usable, chosen: null, hasChat: true }).map((step) => step.state), ['done', 'done', 'done']); + // An agent can be set up before a folder is open; the folder is still the next step. + assert.deepEqual(onboardingSteps({ hasFolder: false, agents: usable, chosen: null, hasChat: false }).map((step) => step.state), ['current', 'done', 'todo']); + }); + + it('opens on its own only on a first run', () => { + assert.equal(shouldShowOnboarding(null, false), true); + assert.equal(shouldShowOnboarding('true', false), false); + assert.equal(shouldShowOnboarding(null, true), false); + }); +}); diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts new file mode 100644 index 000000000..fed13da27 --- /dev/null +++ b/apps/ide/test/agentSessions.test.ts @@ -0,0 +1,696 @@ +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 { agent, methods, RequestError, type AgentContext } from '@agentclientprotocol/sdk'; +import { applySessionEvent, emptySession, type AgentSessionMessage, type AgentSessionState, type SessionEvent, type TranscriptItem } from '../src/shared/agentSession.ts'; +import { JsonKeyValueStore } from '../src/main/core/jsonStore.ts'; +import { AcpConnection } from '../src/main/agentSessions/acpConnection.ts'; +import { buildPromptBlocks, isAuthRequiredError, mapAuthMethods, mapConfigOptions, mapSessionUpdate, sliceLines, stopReasonOf } from '../src/main/agentSessions/acpMapping.ts'; +import { AgentCatalog, agentEnvironment, findOnPath, diskProbe } from '../src/main/agentSessions/agentCatalog.ts'; +import { AgentSessionService, 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 { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-agent-sessions-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +const AT = '2026-11-27T10:00:00.000Z'; + +function fresh(): AgentSessionState { + return emptySession({ id: 's1', title: 'New chat', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/p', createdAt: AT, updatedAt: AT }); +} + +function reduce(events: readonly SessionEvent[], state: AgentSessionState = fresh()): AgentSessionState { + return events.reduce((current, event) => applySessionEvent(current, event), state); +} + +describe('applySessionEvent', () => { + it('merges consecutive chunks and starts a new item after anything else', () => { + const state = reduce([ + { type: 'assistant-chunk', text: 'Hel' }, + { type: 'assistant-chunk', text: 'lo' }, + { type: 'thought-chunk', text: 'hmm' }, + { type: 'thought-chunk', text: '...' }, + { type: 'assistant-chunk', text: 'Again' }, + ]); + assert.deepEqual(state.items.map((item) => [item.kind, 'text' in item ? item.text : '']), [['assistant', 'Hello'], ['thought', 'hmm...'], ['assistant', 'Again']]); + }); + + it('creates a tool card and updates only the fields an update carries', () => { + const state = reduce([ + { type: 'tool', id: 't1', title: 'Edit a.ts', toolKind: 'edit', status: 'pending', locations: [{ path: '/p/a.ts' }] }, + { type: 'tool', id: 't1', status: 'completed', content: [{ type: 'diff', path: '/p/a.ts', oldText: 'a', newText: 'b' }] }, + ]); + const tool = state.items[0] as Extract; + assert.equal(tool.title, 'Edit a.ts'); + assert.equal(tool.toolKind, 'edit'); + assert.equal(tool.status, 'completed'); + assert.deepEqual(tool.locations, [{ path: '/p/a.ts' }]); + assert.equal(tool.content[0]?.type, 'diff'); + }); + + it('appends terminal output to the card that shows it and caps it', () => { + let state = reduce([{ type: 'tool', id: 't1', title: 'Run', content: [{ type: 'terminal', terminalId: 'term-1', output: '', exitCode: null }] }]); + state = reduce([{ type: 'terminal-output', terminalId: 'term-1', output: 'one\n' }, { type: 'terminal-output', terminalId: 'term-1', output: 'two\n', exitCode: 0 }], state); + let block = (state.items[0] as Extract).content[0]; + assert.deepEqual(block, { type: 'terminal', terminalId: 'term-1', output: 'one\ntwo\n', exitCode: 0 }); + state = reduce([{ type: 'terminal-output', terminalId: 'term-1', output: 'x'.repeat(70_000) }], state); + block = (state.items[0] as Extract).content[0]; + assert.ok(block?.type === 'terminal' && block.output.length === 64_000 && block.truncated === true); + // Output for a terminal no card shows changes nothing. + assert.equal(reduce([{ type: 'terminal-output', terminalId: 'other', output: 'x' }], state), state); + }); + + it('waits on permissions and closes open ones when the turn ends', () => { + const options = [{ id: 'ok', name: 'Allow', kind: 'allow_once' as const }]; + let state = reduce([ + { type: 'user', id: 'u1', text: 'go', at: AT }, + { type: 'permission', id: 'p1', title: 'Run ls', options }, + { type: 'permission', id: 'p2', title: 'Run rm', options }, + ]); + assert.equal(state.status, 'awaiting'); + state = reduce([{ type: 'permission-resolved', id: 'p1', outcome: 'ok' }], state); + assert.equal(state.status, 'awaiting'); + state = reduce([{ type: 'turn-end', id: 'e1', stopReason: 'end_turn', at: AT }], state); + const permissions = state.items.filter((item) => item.kind === 'permission'); + assert.deepEqual(permissions.map((item) => item.outcome), ['ok', 'cancelled']); + assert.equal(state.status, 'idle'); + assert.equal(state.unread, true); + state = reduce([{ type: 'read' }], state); + assert.equal(state.unread, false); + assert.equal(reduce([{ type: 'read' }], state), state); + }); +}); + +describe('applySessionEvent: metric deltas (AF9)', () => { + it('attaches a delta to the turn it names and ignores an unknown turn', () => { + const delta = { summary: 'x', totals: [{ metric: 'maxComplexity', before: 9, after: 1 }], files: [], moreFiles: 0 }; + const ended = reduce([{ type: 'user', id: 'u1', text: 'go', at: AT }, { type: 'turn-end', id: 'e1', stopReason: 'end_turn', at: AT }]); + const state = reduce([{ type: 'metric-delta', turnId: 'e1', delta }], ended); + const turn = state.items.at(-1); + assert.ok(turn?.kind === 'turn-end'); + assert.deepEqual(turn.metricDelta, delta); + assert.notEqual(turn, ended.items.at(-1), 'a new item, so the chat redraws it'); + assert.equal(state.updatedAt, ended.updatedAt, 'a late delta does not move the chat up the list'); + assert.equal(reduce([{ type: 'metric-delta', turnId: 'nope', delta }], ended), ended); + }); +}); + +describe('ACP mapping', () => { + const ctx = { newId: () => 'n1', terminal: (id: string) => (id === 'term-1' ? { output: 'so far', exitCode: null, truncated: false } : undefined) }; + + it('maps every session/update kind it shows and ignores the rest', () => { + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'hi' } }, ctx), [{ type: 'assistant-chunk', text: 'hi' }]); + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'th' } }, ctx), [{ type: 'thought-chunk', text: 'th' }]); + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'me' } }, ctx), []); + const [created] = mapSessionUpdate({ + sessionUpdate: 'tool_call', toolCallId: 't1', title: 'Run tests', kind: 'execute', status: 'in_progress', + locations: [{ path: '/p/a.ts', line: 3 }], rawInput: { command: 'npm test' }, + content: [{ type: 'terminal', terminalId: 'term-1' }, { type: 'content', content: { type: 'text', text: 'note' } }, { type: 'diff', path: '/p/b.ts', newText: 'new' }], + }, ctx); + assert.deepEqual(created, { + type: 'tool', id: 't1', title: 'Run tests', toolKind: 'execute', status: 'in_progress', + locations: [{ path: '/p/a.ts', line: 3 }], + content: [{ type: 'terminal', terminalId: 'term-1', output: 'so far', exitCode: null }, { type: 'text', text: 'note' }, { type: 'diff', path: '/p/b.ts', oldText: null, newText: 'new' }], + rawInput: '{"command":"npm test"}', + }); + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'failed' }, ctx), [{ type: 'tool', id: 't1', status: 'failed' }]); + assert.deepEqual(mapSessionUpdate({ sessionUpdate: 'plan', entries: [{ content: 'Test', priority: 'high', status: 'pending' }] }, ctx), [{ type: 'plan', entries: [{ content: 'Test', priority: 'high', status: 'pending' }] }]); + 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 }]); + 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), []); + }); + + it('flattens config options, grouped selects and booleans', () => { + const options = mapConfigOptions([ + { type: 'select', id: 'model', name: 'Model', category: 'model', currentValue: 'b', options: [{ group: 'g', name: 'G', options: [{ value: 'a', name: 'A' }, { value: 'b', name: 'B', description: 'best' }] }] }, + { type: 'boolean', id: 'fast', name: 'Fast', currentValue: false }, + ]); + assert.deepEqual(options, [ + { id: 'model', name: 'Model', category: 'model', current: 'b', values: [{ id: 'a', name: 'A' }, { id: 'b', name: 'B', description: 'best' }] }, + { id: 'fast', name: 'Fast', current: 'false', values: [{ id: 'true', name: 'On' }, { id: 'false', name: 'Off' }] }, + ]); + }); + + it('classifies login methods and auth errors', () => { + const specs = mapAuthMethods([ + { id: 'claude-ai-login', name: 'Claude Subscription', type: 'terminal', args: ['--cli', 'auth', 'login'] }, + { id: 'chat-gpt', name: 'ChatGPT' }, + { id: 'key', name: 'API key', type: 'env_var' }, + { id: 'hinted', name: 'Hint', _meta: { 'terminal-auth': { command: 'agy', args: ['acp', '--login'] } } }, + ] as never); + assert.deepEqual(specs.map((spec) => spec.view.type), ['terminal', 'agent', 'env', 'terminal']); + assert.deepEqual(specs[0]?.args, ['--cli', 'auth', 'login']); + assert.equal(specs[3]?.command, 'agy'); + assert.equal(isAuthRequiredError(RequestError.authRequired()), true); + assert.equal(isAuthRequiredError(new Error('Authentication required')), true); + assert.equal(isAuthRequiredError(new Error('Disk full')), false); + assert.equal(stopReasonOf('max_tokens'), 'max_tokens'); + assert.equal(stopReasonOf('weird'), 'end_turn'); + }); + + it('builds prompts with embedded files, links and selections, and slices reads', () => { + const blocks = buildPromptBlocks('Fix it', [ + { kind: 'file', absolutePath: '/p/a.ts', relativePath: 'a.ts', text: 'code' }, + { kind: 'file', absolutePath: '/p/big.bin', relativePath: 'big.bin', text: null }, + { kind: 'selection', absolutePath: '/p/a.ts', relativePath: 'a.ts', startLine: 2, endLine: 3, text: 'x' }, + ], true); + assert.deepEqual(blocks.map((block) => block.type), ['text', 'resource', 'resource_link', 'text']); + assert.deepEqual(buildPromptBlocks('t', [{ kind: 'file', absolutePath: '/p/a.ts', relativePath: 'a.ts', text: 'code' }], false).map((block) => block.type), ['text', 'resource_link']); + assert.equal(sliceLines('1\n2\n3\n4', 2, 2), '2\n3'); + assert.equal(sliceLines('1\n2\n3', null, null), '1\n2\n3'); + assert.equal(sliceLines('1\n2\n3', 3), '3'); + }); + + it('keeps the tail of terminal output at a character boundary and builds login lines', () => { + assert.deepEqual(keepTail('abc', 10), { text: 'abc', truncated: false }); + const kept = keepTail('aé€', 3); + assert.equal(kept.truncated, true); + assert.equal(kept.text, '€'); + assert.equal(loginCommandLine('posix', "'/bin/agent' --login", { ELECTRON_RUN_AS_NODE: '1', PATH: '/bin' }, { PATH: '/bin' }), "env ELECTRON_RUN_AS_NODE='1' '/bin/agent' --login"); + assert.equal(loginCommandLine('powershell', 'agent', { A: '1' }, {}), "$env:A='1'; agent"); + assert.equal(loginCommandLine('cmd', 'agent', {}, {}), 'agent'); + }); +}); + +describe('SessionStore', () => { + it('writes chats, lists projects with the current one first, and reloads running chats as idle', async () => { + const dir = path.join(base, 'store'); + const store = new SessionStore(dir, { debounceMs: 5 }); + const running: AgentSessionState = { + ...emptySession({ id: 'chat-a', title: 'A', agentRef: 'acp:claude', agentName: 'Claude Code', workspaceRoot: '/projects/one', createdAt: AT, updatedAt: '2026-11-27T10:00:01.000Z' }), + status: 'awaiting', + items: [{ kind: 'permission', id: 'p1', title: 'Run', options: [] }], + }; + await store.saveNow(running); + store.save({ ...emptySession({ id: 'chat-b', title: 'B', agentRef: 'acp:codex', agentName: 'Codex', workspaceRoot: '/projects/two', createdAt: AT, updatedAt: '2026-11-27T10:00:02.000Z' }) }); + await store.flush(); + await store.saveNow(emptySession({ id: 'chat-c', title: 'C', agentRef: 'acp:codex', agentName: 'Codex', workspaceRoot: '/projects/one', createdAt: AT, updatedAt: '2026-11-27T10:00:03.000Z' })); + assert.ok(fs.existsSync(path.join(dir, projectKey('/projects/one'), 'chat-a.json'))); + + const reopened = new SessionStore(dir); + const projects = await reopened.listProjects('/projects/two'); + assert.deepEqual(projects.map((project) => [project.root, project.current, project.sessions.map((session) => session.id)]), [ + ['/projects/two', true, ['chat-b']], + ['/projects/one', false, ['chat-c', 'chat-a']], + ]); + const loaded = await reopened.find('chat-a', null); + assert.equal(loaded?.status, 'idle'); + assert.deepEqual(loaded?.items.map((item) => item.kind === 'permission' && item.outcome), ['cancelled']); + const empty = await reopened.listProjects('/projects/new'); + assert.equal(empty[0]?.root, '/projects/new'); + assert.deepEqual(empty[0]?.sessions, []); + await reopened.remove('/projects/one', 'chat-c'); + assert.equal(await reopened.load('/projects/one', 'chat-c'), null); + assert.equal(await reopened.load('/projects/one', '../escape'), null); + }); +}); + +describe('AgentCatalog', () => { + it('finds a preset on PATH, reports a missing one with how to install it, and lists built-in profiles', async () => { + // A POSIX PATH on every host: a Windows drive letter would be split at its ':'. + const bin = '/agents/bin'; + const agentFile = `${bin}/codex-acp`; + const catalog = new AgentCatalog({ + packagesDir: path.join(base, 'packages'), + store: new JsonKeyValueStore(path.join(base, 'catalog.json')), + probe: { isExecutable: (file) => Promise.resolve(file === agentFile), readText: diskProbe.readText }, + env: { PATH: bin, HOME: '/home/u', OPENAI_API_KEY: 'k', ANTHROPIC_API_KEY: 'secret', UNRELATED: 'x' }, + platform: 'linux', + execPath: process.execPath, + builtinProfiles: () => Promise.resolve([{ id: 'p1', name: 'Assistant' }]), + }); + const views = await catalog.list(); + const byRef = new Map(views.map((view) => [view.ref, view])); + assert.equal(byRef.get('acp:codex')?.availability, 'available'); + assert.equal(byRef.get('acp:claude')?.availability, 'missing'); + assert.match(byRef.get('acp:claude')?.detail ?? '', /Press Install, or install it yourself with: npm install -g @agentclientprotocol\/claude-agent-acp/); + assert.deepEqual(byRef.get('builtin:p1'), { ref: 'builtin:p1', name: 'Assistant', kind: 'builtin', description: byRef.get('builtin:p1')?.description, availability: 'available' }); + const codex = catalog.definition('acp:codex'); + assert.ok(codex); + const resolution = await catalog.resolve(codex); + assert.ok(resolution.found); + assert.equal(resolution.launch.command, agentFile); + // Only the vendor's own key reaches the agent. + assert.equal(resolution.launch.env['OPENAI_API_KEY'], 'k'); + assert.equal(resolution.launch.env['ANTHROPIC_API_KEY'], undefined); + assert.equal(resolution.launch.env['UNRELATED'], undefined); + assert.equal(resolution.launch.env['HOME'], '/home/u'); + }); + + it('prefers a package the IDE installed, run by its own Node', async () => { + const packages = path.join(base, 'pkgs'); + const pkg = path.join(packages, 'node_modules', '@google', 'gemini-cli'); + fs.mkdirSync(path.join(pkg, 'dist'), { recursive: true }); + fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({ name: '@google/gemini-cli', bin: { gemini: 'dist/index.js' } })); + fs.writeFileSync(path.join(pkg, 'dist', 'index.js'), ''); + const catalog = new AgentCatalog({ packagesDir: packages, store: new JsonKeyValueStore(path.join(base, 'catalog2.json')), env: { PATH: '' }, platform: 'linux', execPath: '/electron', builtinProfiles: () => Promise.resolve([]) }); + const gemini = catalog.definition('acp:gemini'); + assert.ok(gemini); + const resolution = await catalog.resolve(gemini); + assert.ok(resolution.found); + assert.deepEqual([resolution.launch.command, ...resolution.launch.args], ['/electron', path.join(pkg, 'dist', 'index.js'), '--acp']); + assert.equal(resolution.launch.env['ELECTRON_RUN_AS_NODE'], '1'); + }); + + it('validates and stores custom agents', async () => { + const catalog = new AgentCatalog({ packagesDir: base, store: new JsonKeyValueStore(path.join(base, 'catalog3.json')), env: { PATH: '' }, platform: 'linux', execPath: process.execPath, builtinProfiles: () => Promise.resolve([]) }); + await assert.rejects(catalog.saveCustom({ name: '', command: 'x' }), /name/); + await assert.rejects(catalog.saveCustom({ name: 'A', command: 'x', env: { 'bad name': 'v' } }), /Environment/); + const saved = await catalog.saveCustom({ name: 'Mine', command: 'not-on-path-xyz', args: ['acp'], env: { MODE: 'x' } }); + assert.match(saved.id, /^custom-[a-f0-9]{8}$/); + const view = await catalog.view(saved); + assert.equal(view.availability, 'missing'); + assert.equal(await findOnPath('not-on-path-xyz', { PATH: base }, 'linux', diskProbe), null); + await catalog.removeCustom(saved.id); + assert.deepEqual(catalog.customAgents(), []); + await assert.rejects(catalog.removeCustom('claude'), /custom/); + assert.deepEqual(agentEnvironment({ PATH: '/bin', SECRET: 's' }, null, { X: '1' }), { PATH: '/bin', X: '1' }); + }); +}); + +// ---- A full chat against an in-process fake agent ----------------------------- + +interface FakeAgentLog { + permissionOutcome?: unknown; + cancelled: number; + prompts: unknown[]; +} + +/** A tiny ACP agent: its behaviour is chosen by the prompt's first word. */ +function fakeAgent(log: FakeAgentLog) { + 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' }) + .onConnect((connection) => { + client = connection.client; + }) + .onRequest(methods.agent.initialize, () => ({ + protocolVersion: 1, + agentCapabilities: { loadSession: false, promptCapabilities: { embeddedContext: true } }, + authMethods: [{ id: 'login', name: 'Log in', type: 'terminal', args: ['--login'] }], + })) + .onRequest(methods.agent.session.new, () => ({ + sessionId: 'agent-1', + modes: { currentModeId: 'ask', availableModes: [{ id: 'ask', name: 'Ask' }, { id: 'code', name: 'Code' }] }, + configOptions: [{ type: 'select', id: 'model', name: 'Model', category: 'model', currentValue: 'a', options: [{ value: 'a', name: 'A' }, { value: 'b', name: 'B' }] }], + })) + .onRequest(methods.agent.session.setMode, () => ({})) + .onRequest(methods.agent.session.setConfigOption, ({ params }) => ({ + configOptions: [{ type: 'select', id: 'model', name: 'Model', currentValue: String(params.value), options: [{ value: 'a', name: 'A' }, { value: 'b', name: 'B' }] }], + })) + .onNotification(methods.agent.session.cancel, () => { + log.cancelled++; + }) + .onRequest(methods.agent.session.prompt, async ({ params, client: ctx }) => { + log.prompts.push(params.prompt); + const first = params.prompt[0]; + const text = first?.type === 'text' ? first.text : ''; + const [command, arg] = text.split(' '); + const sid = params.sessionId; + if (command === 'hello') { + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Hi' } }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: ' there' } }); + await update(sid, { sessionUpdate: 'plan', entries: [{ content: 'Say hi', priority: 'low', status: 'completed' }] }); + await update(sid, { sessionUpdate: 'usage_update', used: 5, size: 100 }); + return { stopReason: 'end_turn' }; + } + if (command === 'perm') { + await update(sid, { sessionUpdate: 'tool_call', toolCallId: 'tc1', title: 'Run ls', kind: 'execute', status: 'pending' }); + const response = await ctx.request(methods.client.session.requestPermission, { + sessionId: sid, + toolCall: { toolCallId: 'tc1' }, + options: [{ optionId: 'once', name: 'Allow', kind: 'allow_once' }, { optionId: 'always', name: 'Always', kind: 'allow_always' }, { optionId: 'no', name: 'Reject', kind: 'reject_once' }], + }); + log.permissionOutcome = response.outcome; + return { stopReason: response.outcome.outcome === 'cancelled' ? 'cancelled' : 'end_turn' }; + } + if (command === 'read' || command === 'write') { + try { + if (command === 'read') { + const result = await ctx.request(methods.client.fs.readTextFile, { sessionId: sid, path: arg ?? '', line: 2, limit: 1 }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `READ:${result.content}` } }); + } else { + await ctx.request(methods.client.fs.writeTextFile, { sessionId: sid, path: arg ?? '', content: 'written' }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'WROTE' } }); + } + } catch (error) { + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `ERR:${(error as Error).message}` } }); + } + return { stopReason: 'end_turn' }; + } + if (command === 'term') { + const created = await ctx.request(methods.client.terminal.create, { sessionId: sid, command: 'echo', args: ['from terminal'] }); + await update(sid, { sessionUpdate: 'tool_call', toolCallId: 'tc2', title: 'echo', kind: 'execute', status: 'in_progress', content: [{ type: 'terminal', terminalId: created.terminalId }] }); + const exit = await ctx.request(methods.client.terminal.waitForExit, { sessionId: sid, terminalId: created.terminalId }); + const output = await ctx.request(methods.client.terminal.output, { sessionId: sid, terminalId: created.terminalId }); + await ctx.request(methods.client.terminal.release, { sessionId: sid, terminalId: created.terminalId }); + await update(sid, { sessionUpdate: 'tool_call_update', toolCallId: 'tc2', status: 'completed' }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `EXIT:${exit.exitCode} OUT:${output.output.trim()}` } }); + return { stopReason: 'end_turn' }; + } + if (command === 'auth') { + throw RequestError.authRequired(); + } + return { stopReason: 'end_turn' }; + }); +} + +async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges } = {}) { + const root = path.join(base, name, 'project'); + fs.mkdirSync(root, { recursive: true }); + fs.writeFileSync(path.join(root, 'a.txt'), 'one\ntwo\nthree\n'); + fs.writeFileSync(path.join(base, name, 'secret.txt'), 'secret'); + const catalog = new AgentCatalog({ packagesDir: path.join(base, name, 'packages'), store: new JsonKeyValueStore(path.join(base, name, 'agents.json')), env: { PATH: '' }, platform: process.platform, execPath: process.execPath, builtinProfiles: () => Promise.resolve([]) }); + const custom = await catalog.saveCustom({ name: 'Fake', command: process.execPath, args: [] }); + const log: FakeAgentLog = { cancelled: 0, prompts: [] }; + const messages: AgentSessionMessage[] = []; + const window: WindowPort = { id: 1, send: (message) => messages.push(message), isDestroyed: () => false }; + const written: string[] = []; + const service = new AgentSessionService({ + catalog, + store: new SessionStore(path.join(base, name, 'sessions'), { debounceMs: 5 }), + decisions: new JsonKeyValueStore(path.join(base, name, 'decisions.json')), + rootOf: () => root, + isTrusted: () => options.trusted ?? true, + readText: (file) => fs.promises.readFile(file, 'utf8'), + writeText: async (file, content) => { + written.push(file); + await fs.promises.writeFile(file, content); + }, + openTerminal: () => Promise.reject(new Error('no terminal in tests')), + connect: (_launch, _cwd, handlers) => AcpConnection.inProcess(fakeAgent(log), handlers), + ...(options.changes + ? { + review: options.changes, + beforePrompt: (sessionId: string, workspaceRoot: string) => options.changes!.beforePrompt(sessionId, workspaceRoot), + afterTurn: (sessionId: string, workspaceRoot: string) => options.changes!.afterTurn(sessionId, workspaceRoot), + } + : { beforePrompt: () => Promise.resolve({ checkpointId: 'cp-1' }) }), + ...(options.afterTurn ? { afterTurn: options.afterTurn } : {}), + spawnAllowed: true, + probeDir: path.join(base, name, 'probe'), + homeDir: os.homedir(), + terminalEnv: { PATH: process.env['PATH'] ?? '' }, + cancelGraceMs: 2000, + }); + return { root, service, window, messages, log, written, ref: `acp:${custom.id}` }; +} + +function lastText(state: AgentSessionState): string { + const item = [...state.items].reverse().find((candidate) => candidate.kind === 'assistant'); + return item && 'text' in item ? item.text : ''; +} + +async function waitFor(check: () => boolean, what: string): Promise { + for (let i = 0; i < 200; i++) { + if (check()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for ${what}.`); +} + +describe('AgentSessionService with a fake ACP agent', () => { + it('runs a prompt round trip and streams the same events the renderer applies', async () => { + const { service, window, messages, ref, log } = await setup('roundtrip', { afterTurn: () => Promise.resolve(2) }); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'hello world', [{ kind: 'file', path: 'a.txt' }, { kind: 'selection', path: 'a.txt', startLine: 1, endLine: 2, text: 'one\ntwo' }]); + const state = await service.get(window, created.id); + assert.equal(lastText(state), 'Hi there'); + assert.equal(state.title, 'hello world'); + assert.equal(state.status, 'idle'); + assert.equal(state.agentSessionId, 'agent-1'); + assert.deepEqual(state.modes?.available.map((mode) => mode.id), ['ask', 'code']); + assert.equal(state.configOptions[0]?.current, 'a'); + assert.deepEqual(state.usage, { used: 5, size: 100 }); + assert.equal(state.plan.length, 1); + assert.equal(state.pendingChanges, 2); + const user = state.items.find((item) => item.kind === 'user'); + assert.ok(user?.kind === 'user'); + assert.deepEqual(user.attachments, ['a.txt', 'a.txt:1-2']); + assert.equal(user.checkpoint, 'cp-1'); + assert.equal(state.items.at(-1)?.kind, 'turn-end'); + // The file was embedded (the agent accepts embedded context). + assert.deepEqual((log.prompts[0] as { type: string }[]).map((block) => block.type), ['text', 'resource', 'text']); + // Replaying the streamed events on the created state gives the main process's state. + let replayed = created; + for (const message of messages) { + if (message.kind === 'event' && message.sessionId === created.id) { + replayed = applySessionEvent(replayed, message.event, message.updatedAt); + } + } + assert.deepEqual(replayed, state); + + await service.setConfigOption(window, created.id, 'model', 'b'); + await service.setMode(window, created.id, 'code'); + const after = await service.get(window, created.id); + assert.equal(after.configOptions[0]?.current, 'b'); + assert.equal(after.modes?.current, 'code'); + await service.markRead(window, created.id); + assert.equal((await service.get(window, created.id)).unread, false); + const projects = await service.listProjects(window); + assert.equal(projects[0]?.sessions[0]?.id, created.id); + await service.remove(window, created.id); + await assert.rejects(service.get(window, created.id), /no longer exists/); + 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); + const turn = service.prompt(window, created.id, 'perm', []); + let waiting: Extract | undefined; + await waitFor(() => { + void service.get(window, created.id).then((state) => { + waiting = state.items.find((item): item is Extract => item.kind === 'permission' && item.outcome === undefined); + }); + return waiting !== undefined; + }, 'the permission request'); + assert.ok(waiting); + assert.equal(waiting.title, 'Run ls'); + assert.equal((await service.get(window, created.id)).status, 'awaiting'); + await assert.rejects(service.respondPermission(window, created.id, waiting.id, 'invented'), /not one the agent offered/); + await service.respondPermission(window, created.id, waiting.id, 'always'); + await turn; + assert.deepEqual(log.permissionOutcome, { outcome: 'selected', optionId: 'always' }); + // The same agent and tool kind is answered without asking. + log.permissionOutcome = undefined; + await service.prompt(window, created.id, 'perm', []); + assert.deepEqual(log.permissionOutcome, { outcome: 'selected', optionId: 'always' }); + const state = await service.get(window, created.id); + assert.equal(state.items.filter((item) => item.kind === 'permission').length, 1); + await service.stopAll(); + }); + + it('cancels a waiting permission when the person stops the turn', async () => { + const { service, window, ref, log } = await setup('cancel'); + 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)); + await service.cancel(window, created.id); + await turn; + assert.deepEqual(log.permissionOutcome, { outcome: 'cancelled' }); + assert.equal(log.cancelled, 1); + const state = await service.get(window, created.id); + const end = state.items.at(-1); + assert.ok(end?.kind === 'turn-end' && end.stopReason === 'cancelled'); + await service.stopAll(); + }); + + it('serves file reads and writes inside the project only', async () => { + const { root, service, window, ref, written } = await setup('files'); + const created = await service.create(window, ref); + await service.prompt(window, created.id, `read ${path.join(root, 'a.txt')}`, []); + assert.equal(lastText(await service.get(window, created.id)), 'READ:two'); + await service.prompt(window, created.id, `read ${path.join(root, '..', 'secret.txt')}`, []); + assert.match(lastText(await service.get(window, created.id)), /^ERR:.*outside the project folder/); + await service.prompt(window, created.id, `write ${path.join(root, 'new.txt')}`, []); + assert.equal(fs.readFileSync(path.join(root, 'new.txt'), 'utf8'), 'written'); + await service.prompt(window, created.id, `write ${path.join(root, '..', 'evil.txt')}`, []); + assert.match(lastText(await service.get(window, created.id)), /^ERR:.*outside/); + assert.equal(fs.existsSync(path.join(root, '..', 'evil.txt')), false); + if (process.platform !== 'win32') { + fs.symlinkSync(path.join(root, '..'), path.join(root, 'link')); + await service.prompt(window, created.id, `read ${path.join(root, 'link', 'secret.txt')}`, []); + assert.match(lastText(await service.get(window, created.id)), /^ERR:.*outside/); + } + assert.deepEqual(written, [path.join(root, 'new.txt')]); + await assert.rejects(service.prompt(window, created.id, 'x', [{ kind: 'file', path: '../secret.txt' }]), /outside the project/); + await service.stopAll(); + }); + + it('reviews the chat\'s changes: list, diff, undo, keep and restore to a message (AF5, AF6)', async () => { + const changes = new SessionChanges({ storageDir: path.join(base, 'review', 'checkpoints'), bases: new JsonKeyValueStore(path.join(base, 'review', 'review.json')) }); + const { root, service, window, ref } = await setup('review', { changes }); + const created = await service.create(window, ref); + const file = path.join(root, 'a.txt'); + await service.prompt(window, created.id, `write ${file}`, []); + let state = await service.get(window, created.id); + assert.equal(state.pendingChanges, 1); + const first = state.items.find((item) => item.kind === 'user'); + assert.ok(first?.kind === 'user' && first.checkpoint && /^[0-9a-f]{40,64}$/.test(first.checkpoint)); + + let listed = await service.changes(window, created.id); + assert.deepEqual(listed.files.map((entry) => [entry.path, entry.status]), [['a.txt', 'modified']]); + assert.deepEqual(await service.changeDiff(window, created.id, './a.txt'), { path: 'a.txt', oldText: 'one\ntwo\nthree\n', newText: 'written' }); + + // Undo puts the file back and the chat's count follows. + listed = await service.undoChanges(window, created.id, ['a.txt']); + 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); + + // Keep accepts the change: no longer pending, still on disk. + await service.prompt(window, created.id, `write ${file}`, []); + assert.equal((await service.get(window, created.id)).pendingChanges, 1); + listed = await service.keepChanges(window, created.id, 'all'); + assert.equal(listed.files.length, 0); + assert.equal(fs.readFileSync(file, 'utf8'), 'written'); + + // Restore to the first message: preview lists the file, restore writes it. + assert.deepEqual(await service.previewRestore(window, created.id, first.checkpoint), ['a.txt']); + assert.deepEqual(await service.restoreCheckpoint(window, created.id, first.checkpoint), ['a.txt']); + assert.equal(fs.readFileSync(file, 'utf8'), 'one\ntwo\nthree\n'); + state = await service.get(window, created.id); + assert.equal(state.pendingChanges, 1, 'the restore differs from what was kept'); + + // 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/); + await assert.rejects(service.undoChanges(window, created.id, []), /Invalid list/); + await assert.rejects(service.keepChanges(window, created.id, [42]), /Invalid file path/); + await assert.rejects(service.undoChanges(window, created.id, ['.git/config']), /\.git/); + await service.remove(window, created.id); + assert.equal(changes.reviewBase(created.id), null); + await service.stopAll(); + await changes.dispose(); + }); + + it('refuses to undo or restore while the agent works', async () => { + const changes = new SessionChanges({ storageDir: path.join(base, 'review-busy', 'checkpoints'), bases: new JsonKeyValueStore(path.join(base, 'review-busy', 'review.json')) }); + const { service, window, ref, log } = await setup('review-busy', { changes }); + const created = await service.create(window, ref); + const turn = service.prompt(window, created.id, 'perm', []); + await waitFor(() => log.prompts.length === 1, 'the prompt'); + const user = (await service.get(window, created.id)).items.find((item) => item.kind === 'user'); + assert.ok(user?.kind === 'user' && user.checkpoint); + await assert.rejects(service.undoChanges(window, created.id, 'all'), /still working/); + await assert.rejects(service.restoreCheckpoint(window, created.id, user.checkpoint), /still working/); + // Reading is fine while it works. + assert.deepEqual((await service.changes(window, created.id)).files, []); + await service.cancel(window, created.id); + await turn; + await service.stopAll(); + await changes.dispose(); + }); + + it('attaches a metric delta to its turn and refuses review actions without checkpoints', async () => { + const { service, window, ref, messages } = await setup('delta'); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'hello', []); + const turn = (await service.get(window, created.id)).items.at(-1); + assert.ok(turn?.kind === 'turn-end'); + const delta = { summary: '1 file (1 changed)', totals: [{ metric: 'codeLines', before: 10, after: 4 }], files: [], moreFiles: 0 }; + service.attachMetricDelta(created.id, turn.id, delta); + service.attachMetricDelta(created.id, 'unknown-turn', delta); + const after = await service.get(window, created.id); + const ended = after.items.at(-1); + assert.ok(ended?.kind === 'turn-end'); + assert.deepEqual(ended.metricDelta, delta); + assert.equal(messages.filter((message) => message.kind === 'event' && message.event.type === 'metric-delta').length, 1); + await assert.rejects(service.changes(window, created.id), /not available/); + await service.stopAll(); + }); + + it('runs agent terminals and shows their output in the tool card', { skip: process.platform === 'win32' }, async () => { + const { service, window, ref } = await setup('terminal'); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'term', []); + const state = await service.get(window, created.id); + assert.equal(lastText(state), 'EXIT:0 OUT:from terminal'); + const tool = state.items.find((item) => item.kind === 'tool' && item.id === 'tc2'); + assert.ok(tool?.kind === 'tool'); + const block = tool.content[0]; + assert.ok(block?.type === 'terminal'); + assert.equal(block.output.trim(), 'from terminal'); + assert.equal(block.exitCode, 0); + await service.stopAll(); + }); + + it('turns an auth error into a notice and marks the agent as needing a login', async () => { + const { service, window, ref } = await setup('auth'); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'auth', []); + const state = await service.get(window, created.id); + const notice = state.items.find((item) => item.kind === 'notice' && item.level === 'error'); + assert.ok(notice?.kind === 'notice' && /log in/i.test(notice.text)); + assert.equal(state.status, 'error'); + const agents = await service.listAgents(window); + const fake = agents.find((view) => view.ref === ref); + assert.equal(fake?.availability, 'needs-login'); + assert.deepEqual(fake?.authMethods?.map((method) => method.type), ['terminal']); + await service.stopAll(); + }); + + it('starts no agent in an untrusted folder and refuses the built-in agent', async () => { + const { service, window, ref, log } = await setup('untrusted', { trusted: false }); + const created = await service.create(window, ref); + await service.prompt(window, created.id, 'hello', []); + const state = await service.get(window, created.id); + assert.ok(state.items.some((item) => item.kind === 'notice' && /Restricted Mode/.test(item.text))); + assert.equal(log.prompts.length, 0); + await assert.rejects(service.create(window, 'builtin:p1'), /Agents view/); + await assert.rejects(service.get(window, '../x'), /Invalid chat/); + 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[] = []; + const handlers = { + onUpdate: (_id: string, update: unknown) => updates.push(update), + requestPermission: () => Promise.resolve({ outcome: { outcome: 'cancelled' as const } }), + readTextFile: () => Promise.reject(new Error('no')), + writeTextFile: () => Promise.reject(new Error('no')), + createTerminal: () => Promise.reject(new Error('no')), + terminalOutput: () => ({ output: '', truncated: false }), + waitForTerminalExit: () => Promise.reject(new Error('no')), + killTerminal: () => undefined, + releaseTerminal: () => undefined, + }; + const script = path.join(import.meta.dirname, 'fixtures', 'fakeAcpAgent.mjs'); + const connection = AcpConnection.spawn({ command: process.execPath, args: [script], env: { PATH: process.env['PATH'] ?? '' } }, import.meta.dirname, handlers); + const init = await connection.initialize(); + assert.equal(init.protocolVersion, 1); + const session = await connection.newSession(import.meta.dirname, []); + const response = await connection.prompt(session.sessionId, [{ type: 'text', text: 'ping' }]); + assert.equal(response.stopReason, 'end_turn'); + assert.deepEqual(updates, [{ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'echo:ping' } }]); + const closed = new Promise((resolve) => connection.onClose(() => resolve())); + connection.close(); + await closed; + assert.equal(connection.isClosed, true); + }); + + it('rejects pending requests with the reason when the agent cannot start', async () => { + const connection = AcpConnection.spawn({ command: path.join(base, 'no-such-agent'), args: [], env: {} }, base, {} as never); + await assert.rejects(connection.initialize(), /no-such-agent|ENOENT|exited/); + }); + + it('reports the exit code and the stderr tail when the agent dies, not just a closed stream', async () => { + const crash = 'process.stdin.once("data", () => { process.stderr.write("Cannot find module foo\\n"); process.exit(3); });'; + const connection = AcpConnection.spawn({ command: process.execPath, args: ['-e', crash], env: { PATH: process.env['PATH'] ?? '' } }, base, {} as never); + await assert.rejects(connection.initialize(), /exited with code 3.*Cannot find module foo/); + }); +}); + diff --git a/apps/ide/test/agentWorktrees.test.ts b/apps/ide/test/agentWorktrees.test.ts new file mode 100644 index 000000000..36aedeebb --- /dev/null +++ b/apps/ide/test/agentWorktrees.test.ts @@ -0,0 +1,346 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { agent, methods, type AgentContext } from '@agentclientprotocol/sdk'; +import { applySessionEvent, emptySession, type AgentSessionState, type WorktreeStatusView } from '../src/shared/agentSession.ts'; +import { JsonKeyValueStore } from '../src/main/core/jsonStore.ts'; +import { AcpConnection } from '../src/main/agentSessions/acpConnection.ts'; +import { AgentCatalog } from '../src/main/agentSessions/agentCatalog.ts'; +import { AgentSessionService, type WindowPort } from '../src/main/agentSessions/agentSessionService.ts'; +import { SessionStore } from '../src/main/agentSessions/sessionStore.ts'; +import { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; +import { + branchLabel, mergeOutcome, parseWorktreeChoice, suggestedCommitMessage, worktreeActions, worktreeSummary, +} from '../src/renderer/agentFirst/worktreeModel.ts'; + +/** + * AF12 (#277): chats in their own git worktree, end to end through + * AgentSessionService with a real temporary repository and an in-process + * fake ACP agent (the pattern of agentSessions.test.ts). + */ + +const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-agent-worktrees-'))); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +function git(cwd: string, ...args: string[]): string { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + if (!key.startsWith('GIT_')) { + env[key] = value; + } + } + return execFileSync('git', args, { cwd, env, encoding: 'utf8' }); +} + +function repo(name: string): string { + const root = path.join(base, name, 'project'); + fs.mkdirSync(root, { recursive: true }); + git(root, 'init', '-q', '-b', 'main'); + git(root, 'config', 'user.name', 'Test Person'); + git(root, 'config', 'user.email', 'test@example.invalid'); + git(root, 'config', 'commit.gpgsign', 'false'); + // Git for Windows checks files out with CRLF by default; the tests compare bytes. + git(root, 'config', 'core.autocrlf', 'false'); + fs.writeFileSync(path.join(root, 'a.txt'), 'one\ntwo\nthree\n'); + git(root, 'add', '-A'); + git(root, 'commit', '-q', '-m', 'initial'); + return root; +} + +interface AgentLog { + connectCwds: string[]; + sessionCwds: string[]; +} + +/** A tiny ACP agent: `write `, `read `, `pwd` (a terminal running Node, so it works on every OS), anything else ends the turn. */ +function fakeAgent(log: AgentLog) { + let client: AgentContext | null = null; + const say = (sessionId: string, text: string): Promise => (client as AgentContext).notify(methods.client.session.update, { sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } }); + return agent({ name: 'fake' }) + .onConnect((connection) => { + client = connection.client; + }) + .onRequest(methods.agent.initialize, () => ({ protocolVersion: 1, agentCapabilities: { loadSession: false } })) + .onRequest(methods.agent.session.new, ({ params }) => { + log.sessionCwds.push(params.cwd); + return { sessionId: 'agent-1' }; + }) + .onRequest(methods.agent.session.prompt, async ({ params, client: ctx }) => { + const first = params.prompt[0]; + const [command, arg] = (first?.type === 'text' ? first.text : '').split(' '); + const sid = params.sessionId; + try { + if (command === 'write') { + await ctx.request(methods.client.fs.writeTextFile, { sessionId: sid, path: arg ?? '', content: 'written\n' }); + await say(sid, 'WROTE'); + } else if (command === 'read') { + const result = await ctx.request(methods.client.fs.readTextFile, { sessionId: sid, path: arg ?? '' }); + await say(sid, `READ:${result.content}`); + } else if (command === 'pwd') { + const created = await ctx.request(methods.client.terminal.create, { sessionId: sid, command: process.execPath, args: ['-e', 'process.stdout.write(process.cwd())'], env: [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }] }); + await ctx.request(methods.client.terminal.waitForExit, { sessionId: sid, terminalId: created.terminalId }); + const output = await ctx.request(methods.client.terminal.output, { sessionId: sid, terminalId: created.terminalId }); + await ctx.request(methods.client.terminal.release, { sessionId: sid, terminalId: created.terminalId }); + await say(sid, `PWD:${output.output.trim()}`); + } + } catch (error) { + await say(sid, `ERR:${(error as Error).message}`); + } + return { stopReason: 'end_turn' }; + }); +} + +async function setup(name: string, options: { trusted?: boolean; storage?: boolean } = {}) { + const root = repo(name); + const dir = path.join(base, name); + const catalog = new AgentCatalog({ packagesDir: path.join(dir, 'packages'), store: new JsonKeyValueStore(path.join(dir, 'agents.json')), env: { PATH: '' }, platform: process.platform, execPath: process.execPath, builtinProfiles: () => Promise.resolve([]) }); + const custom = await catalog.saveCustom({ name: 'Fake', command: process.execPath, args: [] }); + const log: AgentLog = { connectCwds: [], sessionCwds: [] }; + const window: WindowPort = { id: 1, send: () => undefined, isDestroyed: () => false }; + const changes = new SessionChanges({ storageDir: path.join(dir, 'checkpoints'), bases: new JsonKeyValueStore(path.join(dir, 'review.json')) }); + const storageDir = path.join(dir, 'userData', 'worktrees'); + const sessionsDir = path.join(dir, 'sessions'); + const service = new AgentSessionService({ + catalog, + store: new SessionStore(sessionsDir, { debounceMs: 5 }), + decisions: new JsonKeyValueStore(path.join(dir, 'decisions.json')), + rootOf: () => root, + isTrusted: () => options.trusted ?? true, + readText: (file) => fs.promises.readFile(file, 'utf8'), + writeText: (file, content) => fs.promises.writeFile(file, content), + openTerminal: () => Promise.reject(new Error('no terminal in tests')), + connect: (_launch, cwd, handlers) => { + log.connectCwds.push(cwd); + return AcpConnection.inProcess(fakeAgent(log), handlers); + }, + review: changes, + beforePrompt: (sessionId, workspaceRoot) => changes.beforePrompt(sessionId, workspaceRoot), + afterTurn: (sessionId, workspaceRoot) => changes.afterTurn(sessionId, workspaceRoot), + ...(options.storage === false ? {} : { worktreeStorageDir: storageDir }), + spawnAllowed: true, + probeDir: path.join(dir, 'probe'), + homeDir: os.homedir(), + terminalEnv: { PATH: process.env['PATH'] ?? '' }, + cancelGraceMs: 2000, + }); + return { root, service, window, log, storageDir, sessionsDir, ref: `acp:${custom.id}` }; +} + +function lastText(state: AgentSessionState): string { + const item = [...state.items].reverse().find((candidate) => candidate.kind === 'assistant'); + return item && 'text' in item ? item.text : ''; +} + +async function errorOf(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return (error as Error).message; + } + assert.fail('expected a refusal'); +} + +function branchExists(root: string, branch: string): boolean { + try { + git(root, 'rev-parse', '--verify', '-q', `refs/heads/${branch}`); + return true; + } catch { + return false; + } +} + +describe('AgentSessionService: chats in their own worktree (AF12)', () => { + it('runs the agent in the worktree, confines it there, and commits, merges and discards it', async () => { + const { root, service, window, log, storageDir, sessionsDir, ref } = await setup('lifecycle'); + assert.deepEqual(await service.worktreeAvailability(window), { ok: true, message: null }); + + const created = await service.create(window, ref, { worktree: true }); + const worktree = created.worktree; + assert.ok(worktree); + assert.match(worktree.branch, /^codexr\/agent\/fake-[0-9a-f]{6}$/); + assert.ok(worktree.path.startsWith(storageDir + path.sep), worktree.path); + assert.equal(worktree.cwd, worktree.path); + assert.equal(worktree.repoRoot, root); + assert.equal(created.workspaceRoot, root, 'the chat still belongs to the project'); + + // The agent starts in the worktree, and session/new names it. + await service.prompt(window, created.id, 'pwd', []); + assert.deepEqual(log.connectCwds, [worktree.cwd]); + assert.deepEqual(log.sessionCwds, [worktree.cwd]); + const printed = lastText(await service.get(window, created.id)) ?? ''; + assert.ok(printed.startsWith('PWD:'), printed); + // Compared as real paths: Windows may print a short (8.3) or differently cased temp path. + assert.equal(fs.realpathSync.native(printed.slice(4)), fs.realpathSync.native(worktree.cwd)); + + // It writes in the worktree only. + await service.prompt(window, created.id, `write ${path.join(worktree.cwd, 'new.txt')}`, []); + assert.equal(lastText(await service.get(window, created.id)), 'WROTE'); + assert.ok(fs.existsSync(path.join(worktree.cwd, 'new.txt'))); + assert.ok(!fs.existsSync(path.join(root, 'new.txt'))); + await service.prompt(window, created.id, `write ${path.join(root, 'escape.txt')}`, []); + assert.match(lastText(await service.get(window, created.id)), /^ERR:.*outside the chat's worktree/); + assert.ok(!fs.existsSync(path.join(root, 'escape.txt'))); + await service.prompt(window, created.id, `read ${path.join(root, 'a.txt')}`, []); + assert.match(lastText(await service.get(window, created.id)), /^ERR:.*outside/); + + // The Changes tab and the checkpoints work on the worktree. + const changes = await service.changes(window, created.id); + assert.deepEqual(changes.files.map((file) => file.path), ['new.txt']); + assert.equal((await service.get(window, created.id)).pendingChanges, 1); + + // Status, then a merge refused while the agent's work is not committed. + let status: WorktreeStatusView = await service.worktreeStatus(window, created.id); + assert.equal(status.into, 'main'); + assert.equal(status.exists, true); + assert.deepEqual(status.files.map((file) => [file.path, file.status, file.uncommitted]), [['new.txt', 'added', true]]); + assert.equal(status.ahead, 0); + assert.equal(status.hasUncommitted, true); + assert.match(await errorOf(service.worktreeMerge(window, created.id, 'merge')), /uncommitted changes.*Files: new\.txt/); + + const commit = await service.worktreeCommit(window, created.id, 'Add new.txt'); + assert.equal(commit.fileCount, 1); + assert.ok(commit.commit); + assert.deepEqual(await service.worktreeCommit(window, created.id, 'Again'), { commit: null, fileCount: 0 }); + await assert.rejects(service.worktreeCommit(window, created.id, ' '), /needs a message/); + status = await service.worktreeStatus(window, created.id); + assert.equal(status.ahead, 1); + assert.equal(status.hasUncommitted, false); + + const merged = await service.worktreeMerge(window, created.id, 'merge'); + assert.equal(merged.into, 'main'); + assert.equal(merged.nothingToMerge, false); + assert.equal(fs.readFileSync(path.join(root, 'new.txt'), 'utf8'), 'written\n'); + assert.equal((await service.worktreeMerge(window, created.id, 'squash')).nothingToMerge, true); + await assert.rejects(service.worktreeMerge(window, created.id, 'rebase'), /Unknown merge strategy/); + + // The worktree record is kept with the chat, on disk. + const stored = await new SessionStore(sessionsDir).find(created.id, root); + assert.deepEqual(stored?.worktree, worktree); + const listed = (await service.listProjects(window))[0]?.sessions.find((session) => session.id === created.id); + assert.equal(listed?.worktree?.branch, worktree.branch); + + // Discard: folder and branch gone, the chat kept read-only. + await service.worktreeDiscard(window, created.id); + assert.ok(!fs.existsSync(worktree.path)); + assert.ok(!branchExists(root, worktree.branch)); + const discarded = await service.get(window, created.id); + assert.equal(discarded.worktree?.removed, true); + assert.equal(discarded.pendingChanges, 0); + await assert.rejects(service.prompt(window, created.id, 'pwd', []), /discarded/); + assert.equal((await service.worktreeStatus(window, created.id)).removed, true); + await assert.rejects(service.worktreeDiscard(window, created.id), /discarded/); + await service.remove(window, created.id, { removeWorktree: true }); + await assert.rejects(service.get(window, created.id), /no longer exists/); + }); + + it('refuses a squash that would conflict, leaving the project as it was', async () => { + const { root, service, window, ref } = await setup('conflict'); + const created = await service.create(window, ref, { worktree: true }); + const worktree = created.worktree; + assert.ok(worktree); + await service.prompt(window, created.id, `write ${path.join(worktree.cwd, 'a.txt')}`, []); + await service.worktreeCommit(window, created.id, 'Rewrite a.txt'); + fs.writeFileSync(path.join(root, 'a.txt'), 'changed in the project\n'); + git(root, 'commit', '-q', '-am', 'project change'); + const head = git(root, 'rev-parse', 'HEAD'); + const status = await service.worktreeStatus(window, created.id); + assert.equal(status.behind, 1); + assert.match(await errorOf(service.worktreeMerge(window, created.id, 'squash')), /would conflict\. Nothing was changed\. Files: a\.txt/); + assert.equal(git(root, 'rev-parse', 'HEAD'), head); + assert.equal(git(root, 'status', '--porcelain'), ''); + await service.stopAll(); + }); + + it('asks nothing of a plain chat, and keeps or removes the worktree when its chat is deleted', async () => { + const { root, service, window, ref } = await setup('remove'); + const plain = await service.create(window, ref); + assert.equal(plain.worktree, undefined); + await assert.rejects(service.worktreeStatus(window, plain.id), /does not have a worktree/); + + const kept = await service.create(window, ref, { worktree: true }); + assert.ok(kept.worktree); + await service.remove(window, kept.id); + assert.ok(fs.existsSync(kept.worktree.path), 'without removeWorktree the worktree is kept'); + assert.ok(branchExists(root, kept.worktree.branch)); + + const removed = await service.create(window, ref, { worktree: true }); + assert.ok(removed.worktree); + await service.remove(window, removed.id, { removeWorktree: true }); + assert.ok(!fs.existsSync(removed.worktree.path)); + assert.ok(!branchExists(root, removed.worktree.branch)); + await service.stopAll(); + }); + + it('only uses a worktree record the IDE created, and refuses worktrees where they cannot be', async () => { + const { root, service, window, sessionsDir, ref } = await setup('records'); + // A record pointing at the project itself (a tampered file) is never acted on. + const forged: AgentSessionState = applySessionEvent( + emptySession({ id: 'forged-chat', title: 'Forged', agentRef: ref, agentName: 'Fake', workspaceRoot: root, createdAt: '2026-11-27T10:00:00.000Z', updatedAt: '2026-11-27T10:00:00.000Z' }), + { type: 'worktree', worktree: { branch: 'codexr/agent/x-000000', path: root, cwd: root, baseCommit: 'HEAD', repoRoot: root } }, + ); + await new SessionStore(sessionsDir).saveNow(forged); + await assert.rejects(service.worktreeStatus(window, 'forged-chat'), /not one the IDE created/); + await assert.rejects(service.worktreeDiscard(window, 'forged-chat'), /not one the IDE created/); + await assert.rejects(service.prompt(window, 'forged-chat', 'pwd', []), /not one the IDE created/); + assert.ok(fs.existsSync(path.join(root, 'a.txt'))); + + const untrusted = await setup('untrusted', { trusted: false }); + assert.equal((await untrusted.service.worktreeAvailability(untrusted.window)).ok, false); + await assert.rejects(untrusted.service.create(untrusted.window, untrusted.ref, { worktree: true }), /Restricted Mode/); + + const noStorage = await setup('no-storage', { storage: false }); + assert.deepEqual(await noStorage.service.worktreeAvailability(noStorage.window), { ok: false, message: 'Worktrees are not available here.' }); + + const notRepo = await setup('not-repo'); + fs.rmSync(path.join(notRepo.root, '.git'), { recursive: true, force: true }); + const availability = await notRepo.service.worktreeAvailability(notRepo.window); + assert.equal(availability.ok, false); + assert.match(availability.message ?? '', /not inside a git repository/); + await assert.rejects(notRepo.service.create(notRepo.window, notRepo.ref, { worktree: true }), /not inside a git repository/); + for (const each of [service, untrusted.service, noStorage.service, notRepo.service]) { + await each.stopAll(); + } + }); +}); + +describe('worktree bar model (AF12)', () => { + const status = (extra: Partial = {}): WorktreeStatusView => ({ + branch: 'codexr/agent/fix-abc123', into: 'main', exists: true, removed: false, files: [], ahead: 0, behind: 0, hasUncommitted: false, ...extra, + }); + + it('labels branches and summarises a status', () => { + assert.equal(branchLabel({ branch: 'codexr/agent/fix-abc123' }), 'fix-abc123'); + assert.equal(branchLabel({ branch: 'feature/x' }), 'feature/x'); + assert.equal(worktreeSummary(status()), 'No changes yet, 0 commits ahead'); + assert.equal(worktreeSummary(status({ + files: [{ path: 'a', status: 'added', committed: false, uncommitted: true }, { path: 'b', status: 'modified', committed: true, uncommitted: false }], + ahead: 1, behind: 2, hasUncommitted: true, + })), '2 files changed (1 uncommitted), 1 commit ahead, 2 behind main'); + assert.match(worktreeSummary(status({ removed: true })), /discarded/); + assert.match(worktreeSummary(status({ exists: false, ahead: 2 })), /missing.*2 commits/); + }); + + it('enables the actions that can work now', () => { + assert.deepEqual(worktreeActions(status({ hasUncommitted: true }), false), { commit: true, merge: false, discard: true, mergeHint: 'Commit the agent\'s changes first.' }); + assert.deepEqual(worktreeActions(status({ ahead: 2 }), false), { commit: false, merge: true, discard: true, mergeHint: null }); + assert.equal(worktreeActions(status({ ahead: 2 }), true).merge, false, 'not while the agent works'); + assert.equal(worktreeActions(status({ ahead: 2, into: null }), false).mergeHint, 'The project is not on a branch (detached HEAD).'); + assert.equal(worktreeActions(status(), false).mergeHint, 'Nothing to merge yet.'); + assert.deepEqual(worktreeActions(status({ removed: true }), false), { commit: false, merge: false, discard: false, mergeHint: null }); + assert.deepEqual(worktreeActions(null, false), { commit: false, merge: false, discard: false, mergeHint: null }); + }); + + it('suggests a commit message, words outcomes and reads the remembered choice', () => { + assert.equal(suggestedCommitMessage(' Fix the parser '), 'Fix the parser'); + assert.equal(suggestedCommitMessage('New chat'), 'Changes by the agent'); + assert.equal(mergeOutcome({ strategy: 'merge', into: 'main', nothingToMerge: false }), 'Merged into main.'); + assert.equal(mergeOutcome({ strategy: 'squash', into: 'dev', nothingToMerge: false }), 'Squashed into dev as one commit.'); + assert.match(mergeOutcome({ strategy: 'merge', into: 'main', nothingToMerge: true }), /^Nothing to merge/); + assert.equal(parseWorktreeChoice('1'), true); + assert.equal(parseWorktreeChoice('0'), false); + assert.equal(parseWorktreeChoice(null), false); + }); +}); diff --git a/apps/ide/test/checkpoints.test.ts b/apps/ide/test/checkpoints.test.ts new file mode 100644 index 000000000..f4585f161 --- /dev/null +++ b/apps/ide/test/checkpoints.test.ts @@ -0,0 +1,327 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { CheckpointStore, normalizeProjectPath, shadowRepoName } from '../src/main/checkpoints/checkpointStore.ts'; +import { + baseFor, basesToQuery, createReviewBase, keepAll, keepFile, keepFiles, mergePendingChanges, parseReviewBase, serializeReviewBase, +} from '../src/main/checkpoints/reviewBase.ts'; + +const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-checkpoints-'))); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +let counter = 0; + +/** A fresh project folder with `files`, and a store whose shadow repos live outside it. */ +function project(files: Record, options: { maxFiles?: number; maxFileBytes?: number } = {}): { root: string; store: CheckpointStore } { + counter += 1; + const root = path.join(base, `project-${counter}`); + for (const [relative, content] of Object.entries(files)) { + write(root, relative, content); + } + fs.mkdirSync(root, { recursive: true }); + const store = new CheckpointStore({ storageDir: path.join(base, 'storage'), projectRoot: root, ...options }); + return { root, store }; +} + +function write(root: string, relative: string, content: string | Buffer): void { + const target = path.join(root, ...relative.split('/')); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); +} + +function read(root: string, relative: string): string | null { + const target = path.join(root, ...relative.split('/')); + return fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null; +} + +function realGit(cwd: string, ...args: string[]): string { + return execFileSync('git', ['-c', 'user.name=Test', '-c', 'user.email=test@example.com', '-c', 'commit.gpgsign=false', ...args], { cwd, encoding: 'utf8' }); +} + +async function snapshotOrFail(store: CheckpointStore, label: string): Promise { + const checkpoint = await store.snapshot(label); + assert.ok(checkpoint, `snapshot "${label}" returned null: ${store.disabledReason ?? ''}`); + return checkpoint.id; +} + +describe('CheckpointStore: snapshots and changes', () => { + it('lists added, modified and deleted files with line counts', async () => { + const { root, store } = project({ 'a.txt': 'one\ntwo\nthree\n', 'src/b.ts': 'export const b = 1;\n', 'gone.md': 'bye\n' }); + const checkpoint = await store.snapshot('Before prompt 1'); + assert.ok(checkpoint); + assert.match(checkpoint.id, /^[0-9a-f]{40,64}$/); + assert.equal(checkpoint.label, 'Before prompt 1'); + assert.equal(checkpoint.fileCount, 3); + assert.equal(typeof checkpoint.createdAt, 'number'); + + write(root, 'a.txt', 'one\nTWO\nthree\nfour\n'); + write(root, 'new/c.txt', 'c\n'); + fs.rmSync(path.join(root, 'gone.md')); + write(root, 'image.bin', Buffer.from([0, 1, 2, 0, 255])); + + const changes = await store.changes(checkpoint.id); + assert.deepEqual(changes, [ + { path: 'a.txt', status: 'modified', additions: 2, deletions: 1, binary: false }, + { path: 'gone.md', status: 'deleted', additions: 0, deletions: 1, binary: false }, + { path: 'image.bin', status: 'added', additions: 0, deletions: 0, binary: true }, + { path: 'new/c.txt', status: 'added', additions: 1, deletions: 0, binary: false }, + ]); + assert.deepEqual(await store.changes(await snapshotOrFail(store, 'now')), []); + }); + + it('reads a file at a checkpoint and the diff text against disk', async () => { + const { root, store } = project({ 'a.txt': 'old\n' }); + const id = await snapshotOrFail(store, 'one'); + write(root, 'a.txt', 'new\n'); + write(root, 'b.txt', 'b\n'); + assert.equal(await store.fileAt(id, 'a.txt'), 'old\n'); + assert.equal(await store.fileAt(id, 'b.txt'), null); + assert.deepEqual(await store.diffText(id, 'a.txt'), { oldText: 'old\n', newText: 'new\n' }); + assert.deepEqual(await store.diffText(id, 'b.txt'), { oldText: null, newText: 'b\n' }); + fs.rmSync(path.join(root, 'a.txt')); + assert.deepEqual(await store.diffText(id, 'a.txt'), { oldText: 'old\n', newText: null }); + }); + + it('chains checkpoints and keeps them in a shadow repository outside the project', async () => { + const { root, store } = project({ 'a.txt': 'a\n' }); + const first = await snapshotOrFail(store, 'first'); + const second = await snapshotOrFail(store, 'second'); + assert.notEqual(first, second); + assert.equal(path.basename(store.gitDir), shadowRepoName(root)); + assert.ok(!store.gitDir.startsWith(root + path.sep)); + assert.ok(!fs.existsSync(path.join(root, '.git'))); + const parent = execFileSync('git', ['--git-dir', store.gitDir, 'rev-parse', `${second}^`], { encoding: 'utf8' }).trim(); + assert.equal(parent, first); + }); + + it('refuses bad ids and paths that leave the project', async () => { + const { store } = project({ 'a.txt': 'a\n' }); + const id = await snapshotOrFail(store, 'one'); + await assert.rejects(store.changes('--output=/tmp/x'), /Not a checkpoint id/); + await assert.rejects(store.changes('a'.repeat(40)), /does not exist/); + await assert.rejects(store.restoreFiles(id, ['../outside.txt']), /cannot leave the project/); + await assert.rejects(store.restoreFiles(id, ['.git/config']), /\.git folder/); + await assert.rejects(store.fileAt(id, '/etc/passwd'), /relative to the project/); + assert.equal(normalizeProjectPath('.\\src\\a.ts'), 'src/a.ts'); + }); +}); + +describe('CheckpointStore: restore', () => { + it('restoreFiles puts content back, deletes added files and recreates deleted ones', async () => { + const { root, store } = project({ 'a.txt': 'original\n', 'keep/b.txt': 'b\n', 'other.txt': 'other\n' }); + const id = await snapshotOrFail(store, 'one'); + write(root, 'a.txt', 'agent edit\n'); + write(root, 'added/deep/x.txt', 'x\n'); + fs.rmSync(path.join(root, 'keep', 'b.txt')); + write(root, 'other.txt', 'user edit\n'); + + await store.restoreFiles(id, ['a.txt', 'added/deep/x.txt', 'keep/b.txt']); + assert.equal(read(root, 'a.txt'), 'original\n'); + assert.equal(read(root, 'added/deep/x.txt'), null); + assert.ok(!fs.existsSync(path.join(root, 'added')), 'folders left empty are removed'); + assert.equal(read(root, 'keep/b.txt'), 'b\n'); + assert.equal(read(root, 'other.txt'), 'user edit\n', 'a path not named is left alone'); + assert.deepEqual((await store.changes(id)).map((change) => change.path), ['other.txt']); + }); + + it('restoreAll previews, then restores every changed file', async () => { + const { root, store } = project({ 'a.txt': 'a\n', 'b.txt': 'b\n', 'c.txt': 'c\n' }); + const id = await snapshotOrFail(store, 'one'); + write(root, 'a.txt', 'A\n'); + fs.rmSync(path.join(root, 'b.txt')); + write(root, 'd.txt', 'd\n'); + + assert.deepEqual(await store.previewRestore(id), ['a.txt', 'b.txt', 'd.txt']); + assert.equal(read(root, 'a.txt'), 'A\n', 'a preview writes nothing'); + assert.deepEqual(await store.restoreAll(id), ['a.txt', 'b.txt', 'd.txt']); + assert.equal(read(root, 'a.txt'), 'a\n'); + assert.equal(read(root, 'b.txt'), 'b\n'); + assert.equal(read(root, 'c.txt'), 'c\n'); + assert.equal(read(root, 'd.txt'), null); + assert.deepEqual(await store.changes(id), []); + assert.deepEqual(await store.restoreAll(id), []); + }); + + it('keeps CRLF bytes, even when the project asks git to normalize line endings', async () => { + const crlf = Buffer.from('line one\r\nline two\r\n'); + const { root, store } = project({ 'win.txt': crlf, 'mixed.txt': Buffer.from('a\r\nb\nc\r\n'), '.gitattributes': '* text=auto eol=lf\n' }); + const id = await snapshotOrFail(store, 'one'); + write(root, 'win.txt', 'rewritten\n'); + write(root, 'mixed.txt', 'rewritten\n'); + await store.restoreAll(id); + assert.deepEqual(fs.readFileSync(path.join(root, 'win.txt')), crlf); + assert.deepEqual(fs.readFileSync(path.join(root, 'mixed.txt')), Buffer.from('a\r\nb\nc\r\n')); + assert.equal(await store.fileAt(id, 'win.txt'), 'line one\r\nline two\r\n'); + }); + + it('keeps the executable bit', { skip: process.platform === 'win32' }, async () => { + const { root, store } = project({ 'run.sh': '#!/bin/sh\necho hi\n' }); + fs.chmodSync(path.join(root, 'run.sh'), 0o755); + const id = await snapshotOrFail(store, 'one'); + fs.rmSync(path.join(root, 'run.sh')); + await store.restoreAll(id); + assert.equal(fs.statSync(path.join(root, 'run.sh')).mode & 0o111, 0o111); + }); +}); + +describe('CheckpointStore: what is not snapshotted', () => { + it('skips gitignored files, node_modules, the default excludes, .git/info/exclude and large files', async () => { + const { root, store } = project({ + '.gitignore': 'secret.env\ncache/\n', + 'src/app.ts': 'app\n', + 'secret.env': 'TOKEN=1\n', + 'cache/blob.txt': 'cached\n', + 'node_modules/pkg/index.js': 'module\n', + 'dist/bundle.js': 'bundle\n', + 'server.log': 'log\n', + 'local-only.txt': 'local\n', + 'huge.bin': Buffer.alloc(2048, 1), + }, { maxFileBytes: 1024 }); + realGit(root, 'init', '-q'); + fs.appendFileSync(path.join(root, '.git', 'info', 'exclude'), 'local-only.txt\n'); + + const id = await snapshotOrFail(store, 'one'); + const tracked = execFileSync('git', ['--git-dir', store.gitDir, 'ls-tree', '-r', '--name-only', id], { encoding: 'utf8' }).trim().split('\n').sort(); + assert.deepEqual(tracked, ['.gitignore', 'src/app.ts']); + + write(root, 'node_modules/pkg/index.js', 'changed\n'); + write(root, 'secret.env', 'TOKEN=2\n'); + assert.deepEqual(await store.changes(id), []); + assert.deepEqual(await store.restoreAll(id), []); + assert.equal(read(root, 'secret.env'), 'TOKEN=2\n', 'an ignored file is never touched by a restore'); + }); + + it('leaves a project that is itself a git repository byte-identical', async () => { + const { root, store } = project({ 'a.txt': 'a\n', 'b.txt': 'b\n' }); + realGit(root, 'init', '-q', '-b', 'main'); + realGit(root, 'add', '.'); + realGit(root, 'commit', '-q', '-m', 'initial'); + write(root, 'a.txt', 'staged\n'); + realGit(root, 'add', 'a.txt'); + write(root, 'b.txt', 'unstaged\n'); + write(root, 'untracked.txt', 'u\n'); + + const dotGit = path.join(root, '.git'); + const fingerprint = (): string[] => [ + fs.readFileSync(path.join(dotGit, 'HEAD'), 'utf8'), + fs.readFileSync(path.join(dotGit, 'index')).toString('base64'), + fs.readFileSync(path.join(dotGit, 'config'), 'utf8'), + realGit(root, 'rev-parse', 'HEAD'), + realGit(root, 'status', '--porcelain=v2', '--untracked-files=all'), + fs.readdirSync(path.join(dotGit, 'objects')).sort().join(','), + ]; + // Status may refresh the stat cache of the real index once; measure after that. + realGit(root, 'status'); + const before = fingerprint(); + + const id = await snapshotOrFail(store, 'one'); + write(root, 'b.txt', 'agent\n'); + await store.changes(id); + await store.restoreAll(id); + assert.equal(read(root, 'b.txt'), 'unstaged\n'); + assert.deepEqual(fingerprint(), before); + }); + + it('excludes a nested repository instead of failing on it', async () => { + const { root, store } = project({ 'a.txt': 'a\n', 'vendor/lib/x.txt': 'x\n', 'empty-repo/y.txt': 'y\n' }); + realGit(path.join(root, 'vendor', 'lib'), 'init', '-q'); + realGit(path.join(root, 'vendor', 'lib'), 'add', '.'); + realGit(path.join(root, 'vendor', 'lib'), 'commit', '-q', '-m', 'nested'); + // A nested repository without a commit makes a plain `git add -A` fail outright. + realGit(path.join(root, 'empty-repo'), 'init', '-q'); + + const id = await snapshotOrFail(store, 'one'); + const tracked = execFileSync('git', ['--git-dir', store.gitDir, 'ls-tree', '-r', '--name-only', id], { encoding: 'utf8' }).trim().split('\n'); + assert.deepEqual(tracked, ['a.txt']); + write(root, 'a.txt', 'A\n'); + assert.deepEqual((await store.changes(id)).map((change) => change.path), ['a.txt']); + assert.equal(realGit(path.join(root, 'vendor', 'lib'), 'status', '--porcelain'), ''); + }); + + it('turns itself off past maxFiles, with a reason to show', async () => { + const files: Record = {}; + for (let index = 0; index < 6; index += 1) { + files[`f${index}.txt`] = `${index}\n`; + } + const { store } = project(files, { maxFiles: 5 }); + assert.equal(await store.snapshot('one'), null); + assert.equal(store.disabledReason, 'This project is too large for checkpoints (more than 5 files).'); + assert.equal(await store.snapshot('two'), null); + await assert.rejects(store.previewRestore('a'.repeat(40)), /does not exist|too large/); + store.clearDisabled(); + assert.equal(store.disabledReason, null); + }); +}); + +describe('CheckpointStore: concurrency and lifecycle', () => { + it('serializes concurrent calls into a linear chain', async () => { + const { root, store } = project({ 'a.txt': '0\n' }); + const results = await Promise.all(Array.from({ length: 6 }, (_, index) => { + write(root, `file-${index}.txt`, `${index}\n`); + return store.snapshot(`snapshot ${index}`); + })); + const ids = results.map((checkpoint) => checkpoint?.id); + assert.equal(new Set(ids).size, 6); + const log = execFileSync('git', ['--git-dir', store.gitDir, 'rev-list', 'refs/codexr/checkpoints'], { encoding: 'utf8' }).trim().split('\n'); + assert.deepEqual(log, [...ids].reverse()); + }); + + it('serializes two stores of the same project', async () => { + const { root, store } = project({ 'a.txt': 'a\n' }); + const twin = new CheckpointStore({ storageDir: path.join(base, 'storage'), projectRoot: root }); + const results = await Promise.all([store.snapshot('a'), twin.snapshot('b'), store.snapshot('c'), twin.snapshot('d')]); + assert.ok(results.every((checkpoint) => checkpoint !== null)); + }); + + it('refuses calls after dispose', async () => { + const { store } = project({ 'a.txt': 'a\n' }); + await snapshotOrFail(store, 'one'); + await store.dispose(); + await assert.rejects(store.snapshot('two'), /disposed/); + }); + + it('reports a missing git executable clearly', async () => { + counter += 1; + const store = new CheckpointStore({ storageDir: path.join(base, 'storage'), projectRoot: path.join(base, `project-${counter}`), git: 'codexr-no-such-git' }); + await assert.rejects(store.snapshot('one'), /need git/); + }); +}); + +describe('reviewBase', () => { + it('compares each file against its own base once kept', () => { + let state = createReviewBase('base1'); + assert.equal(baseFor(state, 'a.ts'), 'base1'); + state = keepFile(state, 'a.ts', 'snap2'); + assert.equal(baseFor(state, 'a.ts'), 'snap2'); + assert.equal(baseFor(state, 'b.ts'), 'base1'); + assert.equal(baseFor(state, 'constructor'), 'base1'); + assert.deepEqual(basesToQuery(state), ['base1', 'snap2']); + state = keepFiles(state, ['b.ts', 'c.ts'], 'snap3'); + assert.deepEqual(basesToQuery(state), ['base1', 'snap2', 'snap3']); + assert.deepEqual(keepFile(state, 'a.ts', 'base1').fileBases, { 'b.ts': 'snap3', 'c.ts': 'snap3' }); + assert.deepEqual(keepAll(state, 'snap4'), { baseId: 'snap4', fileBases: {} }); + }); + + it('merges per-base changes, each file from its own base', () => { + const state = keepFile(createReviewBase('base1'), 'a.ts', 'snap2'); + const changes = new Map([ + ['base1', [{ path: 'b.ts', status: 'modified' }, { path: 'a.ts', status: 'modified' }]], + ['snap2', [{ path: 'a.ts', status: 'added' }, { path: 'b.ts', status: 'deleted' }]], + ]); + assert.deepEqual(mergePendingChanges(state, changes), [{ path: 'a.ts', status: 'added' }, { path: 'b.ts', status: 'modified' }]); + }); + + it('round-trips through JSON and rejects malformed data', () => { + const state = keepFile(createReviewBase('base1'), 'src/a.ts', 'snap2'); + assert.deepEqual(parseReviewBase(serializeReviewBase(state)), state); + assert.deepEqual(parseReviewBase(JSON.parse(serializeReviewBase(state)) as unknown), state); + assert.equal(parseReviewBase('{not json'), null); + assert.equal(parseReviewBase({ baseId: 3 }), null); + assert.equal(parseReviewBase({ baseId: 'b', fileBases: { 'a.ts': 4 } }), null); + assert.equal(parseReviewBase({ baseId: 'b', fileBases: [] }), null); + assert.deepEqual(parseReviewBase({ baseId: 'b' }), { baseId: 'b', fileBases: {} }); + }); +}); diff --git a/apps/ide/test/codexrMcp.test.ts b/apps/ide/test/codexrMcp.test.ts new file mode 100644 index 000000000..3242e6d45 --- /dev/null +++ b/apps/ide/test/codexrMcp.test.ts @@ -0,0 +1,165 @@ +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 { 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_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'; + +/** AF10: Code-XR's analysis queries as an MCP server for external agents. */ + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-mcp-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +const records = [ + { relativePath: 'src/a.ts', language: 'TypeScript', codeLines: 100, maxComplexity: 12, functionCount: 5, cyclomaticComplexityNumber: 3 }, + { relativePath: 'src\\b.ts', language: 'TypeScript', codeLines: 40, maxComplexity: 3, functionCount: 2, cyclomaticComplexityNumber: 1 }, +]; +const graph = { + nodes: [ + { id: 'n1', relativePath: 'src/a.ts', metrics: { fanIn: 0, fanOut: 1, degree: 1, cycleSize: 0 } }, + { id: 'n2', relativePath: 'src/b.ts', metrics: { fanIn: 1, fanOut: 0, degree: 1, cycleSize: 0 } }, + ], + edges: [{ source: 'n1', target: 'n2', kind: 'import' }], +}; + +/** A fixture analysis folder, as an XR analysis leaves it. */ +function analysisFolder(withGraph: boolean): string { + const dir = fs.mkdtempSync(path.join(base, 'analysis-')); + fs.writeFileSync(path.join(dir, 'data.json'), JSON.stringify(records)); + if (withGraph) { + fs.writeFileSync(path.join(dir, 'dependency-graph.json'), JSON.stringify(graph)); + } + const revision = path.join(dir, 'evolution', 'revision-3'); + fs.mkdirSync(revision, { recursive: true }); + fs.writeFileSync(path.join(revision, 'manifest.json'), JSON.stringify({ frames: [ + { date: '2026-01-01', url: '/evolution/revision-3/data1.json' }, + { date: '2026-02-01', url: '/evolution/revision-3/data2.json' }, + { date: '2026-03-01', url: '../../../outside.json' }, + ] })); + fs.writeFileSync(path.join(revision, 'data1.json'), JSON.stringify(records.slice(0, 1))); + fs.writeFileSync(path.join(revision, 'data2.json'), JSON.stringify(records)); + return dir; +} + +async function connect(options: CodexrMcpOptions): Promise { + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await createCodexrMcpServer(options).connect(serverSide); + const client = new Client({ name: 'test', version: '0' }); + await client.connect(clientSide); + return client; +} + +function text(result: Awaited>): string { + const content = result.content as { type: string; text?: string }[]; + return content.map((item) => item.text ?? '').join(''); +} + +describe('analysis queries (shared by the agent and the MCP server)', () => { + it('reads the metrics and the evolution frames of an analysis folder', async () => { + const dir = analysisFolder(false); + assert.deepEqual((await readMetrics(dir)).map((record) => record.relativePath), ['src/a.ts', 'src/b.ts']); + const frames = await readEvolution(dir); + // The third frame points outside the revision folder: it is skipped, never read. + assert.deepEqual(frames?.map(({ frame }) => frame.date), ['2026-01-01', '2026-02-01']); + await assert.rejects(readMetrics(path.join(base, 'missing')), { message: NO_ANALYSIS }); + }); + it('answers every query from the folder, and explains what is missing', async () => { + const dir = analysisFolder(false); + const query = (name: string) => ANALYSIS_QUERIES.find((candidate) => candidate.name === name)!; + assert.match(await query('get_metrics').run({ path: 'src' }, dir), /src: 2 analysed files[\s\S]*total codeLines: 140/); + assert.match(await query('get_hotspots').run({ limit: '1' }, dir), /Top 1 files by maxComplexity:\n1\. src\/a\.ts/); + await assert.rejects(query('get_dependencies').run({}, dir), /Dependency graph mode/); + assert.match(await query('get_evolution').run({ path: 'src/a.ts' }, dir), /2026-01-01: codeLines=100\n- 2026-02-01: codeLines=100/); + }); + it('are exactly the built-in agent\'s analysis tools', () => { + assert.deepEqual(ANALYSIS_TOOLS.map((tool) => [tool.name, tool.title, tool.description, tool.parameters, tool.risk]), + ANALYSIS_QUERIES.map((query) => [query.name, query.title, query.description, query.parameters, 'read'])); + assert.equal(ANALYSIS_TOOLS[1]!.preview({ metric: 'codeLines' }).summary, 'top files by codeLines'); + }); +}); + +describe('Code-XR MCP server (AF10)', () => { + it('lists the four read-only tools with the agent\'s names and argument schemas', async () => { + 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']); + for (const tool of tools) { + const query = ANALYSIS_QUERIES.find((candidate) => candidate.name === tool.name)!; + assert.equal(tool.description, `[Code-XR] ${query.description}`); + assert.equal(tool.annotations?.readOnlyHint, true); + assert.equal(tool.annotations?.openWorldHint, false); + assert.deepEqual(tool.inputSchema.required ?? [], []); + for (const [key, property] of Object.entries(query.parameters.properties)) { + assert.equal((tool.inputSchema.properties?.[key] as { type?: string }).type, property.type, `${tool.name}.${key}`); + assert.equal((tool.inputSchema.properties?.[key] as { description?: string }).description, property.description); + } + assert.deepEqual(Object.keys(tool.inputSchema.properties ?? {}).sort(), Object.keys(query.parameters.properties).sort()); + } + await client.close(); + }); + it('answers tool calls from the analysis folder and reports failures as tool errors', async () => { + const client = await connect({ root: base, analysisDir: analysisFolder(true) }); + const hot = await client.callTool({ name: 'get_hotspots', arguments: { limit: 1 } }); + assert.equal(hot.isError, undefined); + assert.match(text(hot), /1\. src\/a\.ts: maxComplexity=12/); + assert.match(text(await client.callTool({ name: 'get_dependencies', arguments: { path: 'src/b.ts' } })), /Used by \(1\):\n- src\/a\.ts \(import\)/); + const missing = await client.callTool({ name: 'get_metrics', arguments: { path: 'nope' } }); + assert.equal(missing.isError, true); + assert.match(text(missing), /no file at or under "nope"/); + const invalid = await client.callTool({ name: 'get_hotspots', arguments: { limit: 'many' } }); + assert.equal(invalid.isError, true); + await client.close(); + }); + it('answers with the built-in agent\'s "no analysis" message when none has run', async () => { + for (const analysisDir of [null, path.join(base, 'not-yet')]) { + const client = await connect({ root: base, analysisDir }); + const result = await client.callTool({ name: 'get_metrics', arguments: {} }); + assert.equal(result.isError, true); + assert.equal(text(result), NO_ANALYSIS); + await client.close(); + } + }); + 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', path.join(root, 'out')]), { root, analysisDir: path.join(root, 'out') }); + assert.throws(() => parseArgs(['--analysis', root]), /--root/); + assert.throws(() => parseArgs(['--root', 'relative']), /--root/); + assert.throws(() => parseArgs(['--root', root, '--analysis', 'relative']), /--analysis/); + }); + it('serves MCP over stdio from its entry point', async () => { + const entry = fileURLToPath(new URL('../src/codexrMcp/index.ts', import.meta.url)); + const transport = new StdioClientTransport({ + command: process.execPath, + args: ['--experimental-strip-types', '--no-warnings', entry, '--root', base, '--analysis', analysisFolder(false)], + stderr: 'pipe', + }); + 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/); + await client.close(); + }); +}); + +describe('codexrMcpServerSpec', () => { + it('runs the bundled server with the IDE\'s own binary in Node mode', () => { + const spec = codexrMcpServerSpec({ execPath: '/opt/Code-XR IDE/code-xr-ide', appPath: '/opt/Code-XR IDE/resources/app.asar', root: '/home/me/project', analysisDir: '/home/me/.codexr/out', isPackaged: true }); + assert.deepEqual(spec, { + name: 'code-xr', + command: '/opt/Code-XR IDE/code-xr-ide', + args: [path.join('/opt/Code-XR IDE/resources/app.asar', 'out', 'codexrMcp', 'index.cjs'), '--root', '/home/me/project', '--analysis', '/home/me/.codexr/out'], + env: [{ name: 'ELECTRON_RUN_AS_NODE', value: '1' }], + }); + const dev = codexrMcpServerSpec({ execPath: '/repo/node_modules/electron/dist/electron', 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', '']); + }); +}); diff --git a/apps/ide/test/fixtures/fakeAcpAgent.mjs b/apps/ide/test/fixtures/fakeAcpAgent.mjs new file mode 100644 index 000000000..e0df4510b --- /dev/null +++ b/apps/ide/test/fixtures/fakeAcpAgent.mjs @@ -0,0 +1,20 @@ +// A minimal ACP agent over stdio for agentSessions.test.ts: it answers +// initialize, session/new and session/prompt (echoing the prompt's text as a +// message chunk), so the test exercises the real spawn + ndJsonStream path. +import { Readable, Writable } from 'node:stream'; +import { agent, methods, ndJsonStream } from '@agentclientprotocol/sdk'; + +let client = null; +const app = agent({ name: 'fixture' }) + .onConnect((connection) => { + client = connection.client; + }) + .onRequest(methods.agent.initialize, () => ({ protocolVersion: 1, agentCapabilities: {}, authMethods: [] })) + .onRequest(methods.agent.session.new, () => ({ sessionId: `pid-${process.pid}` })) + .onRequest(methods.agent.session.prompt, async ({ params }) => { + const text = params.prompt.map((block) => (block.type === 'text' ? block.text : '')).join(''); + await client.notify(methods.client.session.update, { sessionId: params.sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `echo:${text}` } } }); + return { stopReason: 'end_turn' }; + }); +const connection = app.connect(ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin))); +await connection.closed; diff --git a/apps/ide/test/metricDelta.test.ts b/apps/ide/test/metricDelta.test.ts new file mode 100644 index 000000000..3ff663f0c --- /dev/null +++ b/apps/ide/test/metricDelta.test.ts @@ -0,0 +1,154 @@ +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 { readMetrics, type FileMetrics } from '../src/main/agents/tools/analysisQueries.ts'; +import { computeMetricDelta, formatMetricDelta, metricTotals, toTurnMetricDeltaView } from '../src/main/analysis/metricDelta.ts'; + +/** AF9 (#274): the metric delta of an agent's turn, from two analyses' records. */ + +/** A record shaped like the backend's XR directory output (xr_field_schema.py, XR_DIRECTORY_FIELDS). */ +function record(relativePath: string, metrics: Record, language = 'TypeScript'): FileMetrics { + return { + fileName: path.posix.basename(relativePath), + filePath: `/project/${relativePath}`, + relativePath, + language, + totalLines: 0, codeLines: 0, commentLines: 0, blankLines: 0, commentRatio: 0, + classCount: 0, functionCount: 0, maxComplexity: 0, cyclomaticComplexityNumber: 0, + highComplexityFunctions: 0, criticalComplexityFunctions: 0, + averageFunctionParameters: 0, maxFunctionParameters: 0, averageFunctionLines: 0, maxFunctionLines: 0, + fileSizeBytes: 0, + ...metrics, + }; +} + +const before = [ + record('src/a.ts', { totalLines: 120, codeLines: 100, functionCount: 5, maxComplexity: 12, cyclomaticComplexityNumber: 3, highComplexityFunctions: 1 }), + record('src/b.ts', { totalLines: 50, codeLines: 40, functionCount: 2, maxComplexity: 3, cyclomaticComplexityNumber: 1 }), + record('lib/old.py', { totalLines: 30, codeLines: 20, functionCount: 1, maxComplexity: 2, cyclomaticComplexityNumber: 2 }, 'Python'), +]; +const afterTurn = [ + record('src/a.ts', { totalLines: 140, codeLines: 118, functionCount: 6, maxComplexity: 15, cyclomaticComplexityNumber: 3.5, highComplexityFunctions: 2 }), + record('src/b.ts', { totalLines: 50, codeLines: 40, functionCount: 2, maxComplexity: 3, cyclomaticComplexityNumber: 1 }), + record('src\\c.ts', { totalLines: 12, codeLines: 10, functionCount: 1, maxComplexity: 1, cyclomaticComplexityNumber: 1 }), +]; + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-delta-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +describe('metric delta of a turn', () => { + it('reports added, removed, changed and touched-but-unchanged files, with project totals', () => { + const report = computeMetricDelta(before, afterTurn, ['src/a.ts', './src/b.ts', 'src/c.ts', 'lib/old.py', 'README.md']); + assert.equal(report.status, 'ok'); + assert.deepEqual(report.files.map((file) => [file.path, file.status]), [ + ['README.md', 'not-analysed'], + ['lib/old.py', 'removed'], + ['src/a.ts', 'changed'], + ['src/b.ts', 'unchanged'], + ['src/c.ts', 'added'], + ]); + const a = report.files.find((file) => file.path === 'src/a.ts')!; + assert.deepEqual(a.metrics.codeLines, { before: 100, after: 118, delta: 18 }); + assert.deepEqual(a.metrics.maxComplexity, { before: 12, after: 15, delta: 3 }); + assert.deepEqual(a.metrics.cyclomaticComplexityNumber, { before: 3, after: 3.5, delta: 0.5 }); + // Only the metrics that moved are listed. + assert.equal(a.metrics.classCount, undefined); + assert.deepEqual(report.files.find((file) => file.path === 'src/b.ts')!.metrics, {}); + const added = report.files.find((file) => file.path === 'src/c.ts')!; + assert.deepEqual(added.metrics.codeLines, { before: null, after: 10, delta: 10 }); + const removed = report.files.find((file) => file.path === 'lib/old.py')!; + assert.equal(removed.language, 'Python'); + assert.deepEqual(removed.metrics.codeLines, { before: 20, after: null, delta: -20 }); + + assert.equal(report.totals.before?.codeLines, 160); + assert.equal(report.totals.after?.codeLines, 168); + assert.deepEqual(report.totals.delta, { + files: 0, codeLines: 8, totalLines: 2, functionCount: 1, classCount: 0, + highComplexityFunctions: 1, criticalComplexityFunctions: 0, maxComplexity: 3, avgComplexity: -0.17, + }); + assert.equal(report.summary, '3 files (1 added, 1 removed, 1 changed): code lines +8 (160 -> 168), functions +1, max complexity 12 -> 15, avg complexity 2 -> 1.83, high-complexity functions +1'); + }); + + it('lists every differing file when the changed paths are unknown', () => { + const report = computeMetricDelta(before, afterTurn); + assert.deepEqual(report.files.map((file) => [file.path, file.status]), [ + ['lib/old.py', 'removed'], + ['src/a.ts', 'changed'], + ['src/c.ts', 'added'], + ]); + }); + + it('expands a changed folder to the analysed files under it', () => { + const report = computeMetricDelta(before, afterTurn, ['lib', 'src/']); + assert.deepEqual(report.files.map((file) => file.path), ['lib/old.py', 'src/a.ts', 'src/b.ts', 'src/c.ts']); + }); + + it('says when nothing moved', () => { + const report = computeMetricDelta(before, before, ['src/b.ts']); + assert.equal(report.summary, 'No metric changes.'); + assert.deepEqual(report.files.map((file) => file.status), ['unchanged']); + assert.equal(computeMetricDelta(before, before, []).files.length, 0); + }); + + it('handles a missing analysis on either side', () => { + const noBaseline = computeMetricDelta(null, afterTurn, ['src/a.ts']); + assert.equal(noBaseline.status, 'no-baseline'); + assert.equal(noBaseline.totals.after?.files, 3); + assert.deepEqual(noBaseline.files, []); + const noAnalysis = computeMetricDelta(before, null, ['src/a.ts']); + assert.equal(noAnalysis.status, 'no-analysis'); + assert.equal(noAnalysis.totals.before?.files, 3); + assert.deepEqual(noAnalysis.totals.delta, {}); + }); + + it('keeps totals null for metrics no record has', () => { + const totals = metricTotals([{ relativePath: 'notes.txt' }]); + assert.equal(totals.maxComplexity, null); + assert.equal(totals.avgComplexity, null); + assert.equal(totals.codeLines, 0); + assert.deepEqual(metricTotals([]).files, 0); + }); + + it('formats a report for an agent', () => { + const text = formatMetricDelta(computeMetricDelta(before, afterTurn, ['src/c.ts', 'src/b.ts'])); + const lines = text.split('\n'); + assert.match(lines[0]!, /^1 file \(1 added\): code lines \+8/); + assert.equal(lines[1], '- src/b.ts [unchanged]'); + assert.match(lines[2]!, /^- src\/c\.ts \[added\]: codeLines - -> 10 \(\+10\), totalLines - -> 12 \(\+12\)/); + }); + + it('works on the records readMetrics reads from a data.json', async () => { + const dir = (name: string, records: readonly FileMetrics[]): string => { + const folder = path.join(base, name); + fs.mkdirSync(folder); + fs.writeFileSync(path.join(folder, 'data.json'), JSON.stringify(records)); + return folder; + }; + const report = computeMetricDelta(await readMetrics(dir('before', before)), await readMetrics(dir('after', afterTurn)), ['src/c.ts']); + assert.deepEqual(report.files.map((file) => [file.path, file.status]), [['src/c.ts', 'added']]); + }); +}); + +describe('metric delta as a chat keeps it (AF9)', () => { + it('keeps only what moved, caps the files and stays quiet when nothing did', () => { + const report = computeMetricDelta(before, afterTurn, ['src/a.ts', 'src/b.ts', 'src/c.ts', 'lib/old.py', 'README.md']); + const view = toTurnMetricDeltaView(report); + assert.ok(view); + assert.equal(view.summary, report.summary); + assert.deepEqual(view.totals.map((total) => total.metric), ['maxComplexity', 'avgComplexity', 'codeLines', 'functionCount', 'highComplexityFunctions']); + assert.deepEqual(view.totals[0], { metric: 'maxComplexity', before: 12, after: 15 }); + assert.deepEqual(view.files.map((file) => [file.path, file.status]), [['lib/old.py', 'removed'], ['src/a.ts', 'changed'], ['src/c.ts', 'added']]); + assert.deepEqual(view.files[1]?.changes.find((change) => change.metric === 'codeLines'), { metric: 'codeLines', before: 100, after: 118 }); + assert.equal(view.moreFiles, 0); + const capped = toTurnMetricDeltaView(report, 1); + assert.equal(capped?.files.length, 1); + assert.equal(capped?.moreFiles, 2); + // Serialisable as is: it travels over IPC and is saved with the chat. + assert.deepEqual(JSON.parse(JSON.stringify(view)), view); + assert.equal(toTurnMetricDeltaView(computeMetricDelta(before, before, ['src/b.ts'])), null); + assert.equal(toTurnMetricDeltaView(computeMetricDelta(null, afterTurn)), null); + assert.equal(toTurnMetricDeltaView(computeMetricDelta(before, null)), null); + }); +}); diff --git a/apps/ide/test/sceneRefresh.test.ts b/apps/ide/test/sceneRefresh.test.ts new file mode 100644 index 000000000..f692ba8b0 --- /dev/null +++ b/apps/ide/test/sceneRefresh.test.ts @@ -0,0 +1,74 @@ +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'; + +/** AF8/AF9: reading the core's refresh coordinator for an open scene. */ + +function view(overrides: Partial = {}): RefreshView { + return { mode: 'single', status: 'ready', sourceRevision: 0, appliedRevision: { single: 0 }, modeRevision: { single: 0 }, ...overrides }; +} + +/** A fake session: `set` changes the view and notifies, like the coordinator's emitState. */ +function fakePort(initial: RefreshView): RefreshPort & { set(next: RefreshView): void; listeners(): number } { + let current = initial; + const listeners = new Set<() => void>(); + return { + view: () => current, + onChange(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + set(next) { + current = next; + for (const listener of [...listeners]) { + listener(); + } + }, + listeners: () => listeners.size, + }; +} + +describe('scene refresh state', () => { + it('is settled once the classic view applied every source revision', () => { + assert.equal(refreshState(view()), 'settled'); + assert.equal(refreshState(view({ sourceRevision: 2, appliedRevision: { single: 1 }, status: 'updating' })), 'pending'); + assert.equal(refreshState(view({ sourceRevision: 2, appliedRevision: { single: 2 }, status: 'updating' })), 'pending'); + assert.equal(refreshState(view({ sourceRevision: 2, appliedRevision: { single: 2 } })), 'settled'); + assert.equal(refreshState(view({ sourceRevision: 2, appliedRevision: { single: 1 }, status: 'error' })), 'settled'); + }); + + it('is paused while the scene shows another mode', () => { + assert.equal(refreshState(view({ mode: 'dependency-graph', sourceRevision: 3 })), 'paused'); + assert.equal(refreshState(view({ mode: 'selection' })), 'paused'); + }); + + it('waits for a pending refresh, then stops listening', async () => { + const port = fakePort(view({ sourceRevision: 1, status: 'updating' })); + const settled = waitUntilSettled(port, 5_000); + assert.equal(port.listeners(), 1); + port.set(view({ sourceRevision: 2, appliedRevision: { single: 1 }, status: 'updating' })); + port.set(view({ sourceRevision: 2, appliedRevision: { single: 2 }, modeRevision: { single: 2 } })); + assert.equal(await settled, 'settled'); + assert.equal(port.listeners(), 0); + }); + + it('answers at once when nothing is pending, and times out otherwise', async () => { + assert.equal(await waitUntilSettled(fakePort(view()), 5_000), 'settled'); + const stuck = fakePort(view({ sourceRevision: 1, status: 'updating' })); + assert.equal(await waitUntilSettled(stuck, 20), 'timeout'); + assert.equal(stuck.listeners(), 0); + }); + + it('reports each finished refresh once', () => { + const port = fakePort(view({ modeRevision: { single: 3 } })); + const seen: number[] = []; + const stop = followRefreshes(port, (revision) => seen.push(revision)); + port.set(view({ modeRevision: { single: 3 }, status: 'updating', sourceRevision: 1 })); + port.set(view({ modeRevision: { single: 4 }, sourceRevision: 1, appliedRevision: { single: 1 } })); + port.set(view({ modeRevision: { single: 4 }, mode: 'dependency-graph' })); + port.set(view({ modeRevision: { single: 6 } })); + stop(); + port.set(view({ modeRevision: { single: 7 } })); + assert.deepEqual(seen, [4, 6]); + }); +}); diff --git a/apps/ide/test/sessionChanges.test.ts b/apps/ide/test/sessionChanges.test.ts new file mode 100644 index 000000000..2437a2407 --- /dev/null +++ b/apps/ide/test/sessionChanges.test.ts @@ -0,0 +1,147 @@ +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 { JsonKeyValueStore } from '../src/main/core/jsonStore.ts'; +import { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; + +const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-session-changes-'))); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +let counter = 0; + +function setup(files: Record, store: { maxFiles?: number } = {}): { root: string; changes: SessionChanges; basesFile: string } { + counter += 1; + const root = path.join(base, `project-${counter}`); + fs.mkdirSync(root, { recursive: true }); + for (const [relative, content] of Object.entries(files)) { + write(root, relative, content); + } + const basesFile = path.join(base, `review-${counter}.json`); + const changes = new SessionChanges({ storageDir: path.join(base, 'checkpoints'), bases: new JsonKeyValueStore(basesFile), store }); + return { root, changes, basesFile }; +} + +function write(root: string, relative: string, content: string): void { + const target = path.join(root, ...relative.split('/')); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); +} + +function read(root: string, relative: string): string | null { + const target = path.join(root, ...relative.split('/')); + return fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null; +} + +describe('SessionChanges', () => { + it('makes the first checkpoint of a chat its review base and lists what changed since', async () => { + const { root, changes } = setup({ 'a.txt': 'a\n', 'src/b.ts': 'b\n' }); + assert.equal(await changes.afterTurn('s1', root), null, 'no base before the first message'); + const first = await changes.beforePrompt('s1', root); + assert.ok(first); + assert.equal(changes.reviewBase('s1')?.baseId, first.checkpointId); + write(root, 'a.txt', 'a\nmore\n'); + write(root, 'new.md', 'hi\n'); + const second = await changes.beforePrompt('s1', root); + assert.ok(second && second.checkpointId !== first.checkpointId); + assert.equal(changes.reviewBase('s1')?.baseId, first.checkpointId, 'later checkpoints do not move the base'); + fs.rmSync(path.join(root, 'src', 'b.ts')); + assert.equal(await changes.afterTurn('s1', root), 3); + const pending = await changes.pending('s1', root); + assert.equal(pending.disabledReason, null); + assert.deepEqual(pending.files.map((file) => [file.path, file.status, file.additions, file.deletions]), [ + ['a.txt', 'modified', 1, 0], + ['new.md', 'added', 1, 0], + ['src/b.ts', 'deleted', 0, 1], + ]); + assert.deepEqual(await changes.changedSince(root, second.checkpointId), ['src/b.ts']); + assert.deepEqual(await changes.diff('s1', root, 'a.txt'), { oldText: 'a\n', newText: 'a\nmore\n' }); + assert.deepEqual(await changes.diff('s1', root, 'new.md'), { oldText: null, newText: 'hi\n' }); + await changes.dispose(); + }); + + it('keeps one file against a fresh snapshot, and shows it again only if it changes after', async () => { + const { root, changes } = setup({ 'a.txt': 'a\n', 'b.txt': 'b\n' }); + await changes.beforePrompt('s1', root); + write(root, 'a.txt', 'A\n'); + write(root, 'b.txt', 'B\n'); + await changes.keep('s1', root, ['./a.txt']); + assert.deepEqual((await changes.pending('s1', root)).files.map((file) => file.path), ['b.txt']); + write(root, 'a.txt', 'AA\n'); + const pending = await changes.pending('s1', root); + assert.deepEqual(pending.files.map((file) => file.path), ['a.txt', 'b.txt']); + assert.deepEqual(await changes.diff('s1', root, 'a.txt'), { oldText: 'A\n', newText: 'AA\n' }, 'compared with what was kept'); + await changes.keep('s1', root, 'all'); + assert.deepEqual((await changes.pending('s1', root)).files, []); + await changes.dispose(); + }); + + it('undoes files from their own base: modified back, added deleted, deleted recreated', async () => { + const { root, changes } = setup({ 'a.txt': 'a\n', 'gone.txt': 'g\n', 'keep.txt': 'k\n' }); + await changes.beforePrompt('s1', root); + write(root, 'a.txt', 'changed\n'); + write(root, 'added.txt', 'new\n'); + fs.rmSync(path.join(root, 'gone.txt')); + write(root, 'keep.txt', 'K\n'); + await changes.keep('s1', root, ['keep.txt']); + write(root, 'keep.txt', 'KK\n'); + assert.deepEqual(await changes.undo('s1', root, ['a.txt']), ['a.txt']); + assert.equal(read(root, 'a.txt'), 'a\n'); + const undone = await changes.undo('s1', root, 'all'); + assert.deepEqual(undone.sort(), ['added.txt', 'gone.txt', 'keep.txt']); + assert.equal(read(root, 'added.txt'), null); + assert.equal(read(root, 'gone.txt'), 'g\n'); + assert.equal(read(root, 'keep.txt'), 'K\n', 'a kept file goes back to what was kept'); + assert.deepEqual((await changes.pending('s1', root)).files, []); + await assert.rejects(changes.undo('s1', root, ['../outside.txt']), /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); + assert.ok(first); + write(root, 'a.txt', 'turn 1\n'); + write(root, 'b.txt', 'b\n'); + await changes.beforePrompt('s1', root); + write(root, 'a.txt', 'turn 2\n'); + assert.deepEqual((await changes.previewRestore(root, first.checkpointId)).sort(), ['a.txt', 'b.txt']); + assert.equal(read(root, 'a.txt'), 'turn 2\n', 'a preview writes nothing'); + assert.deepEqual((await changes.restoreCheckpoint(root, first.checkpointId)).sort(), ['a.txt', 'b.txt']); + assert.equal(read(root, 'a.txt'), 'a\n'); + assert.equal(read(root, 'b.txt'), null); + assert.equal(await changes.afterTurn('s1', root), 0); + assert.throws(() => changes.previewRestore(root, 'HEAD'), /Invalid checkpoint/); + await changes.dispose(); + }); + + it('persists review bases per chat and forgets a deleted chat', async () => { + const { root, changes, basesFile } = setup({ 'a.txt': 'a\n' }); + const first = await changes.beforePrompt('s1', root); + await changes.beforePrompt('s2', root); + write(root, 'a.txt', 'b\n'); + await changes.dispose(); + const reopened = new SessionChanges({ storageDir: path.join(base, 'checkpoints'), bases: new JsonKeyValueStore(basesFile) }); + assert.equal(reopened.reviewBase('s1')?.baseId, first?.checkpointId); + assert.equal(await reopened.afterTurn('s1', root), 1); + await reopened.forget('s1'); + assert.equal(reopened.reviewBase('s1'), null); + assert.ok(reopened.reviewBase('s2')); + await assert.rejects(reopened.diff('s1', root, 'a.txt'), /no checkpoint/); + await reopened.dispose(); + }); + + it('degrades without checkpoints: no base, no count, the reason for the review', async () => { + const { root, changes } = setup({ 'a.txt': 'a\n', 'b.txt': 'b\n', 'c.txt': 'c\n' }, { maxFiles: 1 }); + assert.equal(await changes.beforePrompt('s1', root), null); + assert.equal(changes.reviewBase('s1'), null); + assert.equal(await changes.afterTurn('s1', root), null); + const pending = await changes.pending('s1', root); + assert.deepEqual(pending.files, []); + assert.ok(pending.disabledReason && pending.disabledReason.length > 0); + assert.deepEqual(await changes.changedSince(root, 'a'.repeat(40)), []); + await assert.rejects(changes.keep('s1', root, 'all'), /no checkpoint/); + await changes.dispose(); + }); +}); diff --git a/apps/ide/test/smoke.test.ts b/apps/ide/test/smoke.test.ts index ed4afea30..7db65b7b1 100644 --- a/apps/ide/test/smoke.test.ts +++ b/apps/ide/test/smoke.test.ts @@ -20,6 +20,7 @@ const healthy: SmokeProbe = { gitStatusState: 'ok', trust: { before: 'unknown', shieldShown: true, restrictedGit: 'restricted', tasksRefused: true, debugRefused: true, remoteRefused: true, after: 'trusted' }, gitTraversalRefused: true, + agentInstallRefused: true, editorOpened: true, fileIconsShown: 9, fileIconsBroken: [], @@ -79,6 +80,7 @@ describe('evaluateSmoke', () => { ['a push, stash or branch deletion ran in an untrusted folder (#284)', { trust: { before: 'unknown', shieldShown: true, restrictedGit: 'restricted', tasksRefused: true, debugRefused: true, remoteRefused: false, after: 'trusted' } }, /did not gate Git, tasks or debugging/], ['trust not taken (#177)', { trust: { error: 'boom' } }, /workspace trust did not gate Git/], ['Source Control traversal allowed', { gitTraversalRefused: false }, /git\.headContent followed/], + ['agent install reachable in the smoke run', { agentInstallRefused: false }, /could reach the npm registry/], ['no editor', { editorOpened: false }, /Monaco/], ['no file icons', { fileIconsShown: 0 }, /no file icon/], ['broken file icons', { fileIconsBroken: ['python'] }, /did not load: python/], diff --git a/apps/ide/test/worktrees.test.ts b/apps/ide/test/worktrees.test.ts new file mode 100644 index 000000000..a9f8d49be --- /dev/null +++ b/apps/ide/test/worktrees.test.ts @@ -0,0 +1,424 @@ +import { after, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + canUseWorktrees, commitAll, createWorktree, listWorktrees, mergeIntoCurrent, removeWorktree, worktreeStatus, WorktreeError, + type CreatedWorktree, +} from '../src/main/worktrees/worktreeManager.ts'; +import { worktreeGitEnvironment } from '../src/main/worktrees/worktreeGit.ts'; +import { + agentBranchName, isAgentBranch, isSafeSessionId, parseNameStatus, parsePorcelain, parseWorktreeList, repoHash, slugify, +} from '../src/main/worktrees/worktreeModel.ts'; + +const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-worktrees-'))); +const storageDir = path.join(base, 'storage'); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +let counter = 0; + +function realGit(cwd: string, ...args: string[]): string { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(process.env)) { + if (!key.startsWith('GIT_')) { + env[key] = value; + } + } + return execFileSync('git', args, { cwd, env, encoding: 'utf8' }); +} + +function write(root: string, relative: string, content: string): void { + const target = path.join(root, ...relative.split('/')); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); +} + +function read(root: string, relative: string): string | null { + const target = path.join(root, ...relative.split('/')); + return fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : null; +} + +/** A repository with a local identity, `files` committed on `main`. */ +function repo(files: Record = { 'a.txt': 'a\n', 'b.txt': 'b\n', 'src/c.txt': 'c\n' }): string { + counter += 1; + const root = path.join(base, `repo-${counter}`); + fs.mkdirSync(root, { recursive: true }); + realGit(root, 'init', '-q', '-b', 'main'); + realGit(root, 'config', 'user.name', 'Test Person'); + realGit(root, 'config', 'user.email', 'test@example.invalid'); + realGit(root, 'config', 'commit.gpgsign', 'false'); + // Git for Windows checks files out with CRLF by default; the tests compare bytes. + realGit(root, 'config', 'core.autocrlf', 'false'); + for (const [relative, content] of Object.entries(files)) { + write(root, relative, content); + } + realGit(root, 'add', '-A'); + realGit(root, 'commit', '-q', '-m', 'initial'); + return root; +} + +function porcelain(root: string): string { + return realGit(root, 'status', '--porcelain', '--untracked-files=all'); +} + +async function agent(root: string, label = 'Fix the parser'): Promise { + counter += 1; + return createWorktree({ projectRoot: root, storageDir, sessionId: `session-${counter}`, label }); +} + +async function rejectsWith(promise: Promise, code: string): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof WorktreeError, `expected a WorktreeError, got ${String(error)}`); + assert.equal(error.code, code, error.message); + return error; + } + assert.fail(`expected a ${code} refusal`); +} + +describe('worktree model', () => { + it('slugs labels and names branches under the agent prefix', () => { + assert.equal(slugify('Fix the Parser: ñandú édition!'), 'fix-the-parser-nandu-edition'); + assert.equal(slugify('***'), 'agent'); + assert.ok(slugify('x'.repeat(100)).length <= 32); + const branch = agentBranchName('Add tests', 'abc123'); + assert.equal(branch, 'codexr/agent/add-tests-abc123'); + assert.ok(isAgentBranch(branch)); + assert.ok(!isAgentBranch('main')); + assert.ok(!isAgentBranch('codexr/agent/')); + }); + + it('accepts only single safe path segments as session ids', () => { + assert.ok(isSafeSessionId('chat-1a2b_3.x')); + for (const bad of ['', '../x', 'a/b', 'a\\b', '.hidden', 'trailing.', 'a..b', 'x'.repeat(200)]) { + assert.ok(!isSafeSessionId(bad), bad); + } + }); + + it('hashes the repository case-insensitively on Windows and macOS only', () => { + assert.equal(repoHash('C:/Repo/.git', 'win32'), repoHash('c:/repo/.git', 'win32')); + assert.notEqual(repoHash('/Repo/.git', 'linux'), repoHash('/repo/.git', 'linux')); + assert.equal(repoHash('/x/.git', 'linux').length, 16); + }); + + it('parses worktree lists, name-status and porcelain', () => { + const list = parseWorktreeList('worktree /r\0HEAD aaa\0branch refs/heads/main\0\0worktree /w\0HEAD bbb\0branch refs/heads/codexr/agent/x-1\0locked\0prunable gone\0\0'); + assert.deepEqual(list.map((entry) => [entry.path, entry.branch, entry.locked, entry.prunable]), [ + ['/r', 'main', false, false], + ['/w', 'codexr/agent/x-1', true, true], + ]); + assert.deepEqual([...parseNameStatus('A\0n.txt\0M\0m.txt\0D\0d.txt\0')], [['n.txt', 'added'], ['m.txt', 'modified'], ['d.txt', 'deleted']]); + assert.deepEqual(parsePorcelain('M s.txt\0 M u.txt\0?? new.txt\0'), [ + { path: 's.txt', staged: true, untracked: false }, + { path: 'u.txt', staged: false, untracked: false }, + { path: 'new.txt', staged: false, untracked: true }, + ]); + }); + + it('drops inherited GIT_* variables and Electron switches from the environment', () => { + const env = worktreeGitEnvironment({ PATH: '/bin', GIT_DIR: '/elsewhere', git_work_tree: '/x', ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: '--inspect' }); + assert.equal(env['PATH'], '/bin'); + assert.equal(env['GIT_DIR'], undefined); + assert.equal(env['git_work_tree'], undefined); + assert.equal(env['ELECTRON_RUN_AS_NODE'], undefined); + assert.equal(env['NODE_OPTIONS'], undefined); + assert.equal(env['GIT_TERMINAL_PROMPT'], '0'); + }); +}); + +describe('agent worktrees', () => { + it('refuses a folder outside git and a repository without commits', async () => { + const plain = path.join(base, 'plain'); + fs.mkdirSync(plain, { recursive: true }); + const notRepo = await canUseWorktrees(plain); + assert.equal(notRepo.ok, false); + assert.equal(notRepo.ok ? '' : notRepo.reason, 'not-a-repo'); + + const empty = path.join(base, 'empty-repo'); + fs.mkdirSync(empty, { recursive: true }); + realGit(empty, 'init', '-q'); + const noCommits = await canUseWorktrees(empty); + assert.equal(noCommits.ok ? '' : noCommits.reason, 'no-commits'); + await rejectsWith(createWorktree({ projectRoot: empty, storageDir, sessionId: 's-empty', label: 'x' }), 'no-commits'); + await rejectsWith(createWorktree({ projectRoot: plain, storageDir, sessionId: 's-plain', label: 'x' }), 'not-a-repo'); + + const ok = await canUseWorktrees(repo()); + assert.equal(ok.ok, true); + }); + + it('creates a worktree on a fresh agent branch from HEAD, outside the project, and reports a dirty main tree', async () => { + const root = repo(); + write(root, 'a.txt', 'local edit\n'); + const head = realGit(root, 'rev-parse', 'HEAD').trim(); + const info = await agent(root); + assert.match(info.branch, /^codexr\/agent\/fix-the-parser-[0-9a-f]{6}$/); + assert.equal(info.baseCommit, head); + assert.equal(info.dirty, true); + assert.ok(path.relative(root, info.path).startsWith('..'), 'worktree is outside the project'); + assert.equal(path.basename(info.path), info.sessionId); + assert.equal(info.cwd, info.path); + // Starts from HEAD: the uncommitted edit is not carried over. + assert.equal(read(info.path, 'a.txt'), 'a\n'); + assert.equal(realGit(info.path, 'symbolic-ref', '--short', 'HEAD').trim(), info.branch); + + const clean = await agent(repo()); + assert.equal(clean.dirty, false); + await rejectsWith(createWorktree({ projectRoot: root, storageDir, sessionId: info.sessionId, label: 'again' }), 'already-exists'); + await rejectsWith(createWorktree({ projectRoot: root, storageDir, sessionId: '../escape', label: 'x' }), 'invalid-argument'); + await rejectsWith(createWorktree({ projectRoot: root, storageDir: path.join(root, 'inside'), sessionId: 's-in', label: 'x' }), 'storage-inside-project'); + }); + + it('keeps the project sub-folder as the agent cwd', async () => { + const root = repo(); + const info = await createWorktree({ projectRoot: path.join(root, 'src'), storageDir, sessionId: 'sub-folder', label: 'sub' }); + assert.equal(info.repoRoot, root); + assert.equal(info.cwd, path.join(info.path, 'src')); + assert.equal(read(info.cwd, 'c.txt'), 'c\n'); + }); + + it('reports committed and uncommitted changes against the base, then commits everything', async () => { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'a committed\n'); + realGit(info.path, 'commit', '-qam', 'agent edit'); + write(info.path, 'b.txt', 'b uncommitted\n'); + write(info.path, 'new/file.txt', 'new\n'); + fs.rmSync(path.join(info.path, 'src', 'c.txt')); + + const status = await worktreeStatus(info); + assert.equal(status.exists, true); + assert.equal(status.ahead, 1); + assert.equal(status.behind, 0); + assert.equal(status.hasUncommitted, true); + assert.deepEqual(status.files.map((file) => [file.path, file.status, file.committed, file.uncommitted]), [ + ['a.txt', 'modified', true, false], + ['b.txt', 'modified', false, true], + ['new/file.txt', 'added', false, true], + ['src/c.txt', 'deleted', false, true], + ]); + + const commit = await commitAll(info, 'Agent: finish'); + assert.ok(commit); + assert.equal(commit.fileCount, 3); + assert.equal(commit.fallbackIdentity, false); + assert.equal(realGit(info.path, 'log', '-1', '--format=%an <%ae>|%s').trim(), 'Test Person |Agent: finish'); + assert.equal(await commitAll(info, 'nothing'), null); + await rejectsWith(commitAll(info, ' '), 'invalid-argument'); + + const after = await worktreeStatus(info); + assert.equal(after.ahead, 2); + assert.equal(after.hasUncommitted, false); + assert.equal(after.files.length, 4); + // The main tree did not move. + assert.equal(read(root, 'a.txt'), 'a\n'); + }); + + it('runs no repository hook on its own commits', async () => { + const root = repo(); + const hook = path.join(root, '.git', 'hooks', 'pre-commit'); + const marker = path.join(base, `hook-ran-${counter}`); + fs.writeFileSync(hook, `#!/bin/sh\necho ran > "${marker}"\nexit 1\n`, { mode: 0o755 }); + const msgHook = path.join(root, '.git', 'hooks', 'prepare-commit-msg'); + fs.writeFileSync(msgHook, `#!/bin/sh\necho ran > "${marker}"\n`, { mode: 0o755 }); + const info = await agent(root); + write(info.path, 'a.txt', 'x\n'); + assert.ok(await commitAll(info, 'no hooks')); + assert.equal(fs.existsSync(marker), false); + }); + + it('falls back to the agent identity without writing any config', async () => { + const root = repo(); + realGit(root, 'config', '--unset', 'user.name'); + realGit(root, 'config', '--unset', 'user.email'); + const configBefore = fs.readFileSync(path.join(root, '.git', 'config'), 'utf8'); + const info = await agent(root); + write(info.path, 'a.txt', 'x\n'); + const previousHome = process.env['HOME']; + const previousXdg = process.env['XDG_CONFIG_HOME']; + // Isolate from the machine's global identity for this one call. + process.env['HOME'] = base; + process.env['XDG_CONFIG_HOME'] = base; + try { + const commit = await commitAll(info, 'fallback'); + assert.ok(commit); + assert.equal(commit.fallbackIdentity, true); + } finally { + restoreEnv('HOME', previousHome); + restoreEnv('XDG_CONFIG_HOME', previousXdg); + } + assert.equal(realGit(info.path, 'log', '-1', '--format=%an <%ae>').trim(), 'Code-XR agent '); + assert.equal(fs.readFileSync(path.join(root, '.git', 'config'), 'utf8'), configBefore); + }); + + it('merges with a merge commit', async () => { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'from agent\n'); + await commitAll(info, 'agent work'); + // The person keeps working on an unrelated file meanwhile. + write(root, 'b.txt', 'person edit\n'); + + const result = await mergeIntoCurrent(info, { strategy: 'merge' }); + assert.equal(result.into, 'main'); + assert.equal(result.nothingToMerge, false); + assert.equal(result.commit, realGit(root, 'rev-parse', 'HEAD').trim()); + assert.equal(realGit(root, 'rev-list', '--count', '--merges', 'HEAD^..HEAD').trim(), '1'); + assert.equal(read(root, 'a.txt'), 'from agent\n'); + assert.equal(read(root, 'b.txt'), 'person edit\n'); + + const again = await mergeIntoCurrent(info, { strategy: 'merge' }); + assert.equal(again.nothingToMerge, true); + assert.equal(again.commit, null); + }); + + it('squashes into one ordinary commit', async () => { + const root = repo(); + const info = await agent(root, 'Squash me'); + write(info.path, 'a.txt', 'one\n'); + await commitAll(info, 'first'); + write(info.path, 'b.txt', 'two\n'); + await commitAll(info, 'second'); + + const result = await mergeIntoCurrent(info, { strategy: 'squash', message: 'Agent: squash me' }); + assert.equal(result.strategy, 'squash'); + assert.equal(realGit(root, 'log', '-1', '--format=%P').trim().split(' ').length, 1, 'one parent'); + assert.equal(realGit(root, 'log', '-1', '--format=%s').trim(), 'Agent: squash me'); + assert.equal(read(root, 'a.txt'), 'one\n'); + assert.equal(read(root, 'b.txt'), 'two\n'); + assert.equal(porcelain(root), ''); + }); + + it('refuses a conflicting merge and leaves the main tree exactly as it was', async () => { + for (const strategy of ['merge', 'squash'] as const) { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'agent side\n'); + await commitAll(info, 'agent'); + write(root, 'a.txt', 'person side\n'); + realGit(root, 'commit', '-qam', 'person'); + write(root, 'b.txt', 'unrelated dirty\n'); + const headBefore = realGit(root, 'rev-parse', 'HEAD'); + const statusBefore = porcelain(root); + + const error = await rejectsWith(mergeIntoCurrent(info, { strategy }), 'conflicts'); + assert.deepEqual(error.files, ['a.txt']); + assert.equal(porcelain(root), statusBefore); + assert.equal(realGit(root, 'rev-parse', 'HEAD'), headBefore); + assert.equal(read(root, 'a.txt'), 'person side\n'); + assert.equal(read(root, 'b.txt'), 'unrelated dirty\n'); + } + }); + + it('refuses when the main tree has uncommitted or staged changes to the same files', async () => { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'agent\n'); + write(info.path, 'added.txt', 'agent new\n'); + await commitAll(info, 'agent'); + + write(root, 'a.txt', 'person dirty\n'); + const statusBefore = porcelain(root); + const dirty = await rejectsWith(mergeIntoCurrent(info, { strategy: 'merge' }), 'dirty-overlap'); + assert.deepEqual(dirty.files, ['a.txt']); + assert.equal(porcelain(root), statusBefore); + + realGit(root, 'checkout', '--', 'a.txt'); + write(root, 'added.txt', 'person untracked\n'); + const untracked = await rejectsWith(mergeIntoCurrent(info, { strategy: 'squash' }), 'dirty-overlap'); + assert.deepEqual(untracked.files, ['added.txt']); + fs.rmSync(path.join(root, 'added.txt')); + + write(root, 'b.txt', 'staged elsewhere\n'); + realGit(root, 'add', 'b.txt'); + await rejectsWith(mergeIntoCurrent(info, { strategy: 'squash' }), 'staged-changes'); + realGit(root, 'reset', '-q'); + + write(info.path, 'b.txt', 'agent not committed\n'); + await rejectsWith(mergeIntoCurrent(info, { strategy: 'merge' }), 'uncommitted-in-worktree'); + }); + + it('runs the person\'s hooks on the final merge and undoes it when one rejects', async () => { + for (const [strategy, hookName] of [['merge', 'pre-merge-commit'], ['squash', 'pre-commit']] as const) { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'agent\n'); + await commitAll(info, 'agent'); + write(root, 'b.txt', 'unrelated dirty\n'); + fs.writeFileSync(path.join(root, '.git', 'hooks', hookName), '#!/bin/sh\necho rejected by hook >&2\nexit 1\n', { mode: 0o755 }); + const headBefore = realGit(root, 'rev-parse', 'HEAD'); + const statusBefore = porcelain(root); + + const error = await rejectsWith(mergeIntoCurrent(info, { strategy }), 'merge-failed'); + assert.match(error.message, /rejected by hook/); + assert.equal(realGit(root, 'rev-parse', 'HEAD'), headBefore); + assert.equal(porcelain(root), statusBefore); + assert.equal(read(root, 'a.txt'), 'a\n'); + assert.equal(read(root, 'b.txt'), 'unrelated dirty\n'); + } + }); + + it('refuses to merge into a detached HEAD', async () => { + const root = repo(); + const info = await agent(root); + write(info.path, 'a.txt', 'agent\n'); + await commitAll(info, 'agent'); + realGit(root, 'checkout', '-q', '--detach'); + await rejectsWith(mergeIntoCurrent(info, { strategy: 'merge' }), 'detached-head'); + }); + + it('lists only agent worktrees, then removes them with or without the branch', async () => { + const root = repo(); + const first = await agent(root, 'First'); + const second = await agent(root, 'Second'); + const foreign = path.join(base, `foreign-${counter}`); + realGit(root, 'worktree', 'add', '-q', '-b', 'feature/mine', foreign); + + const listed = await listWorktrees(root); + assert.deepEqual(listed.map((entry) => entry.info.branch).sort(), [first.branch, second.branch].sort()); + const restored = listed.find((entry) => entry.info.branch === first.branch); + assert.ok(restored); + assert.equal(restored.recovered, false); + assert.equal(restored.info.baseCommit, first.baseCommit); + assert.equal(restored.info.sessionId, first.sessionId); + + const kept = await removeWorktree(first, { deleteBranch: false }); + assert.deepEqual(kept, { removedWorktree: true, deletedBranch: false }); + assert.equal(fs.existsSync(first.path), false); + assert.equal(realGit(root, 'branch', '--list', first.branch).trim().length > 0, true); + + const gone = await removeWorktree(second, { deleteBranch: true }); + assert.deepEqual(gone, { removedWorktree: true, deletedBranch: true }); + assert.equal(realGit(root, 'branch', '--list', second.branch).trim(), ''); + + assert.deepEqual(await listWorktrees(root), []); + assert.ok(fs.existsSync(foreign), 'a worktree that is not ours is never touched'); + await rejectsWith(removeWorktree({ ...first, branch: 'feature/mine', path: foreign }, { deleteBranch: true }), 'not-ours'); + + // Removing again is harmless; the branch delete then takes the branch. + assert.deepEqual(await removeWorktree(first, { deleteBranch: true }), { removedWorktree: false, deletedBranch: true }); + }); + + it('cleans up a worktree whose folder was deleted by hand', async () => { + const root = repo(); + const info = await agent(root); + fs.rmSync(info.path, { recursive: true, force: true }); + const status = await worktreeStatus(info); + assert.equal(status.exists, false); + await rejectsWith(commitAll(info, 'x'), 'worktree-missing'); + const listed = await listWorktrees(root); + assert.equal(listed[0]?.prunable, true); + assert.deepEqual(await removeWorktree(info, { deleteBranch: true }), { removedWorktree: true, deletedBranch: true }); + assert.deepEqual(await listWorktrees(root), []); + }); +}); + +function restoreEnv(key: string, value: string | undefined): void { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } +} diff --git a/apps/ide/tsconfig.node.json b/apps/ide/tsconfig.node.json index b7bcb450c..493be7c9c 100644 --- a/apps/ide/tsconfig.node.json +++ b/apps/ide/tsconfig.node.json @@ -9,5 +9,5 @@ "@codexr/logging/*": ["./.core-types/platform/logging/*"] } }, - "include": ["src/main/**/*.ts", "src/preload/**/*.ts", "src/scenePreload/**/*.ts", "src/extensionHost/**/*.ts", "src/shared/**/*.ts", "test/**/*.ts"] + "include": ["src/main/**/*.ts", "src/preload/**/*.ts", "src/scenePreload/**/*.ts", "src/extensionHost/**/*.ts", "src/shared/**/*.ts", "src/codexrMcp/**/*.ts", "test/**/*.ts"] } diff --git a/docs/ide/agent-first-test-guide.md b/docs/ide/agent-first-test-guide.md new file mode 100644 index 000000000..cc7cc7624 --- /dev/null +++ b/docs/ide/agent-first-test-guide.md @@ -0,0 +1,62 @@ +# Agent-first IDE (epic #265): manual test guide + +Everything here has unit tests and the IDE smoke test, run on Linux, Windows and macOS in CI, and the main flow was driven in the real window on Linux with a scripted agent. What CI cannot do is sign in to a real vendor agent. These checks need you, your machine and your own subscriptions. Each row names the story it closes; when all rows of a story pass, move its card to **Done**. + +## Before you start + +1. Update your copy to the `ide` branch, then from the repository root: `npm ci` and `npm run ide:dev` (or `npm run ide:start`). +2. Have at least one agent you can sign in to. Any of: + - **Claude Code** (Claude Pro/Max or an Anthropic API key): the IDE can install its adapter for you (step 2.1), or `npm install -g @agentclientprotocol/claude-agent-acp`. + - **Codex** (ChatGPT Plus/Pro or an OpenAI key): `npm install -g @agentclientprotocol/codex-acp`. + - **Gemini CLI** (Google account or Gemini API key): `npm install -g @google/gemini-cli`. + Installing from the IDE needs Node.js (npm) on your PATH. The adapters are large (Claude Code and Codex each download a native binary of about 400 MB). +3. Use a small project of your own that is a git repository, with the Python analysis environment ready (status bar: "Python: ready"). + +## 1. Layout and first run + +| # | Story | Steps | Expected | +|---|---|---|---| +| 1.1 | #278 | Start the IDE with no chats yet. | The welcome page shows "Get started" with three steps; steps already done are marked Done. **Skip** hides it for good; *Chat: Show Getting Started* in the palette (F1) reopens it as a tab. | +| 1.2 | #269 | Look at the window, then press Ctrl+Alt+M (Cmd+Alt+M on macOS) twice. | Agent layout: Chats on the left, work area in the middle, live analysis on the right. Classic is the workbench as before. The choice survives a restart. | +| 1.3 | #273 | Open your project in the Agent layout. | The right column shows the XR scene once the analysis finishes (or "Analyse this project"). The × hides the column; *View: Toggle Live Analysis Column* brings it back. | + +## 2. Agents and sign-in + +| # | Story | Steps | Expected | +|---|---|---|---| +| 2.1 | #267 | In the Chats view, Agents section, press **Install** on an agent that is not installed. | A description appears (package, version, licence, size, source, install scripts), then a native dialog with the exact npm command. Nothing downloads before you confirm. Progress shows as a notification; the agent becomes "Installed". **Remove** asks again before deleting. | +| 2.2 | #266 | Press **Check** on an installed agent. | It becomes "Ready", or "Needs login" with the vendor's own login buttons. | +| 2.3 | #266 | Use a login button. | A terminal opens with the vendor's own sign-in (browser or code). After it, **Check** says Ready. The IDE never asks for your password or token. | + +## 3. A coding chat + +| # | Story | Steps | Expected | +|---|---|---|---| +| 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.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. | + +## 4. Review, checkpoints, live analysis + +| # | Story | Steps | Expected | +|---|---|---|---| +| 4.1 | #273 | Watch the scene while the agent edits files. | The scene updates by itself (status bar: "Code-XR re-analysis updated N file(s)"), no save needed. | +| 4.2 | #274 | After a turn that changed code. | Under the turn: "Metrics: Complexity max a -> b, LOC ...", folded detail per file. | +| 4.3 | #270 | Press **Changes (N)** in the chat header. | A tab lists the changed files with a side-by-side diff. **Keep** and **Undo** per file and for all work; Undo puts the file back on disk. | +| 4.4 | #271 | On an earlier message, **Restore files to here**. | It lists the files it will change, then puts them back as they were before that message. Your own git history is untouched (`git status` and `git log` unchanged except the file contents). | + +## 5. Project instructions and worktrees + +| # | Story | Steps | Expected | +|---|---|---|---| +| 5.1 | #276 | Chats view, *Project instructions*: **Create** AGENTS.md, edit it, start a new chat and ask "what are the project rules?". | The file opens from a template; the agent quotes your rules. CLAUDE.md created from the panel imports AGENTS.md. | +| 5.2 | #277 | New chat with **Separate worktree** ticked; ask for a change; then Commit and Merge into your branch. | The agent works in a worktree outside the project (branch `codexr/agent/...`); your working copy only changes on Merge. Discard removes the worktree and its branch. | + +## Known limits + +- The scene follows the main project, not a chat's worktree. +- Checkpoints are skipped on very large projects (over 20,000 files) and ignore git-ignored files and files over 5 MB. +- An agent reads files from disk: unsaved editor changes are not visible to it. +- The built-in agents of the AI hub (Assistant, Code reviewer, Architect) still chat in the Agents view. diff --git a/package-lock.json b/package-lock.json index da62f4f8d..6a2772bee 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,8 @@ "typescript-language-server": "6.1.0" }, "devDependencies": { + "@agentclientprotocol/sdk": "2.12.0", + "@modelcontextprotocol/sdk": "1.32.2", "@types/node": "^22.20.7", "@types/vscode": "1.146.0", "@types/yauzl": "3.4.0", @@ -247,6 +249,22 @@ "vscode": "^1.98.0" } }, + "node_modules/@agentclientprotocol/sdk": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-2.12.0.tgz", + "integrity": "sha512-nSkamfY4Lw9/AVBU5G5V9p82ScXhANDMBybQwcPH/9+euUtZm04/VFUMaLj4gLFEXxQEy+QP1VQiKgSRbYVIPg==", + "dev": true, + "license": "Apache-2.0", + "peerDependencies": { + "@modelcontextprotocol/server": "^2.4.0", + "zod": "^3.25.76 || ^4.0.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": true + } + } + }, "node_modules/@azu/format-text": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@azu/format-text/-/format-text-1.0.2.tgz", @@ -980,6 +998,19 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@hono/node-server": { + "version": "2.1.11", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.11.tgz", + "integrity": "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -1164,6 +1195,89 @@ "node": ">=10" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz", + "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/@napi-rs/canvas": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz", @@ -3262,6 +3376,47 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/acorn": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", @@ -3905,6 +4060,62 @@ "dev": true, "license": "MIT" }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -4119,6 +4330,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/bytestreamjs": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz", @@ -4500,6 +4721,50 @@ "dev": true, "license": "MIT" }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, "node_modules/copy-webpack-plugin": { "version": "13.0.1", "resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-13.0.1.tgz", @@ -4544,6 +4809,24 @@ "dev": true, "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/cross-dirname": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", @@ -4751,6 +5034,16 @@ "node": ">=0.4.0" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -4982,6 +5275,13 @@ "url": "https://bevry.me/fund" } }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT" + }, "node_modules/ejs": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", @@ -5208,6 +5508,20 @@ "dev": true, "license": "MIT" }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/encoding-sniffer": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz", @@ -5379,6 +5693,13 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -5620,6 +5941,16 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/events": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", @@ -5630,6 +5961,29 @@ "node": ">=0.8.x" } }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/expand-template": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", @@ -5648,34 +6002,139 @@ "dev": true, "license": "Apache-2.0" }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "node_modules/express-rate-limit": { + "version": "8.7.5", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.5.tgz", + "integrity": "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA==", "dev": true, "license": "MIT", "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" + "debug": "^4.4.3", + "ip-address": "^10.2.0" }, "engines": { - "node": ">=8.6.0" + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" } }, - "node_modules/fast-json-stable-stringify": { + "node_modules/express/node_modules/content-type": { "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true, "license": "MIT" }, @@ -5782,6 +6241,28 @@ "node": ">=8" } }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -5864,6 +6345,26 @@ "node": ">= 6" } }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fs-constants": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", @@ -6278,6 +6779,16 @@ "node": ">= 0.4" } }, + "node_modules/hono": { + "version": "4.13.23", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.23.tgz", + "integrity": "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hosted-git-info": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", @@ -6331,6 +6842,27 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -6515,6 +7047,26 @@ "node": ">=10.13.0" } }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-core-module": { "version": "2.16.1", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", @@ -6622,6 +7174,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-wsl": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", @@ -6778,6 +7337,16 @@ "jiti": "lib/jiti-cli.mjs" } }, + "node_modules/jose": { + "version": "6.2.18", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.18.tgz", + "integrity": "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -6819,6 +7388,13 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "dev": true, + "license": "BSD-2-Clause" + }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -7449,6 +8025,33 @@ "dev": true, "license": "MIT" }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -7659,6 +8262,37 @@ "dev": true, "license": "MIT" }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", @@ -7911,10 +8545,20 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", "dev": true, "license": "MIT", "engines": { @@ -7935,6 +8579,23 @@ "node": ">= 0.4" } }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -8158,6 +8819,16 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -8222,6 +8893,17 @@ "node": "20 || >=22" } }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/path-type": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-6.0.0.tgz", @@ -8290,6 +8972,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkce-challenge": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.2.tgz", + "integrity": "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkg-dir": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", @@ -8617,6 +9309,24 @@ "dev": true, "license": "ISC" }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pump": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", @@ -8675,13 +9385,14 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", - "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.1.0" + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" @@ -8724,6 +9435,53 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -9111,6 +9869,27 @@ "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, + "node_modules/router": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", + "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/run-applescript": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", @@ -9296,6 +10075,60 @@ "license": "MIT", "optional": true }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/send/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/send/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/serialize-error": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", @@ -9337,6 +10170,33 @@ "node": ">=20.0.0" } }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, "node_modules/shallow-clone": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", @@ -9374,15 +10234,15 @@ } }, "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -9394,14 +10254,14 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -9650,6 +10510,16 @@ "node": ">= 6" } }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -10188,6 +11058,16 @@ "node": ">=8.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/truncate-utf8-bytes": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz", @@ -10309,6 +11189,66 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "dev": true, + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/type-is/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/typed-rest-client": { "version": "1.8.11", "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.11.tgz", @@ -10400,6 +11340,16 @@ "node": ">= 10.0.0" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/unzipper": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", @@ -10525,6 +11475,16 @@ "spdx-expression-parse": "^3.0.0" } }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/version-range": { "version": "4.15.0", "resolved": "https://registry.npmjs.org/version-range/-/version-range-4.15.0.tgz", @@ -11030,6 +11990,26 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } } } }