Skip to content

Commit 2d46275

Browse files
committed
feat: refresh a resumed thread's imported history when reopened
If you resume a Claude session into a T3 thread and then keep chatting with that same session directly in a terminal (claude --resume <id>), T3 previously had no way to see those messages short of re-resuming from scratch. Adds serverGetClaudeThreadImportedHistory, which resolves a thread's bound session id server-side from its ProviderSessionDirectory binding and re-reads the on-disk transcript. The client calls it whenever a resumed thread is opened/switched to, merging in only messages newer than everything T3 already knows about (its own driven turns plus the original import) so nothing gets duplicated.
1 parent a7b4ef0 commit 2d46275

9 files changed

Lines changed: 146 additions & 0 deletions

File tree

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ import {
3535
type ServerClaudeResumableSessionMessage,
3636
type ServerGetClaudeResumableSessionTranscriptInput,
3737
type ServerGetClaudeResumableSessionTranscriptResult,
38+
type ServerGetClaudeThreadImportedHistoryInput,
39+
type ServerGetClaudeThreadImportedHistoryResult,
3840
type ServerListClaudeResumableSessionsInput,
3941
type ServerListClaudeResumableSessionsResult,
4042
type ServerSetClaudeThreadRemoteControlInput,
@@ -262,6 +264,18 @@ export class ClaudeSessionHistory extends Context.Service<
262264
readonly getTranscript: (
263265
input: ServerGetClaudeResumableSessionTranscriptInput,
264266
) => Effect.Effect<ServerGetClaudeResumableSessionTranscriptResult>;
267+
/**
268+
* Re-reads a resumed thread's bound on-disk transcript, resolving the
269+
* bound session id from the thread's `ProviderSessionDirectory`
270+
* binding server-side (the caller only needs to know the thread, not
271+
* which session it's bound to). Returns `{messages: []}` — not an
272+
* error — when the thread has no bound `resume` session (never
273+
* resumed) or the binding can't be read, matching `getTranscript`'s
274+
* best-effort behavior.
275+
*/
276+
readonly getImportedHistoryForThread: (
277+
input: ServerGetClaudeThreadImportedHistoryInput,
278+
) => Effect.Effect<ServerGetClaudeThreadImportedHistoryResult>;
265279
/**
266280
* Binds thread-creation-time Claude launch choices (resume a picked
267281
* on-disk session, and/or start with Remote Control enabled) onto a
@@ -420,6 +434,26 @@ export const make = Effect.gen(function* () {
420434
return { messages: trimmedMessages };
421435
});
422436

437+
const getImportedHistoryForThread: ClaudeSessionHistory["Service"]["getImportedHistoryForThread"] =
438+
Effect.fn("ClaudeSessionHistory.getImportedHistoryForThread")(function* (input) {
439+
const binding = yield* providerSessionDirectory
440+
.getBinding(input.threadId)
441+
.pipe(Effect.orElseSucceed(() => Option.none()));
442+
const resumeCursor = Option.getOrUndefined(binding)?.resumeCursor;
443+
const resumeSessionId =
444+
resumeCursor !== null && typeof resumeCursor === "object" && resumeCursor !== undefined
445+
? (resumeCursor as Record<string, unknown>).resume
446+
: undefined;
447+
if (typeof resumeSessionId !== "string") {
448+
return { messages: [] };
449+
}
450+
return yield* getTranscript({
451+
workspaceRoot: input.workspaceRoot,
452+
providerInstanceId: input.providerInstanceId,
453+
sessionId: resumeSessionId,
454+
});
455+
});
456+
423457
const bindSessionLaunchOptions: ClaudeSessionHistory["Service"]["bindSessionLaunchOptions"] =
424458
Effect.fn("ClaudeSessionHistory.bindSessionLaunchOptions")(function* (input) {
425459
if (input.resumeExternalSessionId === undefined && input.remoteControl === undefined) {
@@ -493,6 +527,7 @@ export const make = Effect.gen(function* () {
493527
return ClaudeSessionHistory.of({
494528
list,
495529
getTranscript,
530+
getImportedHistoryForThread,
496531
bindSessionLaunchOptions,
497532
setThreadRemoteControl,
498533
});

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -613,6 +613,7 @@ const buildAppUnderTest = (options?: {
613613
Layer.mock(ClaudeSessionHistory.ClaudeSessionHistory)({
614614
list: () => Effect.succeed({ sessions: [] }),
615615
getTranscript: () => Effect.succeed({ messages: [] }),
616+
getImportedHistoryForThread: () => Effect.succeed({ messages: [] }),
616617
bindSessionLaunchOptions: () => Effect.void,
617618
setThreadRemoteControl: () => Effect.succeed({ applied: true }),
618619
}),

‎apps/server/src/ws.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
309309
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
310310
[WS_METHODS.serverListClaudeResumableSessions, AuthOrchestrationReadScope],
311311
[WS_METHODS.serverGetClaudeResumableSessionTranscript, AuthOrchestrationReadScope],
312+
[WS_METHODS.serverGetClaudeThreadImportedHistory, AuthOrchestrationReadScope],
312313
[WS_METHODS.serverSetClaudeThreadRemoteControl, AuthOrchestrationOperateScope],
313314
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
314315
[WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope],
@@ -1584,6 +1585,14 @@ const makeWsRpcLayer = (
15841585
"rpc.aggregate": "server",
15851586
},
15861587
),
1588+
[WS_METHODS.serverGetClaudeThreadImportedHistory]: (input) =>
1589+
observeRpcEffect(
1590+
WS_METHODS.serverGetClaudeThreadImportedHistory,
1591+
claudeSessionHistory.getImportedHistoryForThread(input),
1592+
{
1593+
"rpc.aggregate": "server",
1594+
},
1595+
),
15871596
[WS_METHODS.serverSetClaudeThreadRemoteControl]: (input) =>
15881597
observeRpcEffect(
15891598
WS_METHODS.serverSetClaudeThreadRemoteControl,

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

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,6 +1145,10 @@ function ChatViewContent(props: ChatViewProps) {
11451145
serverEnvironment.setClaudeThreadRemoteControl,
11461146
{ reportFailure: false },
11471147
);
1148+
const getClaudeThreadImportedHistory = useAtomCommand(
1149+
serverEnvironment.getClaudeThreadImportedHistory,
1150+
{ reportFailure: false },
1151+
);
11481152
const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
11491153
const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
11501154
const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");
@@ -2279,6 +2283,8 @@ function ChatViewContent(props: ChatViewProps) {
22792283
}
22802284
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
22812285
}, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);
2286+
const timelineMessagesRef = useRef(timelineMessages);
2287+
timelineMessagesRef.current = timelineMessages;
22822288
const importedResumeHistoryMessages = useResumeSessionHistoryStore((store) =>
22832289
activeThread
22842290
? (store.historyByThreadId[activeThread.id] ?? EMPTY_RESUME_HISTORY)
@@ -2301,6 +2307,53 @@ function ChatViewContent(props: ChatViewProps) {
23012307
}));
23022308
return [...importedChatMessages, ...timelineMessages];
23032309
}, [importedResumeHistoryMessages, timelineMessages]);
2310+
useEffect(() => {
2311+
if (!activeThread || isLocalDraftThread || !activeProject) return;
2312+
if (selectedProvider !== ProviderDriverKind.make("claudeAgent")) return;
2313+
const threadId = activeThread.id;
2314+
const instanceId = activeThread.modelSelection.instanceId;
2315+
const workspaceRoot = activeProject.workspaceRoot;
2316+
let cancelled = false;
2317+
void (async () => {
2318+
const result = await getClaudeThreadImportedHistory({
2319+
environmentId,
2320+
input: { threadId, workspaceRoot, providerInstanceId: instanceId },
2321+
});
2322+
if (cancelled || result._tag === "Failure") return;
2323+
const fetchedMessages = result.value.messages;
2324+
if (fetchedMessages.length === 0) return;
2325+
const { historyByThreadId, setResumeSessionHistory } =
2326+
useResumeSessionHistoryStore.getState();
2327+
const existingImported = historyByThreadId[threadId] ?? EMPTY_RESUME_HISTORY;
2328+
// Re-fetching returns the on-disk transcript's FULL current state, so
2329+
// it also includes every turn T3 itself has already driven for this
2330+
// thread (they're all written to the same file by the same `claude`
2331+
// process) — only messages newer than everything T3 already knows
2332+
// about (either from the original import, or its own live timeline)
2333+
// are actually new content from a session continued directly in the
2334+
// CLI. Anything at/before that point would otherwise show up twice.
2335+
const latestKnownCreatedAt = [...existingImported, ...timelineMessagesRef.current].reduce(
2336+
(max, message) => (message.createdAt > max ? message.createdAt : max),
2337+
"",
2338+
);
2339+
const newMessages = fetchedMessages.filter(
2340+
(message) => message.createdAt > latestKnownCreatedAt,
2341+
);
2342+
if (newMessages.length === 0) return;
2343+
const merged = [...existingImported, ...newMessages].sort((a, b) =>
2344+
a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0,
2345+
);
2346+
setResumeSessionHistory(threadId, merged);
2347+
})();
2348+
return () => {
2349+
cancelled = true;
2350+
};
2351+
// Deliberately keyed on activeThread.id (not on timelineMessages, which
2352+
// changes constantly while streaming) — this is a refresh-on-open, not
2353+
// a live poll. Current timeline/imported state is read fresh via
2354+
// `timelineMessagesRef`/`getState()` when the fetch resolves.
2355+
// eslint-disable-next-line react-hooks/exhaustive-deps
2356+
}, [activeThread?.id, isLocalDraftThread, activeProject, selectedProvider, environmentId]);
23042357
const timelineEntries = useMemo(
23052358
() =>
23062359
deriveTimelineEntries(

‎apps/web/src/localApi.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ function createBrowserLocalApi(): LocalApi {
7777
getProcessResourceHistory: () => Promise.reject(unavailableLocalBackendError()),
7878
listClaudeResumableSessions: () => Promise.reject(unavailableLocalBackendError()),
7979
getClaudeResumableSessionTranscript: () => Promise.reject(unavailableLocalBackendError()),
80+
getClaudeThreadImportedHistory: () => Promise.reject(unavailableLocalBackendError()),
8081
setClaudeThreadRemoteControl: () => Promise.reject(unavailableLocalBackendError()),
8182
signalProcess: () => Promise.reject(unavailableLocalBackendError()),
8283
},

‎packages/client-runtime/src/state/server.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,10 @@ export function createServerEnvironmentAtoms<R, E>(
306306
label: "environment-data:server:get-claude-resumable-session-transcript",
307307
tag: WS_METHODS.serverGetClaudeResumableSessionTranscript,
308308
}),
309+
getClaudeThreadImportedHistory: createEnvironmentRpcCommand(runtime, {
310+
label: "environment-data:server:get-claude-thread-imported-history",
311+
tag: WS_METHODS.serverGetClaudeThreadImportedHistory,
312+
}),
309313
setClaudeThreadRemoteControl: createEnvironmentRpcCommand(runtime, {
310314
label: "environment-data:server:set-claude-thread-remote-control",
311315
tag: WS_METHODS.serverSetClaudeThreadRemoteControl,

‎packages/contracts/src/ipc.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ import type {
4141
ServerProcessDiagnosticsResult,
4242
ServerProcessResourceHistoryInput,
4343
ServerProcessResourceHistoryResult,
44+
ServerGetClaudeThreadImportedHistoryInput,
45+
ServerGetClaudeThreadImportedHistoryResult,
4446
ServerProviderUpdateInput,
4547
ServerProviderUpdatedPayload,
4648
ServerRemoveKeybindingResult,
@@ -1166,6 +1168,9 @@ export interface LocalApi {
11661168
getClaudeResumableSessionTranscript: (
11671169
input: ServerGetClaudeResumableSessionTranscriptInput,
11681170
) => Promise<ServerGetClaudeResumableSessionTranscriptResult>;
1171+
getClaudeThreadImportedHistory: (
1172+
input: ServerGetClaudeThreadImportedHistoryInput,
1173+
) => Promise<ServerGetClaudeThreadImportedHistoryResult>;
11691174
setClaudeThreadRemoteControl: (
11701175
input: ServerSetClaudeThreadRemoteControlInput,
11711176
) => Promise<ServerSetClaudeThreadRemoteControlResult>;

‎packages/contracts/src/rpc.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ import {
133133
ServerListClaudeResumableSessionsResult,
134134
ServerGetClaudeResumableSessionTranscriptInput,
135135
ServerGetClaudeResumableSessionTranscriptResult,
136+
ServerGetClaudeThreadImportedHistoryInput,
137+
ServerGetClaudeThreadImportedHistoryResult,
136138
ServerSetClaudeThreadRemoteControlInput,
137139
ServerSetClaudeThreadRemoteControlResult,
138140
ServerSignalProcessInput,
@@ -225,6 +227,7 @@ export const WS_METHODS = {
225227
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
226228
serverListClaudeResumableSessions: "server.listClaudeResumableSessions",
227229
serverGetClaudeResumableSessionTranscript: "server.getClaudeResumableSessionTranscript",
230+
serverGetClaudeThreadImportedHistory: "server.getClaudeThreadImportedHistory",
228231
serverSetClaudeThreadRemoteControl: "server.setClaudeThreadRemoteControl",
229232
serverSignalProcess: "server.signalProcess",
230233

@@ -355,6 +358,15 @@ export const WsServerGetClaudeResumableSessionTranscriptRpc = Rpc.make(
355358
},
356359
);
357360

361+
export const WsServerGetClaudeThreadImportedHistoryRpc = Rpc.make(
362+
WS_METHODS.serverGetClaudeThreadImportedHistory,
363+
{
364+
payload: ServerGetClaudeThreadImportedHistoryInput,
365+
success: ServerGetClaudeThreadImportedHistoryResult,
366+
error: EnvironmentAuthorizationError,
367+
},
368+
);
369+
358370
export const WsServerSetClaudeThreadRemoteControlRpc = Rpc.make(
359371
WS_METHODS.serverSetClaudeThreadRemoteControl,
360372
{
@@ -750,6 +762,7 @@ export const WsRpcGroup = RpcGroup.make(
750762
WsServerGetProcessResourceHistoryRpc,
751763
WsServerListClaudeResumableSessionsRpc,
752764
WsServerGetClaudeResumableSessionTranscriptRpc,
765+
WsServerGetClaudeThreadImportedHistoryRpc,
753766
WsServerSetClaudeThreadRemoteControlRpc,
754767
WsServerSignalProcessRpc,
755768
WsCloudGetRelayClientStatusRpc,

‎packages/contracts/src/server.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,31 @@ export const ServerGetClaudeResumableSessionTranscriptResult = Schema.Struct({
455455
export type ServerGetClaudeResumableSessionTranscriptResult =
456456
typeof ServerGetClaudeResumableSessionTranscriptResult.Type;
457457

458+
/**
459+
* Re-reads a resumed thread's bound on-disk Claude session transcript, for
460+
* threads created via the "resume a previous session" flow. The thread may
461+
* have gained messages since it was first imported — e.g. the user
462+
* continued the same underlying Claude session directly in a terminal
463+
* (`claude --resume <id>`) — so this is called again each time the thread
464+
* is opened. Resolves the thread's bound session id server-side (from its
465+
* `ProviderSessionDirectory` binding); returns `{messages: []}` if the
466+
* thread was never resumed (no bound session) rather than an error, since
467+
* that's the common case for most threads.
468+
*/
469+
export const ServerGetClaudeThreadImportedHistoryInput = Schema.Struct({
470+
threadId: ThreadId,
471+
workspaceRoot: TrimmedNonEmptyString,
472+
providerInstanceId: Schema.optional(ProviderInstanceId),
473+
});
474+
export type ServerGetClaudeThreadImportedHistoryInput =
475+
typeof ServerGetClaudeThreadImportedHistoryInput.Type;
476+
477+
export const ServerGetClaudeThreadImportedHistoryResult = Schema.Struct({
478+
messages: Schema.Array(ServerClaudeResumableSessionMessage),
479+
});
480+
export type ServerGetClaudeThreadImportedHistoryResult =
481+
typeof ServerGetClaudeThreadImportedHistoryResult.Type;
482+
458483
/**
459484
* Turns Remote Control on/off for an already-created Claude Code thread
460485
* (as opposed to `ThreadTurnStartBootstrapCreateThread.remoteControl`,

0 commit comments

Comments
 (0)