@devries-cameron20 / t3code-1 / commits / 35c1210331
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix: guest links can load earlier turns (#27354)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 29, 2026 at 22:23 UTC 35c1210331a70fd3f460f9ad3425aed7d9a263cf
8 files changed +262 -3
apps/server/src/guest/GuestShareService.test.ts
+85
@@ -7,6 +7,7 @@ import {
7 GuestShareId,
8 type GuestStreamEvent,
9 MessageId,
10 + type OrchestrationV2ThreadHistoryPage,
11 type OrchestrationV2TurnItem,
12 ProjectId,
13 ProviderDriverKind,
@@ -529,6 +530,90 @@ it.effect("gives the guest a command's detail and output, but no file diffs", ()
530 }).pipe(Effect.provide(layerTest)),
531 );
532
533 +it.effect("pages the guest back through turns older than the stream's snapshot", () =>
534 + Effect.gen(function* () {
535 + const { guestShares, credential } = yield* shareThread;
536 + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" });
537 + const runId = yield* ownerRun;
538 + const fileSystem = yield* FileSystem.FileSystem;
539 + const directory = yield* fileSystem.makeTempDirectoryScoped();
540 + const shot = `${directory}/old.png`;
541 + yield* fileSystem.writeFile(shot, PNG);
542 + const eventSink = yield* EventSink.EventSinkV2;
543 + const now = yield* DateTime.now;
544 + const base = { threadId, runId, nodeId: null, providerThreadId: null, providerTurnId: null };
545 + const turnItem = (id: string, ordinal: number, payload: object) => ({
546 + id: EventId.make(`event:${id}`),
547 + type: "turn-item.updated" as const,
548 + threadId,
549 + driver: ProviderDriverKind.make("codex"),
550 + providerInstanceId: instanceId,
551 + occurredAt: now,
552 + payload: {
553 + ...base,
554 + id: TurnItemId.make(id),
555 + nativeItemRef: null,
556 + parentItemId: null,
557 + ordinal,
558 + title: null,
559 + status: "completed" as const,
560 + startedAt: now,
561 + completedAt: now,
562 + updatedAt: now,
563 + messageId: MessageId.make(id),
564 + ...payload,
565 + } as OrchestrationV2TurnItem,
566 + });
567 + yield* eventSink.write({
568 + events: [
569 + turnItem("item:old-image", 1, {
570 + type: "assistant_message",
571 + text: `![Old](${shot})`,
572 + streaming: false,
573 + }),
574 + ...Array.from({ length: 30 }, (_, index) =>
575 + turnItem(`item:ask-${index}`, index + 2, {
576 + type: "user_message",
577 + text: `Ask ${index}`,
578 + createdBy: "user",
579 + creationSource: "web",
580 + inputIntent: "turn_start",
581 + attachments: [],
582 + }),
583 + ),
584 + ],
585 + });
586 +
587 + const [, opening] = Array.from(
588 + yield* Stream.runCollect(Stream.take(yield* guestShares.stream(session), 2)),
589 + );
590 + if (opening?.type !== "thread" || opening.item.kind !== "snapshot") {
591 + return assert.fail("Expected the thread snapshot second.");
592 + }
593 + const ids = (rows: ReadonlyArray<{ readonly sourceItemId: string }>) =>
594 + rows.map((row) => row.sourceItemId);
595 + assert.notInclude(ids(opening.item.projection.visibleTurnItems), "item:old-image");
596 + let cursor = opening.item.historyCursor ?? null;
597 + assert.isNotNull(cursor);
598 + // The page has not shown the old reply yet, so its image does not load.
599 + assert.equal((yield* Effect.flip(guestShares.media(session, shot))).reason, "unavailable");
600 + // Only a session pages.
601 + assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.history(credential, cursor!))));
602 +
603 + const older: Array<string> = [];
604 + while (cursor !== null) {
605 + const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor);
606 + older.push(...ids(page.items));
607 + cursor = page.hasMoreHistory ? page.nextCursor : null;
608 + }
609 + assert.include(older, "item:old-image");
610 + assert.deepStrictEqual(yield* guestShares.media(session, shot), {
611 + path: shot,
612 + mimeType: "image/png",
613 + });
614 + }).pipe(Effect.scoped, Effect.provide(layerTest)),
615 +);
616 +
617 it.effect("ends a running command's output once the owner stops sharing", () =>
618 Effect.gen(function* () {
619 const { orchestrator, guestShares, credential } = yield* shareThread;
apps/server/src/guest/GuestShareService.ts
+22
@@ -15,6 +15,7 @@ import {
15 type OrchestrationV2CommandOutputFrame,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2GetTurnItemResult,
18 + type OrchestrationV2ThreadHistoryPage,
19 type OrchestrationV2TurnItem,
20 ThreadId,
21 TurnItemId,
@@ -185,6 +186,11 @@ export class GuestShareService extends Context.Service<
186 session: string,
187 itemId: string,
188 ) => Effect.Effect<OrchestrationV2GetTurnItemResult, GuestShareAccessError>;
189 + /** Older turns of the shared thread, as the owner's client pages them. */
190 + readonly history: (
191 + session: string,
192 + cursor: string,
193 + ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, GuestShareAccessError>;
194 /** A command's output frames, as the owner's expanded row gets them, until the link ends. */
195 readonly commandOutput: (
196 session: string,
@@ -665,6 +671,21 @@ const make = Effect.gen(function* () {
671 };
672 });
673
674 + const history = Effect.fn("GuestShareService.history")(function* (
675 + session: string,
676 + cursor: string,
677 + ) {
678 + const { thread, share } = yield* authorize(session, "session");
679 + const page = yield* orchestrator
680 + .getThreadHistoryPage(thread.id, cursor)
681 + .pipe(Effect.mapError(() => unavailable));
682 + rememberSent(
683 + share.id,
684 + page.items.map((row) => row.item),
685 + );
686 + return page;
687 + });
688 +
689 const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
690 session: string,
691 itemId: string,
@@ -739,6 +760,7 @@ const make = Effect.gen(function* () {
760 stream,
761 render,
762 item,
763 + history,
764 commandOutput,
765 attachment,
766 media,
apps/server/src/guest/http.ts
+24
@@ -1,6 +1,7 @@
1 import {
2 GUEST_ATTACHMENT_ROUTE,
3 GUEST_COMMAND_OUTPUT_ROUTE,
4 + GUEST_HISTORY_ROUTE,
5 GUEST_ITEM_ROUTE,
6 GUEST_MEDIA_ROUTE,
7 GUEST_RENDER_ROUTE,
@@ -16,6 +17,7 @@ import {
17 isProviderSendTurnSupportedImageMimeType,
18 OrchestrationV2CommandOutputFrame,
19 OrchestrationV2GetTurnItemResult,
20 + OrchestrationV2ThreadHistoryPage,
21 } from "@t3tools/contracts";
22 import * as ByteSize from "effect/ByteSize";
23 import * as Duration from "effect/Duration";
@@ -52,6 +54,7 @@ const encodeOutputFrame = Schema.encodeEffect(
54 Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
55 );
56 const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
57 +const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
58
59 const errorResponse = (error: GuestShareAccessError) =>
60 HttpServerResponse.json(
@@ -292,6 +295,26 @@ const itemRoute = HttpRouter.add(
295 }),
296 );
297
298 +const historyRoute = HttpRouter.add(
299 + "GET",
300 + GUEST_HISTORY_ROUTE,
301 + Effect.gen(function* () {
302 + const request = yield* HttpServerRequest.HttpServerRequest;
303 + const cursor = new URLSearchParams(request.url.split("?", 2)[1] ?? "").get("cursor");
304 + if (!cursor) return yield* badRequest;
305 + const guestShares = yield* GuestShareService;
306 + return yield* guestShares.history(yield* sessionToken, cursor).pipe(
307 + Effect.flatMap((page) =>
308 + encodeHistoryPage(page).pipe(
309 + Effect.mapError(() => new GuestShareAccessError({ reason: "unavailable" })),
310 + ),
311 + ),
312 + Effect.map((body) => HttpServerResponse.jsonUnsafe(body, { headers: NO_STORE })),
313 + Effect.catchTags({ GuestShareAccessError: errorResponse }),
314 + );
315 + }),
316 +);
317 +
318 // Ends when the command settles; the page closes its EventSource on that last frame, so the
319 // browser does not reconnect.
320 const commandOutputRoute = HttpRouter.add(
@@ -365,6 +388,7 @@ export const layer = Layer.mergeAll(
388 streamRoute,
389 renderRoute,
390 itemRoute,
391 + historyRoute,
392 commandOutputRoute,
393 attachmentRoute,
394 mediaRoute,
apps/web/src/components/guest/GuestPage.tsx
+59 -1
@@ -1,6 +1,7 @@
1 import {
2 EnvironmentId,
3 GUEST_MESSAGE_MAX_LENGTH,
4 + GUEST_HISTORY_ROUTE,
5 GUEST_NAME_MAX_LENGTH,
6 GUEST_ROUTE_PREFIX,
7 GUEST_SHARE_PARAM,
@@ -8,6 +9,7 @@ import {
9 type GuestRedeemRequest,
10 type GuestShareView,
11 type GuestThreadModel,
12 + OrchestrationV2ThreadHistoryPage,
13 type OrchestrationV2ThreadProjection,
14 type ThreadGuestMessage,
15 type ThreadGuestMessageStatus,
@@ -46,7 +48,7 @@ import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";
48 import { HostImageUrlContext } from "../chat/hostImageUrl";
49 import { PierreEntryIcon } from "../chat/PierreEntryIcon";
50 import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";
49 -import { MessagesTimeline } from "../chat/MessagesTimeline";
51 +import { MessagesTimeline, type MessagesTimelineHistoryControls } from "../chat/MessagesTimeline";
52 import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
53 import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils";
54 import { ScrollToEndButton } from "../chat/TimelineOverlays";
@@ -131,6 +133,32 @@ function takeGuestEntry(): GuestEntry {
133 }
134
135 const decodeErrorBody = Schema.decodeUnknownOption(Schema.Struct({ message: Schema.String }));
136 +const decodeHistoryPage = Schema.decodeUnknownOption(
137 + Schema.toCodecJson(OrchestrationV2ThreadHistoryPage),
138 +);
139 +
140 +/** Resolves to the page, or to a message the guest can read. */
141 +async function fetchGuestHistoryPage(
142 + shareId: string,
143 + cursor: string,
144 +): Promise<OrchestrationV2ThreadHistoryPage | string> {
145 + const failed = "Could not load earlier turns. Try again.";
146 + try {
147 + const response = await fetch(
148 + `${GUEST_HISTORY_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&cursor=${encodeURIComponent(cursor)}`,
149 + );
150 + const json: unknown = await response.json().catch(() => null);
151 + if (!response.ok) {
152 + return Option.match(decodeErrorBody(json), {
153 + onNone: () => failed,
154 + onSome: ({ message }) => message,
155 + });
156 + }
157 + return Option.getOrElse(decodeHistoryPage(json), () => failed);
158 + } catch {
159 + return "Could not reach the server.";
160 + }
161 +}
162
163 /** Resolves to null on success, or to a message the guest can read. */
164 async function postGuest(
@@ -241,6 +269,32 @@ function GuestSession({ shareId }: { readonly shareId: string }) {
269 // missing, invalid, or ended session. Network drops reconnect on their own.
270 const [rejected, setRejected] = useState(false);
271
272 + const [historyLoad, setHistoryLoad] = useState<{
273 + readonly cursor: string;
274 + readonly error: string | null;
275 + } | null>(null);
276 + const historyCursor = stream.historyCursor;
277 + // A load for an older cursor is stale: a page or a reconnect snapshot moved the cursor on.
278 + const currentLoad = historyLoad?.cursor === historyCursor ? historyLoad : null;
279 + const loadingHistory = currentLoad !== null && currentLoad.error === null;
280 + const historyError = currentLoad?.error ?? null;
281 + const loadEarlier = async () => {
282 + if (historyCursor === null || loadingHistory) return;
283 + setHistoryLoad({ cursor: historyCursor, error: null });
284 + const result = await fetchGuestHistoryPage(shareId, historyCursor);
285 + if (typeof result === "string") setHistoryLoad({ cursor: historyCursor, error: result });
286 + else dispatch({ type: "history-page", cursor: historyCursor, page: result });
287 + };
288 + const historyControls: MessagesTimelineHistoryControls | undefined =
289 + historyCursor === null
290 + ? undefined
291 + : {
292 + hasMoreHistory: true,
293 + loading: loadingHistory,
294 + error: historyError,
295 + onLoadEarlier: () => void loadEarlier(),
296 + };
297 +
298 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets document.title to the shared thread's title
299 useEffect(() => {
300 if (stream.view) document.title = stream.view.title;
@@ -273,6 +327,7 @@ function GuestSession({ shareId }: { readonly shareId: string }) {
327 view={stream.view}
328 projection={stream.projection}
329 awaitingRowIds={stream.awaitingRowIds}
330 + historyControls={historyControls}
331 />
332 );
333 }
@@ -358,10 +413,12 @@ function GuestThread({
413 view: { shareId, title, expiresAt, messages, model },
414 projection,
415 awaitingRowIds,
416 + historyControls,
417 }: {
418 readonly view: GuestShareView;
419 readonly projection: OrchestrationV2ThreadProjection;
420 readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];
421 + readonly historyControls: MessagesTimelineHistoryControls | undefined;
422 }) {
423 // No ":" so the timeline finds no environment thread behind the key.
424 const threadKey = `guest-${shareId}`;
@@ -467,6 +524,7 @@ function GuestThread({
524 onFileDownload={openFile}
525 renderHtmlRender={renderHtmlRender}
526 turnItemSource={turnItemSource}
527 + historyControls={historyControls}
528 activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}
529 markdownCwd={undefined}
530 resolvedTheme={resolvedTheme}
apps/web/src/components/guest/guestStream.logic.test.ts
+39
@@ -112,6 +112,45 @@ describe("applyGuestStreamEvent", () => {
112 expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once);
113 });
114
115 + it("merges older pages in front, only for the cursor the thread is at", () => {
116 + const windowed: GuestStreamEvent = {
117 + type: "thread",
118 + item: {
119 + kind: "snapshot",
120 + snapshotSequence: 1,
121 + projection,
122 + historyCursor: "cursor-1",
123 + hasMoreHistory: true,
124 + },
125 + };
126 + const page = (id: string, nextCursor: string | null) => ({
127 + snapshotSequence: 1,
128 + items: [
129 + {
130 + position: 0,
131 + visibility: "local" as const,
132 + sourceThreadId: projection.thread.id,
133 + sourceItemId: TurnItemId.make(id),
134 + item: reply(id, "Earlier"),
135 + },
136 + ],
137 + nextCursor,
138 + hasMoreHistory: nextCursor !== null,
139 + });
140 + const live = apply([windowed, itemEvent(2, reply("a1", "Hi"))]);
141 + expect(live.historyCursor).toBe("cursor-1");
142 + // A page fetched before a reconnect moved the cursor changes nothing.
143 + const stale = { type: "history-page" as const, cursor: "cursor-0", page: page("old", null) };
144 + expect(applyGuestStreamEvent(live, stale)).toBe(live);
145 + const merged = applyGuestStreamEvent(live, {
146 + type: "history-page",
147 + cursor: "cursor-1",
148 + page: page("o1", null),
149 + });
150 + expect(itemIds(merged)).toEqual(["o1", "a1"]);
151 + expect(merged.historyCursor).toBeNull();
152 + });
153 +
154 it("replaces the thread on a new snapshot, as after a reconnect", () => {
155 const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]);
156 const after = apply([snapshot(1)], { ...before, ended: false });
apps/web/src/components/guest/guestStream.logic.ts
+24 -2
@@ -9,11 +9,13 @@ import {
9 type GuestMessageId,
10 type GuestShareView,
11 type OrchestrationV2ProjectedTurnItem,
12 + type OrchestrationV2ThreadHistoryPage,
13 type OrchestrationV2ThreadProjection,
14 type OrchestrationV2TurnItem,
15 type ThreadGuestMessage,
16 } from "@t3tools/contracts";
17 import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection";
18 +import { mergeOlderHistoryIntoProjection } from "@t3tools/client-runtime/state/thread-history-merge";
19 import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
20 import * as Option from "effect/Option";
21 import * as Schema from "effect/Schema";
@@ -25,6 +27,8 @@ export interface GuestStreamState {
27 readonly sequence: number;
28 /** Set while the snapshot is a window of a longer history, as the owner's client tracks it. */
29 readonly partial: { readonly latestLocalTurnOrdinal: number | null } | null;
30 + /** Where "Load earlier turns" continues, or null once the whole thread is loaded. */
31 + readonly historyCursor: string | null;
32 readonly ended: boolean;
33 /**
34 * Messages this page saw waiting that have no transcript row yet. Survives reconnects, and a
@@ -38,6 +42,7 @@ export const initialGuestStreamState: GuestStreamState = {
42 projection: null,
43 sequence: 0,
44 partial: null,
45 + historyCursor: null,
46 ended: false,
47 awaitingRowIds: new Set(),
48 };
@@ -76,16 +81,32 @@ const decodeGuestStreamEvent = Schema.decodeUnknownOption(
81 export const parseGuestStreamEvent = (data: string): GuestStreamEvent | null =>
82 Option.getOrNull(decodeGuestStreamEvent(data));
83
84 +/** A page of older turns, fetched from `cursor`. */
85 +export type GuestHistoryPageLoaded = {
86 + readonly type: "history-page";
87 + readonly cursor: string;
88 + readonly page: OrchestrationV2ThreadHistoryPage;
89 +};
90 +
91 /**
92 * Applies the owner's thread stream the way the owner's client does (see
93 * EnvironmentThreadState in client-runtime): a snapshot replaces the thread, and later events
82 - * pass through the same projection reducer, once each.
94 + * pass through the same projection reducer, once each. Older pages merge in front, as they do in
95 + * the owner's view.
96 */
97 export function applyGuestStreamEvent(
98 state: GuestStreamState,
86 - event: GuestStreamEvent,
99 + event: GuestStreamEvent | GuestHistoryPageLoaded,
100 ): GuestStreamState {
101 switch (event.type) {
102 + case "history-page":
103 + // A snapshot since the request replaced the thread and its cursor.
104 + if (state.projection === null || state.historyCursor !== event.cursor) return state;
105 + return {
106 + ...state,
107 + projection: mergeOlderHistoryIntoProjection(state.projection, event.page.items),
108 + historyCursor: event.page.hasMoreHistory ? event.page.nextCursor : null,
109 + };
110 case "view":
111 // The page follows the share it names; a view of another one means the link changed.
112 if (state.view !== null && state.view.shareId !== event.view.shareId) {
@@ -108,6 +129,7 @@ export function applyGuestStreamEvent(
129 item.hasMoreHistory === true || (item.historyCursor ?? null) !== null
130 ? { latestLocalTurnOrdinal: item.latestLocalTurnOrdinal ?? null }
131 : null,
132 + historyCursor: item.hasMoreHistory === true ? (item.historyCursor ?? null) : null,
133 awaitingRowIds: withoutPlaced(
134 state.awaitingRowIds,
135 projection.visibleTurnItems.map((row) => row.item),
packages/client-runtime/package.json
+4
@@ -203,6 +203,10 @@
203 "types": "./src/state/orchestration.ts",
204 "default": "./src/state/orchestration.ts"
205 },
206 + "./state/thread-history-merge": {
207 + "types": "./src/state/threadHistoryMerge.ts",
208 + "default": "./src/state/threadHistoryMerge.ts"
209 + },
210 "./state/orchestration-v2-projection": {
211 "types": "./src/state/orchestrationV2Projection.ts",
212 "default": "./src/state/orchestrationV2Projection.ts"
packages/contracts/src/guestShare.ts
+5
@@ -129,6 +129,11 @@ export const guestSessionCookieName = (shareId: string) => `t3_guest_${shareId}`
129 export const GUEST_RENDER_ROUTE = `${GUEST_ROUTE_PREFIX}/render`;
130 /** One item of the shared thread, as an expanded row loads it: `?share=<share id>&item=<id>`. */
131 export const GUEST_ITEM_ROUTE = `${GUEST_ROUTE_PREFIX}/item`;
132 +/**
133 + * Older turns of the shared thread, as the owner's "Load earlier turns" pages them:
134 + * `?share=<share id>&cursor=<history cursor>`.
135 + */
136 +export const GUEST_HISTORY_ROUTE = `${GUEST_ROUTE_PREFIX}/history`;
137 /** Server-sent output frames of one command in the shared thread: `?share=<share id>&item=<id>`. */
138 export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output`;
139 /**