Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions apps/ide/src/main/agentSessions/acpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {} },
},
}));
}
Expand All @@ -248,17 +250,18 @@ export class AcpConnection {
return this.explain(this.connection.agent.request(methods.agent.authenticate, { methodId }));
}

newSession(cwd: string, mcpServers: readonly McpServer[]): Promise<NewSessionResponse> {
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<string, unknown> | null): Promise<NewSessionResponse> {
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`). */
listSessions(cwd: string, cursor?: string): Promise<ListSessionsResponse> {
return this.explain(this.connection.agent.request(methods.agent.session.list, { cwd, ...(cursor ? { cursor } : {}) }));
}

loadSession(sessionId: string, cwd: string, mcpServers: readonly McpServer[]): Promise<LoadSessionResponse> {
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<string, unknown> | null): Promise<LoadSessionResponse> {
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<PromptResponse> {
Expand Down
45 changes: 43 additions & 2 deletions apps/ide/src/main/agentSessions/agentSessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ import {
parseCloudSessionRef,
parseRemoteControlReply,
remoteControlPrompt,
remoteControlSessionMeta,
type AutoRemoteControlMode,
resumeArgs,
teleportArgs,
type RemoteControlReply,
Expand Down Expand Up @@ -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<AutoRemoteControlMode>;
ask(window: WindowPort): Promise<boolean>;
remember(mode: 'always' | 'never'): Promise<void>;
};
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;
Expand Down Expand Up @@ -316,6 +329,8 @@ export class AgentSessionService {
private readonly now: () => string;
private sessionsChangedTimer: ReturnType<typeof setTimeout> | null = null;
private stopped = false;
/** #456: the one pending "continue Claude Code chats on claude.ai?" question. */
private remoteControlQuestion: Promise<boolean> | null = null;
private storageReal: string | null | undefined = undefined;

constructor(options: AgentSessionServiceOptions) {
Expand Down Expand Up @@ -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<boolean> {
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;
Expand Down Expand Up @@ -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))) {
Expand Down Expand Up @@ -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);
Expand All @@ -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)) {
Expand Down
34 changes: 33 additions & 1 deletion apps/ide/src/main/agentSessions/agentSessionsRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<AnalysisService, 'sceneMetrics' | 'turnMetricDelta'>;
/** #456: reads and stores the user's `agents.claude.remoteControl` setting. Absent (the smoke run), chats never start with it. */
readonly claudeRemoteControlSetting?: {
get(): Promise<unknown>;
set(mode: 'always' | 'never'): Promise<void>;
};
}

/** How long the metric delta waits for the scene to catch up with a turn's edits. */
Expand Down Expand Up @@ -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;
Expand Down
14 changes: 12 additions & 2 deletions apps/ide/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -129,7 +129,17 @@ async function start(): Promise<void> {
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 = [];
Expand Down
6 changes: 6 additions & 0 deletions apps/ide/src/shared/i18n/settings.es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const SETTING_CATEGORIES_ES: Readonly<Record<string, string>> = {
Run: 'Ejecutar',
Extensions: 'Extensiones',
Terminal: 'Terminal',
Agents: 'Agentes',
};

export const SETTINGS_ES: Readonly<Record<string, SettingText>> = {
Expand Down Expand Up @@ -112,6 +113,11 @@ export const SETTINGS_ES: Readonly<Record<string, SettingText>> = {
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).',
Expand Down
5 changes: 5 additions & 0 deletions apps/ide/src/shared/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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).
Expand Down
Loading
Loading