@tangle-network/agent-app 0.46.36 → 0.46.40

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.
Files changed (44) hide show
  1. package/README.md +8 -7
  2. package/dist/assets/index.js +18 -0
  3. package/dist/assets/index.js.map +1 -1
  4. package/dist/assets/schema.d.ts +657 -0
  5. package/dist/assistant/index.js +5 -5
  6. package/dist/chat-react/index.js +2 -2
  7. package/dist/chat-routes/index.js +2 -2
  8. package/dist/chat-store/index.js +1 -1
  9. package/dist/{chunk-BDMDL4AB.js → chunk-HJBLT2BW.js} +1 -1
  10. package/dist/chunk-HJBLT2BW.js.map +1 -0
  11. package/dist/{chunk-64EVYEGI.js → chunk-PZOTRGGQ.js} +162 -8
  12. package/dist/chunk-PZOTRGGQ.js.map +1 -0
  13. package/dist/{chunk-7NP744YO.js → chunk-QK4IFP3E.js} +3 -3
  14. package/dist/{chunk-7NP744YO.js.map → chunk-QK4IFP3E.js.map} +1 -1
  15. package/dist/{chunk-EDTWGSQT.js → chunk-SJWIZT7B.js} +6 -2
  16. package/dist/{chunk-EDTWGSQT.js.map → chunk-SJWIZT7B.js.map} +1 -1
  17. package/dist/{chunk-CYSN24KI.js → chunk-U2UAQTFY.js} +2 -2
  18. package/dist/{chunk-4XWVCO7P.js → chunk-Z4TPWP6A.js} +13 -3
  19. package/dist/chunk-Z4TPWP6A.js.map +1 -0
  20. package/dist/{chunk-4SGGSXI7.js → chunk-ZMMIQOFI.js} +6 -5
  21. package/dist/chunk-ZMMIQOFI.js.map +1 -0
  22. package/dist/sandbox/foreground-single-flight.d.ts +62 -0
  23. package/dist/sandbox/index.d.ts +1 -0
  24. package/dist/sandbox/index.js +13 -1
  25. package/dist/sandbox/prewarm-claim-d1.d.ts +15 -8
  26. package/dist/sandbox/prewarm.d.ts +44 -0
  27. package/dist/session-shell/index.js +1 -1
  28. package/dist/signoff/cli.js +1 -1
  29. package/dist/signoff/index.js +1 -1
  30. package/dist/signoff/workflow-pin.d.ts +3 -2
  31. package/dist/stream/index.js +1 -1
  32. package/dist/studio-react/index.js +2 -2
  33. package/dist/trace/index.d.ts +1 -0
  34. package/dist/trace/index.js +240 -0
  35. package/dist/trace/index.js.map +1 -1
  36. package/dist/trace/stage-timing.d.ts +61 -0
  37. package/dist/web-react/index.js +5 -5
  38. package/dist/workspace-react/index.js +1 -1
  39. package/package.json +13 -13
  40. package/dist/chunk-4SGGSXI7.js.map +0 -1
  41. package/dist/chunk-4XWVCO7P.js.map +0 -1
  42. package/dist/chunk-64EVYEGI.js.map +0 -1
  43. package/dist/chunk-BDMDL4AB.js.map +0 -1
  44. /package/dist/{chunk-CYSN24KI.js.map → chunk-U2UAQTFY.js.map} +0 -0
@@ -406,7 +406,11 @@ function activeSessionIdFromPath({
406
406
  const id = path.slice(prefix.length + 1).split("/")[0] ?? "";
407
407
  if (!id || id === newSegment) return null;
408
408
  if (reserved?.some((name) => stripSlashes(name) === id)) return null;
409
- return decodeURIComponent(id);
409
+ try {
410
+ return decodeURIComponent(id);
411
+ } catch {
412
+ return null;
413
+ }
410
414
  }
411
415
  function resolveActiveNavId({
412
416
  pathname,
@@ -519,4 +523,4 @@ export {
519
523
  railCollapsedCookie,
520
524
  writeRailCollapsedCookie
521
525
  };
522
- //# sourceMappingURL=chunk-EDTWGSQT.js.map
526
+ //# sourceMappingURL=chunk-SJWIZT7B.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/session-shell/path.ts","../src/session-shell/nav-guard.ts","../src/session-shell/command-palette.ts","../src/session-shell/index.ts"],"sourcesContent":["/**\n * Path normalisation shared by the shell's routing helpers. Segment-aligned\n * comparison is the invariant: `/vault` must never claim `/vault-archive`, so\n * every prefix test here works on whole segments rather than string prefixes.\n */\n\nexport function stripTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\n/** Bare segment name, so a caller may pass `'/settings'` or `'settings'`. */\nexport function stripSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\n/** Path with query + fragment removed and trailing slashes trimmed. A caller\n * passing a full href instead of a pathname would otherwise match nothing. */\nexport function normalizePath(pathname: string): string {\n const withoutHash = pathname.split('#')[0] ?? ''\n const withoutQuery = withoutHash.split('?')[0] ?? ''\n return stripTrailingSlashes(withoutQuery)\n}\n\n/** True when `path` is `prefix` or a segment-aligned descendant of it, so\n * `/vault` never claims `/vault-archive`. */\nexport function isUnderPrefix(path: string, prefix: string): boolean {\n const p = stripTrailingSlashes(prefix)\n if (p === '') return true\n return path === p || path.startsWith(`${p}/`)\n}\n\n/** Non-empty segments of a path or route pattern. Leading/trailing/duplicate\n * slashes collapse, so `/app//x/` and `app/x` compare equal. */\nexport function toSegments(value: string): string[] {\n return value.split('/').filter((segment) => segment.length > 0)\n}\n\n/** Canonical display form: rooted, no trailing slash, no empty segments. */\nexport function toRootedPath(value: string): string {\n return `/${toSegments(value).join('/')}`\n}\n","/**\n * Nav destinations, and the guard that proves every href the rail renders\n * resolves to a route the product's router actually registered.\n *\n * A rail row's href is assembled from a base plus a relative path, and nothing\n * downstream re-checks it: the sidebar renders a link, the click navigates, and\n * the router answers 404. A unit test written against the nav builder alone\n * cannot catch that — it asserts the href the builder produced, which is the\n * same wrong string the user clicks.\n *\n * Two mechanisms, meant to be used together:\n *\n * 1. `NavDestination` makes the base a REQUIRED discriminant (`scope`). An\n * optional `absolute?: boolean`-style flag has the opposite property:\n * omitting it type-checks, and the destination silently resolves under the\n * workspace prefix instead of the app-level one. A required literal union\n * turns that omission into a compile error, and widening `TScope` demands a\n * base for the new scope rather than defaulting to a wrong one.\n * 2. `assertNavHrefsRegistered` matches every resolved href against the route\n * table, so a destination the router never registered fails a test instead\n * of a user's click. It reads the product's real route table, so it cannot\n * agree with the builder's mistake the way a hand-maintained expected-href\n * list does.\n */\n\nimport { isUnderPrefix, normalizePath, stripTrailingSlashes, toRootedPath, toSegments } from './path'\n\n// ---------------------------------------------------------------------------\n// Destinations — the base is a required discriminant, never an optional flag\n// ---------------------------------------------------------------------------\n\n/** The bases a product routes rail rows under. `workspace` is the per-workspace\n * prefix (`/app/ws_123`); `app` is the account-level one (`/app`), where\n * singleton surfaces such as a shared terminal or billing live. */\nexport type NavScope = 'workspace' | 'app'\n\n/** A base path per scope. Widening `TScope` widens this record, so a product\n * that adds a scope cannot compile until it supplies that scope's base. */\nexport type NavScopeBases<TScope extends string = NavScope> = Readonly<Record<TScope, string>>\n\n/** One rail destination as the product declares it, before a base is applied. */\nexport interface NavDestination<TScope extends string = NavScope> {\n id: string\n /** Path relative to the base named by `scope`. `''` is the base itself.\n * Must be empty or start with `/` — a bare `'vault'` would concatenate into\n * `/app/ws_123vault`, so it is rejected rather than silently repaired. */\n path: string\n /** Which base `path` resolves against. Required on purpose. */\n scope: TScope\n}\n\n/** A destination with its base applied. */\nexport interface ResolvedNavDestination<TScope extends string = NavScope> {\n id: string\n href: string\n scope: TScope\n}\n\n/** Apply a destination's scope base to its path.\n *\n * Throws when the scope has no base configured — a product that assembles\n * `bases` dynamically can defeat the type-level guarantee, and a missing base\n * would otherwise produce `undefined/vault`. */\nexport function resolveNavHref<TScope extends string>(\n destination: NavDestination<TScope>,\n bases: NavScopeBases<TScope>,\n): string {\n const base = bases[destination.scope]\n if (typeof base !== 'string') {\n throw new Error(\n `Nav destination '${destination.id}' uses scope '${destination.scope}', which has no configured base`,\n )\n }\n if (destination.path !== '' && !destination.path.startsWith('/')) {\n throw new Error(\n `Nav destination '${destination.id}' path must be empty or start with '/' (got '${destination.path}')`,\n )\n }\n const rooted = `${stripTrailingSlashes(base)}${destination.path}`\n return rooted === '' ? '/' : stripTrailingSlashes(rooted)\n}\n\n/** Apply the bases to every destination, preserving declaration order. */\nexport function resolveNavDestinations<TScope extends string>(\n destinations: readonly NavDestination<TScope>[],\n bases: NavScopeBases<TScope>,\n): ResolvedNavDestination<TScope>[] {\n return destinations.map((destination) => ({\n id: destination.id,\n href: resolveNavHref(destination, bases),\n scope: destination.scope,\n }))\n}\n\nexport interface ResolveScopedActiveNavIdOptions<TScope extends string = NavScope> {\n pathname: string\n destinations: readonly NavDestination<TScope>[]\n bases: NavScopeBases<TScope>\n /** Extra ABSOLUTE prefixes that light an existing row, e.g.\n * `{ '/app/ws_1/agents': 'integrations' }`. Same longest-prefix contest. */\n aliases?: Readonly<Record<string, string>>\n /** ABSOLUTE prefixes that deliberately highlight nothing, beating any shorter\n * match. */\n claimsNothing?: readonly string[]\n}\n\n/**\n * The rail row to highlight, across scopes.\n *\n * `resolveActiveNavId` resolves rows against ONE base, so an app-level row can\n * only be highlighted by a second, hand-rolled scan — the same split that lets\n * an app-level destination render under the workspace base. This resolves the\n * hrefs first and runs a single longest-prefix contest over absolute paths, so\n * declaration order cannot change the answer and no scope needs its own pass.\n *\n * Prefixes in `aliases` / `claimsNothing` are absolute here, unlike\n * `resolveActiveNavId`'s base-relative ones, because the contest itself is\n * absolute.\n */\nexport function resolveScopedActiveNavId<TScope extends string>({\n pathname,\n destinations,\n bases,\n aliases,\n claimsNothing,\n}: ResolveScopedActiveNavIdOptions<TScope>): string | undefined {\n const path = normalizePath(pathname)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (candidate: string, id: string | undefined, winsTies = false): void => {\n const full = stripTrailingSlashes(candidate)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const resolved of resolveNavDestinations(destinations, bases)) consider(resolved.href, resolved.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix here is a\n // deliberate override of the row that owns it.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Route table — structurally the product's own router config\n// ---------------------------------------------------------------------------\n\n/**\n * One entry of a registered route table. Structurally compatible with\n * react-router's `RouteConfigEntry`, so a product passes its real `routes.ts`\n * default export straight in — the point of the guard is that it reads the\n * router's own truth rather than a second list that can agree with the bug.\n */\nexport interface RegisteredRoute {\n /** Absent on a pathless layout route: its children inherit the parent path. */\n path?: string\n index?: boolean\n children?: readonly RegisteredRoute[]\n}\n\n/** A route table entry is either a bare pattern string or a router config node. */\nexport type NavRouteTable = readonly (string | RegisteredRoute)[]\n\nfunction joinPattern(parent: string, child: string): string {\n if (child.startsWith('/')) return child\n if (child === '') return parent\n return `${parent}/${child}`\n}\n\n/**\n * Every path pattern the table registers, rooted and de-duplicated.\n *\n * Parent nodes contribute their own cumulative path as well as their children's:\n * a router matches a parent route with an index child at the parent path, and a\n * parent without one still matches with an empty outlet, so treating parents as\n * unregistered would flag working hrefs.\n */\nexport function flattenRouteTable(table: NavRouteTable): string[] {\n const patterns: string[] = []\n const walk = (entries: NavRouteTable, parent: string): void => {\n for (const entry of entries) {\n if (typeof entry === 'string') {\n patterns.push(toRootedPath(joinPattern(parent, entry)))\n continue\n }\n const own = entry.path === undefined ? parent : joinPattern(parent, entry.path)\n patterns.push(toRootedPath(own))\n if (entry.children) walk(entry.children, own)\n }\n }\n walk(table, '')\n return [...new Set(patterns)]\n}\n\n/**\n * Whole-path segment match of a concrete path against one route pattern.\n *\n * Supports the three pattern forms a router uses: literal segments, `:param`\n * (exactly one non-empty segment), optional `:param?` / `segment?` (zero or\n * one), and a trailing `*` splat (zero or more). Matching is recursive because\n * an optional segment forks the walk — a linear scan silently mismatches\n * `/a/b` against `a/:x?/b`.\n */\nfunction matchesPattern(pathSegments: readonly string[], patternSegments: readonly string[], caseSensitive: boolean): boolean {\n if (patternSegments.length === 0) return pathSegments.length === 0\n const head = patternSegments[0] ?? ''\n if (head === '*') return true\n const rest = patternSegments.slice(1)\n const optional = head.endsWith('?')\n const core = optional ? head.slice(0, -1) : head\n const first = pathSegments[0]\n if (first !== undefined) {\n const hit = core.startsWith(':')\n ? first.length > 0\n : caseSensitive\n ? core === first\n : core.toLowerCase() === first.toLowerCase()\n if (hit && matchesPattern(pathSegments.slice(1), rest, caseSensitive)) return true\n }\n return optional ? matchesPattern(pathSegments, rest, caseSensitive) : false\n}\n\n// ---------------------------------------------------------------------------\n// The guard\n// ---------------------------------------------------------------------------\n\n/**\n * A nav row as the guard needs to see it. Structurally satisfied by\n * `SessionRailNavItem` / `SessionRailSubItem` and by sandbox-ui's\n * `SidebarLayoutNavItem`, so the guard runs over the builder's real output\n * rather than a re-declaration of it.\n */\nexport interface NavHrefItem {\n id: string\n href: string\n subItems?: readonly NavHrefItem[]\n}\n\nexport type NavHrefProblemReason =\n /** No registered pattern matches the resolved href. */\n | 'unregistered'\n /** Empty, fragment-only, or not rooted at `/` — the row navigates nowhere\n * predictable regardless of the route table. */\n | 'not-a-path'\n /** Leaves the router (scheme or protocol-relative) while `allowExternal` is\n * off. */\n | 'external'\n\nexport interface NavHrefProblem {\n id: string\n href: string\n reason: NavHrefProblemReason\n /** Registered patterns ending in the same segment. A destination resolved\n * under the wrong base lands here as its correctly-based twin, which is what\n * names the missing scope in the failure message. */\n nearest: string[]\n message: string\n}\n\nexport interface NavHrefReport {\n /** Hrefs examined, including nested sub-items. */\n checked: number\n problems: NavHrefProblem[]\n /** Off-router destinations accepted because `allowExternal` is on. */\n external: string[]\n /** The flattened route table the check ran against. */\n patterns: string[]\n}\n\nexport interface NavHrefCheckOptions {\n /** Hrefs to skip, compared after query/fragment removal. For a destination\n * served outside this route table (a static asset, another worker). */\n ignore?: readonly string[]\n /** Absolute URLs / `mailto:` / `tel:` are reported under `external` instead\n * of failing. Default true. */\n allowExternal?: boolean\n /** Compare literal segments case-sensitively. Default true — a router that\n * matches case-insensitively still renders a link the deploy's CDN or a\n * case-sensitive origin may not. */\n caseSensitive?: boolean\n}\n\n/** `scheme:` or `//host` — anything the router will not resolve as a path. */\nconst OFF_ROUTER_HREF = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i\n\nfunction flattenItems(items: readonly NavHrefItem[], out: NavHrefItem[] = []): NavHrefItem[] {\n for (const item of items) {\n out.push(item)\n if (item.subItems) flattenItems(item.subItems, out)\n }\n return out\n}\n\n/**\n * Check every nav href against the product's route table.\n *\n * Pure — returns the full report so a caller can assert on parts of it. Use\n * {@link assertNavHrefsRegistered} in tests; it turns the report into a failure\n * that names the offending row, its resolved href, and the near-miss pattern.\n */\nexport function checkNavHrefs(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): NavHrefReport {\n const { ignore, allowExternal = true, caseSensitive = true } = options\n const patterns = flattenRouteTable(routes)\n const patternSegments = patterns.map((pattern) => ({ pattern, segments: toSegments(pattern) }))\n const ignored = new Set((ignore ?? []).map((href) => normalizePath(href)))\n const problems: NavHrefProblem[] = []\n const external: string[] = []\n const flat = flattenItems(items)\n let checked = 0\n\n for (const item of flat) {\n const raw = item.href\n const path = normalizePath(raw)\n if (ignored.has(path)) continue\n if (OFF_ROUTER_HREF.test(raw)) {\n if (allowExternal) {\n external.push(raw)\n continue\n }\n // Counted as checked: it was examined and rejected, so the vacuous-pass\n // guard must not read this run as \"nothing was looked at\".\n checked += 1\n problems.push({\n id: item.id,\n href: raw,\n reason: 'external',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' leaves the router, and external destinations are rejected`,\n })\n continue\n }\n checked += 1\n if (raw === '' || raw.startsWith('#') || !raw.startsWith('/')) {\n problems.push({\n id: item.id,\n href: raw,\n reason: 'not-a-path',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' is not a rooted path — it cannot resolve to a registered route`,\n })\n continue\n }\n const segments = toSegments(path)\n if (patternSegments.some((candidate) => matchesPattern(segments, candidate.segments, caseSensitive))) continue\n const nearest = nearestPatterns(segments, patternSegments.map((candidate) => candidate.pattern), caseSensitive)\n problems.push({\n id: item.id,\n href: raw,\n reason: 'unregistered',\n nearest,\n message:\n `Nav item '${item.id}' href '${raw}' matches no registered route` +\n (nearest.length ? ` — nearest registered: ${nearest.join(', ')}` : ''),\n })\n }\n\n return { checked, problems, external, patterns }\n}\n\n/** Registered patterns whose last segment equals the href's last segment: the\n * same destination under a different base is the near-miss worth printing. */\nfunction nearestPatterns(segments: readonly string[], patterns: readonly string[], caseSensitive: boolean): string[] {\n const tail = segments[segments.length - 1]\n if (tail === undefined) return []\n const same = (a: string, b: string): boolean => (caseSensitive ? a === b : a.toLowerCase() === b.toLowerCase())\n return patterns\n .filter((pattern) => {\n const patternTail = toSegments(pattern).at(-1)\n return patternTail !== undefined && same(patternTail, tail)\n })\n .slice(0, 5)\n}\n\n/**\n * Fail unless every nav href resolves to a registered route.\n *\n * Throws on an empty item list or an empty route table as well: a guard that\n * examined nothing reports safety it does not provide, and both are what a\n * mis-wired import looks like.\n */\nexport function assertNavHrefsRegistered(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): void {\n if (items.length === 0) {\n throw new Error('assertNavHrefsRegistered received no nav items — the check would pass without examining anything')\n }\n const report = checkNavHrefs(items, routes, options)\n if (report.patterns.length === 0) {\n throw new Error('assertNavHrefsRegistered received an empty route table — every href would fail or nothing would be proven')\n }\n // Real problems are reported before the vacuous-pass guard: rejected external\n // hrefs are problems that were never \"checked\", and the guard's message would\n // otherwise hide them.\n if (report.problems.length > 0) {\n const detail = report.problems.map((problem) => ` - ${problem.message}`).join('\\n')\n throw new Error(\n `${report.problems.length} of ${report.checked} nav hrefs do not resolve to a registered route:\\n${detail}\\n` +\n `Registered patterns (${report.patterns.length}): ${report.patterns.join(', ')}`,\n )\n }\n if (report.checked === 0) {\n throw new Error(\n `assertNavHrefsRegistered examined 0 hrefs (${report.external.length} external, ${ignoredCount(items, options)} ignored) — the check would pass without examining anything`,\n )\n }\n}\n\nfunction ignoredCount(items: readonly NavHrefItem[], options: NavHrefCheckOptions): number {\n const ignored = new Set((options.ignore ?? []).map((href) => normalizePath(href)))\n return flattenItems(items).filter((item) => ignored.has(normalizePath(item.href))).length\n}\n","/**\n * Command palette — the React-free selection half of the Cmd/Ctrl+K surface\n * (`/web-react` holds the rendered half, `CommandPalette`).\n *\n * Pure and import-free beyond this module's own types: no React, no DOM, no\n * fuse.js. A route loader or a worker can build and rank the same items the\n * browser renders.\n *\n * Domain stays a parameter. The palette knows two kinds of row — a SESSION the\n * user can jump to and an ACTION the product offers (new chat, toggle theme,\n * open settings) — and both arrive as data. What a selection DOES is the\n * product's business; the shell only builds, ranks, and groups.\n *\n * Ranking is the documented ladder, not a fuzzy library: exact > prefix >\n * word-prefix > substring (earlier index wins) > token-order, with keyword\n * hits ranked a fixed step below the same hit on the label. Deterministic —\n * no index-building, no async, same input always sorts the same way.\n */\n\nimport { sessionLabel, UNTITLED_SESSION_LABEL, type SessionSummary } from './index'\n\n/** A product-supplied palette action. `hint` is the right-aligned affordance\n * copy (a kbd chord, a route name) — rendered verbatim, never interpreted. */\nexport interface CommandPaletteAction {\n id: string\n label: string\n description?: string\n hint?: string\n /** Extra match vocabulary that never renders (`settings` matching\n * \"preferences\"). A keyword hit ranks below the same hit on the label. */\n keywords?: string[]\n}\n\n/** One selectable row. `group` is the section header it renders under. */\nexport interface CommandPaletteItem {\n id: string\n group: string\n label: string\n description?: string\n hint?: string\n keywords?: string[]\n /** Recency key (ISO-8601). Breaks score ties and orders the unfiltered\n * list recent-first. Rows without one sort below rows with one. */\n recentAt?: string | null\n}\n\n/** One rendered section: a header plus its rows, in first-seen group order. */\nexport interface CommandPaletteGroup {\n group: string\n items: CommandPaletteItem[]\n}\n\nexport const COMMAND_PALETTE_SESSIONS_GROUP = 'Sessions'\nexport const COMMAND_PALETTE_ACTIONS_GROUP = 'Actions'\n\nexport interface BuildCommandPaletteItemsOptions {\n sessions?: readonly SessionSummary[]\n actions?: readonly CommandPaletteAction[]\n /** Section label for sessions. Default \"Sessions\". */\n sessionsLabel?: string\n /** Section label for actions. Default \"Actions\". */\n actionsLabel?: string\n /** Placeholder title for an untitled session. */\n untitledLabel?: string\n}\n\n/**\n * Flatten sessions + actions into palette items, sessions group first (the\n * jump-back-in list), actions after. Sessions order recent-first by\n * `updatedAt` — a palette with an empty query IS the recency list, so the\n * build order is the render order and the filter never has to re-derive it.\n * Pinned sessions lead the recency sort, matching the rail.\n */\nexport function buildCommandPaletteItems({\n sessions = [],\n actions = [],\n sessionsLabel = COMMAND_PALETTE_SESSIONS_GROUP,\n actionsLabel = COMMAND_PALETTE_ACTIONS_GROUP,\n untitledLabel = UNTITLED_SESSION_LABEL,\n}: BuildCommandPaletteItemsOptions): CommandPaletteItem[] {\n const ordered = [...sessions].sort((a, b) => {\n if (!!a.isPinned !== !!b.isPinned) return a.isPinned ? -1 : 1\n return compareRecent(a.updatedAt, b.updatedAt)\n })\n const sessionItems: CommandPaletteItem[] = ordered.map((session) => ({\n id: session.id,\n group: sessionsLabel,\n label: sessionLabel(session, untitledLabel),\n keywords: session.category ? [session.category] : undefined,\n recentAt: session.updatedAt,\n }))\n const actionItems: CommandPaletteItem[] = actions.map((action) => ({\n id: action.id,\n group: actionsLabel,\n label: action.label,\n description: action.description,\n hint: action.hint,\n keywords: action.keywords,\n }))\n return [...sessionItems, ...actionItems]\n}\n\n/** Newer first; an undated row sorts below every dated one. ISO strings\n * compare lexicographically. */\nfunction compareRecent(a: string | null | undefined, b: string | null | undefined): number {\n if (a && b) return a < b ? 1 : a > b ? -1 : 0\n if (a) return -1\n if (b) return 1\n return 0\n}\n\n/** Collapse whitespace, lowercase once — every comparison runs on this form. */\nfunction normalize(text: string): string {\n return text.trim().toLowerCase().replace(/\\s+/g, ' ')\n}\n\n/** Words of a normalized string: runs of letters/numbers, so \"new-chat\" and\n * \"new chat\" word-prefix identically. */\nconst WORD_SPLIT = /[^\\p{L}\\p{N}]+/u\n\nfunction wordsOf(text: string): string[] {\n return text.split(WORD_SPLIT).filter(Boolean)\n}\n\n/** How far below a label hit the same keyword hit ranks: any label match, even\n * a token-order one (40), outranks a keyword exact match (100 − 65 = 35). */\nconst KEYWORD_PENALTY = 65\n\n/**\n * Score one text against the query on the prefix > substring > token-order\n * ladder. Returns `null` for no match. Higher is better; tiers are spaced so\n * no within-tier adjustment can cross a tier boundary:\n *\n * - 100 exact\n * - 90 prefix (`text` starts with the query)\n * - 80 word-prefix (a WORD starts with the query — \"chat\" hits \"New chat\")\n * - 60–79 substring, minus the match index clamped to 19 (earlier wins)\n * - 40 token-order (every query token matches a later word, in order)\n */\nfunction scoreText(text: string, query: string): number | null {\n if (!query) return 0\n if (text === query) return 100\n if (text.startsWith(query)) return 90\n const words = wordsOf(text)\n if (words.some((word) => word.startsWith(query))) return 80\n const at = text.indexOf(query)\n if (at >= 0) return 60 + Math.max(0, 19 - at)\n const tokens = wordsOf(query)\n if (tokens.length > 1) {\n let atWord = 0\n const inOrder = tokens.every((token) => {\n while (atWord < words.length) {\n const word = words[atWord]\n atWord += 1\n // Guarded by the while condition; noUncheckedIndexedAccess can't see it.\n if (word !== undefined && (word.startsWith(token) || word.includes(token))) return true\n }\n return false\n })\n if (inOrder) return 40\n }\n return null\n}\n\n/**\n * Score an item: the best label score, or the best keyword score a fixed step\n * below. `null` when neither matches — the item is filtered out. An empty\n * query scores every item 0 (the caller keeps build order: recent-first).\n */\nexport function scoreCommandPaletteItem(item: CommandPaletteItem, query: string): number | null {\n const q = normalize(query)\n const label = scoreText(normalize(item.label), q)\n let best = label\n for (const keyword of item.keywords ?? []) {\n const score = scoreText(normalize(keyword), q)\n if (score !== null) {\n const penalized = score - KEYWORD_PENALTY\n if (best === null || penalized > best) best = penalized\n }\n }\n return best\n}\n\n/**\n * Filter + rank: an empty query returns the items untouched (build order is\n * the recency order); a real query drops non-matches and sorts by score, then\n * recency, then original position — stable and deterministic.\n */\nexport function filterCommandPaletteItems(\n items: readonly CommandPaletteItem[],\n query: string,\n): CommandPaletteItem[] {\n if (!normalize(query)) return [...items]\n const scored: Array<{ item: CommandPaletteItem; score: number; index: number }> = []\n items.forEach((item, index) => {\n const score = scoreCommandPaletteItem(item, query)\n if (score !== null) scored.push({ item, score, index })\n })\n scored.sort((a, b) => {\n if (a.score !== b.score) return b.score - a.score\n const recent = compareRecent(a.item.recentAt, b.item.recentAt)\n if (recent !== 0) return recent\n return a.index - b.index\n })\n return scored.map(({ item }) => item)\n}\n\n/**\n * Fold a flat (already ordered) item list into renderable sections. Groups\n * appear in first-seen order and each group appears ONCE — a filtered ranking\n * interleaves sessions and actions by score, and folding only consecutive runs\n * would render the same header twice. Within a group, rows keep the flat\n * order. Empty groups vanish, so a filter that leaves only actions renders no\n * \"Sessions\" header over nothing.\n */\nexport function groupCommandPaletteItems(items: readonly CommandPaletteItem[]): CommandPaletteGroup[] {\n const groups: CommandPaletteGroup[] = []\n const byGroup = new Map<string, CommandPaletteGroup>()\n for (const item of items) {\n let group = byGroup.get(item.group)\n if (!group) {\n group = { group: item.group, items: [] }\n byGroup.set(item.group, group)\n groups.push(group)\n }\n group.items.push(item)\n }\n return groups\n}\n","/**\n * Session shell — the app-shell mechanism every agent product needs around the\n * chat surface: a list of past sessions in the rail, an entry point for a new\n * one, and a paged history view behind it.\n *\n * `/web-react` already owns the chat SURFACE (composer, transcript, cards); it\n * owned no session SHELL, so all four products hand-rolled one and drifted.\n * This module is the shell's pure half: no React, no DOM, no peer imports, so a\n * server loader can call `readRailCollapsedCookie` without dragging React into\n * a worker bundle (`/web-react` holds the rendered half).\n *\n * Domain stays a parameter. A \"session\" here is only an id, a title and a\n * timestamp — a gtm thread, a tax session and a legal matter are all the same\n * shape to the shell, and the product supplies routing through `hrefForSession`\n * rather than the shell knowing any URL.\n */\n\nimport { isUnderPrefix, normalizePath, stripSlashes, stripTrailingSlashes } from './path'\n\nexport * from './nav-guard'\nexport * from './command-palette'\n\n/** One session as the shell needs to see it. Products map their own row\n * (thread / session / matter) onto this before handing it over. */\nexport interface SessionSummary {\n id: string\n /** `null`/empty renders as the untitled placeholder rather than a blank row. */\n title: string | null\n /** ISO-8601. `null` when the product has no timestamp to show. */\n updatedAt: string | null\n isPinned?: boolean\n /** Unread for the viewer. Use `resolveSessionUnread` to fold live overlays in. */\n unread?: boolean\n /** Free-form product label (gtm categories, legal matter types). Passed\n * through untouched — the shell never interprets it. */\n category?: string | null\n}\n\n/** One fetched page of sessions with an optional continuation cursor. */\nexport interface SessionPage {\n items: SessionSummary[]\n /** Opaque continuation token; absent/null ⇒ no further pages. */\n nextCursor?: string | null\n}\n\n/** Sort order for the history view. The product's fetcher decides what these\n * mean against its own storage; the shell only round-trips the value. */\nexport type SessionSort = 'newest' | 'oldest'\n\n// ---------------------------------------------------------------------------\n// Rail items — structurally assignable to sandbox-ui's SidebarLayout types\n// ---------------------------------------------------------------------------\n\n/**\n * These mirror `@tangle-network/sandbox-ui/dashboard`'s `SidebarLayoutNavItem`\n * / `RailExpandableSubItem` STRUCTURALLY rather than importing them, so this\n * module stays free of the optional peer (invariant 3 — structural over\n * hard-dep when the surface is small). `tests/session-shell/rail-contract.test.ts`\n * assigns the builder output to the real sandbox-ui types, so a drift in either\n * direction fails CI instead of silently dropping a field at runtime.\n *\n * `TIcon` is the product's icon component type (lucide, custom, anything) —\n * generic so this file needs no React types.\n */\nexport interface SessionRailAction<TIcon = unknown> {\n id: string\n label: string\n icon?: TIcon\n destructive?: boolean\n onSelect: () => void\n}\n\nexport type RailPrefetch = 'none' | 'intent' | 'render' | 'viewport'\n\nexport interface SessionRailSubItem<TIcon = unknown> {\n id: string\n label: string\n href: string\n prefetch?: RailPrefetch\n /** Live working indicator — the session is mid-turn. */\n isLoading?: boolean\n /** Bold + leading dot. sandbox-ui suppresses it while `isLoading`. */\n unread?: boolean\n /** Emphasised row, used for the trailing \"view all\" overflow link. */\n emphasis?: boolean\n actions?: SessionRailAction<TIcon>[]\n}\n\nexport interface SessionRailNavItem<TIcon = unknown> {\n id: string\n /** REQUIRED, mirroring sandbox-ui — the rail renders `<Icon />` unguarded, so\n * an omitted icon is a blank/crashing row rather than a styling nit. */\n icon: TIcon\n label: string\n href: string\n badge?: number\n expandable?: boolean\n defaultOpen?: boolean\n subItems?: SessionRailSubItem<TIcon>[]\n subActiveIds?: string[]\n emptyLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Per-row rename/delete wiring. Supplied by the layout that owns the dialogs;\n * omitted (or `canEdit: false`) leaves rows read-only. */\nexport interface SessionRowActions<TIcon = unknown> {\n canEdit: boolean\n renameIcon?: TIcon\n deleteIcon?: TIcon\n renameLabel?: string\n deleteLabel?: string\n /**\n * Omit when the product cannot rename a session — the row then offers delete\n * only, instead of a menu item that does nothing.\n *\n * Independently optional, matching `SessionHistoryPanel`, which has always\n * rendered whichever of the two it was given. The rail builder used to demand\n * both, so a product with archive-but-no-rename (tax) could either fake a\n * rename or ship no row actions at all.\n */\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /**\n * Row actions this shell has no opinion about — pin, categorise, duplicate,\n * share. Evaluated per session so a label can read that row's state\n * (\"Pin\" vs \"Unpin\"), and ordered between rename and delete so the\n * destructive action stays last.\n *\n * `id` must not be `rename` or `delete`; those are the shell's own.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction<TIcon>[]\n}\n\nexport const UNTITLED_SESSION_LABEL = 'Untitled chat'\n\n/** Display title for a session row — trims, and falls back rather than\n * rendering an empty row the user cannot aim at. */\nexport function sessionLabel(session: SessionSummary, untitled = UNTITLED_SESSION_LABEL): string {\n return session.title?.trim() || untitled\n}\n\nexport interface BuildSessionSubItemsOptions<TIcon = unknown> {\n sessions: SessionSummary[]\n /** The product's route for one session. The shell never builds a URL itself. */\n hrefForSession: (sessionId: string) => string\n /** Ids currently mid-turn — renders the working indicator. */\n respondingSessionIds?: ReadonlySet<string>\n actions?: SessionRowActions<TIcon>\n untitledLabel?: string\n prefetch?: RailPrefetch\n /** Trailing \"view all\" row, appended when the capped list hides sessions. */\n overflow?: { href: string; label?: string }\n}\n\n/** Session rows for the rail's expandable history item. */\nexport function buildSessionSubItems<TIcon = unknown>({\n sessions,\n hrefForSession,\n respondingSessionIds,\n actions,\n untitledLabel = UNTITLED_SESSION_LABEL,\n prefetch = 'intent',\n overflow,\n}: BuildSessionSubItemsOptions<TIcon>): SessionRailSubItem<TIcon>[] {\n /**\n * Only the handlers the product actually supplied. An empty result becomes\n * `undefined` rather than `[]`, because sandbox-ui renders the kebab trigger\n * whenever `actions` is an array — an empty one is a button that opens an\n * empty menu.\n */\n const rowActions = (session: SessionSummary): SessionRailAction<TIcon>[] | undefined => {\n if (!actions?.canEdit) return undefined\n const built: SessionRailAction<TIcon>[] = []\n const { onRename, onDelete, extraActions } = actions\n if (onRename) {\n built.push({\n id: 'rename',\n label: actions.renameLabel ?? 'Rename',\n icon: actions.renameIcon,\n onSelect: () => onRename(session),\n })\n }\n if (extraActions) built.push(...extraActions(session))\n if (onDelete) {\n built.push({\n id: 'delete',\n label: actions.deleteLabel ?? 'Delete',\n icon: actions.deleteIcon,\n destructive: true,\n onSelect: () => onDelete(session),\n })\n }\n return built.length ? built : undefined\n }\n\n const rows: SessionRailSubItem<TIcon>[] = sessions.map((session) => ({\n id: session.id,\n label: sessionLabel(session, untitledLabel),\n href: hrefForSession(session.id),\n prefetch,\n isLoading: respondingSessionIds?.has(session.id) ?? false,\n unread: Boolean(session.unread),\n actions: rowActions(session),\n }))\n if (!overflow) return rows\n return [\n ...rows,\n {\n id: 'view-all',\n label: overflow.label ?? 'View all chats',\n href: overflow.href,\n prefetch,\n emphasis: true,\n },\n ]\n}\n\nexport interface BuildSessionNavItemOptions<TIcon = unknown>\n extends BuildSessionSubItemsOptions<TIcon> {\n /** Nav id the product highlights against (`activeNavId === id`). */\n id?: string\n label?: string\n /** The product's icon component. Required — see `SessionRailNavItem.icon`. */\n icon: TIcon\n /** The expandable row's own destination — the full history page. */\n href: string\n /** Session currently open, highlighted inside the expandable. */\n activeSessionId?: string | null\n emptyLabel?: string\n defaultOpen?: boolean\n}\n\n/**\n * The rail's session entry: one expandable nav row whose sub-items are the\n * recent sessions. This is the structure the owner asked for — history lives IN\n * the rail, not in a second sidebar panel beside it.\n */\nexport function buildSessionNavItem<TIcon = unknown>({\n id = 'history',\n label = 'History',\n icon,\n href,\n activeSessionId,\n emptyLabel = 'No chats yet',\n defaultOpen = true,\n ...subItemOptions\n}: BuildSessionNavItemOptions<TIcon>): SessionRailNavItem<TIcon> {\n return {\n id,\n icon,\n label,\n href,\n expandable: true,\n defaultOpen,\n subItems: buildSessionSubItems<TIcon>(subItemOptions),\n subActiveIds: activeSessionId ? [activeSessionId] : undefined,\n emptyLabel,\n prefetch: subItemOptions.prefetch ?? 'intent',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Routing / selection\n// ---------------------------------------------------------------------------\n\nexport interface ActiveSessionIdOptions {\n pathname: string\n /** Workspace-scoped route base, e.g. `/app/ws_123`. */\n base: string\n /** Route segment sessions live under. Default `chat` ⇒ `${base}/chat/:id`.\n * Pass `''` when sessions sit DIRECTLY under the base (`/app/:sessionId`),\n * which is how one product routes them — then `reserved` is mandatory. */\n segment?: string\n /** Segment that means \"composing a new session\", not an id. Default `new`. */\n newSegment?: string\n /**\n * First segments that are OTHER routes, not session ids. Only meaningful\n * with `segment: ''`, where `/app/settings` is otherwise indistinguishable\n * from a session called `settings` — and resolving it as one would highlight\n * and prefetch a session that does not exist. Pass the product's own nav\n * paths; unknown-but-reserved is a routing bug, so this fails closed.\n */\n reserved?: readonly string[]\n}\n\n/**\n * The session id the current route has open, or `null` on the new-session\n * composer / anywhere else.\n *\n * Anchored at `base` on purpose. A bare `/\\/chat\\/([^/]+)/` scan — the shape\n * three products shipped — matches the FIRST `/chat/` anywhere in the path, so\n * a workspace or vault folder named `chat` resolves a neighbouring segment as a\n * session id and the rail highlights (and prefetches) a session the user is not\n * in. Same class as attaching to a stale box: it looks right and points at the\n * wrong row.\n */\nexport function activeSessionIdFromPath({\n pathname,\n base,\n segment = 'chat',\n newSegment = 'new',\n reserved,\n}: ActiveSessionIdOptions): string | null {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n const prefix = segment ? `${root}/${segment}` : root\n if (!isUnderPrefix(path, prefix) || path === prefix) return null\n const id = path.slice(prefix.length + 1).split('/')[0] ?? ''\n if (!id || id === newSegment) return null\n // `/app/settings` under a segment-less route is a sibling page, not a\n // session named \"settings\".\n if (reserved?.some((name) => stripSlashes(name) === id)) return null\n return decodeURIComponent(id)\n}\n\n/** One rail destination. `path` is relative to the workspace base. */\nexport interface NavRouteDef {\n id: string\n path: string\n}\n\nexport interface ResolveActiveNavIdOptions {\n pathname: string\n base: string\n /** The product's rail rows, in any order — resolution is longest-prefix. */\n routes: NavRouteDef[]\n /** Extra prefixes that light an existing row: `{ '/agents': 'integrations' }`.\n * Participates in the same longest-prefix contest. */\n aliases?: Record<string, string>\n /** Prefixes that deliberately highlight NOTHING, beating any shorter match.\n * gtm uses this so an open chat lights no rail row while `/chat/new` still\n * lights \"New\". */\n claimsNothing?: string[]\n}\n\n/**\n * The rail row to highlight for the current route.\n *\n * Longest-prefix wins, so declaration order cannot change the answer. The\n * per-product versions this replaces were first-match over an array, which made\n * `/chat/new` vs `/chat` an ordering accident rather than a rule.\n */\nexport function resolveActiveNavId({\n pathname,\n base,\n routes,\n aliases,\n claimsNothing,\n}: ResolveActiveNavIdOptions): string | undefined {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (relative: string, id: string | undefined, winsTies = false) => {\n const full = stripTrailingSlashes(`${root}${relative}`)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const route of routes) consider(route.path, route.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix in\n // `claimsNothing` is a deliberate override of the row that owns it, so\n // `claimsNothing: ['/chat']` beats a `{ id: 'chat', path: '/chat' }` row while\n // a longer `/chat/new` still wins on specificity.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Sidebar list composition\n// ---------------------------------------------------------------------------\n\nexport interface ResolveSessionUnreadOptions {\n sessionId: string\n /** Server-computed unread from the route loader. */\n loaderUnread: boolean\n /** Live \"went unread\" ids from the workspace channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has already opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** The open session is never unread to its own viewer. */\n currentSessionId?: string | null\n}\n\n/**\n * Effective unread for one row. The loader's value can be stale — a layout\n * loader that survives same-workspace navigation keeps reporting a session as\n * unread after the user opened it — so live and local overlays win over it, and\n * the currently-open session always reads as read.\n */\nexport function resolveSessionUnread({\n sessionId,\n loaderUnread,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ResolveSessionUnreadOptions): boolean {\n if (sessionId === currentSessionId) return false\n if (liveUnreadIds?.has(sessionId)) return true\n if (locallyReadIds?.has(sessionId)) return false\n return loaderUnread\n}\n\nexport interface ComposeSidebarSessionsOptions {\n /** Server-rendered rows, already ordered by the product's query. */\n loaderSessions: SessionSummary[]\n /** Optimistic rows from the live channel (a chat created in another tab). */\n optimisticSessions?: SessionSummary[]\n /** Rail cap. The full list lives on the history page. */\n limit: number\n /** Total sessions the product holds, used to decide the overflow row. */\n totalCount?: number\n liveUnreadIds?: ReadonlySet<string>\n locallyReadIds?: ReadonlySet<string>\n currentSessionId?: string | null\n}\n\nexport interface ComposedSidebarSessions {\n sessions: SessionSummary[]\n /** More sessions exist than the rail shows ⇒ render the \"view all\" row. */\n hasMore: boolean\n}\n\n/**\n * The rail's session list: optimistic rows first, then the loader's, capped,\n * with unread resolved per row.\n *\n * Optimistic rows are deduped against the loader by id — once a revalidation\n * brings a live-created session back from the server it must not appear twice\n * (duplicate React keys, and the row's actions would target the same session\n * from two places).\n */\nexport function composeSidebarSessions({\n loaderSessions,\n optimisticSessions = [],\n limit,\n totalCount,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ComposeSidebarSessionsOptions): ComposedSidebarSessions {\n const loaderIds = new Set(loaderSessions.map((session) => session.id))\n const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id))\n const merged = [...pendingNew, ...loaderSessions]\n const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({\n ...session,\n unread: resolveSessionUnread({\n sessionId: session.id,\n loaderUnread: Boolean(session.unread),\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n }),\n }))\n const known = (totalCount ?? loaderSessions.length) + pendingNew.length\n return { sessions, hasMore: known > sessions.length }\n}\n\n/**\n * Append a fetched page to held rows, dropping ids already shown. A session\n * bumped to the top between two page fetches otherwise arrives twice — once in\n * the page it moved out of and once in the page it moved into.\n */\nexport function mergeSessionPages(\n existing: SessionSummary[],\n incoming: SessionSummary[],\n): SessionSummary[] {\n const seen = new Set(existing.map((session) => session.id))\n return [...existing, ...incoming.filter((session) => !seen.has(session.id))]\n}\n\n// ---------------------------------------------------------------------------\n// Rail collapse cookie (SSR-seeded so the first paint matches the client)\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_RAIL_COOKIE_NAME = 'agent-sidebar-rail-collapsed'\n\n/**\n * Read the persisted rail-collapse state from a request's `Cookie` header, so\n * the server renders the rail in the state the user left it and the first\n * client render does not re-flow.\n *\n * Parses the header rather than building a `RegExp` from the cookie name (the\n * shape the products shipped): a name containing a regex metacharacter would\n * silently match the wrong cookie or none at all.\n */\nexport function readRailCollapsedCookie(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_RAIL_COOKIE_NAME,\n): boolean {\n for (const pair of (cookieHeader ?? '').split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n return pair.slice(eq + 1).trim() === '1'\n }\n return false\n}\n\nexport interface RailCookieOptions {\n name?: string\n /** Seconds. Default one year. */\n maxAge?: number\n path?: string\n /** Omit to auto-detect: `secure` on https, off on http://localhost — a Secure\n * cookie is dropped there and the rail state would not persist in dev. */\n secure?: boolean\n}\n\n/** The cookie string for a collapse state. Usable as `document.cookie` or as a\n * `Set-Cookie` value. Exported separately so it is testable without a DOM. */\nexport function railCollapsedCookie(\n collapsed: boolean,\n { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31_536_000, path = '/', secure }: RailCookieOptions = {},\n): string {\n const isSecure =\n secure ?? (typeof location !== 'undefined' && location.protocol === 'https:')\n return `${name}=${collapsed ? '1' : '0'}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? '; secure' : ''}`\n}\n\n/** Persist the rail-collapse state from the browser. No-op without a document\n * so a shared toggle handler is safe to call during SSR. */\nexport function writeRailCollapsedCookie(collapsed: boolean, options: RailCookieOptions = {}): void {\n if (typeof document === 'undefined') return\n document.cookie = railCollapsedCookie(collapsed, options)\n}\n"],"mappings":";AAMO,SAAS,qBAAqB,OAAuB;AAC1D,SAAO,MAAM,QAAQ,QAAQ,EAAE;AACjC;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAIO,SAAS,cAAc,UAA0B;AACtD,QAAM,cAAc,SAAS,MAAM,GAAG,EAAE,CAAC,KAAK;AAC9C,QAAM,eAAe,YAAY,MAAM,GAAG,EAAE,CAAC,KAAK;AAClD,SAAO,qBAAqB,YAAY;AAC1C;AAIO,SAAS,cAAc,MAAc,QAAyB;AACnE,QAAM,IAAI,qBAAqB,MAAM;AACrC,MAAI,MAAM,GAAI,QAAO;AACrB,SAAO,SAAS,KAAK,KAAK,WAAW,GAAG,CAAC,GAAG;AAC9C;AAIO,SAAS,WAAW,OAAyB;AAClD,SAAO,MAAM,MAAM,GAAG,EAAE,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AAChE;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,IAAI,WAAW,KAAK,EAAE,KAAK,GAAG,CAAC;AACxC;;;ACuBO,SAAS,eACd,aACA,OACQ;AACR,QAAM,OAAO,MAAM,YAAY,KAAK;AACpC,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI;AAAA,MACR,oBAAoB,YAAY,EAAE,iBAAiB,YAAY,KAAK;AAAA,IACtE;AAAA,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A,MACA;AAAA,IACF,CAAC;AAAA,EACH,EAAE;AACF,QAAM,SAAS,cAAc,eAAe,UAAU,WAAW;AACjE,SAAO,EAAE,UAAU,SAAS,QAAQ,SAAS,OAAO;AACtD;AAOO,SAAS,kBACd,UACA,UACkB;AAClB,QAAM,OAAO,IAAI,IAAI,SAAS,IAAI,CAAC,YAAY,QAAQ,EAAE,CAAC;AAC1D,SAAO,CAAC,GAAG,UAAU,GAAG,SAAS,OAAO,CAAC,YAAY,CAAC,KAAK,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC7E;AAMO,IAAM,2BAA2B;AAWjC,SAAS,wBACd,cACA,OAAe,0BACN;AACT,aAAW,SAAS,gBAAgB,IAAI,MAAM,GAAG,GAAG;AAClD,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,GAAI;AACf,QAAI,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,KAAM;AACvC,WAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK,MAAM;AAAA,EACvC;AACA,SAAO;AACT;AAcO,SAAS,oBACd,WACA,EAAE,OAAO,0BAA0B,SAAS,SAAY,OAAO,KAAK,OAAO,IAAuB,CAAC,GAC3F;AACR,QAAM,WACJ,WAAW,OAAO,aAAa,eAAe,SAAS,aAAa;AACtE,SAAO,GAAG,IAAI,IAAI,YAAY,MAAM,GAAG,UAAU,IAAI,aAAa,MAAM,iBAAiB,WAAW,aAAa,EAAE;AACrH;AAIO,SAAS,yBAAyB,WAAoB,UAA6B,CAAC,GAAS;AAClG,MAAI,OAAO,aAAa,YAAa;AACrC,WAAS,SAAS,oBAAoB,WAAW,OAAO;AAC1D;","names":[]}
1
+ {"version":3,"sources":["../src/session-shell/path.ts","../src/session-shell/nav-guard.ts","../src/session-shell/command-palette.ts","../src/session-shell/index.ts"],"sourcesContent":["/**\n * Path normalisation shared by the shell's routing helpers. Segment-aligned\n * comparison is the invariant: `/vault` must never claim `/vault-archive`, so\n * every prefix test here works on whole segments rather than string prefixes.\n */\n\nexport function stripTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\n/** Bare segment name, so a caller may pass `'/settings'` or `'settings'`. */\nexport function stripSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\n/** Path with query + fragment removed and trailing slashes trimmed. A caller\n * passing a full href instead of a pathname would otherwise match nothing. */\nexport function normalizePath(pathname: string): string {\n const withoutHash = pathname.split('#')[0] ?? ''\n const withoutQuery = withoutHash.split('?')[0] ?? ''\n return stripTrailingSlashes(withoutQuery)\n}\n\n/** True when `path` is `prefix` or a segment-aligned descendant of it, so\n * `/vault` never claims `/vault-archive`. */\nexport function isUnderPrefix(path: string, prefix: string): boolean {\n const p = stripTrailingSlashes(prefix)\n if (p === '') return true\n return path === p || path.startsWith(`${p}/`)\n}\n\n/** Non-empty segments of a path or route pattern. Leading/trailing/duplicate\n * slashes collapse, so `/app//x/` and `app/x` compare equal. */\nexport function toSegments(value: string): string[] {\n return value.split('/').filter((segment) => segment.length > 0)\n}\n\n/** Canonical display form: rooted, no trailing slash, no empty segments. */\nexport function toRootedPath(value: string): string {\n return `/${toSegments(value).join('/')}`\n}\n","/**\n * Nav destinations, and the guard that proves every href the rail renders\n * resolves to a route the product's router actually registered.\n *\n * A rail row's href is assembled from a base plus a relative path, and nothing\n * downstream re-checks it: the sidebar renders a link, the click navigates, and\n * the router answers 404. A unit test written against the nav builder alone\n * cannot catch that — it asserts the href the builder produced, which is the\n * same wrong string the user clicks.\n *\n * Two mechanisms, meant to be used together:\n *\n * 1. `NavDestination` makes the base a REQUIRED discriminant (`scope`). An\n * optional `absolute?: boolean`-style flag has the opposite property:\n * omitting it type-checks, and the destination silently resolves under the\n * workspace prefix instead of the app-level one. A required literal union\n * turns that omission into a compile error, and widening `TScope` demands a\n * base for the new scope rather than defaulting to a wrong one.\n * 2. `assertNavHrefsRegistered` matches every resolved href against the route\n * table, so a destination the router never registered fails a test instead\n * of a user's click. It reads the product's real route table, so it cannot\n * agree with the builder's mistake the way a hand-maintained expected-href\n * list does.\n */\n\nimport { isUnderPrefix, normalizePath, stripTrailingSlashes, toRootedPath, toSegments } from './path'\n\n// ---------------------------------------------------------------------------\n// Destinations — the base is a required discriminant, never an optional flag\n// ---------------------------------------------------------------------------\n\n/** The bases a product routes rail rows under. `workspace` is the per-workspace\n * prefix (`/app/ws_123`); `app` is the account-level one (`/app`), where\n * singleton surfaces such as a shared terminal or billing live. */\nexport type NavScope = 'workspace' | 'app'\n\n/** A base path per scope. Widening `TScope` widens this record, so a product\n * that adds a scope cannot compile until it supplies that scope's base. */\nexport type NavScopeBases<TScope extends string = NavScope> = Readonly<Record<TScope, string>>\n\n/** One rail destination as the product declares it, before a base is applied. */\nexport interface NavDestination<TScope extends string = NavScope> {\n id: string\n /** Path relative to the base named by `scope`. `''` is the base itself.\n * Must be empty or start with `/` — a bare `'vault'` would concatenate into\n * `/app/ws_123vault`, so it is rejected rather than silently repaired. */\n path: string\n /** Which base `path` resolves against. Required on purpose. */\n scope: TScope\n}\n\n/** A destination with its base applied. */\nexport interface ResolvedNavDestination<TScope extends string = NavScope> {\n id: string\n href: string\n scope: TScope\n}\n\n/** Apply a destination's scope base to its path.\n *\n * Throws when the scope has no base configured — a product that assembles\n * `bases` dynamically can defeat the type-level guarantee, and a missing base\n * would otherwise produce `undefined/vault`. */\nexport function resolveNavHref<TScope extends string>(\n destination: NavDestination<TScope>,\n bases: NavScopeBases<TScope>,\n): string {\n const base = bases[destination.scope]\n if (typeof base !== 'string') {\n throw new Error(\n `Nav destination '${destination.id}' uses scope '${destination.scope}', which has no configured base`,\n )\n }\n if (destination.path !== '' && !destination.path.startsWith('/')) {\n throw new Error(\n `Nav destination '${destination.id}' path must be empty or start with '/' (got '${destination.path}')`,\n )\n }\n const rooted = `${stripTrailingSlashes(base)}${destination.path}`\n return rooted === '' ? '/' : stripTrailingSlashes(rooted)\n}\n\n/** Apply the bases to every destination, preserving declaration order. */\nexport function resolveNavDestinations<TScope extends string>(\n destinations: readonly NavDestination<TScope>[],\n bases: NavScopeBases<TScope>,\n): ResolvedNavDestination<TScope>[] {\n return destinations.map((destination) => ({\n id: destination.id,\n href: resolveNavHref(destination, bases),\n scope: destination.scope,\n }))\n}\n\nexport interface ResolveScopedActiveNavIdOptions<TScope extends string = NavScope> {\n pathname: string\n destinations: readonly NavDestination<TScope>[]\n bases: NavScopeBases<TScope>\n /** Extra ABSOLUTE prefixes that light an existing row, e.g.\n * `{ '/app/ws_1/agents': 'integrations' }`. Same longest-prefix contest. */\n aliases?: Readonly<Record<string, string>>\n /** ABSOLUTE prefixes that deliberately highlight nothing, beating any shorter\n * match. */\n claimsNothing?: readonly string[]\n}\n\n/**\n * The rail row to highlight, across scopes.\n *\n * `resolveActiveNavId` resolves rows against ONE base, so an app-level row can\n * only be highlighted by a second, hand-rolled scan — the same split that lets\n * an app-level destination render under the workspace base. This resolves the\n * hrefs first and runs a single longest-prefix contest over absolute paths, so\n * declaration order cannot change the answer and no scope needs its own pass.\n *\n * Prefixes in `aliases` / `claimsNothing` are absolute here, unlike\n * `resolveActiveNavId`'s base-relative ones, because the contest itself is\n * absolute.\n */\nexport function resolveScopedActiveNavId<TScope extends string>({\n pathname,\n destinations,\n bases,\n aliases,\n claimsNothing,\n}: ResolveScopedActiveNavIdOptions<TScope>): string | undefined {\n const path = normalizePath(pathname)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (candidate: string, id: string | undefined, winsTies = false): void => {\n const full = stripTrailingSlashes(candidate)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const resolved of resolveNavDestinations(destinations, bases)) consider(resolved.href, resolved.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix here is a\n // deliberate override of the row that owns it.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Route table — structurally the product's own router config\n// ---------------------------------------------------------------------------\n\n/**\n * One entry of a registered route table. Structurally compatible with\n * react-router's `RouteConfigEntry`, so a product passes its real `routes.ts`\n * default export straight in — the point of the guard is that it reads the\n * router's own truth rather than a second list that can agree with the bug.\n */\nexport interface RegisteredRoute {\n /** Absent on a pathless layout route: its children inherit the parent path. */\n path?: string\n index?: boolean\n children?: readonly RegisteredRoute[]\n}\n\n/** A route table entry is either a bare pattern string or a router config node. */\nexport type NavRouteTable = readonly (string | RegisteredRoute)[]\n\nfunction joinPattern(parent: string, child: string): string {\n if (child.startsWith('/')) return child\n if (child === '') return parent\n return `${parent}/${child}`\n}\n\n/**\n * Every path pattern the table registers, rooted and de-duplicated.\n *\n * Parent nodes contribute their own cumulative path as well as their children's:\n * a router matches a parent route with an index child at the parent path, and a\n * parent without one still matches with an empty outlet, so treating parents as\n * unregistered would flag working hrefs.\n */\nexport function flattenRouteTable(table: NavRouteTable): string[] {\n const patterns: string[] = []\n const walk = (entries: NavRouteTable, parent: string): void => {\n for (const entry of entries) {\n if (typeof entry === 'string') {\n patterns.push(toRootedPath(joinPattern(parent, entry)))\n continue\n }\n const own = entry.path === undefined ? parent : joinPattern(parent, entry.path)\n patterns.push(toRootedPath(own))\n if (entry.children) walk(entry.children, own)\n }\n }\n walk(table, '')\n return [...new Set(patterns)]\n}\n\n/**\n * Whole-path segment match of a concrete path against one route pattern.\n *\n * Supports the three pattern forms a router uses: literal segments, `:param`\n * (exactly one non-empty segment), optional `:param?` / `segment?` (zero or\n * one), and a trailing `*` splat (zero or more). Matching is recursive because\n * an optional segment forks the walk — a linear scan silently mismatches\n * `/a/b` against `a/:x?/b`.\n */\nfunction matchesPattern(pathSegments: readonly string[], patternSegments: readonly string[], caseSensitive: boolean): boolean {\n if (patternSegments.length === 0) return pathSegments.length === 0\n const head = patternSegments[0] ?? ''\n if (head === '*') return true\n const rest = patternSegments.slice(1)\n const optional = head.endsWith('?')\n const core = optional ? head.slice(0, -1) : head\n const first = pathSegments[0]\n if (first !== undefined) {\n const hit = core.startsWith(':')\n ? first.length > 0\n : caseSensitive\n ? core === first\n : core.toLowerCase() === first.toLowerCase()\n if (hit && matchesPattern(pathSegments.slice(1), rest, caseSensitive)) return true\n }\n return optional ? matchesPattern(pathSegments, rest, caseSensitive) : false\n}\n\n// ---------------------------------------------------------------------------\n// The guard\n// ---------------------------------------------------------------------------\n\n/**\n * A nav row as the guard needs to see it. Structurally satisfied by\n * `SessionRailNavItem` / `SessionRailSubItem` and by sandbox-ui's\n * `SidebarLayoutNavItem`, so the guard runs over the builder's real output\n * rather than a re-declaration of it.\n */\nexport interface NavHrefItem {\n id: string\n href: string\n subItems?: readonly NavHrefItem[]\n}\n\nexport type NavHrefProblemReason =\n /** No registered pattern matches the resolved href. */\n | 'unregistered'\n /** Empty, fragment-only, or not rooted at `/` — the row navigates nowhere\n * predictable regardless of the route table. */\n | 'not-a-path'\n /** Leaves the router (scheme or protocol-relative) while `allowExternal` is\n * off. */\n | 'external'\n\nexport interface NavHrefProblem {\n id: string\n href: string\n reason: NavHrefProblemReason\n /** Registered patterns ending in the same segment. A destination resolved\n * under the wrong base lands here as its correctly-based twin, which is what\n * names the missing scope in the failure message. */\n nearest: string[]\n message: string\n}\n\nexport interface NavHrefReport {\n /** Hrefs examined, including nested sub-items. */\n checked: number\n problems: NavHrefProblem[]\n /** Off-router destinations accepted because `allowExternal` is on. */\n external: string[]\n /** The flattened route table the check ran against. */\n patterns: string[]\n}\n\nexport interface NavHrefCheckOptions {\n /** Hrefs to skip, compared after query/fragment removal. For a destination\n * served outside this route table (a static asset, another worker). */\n ignore?: readonly string[]\n /** Absolute URLs / `mailto:` / `tel:` are reported under `external` instead\n * of failing. Default true. */\n allowExternal?: boolean\n /** Compare literal segments case-sensitively. Default true — a router that\n * matches case-insensitively still renders a link the deploy's CDN or a\n * case-sensitive origin may not. */\n caseSensitive?: boolean\n}\n\n/** `scheme:` or `//host` — anything the router will not resolve as a path. */\nconst OFF_ROUTER_HREF = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i\n\nfunction flattenItems(items: readonly NavHrefItem[], out: NavHrefItem[] = []): NavHrefItem[] {\n for (const item of items) {\n out.push(item)\n if (item.subItems) flattenItems(item.subItems, out)\n }\n return out\n}\n\n/**\n * Check every nav href against the product's route table.\n *\n * Pure — returns the full report so a caller can assert on parts of it. Use\n * {@link assertNavHrefsRegistered} in tests; it turns the report into a failure\n * that names the offending row, its resolved href, and the near-miss pattern.\n */\nexport function checkNavHrefs(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): NavHrefReport {\n const { ignore, allowExternal = true, caseSensitive = true } = options\n const patterns = flattenRouteTable(routes)\n const patternSegments = patterns.map((pattern) => ({ pattern, segments: toSegments(pattern) }))\n const ignored = new Set((ignore ?? []).map((href) => normalizePath(href)))\n const problems: NavHrefProblem[] = []\n const external: string[] = []\n const flat = flattenItems(items)\n let checked = 0\n\n for (const item of flat) {\n const raw = item.href\n const path = normalizePath(raw)\n if (ignored.has(path)) continue\n if (OFF_ROUTER_HREF.test(raw)) {\n if (allowExternal) {\n external.push(raw)\n continue\n }\n // Counted as checked: it was examined and rejected, so the vacuous-pass\n // guard must not read this run as \"nothing was looked at\".\n checked += 1\n problems.push({\n id: item.id,\n href: raw,\n reason: 'external',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' leaves the router, and external destinations are rejected`,\n })\n continue\n }\n checked += 1\n if (raw === '' || raw.startsWith('#') || !raw.startsWith('/')) {\n problems.push({\n id: item.id,\n href: raw,\n reason: 'not-a-path',\n nearest: [],\n message: `Nav item '${item.id}' href '${raw}' is not a rooted path — it cannot resolve to a registered route`,\n })\n continue\n }\n const segments = toSegments(path)\n if (patternSegments.some((candidate) => matchesPattern(segments, candidate.segments, caseSensitive))) continue\n const nearest = nearestPatterns(segments, patternSegments.map((candidate) => candidate.pattern), caseSensitive)\n problems.push({\n id: item.id,\n href: raw,\n reason: 'unregistered',\n nearest,\n message:\n `Nav item '${item.id}' href '${raw}' matches no registered route` +\n (nearest.length ? ` — nearest registered: ${nearest.join(', ')}` : ''),\n })\n }\n\n return { checked, problems, external, patterns }\n}\n\n/** Registered patterns whose last segment equals the href's last segment: the\n * same destination under a different base is the near-miss worth printing. */\nfunction nearestPatterns(segments: readonly string[], patterns: readonly string[], caseSensitive: boolean): string[] {\n const tail = segments[segments.length - 1]\n if (tail === undefined) return []\n const same = (a: string, b: string): boolean => (caseSensitive ? a === b : a.toLowerCase() === b.toLowerCase())\n return patterns\n .filter((pattern) => {\n const patternTail = toSegments(pattern).at(-1)\n return patternTail !== undefined && same(patternTail, tail)\n })\n .slice(0, 5)\n}\n\n/**\n * Fail unless every nav href resolves to a registered route.\n *\n * Throws on an empty item list or an empty route table as well: a guard that\n * examined nothing reports safety it does not provide, and both are what a\n * mis-wired import looks like.\n */\nexport function assertNavHrefsRegistered(\n items: readonly NavHrefItem[],\n routes: NavRouteTable,\n options: NavHrefCheckOptions = {},\n): void {\n if (items.length === 0) {\n throw new Error('assertNavHrefsRegistered received no nav items — the check would pass without examining anything')\n }\n const report = checkNavHrefs(items, routes, options)\n if (report.patterns.length === 0) {\n throw new Error('assertNavHrefsRegistered received an empty route table — every href would fail or nothing would be proven')\n }\n // Real problems are reported before the vacuous-pass guard: rejected external\n // hrefs are problems that were never \"checked\", and the guard's message would\n // otherwise hide them.\n if (report.problems.length > 0) {\n const detail = report.problems.map((problem) => ` - ${problem.message}`).join('\\n')\n throw new Error(\n `${report.problems.length} of ${report.checked} nav hrefs do not resolve to a registered route:\\n${detail}\\n` +\n `Registered patterns (${report.patterns.length}): ${report.patterns.join(', ')}`,\n )\n }\n if (report.checked === 0) {\n throw new Error(\n `assertNavHrefsRegistered examined 0 hrefs (${report.external.length} external, ${ignoredCount(items, options)} ignored) — the check would pass without examining anything`,\n )\n }\n}\n\nfunction ignoredCount(items: readonly NavHrefItem[], options: NavHrefCheckOptions): number {\n const ignored = new Set((options.ignore ?? []).map((href) => normalizePath(href)))\n return flattenItems(items).filter((item) => ignored.has(normalizePath(item.href))).length\n}\n","/**\n * Command palette — the React-free selection half of the Cmd/Ctrl+K surface\n * (`/web-react` holds the rendered half, `CommandPalette`).\n *\n * Pure and import-free beyond this module's own types: no React, no DOM, no\n * fuse.js. A route loader or a worker can build and rank the same items the\n * browser renders.\n *\n * Domain stays a parameter. The palette knows two kinds of row — a SESSION the\n * user can jump to and an ACTION the product offers (new chat, toggle theme,\n * open settings) — and both arrive as data. What a selection DOES is the\n * product's business; the shell only builds, ranks, and groups.\n *\n * Ranking is the documented ladder, not a fuzzy library: exact > prefix >\n * word-prefix > substring (earlier index wins) > token-order, with keyword\n * hits ranked a fixed step below the same hit on the label. Deterministic —\n * no index-building, no async, same input always sorts the same way.\n */\n\nimport { sessionLabel, UNTITLED_SESSION_LABEL, type SessionSummary } from './index'\n\n/** A product-supplied palette action. `hint` is the right-aligned affordance\n * copy (a kbd chord, a route name) — rendered verbatim, never interpreted. */\nexport interface CommandPaletteAction {\n id: string\n label: string\n description?: string\n hint?: string\n /** Extra match vocabulary that never renders (`settings` matching\n * \"preferences\"). A keyword hit ranks below the same hit on the label. */\n keywords?: string[]\n}\n\n/** One selectable row. `group` is the section header it renders under. */\nexport interface CommandPaletteItem {\n id: string\n group: string\n label: string\n description?: string\n hint?: string\n keywords?: string[]\n /** Recency key (ISO-8601). Breaks score ties and orders the unfiltered\n * list recent-first. Rows without one sort below rows with one. */\n recentAt?: string | null\n}\n\n/** One rendered section: a header plus its rows, in first-seen group order. */\nexport interface CommandPaletteGroup {\n group: string\n items: CommandPaletteItem[]\n}\n\nexport const COMMAND_PALETTE_SESSIONS_GROUP = 'Sessions'\nexport const COMMAND_PALETTE_ACTIONS_GROUP = 'Actions'\n\nexport interface BuildCommandPaletteItemsOptions {\n sessions?: readonly SessionSummary[]\n actions?: readonly CommandPaletteAction[]\n /** Section label for sessions. Default \"Sessions\". */\n sessionsLabel?: string\n /** Section label for actions. Default \"Actions\". */\n actionsLabel?: string\n /** Placeholder title for an untitled session. */\n untitledLabel?: string\n}\n\n/**\n * Flatten sessions + actions into palette items, sessions group first (the\n * jump-back-in list), actions after. Sessions order recent-first by\n * `updatedAt` — a palette with an empty query IS the recency list, so the\n * build order is the render order and the filter never has to re-derive it.\n * Pinned sessions lead the recency sort, matching the rail.\n */\nexport function buildCommandPaletteItems({\n sessions = [],\n actions = [],\n sessionsLabel = COMMAND_PALETTE_SESSIONS_GROUP,\n actionsLabel = COMMAND_PALETTE_ACTIONS_GROUP,\n untitledLabel = UNTITLED_SESSION_LABEL,\n}: BuildCommandPaletteItemsOptions): CommandPaletteItem[] {\n const ordered = [...sessions].sort((a, b) => {\n if (!!a.isPinned !== !!b.isPinned) return a.isPinned ? -1 : 1\n return compareRecent(a.updatedAt, b.updatedAt)\n })\n const sessionItems: CommandPaletteItem[] = ordered.map((session) => ({\n id: session.id,\n group: sessionsLabel,\n label: sessionLabel(session, untitledLabel),\n keywords: session.category ? [session.category] : undefined,\n recentAt: session.updatedAt,\n }))\n const actionItems: CommandPaletteItem[] = actions.map((action) => ({\n id: action.id,\n group: actionsLabel,\n label: action.label,\n description: action.description,\n hint: action.hint,\n keywords: action.keywords,\n }))\n return [...sessionItems, ...actionItems]\n}\n\n/** Newer first; an undated row sorts below every dated one. ISO strings\n * compare lexicographically. */\nfunction compareRecent(a: string | null | undefined, b: string | null | undefined): number {\n if (a && b) return a < b ? 1 : a > b ? -1 : 0\n if (a) return -1\n if (b) return 1\n return 0\n}\n\n/** Collapse whitespace, lowercase once — every comparison runs on this form. */\nfunction normalize(text: string): string {\n return text.trim().toLowerCase().replace(/\\s+/g, ' ')\n}\n\n/** Words of a normalized string: runs of letters/numbers, so \"new-chat\" and\n * \"new chat\" word-prefix identically. */\nconst WORD_SPLIT = /[^\\p{L}\\p{N}]+/u\n\nfunction wordsOf(text: string): string[] {\n return text.split(WORD_SPLIT).filter(Boolean)\n}\n\n/** How far below a label hit the same keyword hit ranks: any label match, even\n * a token-order one (40), outranks a keyword exact match (100 − 65 = 35). */\nconst KEYWORD_PENALTY = 65\n\n/**\n * Score one text against the query on the prefix > substring > token-order\n * ladder. Returns `null` for no match. Higher is better; tiers are spaced so\n * no within-tier adjustment can cross a tier boundary:\n *\n * - 100 exact\n * - 90 prefix (`text` starts with the query)\n * - 80 word-prefix (a WORD starts with the query — \"chat\" hits \"New chat\")\n * - 60–79 substring, minus the match index clamped to 19 (earlier wins)\n * - 40 token-order (every query token matches a later word, in order)\n */\nfunction scoreText(text: string, query: string): number | null {\n if (!query) return 0\n if (text === query) return 100\n if (text.startsWith(query)) return 90\n const words = wordsOf(text)\n if (words.some((word) => word.startsWith(query))) return 80\n const at = text.indexOf(query)\n if (at >= 0) return 60 + Math.max(0, 19 - at)\n const tokens = wordsOf(query)\n if (tokens.length > 1) {\n let atWord = 0\n const inOrder = tokens.every((token) => {\n while (atWord < words.length) {\n const word = words[atWord]\n atWord += 1\n // Guarded by the while condition; noUncheckedIndexedAccess can't see it.\n if (word !== undefined && (word.startsWith(token) || word.includes(token))) return true\n }\n return false\n })\n if (inOrder) return 40\n }\n return null\n}\n\n/**\n * Score an item: the best label score, or the best keyword score a fixed step\n * below. `null` when neither matches — the item is filtered out. An empty\n * query scores every item 0 (the caller keeps build order: recent-first).\n */\nexport function scoreCommandPaletteItem(item: CommandPaletteItem, query: string): number | null {\n const q = normalize(query)\n const label = scoreText(normalize(item.label), q)\n let best = label\n for (const keyword of item.keywords ?? []) {\n const score = scoreText(normalize(keyword), q)\n if (score !== null) {\n const penalized = score - KEYWORD_PENALTY\n if (best === null || penalized > best) best = penalized\n }\n }\n return best\n}\n\n/**\n * Filter + rank: an empty query returns the items untouched (build order is\n * the recency order); a real query drops non-matches and sorts by score, then\n * recency, then original position — stable and deterministic.\n */\nexport function filterCommandPaletteItems(\n items: readonly CommandPaletteItem[],\n query: string,\n): CommandPaletteItem[] {\n if (!normalize(query)) return [...items]\n const scored: Array<{ item: CommandPaletteItem; score: number; index: number }> = []\n items.forEach((item, index) => {\n const score = scoreCommandPaletteItem(item, query)\n if (score !== null) scored.push({ item, score, index })\n })\n scored.sort((a, b) => {\n if (a.score !== b.score) return b.score - a.score\n const recent = compareRecent(a.item.recentAt, b.item.recentAt)\n if (recent !== 0) return recent\n return a.index - b.index\n })\n return scored.map(({ item }) => item)\n}\n\n/**\n * Fold a flat (already ordered) item list into renderable sections. Groups\n * appear in first-seen order and each group appears ONCE — a filtered ranking\n * interleaves sessions and actions by score, and folding only consecutive runs\n * would render the same header twice. Within a group, rows keep the flat\n * order. Empty groups vanish, so a filter that leaves only actions renders no\n * \"Sessions\" header over nothing.\n */\nexport function groupCommandPaletteItems(items: readonly CommandPaletteItem[]): CommandPaletteGroup[] {\n const groups: CommandPaletteGroup[] = []\n const byGroup = new Map<string, CommandPaletteGroup>()\n for (const item of items) {\n let group = byGroup.get(item.group)\n if (!group) {\n group = { group: item.group, items: [] }\n byGroup.set(item.group, group)\n groups.push(group)\n }\n group.items.push(item)\n }\n return groups\n}\n","/**\n * Session shell — the app-shell mechanism every agent product needs around the\n * chat surface: a list of past sessions in the rail, an entry point for a new\n * one, and a paged history view behind it.\n *\n * `/web-react` already owns the chat SURFACE (composer, transcript, cards); it\n * owned no session SHELL, so all four products hand-rolled one and drifted.\n * This module is the shell's pure half: no React, no DOM, no peer imports, so a\n * server loader can call `readRailCollapsedCookie` without dragging React into\n * a worker bundle (`/web-react` holds the rendered half).\n *\n * Domain stays a parameter. A \"session\" here is only an id, a title and a\n * timestamp — a gtm thread, a tax session and a legal matter are all the same\n * shape to the shell, and the product supplies routing through `hrefForSession`\n * rather than the shell knowing any URL.\n */\n\nimport { isUnderPrefix, normalizePath, stripSlashes, stripTrailingSlashes } from './path'\n\nexport * from './nav-guard'\nexport * from './command-palette'\n\n/** One session as the shell needs to see it. Products map their own row\n * (thread / session / matter) onto this before handing it over. */\nexport interface SessionSummary {\n id: string\n /** `null`/empty renders as the untitled placeholder rather than a blank row. */\n title: string | null\n /** ISO-8601. `null` when the product has no timestamp to show. */\n updatedAt: string | null\n isPinned?: boolean\n /** Unread for the viewer. Use `resolveSessionUnread` to fold live overlays in. */\n unread?: boolean\n /** Free-form product label (gtm categories, legal matter types). Passed\n * through untouched — the shell never interprets it. */\n category?: string | null\n}\n\n/** One fetched page of sessions with an optional continuation cursor. */\nexport interface SessionPage {\n items: SessionSummary[]\n /** Opaque continuation token; absent/null ⇒ no further pages. */\n nextCursor?: string | null\n}\n\n/** Sort order for the history view. The product's fetcher decides what these\n * mean against its own storage; the shell only round-trips the value. */\nexport type SessionSort = 'newest' | 'oldest'\n\n// ---------------------------------------------------------------------------\n// Rail items — structurally assignable to sandbox-ui's SidebarLayout types\n// ---------------------------------------------------------------------------\n\n/**\n * These mirror `@tangle-network/sandbox-ui/dashboard`'s `SidebarLayoutNavItem`\n * / `RailExpandableSubItem` STRUCTURALLY rather than importing them, so this\n * module stays free of the optional peer (invariant 3 — structural over\n * hard-dep when the surface is small). `tests/session-shell/rail-contract.test.ts`\n * assigns the builder output to the real sandbox-ui types, so a drift in either\n * direction fails CI instead of silently dropping a field at runtime.\n *\n * `TIcon` is the product's icon component type (lucide, custom, anything) —\n * generic so this file needs no React types.\n */\nexport interface SessionRailAction<TIcon = unknown> {\n id: string\n label: string\n icon?: TIcon\n destructive?: boolean\n onSelect: () => void\n}\n\nexport type RailPrefetch = 'none' | 'intent' | 'render' | 'viewport'\n\nexport interface SessionRailSubItem<TIcon = unknown> {\n id: string\n label: string\n href: string\n prefetch?: RailPrefetch\n /** Live working indicator — the session is mid-turn. */\n isLoading?: boolean\n /** Bold + leading dot. sandbox-ui suppresses it while `isLoading`. */\n unread?: boolean\n /** Emphasised row, used for the trailing \"view all\" overflow link. */\n emphasis?: boolean\n actions?: SessionRailAction<TIcon>[]\n}\n\nexport interface SessionRailNavItem<TIcon = unknown> {\n id: string\n /** REQUIRED, mirroring sandbox-ui — the rail renders `<Icon />` unguarded, so\n * an omitted icon is a blank/crashing row rather than a styling nit. */\n icon: TIcon\n label: string\n href: string\n badge?: number\n expandable?: boolean\n defaultOpen?: boolean\n subItems?: SessionRailSubItem<TIcon>[]\n subActiveIds?: string[]\n emptyLabel?: string\n prefetch?: RailPrefetch\n}\n\n/** Per-row rename/delete wiring. Supplied by the layout that owns the dialogs;\n * omitted (or `canEdit: false`) leaves rows read-only. */\nexport interface SessionRowActions<TIcon = unknown> {\n canEdit: boolean\n renameIcon?: TIcon\n deleteIcon?: TIcon\n renameLabel?: string\n deleteLabel?: string\n /**\n * Omit when the product cannot rename a session — the row then offers delete\n * only, instead of a menu item that does nothing.\n *\n * Independently optional, matching `SessionHistoryPanel`, which has always\n * rendered whichever of the two it was given. The rail builder used to demand\n * both, so a product with archive-but-no-rename (tax) could either fake a\n * rename or ship no row actions at all.\n */\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /**\n * Row actions this shell has no opinion about — pin, categorise, duplicate,\n * share. Evaluated per session so a label can read that row's state\n * (\"Pin\" vs \"Unpin\"), and ordered between rename and delete so the\n * destructive action stays last.\n *\n * `id` must not be `rename` or `delete`; those are the shell's own.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction<TIcon>[]\n}\n\nexport const UNTITLED_SESSION_LABEL = 'Untitled chat'\n\n/** Display title for a session row — trims, and falls back rather than\n * rendering an empty row the user cannot aim at. */\nexport function sessionLabel(session: SessionSummary, untitled = UNTITLED_SESSION_LABEL): string {\n return session.title?.trim() || untitled\n}\n\nexport interface BuildSessionSubItemsOptions<TIcon = unknown> {\n sessions: SessionSummary[]\n /** The product's route for one session. The shell never builds a URL itself. */\n hrefForSession: (sessionId: string) => string\n /** Ids currently mid-turn — renders the working indicator. */\n respondingSessionIds?: ReadonlySet<string>\n actions?: SessionRowActions<TIcon>\n untitledLabel?: string\n prefetch?: RailPrefetch\n /** Trailing \"view all\" row, appended when the capped list hides sessions. */\n overflow?: { href: string; label?: string }\n}\n\n/** Session rows for the rail's expandable history item. */\nexport function buildSessionSubItems<TIcon = unknown>({\n sessions,\n hrefForSession,\n respondingSessionIds,\n actions,\n untitledLabel = UNTITLED_SESSION_LABEL,\n prefetch = 'intent',\n overflow,\n}: BuildSessionSubItemsOptions<TIcon>): SessionRailSubItem<TIcon>[] {\n /**\n * Only the handlers the product actually supplied. An empty result becomes\n * `undefined` rather than `[]`, because sandbox-ui renders the kebab trigger\n * whenever `actions` is an array — an empty one is a button that opens an\n * empty menu.\n */\n const rowActions = (session: SessionSummary): SessionRailAction<TIcon>[] | undefined => {\n if (!actions?.canEdit) return undefined\n const built: SessionRailAction<TIcon>[] = []\n const { onRename, onDelete, extraActions } = actions\n if (onRename) {\n built.push({\n id: 'rename',\n label: actions.renameLabel ?? 'Rename',\n icon: actions.renameIcon,\n onSelect: () => onRename(session),\n })\n }\n if (extraActions) built.push(...extraActions(session))\n if (onDelete) {\n built.push({\n id: 'delete',\n label: actions.deleteLabel ?? 'Delete',\n icon: actions.deleteIcon,\n destructive: true,\n onSelect: () => onDelete(session),\n })\n }\n return built.length ? built : undefined\n }\n\n const rows: SessionRailSubItem<TIcon>[] = sessions.map((session) => ({\n id: session.id,\n label: sessionLabel(session, untitledLabel),\n href: hrefForSession(session.id),\n prefetch,\n isLoading: respondingSessionIds?.has(session.id) ?? false,\n unread: Boolean(session.unread),\n actions: rowActions(session),\n }))\n if (!overflow) return rows\n return [\n ...rows,\n {\n id: 'view-all',\n label: overflow.label ?? 'View all chats',\n href: overflow.href,\n prefetch,\n emphasis: true,\n },\n ]\n}\n\nexport interface BuildSessionNavItemOptions<TIcon = unknown>\n extends BuildSessionSubItemsOptions<TIcon> {\n /** Nav id the product highlights against (`activeNavId === id`). */\n id?: string\n label?: string\n /** The product's icon component. Required — see `SessionRailNavItem.icon`. */\n icon: TIcon\n /** The expandable row's own destination — the full history page. */\n href: string\n /** Session currently open, highlighted inside the expandable. */\n activeSessionId?: string | null\n emptyLabel?: string\n defaultOpen?: boolean\n}\n\n/**\n * The rail's session entry: one expandable nav row whose sub-items are the\n * recent sessions. This is the structure the owner asked for — history lives IN\n * the rail, not in a second sidebar panel beside it.\n */\nexport function buildSessionNavItem<TIcon = unknown>({\n id = 'history',\n label = 'History',\n icon,\n href,\n activeSessionId,\n emptyLabel = 'No chats yet',\n defaultOpen = true,\n ...subItemOptions\n}: BuildSessionNavItemOptions<TIcon>): SessionRailNavItem<TIcon> {\n return {\n id,\n icon,\n label,\n href,\n expandable: true,\n defaultOpen,\n subItems: buildSessionSubItems<TIcon>(subItemOptions),\n subActiveIds: activeSessionId ? [activeSessionId] : undefined,\n emptyLabel,\n prefetch: subItemOptions.prefetch ?? 'intent',\n }\n}\n\n// ---------------------------------------------------------------------------\n// Routing / selection\n// ---------------------------------------------------------------------------\n\nexport interface ActiveSessionIdOptions {\n pathname: string\n /** Workspace-scoped route base, e.g. `/app/ws_123`. */\n base: string\n /** Route segment sessions live under. Default `chat` ⇒ `${base}/chat/:id`.\n * Pass `''` when sessions sit DIRECTLY under the base (`/app/:sessionId`),\n * which is how one product routes them — then `reserved` is mandatory. */\n segment?: string\n /** Segment that means \"composing a new session\", not an id. Default `new`. */\n newSegment?: string\n /**\n * First segments that are OTHER routes, not session ids. Only meaningful\n * with `segment: ''`, where `/app/settings` is otherwise indistinguishable\n * from a session called `settings` — and resolving it as one would highlight\n * and prefetch a session that does not exist. Pass the product's own nav\n * paths; unknown-but-reserved is a routing bug, so this fails closed.\n */\n reserved?: readonly string[]\n}\n\n/**\n * The session id the current route has open, or `null` on the new-session\n * composer / anywhere else.\n *\n * Anchored at `base` on purpose. A bare `/\\/chat\\/([^/]+)/` scan — the shape\n * three products shipped — matches the FIRST `/chat/` anywhere in the path, so\n * a workspace or vault folder named `chat` resolves a neighbouring segment as a\n * session id and the rail highlights (and prefetches) a session the user is not\n * in. Same class as attaching to a stale box: it looks right and points at the\n * wrong row.\n */\nexport function activeSessionIdFromPath({\n pathname,\n base,\n segment = 'chat',\n newSegment = 'new',\n reserved,\n}: ActiveSessionIdOptions): string | null {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n const prefix = segment ? `${root}/${segment}` : root\n if (!isUnderPrefix(path, prefix) || path === prefix) return null\n const id = path.slice(prefix.length + 1).split('/')[0] ?? ''\n if (!id || id === newSegment) return null\n // `/app/settings` under a segment-less route is a sibling page, not a\n // session named \"settings\".\n if (reserved?.some((name) => stripSlashes(name) === id)) return null\n try {\n return decodeURIComponent(id)\n } catch {\n // A malformed route is not a session id. Fail closed so a bad URL cannot\n // take down the shell while it resolves the active row.\n return null\n }\n}\n\n/** One rail destination. `path` is relative to the workspace base. */\nexport interface NavRouteDef {\n id: string\n path: string\n}\n\nexport interface ResolveActiveNavIdOptions {\n pathname: string\n base: string\n /** The product's rail rows, in any order — resolution is longest-prefix. */\n routes: NavRouteDef[]\n /** Extra prefixes that light an existing row: `{ '/agents': 'integrations' }`.\n * Participates in the same longest-prefix contest. */\n aliases?: Record<string, string>\n /** Prefixes that deliberately highlight NOTHING, beating any shorter match.\n * gtm uses this so an open chat lights no rail row while `/chat/new` still\n * lights \"New\". */\n claimsNothing?: string[]\n}\n\n/**\n * The rail row to highlight for the current route.\n *\n * Longest-prefix wins, so declaration order cannot change the answer. The\n * per-product versions this replaces were first-match over an array, which made\n * `/chat/new` vs `/chat` an ordering accident rather than a rule.\n */\nexport function resolveActiveNavId({\n pathname,\n base,\n routes,\n aliases,\n claimsNothing,\n}: ResolveActiveNavIdOptions): string | undefined {\n const path = normalizePath(pathname)\n const root = stripTrailingSlashes(base)\n let bestLength = -1\n let bestId: string | undefined\n const consider = (relative: string, id: string | undefined, winsTies = false) => {\n const full = stripTrailingSlashes(`${root}${relative}`)\n if (!isUnderPrefix(path, full)) return\n if (full.length > bestLength || (winsTies && full.length === bestLength)) {\n bestLength = full.length\n bestId = id\n }\n }\n for (const route of routes) consider(route.path, route.id)\n for (const [prefix, id] of Object.entries(aliases ?? {})) consider(prefix, id)\n // Declared last and wins an exact-length tie: naming a prefix in\n // `claimsNothing` is a deliberate override of the row that owns it, so\n // `claimsNothing: ['/chat']` beats a `{ id: 'chat', path: '/chat' }` row while\n // a longer `/chat/new` still wins on specificity.\n for (const prefix of claimsNothing ?? []) consider(prefix, undefined, true)\n return bestId\n}\n\n// ---------------------------------------------------------------------------\n// Sidebar list composition\n// ---------------------------------------------------------------------------\n\nexport interface ResolveSessionUnreadOptions {\n sessionId: string\n /** Server-computed unread from the route loader. */\n loaderUnread: boolean\n /** Live \"went unread\" ids from the workspace channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has already opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** The open session is never unread to its own viewer. */\n currentSessionId?: string | null\n}\n\n/**\n * Effective unread for one row. The loader's value can be stale — a layout\n * loader that survives same-workspace navigation keeps reporting a session as\n * unread after the user opened it — so live and local overlays win over it, and\n * the currently-open session always reads as read.\n */\nexport function resolveSessionUnread({\n sessionId,\n loaderUnread,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ResolveSessionUnreadOptions): boolean {\n if (sessionId === currentSessionId) return false\n if (liveUnreadIds?.has(sessionId)) return true\n if (locallyReadIds?.has(sessionId)) return false\n return loaderUnread\n}\n\nexport interface ComposeSidebarSessionsOptions {\n /** Server-rendered rows, already ordered by the product's query. */\n loaderSessions: SessionSummary[]\n /** Optimistic rows from the live channel (a chat created in another tab). */\n optimisticSessions?: SessionSummary[]\n /** Rail cap. The full list lives on the history page. */\n limit: number\n /** Total sessions the product holds, used to decide the overflow row. */\n totalCount?: number\n liveUnreadIds?: ReadonlySet<string>\n locallyReadIds?: ReadonlySet<string>\n currentSessionId?: string | null\n}\n\nexport interface ComposedSidebarSessions {\n sessions: SessionSummary[]\n /** More sessions exist than the rail shows ⇒ render the \"view all\" row. */\n hasMore: boolean\n}\n\n/**\n * The rail's session list: optimistic rows first, then the loader's, capped,\n * with unread resolved per row.\n *\n * Optimistic rows are deduped against the loader by id — once a revalidation\n * brings a live-created session back from the server it must not appear twice\n * (duplicate React keys, and the row's actions would target the same session\n * from two places).\n */\nexport function composeSidebarSessions({\n loaderSessions,\n optimisticSessions = [],\n limit,\n totalCount,\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n}: ComposeSidebarSessionsOptions): ComposedSidebarSessions {\n const loaderIds = new Set(loaderSessions.map((session) => session.id))\n const pendingNew = optimisticSessions.filter((session) => !loaderIds.has(session.id))\n const merged = [...pendingNew, ...loaderSessions]\n const sessions = merged.slice(0, Math.max(0, limit)).map((session) => ({\n ...session,\n unread: resolveSessionUnread({\n sessionId: session.id,\n loaderUnread: Boolean(session.unread),\n liveUnreadIds,\n locallyReadIds,\n currentSessionId,\n }),\n }))\n const known = (totalCount ?? loaderSessions.length) + pendingNew.length\n return { sessions, hasMore: known > sessions.length }\n}\n\n/**\n * Append a fetched page to held rows, dropping ids already shown. A session\n * bumped to the top between two page fetches otherwise arrives twice — once in\n * the page it moved out of and once in the page it moved into.\n */\nexport function mergeSessionPages(\n existing: SessionSummary[],\n incoming: SessionSummary[],\n): SessionSummary[] {\n const seen = new Set(existing.map((session) => session.id))\n return [...existing, ...incoming.filter((session) => !seen.has(session.id))]\n}\n\n// ---------------------------------------------------------------------------\n// Rail collapse cookie (SSR-seeded so the first paint matches the client)\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_RAIL_COOKIE_NAME = 'agent-sidebar-rail-collapsed'\n\n/**\n * Read the persisted rail-collapse state from a request's `Cookie` header, so\n * the server renders the rail in the state the user left it and the first\n * client render does not re-flow.\n *\n * Parses the header rather than building a `RegExp` from the cookie name (the\n * shape the products shipped): a name containing a regex metacharacter would\n * silently match the wrong cookie or none at all.\n */\nexport function readRailCollapsedCookie(\n cookieHeader: string | null | undefined,\n name: string = DEFAULT_RAIL_COOKIE_NAME,\n): boolean {\n for (const pair of (cookieHeader ?? '').split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n if (pair.slice(0, eq).trim() !== name) continue\n return pair.slice(eq + 1).trim() === '1'\n }\n return false\n}\n\nexport interface RailCookieOptions {\n name?: string\n /** Seconds. Default one year. */\n maxAge?: number\n path?: string\n /** Omit to auto-detect: `secure` on https, off on http://localhost — a Secure\n * cookie is dropped there and the rail state would not persist in dev. */\n secure?: boolean\n}\n\n/** The cookie string for a collapse state. Usable as `document.cookie` or as a\n * `Set-Cookie` value. Exported separately so it is testable without a DOM. */\nexport function railCollapsedCookie(\n collapsed: boolean,\n { name = DEFAULT_RAIL_COOKIE_NAME, maxAge = 31_536_000, path = '/', secure }: RailCookieOptions = {},\n): string {\n const isSecure =\n secure ?? (typeof location !== 'undefined' && location.protocol === 'https:')\n return `${name}=${collapsed ? '1' : '0'}; path=${path}; max-age=${maxAge}; samesite=lax${isSecure ? '; secure' : ''}`\n}\n\n/** Persist the rail-collapse state from the browser. No-op without a document\n * so a shared toggle handler is safe to call during SSR. */\nexport function writeRailCollapsedCookie(collapsed: boolean, options: RailCookieOptions = {}): void {\n if (typeof document === 'undefined') return\n document.cookie = railCollapsedCookie(collapsed, options)\n}\n"],"mappings":";AAMO,SAAS,qBAAqB,OAAuB;AAC1D,SAAO,MAAM,QAAQ,QAAQ,EAAE;AACjC;AAGO,SAAS,aAAa,OAAuB;AAClD,SAAO,MAAM,QAAQ,cAAc,EAAE;AACvC;AAIO,SAAS,cAAc,UAA0B;AACtD,QAAM,cAAc,SAAS,MAAM,GAAG,EAAE,CAAC,KAAK;AAC9C,QAAM,eAAe,YAAY,MAAM,GAAG,EAAE,CAAC,KAAK;AAClD,SAAO,qBAAqB,YAAY;AAC1C;AAIO,SAAS,cAAc,MAAc,QAAyB;AACnE,QAAM,IAAI,qBAAqB,MAAM;AACrC,MAAI,MAAM,GAAI,QAAO;AACrB,SAAO,SAAS,KAAK,KAAK,WAAW,GAAG,CAAC,GAAG;AAC9C;AAIO,SAAS,WAAW,OAAyB;AAClD,SAAO,MAAM,MAAM,GAAG,EAAE,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AAChE;AAGO,SAAS,aAAa,OAAuB;AAClD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UAA6B,CAAC,GAAS;AAClG,MAAI,OAAO,aAAa,YAAa;AACrC,WAAS,SAAS,oBAAoB,WAAW,OAAO;AAC1D;","names":[]}
@@ -30,7 +30,7 @@ import {
30
30
  import {
31
31
  filterCommandPaletteItems,
32
32
  groupCommandPaletteItems
33
- } from "./chunk-EDTWGSQT.js";
33
+ } from "./chunk-SJWIZT7B.js";
34
34
  import {
35
35
  attachmentPartsFromMessageParts
36
36
  } from "./chunk-5ZTFZBS6.js";
@@ -5959,4 +5959,4 @@ export {
5959
5959
  useThinkingSeconds,
5960
5960
  ChatMessages
5961
5961
  };
5962
- //# sourceMappingURL=chunk-CYSN24KI.js.map
5962
+ //# sourceMappingURL=chunk-U2UAQTFY.js.map
@@ -7,7 +7,7 @@ import {
7
7
  UNTITLED_SESSION_LABEL,
8
8
  mergeSessionPages,
9
9
  sessionLabel
10
- } from "./chunk-EDTWGSQT.js";
10
+ } from "./chunk-SJWIZT7B.js";
11
11
 
12
12
  // src/web-react/session-history.tsx
13
13
  import {
@@ -51,7 +51,17 @@ function useInfiniteScroll(onLoadMore, { enabled, root, rootMargin = "300px" })
51
51
  return sentinelRef;
52
52
  }
53
53
  function seedSignature(page) {
54
- return `${page.nextCursor ?? ""}|${page.items.map((item) => item.id).join(",")}`;
54
+ return JSON.stringify({
55
+ nextCursor: page.nextCursor ?? null,
56
+ items: page.items.map((item) => ({
57
+ id: item.id,
58
+ title: item.title,
59
+ updatedAt: item.updatedAt,
60
+ isPinned: Boolean(item.isPinned),
61
+ unread: Boolean(item.unread),
62
+ category: item.category ?? null
63
+ }))
64
+ });
55
65
  }
56
66
  function useSessionHistory({
57
67
  fetchPage,
@@ -802,4 +812,4 @@ export {
802
812
  formatSessionTimestamp,
803
813
  SessionHistoryPanel
804
814
  };
805
- //# sourceMappingURL=chunk-4XWVCO7P.js.map
815
+ //# sourceMappingURL=chunk-Z4TPWP6A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-react/session-history.tsx"],"sourcesContent":["/**\n * The rendered half of the session shell: the history view behind the rail's\n * session list, and the rename/delete dialogs both surfaces drive.\n *\n * Storage is a seam, not a dependency. Every product keeps sessions somewhere\n * different (gtm threads, tax sessions, legal matters), so this takes a\n * `fetchPage` data port and injected mutations — the same shape\n * `AgentActivityPanel` (`fetchActivity`) and `ReviewQueuePanel` (`fetchQueue`)\n * already use, rather than a fifth pattern.\n *\n * sandbox-ui free on purpose: `/web-react` must not force the optional peer, so\n * these render on the shared design tokens like the rest of the subpath. The\n * pure logic (nav items, routing, cookies, merging) lives in `/session-shell`,\n * which a server loader can import without pulling React.\n */\n\nimport {\n type ReactNode,\n type RefObject,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nimport {\n type SessionPage,\n type SessionRailAction,\n type SessionSort,\n type SessionSummary,\n mergeSessionPages,\n sessionLabel,\n UNTITLED_SESSION_LABEL,\n} from '../session-shell/index'\nimport { OVERLAY_SHADOW, PopoverSurface, usePopover } from './controls'\n\n// ---------------------------------------------------------------------------\n// useInfiniteScroll\n// ---------------------------------------------------------------------------\n\nexport interface UseInfiniteScrollOptions {\n /** Only fire `onLoadMore` while true (a next page exists, none in flight). */\n enabled: boolean\n /** Scroll container the sentinel lives in. Defaults to the viewport. */\n root?: RefObject<HTMLElement | null>\n /** Prefetch distance before the sentinel is actually reached. */\n rootMargin?: string\n}\n\nfunction rethrowAsync(error: unknown) {\n queueMicrotask(() => {\n throw error\n })\n}\n\n/**\n * Fires `onLoadMore` when a sentinel element scrolls into view. Returns a ref\n * callback for that sentinel (typically the last element in a list).\n *\n * The observer is re-created whenever `enabled` flips, so a short first page\n * that leaves the sentinel on-screen keeps loading: when a load finishes and\n * `enabled` returns to true, the fresh observer re-reads the current\n * intersection state and fires again until the sentinel is pushed off-screen.\n */\nexport function useInfiniteScroll(\n onLoadMore: () => void,\n { enabled, root, rootMargin = '300px' }: UseInfiniteScrollOptions,\n): (node: HTMLElement | null) => void {\n const [sentinel, setSentinel] = useState<HTMLElement | null>(null)\n const sentinelRef = useCallback((node: HTMLElement | null) => setSentinel(node), [])\n const onLoadMoreRef = useRef(onLoadMore)\n\n useEffect(() => {\n onLoadMoreRef.current = onLoadMore\n }, [onLoadMore])\n\n useEffect(() => {\n if (!sentinel || !enabled) return\n if (typeof IntersectionObserver === 'undefined') return\n const observer = new IntersectionObserver(\n (entries) => {\n if (!entries.some((entry) => entry.isIntersecting)) return\n try {\n onLoadMoreRef.current()\n } catch (error) {\n rethrowAsync(error)\n }\n },\n { root: root?.current ?? null, rootMargin },\n )\n observer.observe(sentinel)\n return () => observer.disconnect()\n }, [sentinel, enabled, root, rootMargin])\n\n return sentinelRef\n}\n\n// ---------------------------------------------------------------------------\n// useSessionHistory — cursor-paged data over an injected port\n// ---------------------------------------------------------------------------\n\nexport interface SessionPageQuery {\n /** Trimmed search term; empty string means no filter. */\n q: string\n sort: SessionSort\n /** `null` for the first page. */\n cursor: string | null\n /** Aborted when the view changes or the component unmounts. */\n signal: AbortSignal\n}\n\n/** Data port — one page of sessions for the current view. */\nexport type FetchSessionPage = (query: SessionPageQuery) => Promise<SessionPage>\n\nexport interface UseSessionHistoryOptions {\n fetchPage: FetchSessionPage\n /** Trimmed search term driving the fetch. */\n q: string\n sort: SessionSort\n /** SSR page 1 of the default view, so the first paint costs no request. */\n initialPage: SessionPage\n /** The sort `initialPage` was rendered for. Default `'newest'`. */\n defaultSort?: SessionSort\n}\n\nexport interface SessionHistoryState {\n items: SessionSummary[]\n hasMore: boolean\n isLoadingFirst: boolean\n isLoadingMore: boolean\n isError: boolean\n loadMore: () => void\n /** Re-run whichever load failed. */\n retry: () => void\n /** Refetch page 1 — call after a client-side mutation (e.g. a delete). */\n reload: () => void\n}\n\n/** Cheap content signature so a consumer inlining `initialPage={{items}}` on\n * every render does not reseed (and re-render) forever. Identity alone — what\n * the per-product versions keyed on — makes that an infinite loop. */\nfunction seedSignature(page: SessionPage): string {\n return JSON.stringify({\n nextCursor: page.nextCursor ?? null,\n items: page.items.map((item) => ({\n id: item.id,\n title: item.title,\n updatedAt: item.updatedAt,\n isPinned: Boolean(item.isPinned),\n unread: Boolean(item.unread),\n category: item.category ?? null,\n })),\n })\n}\n\n/**\n * Infinite-scroll data source for the history view. Seeds from `initialPage`\n * for the default view (no fetch) and otherwise fetches page 1 for the current\n * search/sort; `loadMore` appends the next cursor page.\n *\n * Raw promises + `AbortController` rather than a router fetcher, so a filter\n * change cancels in-flight requests, pages accumulate, and a late response from\n * a superseded view is dropped by the monotonic `seq` guard.\n */\nexport function useSessionHistory({\n fetchPage,\n q,\n sort,\n initialPage,\n defaultSort = 'newest',\n}: UseSessionHistoryOptions): SessionHistoryState {\n const [items, setItems] = useState<SessionSummary[]>(initialPage.items)\n const [nextCursor, setNextCursor] = useState<string | null>(initialPage.nextCursor ?? null)\n const [phase, setPhase] = useState<'idle' | 'loadingFirst' | 'loadingMore' | 'error'>('idle')\n const [reloadKey, setReloadKey] = useState(0)\n\n const seqRef = useRef(0)\n const resetAbortRef = useRef<AbortController | null>(null)\n const loadMoreAbortRef = useRef<AbortController | null>(null)\n const loadingMoreRef = useRef(false)\n const lastOpRef = useRef<'first' | 'more'>('first')\n\n // Live values read inside the stable `loadMore` callback.\n const nextCursorRef = useRef(nextCursor)\n nextCursorRef.current = nextCursor\n const viewRef = useRef({ q, sort, fetchPage })\n viewRef.current = { q, sort, fetchPage }\n const seedRef = useRef(initialPage)\n seedRef.current = initialPage\n\n const isDefaultView = q === '' && sort === defaultSort\n const seedKey = useMemo(() => seedSignature(initialPage), [initialPage])\n\n // Reset on view change (q/sort), on a new SSR seed (loader revalidation), or\n // on an explicit retry/reload. The default view comes straight from SSR;\n // explicit reloads fetch page 1 so a client-only mutation refreshes this list\n // without waiting on a route loader.\n useEffect(() => {\n resetAbortRef.current?.abort()\n loadMoreAbortRef.current?.abort()\n loadingMoreRef.current = false\n const seq = ++seqRef.current\n\n if (isDefaultView && reloadKey === 0) {\n setItems(seedRef.current.items)\n setNextCursor(seedRef.current.nextCursor ?? null)\n setPhase('idle')\n return\n }\n\n const controller = new AbortController()\n resetAbortRef.current = controller\n lastOpRef.current = 'first'\n setItems([])\n setNextCursor(null)\n setPhase('loadingFirst')\n\n void (async () => {\n try {\n const page = await viewRef.current.fetchPage({ q, sort, cursor: null, signal: controller.signal })\n if (seq !== seqRef.current) return\n setItems(page.items)\n setNextCursor(page.nextCursor ?? null)\n setPhase('idle')\n } catch {\n if (controller.signal.aborted || seq !== seqRef.current) return\n setPhase('error')\n }\n })()\n\n return () => controller.abort()\n }, [q, sort, seedKey, isDefaultView, reloadKey])\n\n const loadMore = useCallback(() => {\n const cursor = nextCursorRef.current\n if (!cursor || loadingMoreRef.current) return\n\n const { q: currentQ, sort: currentSort, fetchPage: currentFetch } = viewRef.current\n const seq = seqRef.current\n loadingMoreRef.current = true\n lastOpRef.current = 'more'\n const controller = new AbortController()\n loadMoreAbortRef.current = controller\n setPhase('loadingMore')\n\n void (async () => {\n try {\n const page = await currentFetch({ q: currentQ, sort: currentSort, cursor, signal: controller.signal })\n if (seq !== seqRef.current) return\n setItems((prev) => mergeSessionPages(prev, page.items))\n setNextCursor(page.nextCursor ?? null)\n setPhase('idle')\n } catch {\n if (controller.signal.aborted || seq !== seqRef.current) return\n setPhase('error')\n } finally {\n if (seq === seqRef.current) loadingMoreRef.current = false\n }\n })()\n }, [])\n\n const retry = useCallback(() => {\n if (lastOpRef.current === 'more') loadMore()\n else setReloadKey((key) => key + 1)\n }, [loadMore])\n\n const reload = useCallback(() => {\n setReloadKey((key) => key + 1)\n }, [])\n\n useEffect(\n () => () => {\n resetAbortRef.current?.abort()\n loadMoreAbortRef.current?.abort()\n },\n [],\n )\n\n return {\n items,\n hasMore: nextCursor !== null,\n isLoadingFirst: phase === 'loadingFirst',\n isLoadingMore: phase === 'loadingMore',\n isError: phase === 'error',\n loadMore,\n retry,\n reload,\n }\n}\n\n// ---------------------------------------------------------------------------\n// useSessionActions — rename / delete over injected mutations\n// ---------------------------------------------------------------------------\n\nexport interface SessionActionsOptions {\n /** Persist a new title. Reject to surface the error in the dialog. */\n renameSession: (sessionId: string, title: string) => Promise<void>\n deleteSession: (sessionId: string) => Promise<void>\n /** Called after a successful rename/delete — revalidate the rail here. */\n onChanged?: () => void\n /** Called after deleting the session the user is currently viewing, so the\n * product can navigate away from a route that no longer resolves. */\n onDeletedCurrent?: () => void\n /** The open session, compared against the delete target. */\n currentSessionId?: string | null\n /** Product toast/log seam. Errors also render inside the dialog. */\n notify?: (level: 'success' | 'error', message: string) => void\n labels?: Partial<SessionActionLabels>\n}\n\nexport interface SessionActionLabels {\n renameTitle: string\n renameField: string\n renameSubmit: string\n deleteTitle: string\n deleteBody: (title: string) => string\n deleteSubmit: string\n cancel: string\n renamed: string\n deleted: string\n renameFailed: string\n deleteFailed: string\n}\n\nconst DEFAULT_LABELS: SessionActionLabels = {\n renameTitle: 'Rename session',\n renameField: 'Title',\n renameSubmit: 'Save',\n deleteTitle: 'Delete session?',\n deleteBody: (title) => `This will permanently delete “${title}” and its messages. This cannot be undone.`,\n deleteSubmit: 'Delete',\n cancel: 'Cancel',\n renamed: 'Session renamed',\n deleted: 'Session deleted',\n renameFailed: 'Failed to rename session',\n deleteFailed: 'Failed to delete session',\n}\n\nexport interface SessionActions {\n openRename: (session: SessionSummary) => void\n openDelete: (session: SessionSummary) => void\n /** Render once, anywhere that survives navigation (the layout). */\n dialogs: ReactNode\n busy: boolean\n}\n\n/**\n * Rename + delete for one session, shared by the rail kebab and the history\n * row menu so both drive the same dialogs and the same product mutations.\n *\n * Dialogs are owned here rather than returned as raw state: two surfaces\n * needing the same confirm step is exactly how a product ends up with two\n * subtly different delete confirmations.\n */\nexport function useSessionActions({\n renameSession,\n deleteSession,\n onChanged,\n onDeletedCurrent,\n currentSessionId,\n notify,\n labels,\n}: SessionActionsOptions): SessionActions {\n const text = { ...DEFAULT_LABELS, ...labels }\n const [renameTarget, setRenameTarget] = useState<SessionSummary | null>(null)\n const [renameValue, setRenameValue] = useState('')\n const [deleteTarget, setDeleteTarget] = useState<SessionSummary | null>(null)\n const [busy, setBusy] = useState(false)\n const [error, setError] = useState<string | null>(null)\n\n const openRename = useCallback((session: SessionSummary) => {\n setError(null)\n setRenameTarget(session)\n setRenameValue(session.title ?? '')\n }, [])\n\n const openDelete = useCallback((session: SessionSummary) => {\n setError(null)\n setDeleteTarget(session)\n }, [])\n\n const submitRename = useCallback(async () => {\n if (!renameTarget) return\n const title = renameValue.trim()\n // A no-op rename closes rather than writing — otherwise every accidental\n // open costs a request and a revalidation.\n if (!title || title === renameTarget.title) {\n setRenameTarget(null)\n return\n }\n setBusy(true)\n setError(null)\n try {\n await renameSession(renameTarget.id, title)\n setRenameTarget(null)\n notify?.('success', text.renamed)\n onChanged?.()\n } catch (e) {\n const message = e instanceof Error ? e.message : text.renameFailed\n setError(message)\n notify?.('error', message)\n } finally {\n setBusy(false)\n }\n }, [renameTarget, renameValue, renameSession, notify, onChanged, text.renamed, text.renameFailed])\n\n const confirmDelete = useCallback(async () => {\n if (!deleteTarget) return\n const deletingCurrent = currentSessionId != null && deleteTarget.id === currentSessionId\n setBusy(true)\n setError(null)\n try {\n await deleteSession(deleteTarget.id)\n setDeleteTarget(null)\n notify?.('success', text.deleted)\n onChanged?.()\n if (deletingCurrent) onDeletedCurrent?.()\n } catch (e) {\n const message = e instanceof Error ? e.message : text.deleteFailed\n setError(message)\n notify?.('error', message)\n } finally {\n setBusy(false)\n }\n }, [deleteTarget, currentSessionId, deleteSession, notify, onChanged, onDeletedCurrent, text.deleted, text.deleteFailed])\n\n const dialogs = (\n <>\n {renameTarget && (\n <SessionDialog\n title={text.renameTitle}\n onClose={() => setRenameTarget(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <DialogButton onClick={() => setRenameTarget(null)} disabled={busy} variant=\"ghost\">\n {text.cancel}\n </DialogButton>\n <DialogButton onClick={() => void submitRename()} disabled={busy || !renameValue.trim()}>\n {text.renameSubmit}\n </DialogButton>\n </>\n }\n >\n <label htmlFor=\"agent-app-rename-session\" className=\"text-xs text-muted-foreground\">\n {text.renameField}\n </label>\n <input\n id=\"agent-app-rename-session\"\n value={renameValue}\n autoFocus\n onChange={(e) => setRenameValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !busy) {\n e.preventDefault()\n void submitRename()\n }\n }}\n className=\"mt-1.5 h-9 w-full rounded-md border border-strong bg-background px-3 text-sm text-foreground\"\n />\n </SessionDialog>\n )}\n\n {deleteTarget && (\n <SessionDialog\n title={text.deleteTitle}\n onClose={() => setDeleteTarget(null)}\n busy={busy}\n error={error}\n footer={\n <>\n <DialogButton onClick={() => setDeleteTarget(null)} disabled={busy} variant=\"ghost\">\n {text.cancel}\n </DialogButton>\n <DialogButton onClick={() => void confirmDelete()} disabled={busy} variant=\"destructive\">\n {text.deleteSubmit}\n </DialogButton>\n </>\n }\n >\n <p className=\"text-sm text-muted-foreground\">{text.deleteBody(sessionLabel(deleteTarget))}</p>\n </SessionDialog>\n )}\n </>\n )\n\n return { openRename, openDelete, dialogs, busy }\n}\n\nfunction DialogButton({\n children,\n onClick,\n disabled,\n variant = 'primary',\n}: {\n children: ReactNode\n onClick: () => void\n disabled?: boolean\n variant?: 'primary' | 'ghost' | 'destructive'\n}) {\n const tone =\n variant === 'ghost'\n ? 'text-muted-foreground hover:bg-accent hover:text-foreground'\n : variant === 'destructive'\n ? 'bg-destructive text-destructive-foreground hover:opacity-90'\n : 'bg-primary text-primary-foreground hover:opacity-90'\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n className={`h-9 rounded-md px-3 text-sm font-medium transition disabled:opacity-50 ${tone}`}\n >\n {children}\n </button>\n )\n}\n\nfunction SessionDialog({\n title,\n children,\n footer,\n onClose,\n busy,\n error,\n}: {\n title: string\n children: ReactNode\n footer: ReactNode\n onClose: () => void\n busy: boolean\n error: string | null\n}) {\n // Escape closes unless a mutation is in flight — closing mid-write would hide\n // the error the user needs to see.\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.key === 'Escape' && !busy) onClose()\n }\n document.addEventListener('keydown', onKey)\n return () => document.removeEventListener('keydown', onKey)\n }, [busy, onClose])\n\n return (\n <div className=\"fixed inset-0 z-50 flex items-center justify-center p-4\">\n <div\n className=\"absolute inset-0 bg-black/50\"\n onClick={() => {\n if (!busy) onClose()\n }}\n aria-hidden\n />\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={title}\n className={`relative w-full max-w-sm rounded-xl border border-card-edge bg-popover p-5 ${OVERLAY_SHADOW}`}\n >\n <h2 className=\"text-sm font-semibold text-foreground\">{title}</h2>\n <div className=\"mt-3\">{children}</div>\n {error && (\n <p role=\"alert\" className=\"mt-3 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive\">\n {error}\n </p>\n )}\n <div className=\"mt-5 flex justify-end gap-2\">{footer}</div>\n </div>\n </div>\n )\n}\n\n// ---------------------------------------------------------------------------\n// SessionHistoryPanel\n// ---------------------------------------------------------------------------\n\nexport interface SessionHistoryPanelProps {\n history: SessionHistoryState\n /** Whether the workspace has any sessions at all — decided by the SSR page,\n * independent of the active search, so filtering to zero shows \"no matches\"\n * rather than the first-run empty state. */\n hasAnySessions: boolean\n query: string\n onQueryChange: (value: string) => void\n sort: SessionSort\n onSortChange: (value: SessionSort) => void\n /** Product route for one session row. */\n hrefForSession: (sessionId: string) => string\n /** Rendered as the row link. Defaults to an `<a>`; pass a router Link to keep\n * client-side navigation. */\n linkComponent?: LinkLikeComponent\n /** Ids currently mid-turn — renders the responding treatment. */\n respondingSessionIds?: ReadonlySet<string>\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n /** Product-owned mutation for selected rows or a workspace-wide age range. */\n onBulkAction?: (action: SessionBulkAction) => Promise<void>\n /** Menu wording, so this surface and the rail name the same act the same way\n * — a product whose delete is really an archive says so in both places. */\n renameLabel?: string\n deleteLabel?: string\n /**\n * Row actions this shell has no opinion about — pin, categorise, share.\n * Same seam and same ordering as the rail's `SessionRowActions.extraActions`:\n * evaluated per session, placed between rename and delete. This menu is\n * text-only, so `icon` is ignored here and honoured on the rail.\n */\n extraActions?: (session: SessionSummary) => SessionRailAction[]\n /** New-session destination for the header action. Omitted ⇒ no button. */\n newSessionHref?: string\n title?: string\n untitledLabel?: string\n emptyTitle?: string\n emptyDescription?: string\n /** Absolute → relative timestamp. Defaults to a compact built-in. */\n formatTimestamp?: (isoDate: string | null) => string\n /** Max width of the reading column. `'full'` opts out for a product whose\n * surface really is a wide table. Default keeps title and timestamp inside\n * one scannable line rather than at opposite edges of a 1440px viewport. */\n contentWidth?: 'reading' | 'full'\n className?: string\n}\n\nexport type SessionBulkAction =\n | { kind: 'selected'; ids: string[] }\n | { kind: 'older-than'; days: number }\n | { kind: 'newer-than'; days: number }\n\nexport interface LinkLikeProps {\n to: string\n className?: string\n children?: ReactNode\n}\n\nexport type LinkLikeComponent = (props: LinkLikeProps) => ReactNode\n\nfunction AnchorLink({ to, className, children }: LinkLikeProps) {\n return (\n <a href={to} className={className}>\n {children}\n </a>\n )\n}\n\nconst MINUTE = 60_000\nconst HOUR = 60 * MINUTE\nconst DAY = 24 * HOUR\n\n/** Compact relative time. Overridable — a product with its own i18n passes\n * `formatTimestamp` rather than this being the only option. */\nexport function formatSessionTimestamp(isoDate: string | null): string {\n if (!isoDate) return ''\n const at = Date.parse(isoDate)\n if (Number.isNaN(at)) return ''\n const delta = Date.now() - at\n if (delta < MINUTE) return 'just now'\n if (delta < HOUR) return `${Math.floor(delta / MINUTE)}m ago`\n if (delta < DAY) return `${Math.floor(delta / HOUR)}h ago`\n if (delta < 7 * DAY) return `${Math.floor(delta / DAY)}d ago`\n return new Date(at).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })\n}\n\nfunction SkeletonRows() {\n // The shimmer rows stay hidden from assistive tech — they say nothing a\n // reader can use — but the wait itself has to be announced, or the panel is\n // silent from the first paint until the rows arrive. The live region is a\n // sibling so the rows' own flex layout is untouched.\n return (\n <>\n <span role=\"status\" aria-live=\"polite\" aria-busy={true} className=\"sr-only\">\n Loading sessions…\n </span>\n <div className=\"flex flex-col gap-0.5\" aria-hidden>\n {Array.from({ length: 8 }).map((_, i) => (\n <div key={i} className=\"flex items-center gap-3 px-3 py-2.5\">\n <div className=\"h-4 w-4 animate-pulse rounded bg-muted\" />\n <div className=\"h-4 w-1/2 animate-pulse rounded bg-muted\" />\n <div className=\"ml-auto h-3 w-12 animate-pulse rounded bg-muted\" />\n </div>\n ))}\n </div>\n </>\n )\n}\n\nfunction MessageIcon({ className }: { className?: string }) {\n return (\n <svg viewBox=\"0 0 24 24\" className={className} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\" />\n </svg>\n )\n}\n\n/**\n * The full session history: search, sort, cursor-paged rows with per-row\n * actions, and the states in between (first-run empty, loading, no matches,\n * error + retry).\n *\n * This is the surface the rail's capped list overflows into — the reason the\n * rail can stay short without hiding the user's work.\n */\nexport function SessionHistoryPanel({\n history,\n hasAnySessions,\n query,\n onQueryChange,\n sort,\n onSortChange,\n hrefForSession,\n linkComponent: Link = AnchorLink,\n respondingSessionIds,\n onRename,\n onDelete,\n onBulkAction,\n renameLabel = 'Rename',\n deleteLabel = 'Delete',\n extraActions,\n newSessionHref,\n title = 'History',\n untitledLabel = UNTITLED_SESSION_LABEL,\n emptyTitle = 'No sessions yet',\n emptyDescription = 'Your chat sessions will show up here once you start one.',\n formatTimestamp = formatSessionTimestamp,\n contentWidth = 'reading',\n className,\n}: SessionHistoryPanelProps) {\n const scrollRef = useRef<HTMLDivElement | null>(null)\n const sentinelRef = useInfiniteScroll(history.loadMore, {\n enabled: history.hasMore && !history.isLoadingMore && !history.isError,\n root: scrollRef,\n rootMargin: '300px',\n })\n const searchTerm = query.trim()\n const isSearching = searchTerm.length > 0\n const column = contentWidth === 'full' ? 'w-full' : 'mx-auto w-full max-w-4xl'\n const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())\n const [ageDays, setAgeDays] = useState('30')\n const [bulkTarget, setBulkTarget] = useState<{\n action: SessionBulkAction\n title: string\n body: string\n } | null>(null)\n const [bulkBusy, setBulkBusy] = useState(false)\n const [bulkError, setBulkError] = useState<string | null>(null)\n\n useEffect(() => {\n setSelectedIds(new Set())\n }, [searchTerm, sort])\n\n useEffect(() => {\n const visible = new Set(history.items.map((item) => item.id))\n setSelectedIds((current) => {\n const next = new Set([...current].filter((id) => visible.has(id)))\n return next.size === current.size ? current : next\n })\n }, [history.items])\n\n const selectedCount = selectedIds.size\n const allVisibleSelected = history.items.length > 0 && history.items.every((item) => selectedIds.has(item.id))\n const parsedAgeDays = Number(ageDays)\n const validAgeDays = Number.isInteger(parsedAgeDays) && parsedAgeDays >= 1 && parsedAgeDays <= 36_500\n\n const openBulkAction = useCallback((action: SessionBulkAction) => {\n const verb = deleteLabel.toLowerCase()\n if (action.kind === 'selected') {\n setBulkTarget({\n action,\n title: `${deleteLabel} selected sessions?`,\n body: `${verb === 'delete' ? 'This permanently removes' : `This ${verb}s`} ${action.ids.length} selected session${action.ids.length === 1 ? '' : 's'} and its messages.`,\n })\n return\n }\n const range = action.kind === 'older-than' ? `older than ${action.days} days` : `from the last ${action.days} days`\n setBulkTarget({\n action,\n title: `${deleteLabel} sessions ${range}?`,\n body: 'This applies to every matching session in this workspace, including sessions not currently loaded in this list.',\n })\n }, [deleteLabel])\n\n const confirmBulkAction = useCallback(async () => {\n if (!bulkTarget || !onBulkAction) return\n setBulkBusy(true)\n setBulkError(null)\n try {\n await onBulkAction(bulkTarget.action)\n setBulkTarget(null)\n setSelectedIds(new Set())\n history.reload()\n } catch (error) {\n setBulkError(error instanceof Error ? error.message : `Could not ${deleteLabel.toLowerCase()} sessions`)\n } finally {\n setBulkBusy(false)\n }\n }, [bulkTarget, deleteLabel, history, onBulkAction])\n\n return (\n <div className={`flex min-h-0 min-w-0 flex-1 flex-col ${className ?? ''}`}>\n {/* 56px, matching the rail header the fleet aligned on. */}\n <header className=\"flex h-14 shrink-0 items-center border-b border-border px-4 sm:px-6\">\n <div className={`flex items-center gap-3 px-3 ${column}`}>\n <h1 className=\"flex-1 truncate text-sm font-semibold text-foreground\">{title}</h1>\n {newSessionHref && (\n <Link\n to={newSessionHref}\n className=\"inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition hover:opacity-90\"\n >\n <span aria-hidden className=\"text-sm leading-none\">+</span>\n New chat\n </Link>\n )}\n </div>\n </header>\n\n <div ref={scrollRef} className=\"min-h-0 flex-1 overflow-y-auto\">\n {hasAnySessions && (\n <div className=\"sticky top-0 z-10 bg-background px-4 sm:px-6\">\n <div className={`flex flex-col gap-2 px-3 pb-3 pt-4 sm:flex-row sm:items-center sm:gap-3 ${column}`}>\n <input\n type=\"search\"\n value={query}\n onChange={(e) => onQueryChange(e.target.value)}\n placeholder=\"Search your sessions…\"\n aria-label=\"Search sessions\"\n className=\"h-9 min-w-0 appearance-none rounded-md border border-strong bg-card px-3 text-sm text-foreground placeholder:text-muted-foreground sm:flex-1 [&::-webkit-search-cancel-button]:appearance-none\"\n />\n <select\n value={sort}\n onChange={(e) => onSortChange(e.target.value as SessionSort)}\n aria-label=\"Sort sessions\"\n className=\"h-9 shrink-0 appearance-none rounded-md border border-strong bg-card px-2 text-sm text-foreground sm:w-[132px]\"\n >\n <option value=\"newest\">Newest</option>\n <option value=\"oldest\">Oldest</option>\n </select>\n </div>\n {onBulkAction && (\n <div className={`flex flex-col gap-2 border-t border-border px-3 py-3 ${column}`}>\n <div className=\"flex flex-wrap items-center gap-2\">\n <button\n type=\"button\"\n onClick={() => setSelectedIds(new Set(history.items.map((item) => item.id)))}\n disabled={allVisibleSelected || history.items.length === 0}\n className=\"h-8 rounded-md border border-border px-2.5 text-xs font-medium text-foreground transition hover:bg-accent disabled:opacity-50\"\n >\n Select all\n </button>\n <button\n type=\"button\"\n onClick={() => setSelectedIds(new Set())}\n disabled={selectedCount === 0}\n className=\"h-8 rounded-md border border-border px-2.5 text-xs font-medium text-foreground transition hover:bg-accent disabled:opacity-50\"\n >\n Deselect all\n </button>\n <span className=\"text-xs text-muted-foreground\" aria-live=\"polite\">\n {selectedCount} selected\n </span>\n {selectedCount > 0 && (\n <button\n type=\"button\"\n onClick={() => openBulkAction({ kind: 'selected', ids: [...selectedIds] })}\n className=\"h-8 rounded-md bg-destructive px-2.5 text-xs font-medium text-destructive-foreground transition hover:opacity-90\"\n >\n {deleteLabel} selected\n </button>\n )}\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n <label htmlFor=\"agent-app-session-age\" className=\"text-xs text-muted-foreground\">\n Session age\n </label>\n <input\n id=\"agent-app-session-age\"\n type=\"number\"\n min={1}\n max={36_500}\n value={ageDays}\n onChange={(event) => setAgeDays(event.target.value)}\n aria-invalid={ageDays.length > 0 && !validAgeDays}\n className=\"h-8 w-20 rounded-md border border-strong bg-card px-2 text-xs tabular-nums text-foreground\"\n />\n <span className=\"text-xs text-muted-foreground\">days</span>\n <button\n type=\"button\"\n onClick={() => openBulkAction({ kind: 'older-than', days: parsedAgeDays })}\n disabled={!validAgeDays}\n className=\"h-8 rounded-md border border-border px-2.5 text-xs font-medium text-foreground transition hover:bg-accent disabled:opacity-50\"\n >\n {deleteLabel} older\n </button>\n <button\n type=\"button\"\n onClick={() => openBulkAction({ kind: 'newer-than', days: parsedAgeDays })}\n disabled={!validAgeDays}\n className=\"h-8 rounded-md border border-border px-2.5 text-xs font-medium text-foreground transition hover:bg-accent disabled:opacity-50\"\n >\n {deleteLabel} recent\n </button>\n </div>\n </div>\n )}\n </div>\n )}\n\n <div className={`px-4 pb-8 pt-1 sm:px-6 ${column}`}>\n {!hasAnySessions ? (\n <div className=\"flex min-h-[50vh] flex-col items-center justify-center gap-2 text-center\">\n <p className=\"text-sm font-medium text-foreground\">{emptyTitle}</p>\n <p className=\"max-w-xs text-xs text-muted-foreground\">{emptyDescription}</p>\n </div>\n ) : history.isLoadingFirst ? (\n <SkeletonRows />\n ) : history.items.length === 0 ? (\n history.isError ? (\n <ErrorBlock onRetry={history.retry} message=\"Couldn’t load your sessions.\" />\n ) : isSearching ? (\n <p className=\"py-16 text-center text-sm text-muted-foreground\">\n No sessions match “{searchTerm}”.\n </p>\n ) : (\n <p className=\"py-16 text-center text-sm text-muted-foreground\">No sessions remain.</p>\n )\n ) : (\n <div className=\"flex flex-col gap-0.5\">\n {history.items.map((session) => (\n <SessionRow\n key={session.id}\n session={session}\n href={hrefForSession(session.id)}\n Link={Link}\n responding={respondingSessionIds?.has(session.id) ?? false}\n untitledLabel={untitledLabel}\n timestamp={formatTimestamp(session.updatedAt)}\n onRename={onRename}\n onDelete={onDelete}\n selectable={Boolean(onBulkAction)}\n selected={selectedIds.has(session.id)}\n onSelectedChange={(selected) => {\n setSelectedIds((current) => {\n const next = new Set(current)\n if (selected) next.add(session.id)\n else next.delete(session.id)\n return next\n })\n }}\n renameLabel={renameLabel}\n deleteLabel={deleteLabel}\n extraActions={extraActions}\n />\n ))}\n\n {history.isError ? (\n <ErrorBlock onRetry={history.retry} message=\"Couldn’t load more sessions.\" inline />\n ) : history.hasMore ? (\n <div ref={sentinelRef} className=\"flex items-center justify-center py-6\">\n {history.isLoadingMore && (\n <span role=\"status\" aria-live=\"polite\" aria-busy={true} className=\"text-xs text-muted-foreground\">\n Loading…\n </span>\n )}\n </div>\n ) : null}\n </div>\n )}\n </div>\n </div>\n {bulkTarget && (\n <SessionDialog\n title={bulkTarget.title}\n onClose={() => {\n if (!bulkBusy) {\n setBulkTarget(null)\n setBulkError(null)\n }\n }}\n busy={bulkBusy}\n error={bulkError}\n footer={\n <>\n <DialogButton\n onClick={() => {\n setBulkTarget(null)\n setBulkError(null)\n }}\n disabled={bulkBusy}\n variant=\"ghost\"\n >\n Cancel\n </DialogButton>\n <DialogButton onClick={() => void confirmBulkAction()} disabled={bulkBusy} variant=\"destructive\">\n {bulkBusy ? 'Working…' : deleteLabel}\n </DialogButton>\n </>\n }\n >\n <p className=\"text-sm text-muted-foreground\">{bulkTarget.body}</p>\n </SessionDialog>\n )}\n </div>\n )\n}\n\nfunction ErrorBlock({ message, onRetry, inline }: { message: string; onRetry: () => void; inline?: boolean }) {\n return (\n <div\n className={\n inline\n ? 'flex items-center justify-center gap-3 py-6 text-sm text-muted-foreground'\n : 'flex min-h-[40vh] flex-col items-center justify-center gap-3 text-center'\n }\n >\n <span className=\"text-sm text-muted-foreground\">{message}</span>\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"h-8 rounded-md border border-border px-3 text-xs font-medium text-foreground transition hover:bg-accent\"\n >\n Retry\n </button>\n </div>\n )\n}\n\nfunction SessionRow({\n session,\n href,\n Link,\n responding,\n untitledLabel,\n timestamp,\n onRename,\n onDelete,\n renameLabel,\n deleteLabel,\n extraActions,\n selectable,\n selected,\n onSelectedChange,\n}: {\n session: SessionSummary\n href: string\n Link: LinkLikeComponent\n responding: boolean\n untitledLabel: string\n timestamp: string\n onRename?: (session: SessionSummary) => void\n onDelete?: (session: SessionSummary) => void\n renameLabel: string\n deleteLabel: string\n extraActions?: (session: SessionSummary) => SessionRailAction[]\n selectable: boolean\n selected: boolean\n onSelectedChange: (selected: boolean) => void\n}) {\n const [menuOpen, setMenuOpen] = useState(false)\n const panelId = useId()\n const { containerRef, triggerRef, panelRef, triggerProps } = usePopover(menuOpen, setMenuOpen)\n const extras = extraActions?.(session) ?? []\n const hasMenu = Boolean(onRename) || Boolean(onDelete) || extras.length > 0\n // An unread dot next to a live responding indicator is two signals for one\n // state; the working indicator wins while the turn runs.\n const showUnread = Boolean(session.unread) && !responding\n\n return (\n <div className={`group relative flex items-center gap-2 rounded-lg px-3 py-2.5 transition-colors hover:bg-accent ${selected ? 'bg-primary/10' : ''}`}>\n {selectable && (\n <input\n type=\"checkbox\"\n checked={selected}\n onChange={(event) => onSelectedChange(event.target.checked)}\n aria-label={`Select ${sessionLabel(session, untitledLabel)}`}\n className=\"h-4 w-4 shrink-0 rounded border-border accent-primary\"\n />\n )}\n <Link to={href} className=\"flex min-w-0 flex-1 items-center gap-3\">\n {showUnread && <span className=\"h-1.5 w-1.5 shrink-0 rounded-full bg-primary\" aria-hidden />}\n <MessageIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n <span\n className={`truncate text-sm ${responding ? 'text-muted-foreground' : 'text-foreground'} ${showUnread ? 'font-semibold' : ''}`}\n {...(responding ? { role: 'status', 'aria-label': 'Agent responding' } : {})}\n >\n {sessionLabel(session, untitledLabel)}\n </span>\n </Link>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">{timestamp}</span>\n {hasMenu && (\n <div ref={containerRef} className=\"relative shrink-0\">\n <button\n type=\"button\"\n {...triggerProps}\n aria-label=\"Session actions\"\n aria-controls={menuOpen ? panelId : undefined}\n onClick={() => setMenuOpen((open) => !open)}\n // Visible by default and hover-revealed only from `sm:` up: a\n // touch device has no hover, so an opacity-0 kebab is an action\n // the user can never reach.\n className=\"flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 aria-expanded:opacity-100\"\n >\n <span aria-hidden className=\"text-base leading-none\">⋯</span>\n </button>\n <PopoverSurface\n open={menuOpen}\n id={panelId}\n role=\"menu\"\n triggerRef={triggerRef}\n panelRef={panelRef}\n className={`w-36 overflow-hidden rounded-md border border-card-edge bg-popover py-1 ${OVERLAY_SHADOW}`}\n >\n {onRename && (\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n setMenuOpen(false)\n onRename(session)\n }}\n className=\"block w-full px-3 py-1.5 text-left text-xs text-foreground transition hover:bg-accent\"\n >\n {renameLabel}\n </button>\n )}\n {extras.map((action) => (\n <button\n key={action.id}\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n setMenuOpen(false)\n action.onSelect()\n }}\n className={`block w-full px-3 py-1.5 text-left text-xs transition ${\n action.destructive\n ? 'text-destructive hover:bg-destructive/10'\n : 'text-foreground hover:bg-accent'\n }`}\n >\n {action.label}\n </button>\n ))}\n {onDelete && (\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => {\n setMenuOpen(false)\n onDelete(session)\n }}\n className=\"block w-full px-3 py-1.5 text-left text-xs text-destructive transition hover:bg-destructive/10\"\n >\n {deleteLabel}\n </button>\n )}\n </PopoverSurface>\n </div>\n )}\n </div>\n )\n}\n"],"mappings":";;;;;;;;;;;;AAgBA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA4ZK,mBACE,KADF;AAlYZ,SAAS,aAAa,OAAgB;AACpC,iBAAe,MAAM;AACnB,UAAM;AAAA,EACR,CAAC;AACH;AAWO,SAAS,kBACd,YACA,EAAE,SAAS,MAAM,aAAa,QAAQ,GACF;AACpC,QAAM,CAAC,UAAU,WAAW,IAAI,SAA6B,IAAI;AACjE,QAAM,cAAc,YAAY,CAAC,SAA6B,YAAY,IAAI,GAAG,CAAC,CAAC;AACnF,QAAM,gBAAgB,OAAO,UAAU;AAEvC,YAAU,MAAM;AACd,kBAAc,UAAU;AAAA,EAC1B,GAAG,CAAC,UAAU,CAAC;AAEf,YAAU,MAAM;AACd,QAAI,CAAC,YAAY,CAAC,QAAS;AAC3B,QAAI,OAAO,yBAAyB,YAAa;AACjD,UAAM,WAAW,IAAI;AAAA,MACnB,CAAC,YAAY;AACX,YAAI,CAAC,QAAQ,KAAK,CAAC,UAAU,MAAM,cAAc,EAAG;AACpD,YAAI;AACF,wBAAc,QAAQ;AAAA,QACxB,SAAS,OAAO;AACd,uBAAa,KAAK;AAAA,QACpB;AAAA,MACF;AAAA,MACA,EAAE,MAAM,MAAM,WAAW,MAAM,WAAW;AAAA,IAC5C;AACA,aAAS,QAAQ,QAAQ;AACzB,WAAO,MAAM,SAAS,WAA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iBAAO;AAAA;AAAA,cAbH,OAAO;AAAA,YAcd,CACD;AAAA,YACA,YACC;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,MAAK;AAAA,gBACL,SAAS,MAAM;AACb,8BAAY,KAAK;AACjB,2BAAS,OAAO;AAAA,gBAClB;AAAA,gBACA,WAAU;AAAA,gBAET;AAAA;AAAA,YACH;AAAA;AAAA;AAAA,MAEJ;AAAA,OACF;AAAA,KAEJ;AAEJ;","names":[]}
@@ -69,10 +69,11 @@ function normalizeToolEvent(event) {
69
69
  }
70
70
  if (event.type === "tool_result" || event.type === "tool.result") {
71
71
  const data = event.data ?? {};
72
+ const state = asRecord(data.state);
72
73
  const output = data.output;
73
- const exitCode = toolExitCode(output, data);
74
- const error = asString(data.error) ?? toolExitError(output, exitCode);
75
- const terminalError = data.status === "error" || data.status === "failed" || Boolean(error) || exitCode !== void 0 && exitCode !== 0;
74
+ const exitCode = toolExitCode(output, data, data.metadata, state, state?.metadata);
75
+ const error = asString(data.error ?? state?.error) ?? toolExitError(output, exitCode);
76
+ const terminalError = data.status === "error" || data.status === "failed" || state?.status === "error" || state?.status === "failed" || Boolean(error) || exitCode !== void 0 && exitCode !== 0;
76
77
  return {
77
78
  type: "message.part.updated",
78
79
  data: {
@@ -163,7 +164,7 @@ function normalizePersistedPart(rawPart) {
163
164
  if (type === "tool") {
164
165
  const state = asRecord(rawPart.state);
165
166
  const output = state?.output ?? rawPart.output;
166
- const exitCode = toolExitCode(output, state, rawPart);
167
+ const exitCode = toolExitCode(output, state, state?.metadata, rawPart, rawPart.metadata);
167
168
  const error = asString(state?.error ?? rawPart.error) ?? toolExitError(output, exitCode);
168
169
  const terminalError = state?.status === "error" || state?.status === "failed" || rawPart.status === "error" || rawPart.status === "failed" || Boolean(error) || exitCode !== void 0 && exitCode !== 0;
169
170
  const status = terminalError ? "error" : state?.status === "completed" || rawPart.status === "completed" ? "completed" : output !== void 0 ? "completed" : "running";
@@ -405,4 +406,4 @@ export {
405
406
  terminalizeDanglingAssistantToolUpdates,
406
407
  encodeEvent
407
408
  };
408
- //# sourceMappingURL=chunk-4SGGSXI7.js.map
409
+ //# sourceMappingURL=chunk-ZMMIQOFI.js.map