diff --git a/apps/ide/src/main/agentSessions/acpConnection.ts b/apps/ide/src/main/agentSessions/acpConnection.ts index 21678ae4..b9a547ad 100644 --- a/apps/ide/src/main/agentSessions/acpConnection.ts +++ b/apps/ide/src/main/agentSessions/acpConnection.ts @@ -222,6 +222,8 @@ export class AcpConnection { fs: { readTextFile: true, writeTextFile: true }, terminal: true, auth: { terminal: true }, + // #456: the agent's notices (such as Claude Code's "Remote Control connected") arrive as notices, not as reply text. + session: { notices: {} }, }, })); } @@ -248,8 +250,9 @@ export class AcpConnection { 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] })); + /** `meta` is the request's `_meta` (#456: Claude Code's per-session settings). */ + newSession(cwd: string, mcpServers: readonly McpServer[], meta?: Record | null): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.new, { cwd, mcpServers: [...mcpServers], ...(meta ? { _meta: meta } : {}) })); } /** #298: one page of the agent's own history for `cwd` (ACP `session/list`). */ @@ -257,8 +260,8 @@ export class AcpConnection { 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] })); + loadSession(sessionId: string, cwd: string, mcpServers: readonly McpServer[], meta?: Record | null): Promise { + return this.explain(this.connection.agent.request(methods.agent.session.load, { sessionId, cwd, mcpServers: [...mcpServers], ...(meta ? { _meta: meta } : {}) })); } prompt(sessionId: string, prompt: readonly ContentBlock[]): Promise { diff --git a/apps/ide/src/main/agentSessions/agentSessionService.ts b/apps/ide/src/main/agentSessions/agentSessionService.ts index 4fba2de5..c004b491 100644 --- a/apps/ide/src/main/agentSessions/agentSessionService.ts +++ b/apps/ide/src/main/agentSessions/agentSessionService.ts @@ -71,6 +71,8 @@ import { parseCloudSessionRef, parseRemoteControlReply, remoteControlPrompt, + remoteControlSessionMeta, + type AutoRemoteControlMode, resumeArgs, teleportArgs, type RemoteControlReply, @@ -155,6 +157,17 @@ export interface AgentSessionServiceOptions { * live trace sources) and opens a chat on the table. Absent, "Watch in XR" * refuses. */ + /** + * #456: whether Claude Code chats start with Remote Control (the + * `agents.claude.remoteControl` setting). `ask` is answered once, on the + * first Claude Code chat, and the answer is remembered. Absent, chats + * start without it. + */ + readonly claudeRemoteControl?: { + mode(): Promise; + ask(window: WindowPort): Promise; + remember(mode: 'always' | 'never'): Promise; + }; readonly agentFlow?: { onEvent(info: { readonly state: AgentSessionState; readonly root: string; readonly workRoot: string }, event: SessionEvent): void; watch(info: { readonly state: AgentSessionState; readonly root: string; readonly workRoot: string }): number; @@ -316,6 +329,8 @@ export class AgentSessionService { private readonly now: () => string; private sessionsChangedTimer: ReturnType | null = null; private stopped = false; + /** #456: the one pending "continue Claude Code chats on claude.ai?" question. */ + private remoteControlQuestion: Promise | null = null; private storageReal: string | null | undefined = undefined; constructor(options: AgentSessionServiceOptions) { @@ -917,6 +932,30 @@ export class AgentSessionService { this.emit(live, { type: 'remote-control', remote: next }); } + /** + * #456: whether this chat's agent starts with Remote Control. Only Claude + * Code chats, only with the person's consent: `always`, or `ask` answered + * yes once (concurrent chats share the one question). + */ + private async startsWithRemoteControl(preset: string | undefined, window: WindowPort): Promise { + const policy = this.options.claudeRemoteControl; + if (!policy || preset !== 'claude') { + return false; + } + const mode = await policy.mode(); + if (mode !== 'ask') { + return mode === 'always'; + } + this.remoteControlQuestion ??= (async () => { + const yes = await policy.ask(window); + await policy.remember(yes ? 'always' : 'never'); + return yes; + })().finally(() => { + this.remoteControlQuestion = null; + }); + return this.remoteControlQuestion.catch(() => false); + } + /** #431: the agent ended, and its Remote Control with it. */ private endRemoteControl(live: Live): void { const current = live.state.remoteControl; @@ -1596,6 +1635,8 @@ export class AgentSessionService { if (!resolution.found) { throw new Error(resolution.detail); } + // #456: asked (once) before the agent starts, so the answer never races the start timeout. + const sessionMeta = remoteControlSessionMeta(await this.startsWithRemoteControl(definition.preset, window)); // 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))) { @@ -1634,7 +1675,7 @@ export class AgentSessionService { 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.'); + const loaded = await withTimeout(connection.loadSession(previous, workRoot, mcpServers, sessionMeta), timeout, 'The agent did not reopen the chat in time.'); sessionId = previous; if (importing) { this.flushImportedUser(live); @@ -1655,7 +1696,7 @@ export class AgentSessionService { } } if (!sessionId) { - const created = await withTimeout(connection.newSession(workRoot, mcpServers), timeout, 'The agent did not open a session in time.'); + const created = await withTimeout(connection.newSession(workRoot, mcpServers, sessionMeta), 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)) { diff --git a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts index 0ae29e1f..e8518003 100644 --- a/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts +++ b/apps/ide/src/main/agentSessions/agentSessionsRuntime.ts @@ -11,7 +11,7 @@ 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 { REMOTE_CONTROL_CONSENT, TELEPORT_HINT } from '@codexr/core/claude-sessions/claudeSessionContinuity'; +import { AUTO_REMOTE_CONTROL_CONSENT, AUTO_REMOTE_CONTROL_QUESTION, REMOTE_CONTROL_CONSENT, TELEPORT_HINT, isAutoRemoteControlMode } from '@codexr/core/claude-sessions/claudeSessionContinuity'; import { KeyVault } from '../agents/keyVault.ts'; import { electronCipher } from '../agents/electronCipher.ts'; import { AgentInstaller, consentDetail } from './agentInstaller.ts'; @@ -85,6 +85,11 @@ export interface AgentSessionsRuntimeOptions { readonly analysisOutput?: (contents: WebContents) => string | null; /** AF9: the window's live analysis, measured before and after each turn. */ readonly analysis?: Pick; + /** #456: reads and stores the user's `agents.claude.remoteControl` setting. Absent (the smoke run), chats never start with it. */ + readonly claudeRemoteControlSetting?: { + get(): Promise; + set(mode: 'always' | 'never'): Promise; + }; } /** How long the metric delta waits for the scene to catch up with a turn's edits. */ @@ -189,6 +194,33 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS ...(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')), + ...(options.claudeRemoteControlSetting ? { + claudeRemoteControl: { + mode: async () => { + const value = await options.claudeRemoteControlSetting?.get(); + return isAutoRemoteControlMode(value) ? value : 'ask'; + }, + // #456: one native question, on the first Claude Code chat; the answer becomes the setting. + ask: async (port: WindowPort) => { + const contents = contentsOf(port); + if (!contents) { + return false; + } + const response = await ask(contents, { + type: 'question', + title: 'Claude Code on claude.ai', + message: AUTO_REMOTE_CONTROL_QUESTION, + detail: `${AUTO_REMOTE_CONTROL_CONSENT}\n\nSettings > Agents > Continue Claude Code Chats On claude.ai.`, + buttons: ['Yes, every chat', 'No'], + defaultId: 0, + cancelId: 1, + noLink: true, + }); + return response === 0; + }, + remember: (mode: 'always' | 'never') => options.claudeRemoteControlSetting?.set(mode) ?? Promise.resolve(), + }, + } : {}), rootOf: (port) => { const contents = contentsOf(port); return contents ? (currentWorkspaceInfo(contents)?.root ?? null) : null; diff --git a/apps/ide/src/main/index.ts b/apps/ide/src/main/index.ts index 67f9f7b9..fb6dc0b2 100644 --- a/apps/ide/src/main/index.ts +++ b/apps/ide/src/main/index.ts @@ -12,7 +12,7 @@ import { KeybindingsService } from './settings/keybindingsService.ts'; import { KEYBINDINGS_FILE_NAME } from '../shared/keybindings.ts'; import { applyColorTheme } from './settings/theme.ts'; import { OutputService } from './outputPanel/outputService.ts'; -import { COLOR_THEME_SETTING, formatSettingsFile } from '../shared/settings.ts'; +import { CLAUDE_REMOTE_CONTROL_SETTING, COLOR_THEME_SETTING, formatSettingsFile } from '../shared/settings.ts'; import { startCore, type CoreServices } from './core/coreRuntime.ts'; import { installApplicationMenu, setAboutDependencies } from './menu.ts'; import { checkForUpdates } from './updates/updateCheck.ts'; @@ -129,7 +129,17 @@ async function start(): Promise { 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 }); + agentSessions = startAgentSessions({ isSmoke, terminal: terminalHost, profiles: agentServices.profiles, analysisOutput: (contents) => core.analysis.outputDirectory(contents), analysis: core.analysis, + // #456: Claude Code chats on claude.ai, from the user's settings (the smoke run never asks). + ...(isSmoke ? {} : { + claudeRemoteControlSetting: { + get: async () => (await settings.snapshot(null)).effective[CLAUDE_REMOTE_CONTROL_SETTING], + set: async (mode: 'always' | 'never') => { + await settings.update(null, 'user', CLAUDE_REMOTE_CONTROL_SETTING, mode); + }, + }, + }), + }); // #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 = []; diff --git a/apps/ide/src/shared/i18n/settings.es.ts b/apps/ide/src/shared/i18n/settings.es.ts index 7377384f..28a05263 100644 --- a/apps/ide/src/shared/i18n/settings.es.ts +++ b/apps/ide/src/shared/i18n/settings.es.ts @@ -19,6 +19,7 @@ export const SETTING_CATEGORIES_ES: Readonly> = { Run: 'Ejecutar', Extensions: 'Extensiones', Terminal: 'Terminal', + Agents: 'Agentes', }; export const SETTINGS_ES: Readonly> = { @@ -112,6 +113,11 @@ export const SETTINGS_ES: Readonly> = { title: 'Buscar actualizaciones al iniciar', description: 'Al iniciar, el IDE pregunta a GitHub si se ha publicado una versión más reciente de Code-XR IDE y ofrece su página. Desactivado de forma predeterminada: es una llamada de red. Ayuda > Buscar actualizaciones... pregunta una vez, diga lo que diga este ajuste.', }, + 'agents.claude.remoteControl': { + title: 'Continuar los chats de Claude Code en claude.ai', + description: 'Inicia cada chat de Claude Code con Remote Control, para seguirlo desde claude.ai/code o la app móvil de Claude sin pulsar nada. Preguntar (lo predeterminado) pregunta una vez, en el primer chat de Claude Code. El código sigue ejecutándose en este equipo; los mensajes pasan por los servidores de Anthropic. Necesita iniciar sesión con claude.ai. Dejar de compartir en un chat lo termina para ese chat.', + optionLabels: ['Preguntar una vez', 'Siempre', 'Nunca'], + }, 'git.blame.inline': { title: 'Blame en línea', description: 'Al final de la línea del cursor, muestra quién la cambió por última vez, cuándo y el resumen del commit (de git blame sobre el texto del editor).', diff --git a/apps/ide/src/shared/settings.ts b/apps/ide/src/shared/settings.ts index e0d4cfda..68d1bddd 100644 --- a/apps/ide/src/shared/settings.ts +++ b/apps/ide/src/shared/settings.ts @@ -34,6 +34,9 @@ export type SettingValue = boolean | number | string; const MONO = "ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace"; /** #171: the colour theme. `system` follows the OS, live. */ +/** #456: whether Claude Code chats start on claude.ai (Remote Control). */ +export const CLAUDE_REMOTE_CONTROL_SETTING = 'agents.claude.remoteControl'; + export const COLOR_THEME_SETTING = 'workbench.colorTheme'; export const COLOR_THEMES = ['system', 'dark', 'light'] as const; export type ColorTheme = (typeof COLOR_THEMES)[number]; @@ -86,6 +89,8 @@ export const SETTINGS: readonly SettingDefinition[] = [ { key: 'problems.metrics.maxFunctionLines', category: 'Problems', title: 'Max Function Lines', description: 'A function with more lines of code (NLOC) than this is a warning in the Problems panel. 0 turns the check off.', type: 'number', min: 0, max: 100000, integer: true, default: 50 }, { key: 'problems.metrics.maxParameters', category: 'Problems', title: 'Max Parameters', description: 'A function that takes more parameters than this is a warning in the Problems panel. 0 turns the check off.', type: 'number', min: 0, max: 1000, integer: true, default: 5 }, { key: 'update.checkOnStartup', category: 'Application', title: 'Check For Updates On Start-up', description: 'When the IDE starts, ask GitHub whether a newer Code-XR IDE was released, and offer its page. Off by default: it is a network call. Help > Check for Updates… asks once, whatever this says.', type: 'boolean', default: false, userOnly: true }, + // #456: Claude Code chats on claude.ai (Remote Control at start). Asked once when it is `ask`. + { key: CLAUDE_REMOTE_CONTROL_SETTING, category: 'Agents', title: 'Continue Claude Code Chats On claude.ai', description: 'Start every Claude Code chat with Remote Control, so you can continue it from claude.ai/code or the Claude mobile app without pressing anything. Ask (the default) asks once, on the first Claude Code chat. The code keeps running on this computer; messages go through Anthropic\'s servers. Needs a claude.ai sign-in. Stop sharing in a chat ends it for that chat.', type: 'enum', options: ['ask', 'always', 'never'], optionLabels: ['Ask once', 'Always', 'Never'], default: 'ask', userOnly: true }, // #175: Git in the editor. { key: 'git.blame.inline', category: 'Git', title: 'Inline Blame', description: 'At the end of the cursor line, show who last changed it, when, and the commit\'s summary (from git blame on the editor\'s text).', type: 'boolean', default: true }, // #176: Run Current File. Empty means the usual name on PATH (python3, or python on Windows; node). diff --git a/apps/ide/test/agentSessions.test.ts b/apps/ide/test/agentSessions.test.ts index b66d7967..de3b6c46 100644 --- a/apps/ide/test/agentSessions.test.ts +++ b/apps/ide/test/agentSessions.test.ts @@ -9,7 +9,7 @@ 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 { AgentSessionService, type AgentSessionServiceOptions, type WindowPort } from '../src/main/agentSessions/agentSessionService.ts'; import { keepTail, loginCommandLine } from '../src/main/agentSessions/agentTerminals.ts'; import { SessionStore, projectKey } from '../src/main/agentSessions/sessionStore.ts'; import { SessionChanges } from '../src/main/checkpoints/sessionChanges.ts'; @@ -281,6 +281,9 @@ interface FakeAgentLog { permissionOutcome?: unknown; cancelled: number; prompts: unknown[]; + /** #456: the `_meta` of each session/new, and the client capabilities of initialize. */ + newSessionMeta?: unknown[]; + clientCapabilities?: unknown; } /** A tiny ACP agent: its behaviour is chosen by the prompt's first word. */ @@ -291,16 +294,29 @@ function fakeAgent(log: FakeAgentLog) { .onConnect((connection) => { client = connection.client; }) - .onRequest(methods.agent.initialize, () => ({ + .onRequest(methods.agent.initialize, ({ params }) => { + log.clientCapabilities = params.clientCapabilities; + return { protocolVersion: 1, agentCapabilities: { loadSession: false, promptCapabilities: { embeddedContext: true } }, authMethods: [{ id: 'login', name: 'Log in', type: 'terminal', args: ['--login'] }], - })) - .onRequest(methods.agent.session.new, () => ({ + } as never; + }) + .onRequest(methods.agent.session.new, ({ params }) => { + (log.newSessionMeta ??= []).push(params._meta ?? null); + // #456: as Claude Code's adapter when its settings start Remote Control with the session. + const settings = (params._meta as { claudeCode?: { options?: { settings?: Record } } } | undefined)?.claudeCode?.options?.settings; + if (settings?.['remoteControlAtStartup'] === true) { + setTimeout(() => { + void update('agent-1', { sessionUpdate: 'notice', severity: 'info', title: 'Remote Control connected', description: 'Continue this session from claude.ai/code or the Claude mobile app: https://claude.ai/code/session_01AutoFake42\nRun /remote-control off to disconnect.' }); + }, 5); + } + return { 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' }] }], - })) + } as never; + }) .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' }] }], @@ -383,13 +399,21 @@ function fakeAgent(log: FakeAgentLog) { }); } -async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges } = {}) { +async function setup(name: string, options: { trusted?: boolean; afterTurn?: () => Promise; changes?: SessionChanges; claude?: boolean; claudeRemoteControl?: AgentSessionServiceOptions['claudeRemoteControl'] } = {}) { 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: [] }); + if (options.claude) { + // #456: the fake agent stands in for the Claude Code preset. + const definition = catalog.definition.bind(catalog); + catalog.definition = ((agentRef: string) => { + const found = definition(agentRef); + return found ? { ...found, preset: 'claude' } : found; + }) as typeof catalog.definition; + } const log: FakeAgentLog = { cancelled: 0, prompts: [] }; const messages: AgentSessionMessage[] = []; const window: WindowPort = { id: 1, send: (message) => messages.push(message), isDestroyed: () => false }; @@ -420,6 +444,7 @@ async function setup(name: string, options: { trusted?: boolean; afterTurn?: () homeDir: os.homedir(), terminalEnv: { PATH: process.env['PATH'] ?? '' }, cancelGraceMs: 2000, + ...(options.claudeRemoteControl ? { claudeRemoteControl: options.claudeRemoteControl } : {}), }); return { root, service, window, messages, log, written, ref: `acp:${custom.id}` }; } @@ -740,6 +765,53 @@ describe('One Claude Code session everywhere (#431)', () => { await service.stopAll(); }); + it('#456: asks once, then starts every Claude Code chat on claude.ai and shows its link without a press', async () => { + let mode: 'ask' | 'always' | 'never' = 'ask'; + let asked = 0; + const policy = { + mode: () => Promise.resolve(mode), + ask: () => { + asked += 1; + return new Promise((resolve) => setTimeout(() => resolve(true), 5)); + }, + remember: (next: 'always' | 'never') => { + mode = next; + return Promise.resolve(); + }, + }; + const { service, window, ref, log, messages } = await setup('remote-auto', { claude: true, claudeRemoteControl: policy }); + assert.deepEqual((log.clientCapabilities as { session?: unknown } | undefined)?.session, undefined, 'nothing started yet'); + const first = await service.create(window, ref); + const second = await service.create(window, ref); + await Promise.all([service.prompt(window, first.id, 'hello', []), service.prompt(window, second.id, 'hello', [])]); + assert.equal(asked, 1, 'two chats at once: one question'); + assert.equal(mode, 'always', 'the answer is remembered'); + assert.deepEqual((log.clientCapabilities as { session?: unknown }).session, { notices: {} }); + assert.deepEqual(log.newSessionMeta, [ + { claudeCode: { options: { settings: { remoteControlAtStartup: true } } } }, + { claudeCode: { options: { settings: { remoteControlAtStartup: true } } } }, + ]); + await waitFor(() => messages.some((message) => message.kind === 'event' && message.sessionId === first.id && message.event.type === 'remote-control' && message.event.remote.active), 'the connected notice'); + const state = await service.get(window, first.id); + assert.equal(state.remoteControl?.url, 'https://claude.ai/code/session_01AutoFake42'); + await service.stopAll(); + }); + + it('#456: never starts on claude.ai for "never", nor for an agent that is not Claude Code', async () => { + const never = { mode: () => Promise.resolve('never' as const), ask: () => Promise.reject(new Error('never asks')), remember: () => Promise.reject(new Error('never stores')) }; + const a = await setup('remote-never', { claude: true, claudeRemoteControl: never }); + const chat = await a.service.create(a.window, a.ref); + await a.service.prompt(a.window, chat.id, 'hello', []); + assert.deepEqual(a.log.newSessionMeta, [null]); + await a.service.stopAll(); + const always = { mode: () => Promise.resolve('always' as const), ask: () => Promise.reject(new Error('never asks')), remember: () => Promise.resolve() }; + const b = await setup('remote-other-agent', { claudeRemoteControl: always }); + const other = await b.service.create(b.window, b.ref); + await b.service.prompt(b.window, other.id, 'hello', []); + assert.deepEqual(b.log.newSessionMeta, [null]); + await b.service.stopAll(); + }); + it('shows a message typed on claude.ai as the chat\'s own, marked remote, without starting a local turn', async () => { const { service, window, ref, messages } = await setup('remote-user'); const created = await service.create(window, ref); diff --git a/apps/vscode-extension/src/core/claude-sessions/claudeSessionContinuity.ts b/apps/vscode-extension/src/core/claude-sessions/claudeSessionContinuity.ts index e491c6ac..0ed797a3 100644 --- a/apps/vscode-extension/src/core/claude-sessions/claudeSessionContinuity.ts +++ b/apps/vscode-extension/src/core/claude-sessions/claudeSessionContinuity.ts @@ -122,3 +122,75 @@ export const REMOTE_CONTROL_CONSENT = export const TELEPORT_HINT = 'Claude Code copies the claude.ai/code session into this folder (its conversation and its branch). It needs the same repository, a clean git tree and the branch pushed. ' + 'When it is done, quit Claude Code in the terminal; the chat is then in this folder\'s Claude Code history.'; + +// ---- #456: automatic continuity (Remote Control at startup) ----------------- + +/** How a host treats Remote Control for its Claude Code chats: ask once, always on, or never. */ +export const AUTO_REMOTE_CONTROL_MODES = ['ask', 'always', 'never'] as const; +export type AutoRemoteControlMode = (typeof AUTO_REMOTE_CONTROL_MODES)[number]; + +export function isAutoRemoteControlMode(value: unknown): value is AutoRemoteControlMode { + return typeof value === 'string' && (AUTO_REMOTE_CONTROL_MODES as readonly string[]).includes(value); +} + +/** Claude Code's own setting: start Remote Control with every session. */ +export const REMOTE_CONTROL_AT_STARTUP = 'remoteControlAtStartup'; + +/** + * The ACP `_meta` that makes Claude Code's adapter start Remote Control with + * this session only (`session/new` and `session/load`), as the setting would + * for all of them. The adapter then sends a `Remote Control connected` notice + * with the claude.ai link. Null when Remote Control is not wanted. + */ +export function remoteControlSessionMeta(on: boolean): { claudeCode: { options: { settings: Record } } } | null { + return on ? { claudeCode: { options: { settings: { [REMOTE_CONTROL_AT_STARTUP]: true } } } } : null; +} + +/** The one-time question a host asks before it shares chats automatically. */ +export const AUTO_REMOTE_CONTROL_QUESTION = 'Continue your Claude Code chats on claude.ai automatically?'; + +export const AUTO_REMOTE_CONTROL_CONSENT = + 'Every Claude Code chat will start with Remote Control, so you can open it from claude.ai/code or the Claude mobile app, signed in with the same Claude account, without pressing anything. ' + + 'The code keeps running on this computer; messages and tool results travel through Anthropic\'s servers. It needs a claude.ai sign-in (Pro, Max, Team or Enterprise), not an API key. ' + + 'You can change it at any time in the settings, and stop sharing any single chat.'; + +/** + * #456: Claude Code's `settings.json` with `remoteControlAtStartup` set (`on`) + * or removed, every other key kept. `text` is the file's content, or null when + * it does not exist. Throws on a file that is not a JSON object, so a host + * never overwrites settings it could not read. + */ +export function withRemoteControlAtStartup(text: string | null, on: boolean): string { + let settings: Record = {}; + if (text !== null && text.trim() !== '') { + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new Error('Claude Code\'s settings.json is not valid JSON; fix it first.'); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('Claude Code\'s settings.json is not a JSON object; fix it first.'); + } + settings = { ...(parsed as Record) }; + } + if (on) { + settings[REMOTE_CONTROL_AT_STARTUP] = true; + } else { + delete settings[REMOTE_CONTROL_AT_STARTUP]; + } + return `${JSON.stringify(settings, null, 2)}\n`; +} + +/** Whether Claude Code's `settings.json` text turns Remote Control on for every session. */ +export function remoteControlAtStartupIn(text: string | null): boolean { + if (!text) { + return false; + } + try { + const parsed: unknown = JSON.parse(text); + return !!parsed && typeof parsed === 'object' && (parsed as Record)[REMOTE_CONTROL_AT_STARTUP] === true; + } catch { + return false; + } +} diff --git a/apps/vscode-extension/test/analysis/claudeSessionContinuity.test.cjs b/apps/vscode-extension/test/analysis/claudeSessionContinuity.test.cjs index ef3b67e8..4c75a222 100644 --- a/apps/vscode-extension/test/analysis/claudeSessionContinuity.test.cjs +++ b/apps/vscode-extension/test/analysis/claudeSessionContinuity.test.cjs @@ -54,3 +54,19 @@ test('CLI arguments are validated', () => { assert.throws(() => resumeArgs('x; y')); assert.equal(commandLine(resumeArgs(UUID, { remoteControl: true })), `claude --resume ${UUID} --remote-control`); }); + +test('#456: automatic Remote Control (session _meta and Claude Code settings.json)', () => { + const core = require(path.join(projectRoot, 'out', 'core', 'claude-sessions', 'claudeSessionContinuity.js')); + assert.deepEqual(core.remoteControlSessionMeta(true), { claudeCode: { options: { settings: { remoteControlAtStartup: true } } } }); + assert.equal(core.remoteControlSessionMeta(false), null); + assert.ok(core.isAutoRemoteControlMode('ask') && core.isAutoRemoteControlMode('always') && !core.isAutoRemoteControlMode('yes')); + const before = '{\n "model": "opus",\n "permissions": { "allow": ["Bash(ls)"] }\n}\n'; + const on = core.withRemoteControlAtStartup(before, true); + assert.deepEqual(JSON.parse(on), { model: 'opus', permissions: { allow: ['Bash(ls)'] }, remoteControlAtStartup: true }); + assert.ok(core.remoteControlAtStartupIn(on)); + assert.deepEqual(JSON.parse(core.withRemoteControlAtStartup(on, false)), { model: 'opus', permissions: { allow: ['Bash(ls)'] } }); + assert.deepEqual(JSON.parse(core.withRemoteControlAtStartup(null, true)), { remoteControlAtStartup: true }); + assert.throws(() => core.withRemoteControlAtStartup('{ nope', true), /not valid JSON/); + assert.throws(() => core.withRemoteControlAtStartup('[1]', true), /not a JSON object/); + assert.equal(core.remoteControlAtStartupIn('{ nope'), false); +}); diff --git a/docs/agents/claude-session-continuity.md b/docs/agents/claude-session-continuity.md index b661f443..aa9b6a0b 100644 --- a/docs/agents/claude-session-continuity.md +++ b/docs/agents/claude-session-continuity.md @@ -35,6 +35,15 @@ So no fallback is needed in the IDE. The fallback that remains for hosts that do The shared rules (prompts, reply parsing, id validation, CLI arguments, consent text) are in `apps/vscode-extension/src/core/claude-sessions/claudeSessionContinuity.ts`; each host only adds its UI. +## Automatic continuity (#456) + +Sharing chat by chat is still there, but the default way is that every Claude Code chat is on claude.ai without pressing anything. Claude Code already has the switch: `remoteControlAtStartup` in its user `settings.json` starts Remote Control with every session, and the ACP adapter honours it for a single session too when the client passes `_meta.claudeCode.options.settings.remoteControlAtStartup: true` on `session/new` or `session/load`. The adapter then sends a `Remote Control connected` notice with the claude.ai link, which `parseRemoteControlReply` already reads. + +- **VS Code extension**: AI Agents > **Continue sessions on claude.ai automatically** (On/Off). Turning it on asks once, then writes `remoteControlAtStartup: true` into Claude Code's own `settings.json` (`$CLAUDE_CONFIG_DIR` or `~/.claude`), keeping every other key; turning it off removes the key. The extension keeps no setting of its own: Claude Code's file is the single source of truth, so the switch covers the terminal, Claude Desktop and the IDE as well. +- **Code-XR IDE**: setting `agents.claude.remoteControl` (`ask`, `always`, `never`; default `ask`). On the first Claude Code chat with `ask`, a native dialog asks once and stores `always` or `never`. With `always`, every Claude Code chat (new or reopened) starts with Remote Control through the session `_meta`, and shows the **On claude.ai** badge with the link as soon as it connects. **Stop sharing** still ends it for one chat. + +The shared helpers (`remoteControlSessionMeta`, `withRemoteControlAtStartup`, `remoteControlAtStartupIn`, the consent text) live in the same core module. + ## Requirements and limits - A claude.ai sign-in (Pro, Max, Team or Enterprise). API keys, Bedrock, Vertex, Foundry and a custom `ANTHROPIC_BASE_URL` do not support Remote Control or teleport. Team and Enterprise need an owner to allow Remote Control; ZDR and HIPAA organizations cannot use it. `disableRemoteControl` turns it off. @@ -63,3 +72,8 @@ VS Code extension: 1. AI Agents > **Import a chat from claude.ai**: paste the link, confirm; the terminal runs `claude --teleport ...`. 2. Right-click a Claude Code session row > **Continue on claude.ai (Remote Control)**: confirm; the terminal runs `claude --resume --remote-control` and prints the claude.ai link. 3. Right-click > **Continue in the Terminal** resumes it. + +Automatic continuity (#456): + +1. VS Code extension: AI Agents > **Continue sessions on claude.ai automatically**: confirm. The row shows On and `~/.claude/settings.json` has `"remoteControlAtStartup": true`. Run `claude` in a terminal: it prints the claude.ai link without any flag. Press the row again: Off, and the key is gone. +2. IDE: with the setting on `ask`, open a new Claude Code chat: the dialog asks once. Answer Yes: the chat shows **On claude.ai** with the link after the first connection, without pressing Share. Open another chat: no question, also shared. Set the setting to `never`: new chats are not shared.