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
201 changes: 201 additions & 0 deletions apps/ide/src/main/agentSessions/agentSessionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
type ImportableSession,
type InstallDescription,
type LoginTerminal,
type RemoteControlView,
type PermissionOptionView,
type ProjectSessions,
type PromptAttachment,
Expand Down Expand Up @@ -63,6 +64,17 @@ import {
type ResolvedAttachment,
} from './acpMapping.ts';
import { loginProgram, consoleLoginProgram, nativeLoginProgram, type AgentCatalog } from './agentCatalog.ts';
import {
commandLine,
isRemoteControlPrompt,
offersRemoteControl,
parseCloudSessionRef,
parseRemoteControlReply,
remoteControlPrompt,
resumeArgs,
teleportArgs,
type RemoteControlReply,
} from '@codexr/core/claude-sessions/claudeSessionContinuity';
import { parsePresetId, type AgentInstaller } from './agentInstaller.ts';
import { AgentTerminals } from './agentTerminals.ts';
import { isSessionId, type SessionStore } from './sessionStore.ts';
Expand Down Expand Up @@ -215,6 +227,8 @@ interface Live {
replaying: boolean;
/** #298: the person's messages of an imported history arrive in chunks; they are joined here. */
importedUser: string | null;
/** #431: a message typed on claude.ai (Remote Control) arrives in chunks too. */
remoteUser: string | null;
configRaw: readonly SessionConfigOption[];
readonly permissions: Map<string, PendingPermission>;
readonly terminalBuffer: Map<string, { output: string; exitCode?: number | null; truncated: boolean }>;
Expand Down Expand Up @@ -753,6 +767,173 @@ export class AgentSessionService {
return added;
}

/**
* #431: shares the chat with claude.ai/code and the Claude mobile app, or
* stops sharing it. Claude Code's ACP adapter serves `/remote-control`
* itself and answers without a model turn; the answer (and the link) is
* read by `trackRemoteControl`. Turning it on asks first: it is the only
* step of a chat that reaches the network on the person's behalf.
*/
async setRemoteControl(window: WindowPort, sessionId: unknown, on: unknown, confirm: () => Promise<boolean>): Promise<RemoteControlView | false> {
this.remember(window);
const live = await this.open(window, sessionId);
this.assertContinuable(live, window);
if (!live.state.remoteControl?.available) {
throw new Error(`${live.state.agentName} cannot share this chat with claude.ai. It needs Claude Code's ACP adapter 0.110 or later (Update it in the agent setup) and a claude.ai sign-in.`);
}
const turnOn = on === true;
if (turnOn && !(await confirm())) {
return false;
}
await this.prompt(window, live.state.id, remoteControlPrompt(turnOn), []);
return live.state.remoteControl ?? { available: true, active: false, url: null };
}

/**
* #431: brings a claude.ai/code session into the folder with `claude
* --teleport <id>`, run by the agent's own Claude CLI (the adapter's
* `--cli`) in a new terminal of the window. Once there it is a local
* session the person adds with Import chats (#298).
*/
async importFromWeb(window: WindowPort, ref: unknown, link: unknown, cols: unknown, rows: unknown, confirm: (commandLine: string) => Promise<boolean>): Promise<LoginTerminal | null> {
this.remember(window);
const agentRef = requireString(ref, 'agent', 200);
const cloudId = typeof link === 'string' && link.length <= 2000 ? parseCloudSessionRef(link) : null;
if (!cloudId) {
throw new Error('Paste a claude.ai/code session link or its id (session_...).');
}
if (!this.options.rootOf(window)) {
throw new Error('Open a folder to import a chat into it.');
}
const args = teleportArgs(cloudId);
if (!(await confirm(commandLine(args)))) {
return null;
}
return this.openClaudeCli(window, agentRef, args, 'Claude Code: import from claude.ai', cols, rows);
}

/**
* #431: continues the chat in a terminal with the Claude CLI (`claude
* --resume`). The IDE lets go of the chat's agent first, so only one
* process writes the session; the next message here starts it again and
* reads what was done meanwhile.
*/
async continueInTerminal(window: WindowPort, sessionId: unknown, cols: unknown, rows: unknown): Promise<LoginTerminal> {
this.remember(window);
const live = await this.open(window, sessionId);
this.assertContinuable(live, window);
const agentSessionId = live.state.agentSessionId;
if (!agentSessionId) {
throw new Error('This chat has not reached Claude Code yet: send a first message.');
}
if (live.turnActive) {
throw new Error('The agent is still answering; wait for it or stop it first.');
}
const args = resumeArgs(agentSessionId);
const opened = await this.openClaudeCli(window, live.state.agentRef, args, `Claude Code: ${live.state.title}`, cols, rows, this.workRoot(live));
this.stopAgent(live);
this.emit(live, { type: 'notice', id: randomUUID(), level: 'info', text: 'Continued in a terminal. The next message here picks up what was done there; close that terminal session first.' });
return opened;
}

/** #431: the Claude CLI that Claude Code's ACP adapter wraps, with `args`, in a new terminal of the window. */
private async openClaudeCli(window: WindowPort, agentRef: string, args: readonly string[], title: string, cols: unknown, rows: unknown, cwd?: string): Promise<LoginTerminal> {
const definition = this.options.catalog.definition(agentRef);
if (!definition || definition.preset !== 'claude') {
throw new Error('Only Claude Code chats move between claude.ai, the terminal and the IDE.');
}
if (!this.options.spawnAllowed) {
throw new Error('Agents cannot start in this mode.');
}
if (!this.options.isTrusted(window)) {
throw new Error('This folder is in Restricted Mode. Trust it to start an agent.');
}
const resolution = await this.options.catalog.resolve(definition);
if (!resolution.found) {
throw new Error(resolution.detail);
}
const launch = resolution.launch;
const native = await nativeLoginProgram(loginProgram(launch, { args: ['--cli', ...args] }), {
platform: this.platform,
arch: process.arch,
env: launch.env,
exists: (file) => fs.promises.stat(file).then((stat) => stat.isFile(), () => false),
});
const program = await consoleLoginProgram(native, launch, { platform: this.platform, findNode: () => this.options.catalog.findSystemNode() });
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: cwd ?? this.options.rootOf(window) ?? this.options.homeDir,
env: { ...launch.env },
title,
cols: size(cols, 100),
rows: size(rows, 30),
});
return opened.terminal;
}

/**
* #431: keeps the chat's Remote Control state in step with the agent: its
* commands (available or not), its answer to `/remote-control`, and the
* notice Claude Code sends when Remote Control starts with the session.
*/
private trackRemoteControl(live: Live, event: SessionEvent): void {
const current = live.state.remoteControl;
if (event.type === 'commands') {
const available = offersRemoteControl(event.commands);
if (current?.available !== available) {
this.emit(live, { type: 'remote-control', remote: { available, active: available && (current?.active ?? false), url: available ? current?.url ?? null : null } });
}
return;
}
let reply: RemoteControlReply | null = null;
if (event.type === 'notice') {
reply = parseRemoteControlReply(event.text);
} else if (event.type === 'turn-end') {
const items = live.state.items;
let userIndex = -1;
for (let index = items.length - 1; index >= 0; index -= 1) {
if (items[index]?.kind === 'user') {
userIndex = index;
break;
}
}
const user = items[userIndex];
if (!user || user.kind !== 'user' || user.remote || !isRemoteControlPrompt(user.text)) {
return;
}
const answer = items.slice(userIndex + 1).map((item) => (item.kind === 'assistant' ? item.text : '')).join('\n');
reply = parseRemoteControlReply(answer) ?? (event.stopReason === 'error' ? { state: 'failed', reason: 'Claude Code did not answer.' } : null);
}
if (!reply) {
return;
}
const available = current?.available ?? true;
const next: RemoteControlView = reply.state === 'on'
? { available, active: true, url: reply.url }
: reply.state === 'off'
? { available, active: false, url: null }
: { available, active: false, url: null, error: reply.reason };
this.emit(live, { type: 'remote-control', remote: next });
}

/** #431: the agent ended, and its Remote Control with it. */
private endRemoteControl(live: Live): void {
const current = live.state.remoteControl;
if (current?.active) {
this.emit(live, { type: 'remote-control', remote: { available: current.available, active: false, url: null } });
}
}

/** #431: a message typed on claude.ai, joined from its chunks, becomes the chat's message. */
private flushRemoteUser(live: Live): void {
const text = live.remoteUser;
live.remoteUser = null;
if (text !== null && text.trim()) {
this.emit(live, { type: 'user', id: randomUUID(), text, at: this.now(), remote: true });
}
}

/** 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<Set<string>> {
const ids = new Set<string>();
Expand Down Expand Up @@ -1287,6 +1468,7 @@ export class AgentSessionService {
cancelTimer: null,
replaying: false,
importedUser: null,
remoteUser: null,
configRaw: [],
permissions: new Map(),
terminalBuffer: new Map(),
Expand Down Expand Up @@ -1339,6 +1521,9 @@ export class AgentSessionService {
this.sessionsChanged();
}
this.feedAgentFlow(live, event);
if (event.type === 'commands' || event.type === 'notice' || event.type === 'turn-end') {
this.trackRemoteControl(live, event);
}
}

/** Agent Flow sees the event; a failure there never reaches the chat. */
Expand Down Expand Up @@ -1428,6 +1613,8 @@ export class AgentSessionService {
if (live.agent?.connection === connection) {
live.agent = null;
this.cancelPermissions(live);
live.remoteUser = null;
this.endRemoteControl(live);
if (error && !live.turnActive && !this.stopped) {
this.emit(live, { type: 'notice', id: randomUUID(), level: 'warning', text: `${errorMessage(error)} It starts again with the next message.` });
}
Expand Down Expand Up @@ -1541,6 +1728,16 @@ export class AgentSessionService {
// `session/load` replays the history the IDE already has.
return;
}
// #431: outside a replay, the adapter sends the person's message only when it
// was typed in another client of the session (claude.ai, over Remote Control).
if (update.sessionUpdate === 'user_message_chunk' && !live.state.historyPending) {
const text = update.content.type === 'text' ? update.content.text : '';
live.remoteUser = (live.remoteUser ?? '') + text;
return;
}
if (live.remoteUser !== null && !['available_commands_update', 'current_mode_update', 'config_option_update', 'usage_update'].includes(update.sessionUpdate)) {
this.flushRemoteUser(live);
}
if (update.sessionUpdate === 'config_option_update') {
live.configRaw = update.configOptions;
}
Expand Down Expand Up @@ -1813,6 +2010,10 @@ export class AgentSessionService {
this.cancelPermissions(live);
const agent = live.agent;
live.agent = null;
live.remoteUser = null;
if (agent) {
this.endRemoteControl(live);
}
agent?.connection.close();
agent?.terminals.disposeAll();
if (live.terminalTimer) {
Expand Down
4 changes: 4 additions & 0 deletions apps/ide/src/main/agentSessions/agentSessionsIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export function registerAgentSessionHandlers(handle: Handle, runtime: AgentSessi
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));
// #431: sharing a chat with claude.ai and bringing one in each ask natively first.
handle(C.setRemoteControl, (event, id, on) => service.setRemoteControl(portOf(event.sender), id, on, () => runtime.confirmRemoteControl(event.sender)));
handle(C.importFromWeb, (event, ref, link, cols, rows) => service.importFromWeb(portOf(event.sender), ref, link, cols, rows, (line) => runtime.confirmImportFromWeb(event.sender, line)));
handle(C.continueInTerminal, (event, id, cols, rows) => service.continueInTerminal(portOf(event.sender), id, cols, rows));
// 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)));
Expand Down
31 changes: 31 additions & 0 deletions apps/ide/src/main/agentSessions/agentSessionsRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +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 { KeyVault } from '../agents/keyVault.ts';
import { electronCipher } from '../agents/electronCipher.ts';
import { AgentInstaller, consentDetail } from './agentInstaller.ts';
Expand Down Expand Up @@ -40,6 +41,10 @@ export interface AgentSessionsRuntime {
confirmInstall(contents: WebContents, description: InstallDescription): Promise<boolean>;
/** AF2: the confirmation to remove an adapter the IDE installed. */
confirmUninstall(contents: WebContents, packageName: string, version: string): Promise<boolean>;
/** #431: the consent to make a chat reachable from claude.ai (Remote Control). */
confirmRemoteControl(contents: WebContents): Promise<boolean>;
/** #431: the confirmation to run `claude --teleport` for a claude.ai session. */
confirmImportFromWeb(contents: WebContents, commandLine: string): Promise<boolean>;
}

const MAX_REGISTRY_RESPONSE = 32 * 1024 * 1024;
Expand Down Expand Up @@ -281,6 +286,32 @@ export function startAgentSessions(options: AgentSessionsRuntimeOptions): AgentS
});
return response === 0;
},
async confirmRemoteControl(contents) {
const response = await ask(contents, {
type: 'warning',
title: 'Share on claude.ai',
message: 'Share this chat with claude.ai and the Claude mobile app?',
detail: REMOTE_CONTROL_CONSENT,
buttons: ['Share', 'Cancel'],
defaultId: 1,
cancelId: 1,
noLink: true,
});
return response === 0;
},
async confirmImportFromWeb(contents, commandLine) {
const response = await ask(contents, {
type: 'question',
title: 'Import from claude.ai',
message: 'Bring this claude.ai/code session into the folder?',
detail: `${TELEPORT_HINT}\n\nA terminal runs: ${commandLine}`,
buttons: ['Import', 'Cancel'],
defaultId: 1,
cancelId: 1,
noLink: true,
});
return response === 0;
},
async confirmCustomAgent(contents, commandLine) {
const owner = BrowserWindow.fromWebContents(contents);
const confirm: Electron.MessageBoxOptions = {
Expand Down
2 changes: 2 additions & 0 deletions apps/ide/src/main/agentSessions/sessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ function normalize(state: AgentSessionState): AgentSessionState {
usage: state.usage ?? null,
agentSessionId: typeof state.agentSessionId === 'string' ? state.agentSessionId : null,
...(state.historyPending === true ? { historyPending: true } : {}),
// #431: Remote Control ends with the agent, so a chat read from disk is never connected.
...(state.remoteControl && typeof state.remoteControl === 'object' ? { remoteControl: { available: state.remoteControl.available === true, active: false, url: null } } : {}),
});
}

Expand Down
4 changes: 4 additions & 0 deletions apps/ide/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ const api: CodeXRApi = Object.freeze({
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),
// #431: one Claude Code session everywhere; main validates the chat, the link and asks before sharing.
setRemoteControl: (sessionId: string, on: boolean) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.setRemoteControl, sessionId, on === true),
importFromWeb: (ref: string, link: string, cols?: number, rows?: number) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.importFromWeb, ref, link, cols, rows),
continueInTerminal: (sessionId: string, cols?: number, rows?: number) => ipcRenderer.invoke(AGENT_SESSION_CHANNELS.continueInTerminal, sessionId, cols, rows),
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),
Expand Down
3 changes: 3 additions & 0 deletions apps/ide/src/renderer/agentFirst/agentFirst.css
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@
.af-empty p { margin: 0 auto; max-width: 480px; line-height: 1.5; }
.af-message { min-width: 0; overflow-wrap: anywhere; line-height: 1.55; }
.af-message.is-user { align-self: flex-end; max-width: 85%; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--hover); }
.af-remote-origin { display: block; margin-bottom: 2px; font-size: var(--fs-2xs); }
.af-badge.af-remote { color: var(--accent); border-color: var(--accent); background: none; font: inherit; font-size: var(--fs-2xs); cursor: pointer; }
.af-badge.af-remote[hidden] { display: none; }
.af-user-text { margin: 0; white-space: pre-wrap; }
.af-message-actions { display: flex; gap: 8px; margin-top: 4px; font-size: var(--fs-sm); }
.af-message-actions:empty { display: none; }
Expand Down
Loading
Loading