@truefoundry/assistant-ui-runtime 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1379,93 +1379,38 @@ export async function buildSnapshotFromSession(
1379
1379
  });
1380
1380
  }
1381
1381
 
1382
- /** Rebuilds session state from turns strictly before `beforeTurnId` (excludes that turn). */
1383
- export async function buildSnapshotBeforeTurn(
1384
- server: AgentChatServer,
1385
- sessionId: string,
1386
- beforeTurnId: string,
1387
- concurrency: number = DEFAULT_LIST_EVENTS_CONCURRENCY,
1388
- ): Promise<SessionSnapshot> {
1389
- const turns = await listSessionTurnsOrdered(server, sessionId);
1390
-
1391
- const beforeIndex = turns.findIndex((turn) => turn.id === beforeTurnId);
1392
- if (beforeIndex === -1) {
1393
- throw new Error(`Turn ${beforeTurnId} not found in session`);
1394
- }
1395
-
1396
- return buildSnapshotBeforeTurnIndex(
1397
- server,
1398
- sessionId,
1399
- beforeIndex,
1400
- concurrency,
1401
- turns,
1402
- );
1403
- }
1404
-
1405
- /** Rebuilds session state from the first `turnIndex` turns (excludes that turn). */
1406
- export async function buildSnapshotBeforeTurnIndex(
1382
+ /**
1383
+ * Rebuilds the conversation through `anchorTurnId`, including that turn.
1384
+ * The server follows parent links from the anchor, so turns from abandoned
1385
+ * branches are excluded. A null anchor represents an empty conversation.
1386
+ */
1387
+ export async function buildSnapshotThroughTurn(
1407
1388
  server: AgentChatServer,
1408
1389
  sessionId: string,
1409
- turnIndex: number,
1410
- _concurrency: number = DEFAULT_LIST_EVENTS_CONCURRENCY,
1411
- orderedTurns?: Turn[],
1390
+ anchorTurnId: string | null,
1412
1391
  ): Promise<SessionSnapshot> {
1413
- if (turnIndex <= 0) {
1392
+ if (anchorTurnId == null) {
1414
1393
  return createEmptySessionSnapshot();
1415
1394
  }
1416
-
1417
- const turns = orderedTurns ?? (await listSessionTurnsOrdered(server, sessionId));
1418
- const turnsToInclude = turns.slice(0, turnIndex);
1419
- const lastTurnId = turnsToInclude.at(-1)?.id;
1420
- if (lastTurnId == null) {
1421
- return createEmptySessionSnapshot();
1422
- }
1423
-
1424
- // Anchor the session events window at the newest included turn so the
1425
- // ancestor chain matches `[turns[0], …, turns[turnIndex - 1]]`.
1426
- const items = await fetchAllSessionEvents(server, sessionId, { lastTurnId });
1395
+ const items = await fetchAllSessionEvents(server, sessionId, {
1396
+ lastTurnId: anchorTurnId,
1397
+ });
1427
1398
  const snapshot = createEmptySessionSnapshot();
1428
1399
  ingestSessionEventsIntoSnapshot(snapshot, items);
1429
1400
  return snapshot;
1430
1401
  }
1431
1402
 
1432
- /** Turn id to branch from when resubmitting at `turnIndex` (`"none"` for first turn). */
1433
- export async function resolveGatewayBranchPreviousTurnId(
1434
- server: AgentChatServer,
1435
- sessionId: string,
1436
- turnIndex: number,
1437
- orderedTurns?: Turn[],
1438
- ): Promise<string> {
1439
- if (turnIndex <= 0) {
1440
- return "none";
1441
- }
1442
- const turns = orderedTurns ?? (await listSessionTurnsOrdered(server, sessionId));
1443
- return turns[turnIndex - 1]?.id ?? "none";
1444
- }
1445
-
1446
- /** Resolves `previousTurnId` by turn id so partial history windows stay correct. */
1403
+ /**
1404
+ * Resolves `previousTurnId` for edit/retry of `turnId` from the turn's own
1405
+ * parent pointer (`"none"` for roots). Independent of listTurns order.
1406
+ */
1447
1407
  export async function resolveGatewayBranchPreviousTurnIdForTurn(
1448
1408
  server: AgentChatServer,
1449
1409
  sessionId: string,
1450
1410
  turnId: string,
1451
1411
  ): Promise<string> {
1452
- const turns = await listSessionTurnsOrdered(server, sessionId);
1453
- const turnIndex = turns.findIndex((turn) => turn.id === turnId);
1454
- return resolveGatewayBranchPreviousTurnId(server, sessionId, turnIndex, turns);
1455
- }
1456
-
1457
- async function listSessionTurnsOrdered(
1458
- server: AgentChatServer,
1459
- sessionId: string,
1460
- ): Promise<Turn[]> {
1461
- const turns = await drainListPages((pageToken) =>
1462
- server.listTurns({
1463
- sessionId,
1464
- ...(pageToken != null ? { pageToken } : {}),
1465
- }),
1466
- );
1467
- turns.reverse();
1468
- return turns;
1412
+ const turn = await server.getTurn({ sessionId, turnId });
1413
+ return turn.previousTurnId ?? "none";
1469
1414
  }
1470
1415
 
1471
1416
  export async function buildTurnAssistantContent(
package/src/index.ts CHANGED
@@ -143,6 +143,8 @@ export type {
143
143
  SandboxConfig,
144
144
  SandboxCatalogEntry,
145
145
  SandboxBase,
146
+ SandboxSnapshotSyncStatus,
147
+ SandboxProviderListEntry,
146
148
  CreateSandboxRequest,
147
149
  UpdateSandboxRequest,
148
150
  SandboxProviderConfig,
@@ -83,6 +83,8 @@ export type {
83
83
  SandboxConfig,
84
84
  SandboxCatalogEntry,
85
85
  SandboxBase,
86
+ SandboxSnapshotSyncStatus,
87
+ SandboxProviderListEntry,
86
88
  CreateSandboxRequest,
87
89
  UpdateSandboxRequest,
88
90
  SandboxProviderConfig,
@@ -10,7 +10,7 @@ import type {
10
10
  ActionRequiredEvent,
11
11
  SessionEventItem,
12
12
  TurnEvent,
13
- TurnStreamData
13
+ TurnStreamData,
14
14
  } from "./events.js";
15
15
 
16
16
  // ---------------------------------------------------------------------------
@@ -74,19 +74,19 @@ export type SearchAgentSelectorParams = {
74
74
  // ---------------------------------------------------------------------------
75
75
 
76
76
  /**
77
- * Mounts written to AgentSpec.skills[] / AgentSpec.mcpServers[].
78
- *
79
- * These are opaque to the runtime — it stores and forwards them but never reads
80
- * a field, and the backend owns the shape (the gateway identifies a skill by
81
- * `fqn`, with no `id` or `name` anywhere). So the base constrains only that a
82
- * mount is an object; hosts intersect their concrete mount type over it, as
83
- * `TfySkillMount` / `TfyMcpServerMount` do in the gateway adapter.
84
- *
85
- * Naming a field here would not just be unread, it would be wrong: a base with
86
- * required fields rejects the backend's own payloads, and one with only optional
87
- * fields is a weak type, which TypeScript rejects for a source that shares no
88
- * property with it — the gateway's registry skill shares none.
89
- */
77
+ * Mounts written to AgentSpec.skills[] / AgentSpec.mcpServers[].
78
+ *
79
+ * These are opaque to the runtime — it stores and forwards them but never reads
80
+ * a field, and the backend owns the shape (the gateway identifies a skill by
81
+ * `fqn`, with no `id` or `name` anywhere). So the base constrains only that a
82
+ * mount is an object; hosts intersect their concrete mount type over it, as
83
+ * `TfySkillMount` / `TfyMcpServerMount` do in the gateway adapter.
84
+ *
85
+ * Naming a field here would not just be unread, it would be wrong: a base with
86
+ * required fields rejects the backend's own payloads, and one with only optional
87
+ * fields is a weak type, which TypeScript rejects for a source that shares no
88
+ * property with it — the gateway's registry skill shares none.
89
+ */
90
90
  export type SkillMount = object;
91
91
 
92
92
  export type McpServerMount = object;
@@ -116,10 +116,10 @@ export interface AgentRuntimeConfig {
116
116
  }
117
117
 
118
118
  /**
119
- * SDK-owned agent definition — fields the FE reads/writes.
120
- * Host widens `model` / `skills` / `mcpServers` / `config` via type params,
121
- * and adds extra fields via `TSpec extends AgentSpec<...>`.
122
- */
119
+ * SDK-owned agent definition — fields the FE reads/writes.
120
+ * Host widens `model` / `skills` / `mcpServers` / `config` via type params,
121
+ * and adds extra fields via `TSpec extends AgentSpec<...>`.
122
+ */
123
123
  export interface AgentSpec<
124
124
  TModel extends Model = Model,
125
125
  TSkill extends SkillMount = SkillMount,
@@ -193,7 +193,10 @@ export type PreviousTurnIdInput = "auto" | "none" | string;
193
193
 
194
194
  export type UserMessageContent =
195
195
  | string
196
- | Array<{ type: "text"; text: string } | { type: "file"; name: string; data: string }>;
196
+ | Array<
197
+ | { type: "text"; text: string }
198
+ | { type: "file"; name: string; data: string }
199
+ >;
197
200
 
198
201
  export interface UserMessage {
199
202
  type: "user.message";
@@ -265,11 +268,11 @@ export interface Turn {
265
268
  // ---------------------------------------------------------------------------
266
269
 
267
270
  /**
268
- * Chat / session port — the runtime calls these.
269
- *
270
- * All session ops are flat (sessionId param). No gateway client dependency.
271
- * `createTrueFoundryServer` is one possible implementation (TFY adapter).
272
- */
271
+ * Chat / session port — the runtime calls these.
272
+ *
273
+ * All session ops are flat (sessionId param). No gateway client dependency.
274
+ * `createTrueFoundryServer` is one possible implementation (TFY adapter).
275
+ */
273
276
  export interface AgentChatServer<
274
277
  TSpec extends AgentSpec = AgentSpec,
275
278
  TSession extends Session<TSpec> = Session<TSpec>,
@@ -284,44 +287,44 @@ export interface AgentChatServer<
284
287
  updateSession(req: TUpdate): Promise<TSession>;
285
288
 
286
289
  createTurn(req: {
287
- sessionId: string;
288
- input?: TurnInputItem[];
289
- previousTurnId?: PreviousTurnIdInput;
290
- abortSignal?: AbortSignal;
291
- headers?: Record<string, string>;
290
+ sessionId: string;
291
+ input?: TurnInputItem[];
292
+ previousTurnId?: PreviousTurnIdInput;
293
+ abortSignal?: AbortSignal;
294
+ headers?: Record<string, string>;
292
295
  }): AsyncIterable<TurnStreamData>;
293
296
 
294
297
  cancelSession(req: { sessionId: string }): Promise<void>;
295
298
  deleteSession?(req: { sessionId: string }): Promise<void>;
296
299
 
297
300
  listTurns(req: {
298
- sessionId: string;
299
- limit?: number;
300
- pageToken?: string;
301
- order?: ListSessionsOrder;
301
+ sessionId: string;
302
+ limit?: number;
303
+ pageToken?: string;
304
+ order?: ListSessionsOrder;
302
305
  }): Promise<ListResult<TTurn>>;
303
306
  getTurn(req: { sessionId: string; turnId: string }): Promise<TTurn>;
304
307
  listEvents(req: {
305
- sessionId: string;
306
- pageToken?: string;
307
- lastTurnId?: string;
308
- limit?: number;
308
+ sessionId: string;
309
+ pageToken?: string;
310
+ lastTurnId?: string;
311
+ limit?: number;
309
312
  }): Promise<ListResult<SessionEventItem>>;
310
313
 
311
314
  /** Optional per-turn event listing (hydrate in-flight turn content). */
312
315
  listTurnEvents?(req: {
313
- sessionId: string;
314
- turnId: string;
315
- limit?: number;
316
- pageToken?: string;
317
- order?: ListSessionsOrder;
316
+ sessionId: string;
317
+ turnId: string;
318
+ limit?: number;
319
+ pageToken?: string;
320
+ order?: ListSessionsOrder;
318
321
  }): Promise<ListResult<TurnEvent>>;
319
322
 
320
323
  subscribeToTurn?(req: {
321
- sessionId: string;
322
- turnId: string;
323
- afterSequenceNumber?: number;
324
- abortSignal?: AbortSignal;
324
+ sessionId: string;
325
+ turnId: string;
326
+ afterSequenceNumber?: number;
327
+ abortSignal?: AbortSignal;
325
328
  }): AsyncIterable<TurnStreamData>;
326
329
 
327
330
  /**
@@ -330,10 +333,10 @@ export interface AgentChatServer<
330
333
  * directly use `sandboxId`.
331
334
  */
332
335
  downloadSandboxFile?(req: {
333
- sessionId: string;
334
- turnId: string;
335
- sandboxId: string;
336
- path: string;
336
+ sessionId: string;
337
+ turnId: string;
338
+ sandboxId: string;
339
+ path: string;
337
340
  }): Promise<Blob>;
338
341
  }
339
342
 
@@ -365,9 +368,9 @@ export interface AgentBuilderCapabilitiesResponse {
365
368
  }
366
369
 
367
370
  /**
368
- * Builder catalog + persist port — atoms call these.
369
- * Passed separately from the runtime's chat server.
370
- */
371
+ * Builder catalog + persist port — atoms call these.
372
+ * Passed separately from the runtime's chat server.
373
+ */
371
374
  export interface AgentBuilderServer<
372
375
  TSpec extends AgentSpec = AgentSpec,
373
376
  TModel extends ModelSelectorEntry = ModelSelectorEntry,
@@ -375,7 +378,8 @@ export interface AgentBuilderServer<
375
378
  TMcp extends ConnectorSelectorEntry = ConnectorSelectorEntry,
376
379
  TAgent extends AgentSelectorEntry = AgentSelectorEntry,
377
380
  TSave = SaveAgentResult,
378
- TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,
381
+ TCapabilities extends AgentBuilderCapabilitiesResponse =
382
+ AgentBuilderCapabilitiesResponse,
379
383
  > {
380
384
  getCapabilities(): Promise<TCapabilities>;
381
385
  getModels(): Promise<TModel[]>;
@@ -391,28 +395,30 @@ export interface AgentBuilderServer<
391
395
  // ---------------------------------------------------------------------------
392
396
 
393
397
  /**
394
- * Provider type id. Reserved literal: `"custom"` for user-defined providers;
395
- * any other string is a builtin (e.g. `"openai"`, `"anthropic"`).
396
- *
397
- * Note: `string | "custom"` is useless in TypeScript (`"custom"` ⊆ `string`),
398
- * so this stays `string` and `"custom"` is a documented convention.
399
- */
398
+ * Provider type id. Reserved literal: `"custom"` for user-defined providers;
399
+ * any other string is a builtin (e.g. `"openai"`, `"anthropic"`).
400
+ *
401
+ * Note: `string | "custom"` is useless in TypeScript (`"custom"` ⊆ `string`),
402
+ * so this stays `string` and `"custom"` is a documented convention.
403
+ */
400
404
  export type ProviderType = string;
401
405
 
402
406
  /**
403
- * Model row — form "Model ID" + "Display name".
404
- * Host extends for properties, etc.
405
- */
407
+ * Model row — form "Model ID" + "Display name".
408
+ * Host extends for properties, etc.
409
+ */
406
410
  export interface ModelEntry {
407
411
  id: string;
408
412
  name: string;
409
413
  }
410
414
 
411
415
  /**
412
- * Write config for create/update (custom form + catalog "Save key").
413
- * Host extends. `baseUrl` present iff `type === "custom"`.
414
- */
415
- export interface ModelProviderConfigBase<TModel extends ModelEntry = ModelEntry> {
416
+ * Write config for create/update (custom form + catalog "Save key").
417
+ * Host extends. `baseUrl` present iff `type === "custom"`.
418
+ */
419
+ export interface ModelProviderConfigBase<
420
+ TModel extends ModelEntry = ModelEntry,
421
+ > {
416
422
  type: ProviderType;
417
423
  name: string;
418
424
  /** Present iff `type === "custom"`. */
@@ -422,9 +428,9 @@ export interface ModelProviderConfigBase<TModel extends ModelEntry = ModelEntry>
422
428
  }
423
429
 
424
430
  /**
425
- * Configured provider card (list/read). No raw `apiKey`.
426
- * Host extends for apiKeySet, timestamps, etc.
427
- */
431
+ * Configured provider card (list/read). No raw `apiKey`.
432
+ * Host extends for apiKeySet, timestamps, etc.
433
+ */
428
434
  export interface ModelProviderBase<TModel extends ModelEntry = ModelEntry> {
429
435
  id: string;
430
436
  type: ProviderType;
@@ -435,11 +441,13 @@ export interface ModelProviderBase<TModel extends ModelEntry = ModelEntry> {
435
441
  }
436
442
 
437
443
  /**
438
- * Discovery-only catalog provider (AVAILABLE list).
439
- * `type` must not be `"custom"` — custom providers use the custom form.
440
- * Host extends for richer model rows.
441
- */
442
- export interface ModelProviderCatalogEntry<TModel extends ModelEntry = ModelEntry> {
444
+ * Discovery-only catalog provider (AVAILABLE list).
445
+ * `type` must not be `"custom"` — custom providers use the custom form.
446
+ * Host extends for richer model rows.
447
+ */
448
+ export interface ModelProviderCatalogEntry<
449
+ TModel extends ModelEntry = ModelEntry,
450
+ > {
443
451
  type: ProviderType;
444
452
  name: string;
445
453
  models: TModel[];
@@ -458,9 +466,12 @@ export type UpdateModelProviderRequest<TModel extends ModelEntry = ModelEntry> =
458
466
  export interface ModelCatalogServer<
459
467
  TModel extends ModelEntry = ModelEntry,
460
468
  TProvider extends ModelProviderBase<TModel> = ModelProviderBase<TModel>,
461
- TCatalogProvider extends ModelProviderCatalogEntry<TModel> = ModelProviderCatalogEntry<TModel>,
462
- TCreate extends CreateModelProviderRequest<TModel> = CreateModelProviderRequest<TModel>,
463
- TUpdate extends UpdateModelProviderRequest<TModel> = UpdateModelProviderRequest<TModel>,
469
+ TCatalogProvider extends ModelProviderCatalogEntry<TModel> =
470
+ ModelProviderCatalogEntry<TModel>,
471
+ TCreate extends CreateModelProviderRequest<TModel> =
472
+ CreateModelProviderRequest<TModel>,
473
+ TUpdate extends UpdateModelProviderRequest<TModel> =
474
+ UpdateModelProviderRequest<TModel>,
464
475
  > {
465
476
  getModelProviderCatalog(): Promise<TCatalogProvider[]>;
466
477
  listModelProviders(): Promise<TProvider[]>;
@@ -506,8 +517,8 @@ export type ConnectorAuthPublic =
506
517
  | ConnectorAuthPublicNone;
507
518
 
508
519
  /**
509
- * MCP / connector create-edit config. Host extends for extra fields, etc.
510
- */
520
+ * MCP / connector create-edit config. Host extends for extra fields, etc.
521
+ */
511
522
  export interface ConnectorConfigBase<
512
523
  TAuth extends ConnectorAuth = ConnectorAuth,
513
524
  > {
@@ -547,12 +558,14 @@ export interface ConnectorCatalogEntry<
547
558
  }
548
559
 
549
560
  /** Create connector — no `id`; server assigns it. Host extends. */
550
- export type CreateConnectorRequest<TAuth extends ConnectorAuth = ConnectorAuth> =
551
- ConnectorConfigBase<TAuth>;
561
+ export type CreateConnectorRequest<
562
+ TAuth extends ConnectorAuth = ConnectorAuth,
563
+ > = ConnectorConfigBase<TAuth>;
552
564
 
553
565
  /** Update connector — `id` required. Host extends. */
554
- export type UpdateConnectorRequest<TAuth extends ConnectorAuth = ConnectorAuth> =
555
- ConnectorConfigBase<TAuth> & { id: string };
566
+ export type UpdateConnectorRequest<
567
+ TAuth extends ConnectorAuth = ConnectorAuth,
568
+ > = ConnectorConfigBase<TAuth> & { id: string };
556
569
 
557
570
  export interface AuthenticateConnectorRequest {
558
571
  id: string;
@@ -664,7 +677,6 @@ export interface SkillCatalogServer<
664
677
 
665
678
  /** Mutable sandbox provider settings shared by catalog rows, create, and update. */
666
679
  export interface SandboxConfig {
667
- snapshotName: string;
668
680
  execTimeoutMs: number;
669
681
  autoStopIntervalInMinutes: number;
670
682
  autoArchiveIntervalInMinutes: number;
@@ -688,6 +700,18 @@ export interface SandboxBase extends SandboxConfig {
688
700
  isConnected: boolean;
689
701
  }
690
702
 
703
+ export type SandboxSnapshotSyncStatus = {
704
+ status: "pending" | "ready" | "failed";
705
+ statusReason?: string | null;
706
+ };
707
+
708
+ export interface SandboxProviderListEntry<
709
+ TSandbox extends SandboxBase = SandboxBase,
710
+ > {
711
+ data: TSandbox;
712
+ snapshotSyncStatus: SandboxSnapshotSyncStatus;
713
+ }
714
+
691
715
  export interface CreateSandboxRequest extends SandboxConfig {
692
716
  /** `SandboxCatalogEntry.id` used to create this sandbox provider. */
693
717
  catalogId: string;
@@ -714,9 +738,11 @@ export interface SandboxCatalogServer<
714
738
  TCatalogEntry extends SandboxCatalogEntry = SandboxCatalogEntry,
715
739
  TCreate extends CreateSandboxRequest = CreateSandboxRequest,
716
740
  TUpdate extends UpdateSandboxRequest = UpdateSandboxRequest,
741
+ TListEntry extends SandboxProviderListEntry<TProvider> =
742
+ SandboxProviderListEntry<TProvider>,
717
743
  > {
718
744
  getSandboxProviderCatalog(): Promise<TCatalogEntry[]>;
719
- listSandboxProviders(req?: { query?: string }): Promise<TProvider[]>;
745
+ listSandboxProviders(req?: { query?: string }): Promise<TListEntry[]>;
720
746
  createSandboxProvider(req: TCreate): Promise<TProvider>;
721
747
  updateSandboxProvider(req: TUpdate): Promise<TProvider>;
722
748
  deleteSandboxProvider?(req: { id: string }): Promise<void>;
@@ -730,10 +756,10 @@ export type AgentLibraryEntry = AgentSelectorEntry;
730
756
  export type SearchAgentsParams = SearchAgentSelectorParams;
731
757
 
732
758
  /**
733
- * Settings management aggregate — modelCatalog + connectorCatalog + optional
734
- * skill and sandbox catalogs.
735
- * Hosts may pass the whole object to an app shell, or a focused sub-port to a page.
736
- */
759
+ * Settings management aggregate — modelCatalog + connectorCatalog + optional
760
+ * skill and sandbox catalogs.
761
+ * Hosts may pass the whole object to an app shell, or a focused sub-port to a page.
762
+ */
737
763
  export interface CatalogServer<
738
764
  TModelCatalog extends ModelCatalogServer = ModelCatalogServer,
739
765
  TConnectorCatalog extends ConnectorCatalogServer = ConnectorCatalogServer,
package/src/types.ts CHANGED
@@ -28,7 +28,6 @@ type TrueFoundryAgentRuntimeBaseOptions = ExternalStoreSharedOptions & {
28
28
  threadId?: string | undefined;
29
29
  onThreadIdChange?: ((threadId: string | undefined) => void) | undefined;
30
30
  onError?: ((error: unknown) => void) | undefined;
31
- listEventsConcurrency?: number | undefined;
32
31
  /**
33
32
  * Optional filter forwarded to `listSessions({ agentId })`.
34
33
  * Omit for all chats; hosts that key agents by name pass that name as the id.
@@ -47,6 +47,7 @@ vi.mock("./convertTurnMessages.js", async (importOriginal) => {
47
47
  const mockServer = {
48
48
  cancelSession: vi.fn().mockResolvedValue(undefined),
49
49
  listTurns: vi.fn(),
50
+ getTurn: vi.fn(),
50
51
  // Present so resume-capable paths are exercised; resumeTurnStream is mocked.
51
52
  subscribeToTurn: vi.fn(),
52
53
  } as unknown as AgentChatServer;
@@ -429,6 +430,7 @@ describe("useTrueFoundryAgentMessages", () => {
429
430
  expect.any(PeerThreadFoldState),
430
431
  {
431
432
  userMessage: "first",
433
+ previousTurnId: "none",
432
434
  headers: {
433
435
  "x-tfy-session-last-updated-at": "2026-06-30T12:00:00.000Z",
434
436
  },
@@ -689,21 +691,22 @@ describe("useTrueFoundryAgentMessages", () => {
689
691
 
690
692
  it("editFromTurn drops prior turns before showing the edited user message", async () => {
691
693
  const createdAt = new Date().toISOString();
694
+ const rootTurn = {
695
+ id: "turn-1",
696
+ sessionId: "session-1",
697
+ createdAt,
698
+ previousTurnId: null,
699
+ state: {
700
+ status: "done" as const,
701
+ requiredActions: [],
702
+ completedAt: createdAt,
703
+ },
704
+ input: [{ type: "user.message" as const, content: "Hello" }],
705
+ } as Turn;
692
706
  vi.mocked(mockServer.listTurns).mockResolvedValue({
693
- data: [
694
- {
695
- id: "turn-1",
696
- sessionId: "session-1",
697
- createdAt,
698
- state: {
699
- status: "done",
700
- requiredActions: [],
701
- completedAt: createdAt,
702
- },
703
- input: [{ type: "user.message", content: "Hello" }],
704
- } as Turn,
705
- ],
707
+ data: [rootTurn],
706
708
  });
709
+ vi.mocked(mockServer.getTurn).mockResolvedValue(rootTurn);
707
710
  const fold = new PeerThreadFoldState();
708
711
  ingestTurnEvent(fold, {
709
712
  type: "model.message",
@@ -805,21 +808,22 @@ describe("useTrueFoundryAgentMessages", () => {
805
808
  const onError = vi.fn();
806
809
  const original = snapshotWithUserTurn("Hello");
807
810
  vi.mocked(loadSessionSnapshot).mockResolvedValue(original);
811
+ const rootTurn = {
812
+ id: "turn-1",
813
+ sessionId: "session-1",
814
+ createdAt,
815
+ previousTurnId: null,
816
+ state: {
817
+ status: "done" as const,
818
+ requiredActions: [],
819
+ completedAt: createdAt,
820
+ },
821
+ input: [{ type: "user.message" as const, content: "Hello" }],
822
+ } as Turn;
808
823
  vi.mocked(mockServer.listTurns).mockResolvedValue({
809
- data: [
810
- {
811
- id: "turn-1",
812
- sessionId: "session-1",
813
- createdAt,
814
- state: {
815
- status: "done",
816
- requiredActions: [],
817
- completedAt: createdAt,
818
- },
819
- input: [{ type: "user.message", content: "Hello" }],
820
- } as Turn,
821
- ],
824
+ data: [rootTurn],
822
825
  });
826
+ vi.mocked(mockServer.getTurn).mockResolvedValue(rootTurn);
823
827
  vi.mocked(streamTurnContent).mockImplementation(async function* () {
824
828
  throw new Error("Turn preparation failed");
825
829
  });
@@ -15,7 +15,7 @@ import type { AgentChatServer } from "./server/types.js";
15
15
  import { ROOT_THREAD_ID } from "./constants.js";
16
16
  import {
17
17
  buildEditedUserMessageContent,
18
- buildSnapshotBeforeTurn,
18
+ buildSnapshotThroughTurn,
19
19
  computeGroupRootBaseline,
20
20
  extractTurnUserMessageContent,
21
21
  prependOlderSessionHistory,
@@ -60,7 +60,6 @@ export type UseTrueFoundryAgentMessagesOptions = {
60
60
  isMain?: boolean | undefined;
61
61
  /** URL-selected session may load before the thread list marks it as main. */
62
62
  isInitialSession?: boolean | undefined;
63
- listEventsConcurrency?: number | undefined;
64
63
  onError?: ((error: unknown) => void) | undefined;
65
64
  initializeSession?: () => Promise<{
66
65
  remoteId: string;
@@ -293,7 +292,6 @@ export function useTrueFoundryAgentMessages({
293
292
  sessionId,
294
293
  isMain,
295
294
  isInitialSession,
296
- listEventsConcurrency,
297
295
  onError,
298
296
  initializeSession,
299
297
  resolveConversationSessionId,
@@ -975,11 +973,12 @@ export function useTrueFoundryAgentMessages({
975
973
  conversationSessionId,
976
974
  turnId,
977
975
  );
978
- rewound = await buildSnapshotBeforeTurn(
976
+ // Rewind to the exact parent used for the new branch. Using the
977
+ // previous item from listTurns could select an abandoned branch.
978
+ rewound = await buildSnapshotThroughTurn(
979
979
  server,
980
980
  conversationSessionId,
981
- turnId,
982
- listEventsConcurrency,
981
+ previousTurnId === "none" ? null : previousTurnId,
983
982
  );
984
983
  createdAtByMessageIdRef.current = new Map();
985
984
  // Keep the ref aligned before awaiting sendTurn so any intermediate
@@ -1000,13 +999,7 @@ export function useTrueFoundryAgentMessages({
1000
999
  branchRollbackSnapshot: committed,
1001
1000
  });
1002
1001
  },
1003
- [
1004
- cancel,
1005
- server,
1006
- listEventsConcurrency,
1007
- sendTurn,
1008
- sessionId,
1009
- ],
1002
+ [cancel, server, sendTurn, sessionId],
1010
1003
  );
1011
1004
 
1012
1005
  const resetFromTurn = useCallback(
@@ -49,7 +49,6 @@ function useTrueFoundryAgentRuntimeImpl(
49
49
  agent,
50
50
  adapters,
51
51
  onError,
52
- listEventsConcurrency,
53
52
  ...sharedOptions
54
53
  } = options;
55
54
 
@@ -126,7 +125,6 @@ function useTrueFoundryAgentRuntimeImpl(
126
125
  sessionId,
127
126
  isMain,
128
127
  isInitialSession,
129
- listEventsConcurrency,
130
128
  onError,
131
129
  initializeSession,
132
130
  getTurnHeaders: agent.mode === "draft" ? getTurnHeaders : undefined,