Skip to content

Commit 8224188

Browse files
committed
feat: control Remote Control per-session, fix reviewer-flagged resume bugs
Adds a Remote Control toggle chip to the composer for draft Claude threads, wired through a generalized bindSessionLaunchOptions (formerly bindResumeSession) that binds resume and/or remote-control choices together at thread-creation time. Also fixes the Remote Control settings field rendering as a text input instead of a switch, closes a path traversal hole in session id handling, fixes config dir resolution to use the workspace cwd, and fixes a double-click race and stale-draft-loss race in the resume dialog.
1 parent 75336b3 commit 8224188

9 files changed

Lines changed: 223 additions & 54 deletions

File tree

‎apps/server/src/provider/Layers/ClaudeAdapter.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,12 @@ interface ClaudeResumeState {
120120
readonly resume?: string;
121121
readonly resumeSessionAt?: string;
122122
readonly turnCount?: number;
123+
// Per-thread, decided once at thread creation (see
124+
// ClaudeSessionHistory.bindSessionLaunchOptions) — not a resume concept,
125+
// just piggybacking on the same opaque per-thread `resumeCursor` bag
126+
// rather than growing ProviderSessionStartInput's cross-provider schema
127+
// for a single-driver launch flag.
128+
readonly remoteControl?: boolean;
123129
}
124130

125131
interface ClaudeTurnState {
@@ -565,6 +571,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
565571
sessionId?: unknown;
566572
resumeSessionAt?: unknown;
567573
turnCount?: unknown;
574+
remoteControl?: unknown;
568575
};
569576

570577
const threadIdCandidate = typeof cursor.threadId === "string" ? cursor.threadId : undefined;
@@ -582,6 +589,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
582589
const resumeSessionAt =
583590
typeof cursor.resumeSessionAt === "string" ? cursor.resumeSessionAt : undefined;
584591
const turnCountValue = typeof cursor.turnCount === "number" ? cursor.turnCount : undefined;
592+
const remoteControl = cursor.remoteControl === true ? true : undefined;
585593

586594
return {
587595
...(threadId ? { threadId } : {}),
@@ -590,6 +598,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
590598
...(turnCountValue !== undefined && Number.isInteger(turnCountValue) && turnCountValue >= 0
591599
? { turnCount: turnCountValue }
592600
: {}),
601+
...(remoteControl ? { remoteControl } : {}),
593602
};
594603
}
595604

@@ -3486,7 +3495,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
34863495
const claudeBinaryPath = claudeSdkExecutablePath;
34873496
const extraArgs = {
34883497
...parseCliArgs(claudeSettings.launchArgs).flags,
3489-
...(claudeSettings.remoteControl ? { "remote-control": null } : {}),
3498+
// Either the per-instance persistent setting or a per-thread
3499+
// choice made when the thread was created (see
3500+
// ClaudeSessionHistory.bindSessionLaunchOptions) enables it.
3501+
...(claudeSettings.remoteControl || resumeState?.remoteControl
3502+
? { "remote-control": null }
3503+
: {}),
34903504
};
34913505
const modelSelection =
34923506
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;

‎apps/server/src/provider/Layers/ClaudeSessionHistory.ts‎

Lines changed: 86 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,17 @@ const decodeClaudeSettings = Schema.decodeUnknownEffect(ClaudeSettings);
6262
const JSONL_EXTENSION = ".jsonl";
6363
const MAX_LABEL_LENGTH = 80;
6464
const MAX_TRANSCRIPT_MESSAGES = 200;
65+
// Every Claude Code session id observed on disk is a UUID (the filename
66+
// stem of `<sessionId>.jsonl`). `sessionId` is caller-controlled input that
67+
// gets interpolated into a filesystem path (`getTranscript`) — validating it
68+
// against this shape before doing anything with it closes off path
69+
// traversal (`../../other-project/secret`) rather than merely resolving to
70+
// a possibly-out-of-bounds path and hoping the caller was honest.
71+
const CLAUDE_SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
72+
73+
function isValidClaudeSessionId(sessionId: string): boolean {
74+
return CLAUDE_SESSION_ID_PATTERN.test(sessionId);
75+
}
6576

6677
function encodeCwdForClaudeProjectDir(cwd: string): string {
6778
return cwd.replace(/[^a-zA-Z0-9]/g, "-");
@@ -220,10 +231,13 @@ function parseTranscriptMessages(
220231
return messages;
221232
}
222233

223-
export interface ClaudeSessionHistoryBindResumeSessionInput {
234+
export interface ClaudeSessionHistoryBindSessionLaunchOptionsInput {
224235
readonly threadId: ThreadId;
225236
readonly providerInstanceId: ProviderInstanceId;
226-
readonly resumeExternalSessionId: string;
237+
/** Resume a picked on-disk session's model context via `--resume <uuid>`. */
238+
readonly resumeExternalSessionId?: string;
239+
/** Start the session with Claude Code's Remote Control (`--remote-control`) enabled. */
240+
readonly remoteControl?: boolean;
227241
}
228242

229243
export class ClaudeSessionHistory extends Context.Service<
@@ -242,12 +256,14 @@ export class ClaudeSessionHistory extends Context.Service<
242256
input: ServerGetClaudeResumableSessionTranscriptInput,
243257
) => Effect.Effect<ServerGetClaudeResumableSessionTranscriptResult>;
244258
/**
245-
* Binds a picked on-disk Claude session to a thread's provider session
246-
* directory entry, so the next turn resumes it via `--resume <uuid>`.
247-
* Fails if the target provider instance isn't a Claude instance.
259+
* Binds thread-creation-time Claude launch choices (resume a picked
260+
* on-disk session, and/or start with Remote Control enabled) onto a
261+
* thread's provider session directory entry, so they take effect on the
262+
* next (first) turn. No-op if neither option is set. Fails if the
263+
* target provider instance isn't a Claude instance.
248264
*/
249-
readonly bindResumeSession: (
250-
input: ClaudeSessionHistoryBindResumeSessionInput,
265+
readonly bindSessionLaunchOptions: (
266+
input: ClaudeSessionHistoryBindSessionLaunchOptionsInput,
251267
) => Effect.Effect<void, ProviderValidationError | ProviderSessionDirectoryWriteError>;
252268
}
253269
>()("t3/provider/Layers/ClaudeSessionHistory") {}
@@ -266,20 +282,27 @@ export const make = Effect.gen(function* () {
266282
// rather than failing the whole listing — best-effort, matching `list`'s
267283
// other file-not-found handling.
268284
const resolveConfigDirPathForInstance = Effect.fn("ClaudeSessionHistory.resolveConfigDirPath")(
269-
function* (providerInstanceId: ProviderInstanceId | undefined) {
285+
function* (input: {
286+
readonly providerInstanceId: ProviderInstanceId | undefined;
287+
readonly workspaceRoot: string;
288+
}) {
270289
const homePath = yield* Effect.gen(function* () {
271-
if (providerInstanceId === undefined) return "";
290+
if (input.providerInstanceId === undefined) return "";
272291
const settings = yield* serverSettings.getSettings;
273292
const configMap = deriveProviderInstanceConfigMap(settings);
274-
const entry = configMap[providerInstanceId];
293+
const entry = configMap[input.providerInstanceId];
275294
const decoded = yield* decodeClaudeSettings(entry?.config ?? {});
276295
return decoded.homePath;
277296
}).pipe(Effect.orElseSucceed(() => ""));
278297
// `resolveClaudeConfigDirPath` yields its own `Path.Path` requirement;
279298
// satisfy it from the already-resolved `path` in scope so this stays
280299
// free of a `Path.Path` requirement of its own (see the `list`/`make`
281300
// split above — required for `Layer.provideMerge` to fully resolve it).
282-
return yield* resolveClaudeConfigDirPath({ homePath }, process.env).pipe(
301+
// `workspaceRoot` is passed as `cwd`: when `homePath` is unset and a
302+
// *relative* `CLAUDE_CONFIG_DIR` is set in the environment, it must be
303+
// resolved the same way the spawned `claude` subprocess itself
304+
// resolves it — against the workspace cwd, not the server's own cwd.
305+
return yield* resolveClaudeConfigDirPath({ homePath }, process.env, input.workspaceRoot).pipe(
283306
Effect.provideService(Path.Path, path),
284307
);
285308
},
@@ -290,7 +313,10 @@ export const make = Effect.gen(function* () {
290313
readonly workspaceRoot: string;
291314
readonly providerInstanceId?: ProviderInstanceId | undefined;
292315
}) {
293-
const configDirPath = yield* resolveConfigDirPathForInstance(input.providerInstanceId);
316+
const configDirPath = yield* resolveConfigDirPathForInstance({
317+
providerInstanceId: input.providerInstanceId,
318+
workspaceRoot: input.workspaceRoot,
319+
});
294320
return path.join(
295321
configDirPath,
296322
"projects",
@@ -350,6 +376,16 @@ export const make = Effect.gen(function* () {
350376
const getTranscript: ClaudeSessionHistory["Service"]["getTranscript"] = Effect.fn(
351377
"ClaudeSessionHistory.getTranscript",
352378
)(function* (input) {
379+
// Best-effort/display-only endpoint (see class doc), so an invalid
380+
// sessionId — most importantly one crafted to escape `projectDirPath`
381+
// via `../` traversal segments — degrades to "no history to show"
382+
// rather than a hard error, matching this file's other not-found
383+
// handling. The validation itself is still load-bearing: it's what
384+
// stops `path.join` below from ever being handed a value that resolves
385+
// outside `projectDirPath`.
386+
if (!isValidClaudeSessionId(input.sessionId)) {
387+
return { messages: [] };
388+
}
353389
const projectDirPath = yield* resolveProjectDirPath(input);
354390
const filePath = path.join(projectDirPath, `${input.sessionId}${JSONL_EXTENSION}`);
355391
const raw = yield* fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
@@ -362,31 +398,47 @@ export const make = Effect.gen(function* () {
362398
return { messages: trimmedMessages };
363399
});
364400

365-
const bindResumeSession: ClaudeSessionHistory["Service"]["bindResumeSession"] = Effect.fn(
366-
"ClaudeSessionHistory.bindResumeSession",
367-
)(function* (input) {
368-
const instance = yield* providerInstanceRegistry.getInstance(input.providerInstanceId);
369-
if (!instance) {
370-
return yield* new ProviderValidationError({
371-
operation: "ClaudeSessionHistory.bindResumeSession",
372-
issue: `Provider instance '${input.providerInstanceId}' is not configured.`,
373-
});
374-
}
375-
if (instance.driverKind !== CLAUDE_PROVIDER) {
376-
return yield* new ProviderValidationError({
377-
operation: "ClaudeSessionHistory.bindResumeSession",
378-
issue: `resumeExternalSessionId is only supported for Claude Code provider instances; '${input.providerInstanceId}' is a '${instance.driverKind}' instance.`,
401+
const bindSessionLaunchOptions: ClaudeSessionHistory["Service"]["bindSessionLaunchOptions"] =
402+
Effect.fn("ClaudeSessionHistory.bindSessionLaunchOptions")(function* (input) {
403+
if (input.resumeExternalSessionId === undefined && !input.remoteControl) {
404+
return;
405+
}
406+
if (
407+
input.resumeExternalSessionId !== undefined &&
408+
!isValidClaudeSessionId(input.resumeExternalSessionId)
409+
) {
410+
return yield* new ProviderValidationError({
411+
operation: "ClaudeSessionHistory.bindSessionLaunchOptions",
412+
issue: `resumeExternalSessionId must be a Claude session UUID; received '${input.resumeExternalSessionId}'.`,
413+
});
414+
}
415+
const instance = yield* providerInstanceRegistry.getInstance(input.providerInstanceId);
416+
if (!instance) {
417+
return yield* new ProviderValidationError({
418+
operation: "ClaudeSessionHistory.bindSessionLaunchOptions",
419+
issue: `Provider instance '${input.providerInstanceId}' is not configured.`,
420+
});
421+
}
422+
if (instance.driverKind !== CLAUDE_PROVIDER) {
423+
return yield* new ProviderValidationError({
424+
operation: "ClaudeSessionHistory.bindSessionLaunchOptions",
425+
issue: `Resume/Remote Control are only supported for Claude Code provider instances; '${input.providerInstanceId}' is a '${instance.driverKind}' instance.`,
426+
});
427+
}
428+
yield* providerSessionDirectory.upsert({
429+
threadId: input.threadId,
430+
provider: instance.driverKind,
431+
providerInstanceId: input.providerInstanceId,
432+
resumeCursor: {
433+
...(input.resumeExternalSessionId !== undefined
434+
? { resume: input.resumeExternalSessionId }
435+
: {}),
436+
...(input.remoteControl ? { remoteControl: true } : {}),
437+
},
379438
});
380-
}
381-
yield* providerSessionDirectory.upsert({
382-
threadId: input.threadId,
383-
provider: instance.driverKind,
384-
providerInstanceId: input.providerInstanceId,
385-
resumeCursor: { resume: input.resumeExternalSessionId },
386439
});
387-
});
388440

389-
return ClaudeSessionHistory.of({ list, getTranscript, bindResumeSession });
441+
return ClaudeSessionHistory.of({ list, getTranscript, bindSessionLaunchOptions });
390442
});
391443

392444
export const layer = Layer.effect(ClaudeSessionHistory, make);

‎apps/server/src/server.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ const buildAppUnderTest = (options?: {
613613
Layer.mock(ClaudeSessionHistory.ClaudeSessionHistory)({
614614
list: () => Effect.succeed({ sessions: [] }),
615615
getTranscript: () => Effect.succeed({ messages: [] }),
616-
bindResumeSession: () => Effect.void,
616+
bindSessionLaunchOptions: () => Effect.void,
617617
}),
618618
),
619619
),

‎apps/server/src/ws.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -998,14 +998,16 @@ const makeWsRpcLayer = (
998998
});
999999
createdThread = true;
10001000

1001-
const resumeExternalSessionId = bootstrap.createThread.resumeExternalSessionId;
1002-
if (resumeExternalSessionId) {
1003-
yield* claudeSessionHistory.bindResumeSession({
1004-
threadId: command.threadId,
1005-
providerInstanceId: bootstrap.createThread.modelSelection.instanceId,
1006-
resumeExternalSessionId,
1007-
});
1008-
}
1001+
yield* claudeSessionHistory.bindSessionLaunchOptions({
1002+
threadId: command.threadId,
1003+
providerInstanceId: bootstrap.createThread.modelSelection.instanceId,
1004+
...(bootstrap.createThread.resumeExternalSessionId !== undefined
1005+
? { resumeExternalSessionId: bootstrap.createThread.resumeExternalSessionId }
1006+
: {}),
1007+
...(bootstrap.createThread.remoteControl
1008+
? { remoteControl: bootstrap.createThread.remoteControl }
1009+
: {}),
1010+
});
10091011
}
10101012

10111013
if (bootstrap?.prepareWorktree) {

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 59 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ import {
145145
ChevronDownIcon,
146146
GitBranchIcon,
147147
HistoryIcon,
148+
RadioTowerIcon,
148149
TriangleAlertIcon,
149150
WifiOffIcon,
150151
} from "lucide-react";
@@ -238,6 +239,7 @@ import {
238239
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
239240
import { resolveThreadPr } from "./ThreadStatusIndicators";
240241
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
242+
import { Switch } from "./ui/switch";
241243
import {
242244
DRAFT_HERO_TRANSITION_ANIMATION_ID,
243245
DRAFT_HERO_TRANSITION_DURATION_MS,
@@ -1287,6 +1289,11 @@ function ChatViewContent(props: ChatViewProps) {
12871289
>({});
12881290
const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
12891291
useState<DraftThreadEnvMode | null>(null);
1292+
// Remote Control can only be decided once, at thread creation — it's a
1293+
// launch flag for the session's underlying `claude` process, not
1294+
// something that can be toggled after it's already running. Reset
1295+
// whenever the viewed thread changes so it never leaks between drafts.
1296+
const [draftRemoteControlEnabled, setDraftRemoteControlEnabled] = useState(false);
12901297
const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
12911298
const [
12921299
pendingServerThreadStartFromOriginByThreadId,
@@ -4130,6 +4137,19 @@ function ChatViewContent(props: ChatViewProps) {
41304137
const pendingResumeSessionIntent = useResumeSessionIntentStore((store) =>
41314138
isLocalDraftThread && activeThread ? (store.intentByThreadId[activeThread.id] ?? null) : null,
41324139
);
4140+
const cancelResumeSessionIntent = useCallback((draftThreadId: ThreadId) => {
4141+
// Deliberately NOT wired through ComposerBannerStack's `onDismiss`
4142+
// (dismissLabel/onDismiss): that callback is deferred ~220ms behind an
4143+
// exit animation, and this specific banner's host `ComposerBannerStack`
4144+
// instance can unmount mid-animation when a resume draft docks out of
4145+
// hero layout on send — which drops the deferred callback entirely, so
4146+
// a fast cancel-then-send could still resume. Clearing both stores here,
4147+
// synchronously, from a plain button click closes that race: this
4148+
// `useMemo` reacts to the store instantly and the banner just disappears
4149+
// (no animation needed for correctness, only for polish).
4150+
useResumeSessionIntentStore.getState().clearResumeSessionIntent(draftThreadId);
4151+
useResumeSessionHistoryStore.getState().clearResumeSessionHistory(draftThreadId);
4152+
}, []);
41334153
const resumeSessionBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
41344154
if (!pendingResumeSessionIntent || !isLocalDraftThread || !activeThread) return null;
41354155
const draftThreadId = activeThread.id;
@@ -4139,21 +4159,48 @@ function ChatViewContent(props: ChatViewProps) {
41394159
icon: <HistoryIcon />,
41404160
title: "Resuming a previous Claude session",
41414161
description: pendingResumeSessionIntent.label ?? undefined,
4142-
dismissLabel: "Cancel resume",
4143-
onDismiss: () => {
4144-
useResumeSessionIntentStore.getState().clearResumeSessionIntent(draftThreadId);
4145-
},
4162+
actions: (
4163+
<Button size="xs" variant="ghost" onClick={() => cancelResumeSessionIntent(draftThreadId)}>
4164+
Cancel
4165+
</Button>
4166+
),
4167+
};
4168+
}, [pendingResumeSessionIntent, isLocalDraftThread, activeThread, cancelResumeSessionIntent]);
4169+
const canOfferRemoteControlToggle =
4170+
isLocalDraftThread && selectedProvider === ProviderDriverKind.make("claudeAgent");
4171+
const remoteControlBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
4172+
if (!canOfferRemoteControlToggle) return null;
4173+
return {
4174+
id: "draft-remote-control",
4175+
variant: "info",
4176+
icon: <RadioTowerIcon />,
4177+
title: "Remote Control",
4178+
description: "Attach to this session from claude.ai or the Claude mobile app once it starts.",
4179+
actions: (
4180+
<Switch
4181+
checked={draftRemoteControlEnabled}
4182+
onCheckedChange={(checked) => setDraftRemoteControlEnabled(Boolean(checked))}
4183+
aria-label="Enable Remote Control for this session"
4184+
/>
4185+
),
41464186
};
4147-
}, [pendingResumeSessionIntent, isLocalDraftThread, activeThread]);
4187+
}, [canOfferRemoteControlToggle, draftRemoteControlEnabled]);
41484188
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
41494189
const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];
41504190
const resumeSessionItems = resumeSessionBannerItem === null ? [] : [resumeSessionBannerItem];
4191+
const remoteControlItems = remoteControlBannerItem === null ? [] : [remoteControlBannerItem];
41514192
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
4152-
return [...systemComposerBannerItems, ...resumeSessionItems, ...parkedThreadItems];
4193+
return [
4194+
...systemComposerBannerItems,
4195+
...resumeSessionItems,
4196+
...remoteControlItems,
4197+
...parkedThreadItems,
4198+
];
41534199
}
41544200
return [
41554201
...systemComposerBannerItems,
41564202
...resumeSessionItems,
4203+
...remoteControlItems,
41574204
{
41584205
id: `branch-mismatch:${activeBranchMismatchKey}`,
41594206
variant: "info",
@@ -4198,6 +4245,7 @@ function ChatViewContent(props: ChatViewProps) {
41984245
}, [
41994246
activeBranchMismatchKey,
42004247
resumeSessionBannerItem,
4248+
remoteControlBannerItem,
42014249
handleRestoreThreadBranch,
42024250
isRestoringThreadBranch,
42034251
localCheckoutBranchMismatch,
@@ -4211,6 +4259,10 @@ function ChatViewContent(props: ChatViewProps) {
42114259
setPendingServerThreadBranch(undefined);
42124260
}, [activeThread?.id]);
42134261

4262+
useEffect(() => {
4263+
setDraftRemoteControlEnabled(false);
4264+
}, [activeThread?.id]);
4265+
42144266
useEffect(() => {
42154267
if (canOverrideServerThreadEnvMode) {
42164268
return;
@@ -4791,6 +4843,7 @@ function ChatViewContent(props: ChatViewProps) {
47914843
worktreePath: activeThread.worktreePath,
47924844
createdAt: activeThread.createdAt,
47934845
...(resumeExternalSessionId ? { resumeExternalSessionId } : {}),
4846+
...(draftRemoteControlEnabled ? { remoteControl: true } : {}),
47944847
},
47954848
}
47964849
: {}),

0 commit comments

Comments
 (0)