From b616cf333fe9e7ae8fe414d42318aef09f3ce714 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 09:22:30 -0800 Subject: [PATCH 01/19] docs(spec): thread sidebar design for React and Angular Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-16-thread-sidebar-design.md | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-16-thread-sidebar-design.md diff --git a/docs/superpowers/specs/2026-11-16-thread-sidebar-design.md b/docs/superpowers/specs/2026-11-16-thread-sidebar-design.md new file mode 100644 index 000000000..7bf1e001c --- /dev/null +++ b/docs/superpowers/specs/2026-11-16-thread-sidebar-design.md @@ -0,0 +1,216 @@ +# Thread sidebar for React and Angular — design + +Date: 2026-11-16. Status: approved 2026-11-17. + +## Intent + +A React or Angular app that connects to LangGraph should get a working conversation sidebar without writing a data layer: the conversations listed, and new chat, rename, delete, archive, pin, reorder and move-to-project working against the server. Apps must still be able to restyle it, replace pieces of it, add their own sections and actions, and point it at a backend other than LangGraph. + +Why now: the React parity survey (2026-11-15) found that Angular has an SDK-backed thread store (`LangGraphThreadsAdapter`) and React has none. The only React directory is the example app's own `examples/chat/native/shared/directory.ts`. Brian chose to close this by shipping a sidebar in both frameworks rather than a React-only port. + +## Goals + +- One framework-neutral thread store contract, `ThreadDirectory`, that both frameworks' sidebars read. +- A LangGraph implementation of it, `createLangGraphThreadDirectory`, shipped beside `createSession`. +- A connected sidebar in each framework that takes a directory and works with no other wiring: + - React: `ThreadSidebar` in `@threadplane/react/chat`. + - Angular: `` in `@threadplane/chat`. +- The list refreshes after a run ends, when the app asks it to, and after each action. +- Customization without forking. Apps can: + - replace how a row looks; + - add sections above or below the built-in ones; + - add menu actions; + - turn built-in features off (projects, archive, pin, reorder, delete); + - supply their own `ThreadDirectory`. +- Angular's `LangGraphThreadsAdapter` keeps working. It is rebuilt on the shared store once the Angular package exports core (phase 2), so the metadata rules end up in one place. +- Project names are stored on the LangGraph server through the Store API, so they follow the user across devices. + +## Non-goals + +- Thread storage for AG-UI. AG-UI has no thread API; AG-UI apps supply their own directory. +- Server-side search, pagination beyond the first page, or infinite scroll. The first slice keeps Angular's `limit: 50`. Paging is a follow-up. +- Multi-user sharing, permissions, or thread ownership. +- New visual design. The sidebars reuse today's thread list, project list and sidenav styling and tokens. + +## Anti-goals (a failure even if it works) + +- Two copies of the metadata rules (title, archived, pinned, pin order, project) that can drift between frameworks. +- A sidebar that only works for LangGraph. The UI must depend on the contract, not the SDK. +- Breaking existing Angular apps that use `LangGraphThreadsAdapter`, `` inputs or `ThreadActionAdapter`. +- Silent failures. Angular's adapter logs and swallows refresh errors; the shared store must expose a load error the sidebar can show, and action errors must roll back the optimistic change visibly. + +## What exists today + +- **Angular data:** `libs/langgraph/src/lib/threads/threads-adapter.ts`, the `LangGraphThreadsAdapter` DI service. It wraps `client.threads` and stores state in thread `metadata`: + - `title`, falling back to a configurable label; + - `archived`, `pinned` and `pinnedOrder`; + - `projectId`. + It publishes `threads` (active, pinned first by `pinnedOrder`) and `archivedThreads` signals. Every mutation refreshes the whole list. Apps wire its methods to `ThreadActionAdapter` by hand, and `refreshOnRunEnd(agent, fn)` refreshes after a run. +- **Angular UI:** `` takes `threads`, `archivedThreads`, `actions`, `projects`, `projectActions`, `activeThreadId`, `selectedProjectId` and emits `newChat`, `threadSelected`, `projectSelected`. It has named content slots (`sidenavHeader`, `sidenavPrimary`, `sidenavSections`, footer, account). `` also draws a thread list. +- **React UI:** + - `ThreadList` and `ProjectList` take items plus `ThreadActionAdapter` / `ProjectActionAdapter` and handle optimistic rows. + - `ChatSidenav` is a children shell. + - Two open PRs from another session: `ChatSidenavSections` (cacheplane/threadplane#1621) composes new chat, projects, recent and archived; a `threads` prop on `Chat` (#1622). +- **Projects:** neither LangGraph nor the Angular adapter stores project names. Threads carry `metadata.projectId` only. The example keeps project names in `localStorage`. +- **Packaging:** `@threadplane/react`, `core` and `content` are private, and `core` will not be published as its own package. The published Angular packages will export the core contract later in the React parity roadmap; until then `@threadplane/chat` cannot depend on core, and `@threadplane/langgraph` imports only types from its private runtime. + +## Approaches considered + +1. **Shared store, thin sidebar per framework (chosen by Brian).** A neutral `ThreadDirectory` contract, one LangGraph implementation, and a connected sidebar in each framework that binds to it. Angular's adapter is rebuilt on the store. Most up-front work, one set of rules. +2. **Separate implementation per framework.** Keep Angular's adapter; write a React twin. Faster, but the metadata rules are duplicated and will drift. +3. **UI only.** Connected sidebars over a directory interface, with no LangGraph implementation shipped. Least work, but apps still write the data layer, which defeats the goal. + +## Delivery in two phases + +Brian decided that `@threadplane/core` is not published on its own; the Angular packages export it at a later point in the parity roadmap. That decides the order. + +**Phase 1 (this work).** +- The `ThreadDirectory` contract in core, `createLangGraphThreadDirectory` in the private LangGraph runtime, and the React `ThreadSidebar` on top of them. +- The Angular `` in `@threadplane/chat`, reading a structurally identical contract declared inside `@threadplane/chat`. +- `LangGraphThreadsAdapter` implements that Angular contract with its existing code, and gains the LangGraph Store project store. + +**Phase 2 (when the Angular packages export core).** +- The Angular contract becomes a re-export of the core one. +- `LangGraphThreadsAdapter` is rebuilt on `createLangGraphThreadDirectory`, and the second copy of the metadata rules is deleted. + +Phase 1 holds two copies of the metadata rules for a while, which is the drift the anti-goals warn about. Two guards keep them identical until phase 2: +- a type-level spec that asserts the core and Angular contracts are mutually assignable; +- one conformance suite of specs, run against both LangGraph implementations with the same fake SDK client, covering ordering, metadata keys, title fallback, archive, pin order, project moves and failure rollback. + +Item 12 (publishing the neutral runtime) moves to that later roadmap point and is not part of this work. + +## Design + +### The contract (core) + +`ThreadDirectory` lives in `@threadplane/core` beside `AgentSession`, framework-neutral and backend-neutral: + +```ts +interface ThreadDirectorySnapshot { + readonly threads: readonly ThreadEntry[]; // active, pinned first in pin order, then most recent + readonly archived: readonly ThreadEntry[]; + readonly projects?: readonly ProjectEntry[]; // absent when the directory has no project store + readonly status: 'idle' | 'loading' | 'error'; + readonly error?: AgentError; // last load failure, cleared by a successful refresh +} +interface ThreadEntry { + readonly id: string; + readonly title?: string; + readonly updatedAt?: number; + readonly pinned?: boolean; + readonly archived?: boolean; + readonly projectId?: string | null; +} +interface ProjectEntry { readonly id: string; readonly name: string } + +interface ThreadDirectory { + getSnapshot(): ThreadDirectorySnapshot; + subscribe(notify: () => void): () => void; + refresh(options?: { signal?: AbortSignal }): Promise; + create?(options?: { metadata?: PlainRecord; signal?: AbortSignal }): Promise<{ id: string }>; + rename?(id: string, title: string): Promise; + remove?(id: string): Promise; + setArchived?(id: string, archived: boolean): Promise; + setPinned?(id: string, pinned: boolean): Promise; + reorderPinned?(id: string, beforeId: string | null): Promise; + setProject?(id: string, projectId: string | null): Promise; + createProject?(name: string): Promise<{ id: string }>; + renameProject?(id: string, name: string): Promise; + removeProject?(id: string): Promise; + dispose(): void; +} +``` + +The shape follows `AgentSession`: a snapshot, change notification, and optional capabilities whose absence hides the matching UI. Snapshots are frozen and keep unchanged entries by reference. + +A helper, `refreshOnRunEnd(directory, session)`, watches a core `AgentSession` and refreshes when a run leaves `running`. Both sidebars call it when given a session. + +### The LangGraph implementation (runtime) + +`createLangGraphThreadDirectory({ apiUrl | client, titleFallback?, projects? })` sits next to `createSession` in the LangGraph runtime. + +- It reads and writes the same metadata keys as today's Angular adapter (`title`, `archived`, `pinned`, `pinnedOrder`, `projectId`), so existing threads show correctly in both frameworks. +- It brings the example directory's safety rules into the library: + - same-origin checks for browser use; + - no SDK retries for mutations; + - error bodies never read; + - abortable requests; + - a missing thread on `getThread` reported as missing, not as an error. +- Mutations are optimistic in the store and roll back on failure. After a successful mutation the store refreshes. +- `projects` is a pluggable project store. The default stores project names with the LangGraph Store API (`client.store`) under a namespace such as `["threadplane", "projects"]`, one item per project with key = project id and value `{ name }`. Apps can pass their own store, or `projects: false` to turn projects off. +- Removing a project moves its threads out of it (`projectId: null`) before the project item is deleted, so no thread points at a missing project. + +In phase 1, Angular's `LangGraphThreadsAdapter` keeps its own implementation and adds the same project store, `status`/`error` signals and the Angular `ThreadDirectory` shape. In phase 2 it becomes a thin Angular wrapper: it creates the shared directory, exposes `threads` and `archivedThreads` as signals from snapshots, and keeps every public method and signal it has today. + +### React sidebar + +`ThreadSidebar` in `@threadplane/react/chat`: + +```tsx + +``` + +It composes the existing `ThreadList`, `ProjectList` and (once merged) `ChatSidenavSections`. It derives the action adapters from the directory's capabilities, so a directory without `remove` shows no Delete item. It shows loading, empty and error states, with Retry calling `refresh`. It renders inside `ChatSidenav` or standalone. + +### Angular sidebar + +`` in `@threadplane/chat` mirrors the React props. In phase 1, `directory` takes the Angular-side contract, which `LangGraphThreadsAdapter` implements: + +- `features` turns built-ins off; +- `ng-template` slots override rows; +- content projection carries before and after sections; +- an `extraActions` input adds menu items. + +It composes ``'s existing sections, so `` itself does not change. Given an `agent`, it refreshes after each run. + +### Customization levels + +1. Props and inputs: features on or off, labels, the active thread. +2. Slots: row rendering, sections before and after, extra actions. +3. Bring your own directory: any object that meets `ThreadDirectory`, for AG-UI or a custom API. +4. Go lower: the existing `ThreadList`, `ProjectList` and `ChatSidenav` pieces stay public for apps that want full control. + +## Constraints + +- Follow repo rules: + - React parity dispositions, written as text; + - the export allowlists in `verify-packages`; + - runtime candidate module counts; + - no committed `baseline.json` or API content; + - no contractions in docs prose. +- No breaking change to existing Angular APIs. If one becomes unavoidable, it waits for a minor release per the release-versioning rule. +- The LangGraph directory must pass the same installed-package proofs as `createSession` (`verify-langgraph-candidate`). +- Optimistic UI already exists in both thread lists. The store must not fight it: the lists keep their own optimistic overrides, and the store refresh is the source of truth. + +## Calls made while writing this (marked so they can be checked) + +- **Same-origin checks are opt-in.** The factory enforces the example's same-origin rule only when given a `browserOrigin`. An injected SDK `client`, cross-origin LangGraph Platform URLs, `LANGGRAPH_CLIENT`, `LANGGRAPH_CLIENT_OPTIONS` (`defaultHeaders`) and the operation reporter keep working, so existing Angular apps do not break. +- **Phase 1 keeps a second copy of the contract and rules inside the Angular packages,** guarded by the type-level spec and the shared conformance suite, rather than holding the Angular sidebar back until phase 2. +- **Each framework watches its own run end.** The Angular sidebar's `agent` input takes the signals-based `Agent` from `@threadplane/chat` and uses the existing `refreshOnRunEnd`. The React sidebar takes a core `AgentSession`. A small neutral helper for `AgentSession` lives beside the directory. +- **The Angular adapter's behaviour does not change.** `refresh()` still logs and resolves, `create()` still returns `null` on failure, and failed mutations still rethrow sanitised errors. Load errors are exposed additively, through a new `status`/`error` signal and the snapshot. Nothing existing starts throwing, so this ships as a patch. +- **The React sidebar does not wait on #1621 or #1622.** It builds on the existing `ThreadList` and `ProjectList`, and adopts `ChatSidenavSections` once that merges. + +## Decided by Brian + +1. **Packaging.** `@threadplane/core` is not published on its own. The Angular packages will export it later in the parity roadmap, so the work ships in the two phases above, and item 12 is deferred to that point. +2. **Project names** live in the LangGraph Store API, with the option to pass your own project store. + +## Left to the builder + +- Exact prop and input names, as long as React and Angular match. +- Whether `refreshOnRunEnd` for directories lives in core or in each binding. +- How the store merges a refresh with in-flight optimistic changes. +- The test matrix: + - contract specs run against the LangGraph directory and a fake; + - sidebar specs in both frameworks; + - one e2e per framework against the cockpit LangGraph backend. From e435d2f301ccede77bde784d1f432167507ed9ac Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 09:29:11 -0800 Subject: [PATCH 02/19] docs(plan): thread sidebar phase 1 implementation plan Co-Authored-By: Claude Opus 5.5 --- .../2026-11-17-thread-sidebar-phase-1.md | 315 ++++++++++++++++++ 1 file changed, 315 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-17-thread-sidebar-phase-1.md diff --git a/docs/superpowers/plans/2026-11-17-thread-sidebar-phase-1.md b/docs/superpowers/plans/2026-11-17-thread-sidebar-phase-1.md new file mode 100644 index 000000000..024979bab --- /dev/null +++ b/docs/superpowers/plans/2026-11-17-thread-sidebar-phase-1.md @@ -0,0 +1,315 @@ +# Thread Sidebar (Phase 1) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship a connected, customizable conversation sidebar in React and Angular, backed by a LangGraph thread store, with project names in the LangGraph Store API. + +**Architecture:** A framework-neutral `ThreadDirectory` contract in `@threadplane/core` and its LangGraph implementation in the private LangGraph runtime feed a React `ThreadSidebar`. Angular gets a structurally identical contract inside `@threadplane/chat`, implemented by a `directory` view on `LangGraphThreadsAdapter`, and a ``. One conformance suite runs against both LangGraph implementations, and a type-level spec pins the two contracts together until phase 2 merges them. + +**Tech Stack:** TypeScript, React 19, Angular 20+ signals, `@langchain/langgraph-sdk` 1.10 (`client.threads`, `client.store`), Vitest, Playwright, Nx. + +**Spec:** `docs/superpowers/specs/2026-11-16-thread-sidebar-design.md` + +## Global Constraints + +- `@threadplane/core` stays private and is not published. Published `@threadplane/chat` and `@threadplane/langgraph` (Angular entry) must not import `@threadplane/core` or anything under `libs/langgraph/src/runtime` at runtime. Type-only imports from runtime inside `libs/langgraph/src/lib` already exist and are allowed; values are not. +- Metadata keys are exactly `title`, `archived`, `pinned`, `pinnedOrder`, `projectId` (unchanged from today's Angular adapter). +- Thread list reads `client.threads.search({ limit: 50, offset: 0 })`. No paging. +- Project store namespace: `['threadplane', 'projects']`; one item per project, key = project id, value `{ name: string }`. +- No change to existing public Angular signatures (`LangGraphThreadsAdapter` methods/signals, `` inputs, `Thread`, `ThreadActionAdapter`). Additions only; ships as a patch. +- `LangGraphThreadsAdapter.refresh()` keeps logging and resolving on failure; `create()` keeps returning `null` on failure. +- New runtime public API is re-exported from `libs/langgraph/src/runtime/create-session.ts` (the candidate's only entry). Runtime files may import only `@threadplane/core`, `@threadplane/core/tools`, `@langchain/langgraph-sdk`. +- SDK mutations use `maxRetries: 0`. Error bodies are never read. Failures surface as `createSafeRequestError()` (`runtime/operation-errors.ts:72`) / the Angular adapter's existing `safeError`. +- Same-origin enforcement only when `browserOrigin` is passed, using the rule in `examples/chat/native/shared/directory.ts:27-36`. +- Never commit `scripts/react-parity/baseline.json`, `apps/website/content/api`, or `package-version.ts` rewrites. Append `dispositions.json` rows as text; never re-serialize it. +- Docs prose: no contractions. Run `npx vitest run` in `apps/website` for docs edits. +- Use `NX_DAEMON=false` for Nx commands. Commits end with `Co-Authored-By: Claude Opus 5.5 `. + +## Review Focus + +1. **A refresh that resolves while a mutation is pending** must not undo the optimistic change on screen. Test in Task 2 (`keeps a pending rename across a refresh that started earlier`). +2. **A LangGraph server without the Store API** (404 on `/store/items/search`) must still list threads; projects become `[]` and project actions reject. Test in Task 3 (`lists threads when the project store is unavailable`). +3. **Removing the active thread** must tell the app, not leave a dangling selection. Tests in Tasks 6 and 7 (`reports the active thread removed`). +4. **Malformed metadata** (blank title, string `pinnedOrder`, `projectId: ''`) must render with fallbacks, never throw. Conformance case in Task 2 (`projects malformed metadata with fallbacks`). +5. **Disposal mid-request** must not notify or write after `dispose()`. Conformance case in Task 2 (`does not notify after dispose`). + +--- + +## File Structure + +| File | Responsibility | +|---|---| +| `libs/core/src/contracts/thread-directory.ts` (create) | `ThreadDirectory` contract types and `refreshDirectoryOnRunEnd` | +| `libs/core/src/index.ts` (modify) | export the above | +| `libs/langgraph/src/runtime/thread-directory.ts` (create) | `createLangGraphThreadDirectory`: list, mutations, optimistic patches, errors | +| `libs/langgraph/src/runtime/thread-metadata.ts` (create) | pure metadata projection + ordering shared by runtime directory | +| `libs/langgraph/src/runtime/project-store.ts` (create) | `ProjectStore` contract and `createLangGraphProjectStore` | +| `libs/langgraph/src/runtime/testing/fake-threads-client.ts` (create) | in-memory fake of `client.threads` + `client.store` | +| `libs/langgraph/src/runtime/testing/thread-directory-conformance.ts` (create) | shared Vitest suite for any `ThreadDirectory` | +| `libs/chat/src/lib/thread-directory/thread-directory.ts` (create) | Angular-side copy of the contract | +| `libs/langgraph/src/lib/threads/thread-directory-contract.type-spec.ts` (create) | mutual-assignability check, core ↔ chat | +| `libs/langgraph/src/lib/threads/threads-adapter.ts` (modify) | `directory` view, `status`/`error` signals, project store | +| `libs/react/src/chat/thread-sidebar.tsx` (create) | React connected sidebar | +| `libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts` (create) | Angular connected sidebar | + +--- + +### Task 1: Core `ThreadDirectory` contract and run-end helper + +**Files:** +- Create: `libs/core/src/contracts/thread-directory.ts` +- Modify: `libs/core/src/index.ts` +- Test: `libs/core/src/contracts/thread-directory.spec.ts` + +**Interfaces:** +- Produces (exported from `@threadplane/core`): +```ts +export type ThreadDirectoryStatus = 'idle' | 'loading' | 'error'; +export interface ThreadEntry { readonly id: string; readonly title: string; readonly updatedAt?: number; + readonly pinned: boolean; readonly archived: boolean; readonly projectId: string | null; } +export interface ProjectEntry { readonly id: string; readonly name: string; } +export interface ThreadDirectorySnapshot { readonly threads: readonly ThreadEntry[]; readonly archived: readonly ThreadEntry[]; + readonly projects?: readonly ProjectEntry[]; readonly status: ThreadDirectoryStatus; readonly error?: AgentError; } +export interface ThreadDirectory { + getSnapshot(): ThreadDirectorySnapshot; subscribe(notify: () => void): () => void; + refresh(options?: { readonly signal?: AbortSignal }): Promise; + create?(options?: { readonly metadata?: { readonly [key: string]: PlainValue }; readonly signal?: AbortSignal }): Promise<{ readonly id: string }>; + rename?(id: string, title: string): Promise; remove?(id: string): Promise; + setArchived?(id: string, archived: boolean): Promise; setPinned?(id: string, pinned: boolean): Promise; + reorderPinned?(id: string, beforeId: string | null): Promise; setProject?(id: string, projectId: string | null): Promise; + createProject?(name: string): Promise<{ readonly id: string }>; renameProject?(id: string, name: string): Promise; + removeProject?(id: string): Promise; dispose(): void; +} +export function refreshDirectoryOnRunEnd(directory: Pick, + session: Pick): () => void; +``` +(`title` is always a string — the implementation applies the fallback — so views never branch on it.) + +- [ ] **Step 1: Write failing tests** in `thread-directory.spec.ts`: + - `refreshes once when the session leaves running`: fake session (use `createFakeAgentSession` from `../testing`) goes `idle → running → idle`; `refresh` spy called exactly 1 time. + - `refreshes after a run that ends in error`: `running → error` → 1 call. + - `does not refresh on idle → idle notifications`: 0 calls. + - `stops after release`: call the returned release, then `running → idle` → 0 calls. +- [ ] **Step 2:** `NX_DAEMON=false npx nx test core` → FAIL (module not found). +- [ ] **Step 3: Implement** the types and `refreshDirectoryOnRunEnd` (subscribe, remember the last status, call `void directory.refresh()` on a transition out of `'running'`); export all from `src/index.ts`. +- [ ] **Step 4:** `NX_DAEMON=false npx nx run-many -t test lint type-tests -p core` → PASS. +- [ ] **Step 5: Commit** `feat(core): add the ThreadDirectory contract`. + +--- + +### Task 2: LangGraph runtime directory and the conformance suite + +**Files:** +- Create: `libs/langgraph/src/runtime/thread-metadata.ts`, `thread-directory.ts`, `testing/fake-threads-client.ts`, `testing/thread-directory-conformance.ts` +- Modify: `libs/langgraph/src/runtime/create-session.ts` (re-export) +- Test: `libs/langgraph/src/runtime/thread-directory.spec.ts`, `thread-metadata.spec.ts` + +**Interfaces:** +- Consumes: Task 1 types. +- Produces: +```ts +// thread-metadata.ts +export function projectThread(raw: { thread_id: string; updated_at?: string; metadata?: unknown }, + titleFallback: string): ThreadEntry & { readonly pinnedOrder?: number }; +export function orderThreads(entries: readonly (ThreadEntry & { pinnedOrder?: number })[]): + { threads: ThreadEntry[]; archived: ThreadEntry[] }; +// thread-directory.ts +export interface LangGraphThreadDirectoryOptions { + readonly apiUrl?: string; readonly client?: LangGraphThreadsClient; readonly clientOptions?: LangGraphClientOptions; + readonly browserOrigin?: string; readonly titleFallback?: string; // default 'New chat' + readonly projects?: ProjectStore | false; // default: createLangGraphProjectStore(client) (Task 3) +} +export type LangGraphThreadsClient = Pick; +export function createLangGraphThreadDirectory(options: LangGraphThreadDirectoryOptions): ThreadDirectory; +// testing/fake-threads-client.ts +export function createFakeThreadsClient(seed?: readonly FakeThread[]): LangGraphThreadsClient & { + readonly calls: readonly string[]; failNext(method: string, status: number): void; hold(method: string): () => void; }; +// testing/thread-directory-conformance.ts +export function describeThreadDirectoryConformance(name: string, + make: (client: LangGraphThreadsClient) => { directory: ThreadDirectory; teardown?(): void }): void; +``` +- `projectThread` rules (copy of `examples/chat/native/shared/projection.ts:4-22` and the Angular adapter): trimmed non-empty string `title` else fallback; `archived`/`pinned` only `=== true`; `pinnedOrder` only finite number; `projectId` non-blank string else `null`; `updatedAt = Date.parse(updated_at)` when finite. +- `orderThreads`: active threads pinned first by `pinnedOrder` ascending (missing order last, then `updatedAt` desc), then unpinned by `updatedAt` desc; archived by `updatedAt` desc. Match `threads-adapter.ts` today; if they differ, the adapter's current order wins. + +- [ ] **Step 1: Write the conformance suite** with these cases (each builds a fresh fake client and calls `make`): + - `lists active and archived threads in pin order` — seed 4 threads (two pinned with `pinnedOrder` 1 and 0, one archived); after `refresh()`, `threads.map(t => t.id)` equals the pinned-0, pinned-1, then newest unpinned; `archived` has the archived one; `status === 'idle'`. + - `projects malformed metadata with fallbacks` — `{ title: ' ', pinnedOrder: '2', projectId: '', archived: 'yes' }` → `title === 'New chat'`, `pinned === false`, `archived === false`, `projectId === null`. + - `exposes a load error and clears it on success` — `failNext('threads.search', 500)`; `refresh()` resolves; `status === 'error'`, `error.kind === 'server'`, `error.recovery === 'retry'`; second `refresh()` → `status === 'idle'`, `error === undefined`. + - `renames optimistically and confirms with a refresh` — `hold('threads.update')`; call `rename('a', 'Trip')`; snapshot shows `Trip` before release; after release, `calls` includes a later `threads.search`. + - `rolls back a failed rename and rejects` — `failNext('threads.update', 500)`; `rename` rejects with an `Error` whose message is `'The LangGraph request failed.'`; title is the original. + - `keeps a pending rename across a refresh that started earlier` — start `refresh()` with `threads.search` held, call `rename('a','Trip')` with update held, release search: title still `Trip`. + - `archives, pins and reorders with the existing metadata keys` — after `setArchived('a', true)`, `setPinned('b', true)`, `reorderPinned('c', 'b')`, the fake's stored metadata has `archived: true`, `pinned: true`, and `pinnedOrder` 0..n in the new order. + - `removes a thread` — `remove('a')` → gone from snapshot and from the fake. + - `creates a thread with metadata` — `create({ metadata: { projectId: 'p1' } })` resolves `{ id }` present in the next snapshot with `projectId === 'p1'`. + - `does not notify after dispose` — subscribe a spy, hold search, `refresh()`, `dispose()`, release → spy not called after dispose. +- [ ] **Step 2: Write `thread-directory.spec.ts`** that calls `describeThreadDirectoryConformance('runtime', client => ({ directory: createLangGraphThreadDirectory({ client, projects: false }) }))`, plus: + - `rejects a cross-origin apiUrl when browserOrigin is set` — `apiUrl: 'https://other.test'`, `browserOrigin: 'https://app.test'` → throws `'Directory requires an absolute same-origin API base'`. + - `accepts a cross-origin apiUrl without browserOrigin`. + And `thread-metadata.spec.ts` for the projection rules above. +- [ ] **Step 3:** `NX_DAEMON=false npx nx runtime-quality langgraph` → FAIL. +- [ ] **Step 4: Implement.** Build the client with the existing `createLangGraphClient(apiUrl, { ...clientOptions, maxRetries: 0 })` when no `client` is given. Keep a map of pending optimistic patches keyed by thread id; each refresh applies remaining patches over the server list; a patch is removed when its mutation settles. Map load failures to `AgentError` via the existing `projectLangGraphOperationFailure`; reject mutations with `createSafeRequestError()`. Freeze snapshots and keep unchanged entries by reference. Re-export `createLangGraphThreadDirectory`, `LangGraphThreadDirectoryOptions`, `LangGraphThreadsClient` from `create-session.ts`. +- [ ] **Step 5:** `NX_DAEMON=false npx nx run-many -t runtime-quality runtime-type-tests lint -p langgraph` → PASS. Then `TMPDIR=$(cd "$TMPDIR" && pwd -P) node scripts/react-parity/verify-langgraph-candidate.mjs` → PASS (the new files are reached from the entry and import only allowed specifiers). +- [ ] **Step 6: Commit** `feat(langgraph): add a framework-neutral LangGraph thread directory`. + +--- + +### Task 3: LangGraph Store project store + +**Files:** +- Create: `libs/langgraph/src/runtime/project-store.ts` +- Modify: `thread-directory.ts`, `testing/fake-threads-client.ts` (store methods), `testing/thread-directory-conformance.ts`, `create-session.ts` +- Test: `libs/langgraph/src/runtime/project-store.spec.ts` + +**Interfaces:** +- Produces: +```ts +export interface ProjectStore { + list(signal?: AbortSignal): Promise; + create(name: string): Promise<{ readonly id: string }>; + rename(id: string, name: string): Promise; + remove(id: string): Promise; +} +export function createLangGraphProjectStore(client: Pick, + options?: { readonly namespace?: readonly string[] }): ProjectStore; // default ['threadplane','projects'] +``` +- `list` uses `store.searchItems(namespace, { limit: 100 })`, sorted by name (locale compare). `create` uses `crypto.randomUUID()` for the key and `putItem(namespace, id, { name })`. Names are trimmed; blank names reject with `Error('Project name is required')`. +- Directory: `projects` in the snapshot is the store list (absent when `projects: false`). `removeProject(id)` first `setProject(t, null)` for each thread with that project, then `store.remove(id)`. + +- [ ] **Step 1: Failing tests** in `project-store.spec.ts`: `creates, lists, renames and removes under the default namespace` (fake records `putItem` namespace `['threadplane','projects']`, value `{ name: 'Trips' }`); `rejects a blank name`. Add conformance cases (run only when the subject has projects): `moves threads out of a removed project` (thread with `projectId: 'p1'` → `null`, then project gone); `lists threads when the project store is unavailable` (`failNext('store.searchItems', 404)` → `status === 'idle'`, `projects` equals `[]`, `createProject` rejects). +- [ ] **Step 2:** run `runtime-quality` → FAIL. +- [ ] **Step 3: Implement**; directory loads threads and projects in parallel and a project failure never sets `status: 'error'`. +- [ ] **Step 4:** `NX_DAEMON=false npx nx run-many -t runtime-quality runtime-type-tests lint -p langgraph` and `verify-langgraph-candidate.mjs` → PASS. +- [ ] **Step 5: Commit** `feat(langgraph): store project names with the LangGraph Store API`. + +--- + +### Task 4: Angular contract in `@threadplane/chat` and the contract type spec + +**Files:** +- Create: `libs/chat/src/lib/thread-directory/thread-directory.ts` +- Modify: `libs/chat/src/public-api.ts` +- Test: `libs/langgraph/src/lib/threads/thread-directory-contract.type-spec.ts` + +**Interfaces:** +- Produces (exported from `@threadplane/chat`, types only): `ThreadDirectory`, `ThreadDirectorySnapshot`, `ThreadDirectoryStatus`, `ThreadEntry`, `ProjectEntry`, `ThreadDirectoryError` — field-for-field copies of Task 1. `ThreadDirectoryError` copies `AgentError` (`kind: 'connection'|'auth'|'server'|'interrupted'|'aborted'; message; status?; retryable; recovery?: 'retry'|'check'|'none'; detail?`). The `create` metadata type is `{ readonly [key: string]: unknown }`. Header comment: "Phase 1 copy of `ThreadDirectory` from `@threadplane/core`; replaced by a re-export when the Angular packages export core." + +- [ ] **Step 1: Write the type spec** with `type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false;` and `const _x: Equal = true;` for `ThreadEntry`, `ProjectEntry`, `ThreadDirectoryStatus`, `ThreadDirectorySnapshot`, and mutual assignability (`A extends B` and `B extends A`) for `ThreadDirectory` (metadata types differ only in `PlainValue` vs `unknown`, which assignability tolerates in the core → chat direction; assert `Core.ThreadDirectory extends Chat.ThreadDirectory` and `Equal` on every other member via `Omit<…, 'create'>`). +- [ ] **Step 2:** `NX_DAEMON=false npx nx type-tests langgraph` → FAIL (chat types missing). +- [ ] **Step 3: Implement** the chat file and export it from `public-api.ts` next to the thread-list exports (lines 88-91). +- [ ] **Step 4:** `NX_DAEMON=false npx nx type-tests langgraph` → PASS; temporarily rename one field in the chat copy and confirm it FAILS, then restore (do this by editing, not `git checkout`). +- [ ] **Step 5: Commit** `feat(chat): add the ThreadDirectory contract for Angular`. + +--- + +### Task 5: `LangGraphThreadsAdapter` directory view, errors and projects + +**Files:** +- Modify: `libs/langgraph/src/lib/threads/threads-adapter.ts`, `libs/langgraph/src/public-api.ts` +- Test: `libs/langgraph/src/lib/threads/threads-adapter.spec.ts`, create `threads-adapter-conformance.spec.ts` + +**Interfaces:** +- Consumes: Task 4 `ThreadDirectory` (from `@threadplane/chat`), Task 2 `describeThreadDirectoryConformance` and `createFakeThreadsClient` (test-only import from `../../runtime/testing/...`). +- Produces on `LangGraphThreadsAdapter` (additions only): + - `readonly status: Signal`, `readonly error: Signal`, `readonly projects: Signal` + - `readonly directory: ThreadDirectory` — a view over the adapter: `create` maps `null` to a rejection; `remove`→`delete`, `setArchived`→`archive`/`unarchive`, `setPinned`→`pin`/`unpin`, `setProject`→`moveToProject`; `subscribe` keeps a listener set that the adapter notifies wherever it writes `threads`, `archivedThreads`, `projects`, `status` or `error` (no `effect`, so it works outside an injection context); `getSnapshot` returns a frozen snapshot rebuilt only when one of those writes happens. + - `LangGraphThreadsConfig.projects?: false | { namespace?: readonly string[] }` (default on). Project storage is a private Angular-side copy of Task 3's logic, same namespace and value shape. + +- [ ] **Step 1: Failing tests:** `threads-adapter-conformance.spec.ts` runs `describeThreadDirectoryConformance('angular adapter', client => …)` providing `LANGGRAPH_CLIENT` = fake via `TestBed`; plus in `threads-adapter.spec.ts`: `sets status error and keeps refresh resolving on failure`; `keeps create returning null on failure`. +- [ ] **Step 2:** `NX_DAEMON=false npx nx test langgraph` → FAIL. +- [ ] **Step 3: Implement.** Add the optimistic-patch map (same algorithm as Task 2) so the conformance cases pass; existing method behavior is unchanged. +- [ ] **Step 4:** `NX_DAEMON=false npx nx run-many -t test lint type-tests build -p langgraph` → PASS. Confirm the built `dist` Angular entry contains no `@threadplane/core` import: `grep -r "@threadplane/core" dist/libs/langgraph/fesm2022` → no output. +- [ ] **Step 5: Commit** `feat(langgraph): expose LangGraphThreadsAdapter as a ThreadDirectory with project names`. + +--- + +### Task 6: React `ThreadSidebar` + +**Files:** +- Create: `libs/react/src/chat/thread-sidebar.tsx` +- Modify: `libs/react/src/chat/index.ts`, `libs/react/src/chat/styles.css`, `scripts/react-parity/verify-packages.mjs` (line 468 `'react/chat'` list), `scripts/react-parity/verify-packages.spec.mjs` (`supported` literal near line 1043), `scripts/react-parity/dispositions.json` (append rows) +- Test: `libs/react/src/chat/thread-sidebar.spec.tsx` + +**Interfaces:** +- Consumes: Task 1 contract + `refreshDirectoryOnRunEnd`; existing `ChatSidenavSections`, `ThreadList`, `ProjectList`. +- Produces: +```ts +export interface ThreadSidebarFeatures { readonly projects?: boolean; readonly archive?: boolean; readonly pin?: boolean; + readonly reorder?: boolean; readonly rename?: boolean; readonly remove?: boolean; } // all default true when the directory supports them +export interface ThreadSidebarProps { + readonly directory: ThreadDirectory; readonly session?: Pick; + readonly activeThreadId?: string | null; readonly onSelect: (threadId: string) => void; + readonly onNewChat?: () => void; readonly onActiveRemoved?: () => void; + readonly selectedProjectId?: string | null; readonly onProjectSelect?: (projectId: string | null) => void; + readonly features?: ThreadSidebarFeatures; readonly renderThread?: ThreadListProps['renderItem']; + readonly extraActions?: ThreadListProps['extraActions']; readonly before?: ReactNode; readonly after?: ReactNode; + readonly labels?: Partial>; + readonly className?: string; +} +export function ThreadSidebar(props: ThreadSidebarProps): JSX.Element; +``` +If `ThreadList` has no `renderItem`/`extraActions` props today, add them to `ThreadList` in this task (row override receives the `ThreadListItem` and the default row node; extra actions are `{ id; label; run(threadId) }[]` appended to the row menu) and test them in `thread-list.spec.tsx`. +- Default `onNewChat`: `directory.create?.()` then `onSelect(id)`. + +- [ ] **Step 1: Failing tests** (use a hand-written fake `ThreadDirectory` in the spec): + - `lists threads from the directory and refreshes on mount` (refresh called once). + - `hides menu actions the directory lacks` — fake without `remove` → no "Delete" menu item. + - `turns built-ins off with features` — `features={{ projects: false }}` → no Projects section even when `projects` is present. + - `shows the load error and retries` — snapshot `status: 'error'` → `role="alert"` with label `loadError`; clicking Retry calls `refresh`. + - `refreshes after a run ends` — fake session `running → idle` → refresh called a second time. + - `reports the active thread removed` — delete the active row → `onActiveRemoved` called once. + - `renders before and after sections and a custom row`. +- [ ] **Step 2:** `NX_DAEMON=false npx nx test react` → FAIL. +- [ ] **Step 3: Implement** with `useSyncExternalStore(directory.subscribe, directory.getSnapshot)`, composing `ChatSidenavSections`; derive the `ThreadActionAdapter`/`ProjectActionAdapter` from the directory's present methods and `features`. Add `ThreadSidebar` and its types to `index.ts`, the allowlist and spec, and append dispositions rows (`export:libs/react/src/chat/index.ts#ThreadSidebar`, `source:libs/react/src/chat/thread-sidebar.tsx`, `treatment: "react"`, `status: "in-progress"`, `taskIds` following the `ChatSidenavSections` row). +- [ ] **Step 4:** `NX_DAEMON=false npx nx run-many -t test lint -p react`, `node --test scripts/react-parity/verify-packages.spec.mjs`, `node scripts/react-parity/inventory.mjs --check --drift warn` → PASS. +- [ ] **Step 5: Commit** `feat(react): add a connected ThreadSidebar`. + +--- + +### Task 7: Angular `` + +**Files:** +- Create: `libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts`, `.spec.ts` +- Modify: `libs/chat/src/public-api.ts`; `chat-thread-list.component.ts` only if row-template / extra-action inputs are missing + +**Interfaces:** +- Consumes: Task 4 contract; `Agent` from `libs/chat/src/lib/agent/agent.ts` (`status: Signal`). +- Produces: `ChatThreadSidebarComponent`, selector `chat-thread-sidebar`, inputs `directory` (required), `agent?`, `activeThreadId?`, `selectedProjectId?`, `features?: ThreadSidebarFeatures` (same shape as React, declared in this file), `extraActions?`, `labels?`; outputs `threadSelected: string`, `newChat: void`, `projectSelected: string | null`, `activeThreadRemoved: void`; content: `ng-template[chatThreadRow]` (context `$implicit: Thread`), `[chatThreadSidebarBefore]`, `[chatThreadSidebarAfter]`. +- Run-end refresh: an `effect` on `agent()?.status()` that calls `directory().refresh()` on a transition out of `'running'` (same logic as `refresh-on.ts:21-27`, written locally; chat must not import langgraph). +- Default `newChat` when nothing listens: `directory.create?.()` then emit `threadSelected(id)`. + +- [ ] **Step 1: Failing tests** mirroring Task 6 one-for-one (same names), using a signal-backed fake directory and a fake `Agent`. +- [ ] **Step 2:** `NX_DAEMON=false npx nx test chat` → FAIL. +- [ ] **Step 3: Implement** by composing ``, `` and the archived section the way `` does; read the directory with a `signal` updated from `directory.subscribe` and released on destroy. Export from `public-api.ts` next to `ChatSidenavComponent` (line 133). +- [ ] **Step 4:** `NX_DAEMON=false npx nx run-many -t test lint build -p chat` → PASS; `grep -r "@threadplane/core\|@threadplane/langgraph" dist/libs/chat/fesm2022` → no output. +- [ ] **Step 5: Commit** `feat(chat): add a connected chat-thread-sidebar`. + +--- + +### Task 8: Cockpit wiring and end-to-end coverage + +**Files:** +- Modify: `cockpit/chat/threads/angular/src/…` (replace the hand-wired thread list with ``), `cockpit/chat/threads/angular/e2e/c-threads.spec.ts` +- Modify: `cockpit/chat/threads/react/src/…` (replace the `
{ function setup() { let serial = 0; const creations: ReturnType>[] = [], - sessions: ReturnType[] = [], - titles: { - id: string; - signal: AbortSignal; - result: ReturnType>; - }[] = []; + sessions: ReturnType[] = []; const savedStates = new Map(); function makeSession(id: string) { let state: ThreadsState = { @@ -88,15 +83,9 @@ function setup() { sessions.push(selected); return selected.session; }); - const readTitle = vi.fn((id: string, signal: AbortSignal) => { - const result = deferred(); - titles.push({ id, signal, result }); - return result.promise; - }); const app = createThreadsApplication({ createThread, sessionFactory, - readTitle, }); applications.push(app); async function start(text: string, id?: string) { @@ -178,10 +167,8 @@ function setup() { app, creations, sessions, - titles, createThread, sessionFactory, - readTitle, start, confirm, send, @@ -207,7 +194,6 @@ it('keeps mount, blank Send and New free of remote work', async () => { expect(h.app.getSnapshot().selectedKey).not.toBe(initial.selectedKey); expect(h.createThread).not.toHaveBeenCalled(); expect(h.sessionFactory).not.toHaveBeenCalled(); - expect(h.readTitle).not.toHaveBeenCalled(); }); it('clears only the accepted draft synchronously and preserves text typed during creation', async () => { const h = setup(), @@ -248,7 +234,6 @@ it('waits for canonical history and does not clear newly typed text on completio outcome: 'success', busy: false, }); - expect(h.titles).toHaveLength(1); }); it('restores A/B/A through fresh sessions and preserves independent drafts and prefixes', async () => { const h = setup(); @@ -299,31 +284,6 @@ it('cannot treat a fulfilled empty selection load as saved authority', async () await h.app.submit('Replay'); expect(current.runs).toHaveLength(0); }); -it('keeps title requests nonblocking and ignores a late title after New', async () => { - const h = setup(); - await h.send('A question', 'A'); - const key = h.app.getSnapshot().selectedKey; - expect(h.app.getSnapshot().canSubmit).toBe(true); - expect(h.titles).toHaveLength(1); - await h.app.newConversation(); - expect(h.titles[0].signal.aborted).toBe(true); - h.titles[0].result.resolve({ thread_id: 'A', metadata: { title: 'Late' } }); - await tick(); - expect( - h.app.getSnapshot().conversations.find((c) => c.key === key)?.label - ).toBe('Conversation 1'); -}); -it('applies a literal current title without changing continuation authority', async () => { - const h = setup(); - await h.send('Question', 'A'); - h.titles[0].result.resolve({ - thread_id: 'A', - metadata: { title: ' Literal ' }, - }); - await tick(); - expect(h.app.getSnapshot().conversations[0].label).toBe('Literal'); - expect(h.app.getSnapshot().canSubmit).toBe(true); -}); it('detaches Stop during creation and never dispatches the late confirmed ID', async () => { const h = setup(), pending = h.app.submit('Question'); @@ -490,51 +450,6 @@ it('bounds a never-settling Stop and disposal, releasing observation immediately h.confirm(turn.current); await turn.pending; }); -it('cancels optional title reads after five seconds without blocking the saved conversation', async () => { - vi.useFakeTimers(); - const h = setup(); - await h.send('Question', 'A'); - expect(h.app.getSnapshot().canSubmit).toBe(true); - await vi.advanceTimersByTimeAsync(5000); - expect(h.titles[0].signal.aborted).toBe(true); - h.titles[0].result.resolve({ - thread_id: 'A', - metadata: { title: 'Too late' }, - }); - await tick(); - expect(h.app.getSnapshot().conversations[0].label).toBe('Conversation 1'); - expect(h.app.getSnapshot().canSubmit).toBe(true); -}); -it.each([ - undefined, - { thread_id: 'B', metadata: { title: 'Foreign' } }, - { thread_id: 'A', metadata: { title: 42 } }, - { thread_id: 'A', metadata: { title: '' } }, -])('ignores optional malformed metadata %#', async (raw) => { - const h = setup(); - await h.send('Question', 'A'); - h.titles[0].result.resolve(raw); - await tick(); - expect(h.app.getSnapshot().canSubmit).toBe(true); - expect(h.app.getSnapshot().conversations[0].label).toBe('Conversation 1'); -}); -it('fences cancellation triggered during metadata capture', async () => { - const h = setup(); - await h.send('Question', 'A'); - const raw = new Proxy( - { thread_id: 'A', metadata: { title: 'Cancelled' } }, - { - ownKeys(target) { - void h.app.stop(); - return Reflect.ownKeys(target); - }, - } - ); - h.titles[0].result.resolve(raw); - await tick(); - expect(h.app.getSnapshot().conversations[0].label).toBe('Conversation 1'); - expect(h.app.getSnapshot().canSubmit).toBe(true); -}); it('fences Stop triggered during canonical data capture', async () => { const h = setup(), turn = await h.start('Question', 'A'); @@ -552,15 +467,6 @@ it('fences Stop triggered during canonical data capture', async () => { expect(h.app.getSnapshot().canSubmit).toBe(false); expect(h.app.getSnapshot().confirmation).toBeNull(); }); -it('keeps failed optional metadata separate from saved authority', async () => { - const h = setup(); - await h.send('Question', 'A'); - h.titles[0].result.reject(new Error('PRIVATE metadata failure')); - await tick(); - expect(h.app.getSnapshot().canSubmit).toBe(true); - expect(h.app.getSnapshot().error).toBeNull(); -}); - it.each([ 'tools', 'children', @@ -706,34 +612,6 @@ it('ignores unknown and already selected keys without additional history reads', expect(h.sessionFactory).toHaveBeenCalledTimes(1); expect(h.sessions[0].loads).toHaveLength(1); }); -it('preserves the last valid title when a later optional read fails', async () => { - const h = setup(); - await h.send('Question', 'A'); - h.titles[0].result.resolve({ - thread_id: 'A', - metadata: { title: 'First title' }, - }); - await tick(); - await h.send('Follow up'); - h.titles[1].result.reject(new Error('PRIVATE metadata')); - await tick(); - expect(h.app.getSnapshot().conversations[0].label).toBe('First title'); - expect(h.app.getSnapshot().canSubmit).toBe(true); -}); -it('cancels a prior title read on a new explicit turn', async () => { - const h = setup(); - await h.send('Question', 'A'); - await h.send('Follow up'); - expect(h.titles[0].signal.aborted).toBe(true); - h.titles[0].result.resolve({ thread_id: 'A', metadata: { title: 'Stale' } }); - h.titles[1].result.resolve({ - thread_id: 'A', - metadata: { title: 'Current' }, - }); - await tick(); - expect(h.app.getSnapshot().conversations[0].label).toBe('Current'); -}); - it.each(['pending', 'foreign', 'changed-checkpoint', 'generation'])( 'quarantines conflicting idle %s evidence before another submit', async (mode) => { diff --git a/cockpit/chat/threads/react/src/application.ts b/cockpit/chat/threads/react/src/application.ts index 180a54132..07e7f7731 100644 --- a/cockpit/chat/threads/react/src/application.ts +++ b/cockpit/chat/threads/react/src/application.ts @@ -31,7 +31,6 @@ import { messageKey, type ThreadsState, } from './authority'; -import { decodeTitle } from './titles'; /** Own page-local records and one selected session; only matching saved evidence permits continuation. */ export function createThreadsApplication(options: ThreadsClient) { @@ -53,20 +52,12 @@ export function createThreadsApplication(options: ThreadsClient) { selecting: boolean; turn?: Turn; }; - type TitleRead = { - key: string; - version: number; - view: number; - controller: AbortController; - timer: ReturnType; - }; const records = new ConversationRecords(), listeners = new Set<() => void>(), cleanups = new Set>(); let key = records.create().key, owner: Owner | undefined, - operation: AbortController | undefined, - titleRead: TitleRead | undefined; + operation: AbortController | undefined; let disposed = false, disposal: Promise | undefined; let snapshot: ThreadsSnapshot = Object.freeze({ @@ -138,71 +129,6 @@ export function createThreadsApplication(options: ThreadsClient) { owner = undefined; return previous ? close(previous) : Promise.resolve(); } - function cancelTitle() { - const previous = titleRead; - titleRead = undefined; - if (records.get(key)) records.invalidate(key); - if (previous) { - clearTimeout(previous.timer); - previous.controller.abort(); - } - } - function startTitle(selected: Owner) { - const record = records.get(selected.key); - if ( - disposed || - owner !== selected || - selected.closed || - snapshot.busy || - !snapshot.canSubmit || - !record?.threadId || - record.availability !== 'available' - ) - return; - const controller = new AbortController(), - version = records.invalidate(selected.key), - view = snapshot.viewGeneration; - const pending: TitleRead = { - key: selected.key, - version, - view, - controller, - timer: setTimeout(() => { - if (titleRead === pending) { - titleRead = undefined; - controller.abort(); - } - }, 5000), - }; - titleRead = pending; - const current = () => - !disposed && - titleRead === pending && - !controller.signal.aborted && - owner === selected && - !selected.closed && - key === pending.key && - snapshot.viewGeneration === view && - records.get(key)?.version === version; - void Promise.resolve() - .then(async () => { - if (!current()) return; - const raw = await options.readTitle( - record.threadId as string, - controller.signal - ); - if (!current()) return; - const title = decodeTitle(raw, record.threadId as string); - if (!current()) return; - if (title !== undefined && records.setTitle(key, title, version)) - publish(); - }) - .catch(() => undefined) - .finally(() => { - clearTimeout(pending.timer); - if (titleRead === pending) titleRead = undefined; - }); - } function block(selected?: Owner) { if (selected) selected.unsafe = true; records.markUnavailable(key); @@ -392,7 +318,6 @@ export function createThreadsApplication(options: ThreadsClient) { outcome: null, confirmation: null, }); - if (current()) cancelTitle(); return { admitted, current }; } function finish(admitted: AbortController) { @@ -412,7 +337,6 @@ export function createThreadsApplication(options: ThreadsClient) { return; records.setDraft(key, ''); const { admitted, current } = admit(owner ? 'running' : 'creating'); - let succeeded: Owner | undefined; try { if (!current()) return; if (!owner) { @@ -489,12 +413,10 @@ export function createThreadsApplication(options: ThreadsClient) { records.confirm(key, canonical, turn.generation); selected.turn = undefined; publish({ canSubmit: true, outcome: 'success', confirmation: 'saved' }); - if (valid()) succeeded = selected; } catch { if (current()) block(owner); } finally { finish(admitted); - if (succeeded) startTitle(succeeded); } } async function select(nextKey: string) { @@ -509,7 +431,6 @@ export function createThreadsApplication(options: ThreadsClient) { ) return; const { admitted, current } = admit('loading'); - let succeeded: Owner | undefined; try { if (!current()) return; const cleanup = detach(); @@ -545,12 +466,10 @@ export function createThreadsApplication(options: ThreadsClient) { } selected.selecting = false; publish({ canSubmit: true, outcome: 'success', confirmation: 'loaded' }); - if (valid()) succeeded = selected; } catch { if (current()) block(owner); } finally { finish(admitted); - if (succeeded) startTitle(succeeded); } } async function newConversation() { @@ -578,14 +497,10 @@ export function createThreadsApplication(options: ThreadsClient) { async function stop() { if (disposed) return; const previous = operation; - if (!previous) { - cancelTitle(); - return; - } + if (!previous) return; const stopped = new AbortController(); operation = stopped; previous.abort(); - cancelTitle(); const selected = owner, cleanup = detach(); records.markUnavailable(key); @@ -618,7 +533,6 @@ export function createThreadsApplication(options: ThreadsClient) { const previous = operation; operation = undefined; previous?.abort(); - cancelTitle(); void detach(); listeners.clear(); disposal = Promise.all([...cleanups]).then(() => undefined); diff --git a/cockpit/chat/threads/react/src/connection.spec.ts b/cockpit/chat/threads/react/src/connection.spec.ts index bd280d832..67ba49080 100644 --- a/cockpit/chat/threads/react/src/connection.spec.ts +++ b/cockpit/chat/threads/react/src/connection.spec.ts @@ -1,10 +1,15 @@ import { beforeEach, expect, it, vi } from 'vitest'; -import { createThreadsClient, threadsConnection } from './connection'; +import { + createThreadsClient, + createThreadsDirectory, + threadsConnection, +} from './connection'; const mocks = vi.hoisted(() => ({ create: vi.fn(), get: vi.fn(), session: vi.fn(), client: vi.fn(), + directory: vi.fn(), })); vi.mock('@langchain/langgraph-sdk', () => ({ Client: class { @@ -14,7 +19,10 @@ vi.mock('@langchain/langgraph-sdk', () => ({ } }, })); -vi.mock('@threadplane/langgraph', () => ({ createSession: mocks.session })); +vi.mock('@threadplane/langgraph', () => ({ + createSession: mocks.session, + createLangGraphThreadDirectory: mocks.directory, +})); const configuration = { apiUrl: 'https://developer.test', headers: { 'x-api-key': 'fictional' }, @@ -141,39 +149,18 @@ it('disposes a rejected session and returns a generic diagnostic', async () => { ); expect(bad.dispose).toHaveBeenCalledTimes(1); }); -it('reads optional metadata only for known confirmed IDs with the caller signal', async () => { - const client = createThreadsClient(configuration), - signal = new AbortController().signal; - expect(await client.readTitle('unknown', signal)).toBeUndefined(); - expect(mocks.get).not.toHaveBeenCalled(); - const id = await client.createThread(signal), - raw = { thread_id: id, metadata: { title: 'Literal' } }; - mocks.get.mockResolvedValue(raw); - expect(await client.readTitle(id, signal)).toEqual(raw); - expect(mocks.get).toHaveBeenCalledWith(id, { signal }); - expect(mocks.get).toHaveBeenCalledTimes(1); -}); -it('ignores failed, aborted and late metadata without retrying', async () => { - const client = createThreadsClient(configuration), - signal = new AbortController().signal, - id = await client.createThread(signal); - mocks.get.mockRejectedValue(new Error('PRIVATE fictional')); - expect(await client.readTitle(id, signal)).toBeUndefined(); - const aborted = new AbortController(); - aborted.abort(); - expect(await client.readTitle(id, aborted.signal)).toBeUndefined(); - expect(mocks.get).toHaveBeenCalledTimes(1); - let resolve!: (value: unknown) => void; - mocks.get.mockImplementation( - () => - new Promise((r) => { - resolve = r; - }) - ); - const controller = new AbortController(), - pending = client.readTitle(id, controller.signal); - controller.abort(); - resolve({ thread_id: id, metadata: { title: 'Late' } }); - expect(await pending).toBeUndefined(); - expect(mocks.get).toHaveBeenCalledTimes(2); +it('builds the sidebar directory on the same target, headers and no retries', () => { + const directory = { dispose: vi.fn() }; + mocks.directory.mockReturnValue(directory); + expect(createThreadsDirectory(configuration)).toBe(directory); + expect(mocks.client).toHaveBeenCalledWith({ + apiUrl: configuration.apiUrl, + apiKey: null, + defaultHeaders: configuration.headers, + callerOptions: { maxRetries: 0 }, + }); + const [options] = mocks.directory.mock.calls[0]; + expect(options).toMatchObject({ titleFallback: 'Untitled conversation' }); + expect(options.client.threads.create).toBe(mocks.create); + expect(mocks.create).not.toHaveBeenCalled(); }); diff --git a/cockpit/chat/threads/react/src/connection.ts b/cockpit/chat/threads/react/src/connection.ts index 792bf1b60..dad48b070 100644 --- a/cockpit/chat/threads/react/src/connection.ts +++ b/cockpit/chat/threads/react/src/connection.ts @@ -18,7 +18,6 @@ export interface ThreadsConnection { export interface ThreadsClient { createThread(signal: AbortSignal): Promise; sessionFactory(threadId: string): ThreadsSession; - readTitle(threadId: string, signal: AbortSignal): Promise; } /** Resolve the shared proxy or the explicitly authored developer target. */ export function threadsConnection(configuration: RuntimeBridgeConfiguration): { @@ -111,15 +110,6 @@ export function createThreadsClient( throw new Error('Runtime session is unavailable.'); } }, - async readTitle(threadId, signal) { - if (!known.has(threadId) || signal.aborted) return undefined; - try { - const raw = await client.threads.get(threadId, { signal }); - return signal.aborted ? undefined : raw; - } catch { - return undefined; - } - }, }; } /** diff --git a/cockpit/chat/threads/react/src/records.spec.ts b/cockpit/chat/threads/react/src/records.spec.ts index f3fe47872..788594025 100644 --- a/cockpit/chat/threads/react/src/records.spec.ts +++ b/cockpit/chat/threads/react/src/records.spec.ts @@ -88,12 +88,12 @@ describe('page-owned conversation records', () => { key: a.key, threadId: 'thread-a', draft: 'draft', - label: 'Conversation 1', + ordinal: 1, }); expect(records.list()).toHaveLength(1); expect(Object.isFrozen(records.get(a.key))).toBe(true); }); - it('keeps independent drafts and titles for confirmed conversations', () => { + it('keeps independent drafts for confirmed conversations', () => { const r = new ConversationRecords(), a = r.create(); r.confirmThread(a.key, 'thread-a'); @@ -101,15 +101,8 @@ describe('page-owned conversation records', () => { const b = r.create(); r.confirmThread(b.key, 'thread-b'); r.setDraft(b.key, 'draft B'); - expect(r.setTitle(a.key, 'Literal A', a.version)).toBe(true); - expect(r.get(a.key)).toMatchObject({ - draft: 'draft A', - label: 'Literal A', - }); - expect(r.get(b.key)).toMatchObject({ - draft: 'draft B', - label: 'Conversation 2', - }); + expect(r.get(a.key)).toMatchObject({ draft: 'draft A', ordinal: 1 }); + expect(r.get(b.key)).toMatchObject({ draft: 'draft B', ordinal: 2 }); expect(a.key).not.toBe(b.key); expect(r.list()).toHaveLength(2); }); @@ -147,28 +140,16 @@ describe('page-owned conversation records', () => { expect(() => r.confirm(a.key, saved('foreign'), 'run-1')).toThrow(); expect(() => r.confirmThread(a.key, 'different')).toThrow(); }); - it('never repairs an unavailable record through later evidence or metadata', () => { + it('never repairs an unavailable record through later evidence', () => { const r = new ConversationRecords(), a = r.create(); r.confirmThread(a.key, 'thread-a'); r.markUnavailable(a.key); expect(r.get(a.key)?.availability).toBe('unavailable'); expect(() => r.confirm(a.key, saved(), 'run-1')).toThrow(); - expect(r.setTitle(a.key, 'Late title', 0)).toBe(false); expect(r.create().availability).toBe('available'); expect(r.get(a.key)?.availability).toBe('unavailable'); }); - it('fences late title publication using a record version', () => { - const r = new ConversationRecords(), - a = r.create(); - r.confirmThread(a.key, 'thread-a'); - expect(r.setTitle(a.key, 'First', 0)).toBe(true); - const version = r.invalidate(a.key); - expect(version).toBe(1); - expect(r.setTitle(a.key, 'Stale', 0)).toBe(false); - expect(r.get(a.key)?.label).toBe('First'); - expect(r.setTitle(a.key, 'Latest', version)).toBe(true); - }); it('rejects a changed confirmed prefix without replacing saved evidence', () => { const r = new ConversationRecords(), a = r.create(); diff --git a/cockpit/chat/threads/react/src/records.ts b/cockpit/chat/threads/react/src/records.ts index ea97d76de..59ec19b12 100644 --- a/cockpit/chat/threads/react/src/records.ts +++ b/cockpit/chat/threads/react/src/records.ts @@ -3,13 +3,10 @@ export interface ConversationRecord { readonly key: string; readonly ordinal: number; readonly threadId: string | null; - readonly label: string; - readonly title?: string; readonly draft: string; readonly availability: 'available' | 'unavailable'; readonly canonical: Canonical | null; readonly generations: readonly string[]; - readonly version: number; } /** Retains plain page-local records without keeping session or content owners alive. */ export class ConversationRecords { @@ -37,12 +34,10 @@ export class ConversationRecords { key: 'local-' + ordinal, ordinal, threadId: null, - label: 'Conversation ' + ordinal, draft: '', availability: 'available', canonical: null, generations: Object.freeze([]), - version: 0, }); this.records.set(record.key, record); return record; @@ -100,32 +95,9 @@ export class ConversationRecords { generations: Object.freeze([...record.generations, generation]), }); } - /** Invalidate optional metadata work without changing conversation authority. */ - invalidate(key: string): number { - const version = this.require(key).version + 1; - this.update(key, { version }); - return version; - } - /** Apply presentation metadata only to its still-current known record version. */ - setTitle(key: string, title: string, version: number): boolean { - const record = this.records.get(key); - if ( - !record?.threadId || - record.availability !== 'available' || - record.version !== version || - typeof title !== 'string' || - !title.trim() - ) - return false; - this.update(key, { title, label: title }); - return true; - } /** Permanently withhold continuation after uncertain work in this record. */ markUnavailable(key: string): void { - const record = this.require(key); - this.update(key, { - availability: 'unavailable', - version: record.version + 1, - }); + this.require(key); + this.update(key, { availability: 'unavailable' }); } } diff --git a/cockpit/chat/threads/react/src/styles.css b/cockpit/chat/threads/react/src/styles.css index 5edcebb06..29a048ebf 100644 --- a/cockpit/chat/threads/react/src/styles.css +++ b/cockpit/chat/threads/react/src/styles.css @@ -56,6 +56,14 @@ body { .conversation-picker { min-width: 0; } +.conversation-notice { + margin: 0.5rem 0 0; + font-size: 0.85rem; + color: var(--ds-text-secondary, light-dark(#606b76, #b5b5b5)); +} +.conversation-notice:empty { + display: none; +} .conversation-panel { display: flex; flex-direction: column; diff --git a/cockpit/chat/threads/react/src/titles.spec.ts b/cockpit/chat/threads/react/src/titles.spec.ts deleted file mode 100644 index 8f4267101..000000000 --- a/cockpit/chat/threads/react/src/titles.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { decodeTitle } from './titles'; -describe('optional literal conversation titles', () => { - it('accepts a matching own string title and trims only surrounding whitespace', () => { - expect( - decodeTitle( - { thread_id: 'a', metadata: { title: ' Literal ' } }, - 'a' - ) - ).toBe('Literal'); - }); - it('bounds Unicode code points without splitting a surrogate pair', () => { - expect( - decodeTitle({ thread_id: 'a', metadata: { title: '😀'.repeat(81) } }, 'a') - ).toBe('😀'.repeat(80)); - }); - it.each([ - undefined, - null, - {}, - { thread_id: 'b', metadata: { title: 'foreign' } }, - { thread_id: 'a' }, - { thread_id: 'a', metadata: null }, - { thread_id: 'a', metadata: { title: '' } }, - { thread_id: 'a', metadata: { title: ' ' } }, - { thread_id: 'a', metadata: { title: 42 } }, - { thread_id: 'a', metadata: { title: { text: 'bad' } } }, - ])('ignores missing, wrong-thread or malformed metadata %#', (raw) => { - expect(decodeTitle(raw, 'a')).toBeUndefined(); - }); - it('never invokes getters or string coercion', () => { - const getter = vi.fn(() => 'secret'), - coerce = vi.fn(() => 'secret'); - expect( - decodeTitle( - { - thread_id: 'a', - metadata: Object.defineProperty({}, 'title', { get: getter }), - }, - 'a' - ) - ).toBeUndefined(); - expect( - decodeTitle( - { thread_id: 'a', metadata: { title: { toString: coerce } } }, - 'a' - ) - ).toBeUndefined(); - expect(getter).not.toHaveBeenCalled(); - expect(coerce).not.toHaveBeenCalled(); - }); - it('rejects inherited title or thread fields', () => { - expect( - decodeTitle( - { thread_id: 'a', metadata: Object.create({ title: 'Inherited' }) }, - 'a' - ) - ).toBeUndefined(); - expect( - decodeTitle( - Object.assign(Object.create({ thread_id: 'a' }), { - metadata: { title: 'Inherited' }, - }), - 'a' - ) - ).toBeUndefined(); - }); -}); diff --git a/cockpit/chat/threads/react/src/titles.ts b/cockpit/chat/threads/react/src/titles.ts deleted file mode 100644 index 7e961159b..000000000 --- a/cockpit/chat/threads/react/src/titles.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { copyData } from './authority'; -/** Decode optional presentation metadata without granting conversation authority. */ -export function decodeTitle( - input: unknown, - threadId: string -): string | undefined { - try { - const data = copyData(input) as { - thread_id?: unknown; - metadata?: { title?: unknown }; - }; - if ( - !threadId || - data?.thread_id !== threadId || - typeof data.metadata?.title !== 'string' - ) - return undefined; - const title = data.metadata.title.trim(); - return title ? Array.from(title).slice(0, 80).join('') : undefined; - } catch { - return undefined; - } -} diff --git a/libs/cockpit-registry/src/lib/content-descriptors.ts b/libs/cockpit-registry/src/lib/content-descriptors.ts index 0cec9546b..3fac877a8 100644 --- a/libs/cockpit-registry/src/lib/content-descriptors.ts +++ b/libs/cockpit-registry/src/lib/content-descriptors.ts @@ -1071,7 +1071,7 @@ const chatThreadsReact = (() => { if (!canonical || !frontend) throw new Error('Chat Threads frontend registration is missing'); return freezeCapabilityDescriptor({ ...canonical, id: 'chat-threads-python-react', frontend: 'react', title: 'Chat Threads (React preview)', - codeAssetPaths: ['app.tsx', 'application.ts', 'authority.ts', 'records.ts', 'titles.ts', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/chat/threads/react/src/${file}`), + codeAssetPaths: ['app.tsx', 'application.ts', 'authority.ts', 'records.ts', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/chat/threads/react/src/${file}`), runtimeUrl: frontend.runtimePath, devPort: frontend.port, }); })(); diff --git a/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts b/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts index 88e3491ca..a3532d8cb 100644 --- a/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts +++ b/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts @@ -113,7 +113,7 @@ it('resolves native Chat Threads with its canonical docs and existing backend', if(!canonical) throw Error('Missing canonical Chat Threads'); const react=getFrontendCapabilityDescriptor(canonical.manifestIdentity as CockpitManifestIdentity,'react'); expect(react).toMatchObject({id:'chat-threads-python-react',frontend:'react',runtimeAdapter:'langgraph',runtimeUrl:'chat/threads/react',devPort:4625,docsPath:'/docs/react/chat/guides/thread-routing',backendAssetPaths:canonical.backendAssetPaths,promptAssetPaths:canonical.promptAssetPaths}); - expect(react?.codeAssetPaths).toEqual(['app.tsx','application.ts','authority.ts','records.ts','titles.ts','connection.ts','main.tsx','styles.css'].map(file=>`cockpit/chat/threads/react/src/${file}`)); + expect(react?.codeAssetPaths).toEqual(['app.tsx','application.ts','authority.ts','records.ts','connection.ts','main.tsx','styles.css'].map(file=>`cockpit/chat/threads/react/src/${file}`)); for(const asset of react?.codeAssetPaths ?? [])expect(existsSync(new URL('../../../../'+asset,import.meta.url))).toBe(true); expect(getCockpitFrontends().find(entry=>entry.project==='cockpit-chat-threads-react')).toMatchObject({port:4625,runtimePath:'chat/threads/react'}); expect(getFrontendCapabilityDescriptor(canonical.manifestIdentity as CockpitManifestIdentity,'angular')).toBe(canonical); From 30a6cf1ea51fcce64d2442cdf00686384c4144e3 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 12:56:58 -0800 Subject: [PATCH 13/19] docs: document the connected thread sidebars Co-Authored-By: Claude Opus 5.5 --- .../angular/chat/guides/thread-routing.mdx | 51 +++++++++++++++++++ .../docs/react/chat/guides/thread-routing.mdx | 43 ++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/apps/website/content/docs/angular/chat/guides/thread-routing.mdx b/apps/website/content/docs/angular/chat/guides/thread-routing.mdx index 2d5643564..fdefbc3f6 100644 --- a/apps/website/content/docs/angular/chat/guides/thread-routing.mdx +++ b/apps/website/content/docs/angular/chat/guides/thread-routing.mdx @@ -104,6 +104,57 @@ Two handlers close the loop. Selecting a row tells the agent to load that thread Each handler calls both `agent.switchThread(id)` and `activeThreadId.set(id)` because the two calls serve different consumers: the adapter watches the `activeThreadId` signal to drive the sidebar highlight, while `switchThread(id)` resets the agent's own derived state and re-fetches that thread's server-side history. +## Connected sidebar + +`` from `@threadplane/chat` draws New chat, Projects, Recent and Archived for any `ThreadDirectory`. `LangGraphThreadsAdapter` exposes one as `directory`, so the minimal setup is the adapter plus the component: + +```typescript +import { Component, inject, signal } from '@angular/core'; +import { ChatThreadSidebarComponent } from '@threadplane/chat'; +import { injectAgent, LangGraphThreadsAdapter } from '@threadplane/langgraph'; + +@Component({ + selector: 'app-threads', + imports: [ChatThreadSidebarComponent], + template: ` + + `, +}) +export class ThreadsPanelComponent { + protected readonly threads = inject(LangGraphThreadsAdapter); + protected readonly agent = injectAgent(); + protected readonly activeThreadId = signal(null); +} +``` + +With no listener on `(newChat)`, New chat calls `directory.create()` and emits `threadSelected` with the new identifier. The directory belongs to the application: the sidebar unsubscribes when it is destroyed but never disposes it. + +### Projects + +Project names are stored in the LangGraph Store under the namespace `['threadplane', 'projects']`. Each project is one item whose key is the project identifier and whose value is `{ name }`. A thread joins a project through its `projectId` metadata. To turn projects off, set `projects: false` in the `LANGGRAPH_THREADS_CONFIG` value; to keep them in another namespace, set `projects: { namespace: [...] }`. A server without the Store API still lists threads: the adapter's `projects` signal reports an empty list and project commands fail without affecting the thread list. + +The adapter also exposes `status`, `error` and `projects` signals for applications that draw their own list. `status` is `'loading'` until the first successful load, `'error'` after a failed load and `'idle'` otherwise. + +### Refreshing after a run + +The sidebar loads the directory when it mounts and again after each row command. Pass `[agent]` and it also refreshes every time a run ends, which is when the graph has written a generated title. + +### The active thread + +The sidebar never owns the selection. Bind `[activeThreadId]` to highlight a row and handle `(threadSelected)` to switch. When the user deletes the conversation that is active, `(activeThreadRemoved)` fires after the delete succeeds, so the application can return to a new chat. + +### Four levels of customization + +1. **Features and labels.** The `[features]` input turns built-in behavior off: `projects`, `archive`, `pin`, `reorder`, `rename` and `remove`. Each defaults to on when the directory supports it. The `[labels]` input replaces text for `newChat`, `projects`, `recent`, `archived`, `archivedEmpty`, `loadError`, `retry` and `empty`. +2. **Slots.** An `ng-template[chatThreadRow]` replaces each conversation row, with the thread as `let-thread` and `isActive` in the context. `[extraActions]` appends application commands to each row menu, and content marked `chatThreadSidebarBefore` or `chatThreadSidebarAfter` places sections around the built-in ones. Rows drawn by a template get no row menu. +3. **Your own directory.** `[directory]` accepts any object that meets `ThreadDirectory`, so an application without a LangGraph server can supply its own list and commands. The sidebar offers a command only when the directory implements it. +4. **Lower-level pieces.** ``, `` and `` remain public for applications that want full control over layout and behavior. + ## Routing a URL to a thread The example stops at an in-memory signal, which is the right choice for a surface with no visible URL. When the address bar is visible and the user may share it, `injectThreadRouting()` binds the same signal to the Angular Router: it restores the thread id from the URL on load, stamps signal changes back into the URL, validates stale links, and treats a bare URL as "no thread". The URL is the sole source of truth, and nothing is written to `localStorage`. diff --git a/apps/website/content/docs/react/chat/guides/thread-routing.mdx b/apps/website/content/docs/react/chat/guides/thread-routing.mdx index 1692e073e..bd2c9d94c 100644 --- a/apps/website/content/docs/react/chat/guides/thread-routing.mdx +++ b/apps/website/content/docs/react/chat/guides/thread-routing.mdx @@ -25,6 +25,49 @@ The connected `ThreadSidebar` lists the server's conversations from a directory Drafts and confirmed evidence belong to this page, so a reload clears them. Conversations from an earlier visit stay listed and can be organized, but selecting one shows a notice instead of opening it, because this page has not confirmed its saved history. Deleting the active conversation returns to a new chat. Angular remains the default on this canonical guide. +## Connected sidebar + +`ThreadSidebar` comes from `@threadplane/react/chat` and draws New chat, Projects, Recent and Archived for any `ThreadDirectory`. `createLangGraphThreadDirectory` from `@threadplane/langgraph` builds one over the LangGraph threads API. The directory belongs to the application: the sidebar subscribes to it but never disposes it, so dispose it yourself when the page unmounts. + +~~~tsx +import { Client } from '@langchain/langgraph-sdk'; +import { createLangGraphThreadDirectory } from '@threadplane/langgraph'; +import { ThreadSidebar } from '@threadplane/react/chat'; + +const directory = createLangGraphThreadDirectory({ + client: new Client({ apiUrl, callerOptions: { maxRetries: 0 } }), +}); + + setThreadId(null)} +/>; +~~~ + +With no `onNewChat`, New chat creates a thread through the directory and passes its identifier to `onSelect`. Pass `onNewChat` to replace that behavior, as the example above does to open a blank local conversation. + +### Projects + +Project names are stored in the LangGraph Store under the namespace `['threadplane', 'projects']`. Each project is one item whose key is the project identifier and whose value is `{ name }`. A thread joins a project through its `projectId` metadata. Pass `projects: false` to `createLangGraphThreadDirectory` to turn projects off, or pass your own project store in the same option. A server without the Store API still lists threads: the project list stays empty and project commands fail without affecting the thread list. + +### Refreshing after a run + +The sidebar loads the directory when it mounts and again after each row command. Pass `session` and it also refreshes every time a run ends, which is when the graph has written a generated title. Any object with `getSnapshot` and `subscribe`, such as an `AgentSession`, works. + +### The active thread + +The sidebar never owns the selection. Pass `activeThreadId` to highlight a row and handle `onSelect` to switch. When the user deletes the conversation that is active, the sidebar calls `onActiveRemoved` after the delete succeeds, so the application can return to a new chat instead of keeping a dangling selection. + +### Four levels of customization + +1. **Features and labels.** The `features` prop turns built-in behavior off: `projects`, `archive`, `pin`, `reorder`, `rename` and `remove`. Each defaults to on when the directory supports it. The `labels` prop replaces text for `newChat`, `projects`, `recent`, `archived`, `archivedEmpty`, `loadError`, `retry` and `empty`. +2. **Slots.** `renderThread` replaces each conversation row, `extraActions` appends application commands to each row menu, and `before` and `after` place content around the built-in sections. Rows drawn by `renderThread` get no row menu. +3. **Your own directory.** `directory` accepts any object that meets `ThreadDirectory`, so an application without a LangGraph server can supply its own list and commands. The sidebar offers a command only when the directory implements it. +4. **Lower-level pieces.** `ThreadList`, `ProjectList` and `ChatSidenav` remain public for applications that want full control over layout and behavior. + ## Keep titles optional Titles come from thread metadata, which the graph writes after the first turn. The sidebar shows them as literal text and shows "Untitled conversation" when a title is missing or invalid. A title never authorizes execution or replaces saved-history validation. From c4abb5db534332f7e3d4c4f1b89f41eaa9b76f41 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 13:26:16 -0800 Subject: [PATCH 14/19] fix(threads): hide unavailable projects, filter by project, settle first load - Publish no projects while the Store API cannot be read (runtime and adapter), so both sidebars hide the Projects section; project commands still reject. - Both sidebars list only the selected project's threads when selectedProjectId is a project id. - Both sidebars hold the empty label until their first refresh settles. - The adapter's legacy refresh() resolves once threads are published; directory.refresh() and project commands still wait for projects. - rename() shows a trimmed title, or the fallback for a blank one. - refreshDirectoryOnRunEnd swallows a rejected refresh. Co-Authored-By: Claude Opus 5.5 --- .../chat-thread-sidebar.component.spec.ts | 66 ++++++++++++++++- .../chat-thread-sidebar.component.ts | 36 ++++++++-- .../src/contracts/thread-directory.spec.ts | 17 +++++ libs/core/src/contracts/thread-directory.ts | 7 +- .../src/lib/threads/threads-adapter.spec.ts | 27 ++++--- .../src/lib/threads/threads-adapter.ts | 34 ++++++--- .../testing/thread-directory-conformance.ts | 48 ++++++++++++- .../langgraph/src/runtime/thread-directory.ts | 15 +++- libs/react/src/chat/thread-sidebar.spec.tsx | 72 ++++++++++++++++++- libs/react/src/chat/thread-sidebar.tsx | 43 +++++++++-- 10 files changed, 328 insertions(+), 37 deletions(-) diff --git a/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.spec.ts b/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.spec.ts index 94f305683..675afb839 100644 --- a/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.spec.ts +++ b/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.spec.ts @@ -77,6 +77,7 @@ interface Inputs { directory: ThreadDirectory; agent?: Agent; activeThreadId?: string | null; + selectedProjectId?: string | null; features?: ThreadSidebarFeatures; labels?: Record; extraActions?: readonly { @@ -229,7 +230,7 @@ describe('ChatThreadSidebarComponent', () => { expect(directory.refresh).toHaveBeenCalledTimes(2); }); - it('shows an empty state only once loaded', () => { + it('shows an empty state only once loaded', async () => { const directory = fakeDirectory({ threads: [], archived: [], @@ -240,11 +241,74 @@ describe('ChatThreadSidebarComponent', () => { expect(text(fixture)).not.toContain('No conversations yet.'); expect(host.getAttribute('aria-busy')).toBe('true'); directory.set({ threads: [], archived: [], status: 'idle' }); + await flush(); fixture.detectChanges(); expect(text(fixture)).toContain('No conversations yet.'); expect(host.hasAttribute('aria-busy')).toBe(false); }); + it('waits for the first refresh before showing the empty state', async () => { + // A fresh directory reports idle with no threads before it has loaded. + const directory = fakeDirectory({ threads: [], archived: [], status: 'idle' }); + let finish = () => undefined as void; + directory.refresh.mockImplementationOnce( + () => new Promise((resolve) => (finish = resolve)) + ); + const fixture = render({ directory }); + const host = fixture.nativeElement as HTMLElement; + expect(text(fixture)).not.toContain('No conversations yet.'); + expect(host.getAttribute('aria-busy')).toBe('true'); + finish(); + await flush(); + fixture.detectChanges(); + expect(text(fixture)).toContain('No conversations yet.'); + expect(host.hasAttribute('aria-busy')).toBe(false); + }); + + it('filters threads by the selected project', () => { + const directory = fakeDirectory({ + threads: [ + { id: 'a', title: 'Alpha', pinned: false, archived: false, projectId: 'p' }, + { id: 'b', title: 'Beta', pinned: false, archived: false, projectId: null }, + ], + archived: [ + { id: 'c', title: 'Gamma', pinned: false, archived: true, projectId: 'p' }, + { id: 'd', title: 'Delta', pinned: false, archived: true, projectId: 'q' }, + ], + projects: [ + { id: 'p', name: 'Research' }, + { id: 'q', name: 'Travel' }, + ], + status: 'idle', + }); + const fixture = render({ directory, selectedProjectId: 'p' }); + const selected: (string | null)[] = []; + fixture.componentInstance.projectSelected.subscribe((id) => + selected.push(id) + ); + ( + fixture.nativeElement as HTMLElement + ).querySelector('.chat-thread-sidebar__archived-toggle') + ?.click(); + fixture.detectChanges(); + expect(rowButton(fixture, 'Alpha')).toBeDefined(); + expect(rowButton(fixture, 'Beta')).toBeUndefined(); + expect(rowButton(fixture, 'Gamma')).toBeDefined(); + expect(rowButton(fixture, 'Delta')).toBeUndefined(); + const travel = Array.from( + (fixture.nativeElement as HTMLElement).querySelectorAll( + 'chat-project-list button' + ) + ).find((button) => button.textContent?.trim() === 'Travel'); + travel?.click(); + expect(selected).toEqual(['q']); + + fixture.componentRef.setInput('selectedProjectId', null); + fixture.detectChanges(); + for (const title of ['Alpha', 'Beta', 'Gamma', 'Delta']) + expect(rowButton(fixture, title)).toBeDefined(); + }); + it('refreshes after a run ends', () => { const directory = fakeDirectory(); const run = fakeAgent('running'); diff --git a/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts b/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts index 626d46665..06f847502 100644 --- a/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts +++ b/libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts @@ -117,6 +117,16 @@ const asThreads = (entries: readonly ThreadEntry[]): Thread[] => entries as unknown as Thread[]; const asProjects = (entries: readonly ProjectEntry[]): Project[] => entries as unknown as Project[]; + +/** The entries in `projectId`, or all of them when no project is selected. */ +function inProject( + entries: readonly ThreadEntry[], + projectId: string | null +): readonly ThreadEntry[] { + return typeof projectId === 'string' + ? entries.filter((entry) => entry.projectId === projectId) + : entries; +} let sidebarInstanceCounter = 0; const CHAT_THREAD_SIDEBAR_STYLES = ` @@ -396,6 +406,10 @@ export class ChatThreadSidebarComponent { /** Refreshes the directory each time a run ends. */ readonly agent = input(null); readonly activeThreadId = input(null); + /** + * When a project id, Recent and Archived list only that project's threads; + * `null` lists every thread. + */ readonly selectedProjectId = input(null); readonly features = input(null); /** App commands appended to each conversation row menu. */ @@ -431,8 +445,13 @@ export class ChatThreadSidebarComponent { return this.directory().getSnapshot(); }); + /** The directory whose mount refresh has settled. Until then an empty + * list means "not loaded yet", so the empty label waits for it. */ + private readonly settled = signal(null); protected readonly loading = computed( - () => this.snapshot().status === 'loading' + () => + this.snapshot().status === 'loading' || + this.settled() !== this.directory() ); protected readonly failed = computed( () => this.snapshot().status === 'error' @@ -445,11 +464,11 @@ export class ChatThreadSidebarComponent { () => this.on('projects') && this.snapshot().projects !== undefined ); - protected readonly threads = computed( - () => asThreads(this.snapshot().threads) + protected readonly threads = computed(() => + asThreads(inProject(this.snapshot().threads, this.selectedProjectId())) ); - protected readonly archivedThreads = computed( - () => asThreads(this.snapshot().archived) + protected readonly archivedThreads = computed(() => + asThreads(inProject(this.snapshot().archived, this.selectedProjectId())) ); protected readonly projects = computed(() => { if (!this.showProjects()) return null; @@ -541,7 +560,12 @@ export class ChatThreadSidebarComponent { // Catch a change published before this subscription. this.version.update((v) => v + 1); const controller = new AbortController(); - directory.refresh({ signal: controller.signal }).catch(ignore); + directory + .refresh({ signal: controller.signal }) + .catch(ignore) + .then(() => { + if (!controller.signal.aborted) this.settled.set(directory); + }); onCleanup(() => { unsubscribe(); controller.abort(); diff --git a/libs/core/src/contracts/thread-directory.spec.ts b/libs/core/src/contracts/thread-directory.spec.ts index c57338ed6..57409ccf7 100644 --- a/libs/core/src/contracts/thread-directory.spec.ts +++ b/libs/core/src/contracts/thread-directory.spec.ts @@ -36,6 +36,23 @@ describe('refreshDirectoryOnRunEnd', () => { expect(refresh).not.toHaveBeenCalled(); }); + it('ignores a rejected refresh', async () => { + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const fake = createFakeAgentSession(); + const refresh = vi.fn(() => Promise.reject(new Error('offline'))); + refreshDirectoryOnRunEnd({ refresh }, fake.session); + fake.setStatus('running'); + fake.setStatus('idle'); + expect(refresh).toHaveBeenCalledTimes(1); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + it('stops after release', () => { const { fake, refresh, release } = setup(); release(); diff --git a/libs/core/src/contracts/thread-directory.ts b/libs/core/src/contracts/thread-directory.ts index c411ca5c0..4e0141911 100644 --- a/libs/core/src/contracts/thread-directory.ts +++ b/libs/core/src/contracts/thread-directory.ts @@ -59,7 +59,8 @@ export interface ThreadDirectory { /** * Refreshes the directory each time the session leaves `'running'`, whether - * the run succeeded or ended in error. Returns an idempotent release. + * the run succeeded or ended in error. A rejected refresh is ignored. Returns + * an idempotent release. */ export function refreshDirectoryOnRunEnd( directory: Pick, @@ -70,6 +71,8 @@ export function refreshDirectoryOnRunEnd( const next = session.getSnapshot().status; const ended = last === 'running' && next !== 'running'; last = next; - if (ended) void directory.refresh(); + // A failed refresh shows on the directory; it never escapes as an + // unhandled rejection. + if (ended) directory.refresh().catch(() => undefined); }); } diff --git a/libs/langgraph/src/lib/threads/threads-adapter.spec.ts b/libs/langgraph/src/lib/threads/threads-adapter.spec.ts index efdbf75d4..1c9c02d0d 100644 --- a/libs/langgraph/src/lib/threads/threads-adapter.spec.ts +++ b/libs/langgraph/src/lib/threads/threads-adapter.spec.ts @@ -229,8 +229,9 @@ describe('LangGraphThreadsAdapter directory view', () => { expect(svc.threads().map((t) => t.id)).toEqual(['a']); expect(svc.status()).toBe('idle'); - expect(svc.projects()).toEqual([]); - expect(svc.directory.getSnapshot().projects).toEqual([]); + // Unavailable reads like "no project store", so views hide Projects. + await vi.waitFor(() => expect(svc.projects()).toBeUndefined()); + expect('projects' in svc.directory.getSnapshot()).toBe(false); }); it('turns projects off with projects: false', async () => { @@ -273,7 +274,7 @@ describe('LangGraphThreadsAdapter directory view', () => { }); const svc = TestBed.inject(LangGraphThreadsAdapter); - await svc.refresh(); + await svc.directory.refresh(); expect(searchItems).toHaveBeenCalledWith(['app', 'groups'], { limit: 100 }); expect(svc.projects()).toEqual([{ id: 'p1', name: 'Work' }]); @@ -318,23 +319,31 @@ describe('LangGraphThreadsAdapter directory view', () => { (m.client as unknown as { store: unknown }).store = { searchItems }; const svc = configure(m.client); - let refreshed = false; - const refreshing = svc.refresh().then(() => (refreshed = true)); - await vi.waitFor(() => expect(searchItems).toHaveBeenCalledTimes(1)); + // The legacy refresh() resolves once threads are published, with the + // Store API still held. + await svc.refresh(); + expect(searchItems).toHaveBeenCalledTimes(1); expect(svc.threads().map((t) => t.id)).toEqual(['a']); expect(svc.directory.getSnapshot().threads.map((t) => t.id)).toEqual(['a']); expect(svc.status()).toBe('idle'); expect(svc.projects()).toEqual([]); - expect(refreshed).toBe(false); m.search.mockResolvedValue([{ thread_id: 'a', metadata: { title: 'Trip' } }]); await svc.rename('a', 'Trip'); expect(svc.threads()[0].title).toBe('Trip'); + // The directory's refresh() still waits for project names. + let directoryRefreshed = false; + const directoryRefreshing = svc.directory + .refresh() + .then(() => (directoryRefreshed = true)); + await vi.waitFor(() => expect(searchItems).toHaveBeenCalledTimes(3)); + expect(directoryRefreshed).toBe(false); + for (const release of releases) release(); - await refreshing; - await vi.waitFor(() => expect(svc.projects()).toEqual([{ id: 'p1', name: 'P' }])); + await directoryRefreshing; + expect(svc.projects()).toEqual([{ id: 'p1', name: 'P' }]); expect(svc.directory.getSnapshot().projects).toEqual([{ id: 'p1', name: 'P' }]); }); diff --git a/libs/langgraph/src/lib/threads/threads-adapter.ts b/libs/langgraph/src/lib/threads/threads-adapter.ts index c62e1c0de..1897062c9 100644 --- a/libs/langgraph/src/lib/threads/threads-adapter.ts +++ b/libs/langgraph/src/lib/threads/threads-adapter.ts @@ -73,7 +73,9 @@ export interface LangGraphThreadsConfig { /** Project names, kept in the LangGraph Store API under `namespace` * (default `['threadplane', 'projects']`), one item per project with the * value `{ name }`. On by default; `false` turns projects off. A server - * without the Store API still lists threads and reports no projects. */ + * without the Store API still lists threads; while the store cannot be + * read, {@link LangGraphThreadsAdapter.projects} is `undefined` and project + * commands reject. */ projects?: false | { namespace?: readonly string[] }; } @@ -163,8 +165,9 @@ export class LangGraphThreadsAdapter { readonly status: Signal = this._status.asReadonly(); /** The last load failure, opaque by design; cleared by a successful load. */ readonly error: Signal = this._error.asReadonly(); - /** Project names from the LangGraph Store API, sorted by name. `[]` when - * the Store API is unavailable; `undefined` when `projects: false`. */ + /** Project names from the LangGraph Store API, sorted by name. + * `undefined` when `projects: false` or while the Store API cannot be + * read, so views hide the Projects section. */ readonly projects: Signal = this._projects.asReadonly(); @@ -224,7 +227,9 @@ export class LangGraphThreadsAdapter { * with no visible signal. Tighten the log volume if it becomes * noisy. */ async refresh(): Promise { - await this.load(true); + // Resolves once threads are published; project names load in the + // background. The directory's refresh() waits for them. + await this.load(false); } /** Reads the thread list, publishes it, then reads project names and @@ -323,6 +328,8 @@ export class LangGraphThreadsAdapter { } } + // Phase 2: the runtime directory URL-encodes thread ids in request paths; + // this adapter keeps the legacy raw-id paths until it is rebuilt on it. async delete(threadId: string): Promise { await this.mutate([{ id: threadId, fields: { removed: true } }], () => this.client.threads.delete(threadId), @@ -330,7 +337,9 @@ export class LangGraphThreadsAdapter { } async rename(threadId: string, newTitle: string): Promise { - await this.mutate([{ id: threadId, fields: { title: newTitle } }], () => + // A blank title shows the fallback at once, as the server list would. + const shown = newTitle.trim() || this.fallback; + await this.mutate([{ id: threadId, fields: { title: shown } }], () => this.client.threads.update(threadId, { metadata: { title: newTitle } }), ); } @@ -459,7 +468,7 @@ export class LangGraphThreadsAdapter { await this.mutate(patches, run, true); } else { await this.request(run); - await this.refresh(); + await this.load(true); } return result as T; } @@ -509,7 +518,7 @@ export class LangGraphThreadsAdapter { } this._status.set(this.computeStatus()); this._error.set(this.loadFailure); - if (this.projectStore) this._projects.set(this.serverProjects); + this._projects.set(this.publishedProjects()); this.updateView(); } @@ -533,7 +542,7 @@ export class LangGraphThreadsAdapter { }, refresh: async () => { if (this.viewDisposed) return; - await this.refresh(); + await this.load(true); }, create: (options?: { readonly metadata?: { readonly [key: string]: unknown } }) => run(async () => { @@ -591,11 +600,18 @@ export class LangGraphThreadsAdapter { this.viewListeners.clear(); } + /** An unavailable Store API publishes no projects, so views hide them. */ + private publishedProjects(): readonly ProjectEntry[] | undefined { + return this.projectStore && !this.projectsUnavailable + ? this.serverProjects + : undefined; + } + private buildSnapshot(): ThreadDirectorySnapshot { return Object.freeze({ threads: this.activeEntries, archived: this.archivedEntries, - ...(this.projectStore ? { projects: this.serverProjects } : {}), + ...(this.publishedProjects() ? { projects: this.serverProjects } : {}), status: this.computeStatus(), ...(this.loadFailure === undefined ? {} : { error: this.loadFailure }), }); diff --git a/libs/langgraph/src/runtime/testing/thread-directory-conformance.ts b/libs/langgraph/src/runtime/testing/thread-directory-conformance.ts index 3b3f546c8..0eeaadc22 100644 --- a/libs/langgraph/src/runtime/testing/thread-directory-conformance.ts +++ b/libs/langgraph/src/runtime/testing/thread-directory-conformance.ts @@ -167,6 +167,24 @@ export function describeThreadDirectoryConformance( expect(metadata(client, 'a')?.['title']).toBe('Trip'); }); + it('trims a renamed title and shows the fallback for a blank one', async () => { + const { client, directory } = setup([ + { thread_id: 'a', updated_at: at(1), metadata: { title: 'A' } }, + ]); + await directory.refresh(); + const release = client.hold('threads.update'); + + const blank = directory.rename?.('a', ' '); + + expect(entry(directory, 'a')?.title).toBe('New chat'); + release(); + await blank; + expect(entry(directory, 'a')?.title).toBe('New chat'); + + await directory.rename?.('a', ' Trip '); + expect(entry(directory, 'a')?.title).toBe('Trip'); + }); + it('rolls back a failed rename and rejects', async () => { const { client, directory } = setup([ { thread_id: 'a', updated_at: at(1), metadata: { title: 'A' } }, @@ -466,12 +484,40 @@ export function describeThreadDirectoryConformance( expect(snapshot.status).toBe('idle'); expect(snapshot.error).toBeUndefined(); expect(snapshot.threads.map((t) => t.id)).toEqual(['a']); - expect(snapshot.projects).toEqual([]); + expect(snapshot.projects).toBeUndefined(); await expect(directory.createProject?.('Trips')).rejects.toThrow( 'The LangGraph request failed.' ); expect(client.puts).toEqual([]); } ); + + it.skipIf(!withProjects)( + 'stops publishing projects when the project store later fails', + async () => { + const { client, directory } = setup( + [{ thread_id: 'a', updated_at: at(1), metadata: { title: 'A' } }], + [{ id: 'p1', name: 'One' }] + ); + await directory.refresh(); + expect(directory.getSnapshot().projects).toEqual([ + { id: 'p1', name: 'One' }, + ]); + client.failNext('store.searchItems', 500); + + await directory.refresh(); + + expect(directory.getSnapshot().projects).toBeUndefined(); + expect(directory.getSnapshot().threads.map((t) => t.id)).toEqual([ + 'a', + ]); + + await directory.refresh(); + + expect(directory.getSnapshot().projects).toEqual([ + { id: 'p1', name: 'One' }, + ]); + } + ); }); } diff --git a/libs/langgraph/src/runtime/thread-directory.ts b/libs/langgraph/src/runtime/thread-directory.ts index 53390a357..edc56c27a 100644 --- a/libs/langgraph/src/runtime/thread-directory.ts +++ b/libs/langgraph/src/runtime/thread-directory.ts @@ -41,7 +41,9 @@ export interface LangGraphThreadDirectoryOptions { readonly titleFallback?: string; /** * Project names. Defaults to the LangGraph Store API - * (`createLangGraphProjectStore`); `false` turns projects off. + * (`createLangGraphProjectStore`); `false` turns projects off. While the + * store cannot be read, the snapshot has no `projects` and project + * commands reject. */ readonly projects?: ProjectStore | false; } @@ -145,7 +147,10 @@ export function createLangGraphThreadDirectory( archived: sameList(snapshot.archived, archived) ? snapshot.archived : Object.freeze(archived), - ...(projectStore ? { projects: serverProjects } : {}), + // An unavailable Store API publishes no projects, so views hide them. + ...(projectStore && !projectsUnavailable + ? { projects: serverProjects } + : {}), status, ...(error === undefined ? {} : { error }), }); @@ -290,8 +295,12 @@ export function createLangGraphThreadDirectory( await refresh(); return Object.freeze({ id }); }, + // A blank title shows the fallback at once, as the server list would. rename: (id: string, title: string) => - mutate([{ id, fields: { title } }], update(id, { title })), + mutate( + [{ id, fields: { title: title.trim() || titleFallback } }], + update(id, { title }) + ), remove: (id: string) => mutate([{ id, fields: { removed: true } }], (signal) => client.threads.delete(encodeURIComponent(id), { signal }) diff --git a/libs/react/src/chat/thread-sidebar.spec.tsx b/libs/react/src/chat/thread-sidebar.spec.tsx index 6e886f25c..855a3c6f7 100644 --- a/libs/react/src/chat/thread-sidebar.spec.tsx +++ b/libs/react/src/chat/thread-sidebar.spec.tsx @@ -189,7 +189,7 @@ describe('ThreadSidebar', () => { expect(directory.refresh).toHaveBeenCalledTimes(2); }); - it('shows an empty state only once loaded', () => { + it('shows an empty state only once loaded', async () => { const directory = fakeDirectory({ threads: [], archived: [], @@ -202,13 +202,81 @@ describe('ThreadSidebar', () => { expect(view.container.firstElementChild?.getAttribute('aria-busy')).toBe( 'true' ); - act(() => directory.set({ threads: [], archived: [], status: 'idle' })); + await act(async () => + directory.set({ threads: [], archived: [], status: 'idle' }) + ); + expect(view.getByText('No conversations yet.')).not.toBeNull(); + expect(view.container.firstElementChild?.hasAttribute('aria-busy')).toBe( + false + ); + }); + + it('waits for the first refresh before showing the empty state', async () => { + // A fresh directory reports idle with no threads before it has loaded. + const directory = fakeDirectory({ threads: [], archived: [], status: 'idle' }); + let finish = () => undefined as void; + directory.refresh.mockImplementationOnce( + () => new Promise((resolve) => (finish = resolve)) + ); + const view = render( + + ); + expect(view.queryByText('No conversations yet.')).toBeNull(); + expect(view.container.firstElementChild?.getAttribute('aria-busy')).toBe( + 'true' + ); + await act(async () => finish()); expect(view.getByText('No conversations yet.')).not.toBeNull(); expect(view.container.firstElementChild?.hasAttribute('aria-busy')).toBe( false ); }); + it('filters threads by the selected project', async () => { + const directory = fakeDirectory({ + threads: [ + { id: 'a', title: 'Alpha', pinned: false, archived: false, projectId: 'p' }, + { id: 'b', title: 'Beta', pinned: false, archived: false, projectId: null }, + ], + archived: [ + { id: 'c', title: 'Gamma', pinned: false, archived: true, projectId: 'p' }, + { id: 'd', title: 'Delta', pinned: false, archived: true, projectId: 'q' }, + ], + projects: [ + { id: 'p', name: 'Research' }, + { id: 'q', name: 'Travel' }, + ], + status: 'idle', + }); + const onProjectSelect = vi.fn(); + const view = render( + + ); + await act(async () => undefined); + fireEvent.click(view.getByRole('button', { name: 'Archived' })); + expect(view.queryByRole('button', { name: 'Alpha' })).not.toBeNull(); + expect(view.queryByRole('button', { name: 'Beta' })).toBeNull(); + expect(view.queryByRole('button', { name: 'Gamma' })).not.toBeNull(); + expect(view.queryByRole('button', { name: 'Delta' })).toBeNull(); + fireEvent.click(view.getByRole('button', { name: 'Travel' })); + expect(onProjectSelect).toHaveBeenCalledWith('q'); + + view.rerender( + + ); + for (const name of ['Alpha', 'Beta', 'Gamma', 'Delta']) + expect(view.queryByRole('button', { name })).not.toBeNull(); + }); + it('refreshes after a run ends', () => { const directory = fakeDirectory(); const run = fakeSession('running'); diff --git a/libs/react/src/chat/thread-sidebar.tsx b/libs/react/src/chat/thread-sidebar.tsx index 35ff767eb..4897c49bc 100644 --- a/libs/react/src/chat/thread-sidebar.tsx +++ b/libs/react/src/chat/thread-sidebar.tsx @@ -2,7 +2,9 @@ import { useCallback, useEffect, + useMemo, useRef, + useState, useSyncExternalStore, type ReactNode, } from 'react'; @@ -10,6 +12,7 @@ import { refreshDirectoryOnRunEnd, type AgentSession, type ThreadDirectory, + type ThreadEntry, } from '@threadplane/core'; import { ChatSidenavSections } from './chat-sidenav-sections.js'; import type { ProjectActionAdapter } from './project-list.js'; @@ -42,7 +45,12 @@ export interface ThreadSidebarProps { readonly onNewChat?: () => void; /** Called after the active thread is deleted. */ readonly onActiveRemoved?: () => void; + /** + * When a project id, Recent and Archived list only that project's threads; + * `null` or omitted lists every thread. + */ readonly selectedProjectId?: string | null; + /** Called with the project the user picked; the app owns `selectedProjectId`. */ readonly onProjectSelect?: (projectId: string | null) => void; readonly features?: ThreadSidebarFeatures; /** Replaces each conversation row; see `ThreadListProps.renderItem`. */ @@ -72,6 +80,16 @@ export interface ThreadSidebarProps { const ignore = () => undefined; const NO_FEATURES: ThreadSidebarFeatures = {}; +/** The entries in `projectId`, or all of them when no project is selected. */ +function inProject( + entries: readonly ThreadEntry[], + projectId: string | null | undefined +): readonly ThreadEntry[] { + return typeof projectId === 'string' + ? entries.filter((entry) => entry.projectId === projectId) + : entries; +} + /** * A conversation sidebar connected to a `ThreadDirectory`: New chat, * Projects, Recent and Archived with the row commands the directory supports. @@ -106,9 +124,17 @@ export function ThreadSidebar({ const latest = useRef({ activeThreadId, onSelect, onActiveRemoved }); latest.current = { activeThreadId, onSelect, onActiveRemoved }; + // Until the mount refresh settles, an empty list means "not loaded yet", + // so the empty label waits for it. + const [settled, setSettled] = useState(null); useEffect(() => { const controller = new AbortController(); - directory.refresh({ signal: controller.signal }).catch(ignore); + directory + .refresh({ signal: controller.signal }) + .catch(ignore) + .then(() => { + if (!controller.signal.aborted) setSettled(directory); + }); return () => controller.abort(); }, [directory]); @@ -199,7 +225,16 @@ export function ThreadSidebar({ } : undefined); - const loading = snapshot.status === 'loading'; + const threads = useMemo( + () => inProject(snapshot.threads, selectedProjectId), + [snapshot.threads, selectedProjectId] + ); + const archived = useMemo( + () => inProject(snapshot.archived, selectedProjectId), + [snapshot.archived, selectedProjectId] + ); + + const loading = snapshot.status === 'loading' || settled !== directory; const failed = snapshot.status === 'error'; return (
Date: Tue, 17 Nov 2026 13:26:16 -0800 Subject: [PATCH 15/19] test(cockpit): select projects in the threads examples and allow sidebar reads - Both threads examples bind selectedProjectId and toggle it on selection; the Angular sidebar's New chat runs the existing new-thread handler. - The React example creates and disposes its directory in one effect, so a StrictMode remount gets a live directory. - The website preview guard allows the sidebar's read-only thread and Store searches while still rejecting thread creation and runs. Co-Authored-By: Claude Opus 5.5 --- .../e2e/react-chat-threads-preview.spec.ts | 20 ++++-- .../threads/angular/e2e/c-threads.spec.ts | 39 +++++++++++ .../angular/src/app/threads.component.ts | 15 +++- .../chat/threads/react/e2e/threads.spec.ts | 55 +++++++++++++++ cockpit/chat/threads/react/src/app.tsx | 68 ++++++++++++------- 5 files changed, 167 insertions(+), 30 deletions(-) diff --git a/apps/website/e2e/react-chat-threads-preview.spec.ts b/apps/website/e2e/react-chat-threads-preview.spec.ts index ecd49d08d..795cdb7d2 100644 --- a/apps/website/e2e/react-chat-threads-preview.spec.ts +++ b/apps/website/e2e/react-chat-threads-preview.spec.ts @@ -5,6 +5,16 @@ import { fromPageOrReactPreview } from './fixtures/react-preview-requests'; const route = '/docs/angular/chat/guides/thread-routing'; const reactRoute = '/docs/react/chat/guides/thread-routing'; const reactFrame = /(?:localhost:4625|chat\/threads\/react)/; +/** + * The connected sidebar lists saved conversations and project names on mount. + * Those searches are read-only; creating a thread or starting a run is not. + */ +function readOnlyListing(method: string, pathname: string): boolean { + return ( + method === 'POST' && + /\/(?:threads|store\/items)\/search$/.test(pathname) + ); +} const observations = new WeakMap< Page, { requests: string[]; errors: string[] } @@ -13,12 +23,14 @@ test.beforeEach(async ({ page }) => { const observed = { requests: [] as string[], errors: [] as string[] }; observations.set(page, observed); page.on('request', (request) => { + const pathname = new URL(request.url()).pathname; if ( ['fetch', 'xhr'].includes(request.resourceType()) && - /\/threads(?:\/|$)/.test(new URL(request.url()).pathname) && + /\/threads(?:\/|$)/.test(pathname) && + !readOnlyListing(request.method(), pathname) && fromPageOrReactPreview(request, reactFrame) ) - observed.requests.push(request.method()); + observed.requests.push(`${request.method()} ${pathname}`); }); page.on('pageerror', (error) => observed.errors.push(error.message)); }); @@ -123,7 +135,7 @@ test('a direct React run link mounts an empty conversation without creating a th }); await emptyRun(page); }); -test('history preserves the mounted React owner and unsent draft without runtime requests', async ({ +test('history preserves the mounted React owner and unsent draft without creating threads or runs', async ({ page, }) => { await page.goto(reactRoute + '?mode=run', { @@ -153,7 +165,7 @@ test('history preserves the mounted React owner and unsent draft without runtime ).toBe(true); expect(observations.get(page)?.requests).toEqual(before); }); -test('reload clears an unsent React draft without runtime requests', async ({ +test('reload clears an unsent React draft without creating threads or runs', async ({ page, }) => { await page.goto(reactRoute + '?mode=run', { diff --git a/cockpit/chat/threads/angular/e2e/c-threads.spec.ts b/cockpit/chat/threads/angular/e2e/c-threads.spec.ts index 0d0940aa5..9cb409b2f 100644 --- a/cockpit/chat/threads/angular/e2e/c-threads.spec.ts +++ b/cockpit/chat/threads/angular/e2e/c-threads.spec.ts @@ -161,6 +161,45 @@ test('c-threads: a conversation moved into a new project keeps it after reload', expect(items.find((item) => item.key === projectId)?.value.name).toBe(project); }); +test('c-threads: selecting a project lists only its conversations until it is selected again', async ({ + page, + request, +}) => { + const member = `Filtered member ${randomUUID()}`; + const outsider = `Filtered outsider ${randomUUID()}`; + const project = `Filter ${randomUUID().slice(0, 8)}`; + const id = await createThread(request, member); + await createThread(request, outsider); + await page.goto('/'); + await expect(row(page, outsider)).toHaveCount(1); + await sidebar(page).getByRole('button', { name: '+ New project' }).click(); + const name = sidebar(page).getByRole('textbox', { name: 'New project name' }); + await name.fill(project); + await name.press('Enter'); + const projectButton = sidebar(page) + .locator('chat-project-list') + .getByRole('button', { name: project, exact: true }); + await expect(projectButton).toBeVisible(); + await rowCommand(page, member, 'Move to project'); + await page.getByRole('menuitem', { name: project, exact: true }).click(); + await expect + .poll(async () => (await readThread(request, id)).metadata['projectId']) + .toEqual(expect.any(String)); + created.projects.add( + (await readThread(request, id)).metadata['projectId'] as string + ); + + await projectButton.click(); + await expect(projectButton).toHaveAttribute('aria-current', 'true'); + await expect(row(page, member)).toHaveCount(1); + await expect(row(page, outsider)).toHaveCount(0); + + await projectButton.click(); + await expect(projectButton).not.toHaveAttribute('aria-current', 'true'); + await expect(row(page, outsider)).toHaveCount(1); + await expect(row(page, member)).toHaveCount(1); +}); + test('c-threads: deleting the active conversation returns to a new chat', async ({ page, request, diff --git a/cockpit/chat/threads/angular/src/app/threads.component.ts b/cockpit/chat/threads/angular/src/app/threads.component.ts index e54281a62..fb14feda0 100644 --- a/cockpit/chat/threads/angular/src/app/threads.component.ts +++ b/cockpit/chat/threads/angular/src/app/threads.component.ts @@ -55,7 +55,7 @@ export const activeThreadIdState = signal(null); @@ -69,7 +69,10 @@ export const activeThreadIdState = signal(null); [directory]="threadsSvc.directory" [agent]="agent" [activeThreadId]="activeThreadId()" + [selectedProjectId]="selectedProjectId()" (threadSelected)="onThreadSelected($event)" + (newChat)="!agent.isLoading() && onNewThread(conversation)" + (projectSelected)="onProjectSelected($event)" (activeThreadRemoved)="onActiveThreadRemoved(conversation)" /> @@ -91,6 +94,16 @@ export class ThreadsComponent { protected readonly agent = injectAgent(); + /** The project whose conversations the sidebar lists; `null` lists all. */ + protected readonly selectedProjectId = signal(null); + + /** Selecting the selected project again lists every conversation. */ + protected onProjectSelected(projectId: string | null): void { + this.selectedProjectId.update((current) => + current === projectId ? null : projectId, + ); + } + // #region thread-actions /** Row commands go through `threadsSvc.directory`; the sidebar reports * when the active thread was deleted so the surface returns to a new chat. */ diff --git a/cockpit/chat/threads/react/e2e/threads.spec.ts b/cockpit/chat/threads/react/e2e/threads.spec.ts index a3b79cd61..495caf639 100644 --- a/cockpit/chat/threads/react/e2e/threads.spec.ts +++ b/cockpit/chat/threads/react/e2e/threads.spec.ts @@ -627,6 +627,61 @@ test('sidebar creates a project, moves a conversation into it and keeps both aft ]); }); +test('selecting a project lists only its conversations until it is selected again', async ({ + page, + request, +}) => { + await page.goto(base); + await submit(page, 'A first'); + await saved(page); + await newConversation(page); + await submit(page, 'B first'); + await saved(page); + const [a, b] = await createdThreads(request); + for (const [id, title] of [ + [a, 'Alpha'], + [b, 'Beta'], + ]) + expect( + ( + await request.patch(`/api/threads/${id}`, { + data: { metadata: { title } }, + }) + ).status() + ).toBe(200); + await page.reload(); + const sorted = async () => (await rowTitles(page)()).sort(); + await expect.poll(sorted).toEqual(['Alpha', 'Beta']); + await page + .getByRole('button', { name: '+ New project', exact: true }) + .click(); + const name = page.getByLabel('New project name', { exact: true }); + await name.fill('Research'); + await name.press('Enter'); + await rowCommand(page, 'Alpha', 'Move to project'); + await page.getByRole('menuitem', { name: 'Research', exact: true }).click(); + await expect + .poll(async () => + (await serverThreads(request)).find((thread) => thread.thread_id === a) + ?.metadata['projectId'] + ) + .toEqual(expect.any(String)); + + await projectButton(page, 'Research').click(); + await expect(projectButton(page, 'Research')).toHaveAttribute( + 'aria-current', + 'true' + ); + await expect(sidebarRows(page)).toHaveText(['Alpha']); + + await projectButton(page, 'Research').click(); + await expect(projectButton(page, 'Research')).not.toHaveAttribute( + 'aria-current', + 'true' + ); + await expect.poll(sorted).toEqual(['Alpha', 'Beta']); +}); + test('sidebar delete of the active conversation returns to a new chat', async ({ page, request, diff --git a/cockpit/chat/threads/react/src/app.tsx b/cockpit/chat/threads/react/src/app.tsx index 9a0d94771..18d706711 100644 --- a/cockpit/chat/threads/react/src/app.tsx +++ b/cockpit/chat/threads/react/src/app.tsx @@ -11,6 +11,7 @@ import { } from '@threadplane/react/chat'; import { Markdown } from '@threadplane/react/markdown'; import type { MessageRow } from '@threadplane/content/messages'; +import type { ThreadDirectory } from '@threadplane/core'; import { createThreadsClient, createThreadsDirectory, @@ -63,7 +64,15 @@ function ThreadsOwner({ connection, onReady }: Props) { const [application] = useState(() => createThreadsApplication(createThreadsClient(connection)) ); - const [directory] = useState(() => createThreadsDirectory(connection)); + // Created and disposed by the same effect, so a StrictMode remount gets a + // fresh directory instead of one its first cleanup already disposed. + const [directory, setDirectory] = useState(null); + useEffect(() => { + const created = createThreadsDirectory(connection); + setDirectory(created); + return () => created.dispose(); + }, [connection]); + const [projectId, setProjectId] = useState(null); const snapshot = useAgent(application); const [notice, setNotice] = useState(null); // A new view (selection, New, removal) replaces any earlier notice. @@ -77,7 +86,6 @@ function ThreadsOwner({ connection, onReady }: Props) { }, [application] ); - useEffect(() => () => directory.dispose(), [directory]); // The sidebar refreshes itself on mount and after each row command. A new // saved conversation, a saved response (the graph writes the title) and a // loaded conversation also refresh it. @@ -85,6 +93,7 @@ function ThreadsOwner({ connection, onReady }: Props) { .map((record) => record.threadId) .join(' '); useEffect(() => { + if (!directory) return; if (!confirmedThreads && snapshot.confirmation === null) return; directory.refresh().catch(() => undefined); }, [directory, confirmedThreads, snapshot.confirmation]); @@ -141,33 +150,42 @@ function ThreadsOwner({ connection, onReady }: Props) {

The sidebar lists the conversations saved on the server: rename, pin, - reorder, archive, delete or move them into a project from each row menu. - Conversations created on this page can be continued; their drafts last - while this page stays open and saved history is checked before - continuing. Titles are optional. + reorder, archive, delete or move them into a project from each row menu, + and select a project to list only its conversations. Conversations + created on this page can be continued; their drafts last while this page + stays open and saved history is checked before continuing. Titles are + optional.