Skip to content

Commit 35c1210

Browse files
fix: guest links can load earlier turns (#27354)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 6b1245c commit 35c1210

8 files changed

Lines changed: 262 additions & 3 deletions

File tree

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

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
GuestShareId,
88
type GuestStreamEvent,
99
MessageId,
10+
type OrchestrationV2ThreadHistoryPage,
1011
type OrchestrationV2TurnItem,
1112
ProjectId,
1213
ProviderDriverKind,
@@ -529,6 +530,90 @@ it.effect("gives the guest a command's detail and output, but no file diffs", ()
529530
}).pipe(Effect.provide(layerTest)),
530531
);
531532

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+
532617
it.effect("ends a running command's output once the owner stops sharing", () =>
533618
Effect.gen(function* () {
534619
const { orchestrator, guestShares, credential } = yield* shareThread;

‎apps/server/src/guest/GuestShareService.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type OrchestrationV2CommandOutputFrame,
1616
type OrchestrationV2DomainEvent,
1717
type OrchestrationV2GetTurnItemResult,
18+
type OrchestrationV2ThreadHistoryPage,
1819
type OrchestrationV2TurnItem,
1920
ThreadId,
2021
TurnItemId,
@@ -185,6 +186,11 @@ export class GuestShareService extends Context.Service<
185186
session: string,
186187
itemId: string,
187188
) => 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>;
188194
/** A command's output frames, as the owner's expanded row gets them, until the link ends. */
189195
readonly commandOutput: (
190196
session: string,
@@ -665,6 +671,21 @@ const make = Effect.gen(function* () {
665671
};
666672
});
667673

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+
668689
const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* (
669690
session: string,
670691
itemId: string,
@@ -739,6 +760,7 @@ const make = Effect.gen(function* () {
739760
stream,
740761
render,
741762
item,
763+
history,
742764
commandOutput,
743765
attachment,
744766
media,

‎apps/server/src/guest/http.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
GUEST_ATTACHMENT_ROUTE,
33
GUEST_COMMAND_OUTPUT_ROUTE,
4+
GUEST_HISTORY_ROUTE,
45
GUEST_ITEM_ROUTE,
56
GUEST_MEDIA_ROUTE,
67
GUEST_RENDER_ROUTE,
@@ -16,6 +17,7 @@ import {
1617
isProviderSendTurnSupportedImageMimeType,
1718
OrchestrationV2CommandOutputFrame,
1819
OrchestrationV2GetTurnItemResult,
20+
OrchestrationV2ThreadHistoryPage,
1921
} from "@t3tools/contracts";
2022
import * as ByteSize from "effect/ByteSize";
2123
import * as Duration from "effect/Duration";
@@ -52,6 +54,7 @@ const encodeOutputFrame = Schema.encodeEffect(
5254
Schema.fromJsonString(OrchestrationV2CommandOutputFrame),
5355
);
5456
const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
57+
const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
5558

5659
const errorResponse = (error: GuestShareAccessError) =>
5760
HttpServerResponse.json(
@@ -292,6 +295,26 @@ const itemRoute = HttpRouter.add(
292295
}),
293296
);
294297

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+
295318
// Ends when the command settles; the page closes its EventSource on that last frame, so the
296319
// browser does not reconnect.
297320
const commandOutputRoute = HttpRouter.add(
@@ -365,6 +388,7 @@ export const layer = Layer.mergeAll(
365388
streamRoute,
366389
renderRoute,
367390
itemRoute,
391+
historyRoute,
368392
commandOutputRoute,
369393
attachmentRoute,
370394
mediaRoute,

‎apps/web/src/components/guest/GuestPage.tsx‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import {
22
EnvironmentId,
33
GUEST_MESSAGE_MAX_LENGTH,
4+
GUEST_HISTORY_ROUTE,
45
GUEST_NAME_MAX_LENGTH,
56
GUEST_ROUTE_PREFIX,
67
GUEST_SHARE_PARAM,
78
GuestMessageId,
89
type GuestRedeemRequest,
910
type GuestShareView,
1011
type GuestThreadModel,
12+
OrchestrationV2ThreadHistoryPage,
1113
type OrchestrationV2ThreadProjection,
1214
type ThreadGuestMessage,
1315
type ThreadGuestMessageStatus,
@@ -46,7 +48,7 @@ import { GuestMessageAttachments } from "../chat/GuestMessageAttachments";
4648
import { HostImageUrlContext } from "../chat/hostImageUrl";
4749
import { PierreEntryIcon } from "../chat/PierreEntryIcon";
4850
import { GuestMessageName, guestBubbleClassName } from "../chat/guestMessageStyle";
49-
import { MessagesTimeline } from "../chat/MessagesTimeline";
51+
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "../chat/MessagesTimeline";
5052
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
5153
import { getDisplayModelName, getTriggerDisplayModelName } from "../chat/providerIconUtils";
5254
import { ScrollToEndButton } from "../chat/TimelineOverlays";
@@ -131,6 +133,32 @@ function takeGuestEntry(): GuestEntry {
131133
}
132134

133135
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+
}
134162

135163
/** Resolves to null on success, or to a message the guest can read. */
136164
async function postGuest(
@@ -241,6 +269,32 @@ function GuestSession({ shareId }: { readonly shareId: string }) {
241269
// missing, invalid, or ended session. Network drops reconnect on their own.
242270
const [rejected, setRejected] = useState(false);
243271

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+
244298
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets document.title to the shared thread's title
245299
useEffect(() => {
246300
if (stream.view) document.title = stream.view.title;
@@ -273,6 +327,7 @@ function GuestSession({ shareId }: { readonly shareId: string }) {
273327
view={stream.view}
274328
projection={stream.projection}
275329
awaitingRowIds={stream.awaitingRowIds}
330+
historyControls={historyControls}
276331
/>
277332
);
278333
}
@@ -358,10 +413,12 @@ function GuestThread({
358413
view: { shareId, title, expiresAt, messages, model },
359414
projection,
360415
awaitingRowIds,
416+
historyControls,
361417
}: {
362418
readonly view: GuestShareView;
363419
readonly projection: OrchestrationV2ThreadProjection;
364420
readonly awaitingRowIds: GuestStreamState["awaitingRowIds"];
421+
readonly historyControls: MessagesTimelineHistoryControls | undefined;
365422
}) {
366423
// No ":" so the timeline finds no environment thread behind the key.
367424
const threadKey = `guest-${shareId}`;
@@ -467,6 +524,7 @@ function GuestThread({
467524
onFileDownload={openFile}
468525
renderHtmlRender={renderHtmlRender}
469526
turnItemSource={turnItemSource}
527+
historyControls={historyControls}
470528
activeThreadEnvironmentId={GUEST_ENVIRONMENT_ID}
471529
markdownCwd={undefined}
472530
resolvedTheme={resolvedTheme}

‎apps/web/src/components/guest/guestStream.logic.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,45 @@ describe("applyGuestStreamEvent", () => {
112112
expect(apply([itemEvent(2, reply("a1", "Changed"))], once)).toBe(once);
113113
});
114114

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+
115154
it("replaces the thread on a new snapshot, as after a reconnect", () => {
116155
const before = apply([snapshot(1), itemEvent(2, reply("a1", "Hi")), { type: "ended" }]);
117156
const after = apply([snapshot(1)], { ...before, ended: false });

0 commit comments

Comments
 (0)