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
4 changes: 4 additions & 0 deletions apps/vscode-extension/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

#### Added

- **One Claude Code session everywhere.** Continue the same Claude Code chat from Code-XR, claude.ai/code, the Claude mobile app or the terminal.
- **Import a chat from claude.ai** in the AI Agents section: paste the claude.ai/code link and Code-XR brings the session into the folder with `claude --teleport`, branch included.
- Right-click a Claude Code session of the workspace: **Continue on claude.ai** (Remote Control, after you confirm) or **Continue in the terminal**.
- Remote Control needs a claude.ai sign-in, not an API key. Nothing is shared until you confirm.
- **Agent Flow, the fifth analysis type.** Watch an AI coding agent work on the XR analysis table.
- The project is a city: folders are plates, files are buildings.
- Every agent is a worker. Sub-agents get their own worker and work in parallel.
Expand Down
23 changes: 23 additions & 0 deletions apps/vscode-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,18 @@
"title": "Code-XR: Watch an Agent in XR (Agent Flow)",
"enablement": "!codeXR.pythonEnv.uiLocked"
},
{
"command": "codeXR.claudeSessions.importFromWeb",
"title": "Code-XR: Import a Claude Code Chat from claude.ai"
},
{
"command": "codeXR.claudeSessions.continueOnClaudeAi",
"title": "Code-XR: Continue a Claude Code Chat on claude.ai (Remote Control)"
},
{
"command": "codeXR.claudeSessions.continueInTerminal",
"title": "Code-XR: Continue a Claude Code Chat in the Terminal"
},
{
"command": "codeXR.analysis.analyzeProjectXRDeep",
"title": "Code-XR: Analyze Project (XR Deep)",
Expand Down Expand Up @@ -710,6 +722,17 @@
"when": "view == codexrTree && viewItem == activeServerParticipantGuest && !codeXR.pythonEnv.uiLocked",
"group": "activeServerParticipant@1"
}
,
{
"command": "codeXR.claudeSessions.continueOnClaudeAi",
"when": "view == codexrTree && viewItem == codeXR.aiAgents.agentFlow.session.claude && !codeXR.pythonEnv.uiLocked",
"group": "claudeSession@1"
},
{
"command": "codeXR.claudeSessions.continueInTerminal",
"when": "view == codexrTree && viewItem == codeXR.aiAgents.agentFlow.session.claude && !codeXR.pythonEnv.uiLocked",
"group": "claudeSession@2"
}
],
"codeXR.analysis.contextMenu": [
{
Expand Down
2 changes: 2 additions & 0 deletions apps/vscode-extension/src/app/commands/registerAllCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { getVisualizationSettingsCommandRegistrations } from '../../features/visualization-settings/commands/visualizationSettingsCommandRegistrations';
import { getLearnMoreCommandRegistrations } from '../../features/learn-more/commands/learnMoreCommandRegistrations';
import { getAgentFlowCommandRegistrations } from '../../features/ai-agents/commands/agentFlowCommands';
import { getClaudeSessionCommandRegistrations } from '../../features/ai-agents/commands/claudeSessionCommands';
import { getGeneralCommandRegistrations } from './generalCommands';
import { getCollaborationCommandRegistrations } from '../../features/collaboration/commands/collaborationCommands';
import { ExtensionCommandRegistration, assertUniqueCommandIds } from '../../platform/commands/commandRegistry';
Expand All @@ -29,7 +30,7 @@
return;
}
if ('getSectionProvider' in treeDataProvider) {
const sectionProvider = (treeDataProvider as any).getSectionProvider('analysis');

Check warning on line 33 in apps/vscode-extension/src/app/commands/registerAllCommands.ts

View workflow job for this annotation

GitHub Actions / npm test (ubuntu-latest)

Unexpected any. Specify a different type
if (sectionProvider && typeof sectionProvider.refresh === 'function') {
logger.debug('Refreshing ANALYSIS through its section provider.');
sectionProvider.refresh();
Expand All @@ -51,6 +52,7 @@
...getCollaborationCommandRegistrations(context, treeDataProvider),
...getLearnMoreCommandRegistrations(context),
...getAgentFlowCommandRegistrations(),
...getClaudeSessionCommandRegistrations(),
];
assertUniqueCommandIds(registrations);
CommandBuilder.registerAll(context, registrations);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* #431: one Claude Code session everywhere. The pure rules both hosts (the
* Code-XR IDE and the VS Code extension) share to hand a chat between
* Code-XR, claude.ai (web and mobile) and the Claude CLI or Desktop:
*
* - Remote Control: the Claude Code ACP adapter (`claude-agent-acp` 0.110 and
* later) serves `/remote-control [name]` and `/remote-control off` itself,
* through the Agent SDK, and answers with the session's claude.ai URL. A
* host sends the command as a prompt and reads the answer with
* `parseRemoteControlReply`. Messages typed on claude.ai come back to the
* host as `user_message_chunk` updates.
* - Teleport: `claude --teleport <cloud session id>` copies a claude.ai/code
* session (its transcript and branch) into the folder, where it becomes an
* ordinary local session that the host imports.
* - Resume: `claude --resume <local session id> [--remote-control]` continues a
* local session in a terminal, optionally reachable from claude.ai.
*
* Nothing here touches the network, a process or the file system: the hosts
* run the commands, with the person's consent.
*/

/** The adapter command name, as `available_commands_update` lists it. */
export const REMOTE_CONTROL_COMMAND = 'remote-control';

/** The prompt that turns Remote Control on (`on`) or off. */
export function remoteControlPrompt(on: boolean): string {
return on ? `/${REMOTE_CONTROL_COMMAND}` : `/${REMOTE_CONTROL_COMMAND} off`;
}

/** Whether a session's advertised slash commands include Remote Control. */
export function offersRemoteControl(commands: readonly { readonly name: string }[]): boolean {
return commands.some((command) => command.name === REMOTE_CONTROL_COMMAND);
}

/** Whether a prompt is the Remote Control command (on or off). */
export function isRemoteControlPrompt(text: string): boolean {
return /^\/remote-control(?:\s|$)/.test(text.trim());
}

export type RemoteControlReply =
| { readonly state: 'on'; readonly url: string | null }
| { readonly state: 'off' }
| { readonly state: 'failed'; readonly reason: string };

const CLAUDE_URL = /https:\/\/claude\.ai\/[^\s)>\]"'`]+/;

/**
* Reads the adapter's answer to `/remote-control`, or the notice it sends when
* Claude Code starts Remote Control with the session (`remoteControlAtStartup`).
* Null for any other text.
*/
export function parseRemoteControlReply(text: string): RemoteControlReply | null {
const flat = text.replace(/\s+/g, ' ').trim();
if (/^Remote Control is off\b/i.test(flat)) {
return { state: 'off' };
}
const failed = /^Could not (?:start|stop) Remote Control:? ?(.*)$/i.exec(flat);
if (failed) {
return { state: 'failed', reason: failed[1]?.trim() || 'Claude Code refused it.' };
}
if (/^Remote Control (?:is active|connected)\b/i.test(flat)) {
const url = CLAUDE_URL.exec(flat);
return { state: 'on', url: url ? url[0].replace(/[.,;:]+$/, '') : null };
}
return null;
}

const CLOUD_SESSION_ID = /^session_[A-Za-z0-9]{6,120}$/;

/**
* The claude.ai/code session id in what the person pasted: the id itself
* (`session_...`) or a link that contains it. Null when there is none, so a
* host never passes free text to the CLI.
*/
export function parseCloudSessionRef(input: string): string | null {
const text = input.trim();
if (CLOUD_SESSION_ID.test(text)) {
return text;
}
const match = /(?:^|[/=?&#])(session_[A-Za-z0-9]{6,120})(?=$|[/?&#])/.exec(text);
if (match && /^https:\/\/(?:[a-z0-9-]+\.)?claude\.ai\//i.test(text)) {
return match[1];
}
return null;
}

const LOCAL_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

/** Whether `id` is a local Claude Code session id (the name of its transcript). */
export function isLocalSessionId(id: string): boolean {
return LOCAL_SESSION_ID.test(id);
}

/** The Claude CLI arguments that bring a claude.ai/code session into the current folder. */
export function teleportArgs(cloudSessionId: string): string[] {
if (!CLOUD_SESSION_ID.test(cloudSessionId)) {
throw new Error('That is not a Claude Code on the web session id.');
}
return ['--teleport', cloudSessionId];
}

/** The Claude CLI arguments that continue a local session, reachable from claude.ai when `remoteControl`. */
export function resumeArgs(localSessionId: string, options: { readonly remoteControl?: boolean } = {}): string[] {
if (!isLocalSessionId(localSessionId)) {
throw new Error('That is not a Claude Code session id.');
}
return ['--resume', localSessionId, ...(options.remoteControl ? ['--remote-control'] : [])];
}

/** One command line to show or type (the ids are validated, so nothing needs quoting). */
export function commandLine(args: readonly string[], bin = 'claude'): string {
return [bin, ...args].join(' ');
}

/** What every host says before it shares a chat: the only network-facing step of a chat. */
export const REMOTE_CONTROL_CONSENT =
'Remote Control makes this Claude Code session reachable from claude.ai/code and the Claude mobile app, signed in with the same Claude account. '
+ '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. '
+ 'Turn it off at any time.';

/** What a host says when it brings a claude.ai session in. */
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.';
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import * as vscode from 'vscode';
import { ExtensionCommandRegistration } from '../../../platform/commands/commandRegistry';
import {
REMOTE_CONTROL_CONSENT,
TELEPORT_HINT,
commandLine,
isLocalSessionId,
parseCloudSessionRef,
resumeArgs,
teleportArgs,
} from '../../../core/claude-sessions/claudeSessionContinuity';
import { agentFlowWorkspaceRoot, describeAge, listWorkspaceAgentSessions } from './agentFlowCommands';

/**
* #431: one Claude Code session everywhere, in the VS Code extension. The
* extension does not host chats itself, so it hands a Claude Code session of
* the workspace to the Claude CLI in an integrated terminal: from claude.ai
* into the folder (teleport), and from the folder to claude.ai and the Claude
* mobile app (resume with Remote Control). The rules are the shared core's;
* this is only the VS Code adapter. Nothing runs without the person's
* confirmation, and the CLI is the person's own `claude`.
*/
export const IMPORT_FROM_WEB_COMMAND = 'codeXR.claudeSessions.importFromWeb';
export const CONTINUE_ON_CLAUDE_AI_COMMAND = 'codeXR.claudeSessions.continueOnClaudeAi';
export const CONTINUE_IN_TERMINAL_COMMAND = 'codeXR.claudeSessions.continueInTerminal';

const CLAUDE_SOURCE_PREFIX = 'claude-code:';

/** The local session id of an Agent Flow source id (`claude-code:<uuid>`), or null. */
export function claudeSessionIdOf(sourceId: string): string | null {
if (!sourceId.startsWith(CLAUDE_SOURCE_PREFIX)) {
return null;
}
const id = sourceId.slice(CLAUDE_SOURCE_PREFIX.length);
return isLocalSessionId(id) ? id : null;
}

function runInTerminal(name: string, cwd: string, args: readonly string[]): void {
const terminal = vscode.window.createTerminal({ name, cwd });
terminal.show();
terminal.sendText(commandLine(args));
}

/** The workspace's Claude Code sessions, newest first, as `{ id, label, age }`. */
function workspaceClaudeSessions(): { id: string; label: string; age: string }[] {
const now = Date.now();
return listWorkspaceAgentSessions()
.map((session) => ({ session, id: claudeSessionIdOf(session.id) }))
.filter((entry): entry is { session: typeof entry.session; id: string } => entry.id !== null)
.map(({ session, id }) => ({ id, label: session.label, age: describeAge(session.updatedAt, now) }));
}

async function pickClaudeSession(title: string): Promise<string | undefined> {
const sessions = workspaceClaudeSessions();
if (sessions.length === 0) {
void vscode.window.showInformationMessage('This workspace has no Claude Code session yet. Run Claude Code in this folder first.');
return undefined;
}
const picked = await vscode.window.showQuickPick(
sessions.map((session) => ({ label: session.label, description: session.age, id: session.id })),
{ title, placeHolder: 'Pick the Claude Code session' },
);
return picked?.id;
}

function requireRoot(): string | undefined {
const root = agentFlowWorkspaceRoot();
if (!root) {
void vscode.window.showWarningMessage('Open a folder first: Claude Code sessions belong to a folder.');
}
return root;
}

/** Brings a claude.ai/code session into the workspace folder with `claude --teleport`. */
export async function importFromWeb(input?: string): Promise<void> {
const root = requireRoot();
if (!root) {
return;
}
const value = input ?? await vscode.window.showInputBox({
title: 'Import a Claude Code chat from claude.ai',
prompt: 'Paste the claude.ai/code session link or its id (session_...).',
placeHolder: 'https://claude.ai/code/session_...',
ignoreFocusOut: true,
validateInput: (text) => (text.trim() === '' || parseCloudSessionRef(text) ? undefined : 'That is not a claude.ai/code session link or id.'),
});
if (!value) {
return;
}
const cloudId = parseCloudSessionRef(value);
if (!cloudId) {
void vscode.window.showWarningMessage('That is not a claude.ai/code session link or id.');
return;
}
const go = await vscode.window.showInformationMessage(
'Import this chat from claude.ai?',
{ modal: true, detail: `${TELEPORT_HINT}\n\nCode-XR will run in a terminal: ${commandLine(teleportArgs(cloudId))}` },
'Import',
);
if (go !== 'Import') {
return;
}
runInTerminal('Claude Code: import from claude.ai', root, teleportArgs(cloudId));
}

/** Continues a local session in a terminal with Remote Control, so claude.ai and the mobile app reach it. */
export async function continueOnClaudeAi(arg?: unknown): Promise<void> {
const root = requireRoot();
if (!root) {
return;
}
const id = sessionIdFromArgument(arg) ?? await pickClaudeSession('Continue a Claude Code chat on claude.ai');
if (!id) {
return;
}
const go = await vscode.window.showWarningMessage(
'Share this chat with claude.ai?',
{ modal: true, detail: `${REMOTE_CONTROL_CONSENT}\n\nCode-XR will run in a terminal: ${commandLine(resumeArgs(id, { remoteControl: true }))}\nClose the Claude Code session anywhere else first, so only one process writes it.` },
'Share',
);
if (go !== 'Share') {
return;
}
runInTerminal('Claude Code: shared on claude.ai', root, resumeArgs(id, { remoteControl: true }));
}

/** Continues a local session in a terminal (`claude --resume`). */
export async function continueInTerminal(arg?: unknown): Promise<void> {
const root = requireRoot();
if (!root) {
return;
}
const id = sessionIdFromArgument(arg) ?? await pickClaudeSession('Continue a Claude Code chat in the terminal');
if (!id) {
return;
}
runInTerminal('Claude Code', root, resumeArgs(id));
}

/** The session id a tree row passes (the row itself, or an Agent Flow source id). */
function sessionIdFromArgument(arg: unknown): string | null {
if (typeof arg === 'string') {
return claudeSessionIdOf(arg) ?? (isLocalSessionId(arg) ? arg : null);
}
const sourceId = arg && typeof arg === 'object' ? (arg as { command?: { arguments?: unknown[] } }).command?.arguments?.[0] : undefined;
return typeof sourceId === 'string' ? claudeSessionIdOf(sourceId) : null;
}

export function getClaudeSessionCommandRegistrations(): ExtensionCommandRegistration[] {
return [
{
id: IMPORT_FROM_WEB_COMMAND,
module: 'AI_AGENTS',
description: 'Bring a claude.ai/code session into the workspace folder (claude --teleport)',
handler: (input?: unknown) => importFromWeb(typeof input === 'string' ? input : undefined),
errorMessage: 'The chat could not be imported from claude.ai',
},
{
id: CONTINUE_ON_CLAUDE_AI_COMMAND,
module: 'AI_AGENTS',
description: 'Continue a Claude Code session of the workspace from claude.ai and the mobile app (Remote Control)',
handler: (arg?: unknown) => continueOnClaudeAi(arg),
errorMessage: 'The chat could not be shared with claude.ai',
},
{
id: CONTINUE_IN_TERMINAL_COMMAND,
module: 'AI_AGENTS',
description: 'Continue a Claude Code session of the workspace in a terminal (claude --resume)',
handler: (arg?: unknown) => continueInTerminal(arg),
errorMessage: 'The chat could not be continued in the terminal',
},
];
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
AiAgentsTreeItem,
createAgentSessionItem,
createComingSoonItem,
createImportFromWebItem,
createNoAgentSessionsItem,
createWatchAgentFlowItem,
} from './aiAgentsItems';
Expand Down Expand Up @@ -48,6 +49,7 @@ export class AiAgentsSectionProvider extends BaseSectionProvider<AiAgentsTreeIte
...(sessions.length > 0
? sessions.slice(0, RECENT_SESSIONS).map((session) => createAgentSessionItem(session, describeAge(session.updatedAt, now)))
: [createNoAgentSessionsItem()]),
createImportFromWebItem(),
createComingSoonItem(),
];
}
Expand Down
Loading
Loading