@dudko.dev/agent-web-ui 0.0.8 → 0.0.10

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.
package/dist/canvas.js CHANGED
@@ -156,7 +156,7 @@ var hitEdge = (edges, point, tolerance = 8) => {
156
156
  let best;
157
157
  let bestDistance = Infinity;
158
158
  for (const edge of edges) {
159
- const distance = distanceToCurve(edge.curve, point);
159
+ const distance = "route" in edge ? distanceToRoute(edge.route, point) : distanceToCurve(edge.curve, point);
160
160
  if (distance <= tolerance && distance < bestDistance) {
161
161
  best = edge.id;
162
162
  bestDistance = distance;
@@ -169,9 +169,280 @@ var readingOrder = (nodes, column = 40) => nodes.map((node, index) => ({ node, i
169
169
  const bx = Math.round(b.node.x / column);
170
170
  return ax - bx || a.node.y - b.node.y || a.index - b.index;
171
171
  }).map(({ node }) => node.id);
172
+ var EDGE_HANDLE_SIZE = { width: 14, height: 14 };
173
+ var estimateLabelSize = (text) => text ? { width: Math.min(text.length, 28) * 6.2 + 20, height: 22 } : EDGE_HANDLE_SIZE;
174
+ var inflate = (r, by) => ({
175
+ x: r.x - by,
176
+ y: r.y - by,
177
+ width: r.width + by * 2,
178
+ height: r.height + by * 2
179
+ });
180
+ var rectsOverlap = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
181
+ var segmentHitsRect = (a, b, rect) => {
182
+ const dx = b.x - a.x;
183
+ const dy = b.y - a.y;
184
+ let t0 = 0;
185
+ let t1 = 1;
186
+ const sides = [
187
+ [-dx, a.x - rect.x],
188
+ [dx, rect.x + rect.width - a.x],
189
+ [-dy, a.y - rect.y],
190
+ [dy, rect.y + rect.height - a.y]
191
+ ];
192
+ for (const [p, q] of sides) {
193
+ if (p === 0) {
194
+ if (q <= 0) return false;
195
+ continue;
196
+ }
197
+ const t = q / p;
198
+ if (p < 0) {
199
+ if (t > t1) return false;
200
+ if (t > t0) t0 = t;
201
+ } else {
202
+ if (t < t0) return false;
203
+ if (t < t1) t1 = t;
204
+ }
205
+ }
206
+ return t1 - t0 > 1e-9;
207
+ };
208
+ var routePolyline = (route) => route.kind === "curve" && route.curve ? Array.from({ length: 33 }, (_, i) => curvePoint(route.curve, i / 32)) : route.points;
209
+ var routeHitsRect = (route, rect, margin = 0) => {
210
+ const box = inflate(rect, margin);
211
+ const line = routePolyline(route);
212
+ for (let i = 1; i < line.length; i++) if (segmentHitsRect(line[i - 1], line[i], box)) return true;
213
+ return false;
214
+ };
215
+ var distanceToRoute = (route, point) => {
216
+ if (route.kind === "curve" && route.curve) return distanceToCurve(route.curve, point);
217
+ let best = Infinity;
218
+ for (let i = 1; i < route.points.length; i++) {
219
+ best = Math.min(best, distanceToSegment(point, route.points[i - 1], route.points[i]));
220
+ }
221
+ return best;
222
+ };
223
+ var roundedPath = (points, radius = 10) => {
224
+ if (points.length === 0) return "";
225
+ const p = (pt) => `${round(pt.x)} ${round(pt.y)}`;
226
+ let d = `M ${p(points[0])}`;
227
+ for (let i = 1; i < points.length - 1; i++) {
228
+ const a = points[i - 1];
229
+ const c = points[i];
230
+ const b = points[i + 1];
231
+ const inLength = Math.hypot(c.x - a.x, c.y - a.y);
232
+ const outLength = Math.hypot(b.x - c.x, b.y - c.y);
233
+ const r = Math.min(radius, inLength / 2, outLength / 2);
234
+ if (r <= 0.01) {
235
+ d += ` L ${p(c)}`;
236
+ continue;
237
+ }
238
+ const before = { x: c.x - (c.x - a.x) / inLength * r, y: c.y - (c.y - a.y) / inLength * r };
239
+ const after = { x: c.x + (b.x - c.x) / outLength * r, y: c.y + (b.y - c.y) / outLength * r };
240
+ d += ` L ${p(before)} Q ${p(c)}, ${p(after)}`;
241
+ }
242
+ return `${d} L ${p(points[points.length - 1])}`;
243
+ };
244
+ var simplify = (points) => {
245
+ const out = [];
246
+ for (const pt of points) {
247
+ const last = out[out.length - 1];
248
+ if (last && Math.abs(last.x - pt.x) < 0.01 && Math.abs(last.y - pt.y) < 0.01) continue;
249
+ const before = out[out.length - 2];
250
+ if (before && last && (Math.abs(before.x - last.x) < 0.01 && Math.abs(last.x - pt.x) < 0.01 || Math.abs(before.y - last.y) < 0.01 && Math.abs(last.y - pt.y) < 0.01)) {
251
+ out[out.length - 1] = pt;
252
+ continue;
253
+ }
254
+ out.push(pt);
255
+ }
256
+ return out;
257
+ };
258
+ var routeEdges = (nodes, edges, options = {}) => {
259
+ const stub = options.stub ?? 16;
260
+ const spacing = options.spacing ?? 12;
261
+ const clearance = options.clearance ?? 14;
262
+ const radius = options.radius ?? 10;
263
+ const byId = new Map(nodes.map((n) => [n.id, n]));
264
+ const others = (edge) => nodes.filter((n) => n.id !== edge.from && n.id !== edge.to);
265
+ const curves = /* @__PURE__ */ new Map();
266
+ const orthogonal = [];
267
+ for (const edge of edges) {
268
+ if (edge.end.x - edge.start.x >= 40 && edge.from !== edge.to) {
269
+ const curve = edgeCurve(edge.start, edge.end);
270
+ const route = { kind: "curve", points: [], curve };
271
+ if (!others(edge).some((n) => routeHitsRect(route, n, 2))) {
272
+ curves.set(edge.id, curve);
273
+ continue;
274
+ }
275
+ }
276
+ orthogonal.push(edge);
277
+ }
278
+ const exitX = /* @__PURE__ */ new Map();
279
+ const entryX = /* @__PURE__ */ new Map();
280
+ const assignChannels = (key, at, side, into) => {
281
+ const groups = /* @__PURE__ */ new Map();
282
+ for (const e of orthogonal) groups.set(key(e), [...groups.get(key(e)) ?? [], e]);
283
+ for (const group of groups.values()) {
284
+ const sorted = [...group].sort(
285
+ (a, b) => (side === 1 ? a.start.y - b.start.y : a.end.y - b.end.y) || 0
286
+ );
287
+ sorted.forEach((e, i) => into.set(e.id, at(e) + side * (stub + i * spacing)));
288
+ }
289
+ };
290
+ assignChannels(
291
+ (e) => e.from,
292
+ (e) => Math.max(e.start.x, (byId.get(e.from)?.x ?? 0) + (byId.get(e.from)?.width ?? 0)),
293
+ 1,
294
+ exitX
295
+ );
296
+ assignChannels(
297
+ (e) => e.to,
298
+ (e) => Math.min(e.end.x, byId.get(e.to)?.x ?? e.end.x),
299
+ -1,
300
+ entryX
301
+ );
302
+ const runs = [];
303
+ const lanes = /* @__PURE__ */ new Map();
304
+ const order = [...orthogonal].sort(
305
+ (a, b) => Math.abs((exitX.get(a.id) ?? 0) - (entryX.get(a.id) ?? 0)) - Math.abs((exitX.get(b.id) ?? 0) - (entryX.get(b.id) ?? 0))
306
+ );
307
+ for (const edge of order) {
308
+ const xa = exitX.get(edge.id);
309
+ const xb = entryX.get(edge.id);
310
+ const left = Math.min(xa, xb);
311
+ const right = Math.max(xa, xb);
312
+ const solid = nodes.map((n) => inflate(n, clearance - 1));
313
+ const inSpan = nodes.filter((n) => n.x < right + clearance && n.x + n.width > left - clearance).map((n) => inflate(n, clearance)).sort((p, q) => p.y - q.y);
314
+ const corridors = [];
315
+ let reach = -Infinity;
316
+ for (const r of inSpan) {
317
+ if (r.y > reach) corridors.push({ from: reach, to: r.y });
318
+ reach = Math.max(reach, r.y + r.height);
319
+ }
320
+ corridors.push({ from: reach, to: Infinity });
321
+ const travelAt = (y2) => Math.abs(edge.start.y - y2) + Math.abs(edge.end.y - y2);
322
+ const ranked = corridors.map((c) => {
323
+ const ideal = clamp((edge.start.y + edge.end.y) / 2, c.from, c.to);
324
+ return { ...c, cost: travelAt(ideal) };
325
+ }).sort((p, q) => p.cost - q.cost);
326
+ let best;
327
+ for (const c of ranked) {
328
+ const slots = [];
329
+ if (Number.isFinite(c.from) && Number.isFinite(c.to)) {
330
+ const middle = (c.from + c.to) / 2;
331
+ for (let k = 0; k * spacing <= (c.to - c.from) / 2; k++) {
332
+ slots.push(middle + k * spacing);
333
+ if (k > 0) slots.push(middle - k * spacing);
334
+ }
335
+ } else if (Number.isFinite(c.from)) {
336
+ for (let k = 0; k < 24; k++) slots.push(c.from + 4 + k * spacing);
337
+ } else {
338
+ for (let k = 0; k < 24; k++) slots.push(c.to - 4 - k * spacing);
339
+ }
340
+ for (const y2 of slots) {
341
+ if (!(y2 > c.from && y2 < c.to)) continue;
342
+ const path = [
343
+ { x: xa, y: edge.start.y },
344
+ { x: xa, y: y2 },
345
+ { x: xb, y: y2 },
346
+ { x: xb, y: edge.end.y }
347
+ ];
348
+ let blocked = false;
349
+ for (let i = 1; i < path.length && !blocked; i++) {
350
+ blocked = solid.some((r) => segmentHitsRect(path[i - 1], path[i], r));
351
+ }
352
+ if (!blocked) {
353
+ const rest = others(edge);
354
+ blocked = rest.some((r) => segmentHitsRect(edge.start, path[0], r)) || rest.some((r) => segmentHitsRect(path[3], edge.end, r));
355
+ }
356
+ if (blocked) continue;
357
+ if (runs.some((r) => Math.abs(r.y - y2) < spacing - 0.5 && r.x1 < right && left < r.x2)) {
358
+ continue;
359
+ }
360
+ best = y2;
361
+ break;
362
+ }
363
+ if (best !== void 0) break;
364
+ }
365
+ const bottom = Math.max(edge.start.y, edge.end.y, ...inSpan.map((n) => n.y + n.height));
366
+ const y = best ?? bottom + spacing;
367
+ runs.push({ y, x1: left, x2: right });
368
+ lanes.set(edge.id, [
369
+ edge.start,
370
+ { x: xa, y: edge.start.y },
371
+ { x: xa, y },
372
+ { x: xb, y },
373
+ { x: xb, y: edge.end.y },
374
+ edge.end
375
+ ]);
376
+ }
377
+ const placed = [];
378
+ const placeLabel = (candidates, size) => {
379
+ const boxAt = (c) => ({
380
+ x: c.x - size.width / 2,
381
+ y: c.y - size.height / 2,
382
+ width: size.width,
383
+ height: size.height
384
+ });
385
+ for (const c of candidates) {
386
+ const box = boxAt(c);
387
+ if (nodes.some((n) => rectsOverlap(box, inflate(n, 2)))) continue;
388
+ if (placed.some((p) => rectsOverlap(box, p))) continue;
389
+ placed.push(box);
390
+ return c;
391
+ }
392
+ const fallback = candidates.find((c) => !nodes.some((n) => rectsOverlap(boxAt(c), n))) ?? candidates[0];
393
+ placed.push(boxAt(fallback));
394
+ return fallback;
395
+ };
396
+ const fromMiddle = (steps) => {
397
+ const ts = [0.5];
398
+ for (let i = 1; i < steps; i++) ts.push(0.5 - i / (steps * 2), 0.5 + i / (steps * 2));
399
+ return ts;
400
+ };
401
+ return edges.map((edge) => {
402
+ const size = edge.label ?? EDGE_HANDLE_SIZE;
403
+ const curve = curves.get(edge.id);
404
+ if (curve) {
405
+ const label2 = placeLabel(
406
+ fromMiddle(10).map((t) => curvePoint(curve, t)),
407
+ size
408
+ );
409
+ return {
410
+ id: edge.id,
411
+ kind: "curve",
412
+ points: [curve.p0, curve.p3],
413
+ curve,
414
+ path: curvePath(curve),
415
+ label: label2
416
+ };
417
+ }
418
+ const points = simplify(lanes.get(edge.id));
419
+ let lane = [points[0], points[points.length - 1]];
420
+ let longest = -1;
421
+ for (let i = 1; i < points.length; i++) {
422
+ const a = points[i - 1];
423
+ const b = points[i];
424
+ if (Math.abs(a.y - b.y) < 0.01 && Math.abs(a.x - b.x) > longest) {
425
+ longest = Math.abs(a.x - b.x);
426
+ lane = [a, b];
427
+ }
428
+ }
429
+ const label = placeLabel(
430
+ fromMiddle(12).map((t) => ({ x: lane[0].x + (lane[1].x - lane[0].x) * t, y: lane[0].y })),
431
+ size
432
+ );
433
+ return {
434
+ id: edge.id,
435
+ kind: "orthogonal",
436
+ points,
437
+ path: roundedPath(points, radius),
438
+ label
439
+ };
440
+ });
441
+ };
172
442
  export {
173
443
  DEFAULT_MAX_ZOOM,
174
444
  DEFAULT_MIN_ZOOM,
445
+ EDGE_HANDLE_SIZE,
175
446
  IDENTITY_VIEWPORT,
176
447
  boundsOf,
177
448
  centerOn,
@@ -180,7 +451,9 @@ export {
180
451
  curvePoint,
181
452
  defaultCanvasLabels,
182
453
  distanceToCurve,
454
+ distanceToRoute,
183
455
  edgeCurve,
456
+ estimateLabelSize,
184
457
  fitViewport,
185
458
  hitEdge,
186
459
  hitNode,
@@ -191,7 +464,11 @@ export {
191
464
  pinchViewport,
192
465
  readingOrder,
193
466
  rectContains,
467
+ roundedPath,
468
+ routeEdges,
469
+ routeHitsRect,
194
470
  screenToWorld,
471
+ segmentHitsRect,
195
472
  snapPoint,
196
473
  snapTo,
197
474
  worldToScreen,
@@ -30,6 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/controller.ts
31
31
  var controller_exports = {};
32
32
  __export(controller_exports, {
33
+ REPLAY_MAX_MS: () => REPLAY_MAX_MS,
34
+ REPLAY_QUIET_MS: () => REPLAY_QUIET_MS,
33
35
  createAgentController: () => createAgentController,
34
36
  createInitialAgentSnapshot: () => createInitialAgentSnapshot,
35
37
  createInitialRemoteSnapshot: () => createInitialRemoteSnapshot,
@@ -1959,8 +1961,15 @@ var GatewayError = class extends Error {
1959
1961
  status;
1960
1962
  code;
1961
1963
  };
1962
- var createInitialRemoteSnapshot = (options = {}) => snapshotOf({ ...createInitialAgentState(), status: "ready" }, options.sessionId ?? "", /* @__PURE__ */ new Set());
1963
- var snapshotOf = (state, sessionId, answering) => Object.freeze({
1964
+ var REPLAY_QUIET_MS = 150;
1965
+ var REPLAY_MAX_MS = 5e3;
1966
+ var createInitialRemoteSnapshot = (options = {}) => snapshotOf(
1967
+ { ...createInitialAgentState(), status: "ready" },
1968
+ options.sessionId ?? "",
1969
+ /* @__PURE__ */ new Set(),
1970
+ Boolean(options.sessionId?.trim())
1971
+ );
1972
+ var snapshotOf = (state, sessionId, answering, restoring = false) => Object.freeze({
1964
1973
  ...state,
1965
1974
  isRunning: state.status === "running",
1966
1975
  isReady: state.status === "ready",
@@ -1971,7 +1980,8 @@ var snapshotOf = (state, sessionId, answering) => Object.freeze({
1971
1980
  pendingQuestions: [],
1972
1981
  // The server's policy decides; a view hides the switch for a remote agent.
1973
1982
  approvalMode: "ask-writes",
1974
- sessionId
1983
+ sessionId,
1984
+ restoring
1975
1985
  });
1976
1986
  var createRemoteAgentController = (options) => {
1977
1987
  const base = options.baseUrl.replace(/\/+$/, "");
@@ -1986,6 +1996,23 @@ var createRemoteAgentController = (options) => {
1986
1996
  let snapshot;
1987
1997
  const listeners = /* @__PURE__ */ new Set();
1988
1998
  const answering = /* @__PURE__ */ new Set();
1999
+ let restoring = Boolean(sessionId);
2000
+ let quietTimer;
2001
+ let maxTimer;
2002
+ const restored = () => {
2003
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
2004
+ if (maxTimer !== void 0) clearTimeout(maxTimer);
2005
+ quietTimer = maxTimer = void 0;
2006
+ if (!restoring) return;
2007
+ restoring = false;
2008
+ changed();
2009
+ };
2010
+ const quietSoon = () => {
2011
+ if (!restoring) return;
2012
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
2013
+ quietTimer = setTimeout(restored, REPLAY_QUIET_MS);
2014
+ maxTimer ??= setTimeout(restored, REPLAY_MAX_MS);
2015
+ };
1989
2016
  const changed = () => {
1990
2017
  snapshot = void 0;
1991
2018
  for (const listener of [...listeners]) {
@@ -2203,6 +2230,7 @@ var createRemoteAgentController = (options) => {
2203
2230
  );
2204
2231
  const reader = res.body?.getReader();
2205
2232
  if (!reader) throw new Error("the event stream has no body");
2233
+ quietSoon();
2206
2234
  cancelBody = () => void reader.cancel().catch(() => {
2207
2235
  });
2208
2236
  if (ac.signal.aborted) cancelBody();
@@ -2225,6 +2253,7 @@ var createRemoteAgentController = (options) => {
2225
2253
  const { done, value } = await reader.read();
2226
2254
  if (done || generation !== streamGeneration) break;
2227
2255
  parser.push(decoder.decode(value, { stream: true }));
2256
+ quietSoon();
2228
2257
  }
2229
2258
  } catch (err) {
2230
2259
  if (generation === streamGeneration && !disposed) {
@@ -2239,6 +2268,7 @@ var createRemoteAgentController = (options) => {
2239
2268
  } finally {
2240
2269
  if (cancelBody) ac.signal.removeEventListener("abort", cancelBody);
2241
2270
  if (streamAbort === ac) streamAbort = void 0;
2271
+ if (generation === streamGeneration) restored();
2242
2272
  }
2243
2273
  scheduleReconnect(generation);
2244
2274
  };
@@ -2253,6 +2283,7 @@ var createRemoteAgentController = (options) => {
2253
2283
  }
2254
2284
  };
2255
2285
  const forgetSession = () => {
2286
+ restored();
2256
2287
  closeStream();
2257
2288
  cursor = void 0;
2258
2289
  lastCursor = void 0;
@@ -2379,12 +2410,16 @@ var createRemoteAgentController = (options) => {
2379
2410
  const next = chat.sessionId?.trim();
2380
2411
  if (!next || next === sessionId) return;
2381
2412
  reset();
2413
+ restoring = true;
2382
2414
  setSession(next);
2383
2415
  void openStream();
2384
2416
  };
2385
2417
  const dispose = () => {
2386
2418
  if (disposed) return;
2387
2419
  disposed = true;
2420
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
2421
+ if (maxTimer !== void 0) clearTimeout(maxTimer);
2422
+ quietTimer = maxTimer = void 0;
2388
2423
  closeStream();
2389
2424
  for (const [id, done] of runs) runs.delete(id), done(void 0);
2390
2425
  listeners.clear();
@@ -2394,7 +2429,7 @@ var createRemoteAgentController = (options) => {
2394
2429
  throw new Error(`${what} is not available for an agent on a server`);
2395
2430
  };
2396
2431
  return {
2397
- getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering),
2432
+ getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering, restoring),
2398
2433
  subscribe: (listener) => {
2399
2434
  if (disposed) return () => {
2400
2435
  };
@@ -2932,6 +2967,8 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
2932
2967
  };
2933
2968
  // Annotate the CommonJS export names for ESM import in node:
2934
2969
  0 && (module.exports = {
2970
+ REPLAY_MAX_MS,
2971
+ REPLAY_QUIET_MS,
2935
2972
  createAgentController,
2936
2973
  createInitialAgentSnapshot,
2937
2974
  createInitialRemoteSnapshot,
@@ -104,6 +104,10 @@ declare const remoteEventScope: (event: {
104
104
  * which the stream stores as `{ name, message }` - the reducer wants its text.
105
105
  */
106
106
  declare const remoteEventOf: (event: Record<string, unknown>) => AgentEvent;
107
+ /** The replay of a session given is in once its stream has been quiet this long (ms). */
108
+ declare const REPLAY_QUIET_MS = 150;
109
+ /** …and at the latest this long after it opened (ms): a view never waits on a placeholder. */
110
+ declare const REPLAY_MAX_MS = 5000;
107
111
  /** The snapshot of a remote controller before anything happened (what a view shows first). */
108
112
  declare const createInitialRemoteSnapshot: (options?: Pick<RemoteAgentOptions, "sessionId">) => AgentControllerSnapshot;
109
113
  /**
@@ -252,6 +256,12 @@ interface AgentControllerSnapshot extends AgentUiState {
252
256
  pendingQuestions: PendingQuestion[];
253
257
  /** The consent policy in effect. */
254
258
  approvalMode: ToolApprovalMode;
259
+ /**
260
+ * A conversation is being read back (an agent on a server: the session's stream replaying what
261
+ * was said): its transcript is on the way, so a view shows a placeholder - not the empty state.
262
+ * Absent (false) for an agent in the page, whose saved chats say so themselves.
263
+ */
264
+ restoring?: boolean;
255
265
  }
256
266
  /** What a view calls. Each keeps its identity for the controller's life. */
257
267
  interface AgentControllerActions {
@@ -404,5 +414,5 @@ declare const createInitialAgentSnapshot: (config: BrowserAgentConfig) => AgentC
404
414
  */
405
415
  declare const createAgentController: (initialConfig: BrowserAgentConfig, initialOptions?: AgentControllerOptions) => AgentController;
406
416
 
407
- export { PageContext, PageContextCollector, PageContextOptions, createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
417
+ export { PageContext, PageContextCollector, PageContextOptions, REPLAY_MAX_MS, REPLAY_QUIET_MS, createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
408
418
  export type { AgentController, AgentControllerActions, AgentControllerOptions, AgentControllerSnapshot, AgentControllerUpdate, AppToolCall, ApproveOptions, RemoteAgentHeaders, RemoteAgentOptions, RemoteEventInfo, RemoteFrame, RunGoalOptions, SendOptions };
@@ -104,6 +104,10 @@ declare const remoteEventScope: (event: {
104
104
  * which the stream stores as `{ name, message }` - the reducer wants its text.
105
105
  */
106
106
  declare const remoteEventOf: (event: Record<string, unknown>) => AgentEvent;
107
+ /** The replay of a session given is in once its stream has been quiet this long (ms). */
108
+ declare const REPLAY_QUIET_MS = 150;
109
+ /** …and at the latest this long after it opened (ms): a view never waits on a placeholder. */
110
+ declare const REPLAY_MAX_MS = 5000;
107
111
  /** The snapshot of a remote controller before anything happened (what a view shows first). */
108
112
  declare const createInitialRemoteSnapshot: (options?: Pick<RemoteAgentOptions, "sessionId">) => AgentControllerSnapshot;
109
113
  /**
@@ -252,6 +256,12 @@ interface AgentControllerSnapshot extends AgentUiState {
252
256
  pendingQuestions: PendingQuestion[];
253
257
  /** The consent policy in effect. */
254
258
  approvalMode: ToolApprovalMode;
259
+ /**
260
+ * A conversation is being read back (an agent on a server: the session's stream replaying what
261
+ * was said): its transcript is on the way, so a view shows a placeholder - not the empty state.
262
+ * Absent (false) for an agent in the page, whose saved chats say so themselves.
263
+ */
264
+ restoring?: boolean;
255
265
  }
256
266
  /** What a view calls. Each keeps its identity for the controller's life. */
257
267
  interface AgentControllerActions {
@@ -404,5 +414,5 @@ declare const createInitialAgentSnapshot: (config: BrowserAgentConfig) => AgentC
404
414
  */
405
415
  declare const createAgentController: (initialConfig: BrowserAgentConfig, initialOptions?: AgentControllerOptions) => AgentController;
406
416
 
407
- export { PageContext, PageContextCollector, PageContextOptions, createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
417
+ export { PageContext, PageContextCollector, PageContextOptions, REPLAY_MAX_MS, REPLAY_QUIET_MS, createAgentController, createInitialAgentSnapshot, createInitialRemoteSnapshot, createRemoteAgentController, createSseParser, parseRemoteCursor, remoteEventOf, remoteEventScope };
408
418
  export type { AgentController, AgentControllerActions, AgentControllerOptions, AgentControllerSnapshot, AgentControllerUpdate, AppToolCall, ApproveOptions, RemoteAgentHeaders, RemoteAgentOptions, RemoteEventInfo, RemoteFrame, RunGoalOptions, SendOptions };
@@ -95,8 +95,15 @@ var GatewayError = class extends Error {
95
95
  status;
96
96
  code;
97
97
  };
98
- var createInitialRemoteSnapshot = (options = {}) => snapshotOf({ ...createInitialAgentState(), status: "ready" }, options.sessionId ?? "", /* @__PURE__ */ new Set());
99
- var snapshotOf = (state, sessionId, answering) => Object.freeze({
98
+ var REPLAY_QUIET_MS = 150;
99
+ var REPLAY_MAX_MS = 5e3;
100
+ var createInitialRemoteSnapshot = (options = {}) => snapshotOf(
101
+ { ...createInitialAgentState(), status: "ready" },
102
+ options.sessionId ?? "",
103
+ /* @__PURE__ */ new Set(),
104
+ Boolean(options.sessionId?.trim())
105
+ );
106
+ var snapshotOf = (state, sessionId, answering, restoring = false) => Object.freeze({
100
107
  ...state,
101
108
  isRunning: state.status === "running",
102
109
  isReady: state.status === "ready",
@@ -107,7 +114,8 @@ var snapshotOf = (state, sessionId, answering) => Object.freeze({
107
114
  pendingQuestions: [],
108
115
  // The server's policy decides; a view hides the switch for a remote agent.
109
116
  approvalMode: "ask-writes",
110
- sessionId
117
+ sessionId,
118
+ restoring
111
119
  });
112
120
  var createRemoteAgentController = (options) => {
113
121
  const base = options.baseUrl.replace(/\/+$/, "");
@@ -122,6 +130,23 @@ var createRemoteAgentController = (options) => {
122
130
  let snapshot;
123
131
  const listeners = /* @__PURE__ */ new Set();
124
132
  const answering = /* @__PURE__ */ new Set();
133
+ let restoring = Boolean(sessionId);
134
+ let quietTimer;
135
+ let maxTimer;
136
+ const restored = () => {
137
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
138
+ if (maxTimer !== void 0) clearTimeout(maxTimer);
139
+ quietTimer = maxTimer = void 0;
140
+ if (!restoring) return;
141
+ restoring = false;
142
+ changed();
143
+ };
144
+ const quietSoon = () => {
145
+ if (!restoring) return;
146
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
147
+ quietTimer = setTimeout(restored, REPLAY_QUIET_MS);
148
+ maxTimer ??= setTimeout(restored, REPLAY_MAX_MS);
149
+ };
125
150
  const changed = () => {
126
151
  snapshot = void 0;
127
152
  for (const listener of [...listeners]) {
@@ -339,6 +364,7 @@ var createRemoteAgentController = (options) => {
339
364
  );
340
365
  const reader = res.body?.getReader();
341
366
  if (!reader) throw new Error("the event stream has no body");
367
+ quietSoon();
342
368
  cancelBody = () => void reader.cancel().catch(() => {
343
369
  });
344
370
  if (ac.signal.aborted) cancelBody();
@@ -361,6 +387,7 @@ var createRemoteAgentController = (options) => {
361
387
  const { done, value } = await reader.read();
362
388
  if (done || generation !== streamGeneration) break;
363
389
  parser.push(decoder.decode(value, { stream: true }));
390
+ quietSoon();
364
391
  }
365
392
  } catch (err) {
366
393
  if (generation === streamGeneration && !disposed) {
@@ -375,6 +402,7 @@ var createRemoteAgentController = (options) => {
375
402
  } finally {
376
403
  if (cancelBody) ac.signal.removeEventListener("abort", cancelBody);
377
404
  if (streamAbort === ac) streamAbort = void 0;
405
+ if (generation === streamGeneration) restored();
378
406
  }
379
407
  scheduleReconnect(generation);
380
408
  };
@@ -389,6 +417,7 @@ var createRemoteAgentController = (options) => {
389
417
  }
390
418
  };
391
419
  const forgetSession = () => {
420
+ restored();
392
421
  closeStream();
393
422
  cursor = void 0;
394
423
  lastCursor = void 0;
@@ -515,12 +544,16 @@ var createRemoteAgentController = (options) => {
515
544
  const next = chat.sessionId?.trim();
516
545
  if (!next || next === sessionId) return;
517
546
  reset();
547
+ restoring = true;
518
548
  setSession(next);
519
549
  void openStream();
520
550
  };
521
551
  const dispose = () => {
522
552
  if (disposed) return;
523
553
  disposed = true;
554
+ if (quietTimer !== void 0) clearTimeout(quietTimer);
555
+ if (maxTimer !== void 0) clearTimeout(maxTimer);
556
+ quietTimer = maxTimer = void 0;
524
557
  closeStream();
525
558
  for (const [id, done] of runs) runs.delete(id), done(void 0);
526
559
  listeners.clear();
@@ -530,7 +563,7 @@ var createRemoteAgentController = (options) => {
530
563
  throw new Error(`${what} is not available for an agent on a server`);
531
564
  };
532
565
  return {
533
- getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering),
566
+ getSnapshot: () => snapshot ??= snapshotOf(state, sessionId ?? "", answering, restoring),
534
567
  subscribe: (listener) => {
535
568
  if (disposed) return () => {
536
569
  };
@@ -1067,6 +1100,8 @@ var createAgentController = (initialConfig, initialOptions = {}) => {
1067
1100
  };
1068
1101
  };
1069
1102
  export {
1103
+ REPLAY_MAX_MS,
1104
+ REPLAY_QUIET_MS,
1070
1105
  createAgentController,
1071
1106
  createInitialAgentSnapshot,
1072
1107
  createInitialRemoteSnapshot,