diff --git a/apps/ide/README.md b/apps/ide/README.md index 4a1c069c..3e538076 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -389,6 +389,8 @@ The IDE opens in the **Agent** layout: chats with the person's own coding agents - **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`). +- **Signing in (AF14, #297):** a terminal sign-in method runs the agent's login program directly, with no shell, in a terminal tab of its own (`TerminalHost.runProgram`, shown through `TerminalPanel.runTask`), so nothing is typed into the person's shell; the agent is checked again when it ends. *Check* asks the agent who is signed in with `auth/status` (an ACP draft that Claude Code's and Codex's adapters answer) and reports *Needs login* or *Signed in as ...*, because Claude Code opens sessions while signed out and only refuses the first prompt. Agents that cannot say are judged by `session/new`. +- **Importing an agent's chats (AF15, #298):** *Import chats* on a ready agent lists the chats it keeps for the open folder (`session/list`, newest first, at most 200, none already in the IDE) and adds the chosen ones; each reads its messages from the agent's `session/load` replay the first time it opens (`historyPending`), then continues the same agent session. The agent reads its own history files; the IDE never opens them. ## VS Code extensions (stream `ide-extensions`, epic #251) diff --git a/apps/ide/src/main/agentSessions/acpConnection.ts b/apps/ide/src/main/agentSessions/acpConnection.ts index 512cc0e2..21678ae4 100644 --- a/apps/ide/src/main/agentSessions/acpConnection.ts +++ b/apps/ide/src/main/agentSessions/acpConnection.ts @@ -11,6 +11,7 @@ import { type CreateTerminalRequest, type CreateTerminalResponse, type InitializeResponse, + type ListSessionsResponse, type KillTerminalRequest, type LoadSessionResponse, type McpServer, @@ -225,6 +226,24 @@ export class AcpConnection { })); } + /** + * #297: `auth/status` (an ACP draft that Claude Code and Codex answer when + * they advertise `agentCapabilities.auth.status`): whether the agent is + * signed in, and as whom. Unknown when the answer has another shape. + */ + async authStatus(): Promise<{ readonly state: 'authenticated' | 'unauthenticated' | 'unknown'; readonly account?: string }> { + const response = await this.explain(this.connection.agent.request('auth/status', {})); + const record = response && typeof response === 'object' ? (response as Record) : {}; + const state = record['state']; + if (state !== 'authenticated' && state !== 'unauthenticated') { + return { state: 'unknown' }; + } + const accounts = Array.isArray(record['accounts']) ? (record['accounts'] as unknown[]) : []; + const first = accounts.find((item): item is Record => !!item && typeof item === 'object'); + const label = first ? [first['email'], first['label']].find((value): value is string => typeof value === 'string' && value.trim() !== '') : undefined; + return label ? { state, account: label.slice(0, 200) } : { state }; + } + authenticate(methodId: string): Promise { return this.explain(this.connection.agent.request(methods.agent.authenticate, { methodId })); } @@ -233,6 +252,11 @@ export class AcpConnection { return this.explain(this.connection.agent.request(methods.agent.session.new, { cwd, mcpServers: [...mcpServers] })); } + /** #298: one page of the agent's own history for `cwd` (ACP `session/list`). */ + listSessions(cwd: string, cursor?: string): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.list, { cwd, ...(cursor ? { cursor } : {}) })); + } + loadSession(sessionId: string, cwd: string, mcpServers: readonly McpServer[]): Promise { return this.explain(this.connection.agent.request(methods.agent.session.load, { sessionId, cwd, mcpServers: [...mcpServers] })); } diff --git a/apps/ide/src/main/agentSessions/agentCatalog.ts b/apps/ide/src/main/agentSessions/agentCatalog.ts index 35c0e49e..483adca4 100644 --- a/apps/ide/src/main/agentSessions/agentCatalog.ts +++ b/apps/ide/src/main/agentSessions/agentCatalog.ts @@ -236,6 +236,25 @@ function cmdQuote(part: string): string { return /[\s&|<>^()]/.test(part) || part === '' ? `"${part}"` : part; } +/** + * #297: the program a terminal login method runs, started directly in a + * terminal with no shell between. The `terminal-auth` hint names its own + * command; otherwise the agent's own launch runs with the method's arguments. + * A `cmd.exe /d /s /c "..."` launch (a custom agent's .cmd shim on Windows) + * cannot be passed to a terminal unchanged, so its login is refused with how + * to run it by hand. + */ +export function loginProgram(launch: AgentLaunch, spec: Pick): { command: string; args: string[] } { + const extra = spec.args ?? []; + if (spec.command) { + return { command: spec.command, args: [...extra] }; + } + if (launch.verbatimArguments) { + throw new Error(`Run this agent's login yourself in a terminal: its command with ${extra.join(' ') || 'its login arguments'}.`); + } + return { command: launch.command, args: [...launch.args, ...extra] }; +} + export class AgentCatalog { private readonly options: CatalogOptions; private readonly probe: FileProbe; diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index b8d68626..9a505b32 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -23,6 +23,7 @@ import { type AgentView, type ChangeDiffView, type ChatChanges, + type ImportableSession, type InstallDescription, type LoginTerminal, type PermissionOptionView, @@ -57,7 +58,7 @@ import { type MappingContext, type ResolvedAttachment, } from './acpMapping.ts'; -import type { AgentCatalog } from './agentCatalog.ts'; +import { loginProgram, type AgentCatalog } from './agentCatalog.ts'; import { parsePresetId, type AgentInstaller } from './agentInstaller.ts'; import { AgentTerminals } from './agentTerminals.ts'; import { isSessionId, type SessionStore } from './sessionStore.ts'; @@ -110,7 +111,10 @@ export interface AgentSessionServiceOptions { * 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 }>; + /** + * #297: runs a login program directly (no shell) in a terminal of the window. + */ + readonly openTerminal: (window: WindowPort, request: { readonly command: string; readonly args: readonly string[]; readonly cwd: string; readonly env: Readonly>; readonly title: string; readonly cols: number; readonly rows: number }) => 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. */ @@ -193,6 +197,8 @@ interface Live { cancelRequested: boolean; cancelTimer: ReturnType | null; replaying: boolean; + /** #298: the person's messages of an imported history arrive in chunks; they are joined here. */ + importedUser: string | null; configRaw: readonly SessionConfigOption[]; readonly permissions: Map; readonly terminalBuffer: Map; @@ -206,6 +212,15 @@ 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; +/** #298: at most this many chats are offered for import, read in at most this many pages. */ +const MAX_IMPORT = 200; +const MAX_IMPORT_PAGES = 20; + +/** #298: an imported chat's title: the agent's, cleaned, or a neutral one. */ +function importTitle(value: unknown): string { + const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : ''; + return text ? (text.length > 80 ? `${text.slice(0, 79)}...` : text) : 'Imported chat'; +} /** Fails with `message` when `promise` takes longer than `ms`. */ function withTimeout(promise: Promise, ms: number, message: string): Promise { @@ -333,7 +348,7 @@ export class AgentSessionService { this.broadcast({ kind: 'agents-changed' }); } - async login(window: WindowPort, ref: unknown, methodId: unknown): Promise { + async login(window: WindowPort, ref: unknown, methodId: unknown, cols?: unknown, rows?: unknown): Promise { this.remember(window); const agentRef = requireString(ref, 'agent', 200); const method = requireString(methodId, 'login method', 200); @@ -360,10 +375,17 @@ export class AgentSessionService { } 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 program = loginProgram(launch, spec); 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}` }); + const size = (value: unknown, fallback: number): number => (typeof value === 'number' && Number.isInteger(value) && value >= 2 && value <= 1000 ? value : fallback); + const opened = await this.options.openTerminal(window, { + ...program, + cwd, + env: { ...launch.env, ...(spec.env ?? {}) }, + title: `${definition.name}: ${spec.view.name}`, + cols: size(cols, 100), + rows: size(rows, 30), + }); // Once the login command ends, the agent is probed again; the picker hears `agents-changed`. void opened.exited .then(() => this.probeAgent(window, agentRef)) @@ -477,9 +499,16 @@ export class AgentSessionService { return; } const authMethods = mapAuthMethods(init.authMethods ?? []); + // #297: an agent may open a session while signed out and only refuse the + // first prompt (Claude Code does), so ask who is signed in when it can say. + const status = await readAuthStatus(connection, init, timeout); + if (status.state === 'unauthenticated') { + this.options.catalog.setState(agentRef, { availability: 'needs-login', detail: 'Not signed in. Use one of its sign-in buttons.', authMethods }); + return; + } 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 }); + this.options.catalog.setState(agentRef, { availability: 'ready', authMethods, ...(status.account ? { detail: `Signed in as ${status.account}.` } : {}) }); } catch (error) { this.options.catalog.setState(agentRef, isAuthRequiredError(error) ? { availability: 'needs-login', detail: 'Log in to use this agent.', authMethods } @@ -487,6 +516,129 @@ export class AgentSessionService { } } + /** #298: the joined message of the person in an imported replay becomes a message of the chat. */ + private flushImportedUser(live: Live): void { + const text = live.importedUser; + live.importedUser = null; + if (text !== null && text.trim()) { + this.emit(live, { type: 'user', id: randomUUID(), text, at: live.state.updatedAt }); + } + } + + /** + * #298: the chats the agent keeps in its own history for the open folder + * (ACP `session/list`), less those already in the IDE. The agent reads its + * own files; the IDE never opens them. + */ + async listImportable(window: WindowPort, ref: unknown): Promise { + this.remember(window); + const agentRef = requireString(ref, 'agent', 200); + const root = this.options.rootOf(window); + if (!root) { + throw new Error('Open a folder to import its chats.'); + } + if (!this.options.isTrusted(window)) { + throw new Error('This folder is in Restricted Mode. Trust it to start an agent.'); + } + const definition = this.options.catalog.definition(agentRef); + if (!definition) { + throw new Error('Only an ACP agent keeps a history to import.'); + } + const resolution = await this.options.catalog.resolve(definition); + if (!resolution.found) { + throw new Error(resolution.detail); + } + const connection = this.connectAgent(resolution.launch, root, REFUSING_HANDLERS); + const timeout = this.options.startTimeoutMs ?? 60_000; + try { + const init = await withTimeout(connection.initialize(), timeout, 'The agent did not answer initialize in time.'); + if (!init.agentCapabilities?.sessionCapabilities?.list || !init.agentCapabilities.loadSession) { + throw new Error(`${definition.name} cannot list or reopen its earlier chats, so there is nothing to import.`); + } + const known = await this.linkedAgentSessions(root, agentRef); + const found: ImportableSession[] = []; + let cursor: string | undefined; + for (let page = 0; page < MAX_IMPORT_PAGES; page += 1) { + const response = await withTimeout(connection.listSessions(root, cursor), timeout, 'The agent did not list its chats in time.'); + for (const info of response.sessions) { + if (typeof info.sessionId !== 'string' || !info.sessionId || info.sessionId.length > 200 || known.has(info.sessionId)) { + continue; + } + // Only the chats of this folder: an agent may ignore the filter. + if (typeof info.cwd === 'string' && !isSameOrInside(root, info.cwd, this.platform)) { + continue; + } + found.push({ agentSessionId: info.sessionId, title: importTitle(info.title), updatedAt: typeof info.updatedAt === 'string' ? info.updatedAt : null }); + } + cursor = typeof response.nextCursor === 'string' && response.nextCursor ? response.nextCursor : undefined; + if (!cursor || found.length >= MAX_IMPORT) { + break; + } + } + return found.sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '')).slice(0, MAX_IMPORT); + } catch (error) { + if (isAuthRequiredError(error)) { + throw new Error(`${definition.name} needs you to sign in first.`); + } + throw error; + } finally { + connection.close(); + } + } + + /** #298: adds chats of the agent's history to the folder's list; each reads its messages when first opened. */ + async importSessions(window: WindowPort, ref: unknown, sessions: unknown): Promise { + this.remember(window); + const agentRef = requireString(ref, 'agent', 200); + const root = this.options.rootOf(window); + if (!root) { + throw new Error('Open a folder to import its chats.'); + } + const definition = this.options.catalog.definition(agentRef); + if (!definition) { + throw new Error('Only an ACP agent keeps a history to import.'); + } + if (!Array.isArray(sessions) || sessions.length > MAX_IMPORT) { + throw new Error(`Import at most ${MAX_IMPORT} chats at a time.`); + } + const known = await this.linkedAgentSessions(root, agentRef); + let added = 0; + for (const raw of sessions as unknown[]) { + const record = raw && typeof raw === 'object' ? (raw as Record) : {}; + const agentSessionId = record['agentSessionId']; + if (typeof agentSessionId !== 'string' || !agentSessionId || agentSessionId.length > 200 || known.has(agentSessionId)) { + continue; + } + const updatedAt = typeof record['updatedAt'] === 'string' && !Number.isNaN(Date.parse(record['updatedAt'])) ? new Date(record['updatedAt']).toISOString() : this.now(); + const base = emptySession({ id: randomUUID(), title: importTitle(record['title']), agentRef, agentName: definition.name, workspaceRoot: root, createdAt: updatedAt, updatedAt }); + const state: AgentSessionState = { ...base, agentSessionId, historyPending: true }; + known.add(agentSessionId); + this.track(state, root, window.id); + await this.options.store.saveNow(state); + added += 1; + } + if (added > 0) { + this.sessionsChanged(); + } + return added; + } + + /** The agent-side ids of the folder's chats with `agentRef`, so a chat is not imported twice. */ + private async linkedAgentSessions(root: string, agentRef: string): Promise> { + const ids = new Set(); + const projects = await this.options.store.listProjects(root); + for (const summary of projects.find((project) => project.root === root)?.sessions ?? []) { + if (summary.agentRef !== agentRef) { + continue; + } + const state = this.live.get(summary.id)?.state ?? (await this.options.store.load(root, summary.id)); + if (state?.agentSessionId) { + ids.add(state.agentSessionId); + } + } + return ids; + } + private connectAgent(launch: AgentLaunch, cwd: string, handlers: AcpClientHandlers): AcpConnection { if (!this.options.spawnAllowed || this.stopped) { throw new Error('Agents cannot start in this mode.'); @@ -507,6 +659,10 @@ export class AgentSessionService { async get(window: WindowPort, sessionId: unknown): Promise { this.remember(window); const live = await this.open(window, sessionId); + // #298: an imported chat reads its messages from the agent when it is first opened. + if (live.state.historyPending && this.options.spawnAllowed && this.options.isTrusted(window) && this.options.rootOf(window) === live.root) { + void this.ensureAgent(live, window).catch((error: unknown) => this.reportStartFailure(live, error)); + } return live.state; } @@ -984,6 +1140,7 @@ export class AgentSessionService { cancelRequested: false, cancelTimer: null, replaying: false, + importedUser: null, configRaw: [], permissions: new Map(), terminalBuffer: new Map(), @@ -1121,18 +1278,28 @@ export class AgentSessionService { const previous = live.state.agentSessionId; let sessionId: string | null = null; if (previous && init.agentCapabilities?.loadSession) { - live.replaying = true; + // #298: an imported chat keeps what the agent replays: that is its history. + const importing = live.state.historyPending === true; + live.replaying = !importing; try { const loaded = await withTimeout(connection.loadSession(previous, workRoot, mcpServers), timeout, 'The agent did not reopen the chat in time.'); sessionId = previous; + if (importing) { + this.flushImportedUser(live); + this.emit(live, { type: 'history', pending: false }); + } 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.` }); + if (importing) { + this.emit(live, { type: 'history', pending: false }); + } } finally { live.replaying = false; + live.importedUser = null; } } if (!sessionId) { @@ -1192,6 +1359,19 @@ export class AgentSessionService { } private onUpdate(live: Live, update: SessionUpdate, ctx: MappingContext): void { + if (live.state.historyPending) { + // #298: the replay of an imported chat. The person's messages come as + // chunks the live mapping ignores (the IDE records its own), so they + // are joined here and become the chat's messages. + if (update.sessionUpdate === 'user_message_chunk') { + const text = update.content.type === 'text' ? update.content.text : ''; + live.importedUser = (live.importedUser ?? '') + text; + return; + } + if (!['available_commands_update', 'current_mode_update', 'config_option_update', 'usage_update'].includes(update.sessionUpdate)) { + this.flushImportedUser(live); + } + } 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; @@ -1441,7 +1621,7 @@ export class AgentSessionService { 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.` }); + this.emit(live, { type: 'notice', id: randomUUID(), level: 'error', text: `${live.state.agentName} needs you to sign in. Use one of its sign-in buttons in the Agents section of the Chats view, then send the message again.` }); return; } this.emit(live, { type: 'notice', id: randomUUID(), level: 'error', text: errorMessage(error) }); @@ -1477,3 +1657,16 @@ export class AgentSessionService { live.terminalBuffer.clear(); } } + +/** #297: `auth/status` when the agent advertises it; unknown otherwise or on any failure. */ +async function readAuthStatus(connection: AcpConnection, init: InitializeResponse, timeout: number): Promise<{ readonly state: 'authenticated' | 'unauthenticated' | 'unknown'; readonly account?: string }> { + const capabilities = init.agentCapabilities as { readonly auth?: { readonly status?: unknown } } | undefined; + if (!capabilities?.auth?.status) { + return { state: 'unknown' }; + } + try { + return await withTimeout(connection.authStatus(), Math.min(timeout, 15_000), 'The agent did not say whether it is signed in.'); + } catch { + return { state: 'unknown' }; + } +} diff --git a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts index 6ec5a43d..7d73d180 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsIpc.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsIpc.ts @@ -18,7 +18,7 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi 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.login, (event, ref, methodId, cols, rows) => service.login(portOf(event.sender), ref, methodId, cols, rows)); 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)); @@ -42,6 +42,8 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi 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)); + handle(C.listImportable, (event, ref) => service.listImportable(portOf(event.sender), ref)); + handle(C.importSessions, (event, ref, sessions) => service.importSessions(portOf(event.sender), ref, sessions)); // 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))); diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 68742c3a..df04e5de 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -3,7 +3,6 @@ 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'; @@ -14,7 +13,6 @@ import { addFolderChangeListener, currentWorkspaceInfo } from '../workspace/work 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'; @@ -196,15 +194,26 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS 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 }; + // #297: the login program itself runs in the terminal, with no shell between: + // nothing is typed into the person's shell, so no quoting or start-up race. + const created = await options.terminal.runProgram( + contents, + { + file: request.command, + args: request.args, + env: { ...terminalEnvironment(process.env), ...request.env }, + name: request.title, + }, + request.cwd, + request.cols, + request.rows, + { onExit: (_id, exitCode) => markExited(exitCode) }, + ); + return { terminal: { terminal: created, title: request.title, command: [request.command, ...request.args].join(' ') }, exited }; }, // AF10: every chat gets the Code-XR MCP server, so the agent can query the // project's metrics, hotspots, dependencies and evolution itself. diff --git a/apps/ide/src/main/agentSessions/sessionStore.ts b/apps/ide/src/main/agentSessions/sessionStore.ts index 8ecafb36..d3281316 100644 --- a/apps/ide/src/main/agentSessions/sessionStore.ts +++ b/apps/ide/src/main/agentSessions/sessionStore.ts @@ -76,7 +76,7 @@ function worktreeOf(value: unknown): SessionWorktree | undefined { /** 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: storedWorktree, historyPending: _history, ...rest } = state; const worktree = worktreeOf(storedWorktree); return settled({ ...rest, @@ -92,6 +92,7 @@ function normalize(state: AgentSessionState): AgentSessionState { configOptions: Array.isArray(state.configOptions) ? state.configOptions : [], usage: state.usage ?? null, agentSessionId: typeof state.agentSessionId === 'string' ? state.agentSessionId : null, + ...(state.historyPending === true ? { historyPending: true } : {}), }); } diff --git a/apps/ide/src/main/terminal/terminalHost.ts b/apps/ide/src/main/terminal/terminalHost.ts index 820d5a98..d62a0bbd 100644 --- a/apps/ide/src/main/terminal/terminalHost.ts +++ b/apps/ide/src/main/terminal/terminalHost.ts @@ -32,6 +32,8 @@ export interface TerminalHost { killAll(): Promise; /** #176: a terminal of this window that runs one command line in `cwd`, with the default profile's shell. */ runCommand(contents: WebContents, command: string, cwd: string, cols: unknown, rows: unknown, hooks: CommandHooks): Promise; + /** #297: a terminal of this window that runs one program directly (no shell), with `env` as its whole environment. */ + runProgram(contents: WebContents, program: { readonly file: string; readonly args: readonly string[]; readonly env: Readonly>; readonly name: string }, cwd: string, cols: unknown, rows: unknown, hooks: CommandHooks): Promise; /** The default profile's shell, which task command lines are quoted for. */ defaultShellPath(): Promise; /** Runs agents' commands (epic #189, A9) with the default profile's shell. */ @@ -165,6 +167,12 @@ export function createTerminalHost(options: { readonly isSmoke: boolean }): Term log.info(`Terminal ${created.id}: task with ${created.profile.name} in ${cwd}`); return created; }, + async runProgram(contents, program, cwd, cols, rows, hooks) { + track(contents); + const created = await service.createProgram(contents, program, cols, rows, cwd, hooks); + log.info(`Terminal ${created.id}: ${program.name} in ${cwd}`); + return created; + }, defaultShellPath: async () => (await registry.resolve(null)).path, input: (contents, id, data) => service.input(contents, id, data), resize: (contents, id, cols, rows) => service.resize(contents, id, cols, rows), diff --git a/apps/ide/src/main/terminal/terminalService.ts b/apps/ide/src/main/terminal/terminalService.ts index 107c43b1..da32b426 100644 --- a/apps/ide/src/main/terminal/terminalService.ts +++ b/apps/ide/src/main/terminal/terminalService.ts @@ -111,20 +111,30 @@ export class TerminalService { return this.start(owner, null, cols, rows, cwd, args, hooks); } - private async start(owner: TerminalOwner, profileId: unknown, cols: unknown, rows: unknown, cwd: string, args: (profile: TerminalProfile) => readonly string[], hooks: CommandHooks): Promise { + /** + * #297: a terminal that runs one program directly, with no shell between + * (an agent's own login): `env` is its whole environment and `name` the + * terminal's title. It ends with the program, like a task. + */ + createProgram(owner: TerminalOwner, program: { readonly file: string; readonly args: readonly string[]; readonly env: Readonly>; readonly name: string }, cols: unknown, rows: unknown, cwd: string, hooks: CommandHooks): Promise { + const profile: TerminalProfile = { id: 'program', name: program.name, path: program.file, args: [...program.args], source: 'custom' }; + return this.start(owner, null, cols, rows, cwd, () => program.args, hooks, { profile, env: program.env }); + } + + private async start(owner: TerminalOwner, profileId: unknown, cols: unknown, rows: unknown, cwd: string, args: (profile: TerminalProfile) => readonly string[], hooks: CommandHooks, program?: { readonly profile: TerminalProfile; readonly env: Readonly> }): Promise { if (!isDimension(cols) || !isDimension(rows)) { throw new Error('Invalid terminal size.'); } if (this.countOf(owner.id) >= MAX_TERMINALS_PER_WINDOW) { throw new Error(`At most ${MAX_TERMINALS_PER_WINDOW} terminals per window.`); } - const profile = await this.options.resolveProfile(profileId); + const profile = program ? program.profile : await this.options.resolveProfile(profileId); const pty = await this.options.spawn(profile.path, args(profile), { name: 'xterm-256color', cols, rows, cwd, - env: terminalEnvironment(this.options.env), + env: program ? { ...program.env } : terminalEnvironment(this.options.env), }); const id = this.nextId++; let markGone: () => void = () => undefined; diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index dbf2d61c..f4e50c13 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -6,7 +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 { AGENT_SESSION_CHANNELS, AGENT_SESSION_EVENTS, type AcpAgentDefinition, type AgentSessionMessage, type ImportableSession, 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'; @@ -77,7 +77,7 @@ const api: CodeXRApi = Object.freeze({ 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), + login: (ref: string, methodId: string, cols?: number, rows?: number) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.login, ref, methodId, cols, rows), 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 }), @@ -102,6 +102,8 @@ const api: CodeXRApi = Object.freeze({ 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), + listImportable: (ref: string) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.listImportable, ref), + importSessions: (ref: string, sessions: readonly ImportableSession[]) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.importSessions, ref, sessions), 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), diff --git a/apps/ide/src/renderer/agentFirst/agentFirst.css b/apps/ide/src/renderer/agentFirst/agentFirst.css index 14d1b12d..8e34545a 100644 --- a/apps/ide/src/renderer/agentFirst/agentFirst.css +++ b/apps/ide/src/renderer/agentFirst/agentFirst.css @@ -320,3 +320,33 @@ .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; } + + +/* #298: importing an agent's earlier chats (appended block; the visual audit owns the rest). */ +.af-import-list { + display: flex; + flex-direction: column; + gap: 2px; + max-height: 220px; + overflow-y: auto; + margin: 4px 0; +} +.af-import-row { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + padding: 2px 0; + cursor: pointer; +} +.af-import-title { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.af-import-when { + flex: 0 0 auto; + font-size: 11px; +} diff --git a/apps/ide/src/renderer/agentFirst/agentSetup.ts b/apps/ide/src/renderer/agentFirst/agentSetup.ts index fc4a6d04..78fcdfe6 100644 --- a/apps/ide/src/renderer/agentFirst/agentSetup.ts +++ b/apps/ide/src/renderer/agentFirst/agentSetup.ts @@ -1,6 +1,7 @@ -import type { AgentSessionsApi, AgentView, InstallDescription } from '../../shared/agentSession.ts'; +import type { AgentSessionsApi, AgentView, ImportableSession, InstallDescription } from '../../shared/agentSession.ts'; +import type { TerminalCreated } from '../../shared/api.ts'; import { el } from '../dom.ts'; -import { describeRows, isUpToDate, setupActions } from './agentSetupModel.ts'; +import { describeRows, importedWhen, isUpToDate, setupActions } from './agentSetupModel.ts'; /** * The actions of one agent (AF1, AF2 #267), shared by the Agents section of @@ -16,8 +17,8 @@ import { describeRows, isUpToDate, setupActions } from './agentSetupModel.ts'; export interface AgentSetupDeps { readonly api: AgentSessionsApi; onStatus(message: string): void; - /** Shows the terminal panel (terminal sign-ins). */ - showTerminal?(): void; + /** #297: runs a terminal sign-in in a terminal of its own in the panel (`TerminalPanel.runTask`). */ + runInTerminal?(label: string, start: (cols: number, rows: number) => Promise): Promise; /** Reloads the agents (and probes them when asked). */ refresh(probe: boolean): Promise; /** One agent's new view, after a check. */ @@ -42,14 +43,27 @@ export function agentActions(agent: AgentView, deps: AgentSetupDeps): HTMLElemen if (action === 'login') { for (const method of (agent.authMethods ?? []).slice(0, 3)) { button(method.name, method.description ?? method.name, () => { + if (method.type === 'terminal' && deps.runInTerminal) { + // #297: the login program gets a terminal of its own in the panel, shown at once. + const label = `${agent.name}: ${method.name}`; + deps.runInTerminal(label, (cols, rows) => deps.api.login(agent.ref, method.id, cols, rows).then((opened) => { + if (!opened) { + throw new Error('The agent did not start a sign-in.'); + } + return { ...opened.terminal, command: opened.command }; + })) + .then((id) => { + if (id !== null) { + deps.onStatus(`${agent.name}: follow the sign-in in the terminal. The agent is checked again when it ends.`); + } + }) + .catch((error: unknown) => deps.onStatus(errorText(error))); + return; + } + deps.onStatus(`${agent.name}: signing in, follow the browser if it opens...`); 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.`); - } + deps.onStatus(`${agent.name}: signed in.`); return deps.refresh(true); }) .catch((error: unknown) => deps.onStatus(errorText(error))); @@ -67,6 +81,21 @@ export function agentActions(agent: AgentView, deps: AgentSetupDeps): HTMLElemen self.textContent = 'Check'; }); }); + } else if (action === 'import') { + button('Import chats', `Bring the chats ${agent.name} already has for this folder into the list`, (self) => { + self.disabled = true; + self.textContent = 'Looking...'; + const reset = (): void => { + self.disabled = false; + self.textContent = 'Import chats'; + }; + deps.api.listImportable(agent.ref) + .then((found) => showImport(panel, agent, found, deps, reset)) + .catch((error: unknown) => { + reset(); + showError(panel, `Could not read ${agent.name}'s chats: ${errorText(error)}`); + }); + }); } 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) => { @@ -113,6 +142,63 @@ function showError(panel: HTMLElement, message: string): void { panel.replaceChildren(el('p', { className: 'af-install-error', text: message, attrs: { role: 'alert' } })); } +/** #298: the agent's earlier chats with a box each; the chosen ones are added to the list. */ +function showImport(panel: HTMLElement, agent: AgentView, found: readonly ImportableSession[], deps: AgentSetupDeps, reset: () => void): void { + const close = (): void => { + panel.hidden = true; + panel.replaceChildren(); + reset(); + }; + const cancel = el('button', { className: 'secondary-button af-small-button', text: found.length ? 'Cancel' : 'Close', attrs: { type: 'button' } }); + cancel.addEventListener('click', (event) => { + event.stopPropagation(); + close(); + }); + panel.hidden = false; + if (found.length === 0) { + panel.replaceChildren( + el('p', { className: 'muted af-install-note', text: `${agent.name} has no other chats for this folder.` }), + el('div', { className: 'af-install-actions' }, [cancel]), + ); + return; + } + const boxes = found.map((session) => { + const box = el('input', { attrs: { type: 'checkbox', checked: '', 'data-id': session.agentSessionId } }); + const when = importedWhen(session.updatedAt); + return { session, box, row: el('label', { className: 'af-import-row' }, [box, el('span', { className: 'af-import-title', text: session.title }), ...(when ? [el('span', { className: 'muted af-import-when', text: when })] : [])]) }; + }); + const go = el('button', { className: 'primary-button af-small-button', text: `Import ${found.length}`, attrs: { type: 'button', 'data-testid': 'af-import-confirm' } }); + const count = (): void => { + const chosen = boxes.filter((entry) => entry.box.checked).length; + go.textContent = `Import ${chosen}`; + go.disabled = chosen === 0; + }; + for (const entry of boxes) { + entry.box.addEventListener('change', count); + } + go.addEventListener('click', (event) => { + event.stopPropagation(); + go.disabled = true; + cancel.disabled = true; + const chosen = boxes.filter((entry) => entry.box.checked).map((entry) => entry.session); + deps.api.importSessions(agent.ref, chosen) + .then((added) => { + deps.onStatus(added === 1 ? `1 chat of ${agent.name} imported. Its messages load when you open it.` : `${added} chats of ${agent.name} imported. Their messages load when you open them.`); + close(); + }) + .catch((error: unknown) => { + reset(); + showError(panel, `Could not import: ${errorText(error)}`); + }); + }); + panel.replaceChildren( + el('p', { className: 'af-install-title', text: `${agent.name}: chats for this folder` }), + el('div', { className: 'af-import-list', attrs: { 'data-testid': 'af-import-list' } }, boxes.map((entry) => entry.row)), + el('p', { className: 'muted af-install-note', text: `${agent.name} reads them from its own history; they stay there too.` }), + el('div', { className: 'af-install-actions' }, [go, cancel]), + ); +} + 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 })])); diff --git a/apps/ide/src/renderer/agentFirst/agentSetupModel.ts b/apps/ide/src/renderer/agentFirst/agentSetupModel.ts index c3fd02bb..e0098f3a 100644 --- a/apps/ide/src/renderer/agentFirst/agentSetupModel.ts +++ b/apps/ide/src/renderer/agentFirst/agentSetupModel.ts @@ -5,9 +5,9 @@ import type { AgentView, InstallDescription, InstallProgress } from '../../share * (AF2, #267) and the first-run guide (AF13, #278). No DOM. */ -export type SetupAction = 'install' | 'update' | 'remove' | 'login' | 'check'; +export type SetupAction = 'install' | 'update' | 'remove' | 'login' | 'check' | 'import'; -/** What an agent row offers: install a missing preset; update or remove one the IDE installed; sign in and check. */ +/** What an agent row offers: install a missing preset; update or remove one the IDE installed; sign in and check; import its chats once ready. */ export function setupActions(agent: AgentView): SetupAction[] { if (agent.kind !== 'acp') { return []; @@ -20,6 +20,10 @@ export function setupActions(agent: AgentView): SetupAction[] { actions.push('login'); } actions.push('check'); + // #298: a signed-in agent can hand over the chats it already has for this folder. + if (agent.availability === 'ready') { + actions.push('import'); + } if (agent.preset && agent.installedVersion) { actions.push('update', 'remove'); } @@ -150,3 +154,20 @@ export function onboardingSteps(input: OnboardingInput): OnboardingStep[] { export function shouldShowOnboarding(onboarded: string | null, hasChat: boolean): boolean { return onboarded !== 'true' && !hasChat; } + +/** #298: "Today 14:05", "12 Nov", or "" when the agent gave no time. */ +export function importedWhen(updatedAt: string | null, now: Date = new Date()): string { + if (!updatedAt) { + return ''; + } + const at = new Date(updatedAt); + if (Number.isNaN(at.getTime())) { + return ''; + } + const sameDay = at.getFullYear() === now.getFullYear() && at.getMonth() === now.getMonth() && at.getDate() === now.getDate(); + if (sameDay) { + return `Today ${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`; + } + const month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][at.getMonth()] ?? ''; + return at.getFullYear() === now.getFullYear() ? `${at.getDate()} ${month}` : `${at.getDate()} ${month} ${at.getFullYear()}`; +} diff --git a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts index 971ad2b0..ce1eb207 100644 --- a/apps/ide/src/renderer/agentFirst/agentWorkbench.ts +++ b/apps/ide/src/renderer/agentFirst/agentWorkbench.ts @@ -1,4 +1,5 @@ import type { AgentSessionMessage, AgentSessionsApi, AgentSessionState, InstallProgress } from '../../shared/agentSession.ts'; +import type { TerminalCreated } from '../../shared/api.ts'; import type { AttachmentSources } from '../agents/chatAttachments.ts'; import type { CommandRegistry } from '../commands/commandRegistry.ts'; import type { CustomEditorInput } from '../editor/customEditor.ts'; @@ -47,7 +48,8 @@ export interface AgentWorkbenchOptions { onStatus(message: string): void; /** Opens a recent folder in this window (resolves once it is open). */ openProject(root: string): Promise; - showTerminal(): void; + /** #297: runs a sign-in program in a terminal of its own (`TerminalPanel.runTask`). */ + runInTerminal(label: string, start: (cols: number, rows: number) => Promise): Promise; /** Runs the XR analysis of the open folder (the dock's button). */ analyseProject(): void; /** Whether a folder is open in this window. */ @@ -275,7 +277,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork onStatus: options.onStatus, mode: () => mode, setMode, - showTerminal: options.showTerminal, + runInTerminal: options.runInTerminal, extraSections: [instructions.element], openBuiltinAgents: () => workbench.showView('agents'), onRemoved: (id) => tabClosers.get(id)?.(), @@ -361,7 +363,7 @@ export function installAgentWorkbench(options: AgentWorkbenchOptions): AgentWork setup: { api, onStatus: options.onStatus, - showTerminal: options.showTerminal, + runInTerminal: options.runInTerminal, refresh: (probe) => sessions.refreshAgents(probe), replace: () => void sessions.refreshAgents(false), }, diff --git a/apps/ide/src/renderer/agentFirst/sessionsView.ts b/apps/ide/src/renderer/agentFirst/sessionsView.ts index e02a851e..f0eb346a 100644 --- a/apps/ide/src/renderer/agentFirst/sessionsView.ts +++ b/apps/ide/src/renderer/agentFirst/sessionsView.ts @@ -1,4 +1,5 @@ import type { AgentSessionMessage, AgentSessionsApi, AgentView, ProjectSessions, SessionSummary } from '../../shared/agentSession.ts'; +import type { TerminalCreated } from '../../shared/api.ts'; import { el, icon } from '../dom.ts'; import { attentionCounts, availabilityLabel, defaultAgent, filterProjects, shortTime, statusLabel } from './sessionsModel.ts'; import { agentActions, type AgentSetupDeps } from './agentSetup.ts'; @@ -29,8 +30,8 @@ export interface SessionsViewDeps { 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; + /** #297: runs an agent's terminal sign-in in a terminal of its own. */ + runInTerminal?(label: string, start: (cols: number, rows: number) => Promise): Promise; /** Shows the Agents view, where the IDE's own agents chat (epic #189). */ openBuiltinAgents?(): void; /** A chat was deleted: its tab closes. */ @@ -190,7 +191,7 @@ export function createSessionsView(container: HTMLElement, deps: SessionsViewDep const setupDeps: AgentSetupDeps = { api: deps.api, onStatus: deps.onStatus, - ...(deps.showTerminal ? { showTerminal: deps.showTerminal } : {}), + ...(deps.runInTerminal ? { runInTerminal: deps.runInTerminal } : {}), refresh: (probe) => refreshAgents(probe), replace: (view) => { agents = agents.map((other) => (other.ref === view.ref ? view : other)); diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 7e57a94c..d5fe127d 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -1086,7 +1086,7 @@ const agentWorkbench = installAgentWorkbench({ openProject: async (folder) => { await api.workspace.openRecent(folder); }, - showTerminal: () => terminal.show(), + runInTerminal: (label, start) => terminal.runTask(label, start), analyseProject: () => { if (!runView.analyse('xr-deep')) { workbench.showView('analysis'); diff --git a/apps/ide/src/shared/agentSession.ts b/apps/ide/src/shared/agentSession.ts index 84375282..b4d29092 100644 --- a/apps/ide/src/shared/agentSession.ts +++ b/apps/ide/src/shared/agentSession.ts @@ -10,6 +10,8 @@ * extension (1.3.0) can reuse it as is. */ +import type { TerminalCreated } from './api.ts'; + // ---- Agents ---------------------------------------------------------------- /** The agents the IDE knows how to launch without any configuration (AF2). */ @@ -339,6 +341,19 @@ export interface AgentSessionState extends SessionSummary { 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; + /** + * #298: imported from the agent's own history and not read yet: the first + * `session/load` fills the transcript from the agent's replay. + */ + readonly historyPending?: boolean; +} + +/** #298: a chat the agent keeps in its own history (ACP `session/list`), offered for import. */ +export interface ImportableSession { + readonly agentSessionId: string; + readonly title: string; + /** ISO time of its last activity, when the agent says. */ + readonly updatedAt: string | null; } /** A project and its chats, for the sessions sidebar (AF7). */ @@ -387,6 +402,8 @@ export type SessionEvent = | { 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 } + /** #298: the imported history was read (false) or is still to read (true). */ + | { readonly type: 'history'; readonly pending: boolean } | { 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 } @@ -545,6 +562,10 @@ export function applySessionEvent(state: AgentSessionState, event: SessionEvent, return touch({ title: event.title }); case 'agent-session': return touch({ agentSessionId: event.agentSessionId }); + case 'history': { + const { historyPending: _dropped, ...rest } = state; + return event.pending ? { ...state, historyPending: true } : rest; + } case 'pending-changes': return touch({ pendingChanges: event.count }); case 'metric-delta': { @@ -641,6 +662,8 @@ export const AGENT_SESSION_CHANNELS = { worktreeCommit: 'codexr:agent-sessions:worktree-commit', worktreeMerge: 'codexr:agent-sessions:worktree-merge', worktreeDiscard: 'codexr:agent-sessions:worktree-discard', + listImportable: 'codexr:agent-sessions:list-importable', + importSessions: 'codexr:agent-sessions:import-sessions', describeInstall: 'codexr:agent-sessions:describe-install', install: 'codexr:agent-sessions:install', uninstall: 'codexr:agent-sessions:uninstall', @@ -652,9 +675,11 @@ export const AGENT_SESSION_EVENTS = { /** The integrated terminal a terminal login method runs in (see `AgentSessionsApi.login`). */ export interface LoginTerminal { - readonly terminalId: number; + /** #297: the terminal as the terminal API reports it, so the panel shows it like a task's. */ + readonly terminal: TerminalCreated; readonly title: string; - readonly cwd: string; + /** The program and arguments that run, shown at the top of the terminal (no secret is ever in them). */ + readonly command: string; } /** What `window.codexr.agentSessions` offers the renderer. */ @@ -668,12 +693,12 @@ export interface AgentSessionsApi { /** * 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`). + * method resolves as soon as the agent's login program runs, directly and + * with no shell, in a new integrated terminal of this window sized + * `cols` x `rows`; the window shows it through `TerminalPanel.runTask`. + * The agent is probed again when the program exits (`agents-changed`). */ - login(ref: string, methodId: string): Promise; + login(ref: string, methodId: string, cols?: number, rows?: number): Promise; /** Recent projects and their chats, the window's own folder first. */ listProjects(): Promise; get(sessionId: string): Promise; @@ -714,6 +739,14 @@ export interface AgentSessionsApi { 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; + /** + * #298: the chats the agent keeps in its own history for the open folder + * (ACP `session/list`), less the ones already in the IDE. The agent reads + * them itself; the IDE never opens the vendor's files. + */ + listImportable(ref: string): Promise; + /** #298: adds those chats to the list; each one's messages are read from the agent when it is first opened. Resolves with how many were added. */ + importSessions(ref: string, sessions: readonly ImportableSession[]): Promise; /** * AF2: reads from the npm registry what installing a preset's adapter * would download (the only network call, made because the person asked). diff --git a/apps/ide/test/agentLoginImport.test.ts b/apps/ide/test/agentLoginImport.test.ts new file mode 100644 index 00000000..54d20076 --- /dev/null +++ b/apps/ide/test/agentLoginImport.test.ts @@ -0,0 +1,265 @@ +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, type AgentContext } from '@agentclientprotocol/sdk'; +import { applySessionEvent, emptySession, type AgentSessionMessage } from '../src/shared/agentSession.ts'; +import { JsonKeyValueStore } from '../src/main/core/jsonStore.ts'; +import { AcpConnection } from '../src/main/agentSessions/acpConnection.ts'; +import { AgentCatalog, loginProgram } 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 { importedWhen, setupActions } from '../src/renderer/agentFirst/agentSetupModel.ts'; + +/** + * #297 (sign-in) and #298 (import of an agent's own chats), against an + * in-process ACP agent that answers `auth/status`, `session/list` and + * `session/load` the way Claude Code's and Codex's adapters do. + */ + +const base = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ide-agent-login-')); +after(() => fs.rmSync(base, { recursive: true, force: true })); + +interface FakeOptions { + signedIn: boolean | 'unknown'; + /** The agent's own history: sessions of this folder and of another one. */ + history: { readonly sessionId: string; cwd: string; readonly title?: string; readonly updatedAt?: string }[]; + pageSize?: number; +} + +interface FakeLog { + loads: string[]; + lists: number; + lastLoadCwd?: string; +} + +function historyAgent(options: FakeOptions, log: FakeLog) { + 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: 'history' }) + .onConnect((connection) => { + client = connection.client; + }) + .onRequest(methods.agent.initialize, () => ({ + protocolVersion: 1, + agentCapabilities: { + loadSession: true, + sessionCapabilities: { list: {} }, + ...(options.signedIn === 'unknown' ? {} : { auth: { status: {} } }), + } as never, + authMethods: [{ id: 'claude-ai-login', name: 'Claude Subscription', type: 'terminal', args: ['--cli', 'auth', 'login', '--claudeai'] }] as never, + })) + // A custom method for this SDK (an ACP draft): it needs a params parser. + .onRequest('auth/status', { parse: (params: unknown) => params }, () => (options.signedIn === true + ? { state: 'authenticated', accounts: [{ label: 'Claude Max', email: 'person@example.invalid', active: true }] } + : { state: 'unauthenticated' })) + .onRequest(methods.agent.session.new, () => ({ sessionId: 'fresh-1' })) + .onRequest(methods.agent.session.list, ({ params }) => { + log.lists += 1; + const size = options.pageSize ?? 100; + const start = params.cursor ? Number(params.cursor) : 0; + // An empty cwd stands for the folder asked about. + const page = options.history.slice(start, start + size).map((session) => ({ ...session, cwd: session.cwd || params.cwd || '' })); + const next = start + size < options.history.length ? String(start + size) : null; + return { sessions: page, nextCursor: next }; + }) + .onRequest(methods.agent.session.load, async ({ params }) => { + log.loads.push(params.sessionId); + log.lastLoadCwd = params.cwd; + const sid = params.sessionId; + // The replay: the person's message in two chunks, the answer, a second exchange. + await update(sid, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'Add a ' } }); + await update(sid, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'test' } }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Done, I added it.' } }); + await update(sid, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'Thanks' } }); + await update(sid, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'You are welcome.' } }); + await update(sid, { sessionUpdate: 'usage_update', used: 10, size: 100 }); + return {}; + }) + .onRequest(methods.agent.session.prompt, async ({ params }) => { + await update(params.sessionId, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Live answer' } }); + return { stopReason: 'end_turn' }; + }); +} + +async function setup(name: string, options: FakeOptions) { + const root = path.join(base, name, 'project'); + fs.mkdirSync(root, { recursive: true }); + 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: 'History', command: process.execPath, args: [] }); + const log: FakeLog = { loads: [], lists: 0 }; + const messages: AgentSessionMessage[] = []; + const window: WindowPort = { id: 1, send: (message) => messages.push(message), isDestroyed: () => false }; + const terminals: { command: string; args: readonly string[]; cols: number; rows: number; title: string; env: Readonly> }[] = []; + const store = new SessionStore(path.join(base, name, 'sessions'), { debounceMs: 5 }); + const service = new AgentSessionService({ + catalog, + store, + decisions: new JsonKeyValueStore(path.join(base, name, 'decisions.json')), + rootOf: () => root, + isTrusted: () => true, + readText: (file) => fs.promises.readFile(file, 'utf8'), + writeText: (file, content) => fs.promises.writeFile(file, content), + openTerminal: (_window, request) => { + terminals.push(request); + return Promise.resolve({ + terminal: { terminal: { id: 7, profile: { id: 'program', name: request.title, path: request.command, args: [...request.args], source: 'custom' }, cwd: request.cwd }, title: request.title, command: [request.command, ...request.args].join(' ') }, + exited: new Promise(() => undefined), + }); + }, + connect: (_launch, _cwd, handlers) => AcpConnection.inProcess(historyAgent(options, log), handlers), + beforePrompt: () => Promise.resolve({ checkpointId: 'cp-1' }), + spawnAllowed: true, + probeDir: path.join(base, name, 'probe'), + homeDir: os.homedir(), + terminalEnv: { PATH: process.env['PATH'] ?? '' }, + }); + return { root, service, window, messages, log, terminals, store, catalog, ref: `acp:${custom.id}` }; +} + +async function waitFor(check: () => boolean | Promise, what: string): Promise { + for (let i = 0; i < 300; i++) { + if (await check()) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`Timed out waiting for ${what}.`); +} + +describe('agent sign-in (#297)', () => { + it('runs the login program itself: the terminal-auth command, or the agent with the method\'s arguments', () => { + const launch = { command: '/ide/electron', args: ['/pkgs/adapter/dist/index.js'], env: { ELECTRON_RUN_AS_NODE: '1' } }; + assert.deepEqual(loginProgram(launch, { command: '/ide/electron', args: ['/pkgs/adapter/dist/index.js', '--cli', 'auth', 'login'] }), { command: '/ide/electron', args: ['/pkgs/adapter/dist/index.js', '--cli', 'auth', 'login'] }); + assert.deepEqual(loginProgram(launch, { args: ['--login'] }), { command: '/ide/electron', args: ['/pkgs/adapter/dist/index.js', '--login'] }); + assert.deepEqual(loginProgram(launch, {}), { command: '/ide/electron', args: ['/pkgs/adapter/dist/index.js'] }); + // A cmd.exe launch cannot be handed to a terminal unchanged. + assert.throws(() => loginProgram({ command: 'cmd.exe', args: ['/d', '/s', '/c', '"agent.cmd"'], env: {}, verbatimArguments: true }, { args: ['--login'] }), /yourself in a terminal/); + }); + + it('starts the terminal sign-in as a program, sized as the panel asked, with the agent\'s environment', async () => { + const { service, window, terminals, ref, root } = await setup('login-terminal', { signedIn: false, history: [] }); + await service.probeAgent(window, ref); + const opened = await service.login(window, ref, 'claude-ai-login', 120, 40); + assert.ok(opened); + assert.equal(opened.terminal.id, 7); + assert.equal(terminals.length, 1); + const [request] = terminals; + assert.equal(request?.command, process.execPath); + assert.deepEqual(request?.args, ['--cli', 'auth', 'login', '--claudeai']); + assert.equal(request?.cols, 120); + assert.equal(request?.rows, 40); + assert.equal((request as { cwd?: string } | undefined)?.cwd, root); + assert.equal(request?.title, 'History: Claude Subscription'); + // Silly sizes fall back to a sane terminal. + await service.login(window, ref, 'claude-ai-login', -3, 'x'); + assert.deepEqual([terminals[1]?.cols, terminals[1]?.rows], [100, 30]); + }); + + it('reports a signed-out agent as needing a login even though it opens sessions, and names the account once signed in', async () => { + const signedOut = await setup('status-out', { signedIn: false, history: [] }); + const out = await signedOut.service.probeAgent(signedOut.window, signedOut.ref); + assert.equal(out.availability, 'needs-login'); + assert.ok(out.authMethods?.some((method) => method.id === 'claude-ai-login')); + + const signedIn = await setup('status-in', { signedIn: true, history: [] }); + const ready = await signedIn.service.probeAgent(signedIn.window, signedIn.ref); + assert.equal(ready.availability, 'ready'); + assert.equal(ready.detail, 'Signed in as person@example.invalid.'); + + // An agent that cannot say is judged by session/new, as before. + const silent = await setup('status-unknown', { signedIn: 'unknown', history: [] }); + assert.equal((await silent.service.probeAgent(silent.window, silent.ref)).availability, 'ready'); + }); +}); + +describe('importing an agent\'s own chats (#298)', () => { + it('lists the folder\'s chats from the agent, across pages, newest first, without other folders\' ones', async () => { + const { service, window, ref, root, log } = await setup('import-list', { + signedIn: true, + pageSize: 2, + history: [ + { sessionId: 'old', cwd: '', title: 'Old chat\nwith lines', updatedAt: '2026-11-01T10:00:00Z' }, + { sessionId: 'new', cwd: '', title: 'Newest', updatedAt: '2026-11-26T10:00:00Z' }, + { sessionId: 'other', cwd: path.join(base, 'elsewhere'), title: 'Another project' }, + { sessionId: 'untitled', cwd: '' }, + ], + }); + const found = await service.listImportable(window, ref); + assert.ok(log.lists >= 2, 'it followed the cursor'); + assert.deepEqual(found.map((session) => session.agentSessionId), ['new', 'old', 'untitled']); + assert.equal(found[1]?.title, 'Old chat with lines'); + assert.equal(found[2]?.title, 'Imported chat'); + assert.equal(found[2]?.updatedAt, null); + assert.ok(root); + }); + + it('imports chosen chats once, then reads each one\'s messages from the agent when it is opened', async () => { + const history = [{ sessionId: 'claude-1', cwd: '', title: 'Add a test', updatedAt: '2026-11-20T09:30:00Z' }]; + const { service, window, ref, log, store, root } = await setup('import-run', { signedIn: true, history }); + const found = await service.listImportable(window, ref); + assert.equal(found.length, 1); + assert.equal(await service.importSessions(window, ref, found), 1); + // Twice is a no-op, and the list no longer offers it. + assert.equal(await service.importSessions(window, ref, found), 0); + assert.deepEqual(await service.listImportable(window, ref), []); + + const projects = await service.listProjects(window); + const summary = projects.find((project) => project.current)?.sessions[0]; + assert.ok(summary); + assert.equal(summary.title, 'Add a test'); + assert.equal(summary.updatedAt, '2026-11-20T09:30:00.000Z'); + + // Opening it loads the agent's session and keeps the replay as the transcript. + const first = await service.get(window, summary.id); + assert.equal(first.historyPending, true); + await waitFor(async () => (await service.get(window, summary.id)).historyPending !== true, 'the history to load'); + const state = await service.get(window, summary.id); + assert.deepEqual(log.loads, ['claude-1']); + assert.equal(log.lastLoadCwd, root); + assert.deepEqual(state.items.filter((item) => item.kind === 'user' || item.kind === 'assistant').map((item) => [item.kind, 'text' in item ? item.text : '']), [ + ['user', 'Add a test'], + ['assistant', 'Done, I added it.'], + ['user', 'Thanks'], + ['assistant', 'You are welcome.'], + ]); + assert.equal(state.agentSessionId, 'claude-1'); + + // The chat continues the same agent session, and the history is not read again. + await service.prompt(window, summary.id, 'go on', []); + await waitFor(async () => (await service.get(window, summary.id)).items.some((item) => item.kind === 'assistant' && 'text' in item && item.text === 'Live answer'), 'the live answer'); + assert.deepEqual(log.loads, ['claude-1']); + + // The flag is stored, and cleared once read. + await waitFor(async () => (await store.load(root, summary.id))?.historyPending === undefined, 'the store to settle'); + }); + + it('refuses bad input and folders the agent cannot list', async () => { + const { service, window, ref } = await setup('import-bad', { signedIn: true, history: [] }); + await assert.rejects(service.importSessions(window, ref, 'nope'), /at most/); + assert.equal(await service.importSessions(window, ref, [{ agentSessionId: '' }, { title: 'no id' }, 42]), 0); + await assert.rejects(service.listImportable(window, 'acp:nobody'), /Only an ACP agent/); + }); +}); + +describe('import and sign-in helpers (#297, #298)', () => { + it('offers Import once an agent is ready, and dates chats briefly', () => { + const view = { ref: 'acp:claude', name: 'Claude Code', kind: 'acp' as const, description: '', availability: 'ready' as const }; + assert.ok(setupActions(view).includes('import')); + assert.ok(!setupActions({ ...view, availability: 'needs-login' }).includes('import')); + const now = new Date(2026, 10, 27, 18, 0); + assert.equal(importedWhen(null, now), ''); + assert.equal(importedWhen('not a date', now), ''); + assert.equal(importedWhen(new Date(2026, 10, 27, 9, 5).toISOString(), now), 'Today 09:05'); + assert.equal(importedWhen(new Date(2026, 10, 12, 9, 5).toISOString(), now), '12 Nov'); + assert.equal(importedWhen(new Date(2025, 0, 3).toISOString(), now), '3 Jan 2025'); + }); + + it('sets and clears the pending-history flag in the shared reducer', () => { + const state = emptySession({ id: 's', title: 't', agentRef: 'acp:x', agentName: 'X', workspaceRoot: '/p', createdAt: 'a', updatedAt: 'a' }); + const pending = applySessionEvent(state, { type: 'history', pending: true }); + assert.equal(pending.historyPending, true); + assert.equal('historyPending' in applySessionEvent(pending, { type: 'history', pending: false }), false); + }); +}); diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index fed13da2..038f91c4 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -632,7 +632,7 @@ describe('AgentSessionService with a fake ACP agent', () => { 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.ok(notice?.kind === 'notice' && /needs you to sign in/i.test(notice.text)); assert.equal(state.status, 'error'); const agents = await service.listAgents(window); const fake = agents.find((view) => view.ref === ref); diff --git a/docs/ide/agent-first-test-guide.md b/docs/ide/agent-first-test-guide.md index cc7cc762..84e2fbdc 100644 --- a/docs/ide/agent-first-test-guide.md +++ b/docs/ide/agent-first-test-guide.md @@ -26,7 +26,7 @@ Everything here has unit tests and the IDE smoke test, run on Linux, Windows and |---|---|---|---| | 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. | +| 2.3 | #297 | Press **Check** on Claude Code while signed out, then a login button (for example **Claude Subscription**). | Check says **Needs login**, not Ready. The button opens a terminal tab named after the method that runs the sign-in itself: the browser opens, or it prints a link and waits for the code. When it ends, the agent is checked again and says **Ready, Signed in as ...**. The IDE never asks for your password or token. Codex (ChatGPT) and Gemini (Google) open the browser from the agent itself. | ## 3. A coding chat @@ -37,6 +37,7 @@ Everything here has unit tests and the IDE smoke test, run on Linux, Windows and | 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. | +| 3.6 | #298 | On a ready agent that you have already used in this project from its own CLI, press **Import chats**, keep the ticks and press **Import**. | Your earlier chats for this folder are listed with their dates; the chosen ones appear in the Chats list. Opening one shows its messages; sending a message continues it. Importing again does not duplicate them. | ## 4. Review, checkpoints, live analysis