diff --git a/apps/website/content/AGENTS.md.template b/apps/website/content/AGENTS.md.template index 33340ee7b..69e27b01c 100644 --- a/apps/website/content/AGENTS.md.template +++ b/apps/website/content/AGENTS.md.template @@ -24,7 +24,7 @@ Chat Debug has an experimental native React first slice at https://threadplane.a Chat Timeline has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-trace. The first Send creates a conversation lazily; New is local and inert until Send. Refresh checkpoints explicitly requests the recent page with limit 10 and clears selection; successful turns do not refresh it automatically. Selecting a completed root checkpoint loads a separate read-only preview of this graph's strict plain alternating human/assistant transcript. In-progress or invalid checkpoint references are unavailable. Unsupported saved transcripts fail preview validation. Ordinary Send continues the current conversation and retains the validated preview without consuming the draft on selection. Fork from here uses the selected checkpoint and current draft: after A+B, preview A and Send C gives A+B+C; Fork D gives A+D; after confirmation the fork becomes current, the preview clears, and Send E gives A+D+E. Failed or cancelled reads leave the primary conversation usable. Stop or uncertain execution requires New, with no replay, retry or resume. One configured target and header owner serves creation, streams and reads with retries disabled, using the existing shared FREE c-timeline graph. Docs, Code and Run use the same native React implementation; mode navigation preserves the mounted frame and draft, and reload clears local state. Mount and mode changes make no thread requests. Angular remains the default; its Replay/Fork events require host wiring. Candidate packages remain private source builds. Build with `npx nx build cockpit-chat-timeline-react` and verify with `npx nx e2e cockpit-chat-timeline-react`. -Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes MessageList, Markdown, Reasoning, Citations and ChatInput with the existing c-threads graph. The picker and per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Optional titles are literal text bounded to 80 Unicode code points; missing or invalid metadata preserves the fallback or last valid title, and stale title requests cannot affect another selection. Titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no shared search, arbitrary-ID loading, URL routing, rename/delete management, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and optional titles, with retries disabled. Mount and mode changes cause no thread requests; Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. +Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes the connected ThreadSidebar with MessageList, Markdown, Reasoning, Citations and ChatInput over the existing c-threads graph. The sidebar lists the threads saved on the server through a directory from createLangGraphThreadDirectory and offers rename, pin, drag reordering, archive, delete and projects; project names are kept in the LangGraph Store under the namespace ['threadplane', 'projects'], and selecting a project lists only its conversations until it is selected again. Only conversations created and confirmed on the open page can be continued; choosing a listed conversation from an earlier visit shows a notice instead of loading it. Per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Titles are optional server metadata written by the graph; the sidebar shows a fallback when a title is missing, and titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no arbitrary-ID loading, URL routing, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and the sidebar's thread and Store requests, with retries disabled. On mount the sidebar makes read-only thread and Store searches; mount and mode changes create no threads and start no runs. Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. Chat Subagents has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-subagent-card. It uses the existing c-subagents graph with research, booking and itinerary specialists to provide model-generated planning suggestions, without live availability/prices or actual booking. Saved root task calls and literal results stay with the requesting assistant. A separate default-closed Child response observations disclosure retains validated child text locally across root history loads and follow-up turns; these rows are not restored execution history and are not mapped to task cards. Full namespaces identify local observations internally; no parent binding is inferred from role, order or task arguments. Valid empty child text adds no row. Stop and incomplete work label retained observations accordingly, without claiming child execution success. Child errors, interruptions, tools, malformed supplied values, changed completed text and foreign generations permanently withhold continuation for that owner, even if later history clears child snapshots. Only matching terminal saved root evidence permits a follow-up; a fulfilled aborted load does not. New clears local state without remote deletion. Mount, draft seeds and local reset cause no runtime request. Title generation remains metadata-only, the existing shared deployment is reused, Angular remains the default, and candidate packages remain private source builds. diff --git a/apps/website/content/CLAUDE.md.template b/apps/website/content/CLAUDE.md.template index 33340ee7b..69e27b01c 100644 --- a/apps/website/content/CLAUDE.md.template +++ b/apps/website/content/CLAUDE.md.template @@ -24,7 +24,7 @@ Chat Debug has an experimental native React first slice at https://threadplane.a Chat Timeline has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-trace. The first Send creates a conversation lazily; New is local and inert until Send. Refresh checkpoints explicitly requests the recent page with limit 10 and clears selection; successful turns do not refresh it automatically. Selecting a completed root checkpoint loads a separate read-only preview of this graph's strict plain alternating human/assistant transcript. In-progress or invalid checkpoint references are unavailable. Unsupported saved transcripts fail preview validation. Ordinary Send continues the current conversation and retains the validated preview without consuming the draft on selection. Fork from here uses the selected checkpoint and current draft: after A+B, preview A and Send C gives A+B+C; Fork D gives A+D; after confirmation the fork becomes current, the preview clears, and Send E gives A+D+E. Failed or cancelled reads leave the primary conversation usable. Stop or uncertain execution requires New, with no replay, retry or resume. One configured target and header owner serves creation, streams and reads with retries disabled, using the existing shared FREE c-timeline graph. Docs, Code and Run use the same native React implementation; mode navigation preserves the mounted frame and draft, and reload clears local state. Mount and mode changes make no thread requests. Angular remains the default; its Replay/Fork events require host wiring. Candidate packages remain private source builds. Build with `npx nx build cockpit-chat-timeline-react` and verify with `npx nx e2e cockpit-chat-timeline-react`. -Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes MessageList, Markdown, Reasoning, Citations and ChatInput with the existing c-threads graph. The picker and per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Optional titles are literal text bounded to 80 Unicode code points; missing or invalid metadata preserves the fallback or last valid title, and stale title requests cannot affect another selection. Titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no shared search, arbitrary-ID loading, URL routing, rename/delete management, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and optional titles, with retries disabled. Mount and mode changes cause no thread requests; Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. +Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes the connected ThreadSidebar with MessageList, Markdown, Reasoning, Citations and ChatInput over the existing c-threads graph. The sidebar lists the threads saved on the server through a directory from createLangGraphThreadDirectory and offers rename, pin, drag reordering, archive, delete and projects; project names are kept in the LangGraph Store under the namespace ['threadplane', 'projects'], and selecting a project lists only its conversations until it is selected again. Only conversations created and confirmed on the open page can be continued; choosing a listed conversation from an earlier visit shows a notice instead of loading it. Per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Titles are optional server metadata written by the graph; the sidebar shows a fallback when a title is missing, and titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no arbitrary-ID loading, URL routing, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and the sidebar's thread and Store requests, with retries disabled. On mount the sidebar makes read-only thread and Store searches; mount and mode changes create no threads and start no runs. Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. Chat Subagents has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-subagent-card. It uses the existing c-subagents graph with research, booking and itinerary specialists to provide model-generated planning suggestions, without live availability/prices or actual booking. Saved root task calls and literal results stay with the requesting assistant. A separate default-closed Child response observations disclosure retains validated child text locally across root history loads and follow-up turns; these rows are not restored execution history and are not mapped to task cards. Full namespaces identify local observations internally; no parent binding is inferred from role, order or task arguments. Valid empty child text adds no row. Stop and incomplete work label retained observations accordingly, without claiming child execution success. Child errors, interruptions, tools, malformed supplied values, changed completed text and foreign generations permanently withhold continuation for that owner, even if later history clears child snapshots. Only matching terminal saved root evidence permits a follow-up; a fulfilled aborted load does not. New clears local state without remote deletion. Mount, draft seeds and local reset cause no runtime request. Title generation remains metadata-only, the existing shared deployment is reused, Angular remains the default, and candidate packages remain private source builds. 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 ccba96fe9..1de154517 100644 --- a/apps/website/content/docs/angular/chat/guides/thread-routing.mdx +++ b/apps/website/content/docs/angular/chat/guides/thread-routing.mdx @@ -16,7 +16,7 @@ Start with one active-thread value, then decide where it lives: page memory for The Run tab shows the prebuilt `` composition with a thread sidebar beside it. Ask the aviation assistant about a route — a flight from LAX to JFK, for instance — and the backend allocates a thread. The sidebar row starts out labeled `Untitled` and picks up a short generated title once the run finishes. -Press "+ New" above the list to open a second conversation, then move between the rows and watch the transcript swap. Each row also carries a menu with Rename, Archive, and Delete, and every one of those round-trips through the LangGraph Threads API. Archiving a thread moves it out of the top list and into a second one headed Archived, whose rows offer Unarchive, so the round trip is reachable from the page. +Press "New chat" at the top of the sidebar to open a second conversation, then move between the rows and watch the transcript swap. Each row also carries a menu with Rename, Pin, Move to project, Archive, and Delete, and pinned rows can be dragged into a new order. Every one of those round-trips through the LangGraph Threads API, and project names are kept in the LangGraph Store. Archived threads move into a collapsible Archived section whose rows offer Unarchive. ## How it is built @@ -70,40 +70,100 @@ Use a confirmed backend thread: one reported through `onThreadId`, or one create ### The sidebar and the thread list -The `` composition owns the transcript, the input, and the loading and error states, so the template adds the lists beside it. `` can also render a `` of its own, in a sidebar shown at widths of 768px and up whenever its `[threads]` input is non-empty, and it re-emits that list's `threadSelected`. The demo leaves those inputs unbound and mounts explicit lists instead, so that they can carry the row actions shown below: one over `threads()` in the default `active` mode, and a second over `archivedThreads()` in `archived` mode that renders only when something has been archived. +The `` composition owns the transcript, the input, and the loading and error states, so the template adds the sidebar beside it. `` is connected: it takes the adapter's `directory` and draws New chat, Projects, Recent, and Archived with the row commands the directory supports. It refreshes the directory when it mounts, after each row command, and, given `[agent]`, each time a run ends. -Both `` and `` emit `threadSelected`, so either surface can drive the switch. +The sidebar emits `threadSelected` when a row is chosen. The template listens to `(newChat)`, so New chat runs the same handler as the header's "New conversation" button and clears the unsent draft. Selecting a project emits `projectSelected`; the component keeps the selection in a signal bound to `[selectedProjectId]`, so the sidebar lists only that project's conversations until the project is selected again. ### Row actions -`ThreadActionAdapter` is how the list asks the application to perform a rename, an archive, or a delete. The framework owns the row interactions around each call — the inline rename field, the delete confirmation dialog, and the optimistic row update — so the adapter only has to perform the write. +The sidebar performs each row command through the directory. The framework owns the interactions around each call (the inline rename field, the delete confirmation dialog, and the optimistic row update), so the component only handles the one event that changes its own state: the active conversation was deleted. - + -Deleting or archiving the active conversation clears the signal, which returns the surface to its empty state. +Clearing the signal and calling `switchThread(null)` returns the surface to a new chat. -`` builds its menu from the keys the adapter defines, and then filters by mode. The demo's first list runs in the default `active` mode, so it offers Rename, Archive, and Delete; `unarchive` surfaces only in a list rendered with `[mode]="'archived'"`, which is the second list. One adapter serves both. Each adapter method refreshes the store on success, which the framework relies on to clear its optimistic overrides. +The sidebar offers a command only when the directory can perform it, and the `features` input turns built-in commands off. The adapter's directory supports them all. It is owned by the application: the sidebar unsubscribes when it is destroyed but never disposes it. ### Refreshing after a run -The store is a snapshot, not a subscription, so something has to re-fetch it. `refreshOnRunEnd()` calls back on every transition out of the running state, which is precisely when the title node has finished writing. +The store is a snapshot, not a subscription, so something has to re-fetch it. Given `[agent]`, the sidebar refreshes on every transition out of the running state, which is precisely when the title node has finished writing. - + -`refreshOnRunEnd()` must run inside an injection context, because it uses an Angular effect; `refresh()` is a plain async call. +Apps that draw their own list can call `refreshOnRunEnd(agent, () => threads.refresh())` inside an injection context instead. ### Switching and creating -Two handlers close the loop. Selecting a row tells the agent to load that thread and updates the signal; the "+ New" button asks the store for a thread and then activates it. `create()` returns `null` when the request fails, which is why the result is checked before it is used. +Two handlers close the loop. Selecting a row tells the agent to load that thread and updates the signal; New chat in the sidebar and the header's "New conversation" button both ask the store for a thread and then activate it. `create()` returns `null` when the request fails, which is why the result is checked before it is used. 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); + protected readonly projectId = signal(null); + + protected selectProject(id: string | null): void { + this.projectId.update((current) => (current === id ? null : id)); + } +} +``` + +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 is `undefined`, the sidebar hides the Projects section and project commands fail without affecting the thread list. + +`[selectedProjectId]` is controlled by the application. When it holds a project identifier, Recent and Archived list only that project's conversations; `null` lists every conversation. `(projectSelected)` emits the project the user picked so the component above clears the selection when the selected project is picked again. The sidebar lists every conversation when the selected identifier matches no project in the directory, and it emits `(projectSelected)` with `null` after the selected project is deleted from the sidebar. + +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. The adapter's `refresh()` resolves once the thread list is published and loads project names in the background; `directory.refresh()` resolves after both. + +### Refreshing the sidebar 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 abc9c16c0..8b2961566 100644 --- a/apps/website/content/docs/react/chat/guides/thread-routing.mdx +++ b/apps/website/content/docs/react/chat/guides/thread-routing.mdx @@ -11,7 +11,7 @@ The native React APIs on this page are experimental, private source-build packag ## Select an identity before allowing commands -The application holds a page-local collection of confirmed IDs and drafts. Selecting an ID creates a session bound to that conversation and loads saved history; only then can the user continue. Titles are optional labels from metadata, not identifiers or proof that a conversation is ready. This example teaches thread selection without adding a server-wide catalog or URL routing. +The application holds a page-local collection of confirmed IDs and drafts. Selecting an ID creates a session bound to that conversation and loads saved history; only then can the user continue. The sidebar lists the conversations saved on the server, but titles are display metadata, not identifiers or proof that a conversation is ready. This example teaches thread selection without URL routing. The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation-turns) connects this capability to requests, tools, UI state, and saved history. @@ -19,19 +19,87 @@ The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation Choose **Run**, select **Try a question**, then send the draft. The suggestion only fills the composer. The first Send creates a conversation; **New conversation** opens a blank local view and waits for Send before creating another. -The picker contains conversations created while this page is open. Select a saved conversation to restore its messages and draft. Each selection loads its saved history before another message can be sent. New preserves drafts on saved conversations and replaces an unsent blank view. +The connected `ThreadSidebar` lists the server's conversations from a directory built with `createLangGraphThreadDirectory`. Its row menus rename, pin, reorder, archive, delete and move conversations into projects, and project names are kept in the LangGraph Store. Select a conversation created on this page to restore its messages and draft. Each selection loads its saved history before another message can be sent. New preserves drafts on saved conversations and replaces an unsent blank view. -The list and drafts belong to this page. Reloading clears them. This preview has no shared conversation search, arbitrary-ID loading, URL routing, renaming or remote deletion. Angular remains the default on this canonical guide. +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. + +Create the directory and dispose it in the same effect. A directory created in `useState` and disposed in an effect cleanup does not survive React StrictMode: the development double mount runs the cleanup once, and the directory stays disposed for good. The example creates its directory this way. + +~~~tsx +import { useEffect, useState } from 'react'; +import { Client } from '@langchain/langgraph-sdk'; +import type { AgentSession, ThreadDirectory } from '@threadplane/core'; +import { createLangGraphThreadDirectory } from '@threadplane/langgraph'; +import { ThreadSidebar } from '@threadplane/react/chat'; + +export function Conversations(props: { + readonly apiUrl: string; + /** The selected conversation's session, for example from `createSession`. */ + readonly session?: AgentSession; + readonly threadId: string | null; + readonly onThreadChange: (threadId: string | null) => void; +}) { + const { apiUrl, session, threadId, onThreadChange } = props; + const [directory, setDirectory] = useState(null); + const [projectId, setProjectId] = useState(null); + useEffect(() => { + const created = createLangGraphThreadDirectory({ + client: new Client({ apiUrl, callerOptions: { maxRetries: 0 } }), + }); + setDirectory(created); + return () => created.dispose(); + }, [apiUrl]); + if (!directory) return null; + return ( + onThreadChange(null)} + selectedProjectId={projectId} + onProjectSelect={(id) => + setProjectId((current) => (current === id ? null : id)) + } + /> + ); +} +~~~ -## Keep titles optional +The `session` is the `AgentSession` of the selected conversation, such as one returned by `createSession` from `@threadplane/langgraph` for that thread. The example builds a session the same way each time a conversation is selected. + +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 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 snapshot carries no `projects`, the sidebar hides the Projects section and project commands fail without affecting the thread list. + +`selectedProjectId` is controlled by the application. When it holds a project identifier, Recent and Archived list only that project's conversations; `null` or no value lists every conversation. `onProjectSelect` reports the project the user picked, so the snippet above clears the selection when the selected project is picked again. The sidebar lists every conversation when the selected identifier matches no project in the directory, and it calls `onProjectSelect(null)` after the selected project is deleted from the sidebar. -A completed turn or successful selection can fetch a title for its known conversation. Titles are displayed as literal text, limited to 80 Unicode code points. Missing or invalid titles leave the numbered fallback or last valid title in place. A title request does not hold up the composer. +### Refreshing after a run -Changing conversations, sending again, stopping or leaving the page cancels the previous title request. Late title data cannot rename the newly selected conversation. Titles never authorize execution or replace saved-history validation. +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. ## Check saved history before continuing @@ -39,19 +107,19 @@ After each successful stream, the application reads saved history and compares i -Plain local records retain identity, draft, title and confirmed evidence; they do not keep inactive sessions or content stores alive. These checks cover state observed by this page and cannot detect an external change that this page has not read. +Plain local records retain identity, draft and confirmed evidence; they do not keep inactive sessions or content stores alive. These checks cover state observed by this page and cannot detect an external change that this page has not read. ## Stop and recover -While creating, receiving or loading, **Stop** releases the current owner and prevents late responses from restoring its commands. An uncertain conversation is marked unavailable. Other confirmed conversations remain selectable, and **New conversation** can start a separate one after cleanup. There is no retry, replay or resume of uncertain work. +While creating, receiving or loading, **Stop** releases the current owner and prevents late responses from restoring its commands. An uncertain conversation is marked unavailable, and selecting it shows a notice instead of loading it. Other confirmed conversations remain selectable, and **New conversation** can start a separate one after cleanup. There is no retry, replay or resume of uncertain work. Text typed during streaming or saved-history confirmation is kept as the next draft. Selection and cleanup temporarily disable typing. Switching back to a confirmed conversation restores its own draft. -Runtime settings can select a developer LangGraph target. Creation, streams, history and optional title reads use the same target with SDK retries disabled. Creation must confirm the requested thread identity. The shared backend runs c-threads. Docs, Code and Run select the same React implementation; mode navigation preserves the mounted example and draft. +Runtime settings can select a developer LangGraph target. Creation, streams, history and the sidebar's directory requests use the same target with SDK retries disabled. Creation must confirm the requested thread identity. The shared backend runs c-threads. Docs, Code and Run select the same React implementation; mode navigation preserves the mounted example and draft. @@ -64,4 +132,4 @@ npx nx build cockpit-chat-threads-react npx nx e2e cockpit-chat-threads-react ~~~ -The isolated build installs private candidate packages. Browser tests use the real SDK and compiled Python graph with deterministic providers and real saved checkpoints. Test workers and verification endpoints are excluded from public output. Background title generation updates metadata without entering the answer stream. This preview does not claim the Angular thread adapter's search, routing or management features. +The isolated build installs private candidate packages. Browser tests use the real SDK and compiled Python graph with deterministic providers and real saved checkpoints. Test workers and verification endpoints are excluded from public output. Background title generation updates metadata without entering the answer stream. This preview does not claim URL routing or server-side search. 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/apps/website/public/AGENTS.md b/apps/website/public/AGENTS.md index e2c87a1ea..09e3dfa99 100644 --- a/apps/website/public/AGENTS.md +++ b/apps/website/public/AGENTS.md @@ -24,7 +24,7 @@ Chat Debug has an experimental native React first slice at https://threadplane.a Chat Timeline has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-trace. The first Send creates a conversation lazily; New is local and inert until Send. Refresh checkpoints explicitly requests the recent page with limit 10 and clears selection; successful turns do not refresh it automatically. Selecting a completed root checkpoint loads a separate read-only preview of this graph's strict plain alternating human/assistant transcript. In-progress or invalid checkpoint references are unavailable. Unsupported saved transcripts fail preview validation. Ordinary Send continues the current conversation and retains the validated preview without consuming the draft on selection. Fork from here uses the selected checkpoint and current draft: after A+B, preview A and Send C gives A+B+C; Fork D gives A+D; after confirmation the fork becomes current, the preview clears, and Send E gives A+D+E. Failed or cancelled reads leave the primary conversation usable. Stop or uncertain execution requires New, with no replay, retry or resume. One configured target and header owner serves creation, streams and reads with retries disabled, using the existing shared FREE c-timeline graph. Docs, Code and Run use the same native React implementation; mode navigation preserves the mounted frame and draft, and reload clears local state. Mount and mode changes make no thread requests. Angular remains the default; its Replay/Fork events require host wiring. Candidate packages remain private source builds. Build with `npx nx build cockpit-chat-timeline-react` and verify with `npx nx e2e cockpit-chat-timeline-react`. -Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes MessageList, Markdown, Reasoning, Citations and ChatInput with the existing c-threads graph. The picker and per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Optional titles are literal text bounded to 80 Unicode code points; missing or invalid metadata preserves the fallback or last valid title, and stale title requests cannot affect another selection. Titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no shared search, arbitrary-ID loading, URL routing, rename/delete management, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and optional titles, with retries disabled. Mount and mode changes cause no thread requests; Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. +Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes the connected ThreadSidebar with MessageList, Markdown, Reasoning, Citations and ChatInput over the existing c-threads graph. The sidebar lists the threads saved on the server through a directory from createLangGraphThreadDirectory and offers rename, pin, drag reordering, archive, delete and projects; project names are kept in the LangGraph Store under the namespace ['threadplane', 'projects'], and selecting a project lists only its conversations until it is selected again. Only conversations created and confirmed on the open page can be continued; choosing a listed conversation from an earlier visit shows a notice instead of loading it. Per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Titles are optional server metadata written by the graph; the sidebar shows a fallback when a title is missing, and titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no arbitrary-ID loading, URL routing, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and the sidebar's thread and Store requests, with retries disabled. On mount the sidebar makes read-only thread and Store searches; mount and mode changes create no threads and start no runs. Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. Chat Subagents has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-subagent-card. It uses the existing c-subagents graph with research, booking and itinerary specialists to provide model-generated planning suggestions, without live availability/prices or actual booking. Saved root task calls and literal results stay with the requesting assistant. A separate default-closed Child response observations disclosure retains validated child text locally across root history loads and follow-up turns; these rows are not restored execution history and are not mapped to task cards. Full namespaces identify local observations internally; no parent binding is inferred from role, order or task arguments. Valid empty child text adds no row. Stop and incomplete work label retained observations accordingly, without claiming child execution success. Child errors, interruptions, tools, malformed supplied values, changed completed text and foreign generations permanently withhold continuation for that owner, even if later history clears child snapshots. Only matching terminal saved root evidence permits a follow-up; a fulfilled aborted load does not. New clears local state without remote deletion. Mount, draft seeds and local reset cause no runtime request. Title generation remains metadata-only, the existing shared deployment is reused, Angular remains the default, and candidate packages remain private source builds. diff --git a/apps/website/public/CLAUDE.md b/apps/website/public/CLAUDE.md index e2c87a1ea..09e3dfa99 100644 --- a/apps/website/public/CLAUDE.md +++ b/apps/website/public/CLAUDE.md @@ -24,7 +24,7 @@ Chat Debug has an experimental native React first slice at https://threadplane.a Chat Timeline has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-trace. The first Send creates a conversation lazily; New is local and inert until Send. Refresh checkpoints explicitly requests the recent page with limit 10 and clears selection; successful turns do not refresh it automatically. Selecting a completed root checkpoint loads a separate read-only preview of this graph's strict plain alternating human/assistant transcript. In-progress or invalid checkpoint references are unavailable. Unsupported saved transcripts fail preview validation. Ordinary Send continues the current conversation and retains the validated preview without consuming the draft on selection. Fork from here uses the selected checkpoint and current draft: after A+B, preview A and Send C gives A+B+C; Fork D gives A+D; after confirmation the fork becomes current, the preview clears, and Send E gives A+D+E. Failed or cancelled reads leave the primary conversation usable. Stop or uncertain execution requires New, with no replay, retry or resume. One configured target and header owner serves creation, streams and reads with retries disabled, using the existing shared FREE c-timeline graph. Docs, Code and Run use the same native React implementation; mode navigation preserves the mounted frame and draft, and reload clears local state. Mount and mode changes make no thread requests. Angular remains the default; its Replay/Fork events require host wiring. Candidate packages remain private source builds. Build with `npx nx build cockpit-chat-timeline-react` and verify with `npx nx e2e cockpit-chat-timeline-react`. -Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes MessageList, Markdown, Reasoning, Citations and ChatInput with the existing c-threads graph. The picker and per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Optional titles are literal text bounded to 80 Unicode code points; missing or invalid metadata preserves the fallback or last valid title, and stale title requests cannot affect another selection. Titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no shared search, arbitrary-ID loading, URL routing, rename/delete management, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and optional titles, with retries disabled. Mount and mode changes cause no thread requests; Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. +Chat Threads has an experimental native React preview at https://threadplane.ai/docs/react/chat/guides/thread-routing. It composes the connected ThreadSidebar with MessageList, Markdown, Reasoning, Citations and ChatInput over the existing c-threads graph. The sidebar lists the threads saved on the server through a directory from createLangGraphThreadDirectory and offers rename, pin, drag reordering, archive, delete and projects; project names are kept in the LangGraph Store under the namespace ['threadplane', 'projects'], and selecting a project lists only its conversations until it is selected again. Only conversations created and confirmed on the open page can be continued; choosing a listed conversation from an earlier visit shows a notice instead of loading it. Per-conversation drafts last only while the page stays open. Send creates a confirmed thread lazily; selection creates a fresh session fixed to that known identity and checks the exact retained canonical transcript and terminal checkpoint before enabling a follow-up. Every successful turn also requires saved-history confirmation. Titles are optional server metadata written by the graph; the sidebar shows a fallback when a title is missing, and titles never authorize execution. Stop and cleanup detach the owner, prevent late responses from restoring commands, and leave uncertain records unavailable while other confirmed conversations remain usable. There is no arbitrary-ID loading, URL routing, retry, replay or resume. Runtime settings select one target for creation, streams, saved history and the sidebar's thread and Store requests, with retries disabled. On mount the sidebar makes read-only thread and Store searches; mount and mode changes create no threads and start no runs. Docs, Code and Run select the same React implementation. Angular remains the default, the shared deployment is reused, and candidate packages remain private source builds. Build with `npx nx build cockpit-chat-threads-react` and verify with `npx nx e2e cockpit-chat-threads-react`. Chat Subagents has an experimental native React preview at https://threadplane.ai/docs/react/chat/components/chat-subagent-card. It uses the existing c-subagents graph with research, booking and itinerary specialists to provide model-generated planning suggestions, without live availability/prices or actual booking. Saved root task calls and literal results stay with the requesting assistant. A separate default-closed Child response observations disclosure retains validated child text locally across root history loads and follow-up turns; these rows are not restored execution history and are not mapped to task cards. Full namespaces identify local observations internally; no parent binding is inferred from role, order or task arguments. Valid empty child text adds no row. Stop and incomplete work label retained observations accordingly, without claiming child execution success. Child errors, interruptions, tools, malformed supplied values, changed completed text and foreign generations permanently withhold continuation for that owner, even if later history clears child snapshots. Only matching terminal saved root evidence permits a follow-up; a fulfilled aborted load does not. New clears local state without remote deletion. Mount, draft seeds and local reset cause no runtime request. Title generation remains metadata-only, the existing shared deployment is reused, Angular remains the default, and candidate packages remain private source builds. diff --git a/cockpit/chat/threads/angular/e2e/c-threads.spec.ts b/cockpit/chat/threads/angular/e2e/c-threads.spec.ts index 57b91b793..9cb409b2f 100644 --- a/cockpit/chat/threads/angular/e2e/c-threads.spec.ts +++ b/cockpit/chat/threads/angular/e2e/c-threads.spec.ts @@ -1,16 +1,236 @@ -import { test, expect } from '@playwright/test'; +import { randomUUID } from 'node:crypto'; +import { + test, + expect, + type APIRequestContext, + type Locator, + type Page, +} from '@playwright/test'; import { submitAndWaitForResponse } from '@threadplane-internal/e2e-harness'; const PROMPT = 'Hello'; +const PROJECTS = ['threadplane', 'projects']; + +// The dev server proxies /api to the LangGraph dev server, which keeps its +// threads and store items between runs. Each test names what it creates and +// removes it afterwards, so leftovers never reorder another run's list. +const created = { threads: new Set(), projects: new Set() }; + +async function createThread(request: APIRequestContext, title: string) { + const response = await request.post('/api/threads', { + data: { metadata: { title } }, + }); + expect(response.ok()).toBe(true); + const { thread_id } = (await response.json()) as { thread_id: string }; + created.threads.add(thread_id); + return thread_id; +} + +async function readThread(request: APIRequestContext, id: string) { + const response = await request.get(`/api/threads/${id}`); + expect(response.ok()).toBe(true); + return (await response.json()) as { metadata: Record }; +} + +test.afterEach(async ({ request }) => { + for (const id of created.threads) await request.delete(`/api/threads/${id}`); + for (const key of created.projects) + await request.delete('/api/store/items', { + data: { namespace: PROJECTS, key }, + }); + created.threads.clear(); + created.projects.clear(); +}); + +const sidebar = (page: Page) => page.locator('chat-thread-sidebar'); +const recent = (page: Page) => + sidebar(page).locator('chat-thread-list').first(); +const row = (page: Page, title: string): Locator => + recent(page).locator('li').filter({ hasText: title }); +const rowTitles = (page: Page) => + recent(page).locator('li .chat-thread-list__item-title'); + +async function rowCommand(page: Page, title: string, command: string) { + await row(page, title) + .getByRole('button', { name: 'More actions', exact: true }) + .click(); + await page.getByRole('menuitem', { name: command, exact: true }).click(); +} test('c-threads: AI response renders in composed chat surface', async ({ page }) => { const bubble = await submitAndWaitForResponse(page, PROMPT); await expect(bubble).toContainText('chat-threads demo'); }); -test('c-threads: chat-thread-list sidebar is mounted', async ({ page }) => { +test('c-threads: chat-thread-list sidebar is mounted', async ({ + page, + request, +}) => { + // Self-contained: this test creates the thread its list must show. + const title = `Mounted ${randomUUID()}`; + await createThread(request, title); await page.goto('/'); - // Sidebar's distinctive surface — thread switcher seeded with 3 hardcoded - // threads (thread-1/2/3). Existence + non-zero entry count proves wiring. + await expect(page.locator('chat-thread-sidebar')).toBeVisible(); await expect(page.locator('chat-thread-list')).toBeVisible(); + await expect(row(page, title)).toHaveCount(1); +}); + +test('c-threads: a renamed conversation keeps its title after reload', async ({ + page, + request, +}) => { + const original = `Rename me ${randomUUID()}`; + const renamed = `Renamed ${randomUUID()}`; + await createThread(request, original); + await page.goto('/'); + await rowCommand(page, original, 'Rename'); + const input = sidebar(page).getByRole('textbox', { + name: 'Rename conversation', + }); + await input.fill(renamed); + await input.press('Enter'); + await expect(row(page, renamed)).toHaveCount(1); + await page.reload(); + await expect(row(page, renamed)).toHaveCount(1); + await expect(row(page, original)).toHaveCount(0); +}); + +test('c-threads: pinned conversations reorder by drag and keep the order after reload', async ({ + page, + request, +}) => { + const first = `Pin first ${randomUUID()}`; + const second = `Pin second ${randomUUID()}`; + await createThread(request, first); + await createThread(request, second); + await page.goto('/'); + await rowCommand(page, first, 'Pin'); + await expect(row(page, first).locator('.chat-thread-list__item-pin')).toBeVisible(); + await rowCommand(page, second, 'Pin'); + await expect(row(page, second).locator('.chat-thread-list__item-pin')).toBeVisible(); + + const order = async () => { + const titles = await rowTitles(page).allTextContents(); + const at = (title: string) => titles.findIndex((t) => t.includes(title)); + return at(first) < at(second) ? [first, second] : [second, first]; + }; + const [top, bottom] = await order(); + await row(page, bottom).dragTo(row(page, top), { + targetPosition: { x: 20, y: 2 }, + }); + await expect.poll(order).toEqual([bottom, top]); + await page.reload(); + await expect(row(page, top)).toHaveCount(1); + await expect.poll(order).toEqual([bottom, top]); +}); + +test('c-threads: a conversation moved into a new project keeps it after reload', async ({ + page, + request, +}) => { + const title = `Project member ${randomUUID()}`; + const project = `Project ${randomUUID().slice(0, 8)}`; + const id = await createThread(request, title); + await page.goto('/'); + 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, title, '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)); + const projectId = (await readThread(request, id)).metadata['projectId'] as string; + created.projects.add(projectId); + + await page.reload(); + await expect(projectButton).toBeVisible(); + await expect(row(page, title)).toHaveCount(1); + const stored = await request.post('/api/store/items/search', { + data: { namespace_prefix: PROJECTS, limit: 100 }, + }); + const { items } = (await stored.json()) as { + items: { key: string; value: { name: string } }[]; + }; + 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, +}) => { + const createdIds: string[] = []; + page.on('response', async (response) => { + if ( + response.request().method() === 'POST' && + /\/api\/threads$/.test(new URL(response.url()).pathname) && + response.ok() + ) { + const { thread_id } = (await response.json()) as { thread_id: string }; + created.threads.add(thread_id); + createdIds.push(thread_id); + } + }); + await submitAndWaitForResponse(page, PROMPT); + const active = recent(page).locator('li').filter({ + has: page.locator('button[aria-current="true"]'), + }); + await expect(active).toHaveCount(1); + await active.getByRole('button', { name: 'More actions', exact: true }).click(); + await page.getByRole('menuitem', { name: 'Delete', exact: true }).click(); + await page + .locator('chat-confirm-dialog') + .getByRole('button', { name: 'Delete', exact: true }) + .click(); + + await expect(sidebar(page).locator('button[aria-current="true"]')).toHaveCount(0); + await expect(page.locator('chat-message')).toHaveCount(0); + await expect(page.getByRole('textbox', { name: /message|prompt/i })).toBeEnabled(); + expect(createdIds).toHaveLength(1); + expect((await request.get(`/api/threads/${createdIds[0]}`)).status()).toBe(404); }); diff --git a/cockpit/chat/threads/angular/src/app/threads.component.ts b/cockpit/chat/threads/angular/src/app/threads.component.ts index 085c434df..fb14feda0 100644 --- a/cockpit/chat/threads/angular/src/app/threads.component.ts +++ b/cockpit/chat/threads/angular/src/app/threads.component.ts @@ -1,11 +1,7 @@ import { injectCockpitRuntimeConnection } from '@threadplane/cockpit-telemetry'; import { Component, inject, signal } from '@angular/core'; -import { - ChatComponent, - ChatThreadListComponent, - type ThreadActionAdapter, -} from '@threadplane/chat'; -import { injectAgent, provideAgent, LangGraphThreadsAdapter, refreshOnRunEnd } from '@threadplane/langgraph'; +import { ChatComponent, ChatThreadSidebarComponent } from '@threadplane/chat'; +import { injectAgent, provideAgent, LangGraphThreadsAdapter } from '@threadplane/langgraph'; import { ExampleChatLayoutComponent } from '@threadplane/example-layouts'; // #region active-thread-signal @@ -19,9 +15,11 @@ export const activeThreadIdState = signal(null); /** * ThreadsComponent demonstrates multi-thread conversation management - * backed by the real LangGraph SDK. Consumes the shared - * LangGraphThreadsAdapter from `@threadplane/langgraph` — same service the - * canonical demo uses. Reads `metadata.title` written by this cap's + * backed by the real LangGraph SDK. Passes the shared + * LangGraphThreadsAdapter's `directory` from `@threadplane/langgraph` to + * the connected ``, which lists, renames, pins, + * reorders, archives, deletes and files threads into projects (project names + * live in the LangGraph Store). Reads `metadata.title` written by this cap's * `generate_title` graph node (spec * 2026-05-19-llm-generated-labels-design.md, converged on `title` * after the original `thread_title` choice). See app.config.ts for @@ -30,7 +28,7 @@ export const activeThreadIdState = signal(null); @Component({ selector: 'app-threads', standalone: true, - imports: [ChatComponent, ChatThreadListComponent, ExampleChatLayoutComponent], + imports: [ChatComponent, ChatThreadSidebarComponent, ExampleChatLayoutComponent], // #region agent-provider // Scoped agent (Option B): threadId + onThreadId are per-instance, so the // agent is provided at the component rather than in app.config.ts. @@ -57,7 +55,7 @@ export const activeThreadIdState = signal(null); @@ -65,77 +63,26 @@ export const activeThreadIdState = signal(null);

Enter to send. Shift+Enter adds a new line.

{{ agent.isLoading() ? 'Receiving response…' : agent.error() ? 'Response failed. Try again.' : 'Ready.' }}

-
-
-

Threads

- -
- - - @if (threadsSvc.archivedThreads().length) { -

Archived

- - } -
+ + `, styles: [` .panel { - display: flex; - flex-direction: column; - gap: 0.75rem; padding: 1rem; background: var(--tplane-chat-bg); color: var(--tplane-chat-text); } - - .panel-header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - } - - .cap { - margin: 0; - color: var(--tplane-chat-text-muted); - font-size: var(--tplane-chat-font-size-xs); - font-weight: 700; - letter-spacing: 0.12em; - line-height: var(--tplane-chat-line-height-tight); - text-transform: uppercase; - } - - .action-button { - padding: 0; - border: 0; - background: transparent; - color: var(--tplane-chat-text-muted); - cursor: pointer; - font: inherit; - font-size: var(--tplane-chat-font-size-xs); - line-height: var(--tplane-chat-line-height-tight); - text-decoration: underline; - text-underline-offset: 2px; - } - - .action-button:hover { - color: var(--tplane-chat-text); - } `], }) export class ThreadsComponent { @@ -147,34 +94,30 @@ 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 - /** Action adapter: framework calls these on rename / delete / archive - * after confirmation. Adapter handles SDK round-trip + refresh. */ - protected readonly threadActions: ThreadActionAdapter = { - delete: async (id) => { - await this.threadsSvc.delete(id); - if (this.activeThreadId() === id) this.activeThreadId.set(null); - }, - rename: (id, title) => this.threadsSvc.rename(id, title), - archive: async (id) => { - await this.threadsSvc.archive(id); - if (this.activeThreadId() === id) this.activeThreadId.set(null); - }, - unarchive: (id) => this.threadsSvc.unarchive(id), - }; + /** Row commands go through `threadsSvc.directory`; the sidebar reports + * when the active thread was deleted so the surface returns to a new chat. */ + protected onActiveThreadRemoved(conversation?: ChatComponent): void { + this.agent.switchThread(null); + this.activeThreadId.set(null); + conversation?.clearDraft(); + } // #endregion // #region refresh-on-run-end - constructor() { - // Initial fetch. - void this.threadsSvc.refresh(); - - // Re-fetch when an agent run completes. The graph's generate_title - // node writes metadata.title on the first turn; refreshing - // on the running→idle transition surfaces it in the sidenav - // without a manual reload. - refreshOnRunEnd(this.agent, () => this.threadsSvc.refresh()); - } + // No manual refresh: refreshes the directory on + // mount and whenever [agent] leaves the running state, which is when the + // graph's generate_title node has written metadata.title. // #endregion // #region switch-and-create diff --git a/cockpit/chat/threads/react/e2e/mobile.spec.ts b/cockpit/chat/threads/react/e2e/mobile.spec.ts index 65cdebaa1..22a8f9666 100644 --- a/cockpit/chat/threads/react/e2e/mobile.spec.ts +++ b/cockpit/chat/threads/react/e2e/mobile.spec.ts @@ -15,7 +15,8 @@ test('mobile A/B/A preserves drafts and a usable transcript after viewport reduc }); const picker = page .getByRole('navigation', { name: 'Conversations' }) - .getByRole('button'); + .getByRole('list', { name: 'Recent' }) + .locator('.tp-thread-list__button'); await input().fill('A first'); await input().press('Enter'); await expect(page.getByRole('status')).toHaveText('Response saved.'); diff --git a/cockpit/chat/threads/react/e2e/threads.spec.ts b/cockpit/chat/threads/react/e2e/threads.spec.ts index f08d6a750..495caf639 100644 --- a/cockpit/chat/threads/react/e2e/threads.spec.ts +++ b/cockpit/chat/threads/react/e2e/threads.spec.ts @@ -20,8 +20,12 @@ type Wire = { }; const base = '/chat/threads/react/'; const box = (page: Page) => page.getByLabel('Message', { exact: true }); +// Conversation rows of the connected sidebar (not New chat or row menus). const picker = (page: Page) => - page.getByRole('navigation', { name: 'Conversations' }).getByRole('button'); + page + .getByRole('navigation', { name: 'Conversations' }) + .getByRole('list', { name: 'Recent' }) + .locator('.tp-thread-list__button'); const conversation = (page: Page) => page.getByRole('region', { name: 'Conversation', exact: true }); async function submit(page: Page, text: string) { @@ -44,6 +48,26 @@ async function titleReads(request: APIRequestContext, count: number) { ) .toBe(count); } +const notice = (page: Page) => page.locator('.conversation-notice'); +const UNAVAILABLE = + 'This conversation could not be confirmed and cannot be continued here.'; +const EARLIER_VISIT = + 'This conversation was saved on an earlier visit and cannot be continued here.'; +/** A row the page cannot continue: the click explains why and sends nothing. */ +async function refused( + page: Page, + request: APIRequestContext, + row: ReturnType, + message: string +) { + const before = ((await (await request.get('/__requests')).json()) as Wire[]) + .length; + await row.click(); + await expect(notice(page)).toHaveText(message); + expect( + ((await (await request.get('/__requests')).json()) as Wire[]).length + ).toBe(before); +} async function blocked(page: Page) { await expect(page.getByRole('status')).toHaveText( 'Choose another conversation or start a new one.' @@ -99,14 +123,12 @@ test('installed SDK switches A/B/A and extends only the selected saved conversat await expect(conversation(page).locator('article')).toHaveCount(2); await expect(conversation(page)).toContainText('A first'); await expect(conversation(page)).not.toContainText('B first'); - await titleReads(request, 3); await submit(page, 'A followup'); await saved(page); await expect(conversation(page).locator('article')).toHaveCount(4); await expect(conversation(page)).toContainText('A first'); await expect(conversation(page)).toContainText('A followup'); await expect(conversation(page).locator('pre code')).toHaveCount(2); - await titleReads(request, 4); await page.screenshot({ path: testInfo.outputPath('threads-desktop.png'), fullPage: true, @@ -120,15 +142,9 @@ test('installed SDK switches A/B/A and extends only the selected saved conversat await expect(conversation(page)).not.toContainText( 'Authored conversation title' ); - await expect(picker(page).nth(1)).toHaveAttribute('aria-pressed', 'true'); - await expect - .poll( - async () => - ((await (await request.get('/__requests')).json()) as Wire[]).filter( - (item) => item.method === 'GET' && /\/threads\/[^/]+$/.test(item.path) - ).length - ) - .toBe(5); + await expect(picker(page).nth(1)).toHaveAttribute('aria-current', 'true'); + // Titles come from the sidebar's directory, so the page never reads one. + await titleReads(request, 0); const wire: Wire[] = await (await request.get('/__requests')).json(); const creates = wire.filter((item) => item.path.endsWith('/threads')); const runs = wire.filter((item) => item.path.endsWith('/runs/stream')); @@ -193,6 +209,18 @@ test('mount, prompt fill and New perform no runtime request', async ({ await expect(box(page)).toHaveValue(''); await expect(picker(page)).toHaveCount(0); expect(await (await request.get('/__requests')).json()).toEqual([]); + // The sidebar only reads the server's lists on mount. + const directory: Wire[] = await ( + await request.get('/__directory-requests') + ).json(); + expect(directory.length).toBeGreaterThan(0); + expect( + directory.every( + (item) => + item.method === 'POST' && + ['/api/threads/search', '/api/store/items/search'].includes(item.path) + ) + ).toBe(true); }); test('draft typed while saved history is held survives confirmation', async ({ page, @@ -209,8 +237,9 @@ test('draft typed while saved history is held survives confirmation', async ({ await saved(page); await expect(box(page)).toHaveValue('Next draft'); }); -for (const mode of ['missing', 'wrong-thread', 'invalid', 'titlefailure']) { - test(`optional ${mode} title retains fallback without withholding continuation`, async ({ +// The sidebar shows the server's title; a missing or malformed one falls back. +for (const mode of ['missing', 'invalid']) { + test(`server ${mode} title falls back in the sidebar without withholding continuation`, async ({ page, request, }) => { @@ -218,20 +247,12 @@ for (const mode of ['missing', 'wrong-thread', 'invalid', 'titlefailure']) { await page.goto(base); await submit(page, 'First'); await saved(page); - await expect - .poll( - async () => - ((await (await request.get('/__requests')).json()) as Wire[]).filter( - (item) => - item.method === 'GET' && /\/threads\/[^/]+$/.test(item.path) - ).length - ) - .toBe(1); - await expect(picker(page).first()).toHaveText('Conversation 1'); + await expect(picker(page).first()).toHaveText('Untitled conversation'); await submit(page, 'Second'); await saved(page); await expect(conversation(page).locator('article')).toHaveCount(4); - await expect(picker(page).first()).toHaveText('Conversation 1'); + await expect(picker(page).first()).toHaveText('Untitled conversation'); + await titleReads(request, 0); }); } for (const mode of ['changed', 'missing', 'pending', 'foreign', 'failure']) { @@ -248,7 +269,9 @@ for (const mode of ['changed', 'missing', 'pending', 'foreign', 'failure']) { wire.filter((item) => item.path.endsWith('/runs/stream')) ).toHaveLength(1); expect(wire.filter((item) => item.body.command)).toHaveLength(0); - await expect(picker(page).first()).toBeDisabled(); + // The quarantined conversation cannot be reopened from the sidebar. + await refused(page, request, picker(page).first(), UNAVAILABLE); + await blocked(page); }); } test('cancelled selection quarantines A while independently saved B remains usable', async ({ @@ -271,7 +294,8 @@ test('cancelled selection quarantines A while independently saved B remains usab await blocked(page); await request.post('/__release-history'); await request.post('/__history/safe'); - await expect(picker(page).nth(0)).toBeDisabled(); + await refused(page, request, picker(page).nth(0), UNAVAILABLE); + await blocked(page); await picker(page).nth(1).click(); await loaded(page); await expect(box(page)).toHaveValue('B retained draft'); @@ -314,84 +338,6 @@ test('actual graph failure is generic and never confirms or replays', async ({ ).toHaveLength(1); expect(wire.filter((item) => item.path.endsWith('/history'))).toHaveLength(0); }); -test('held title does not block a new conversation and cannot relabel it after release', async ({ - page, - request, -}) => { - await request.post('/__hold-title'); - await page.goto(base); - await submit(page, 'A first'); - await saved(page); - await expect - .poll( - async () => (await (await request.get('/__lifetime')).json()).activeTitle - ) - .toBe(true); - await expect(picker(page).first()).toHaveText('Conversation 1'); - await newConversation(page); - await expect - .poll( - async () => (await (await request.get('/__lifetime')).json()).activeTitle - ) - .toBe(false); - await request.post('/__release-title'); - await submit(page, 'B first'); - await saved(page); - await expect(picker(page).nth(1)).toHaveText('Authored conversation title'); - await expect(picker(page).first()).toHaveText('Conversation 1'); -}); -test('a late title from selected A cannot relabel B after switching', async ({ - page, - request, -}) => { - await page.goto(base); - await submit(page, 'A first'); - await saved(page); - await expect(picker(page).first()).toHaveText('Authored conversation title'); - await newConversation(page); - await submit(page, 'B first'); - await saved(page); - await expect(picker(page).nth(1)).toHaveText('Authored conversation title'); - await request.post('/__title/literal'); - await request.post('/__hold-title'); - await picker(page).first().click(); - await loaded(page); - await expect - .poll( - async () => (await (await request.get('/__lifetime')).json()).activeTitle - ) - .toBe(true); - await request.post('/__title/safe'); - await picker(page).nth(1).click(); - await loaded(page); - await request.post('/__release-title'); - await expect(picker(page).nth(1)).toHaveAttribute('aria-pressed', 'true'); - await expect(picker(page).nth(1)).toHaveText('Authored conversation title'); - await expect(picker(page).first()).toHaveText('Authored conversation title'); - await expect(conversation(page)).toContainText('B first'); - await expect(conversation(page)).not.toContainText('A first'); -}); -test('failed metadata refresh retains the last valid title', async ({ - page, - request, -}) => { - await page.goto(base); - await submit(page, 'First'); - await saved(page); - await expect(picker(page).first()).toHaveText('Authored conversation title'); - await request.post('/__title/titlefailure'); - await submit(page, 'Second'); - await saved(page); - await expect - .poll( - async () => - ((await (await request.get('/__requests')).json()) as Wire[]).filter( - (item) => item.method === 'GET' && /\/threads\/[^/]+$/.test(item.path) - ).length - ) - .toBe(2); - await expect(picker(page).first()).toHaveText('Authored conversation title'); -}); test('literal title markup remains button text', async ({ page, request }) => { await request.post('/__title/literal'); await page.goto(base); @@ -410,11 +356,8 @@ test('long optional title is bounded and wraps on mobile', async ({ await page.goto(base); await submit(page, 'First'); await saved(page); - await expect - .poll( - async () => [...((await picker(page).first().textContent()) ?? '')].length - ) - .toBe(80); + // The sidebar shows the full server title without widening the page. + await expect(picker(page).first()).toHaveText(/^Long authored title/); expect( await page.evaluate( () => document.documentElement.scrollWidth <= innerWidth @@ -443,7 +386,8 @@ test('Stop fences held streaming and preserves other records', async ({ await page.getByRole('button', { name: 'Stop', exact: true }).click(); await blocked(page); await request.post('/__release'); - await expect(picker(page).nth(1)).toBeDisabled(); + await refused(page, request, picker(page).nth(1), UNAVAILABLE); + await blocked(page); await picker(page).first().click(); await loaded(page); await expect(conversation(page)).toContainText('A first'); @@ -453,7 +397,7 @@ test('Stop fences held streaming and preserves other records', async ({ wire.filter((item) => item.path.endsWith('/runs/stream')) ).toHaveLength(2); }); -for (const kind of ['history', 'title', 'stream']) { +for (const kind of ['history', 'stream']) { test(`page disposal aborts held ${kind} without replay`, async ({ page, request, @@ -498,7 +442,7 @@ test('worker failure stays generic and is not retried', async ({ ).toHaveLength(1); expect(wire.filter((item) => item.path.endsWith('/history'))).toHaveLength(0); }); -test('developer endpoint credentials stay in headers for creation, stream, history and title', async ({ +test('developer endpoint credentials stay in headers for creation, stream, history and the sidebar', async ({ page, request, }) => { @@ -522,10 +466,13 @@ test('developer endpoint credentials stay in headers for creation, stream, histo await frame.getByRole('button', { name: 'Send', exact: true }).click(); await expect(frame.getByRole('status')).toHaveText('Response saved.'); await expect( - frame.getByRole('navigation', { name: 'Conversations' }).getByRole('button') + frame + .getByRole('navigation', { name: 'Conversations' }) + .getByRole('list', { name: 'Recent' }) + .locator('.tp-thread-list__button') ).toHaveText('Authored conversation title'); const wire: Wire[] = await (await request.get('/__requests')).json(); - expect(wire).toHaveLength(5); + expect(wire).toHaveLength(4); expect( wire.every( (item) => @@ -537,4 +484,224 @@ test('developer endpoint credentials stay in headers for creation, stream, histo 'TEST_DEVELOPER_KEY' ); await expect(frame.locator('body')).not.toContainText('TEST_DEVELOPER_KEY'); + const directory: Wire[] = await ( + await request.get('/__directory-requests') + ).json(); + expect(directory.length).toBeGreaterThan(0); + expect( + directory.every( + (item) => + item.path.startsWith('/developer-api/') && + item.key === 'TEST_DEVELOPER_KEY' + ) + ).toBe(true); +}); +const sidebarRows = picker; +// Row titles without the visually hidden "Pinned conversation" note. +const rowTitles = (page: Page) => () => + sidebarRows(page).evaluateAll((rows) => + rows.map((row) => row.getAttribute('title')) + ); +const projectButton = (page: Page, name: string) => + page + .getByRole('navigation', { name: 'Conversations' }) + .getByRole('list', { name: 'Projects' }) + .getByRole('button', { name, exact: true }); +async function rowCommand(page: Page, title: string, command: string) { + await page + .getByRole('button', { name: `More actions for ${title}`, exact: true }) + .click(); + await page.getByRole('menuitem', { name: command, exact: true }).click(); +} +async function createdThreads(request: APIRequestContext) { + const wire: Wire[] = await (await request.get('/__requests')).json(); + return wire + .filter((item) => item.method === 'POST' && item.path.endsWith('/threads')) + .map((item) => item.body.thread_id as string); +} +type ServerThread = { thread_id: string; metadata: Record }; +async function serverThreads(request: APIRequestContext) { + const response = await request.post('/api/threads/search', { + data: { limit: 50, offset: 0 }, + }); + expect(response.status()).toBe(200); + return (await response.json()) as ServerThread[]; +} + +test('sidebar rename persists on the server and survives reload', async ({ + page, + request, +}) => { + await page.goto(base); + await submit(page, 'A first'); + await saved(page); + await expect(sidebarRows(page)).toHaveText(['Authored conversation title']); + await rowCommand(page, 'Authored conversation title', 'Rename'); + const title = page.getByLabel('Conversation title', { exact: true }); + await title.fill('Renamed A'); + await title.press('Enter'); + await expect(sidebarRows(page)).toHaveText(['Renamed A']); + await page.reload(); + await expect(sidebarRows(page)).toHaveText(['Renamed A']); + // Listed after reload, but only conversations confirmed on this page open. + await refused(page, request, sidebarRows(page).first(), EARLIER_VISIT); + await expect(page.getByRole('status')).toHaveText('Ready.'); + const [thread] = await serverThreads(request); + expect(thread.metadata['title']).toBe('Renamed A'); +}); + +test('sidebar pins two conversations, reorders them by drag and keeps the order after reload', 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(); + await expect(sidebarRows(page)).toHaveText(['Alpha', 'Beta']); + await rowCommand(page, 'Alpha', 'Pin'); + await rowCommand(page, 'Beta', 'Pin'); + await expect.poll(rowTitles(page)).toEqual(['Alpha', 'Beta']); + const rows = page + .getByRole('navigation', { name: 'Conversations' }) + .getByRole('list', { name: 'Recent' }) + .locator('li'); + await rows.nth(1).dragTo(rows.nth(0), { targetPosition: { x: 20, y: 2 } }); + await expect.poll(rowTitles(page)).toEqual(['Beta', 'Alpha']); + await page.reload(); + await expect.poll(rowTitles(page)).toEqual(['Beta', 'Alpha']); + const pinned = await serverThreads(request); + expect( + pinned.every((thread) => thread.metadata['pinned'] === true) + ).toBe(true); +}); + +test('sidebar creates a project, moves a conversation into it and keeps both after reload', async ({ + page, + request, +}) => { + await page.goto(base); + await submit(page, 'A first'); + await saved(page); + 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 expect(projectButton(page, 'Research')).toBeVisible(); + await rowCommand(page, 'Authored conversation title', 'Move to project'); + await page.getByRole('menuitem', { name: 'Research', exact: true }).click(); + await expect + .poll(async () => (await serverThreads(request))[0]?.metadata['projectId']) + .toEqual(expect.any(String)); + await page.reload(); + await expect(projectButton(page, 'Research')).toBeVisible(); + await expect(sidebarRows(page)).toHaveText(['Authored conversation title']); + const store = (await ( + await request.post('/api/store/items/search', { + data: { namespace_prefix: ['threadplane', 'projects'], limit: 100 }, + }) + ).json()) as { items: { key: string; value: { name: string } }[] }; + const [thread] = await serverThreads(request); + expect(store.items).toEqual([ + expect.objectContaining({ + key: thread.metadata['projectId'], + value: { name: 'Research' }, + }), + ]); +}); + +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, +}) => { + await page.goto(base); + await submit(page, 'A first'); + await saved(page); + await expect(sidebarRows(page).first()).toHaveAttribute( + 'aria-current', + 'true' + ); + await rowCommand(page, 'Authored conversation title', 'Delete'); + await page + .getByRole('alertdialog', { name: 'Delete conversation?' }) + .getByRole('button', { name: 'Delete', exact: true }) + .click(); + await expect(sidebarRows(page)).toHaveCount(0); + await expect(page.getByRole('status')).toHaveText('Ready.'); + await expect(conversation(page).locator('article')).toHaveCount(0); + await expect(box(page)).toBeEnabled(); + await expect(box(page)).toHaveValue(''); + expect(await serverThreads(request)).toEqual([]); }); diff --git a/cockpit/chat/threads/react/src/app.spec.tsx b/cockpit/chat/threads/react/src/app.spec.tsx index 82afbc40e..13bb3d6e8 100644 --- a/cockpit/chat/threads/react/src/app.spec.tsx +++ b/cockpit/chat/threads/react/src/app.spec.tsx @@ -3,10 +3,19 @@ import { afterEach, beforeAll, afterAll, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render } from '@testing-library/react'; import { createMessageContent } from '@threadplane/content/messages'; import { createThreadsApplication, type ThreadsSnapshot } from './application'; -import { createThreadsClient } from './connection'; +import type { ThreadDirectory, ThreadEntry } from '@threadplane/core'; +import { createThreadsClient, createThreadsDirectory } from './connection'; vi.mock('./application', () => ({ createThreadsApplication: vi.fn() })); -vi.mock('./connection', () => ({ createThreadsClient: vi.fn() })); -import { ThreadsDemo, renderMessage } from './app'; +vi.mock('./connection', () => ({ + createThreadsClient: vi.fn(), + createThreadsDirectory: vi.fn(), +})); +import { + EARLIER_VISIT_NOTICE, + ThreadsDemo, + UNAVAILABLE_NOTICE, + renderMessage, +} from './app'; const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean; }; @@ -70,17 +79,40 @@ function fakeApp() { }; return { app, update }; } -function composition() { +function fakeDirectory(threads: ThreadEntry[] = []) { + const snapshot = Object.freeze({ + threads: Object.freeze(threads), + archived: Object.freeze([]), + status: 'idle' as const, + }); + const directory = { + getSnapshot: () => snapshot, + subscribe: () => () => undefined, + refresh: vi.fn(async () => undefined), + dispose: vi.fn(), + } satisfies ThreadDirectory; + return directory; +} +const entry = (id: string, title: string): ThreadEntry => ({ + id, + title, + pinned: false, + archived: false, + projectId: null, +}); +function composition(threads: ThreadEntry[] = []) { const h = fakeApp(), - onReady = vi.fn(); + onReady = vi.fn(), + directory = fakeDirectory(threads); vi.mocked(createThreadsApplication).mockReturnValue(h.app); + vi.mocked(createThreadsDirectory).mockReturnValue(directory); const connection = { apiUrl: 'https://authored.invalid', headers: {} }; const view = render( ); const box = () => view.getByRole('textbox', { name: 'Message' }) as HTMLTextAreaElement; - return { ...h, view, box, onReady, connection }; + return { ...h, view, box, onReady, connection, directory }; } it('renders the native text, reasoning, citations and Markdown composition', () => { const content = createMessageContent(), @@ -130,77 +162,53 @@ it('mounts ready and fills a draft without remote execution', () => { const h = composition(); expect(h.onReady).toHaveBeenCalledOnce(); expect(createThreadsClient).toHaveBeenCalledWith(h.connection); + expect(createThreadsDirectory).toHaveBeenCalledWith(h.connection); expect(h.view.getByRole('status').textContent).toBe('Ready.'); fireEvent.click(h.view.getByRole('button', { name: 'Try a question' })); expect(h.box().value).toBe( 'Explain how saved conversations work in two sentences.' ); expect(h.app.submit).not.toHaveBeenCalled(); - expect(h.view.getByText(/list and drafts last/i)).toBeTruthy(); + expect(h.view.getByText(/their drafts last/i)).toBeTruthy(); fireEvent.keyDown(h.box(), { key: 'Enter' }); expect(h.app.submit).toHaveBeenCalledExactlyOnceWith( 'Explain how saved conversations work in two sentences.' ); expect(h.box().value).toBe(''); }); -it('renders literal optional titles and marks unavailable records clearly', () => { - const h = composition(), - base = { - ordinal: 1, - draft: '', - canonical: null, - generations: [], - version: 0, - }; - act(() => - h.update({ - selectedKey: 'a', - threadId: 'A', - conversations: [ - { - ...base, - key: 'a', - threadId: 'A', - label: 'Literal title', - availability: 'available', - }, - { - ...base, - key: 'b', - threadId: 'B', - label: 'Conversation 2', - availability: 'unavailable', - }, - ], - }) - ); +it('renders literal server titles and marks the active conversation', () => { + const h = composition([ + entry('A', 'Literal title'), + entry('B', 'Conversation 2'), + ]); + act(() => h.update({ selectedKey: 'a', threadId: 'A' })); const selected = h.view.getByRole('button', { name: 'Literal title' }); - expect(selected.getAttribute('aria-pressed')).toBe('true'); + expect(selected.getAttribute('aria-current')).toBe('true'); expect(selected.querySelector('b')).toBeNull(); expect( - ( - h.view.getByRole('button', { - name: 'Conversation 2 (unavailable)', - }) as HTMLButtonElement - ).disabled - ).toBe(true); + h.view + .getByRole('button', { name: 'Conversation 2' }) + .getAttribute('aria-current') + ).toBeNull(); }); -it('uses known local record keys for selection and preserves the controlled draft', () => { - const h = composition(), - entry = { +it('selects only conversations confirmed on this page and preserves the controlled draft', () => { + const h = composition([entry('A', 'Conversation 1'), entry('X', 'Elsewhere')]), + record = { key: 'a', threadId: 'A', ordinal: 1, - label: 'Conversation 1', availability: 'available' as const, draft: 'A draft', canonical: null, generations: [], - version: 0, }; - act(() => h.update({ conversations: [entry], draft: 'B draft' })); + act(() => h.update({ conversations: [record], draft: 'B draft' })); + fireEvent.click(h.view.getByRole('button', { name: 'Elsewhere' })); + expect(h.app.select).not.toHaveBeenCalled(); + expect(h.view.getByText(EARLIER_VISIT_NOTICE)).toBeTruthy(); fireEvent.click(h.view.getByRole('button', { name: 'Conversation 1' })); expect(h.app.select).toHaveBeenCalledExactlyOnceWith('a'); + expect(h.view.queryByText(EARLIER_VISIT_NOTICE)).toBeNull(); act(() => h.update({ selectedKey: 'a', @@ -213,6 +221,25 @@ it('uses known local record keys for selection and preserves the controlled draf ); expect(h.box().value).toBe('A draft'); expect(h.view.getByRole('status').textContent).toBe('Conversation loaded.'); + expect(h.directory.refresh).toHaveBeenCalled(); +}); +it('marks an unavailable record clearly and never selects it', () => { + const h = composition([entry('B', 'Conversation 2')]), + record = { + key: 'b', + threadId: 'B', + ordinal: 2, + availability: 'unavailable' as const, + draft: '', + canonical: null, + generations: [], + }; + act(() => h.update({ conversations: [record] })); + fireEvent.click(h.view.getByRole('button', { name: 'Conversation 2' })); + expect(h.app.select).not.toHaveBeenCalled(); + expect(h.view.getByText(UNAVAILABLE_NOTICE)).toBeTruthy(); + act(() => h.update({ viewGeneration: 1 })); + expect(h.view.queryByText(UNAVAILABLE_NOTICE)).toBeNull(); }); it('keeps Stop available while loading and prevents changing the selected record', () => { const h = composition(); @@ -273,4 +300,5 @@ it('creates a fresh application lifetime when the runtime target changes', () => expect(h.view.container.textContent).not.toContain('fictional-next'); h.view.unmount(); expect(next.app.dispose).toHaveBeenCalledOnce(); + expect(h.directory.dispose).toHaveBeenCalled(); }); diff --git a/cockpit/chat/threads/react/src/app.tsx b/cockpit/chat/threads/react/src/app.tsx index bca9c5bf4..18d706711 100644 --- a/cockpit/chat/threads/react/src/app.tsx +++ b/cockpit/chat/threads/react/src/app.tsx @@ -7,10 +7,16 @@ import { MessageList, Reasoning, Citations, + ThreadSidebar, } from '@threadplane/react/chat'; import { Markdown } from '@threadplane/react/markdown'; import type { MessageRow } from '@threadplane/content/messages'; -import { createThreadsClient, type ThreadsConnection } from './connection'; +import type { ThreadDirectory } from '@threadplane/core'; +import { + createThreadsClient, + createThreadsDirectory, + type ThreadsConnection, +} from './connection'; import { createThreadsApplication } from './application'; /** Render existing native content stores without retaining them outside their session owner. */ @@ -32,6 +38,11 @@ export function renderMessage(row: MessageRow) { ); } +/** Shown when a listed conversation cannot be opened on this page. */ +export const UNAVAILABLE_NOTICE = + 'This conversation could not be confirmed and cannot be continued here.'; +export const EARLIER_VISIT_NOTICE = + 'This conversation was saved on an earlier visit and cannot be continued here.'; type Props = { readonly connection: ThreadsConnection; readonly onReady: () => void; @@ -53,7 +64,19 @@ function ThreadsOwner({ connection, onReady }: Props) { const [application] = useState(() => createThreadsApplication(createThreadsClient(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. + useEffect(() => setNotice(null), [snapshot.viewGeneration]); useEffect(() => { onReady(); }, [onReady]); @@ -63,6 +86,17 @@ function ThreadsOwner({ connection, onReady }: Props) { }, [application] ); + // 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. + const confirmedThreads = snapshot.conversations + .map((record) => record.threadId) + .join(' '); + useEffect(() => { + if (!directory) return; + if (!confirmedThreads && snapshot.confirmation === null) return; + directory.refresh().catch(() => undefined); + }, [directory, confirmedThreads, snapshot.confirmation]); const status = snapshot.busy ? snapshot.activity === 'creating' ? 'Creating conversation…' @@ -115,28 +149,46 @@ function ThreadsOwner({ connection, onReady }: Props) {

- Switch between conversations created on this page. The list and drafts - last while this page stays open; saved history is checked before - continuing. Titles are optional. + The sidebar lists the conversations saved on the server: rename, pin, + 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.

{ 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 46ee4fb0c..dad48b070 100644 --- a/cockpit/chat/threads/react/src/connection.ts +++ b/cockpit/chat/threads/react/src/connection.ts @@ -1,6 +1,9 @@ import { Client } from '@langchain/langgraph-sdk'; -import { createSession } from '@threadplane/langgraph'; -import type { AgentSession } from '@threadplane/core'; +import { + createLangGraphThreadDirectory, + createSession, +} from '@threadplane/langgraph'; +import type { AgentSession, ThreadDirectory } from '@threadplane/core'; import type { ThreadsState } from './authority'; // eslint-disable-next-line @nx/enforce-module-boundaries -- Internal bridge is copied by the isolated build. import type { RuntimeBridgeConfiguration } from '../../../../../libs/cockpit-runtime-bridge/src/index'; @@ -15,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): { @@ -108,14 +110,22 @@ 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; - } - }, }; } +/** + * The sidebar's thread directory: the server's thread list, row commands and + * Store API project names on the same target and headers, never retried. + */ +export function createThreadsDirectory( + connection: ThreadsConnection +): ThreadDirectory { + return createLangGraphThreadDirectory({ + client: new Client({ + apiUrl: connection.apiUrl, + apiKey: null, + defaultHeaders: connection.headers, + callerOptions: { maxRetries: 0 }, + }), + titleFallback: 'Untitled conversation', + }); +} 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 1c44d169a..29a048ebf 100644 --- a/cockpit/chat/threads/react/src/styles.css +++ b/cockpit/chat/threads/react/src/styles.css @@ -54,35 +54,15 @@ body { flex: 1; } .conversation-picker { - display: flex; - flex-direction: column; - align-items: stretch; - gap: 0.5rem; min-width: 0; } -.conversation-picker h2 { - font-size: 1rem; - margin: 0 0 0.25rem; -} -.conversation-picker p { +.conversation-notice { + margin: 0.5rem 0 0; font-size: 0.85rem; color: var(--ds-text-secondary, light-dark(#606b76, #b5b5b5)); } -.conversation-picker button { - padding: 0.6rem 0.75rem; - border: 1px solid var(--ds-border, light-dark(#cbd2da, #666666)); - border-radius: 0.4rem; - background: var(--ds-surface, light-dark(#fff, #1c1c1c)); - color: inherit; - text-align: left; - overflow-wrap: anywhere; -} -.conversation-picker button[aria-pressed='true'] { - border-color: var(--ds-border, light-dark(#415873, #9dc1ff)); - background: var(--ds-surface-tinted, light-dark(#eaf0f6, #182638)); -} -.conversation-picker button:disabled { - color: var(--ds-text-secondary, light-dark(#606b76, #b5b5b5)); +.conversation-notice:empty { + display: none; } .conversation-panel { display: flex; @@ -109,17 +89,6 @@ body { .threads-layout { grid-template-columns: minmax(0, 1fr); } - .conversation-picker { - flex-direction: row; - flex-wrap: wrap; - } - .conversation-picker h2, - .conversation-picker p { - flex-basis: 100%; - } - .conversation-picker button { - max-width: 100%; - } .conversation-panel .tp-chat-list { max-height: 55dvh; } 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/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 `
)} {archivedThreads != null && ( @@ -186,6 +204,8 @@ export function ChatSidenavSections({ actions={threadActions} projects={destinations} now={now} + renderItem={renderThread} + extraActions={extraThreadActions} /> )}
diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 068d41860..80193de4c 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -168,6 +168,11 @@ export { ChatSidenavSections, type ChatSidenavSectionsProps, } from './chat-sidenav-sections.js'; +export { + ThreadSidebar, + type ThreadSidebarFeatures, + type ThreadSidebarProps, +} from './thread-sidebar.js'; export { ChatSidenavScrim, type ChatSidenavScrimProps, diff --git a/libs/react/src/chat/styles.css b/libs/react/src/chat/styles.css index 19c3dc71f..3279bfe7b 100644 --- a/libs/react/src/chat/styles.css +++ b/libs/react/src/chat/styles.css @@ -3152,3 +3152,16 @@ .tp-genui-skeleton { color: CanvasText; } .tp-genui-skeleton__row { background: GrayText; } } +.tp-thread-sidebar { + display: flex; + flex-direction: column; + gap: 0.75rem; + min-inline-size: 0; +} +.tp-thread-sidebar[aria-busy='true'] .tp-chat-sidenav-sections__section { + opacity: 0.6; +} +.tp-thread-sidebar__error { + padding: 0.5rem 0.75rem; + font-size: var(--tp-chat-font-size-sm, 0.875rem); +} diff --git a/libs/react/src/chat/thread-list.spec.tsx b/libs/react/src/chat/thread-list.spec.tsx index f0fc4ebcb..310ea814f 100644 --- a/libs/react/src/chat/thread-list.spec.tsx +++ b/libs/react/src/chat/thread-list.spec.tsx @@ -1,6 +1,6 @@ import { StrictMode } from 'react'; import { cleanup, fireEvent, render } from '@testing-library/react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ThreadList, type ThreadListItem } from './index'; afterEach(() => { @@ -816,3 +816,53 @@ it('leaves omitted and already claimed context input alone', () => { fireEvent.keyDown(view.getByRole('button'), { key: 'ContextMenu' }) ).toBe(true); }); + +describe('ThreadList extra actions', () => { + beforeEach(() => { + vi.spyOn(HTMLElement.prototype, 'getClientRects').mockImplementation( + function (this: HTMLElement) { + return [this.getBoundingClientRect()] as unknown as DOMRectList; + } + ); + }); + + it('appends app actions to the row menu and runs them with the thread id', () => { + const run = vi.fn(async () => undefined); + const view = render( + + ); + fireEvent.click( + view.getByRole('button', { name: 'More actions for Alpha' }) + ); + expect( + view.getAllByRole('menuitem').map((item) => item.textContent) + ).toEqual(['Rename', 'Share']); + fireEvent.click(view.getByRole('menuitem', { name: 'Share' })); + expect(run.mock.calls).toEqual([['a']]); + }); + + it('offers a menu for app actions alone and survives a rejected action', async () => { + const run = vi.fn(async () => { + throw new Error('refused'); + }); + const view = render( + + ); + fireEvent.click( + view.getByRole('button', { name: 'More actions for Alpha' }) + ); + fireEvent.click(view.getByRole('menuitem', { name: 'Export' })); + await Promise.resolve(); + expect(run.mock.calls).toEqual([['a']]); + expect(view.getByRole('button', { name: 'Alpha' })).not.toBeNull(); + }); +}); diff --git a/libs/react/src/chat/thread-list.tsx b/libs/react/src/chat/thread-list.tsx index 198f5e284..7c80a6f92 100644 --- a/libs/react/src/chat/thread-list.tsx +++ b/libs/react/src/chat/thread-list.tsx @@ -64,6 +64,7 @@ interface MenuState { const NO_ORDER: ReadonlyMap = new Map(); const NO_PROJECT = 'none'; +const EXTRA = 'extra:'; /** Supplies ordered conversations and controlled selection, with creation, row rendering, action, and context-menu hooks. */ export interface ThreadListProps { @@ -102,6 +103,18 @@ export interface ThreadListProps { readonly projects?: | readonly { readonly id: string; readonly name: string }[] | null; + /** + * App commands appended to each row's built-in menu, in both modes. A + * rejected command leaves the row as supplied. Rows drawn by `renderItem` + * get no menu. + */ + readonly extraActions?: + | readonly { + readonly id: string; + readonly label: string; + readonly run: (threadId: string) => RowActionResult; + }[] + | null; } function validDate(value: number | undefined): Date | undefined { @@ -136,6 +149,7 @@ export function ThreadList({ actions: adapter, mode = 'active', projects, + extraActions, }: ThreadListProps) { const listId = useId(); const keyboardContext = useRef(null); @@ -182,8 +196,12 @@ export function ThreadList({ ]; } + const extraItems: OverflowMenuItem[] = (extraActions ?? []).map((action) => ({ + id: `${EXTRA}${action.id}`, + label: action.label, + })); const menuItems = (thread: ThreadListItem): OverflowMenuItem[] => { - if (!adapter) return []; + if (!adapter) return extraItems; const items: OverflowMenuItem[] = []; if (mode === 'archived') { if (adapter.unarchive) @@ -207,7 +225,7 @@ export function ThreadList({ } if (adapter.delete) items.push({ id: 'delete', label: 'Delete', tone: 'destructive' }); - return items; + return [...items, ...extraItems]; }; const projectItems: OverflowMenuItem[] = [ { id: NO_PROJECT, label: 'No project' }, @@ -242,8 +260,15 @@ export function ThreadList({ view: MenuState['view'], returnTo: HTMLElement | null ) => { - if (!adapter) return; const id = thread.id; + if (view === 'actions' && itemId.startsWith(EXTRA)) { + const action = extraActions?.find( + (candidate) => `${EXTRA}${candidate.id}` === itemId + ); + if (action) void optimistic.settle(() => action.run(id)); + return; + } + if (!adapter) return; if (view === 'projects') { const projectId = itemId === NO_PROJECT ? null : itemId.slice('project:'.length); @@ -290,7 +315,7 @@ export function ThreadList({ }; const onContextMenu = ownerContextMenu ?? - (adapter && !renderItem && visible.some((row) => menuItems(row).length > 0) + (!renderItem && visible.some((row) => menuItems(row).length > 0) ? builtInContextMenu : undefined); diff --git a/libs/react/src/chat/thread-list.type-test.tsx b/libs/react/src/chat/thread-list.type-test.tsx index 04b10667b..13c6db657 100644 --- a/libs/react/src/chat/thread-list.type-test.tsx +++ b/libs/react/src/chat/thread-list.type-test.tsx @@ -166,9 +166,23 @@ export type CompletePropsContract = Assert< readonly projects?: | readonly { readonly id: string; readonly name: string }[] | null; + readonly extraActions?: + | readonly { + readonly id: string; + readonly label: string; + readonly run: (threadId: string) => Promise | void; + }[] + | null; } > >; + void id }]} +/>; +const unlabeled = [{ id: 'share', run: () => undefined }] as const; +// @ts-expect-error Extra actions need a label. +; const adapter: ThreadActionAdapter = { rename: async (id, title) => void [id.length, title.length], delete: (id) => void id, diff --git a/libs/react/src/chat/thread-sidebar.spec.tsx b/libs/react/src/chat/thread-sidebar.spec.tsx new file mode 100644 index 000000000..dde13e608 --- /dev/null +++ b/libs/react/src/chat/thread-sidebar.spec.tsx @@ -0,0 +1,472 @@ +import { act, cleanup, fireEvent, render } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { + AgentSession, + AgentSnapshot, + ThreadDirectory, + ThreadDirectorySnapshot, +} from '@threadplane/core'; +import { ThreadSidebar } from './index'; + +beforeEach(() => { + Object.defineProperty(HTMLDialogElement.prototype, 'showModal', { + configurable: true, + value: vi.fn(function (this: HTMLDialogElement) { + this.setAttribute('open', ''); + }), + }); + Object.defineProperty(HTMLDialogElement.prototype, 'close', { + configurable: true, + value: vi.fn(function (this: HTMLDialogElement) { + this.removeAttribute('open'); + }), + }); + vi.spyOn(HTMLElement.prototype, 'getClientRects').mockImplementation( + function (this: HTMLElement) { + return [this.getBoundingClientRect()] as unknown as DOMRectList; + } + ); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const loaded: ThreadDirectorySnapshot = Object.freeze({ + threads: Object.freeze([ + { + id: 'a', + title: 'Alpha', + pinned: true, + archived: false, + projectId: null, + }, + { id: 'b', title: 'Beta', pinned: false, archived: false, projectId: null }, + ]), + archived: Object.freeze([]), + projects: Object.freeze([{ id: 'p', name: 'Research' }]), + status: 'idle', +}); + +type Fake = ThreadDirectory & { + set(next: ThreadDirectorySnapshot): void; + readonly refresh: ReturnType; + readonly dispose: ReturnType; +}; + +/** A hand-written directory; `omit` drops optional commands. */ +function fakeDirectory( + initial: ThreadDirectorySnapshot = loaded, + omit: readonly (keyof ThreadDirectory)[] = [] +): Fake { + let snapshot = initial; + const listeners = new Set<() => void>(); + const directory: Record = { + getSnapshot: () => snapshot, + subscribe: (notify: () => void) => { + listeners.add(notify); + return () => listeners.delete(notify); + }, + refresh: vi.fn(async () => undefined), + create: vi.fn(async () => ({ id: 'new' })), + rename: vi.fn(async () => undefined), + remove: vi.fn(async () => undefined), + setArchived: vi.fn(async () => undefined), + setPinned: vi.fn(async () => undefined), + reorderPinned: vi.fn(async () => undefined), + setProject: vi.fn(async () => undefined), + createProject: vi.fn(async () => ({ id: 'q' })), + renameProject: vi.fn(async () => undefined), + removeProject: vi.fn(async () => undefined), + dispose: vi.fn(), + set(next: ThreadDirectorySnapshot) { + snapshot = next; + for (const notify of [...listeners]) notify(); + }, + }; + for (const key of omit) delete directory[key]; + return directory as unknown as Fake; +} + +function fakeSession(status: AgentSnapshot['status']) { + let current = { status } as AgentSnapshot; + const listeners = new Set<() => void>(); + const session: Pick = { + getSnapshot: () => current, + subscribe: (notify) => { + listeners.add(notify); + return () => listeners.delete(notify); + }, + }; + return { + session, + listeners, + set(next: AgentSnapshot['status']) { + current = { status: next } as AgentSnapshot; + for (const notify of [...listeners]) notify(); + }, + }; +} + +function menuItems(view: ReturnType, title: string) { + fireEvent.click( + view.getByRole('button', { name: `More actions for ${title}` }) + ); + return view.getAllByRole('menuitem').map((item) => item.textContent); +} + +describe('ThreadSidebar', () => { + it('lists threads from the directory and refreshes on mount', () => { + const directory = fakeDirectory(); + const view = render( + + ); + expect(view.getByRole('button', { name: 'Alpha' })).not.toBeNull(); + expect(view.getByRole('button', { name: 'Beta' })).not.toBeNull(); + expect(directory.refresh).toHaveBeenCalledTimes(1); + act(() => directory.set({ ...loaded, threads: [loaded.threads[1]] })); + expect(view.queryByRole('button', { name: 'Alpha' })).toBeNull(); + }); + + it('hides menu actions the directory lacks', () => { + const full = render( + + ); + expect(menuItems(full, 'Beta')).toContain('Delete'); + cleanup(); + const view = render( + + ); + const items = menuItems(view, 'Beta'); + expect(items).not.toContain('Delete'); + expect(items).not.toContain('Pin'); + expect(items).toContain('Rename'); + }); + + it('turns built-ins off with features', () => { + const directory = fakeDirectory(); + const view = render( + + ); + expect(view.queryByRole('heading', { name: 'Projects' })).toBeNull(); + expect(view.queryByRole('button', { name: 'Research' })).toBeNull(); + expect(view.queryByRole('button', { name: 'Archived' })).toBeNull(); + const items = menuItems(view, 'Beta'); + expect(items).not.toContain('Rename'); + expect(items).not.toContain('Archive'); + expect(items).not.toContain('Move to project'); + expect(items).toContain('Delete'); + }); + + it('shows the load error and retries', () => { + const directory = fakeDirectory({ + threads: [], + archived: [], + status: 'error', + error: { + kind: 'network', + message: 'offline', + } as unknown as NonNullable, + }); + const view = render( + + ); + const alert = view.getByRole('alert'); + expect(alert.textContent).toContain('Could not load chats'); + expect(view.queryByText('No conversations yet.')).toBeNull(); + fireEvent.click(view.getByRole('button', { name: 'Try again' })); + expect(directory.refresh).toHaveBeenCalledTimes(2); + }); + + it('shows an empty state only once loaded', async () => { + const directory = fakeDirectory({ + threads: [], + archived: [], + status: 'loading', + }); + const view = render( + + ); + expect(view.queryByText('No conversations yet.')).toBeNull(); + expect(view.container.firstElementChild?.getAttribute('aria-busy')).toBe( + 'true' + ); + 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('shows all threads when the selected project no longer exists', () => { + 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: [], + projects: [{ id: 'p', name: 'Research' }], + status: 'idle', + }); + const view = render( + + ); + expect(view.queryByRole('button', { name: 'Alpha' })).not.toBeNull(); + expect(view.queryByRole('button', { name: 'Beta' })).not.toBeNull(); + // An unavailable Store reports no projects at all. + act(() => + directory.set({ + threads: loaded.threads, + archived: [], + status: 'idle', + }) + ); + expect(view.queryByRole('button', { name: 'Alpha' })).not.toBeNull(); + expect(view.queryByRole('button', { name: 'Beta' })).not.toBeNull(); + }); + + it('clears the selection when the selected project is removed', async () => { + const directory = fakeDirectory({ + threads: loaded.threads, + archived: [], + projects: [ + { id: 'p', name: 'Research' }, + { id: 'q', name: 'Travel' }, + ], + status: 'idle', + }); + const onProjectSelect = vi.fn(); + const view = render( + + ); + const removeProject = async (name: string) => { + fireEvent.click( + view.getByRole('button', { name: `More actions for ${name}` }) + ); + fireEvent.click(view.getByRole('menuitem', { name: 'Delete' })); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Delete' })); + }); + }; + await removeProject('Travel'); + expect(directory.removeProject).toHaveBeenCalledWith('q'); + expect(onProjectSelect).not.toHaveBeenCalled(); + await removeProject('Research'); + expect(directory.removeProject).toHaveBeenCalledWith('p'); + expect(onProjectSelect.mock.calls).toEqual([[null]]); + }); + + it('refreshes after a run ends', () => { + const directory = fakeDirectory(); + const run = fakeSession('running'); + const view = render( + + ); + expect(directory.refresh).toHaveBeenCalledTimes(1); + act(() => run.set('idle')); + expect(directory.refresh).toHaveBeenCalledTimes(2); + view.unmount(); + expect(run.listeners.size).toBe(0); + expect(directory.dispose).not.toHaveBeenCalled(); + }); + + it('reports the active thread removed', async () => { + const directory = fakeDirectory(); + const onActiveRemoved = vi.fn(); + const view = render( + + ); + fireEvent.click( + view.getByRole('button', { name: 'More actions for Beta' }) + ); + fireEvent.click(view.getByRole('menuitem', { name: 'Delete' })); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Delete' })); + }); + expect(directory.remove).toHaveBeenCalledWith('b'); + expect(onActiveRemoved).toHaveBeenCalledTimes(1); + }); + + it('does not report a failed or inactive removal', async () => { + const directory = fakeDirectory(); + (directory.remove as ReturnType).mockRejectedValueOnce( + new Error('refused') + ); + const onActiveRemoved = vi.fn(); + const view = render( + + ); + for (const title of ['Beta', 'Alpha']) { + fireEvent.click( + view.getByRole('button', { name: `More actions for ${title}` }) + ); + fireEvent.click(view.getByRole('menuitem', { name: 'Delete' })); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'Delete' })); + }); + } + expect(directory.remove).toHaveBeenCalledTimes(2); + expect(onActiveRemoved).not.toHaveBeenCalled(); + expect(view.getByRole('button', { name: 'Beta' })).not.toBeNull(); + }); + + it('creates and selects a new chat by default', async () => { + const directory = fakeDirectory(); + const onSelect = vi.fn(); + const view = render( + + ); + await act(async () => { + fireEvent.click(view.getByRole('button', { name: 'New chat' })); + }); + expect(directory.create).toHaveBeenCalledTimes(1); + expect(onSelect.mock.calls).toEqual([['new']]); + }); + + it('omits New chat without a handler or create command', () => { + const view = render( + + ); + expect(view.queryByRole('button', { name: 'New chat' })).toBeNull(); + }); + + it('renders before and after sections and a custom row', () => { + const run = vi.fn(); + const view = render( + Before

} + after={

After

} + renderThread={(thread, isActive) => ( + {`row ${thread.title}${isActive ? ' active' : ''}`} + )} + labels={{ recent: 'Chats' }} + /> + ); + const text = view.container.textContent ?? ''; + expect(text.indexOf('Before')).toBeLessThan(text.indexOf('Chats')); + expect(text.indexOf('Chats')).toBeLessThan(text.indexOf('After')); + expect(view.getByText('row Alpha active')).not.toBeNull(); + expect(view.getByText('row Beta')).not.toBeNull(); + cleanup(); + const extra = render( + + ); + fireEvent.click( + extra.getByRole('button', { name: 'More actions for Beta' }) + ); + fireEvent.click(extra.getByRole('menuitem', { name: 'Share' })); + expect(run).toHaveBeenCalledWith('b'); + }); +}); diff --git a/libs/react/src/chat/thread-sidebar.tsx b/libs/react/src/chat/thread-sidebar.tsx new file mode 100644 index 000000000..72ac10f40 --- /dev/null +++ b/libs/react/src/chat/thread-sidebar.tsx @@ -0,0 +1,310 @@ +'use client'; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from 'react'; +import { + refreshDirectoryOnRunEnd, + type AgentSession, + type ThreadDirectory, + type ThreadDirectorySnapshot, + type ThreadEntry, +} from '@threadplane/core'; +import { ChatSidenavSections } from './chat-sidenav-sections.js'; +import type { ProjectActionAdapter } from './project-list.js'; +import type { ThreadActionAdapter, ThreadListProps } from './thread-list.js'; + +/** + * Built-in sidebar features. Each defaults to on when the directory supports + * it; `false` turns it off even when the directory could perform it. + */ +export interface ThreadSidebarFeatures { + /** The Projects section, project commands and Move to project. */ + readonly projects?: boolean; + /** The Archived section and Archive and Unarchive. */ + readonly archive?: boolean; + readonly pin?: boolean; + readonly reorder?: boolean; + readonly rename?: boolean; + readonly remove?: boolean; +} + +/** A thread directory with selection callbacks, feature switches, row slots and labels. */ +export interface ThreadSidebarProps { + /** App-owned; the sidebar never disposes it. */ + readonly directory: ThreadDirectory; + /** Refreshes the directory each time a run ends. */ + readonly session?: Pick; + readonly activeThreadId?: string | null; + readonly onSelect: (threadId: string) => void; + /** Replaces the default New chat, which creates a thread and selects it. */ + 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`. */ + readonly renderThread?: ThreadListProps['renderItem']; + /** App commands appended to each conversation row menu. */ + readonly extraActions?: ThreadListProps['extraActions']; + /** App content before the built-in sections. */ + readonly before?: ReactNode; + /** App content after the built-in sections. */ + readonly after?: ReactNode; + readonly labels?: Partial< + Record< + | 'newChat' + | 'projects' + | 'recent' + | 'archived' + | 'archivedEmpty' + | 'loadError' + | 'retry' + | 'empty', + string + > + >; + readonly className?: string; +} + +const ignore = () => undefined; +const NO_FEATURES: ThreadSidebarFeatures = {}; + +/** + * The entries in `projectId`, or all of them when no project is selected or + * the selected project is not in `projects` (deleted, or the Store is + * unavailable), so a stale selection never hides every conversation. + */ +function inProject( + entries: readonly ThreadEntry[], + projectId: string | null | undefined, + projects: ThreadDirectorySnapshot['projects'] +): readonly ThreadEntry[] { + return typeof projectId === 'string' && + projects?.some((project) => project.id === projectId) + ? 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. + * It refreshes on mount and, given a session, after each run. Place it inside + * `ChatSidenav` or use it on its own. + */ +export function ThreadSidebar({ + directory, + session, + activeThreadId, + onSelect, + onNewChat, + onActiveRemoved, + selectedProjectId, + onProjectSelect, + features = NO_FEATURES, + renderThread, + extraActions, + before, + after, + labels, + className, +}: ThreadSidebarProps) { + const subscribe = useCallback( + (notify: () => void) => directory.subscribe(notify), + [directory] + ); + const getSnapshot = useCallback(() => directory.getSnapshot(), [directory]); + const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + + // Handlers read the latest props without resubscribing. + const latest = useRef({ + activeThreadId, + onSelect, + onActiveRemoved, + selectedProjectId, + onProjectSelect, + }); + latest.current = { + activeThreadId, + onSelect, + onActiveRemoved, + selectedProjectId, + onProjectSelect, + }; + + // 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) + .then(() => { + if (!controller.signal.aborted) setSettled(directory); + }); + return () => controller.abort(); + }, [directory]); + + useEffect(() => { + if (!session) return undefined; + return refreshDirectoryOnRunEnd( + { refresh: () => directory.refresh().catch(ignore) }, + session + ); + }, [directory, session]); + + const on = (feature: keyof ThreadSidebarFeatures) => + features[feature] !== false; + const showProjects = on('projects') && snapshot.projects !== undefined; + const showArchive = on('archive'); + + const { + rename, + remove, + setArchived, + setPinned, + reorderPinned, + setProject, + createProject, + renameProject, + removeProject, + create, + } = directory; + const threadActions: ThreadActionAdapter = { + rename: + rename && on('rename') + ? (id, title) => rename.call(directory, id, title) + : undefined, + delete: + remove && on('remove') + ? async (id) => { + const wasActive = id === latest.current.activeThreadId; + await remove.call(directory, id); + if (wasActive) latest.current.onActiveRemoved?.(); + } + : undefined, + archive: + setArchived && showArchive + ? (id) => setArchived.call(directory, id, true) + : undefined, + unarchive: + setArchived && showArchive + ? (id) => setArchived.call(directory, id, false) + : undefined, + pin: + setPinned && on('pin') + ? (id) => setPinned.call(directory, id, true) + : undefined, + unpin: + setPinned && on('pin') + ? (id) => setPinned.call(directory, id, false) + : undefined, + reorderPinned: + reorderPinned && on('reorder') + ? (id, beforeId) => reorderPinned.call(directory, id, beforeId) + : undefined, + moveToProject: + setProject && showProjects + ? (id, projectId) => setProject.call(directory, id, projectId) + : undefined, + }; + const projectActions: ProjectActionAdapter | null = showProjects + ? { + create: createProject + ? (name) => createProject.call(directory, name) + : undefined, + rename: renameProject + ? (id, name) => renameProject.call(directory, id, name) + : undefined, + delete: removeProject + ? async (id) => { + const wasSelected = id === latest.current.selectedProjectId; + await removeProject.call(directory, id); + if (wasSelected) latest.current.onProjectSelect?.(null); + } + : undefined, + } + : null; + const newChat = + onNewChat ?? + (create + ? () => { + create + .call(directory) + .then(({ id }) => latest.current.onSelect(id)) + .catch(ignore); + } + : undefined); + + const threads = useMemo( + () => inProject(snapshot.threads, selectedProjectId, snapshot.projects), + [snapshot.threads, snapshot.projects, selectedProjectId] + ); + const archived = useMemo( + () => inProject(snapshot.archived, selectedProjectId, snapshot.projects), + [snapshot.archived, snapshot.projects, selectedProjectId] + ); + + const loading = snapshot.status === 'loading' || settled !== directory; + const failed = snapshot.status === 'error'; + return ( +
+ {before} + {failed && ( +
+

+ {labels?.loadError ?? 'Could not load conversations.'} +

+ +
+ )} + + {after} +
+ ); +} diff --git a/libs/react/src/chat/thread-sidebar.type-test.tsx b/libs/react/src/chat/thread-sidebar.type-test.tsx new file mode 100644 index 000000000..684ce0207 --- /dev/null +++ b/libs/react/src/chat/thread-sidebar.type-test.tsx @@ -0,0 +1,30 @@ +import type { ThreadDirectory } from '@threadplane/core'; +import { + ThreadSidebar, + type ThreadSidebarFeatures, + type ThreadSidebarProps, +} from './index.js'; + +declare const directory: ThreadDirectory; + +const features: ThreadSidebarFeatures = { projects: false, pin: true }; +const props: ThreadSidebarProps = { + directory, + onSelect: (threadId: string) => void threadId, + onProjectSelect: (projectId: string | null) => void projectId, + features, + extraActions: [{ id: 'share', label: 'Share', run: async () => undefined }], + labels: { empty: 'Nothing yet', retry: 'Try again' }, +}; +; + undefined} />; +// @ts-expect-error A directory is required. + undefined} />; +// @ts-expect-error Labels are the documented keys. +; +// @ts-expect-error Feature switches are booleans. +; +// @ts-expect-error Props are readonly. +props.features = {}; +// @ts-expect-error Feature switches are readonly. +features.pin = false; diff --git a/scripts/react-cockpit/chat-threads-fixture.mjs b/scripts/react-cockpit/chat-threads-fixture.mjs index 5f4e43e67..22edeb332 100644 --- a/scripts/react-cockpit/chat-threads-fixture.mjs +++ b/scripts/react-cockpit/chat-threads-fixture.mjs @@ -105,6 +105,7 @@ export function createChatThreadsFixture({ closed = false, closing; let requests = [], + directoryRequests = [], proofs = [], injections = []; let historyMode = 'safe', @@ -114,7 +115,10 @@ export function createChatThreadsFixture({ holds = new Set(), threads = new Set(), runs = new Map(), - operations = new Set(); + operations = new Set(), + // Sidebar directory state: metadata written by PATCH and Store API items. + metadata = new Map(), + store = new Map(); const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const json = (response, value, status = 200) => { @@ -172,14 +176,135 @@ export function createChatThreadsFixture({ queue = Promise.resolve(); operations.clear(); requests = []; + directoryRequests = []; proofs = []; injections = []; threads.clear(); runs.clear(); + metadata.clear(); + store.clear(); historyMode = titleMode = 'safe'; failCreate = false; await previous?.close(); } + const namespaceKey = (namespace, key) => + Array.isArray(namespace) && + namespace.length > 0 && + namespace.every((part) => typeof part === 'string' && part) && + typeof key === 'string' && + key + ? JSON.stringify([namespace, key]) + : null; + /** Server metadata as search reports it: the graph-authored title shaped by + * the authored title mode, then the sidebar's own writes. */ + async function searchMetadata(threadId) { + let authored = {}; + try { + authored = { ...(await operate({ op: 'title', threadId })).thread.metadata }; + } catch { + /* Title unavailable: the sidebar shows its fallback. */ + } + if (titleMode === 'missing') delete authored.title; + if (titleMode === 'invalid') authored.title = { invalid: true }; + if (titleMode === 'literal') + authored.title = ''; + if (titleMode === 'long') + authored.title = 'Long authored title '.repeat(30); + return { ...authored, ...metadata.get(threadId) }; + } + async function directory(request, response, pathname, body) { + const route = + /^\/(?:api|developer-api)\/(threads\/search|threads\/([^/]+)|store\/items(?:\/search)?)$/.exec( + pathname + ); + if (!route) return false; + const method = request.method, + threadId = route[2]; + const known = + (route[1] === 'threads/search' && method === 'POST') || + (threadId !== undefined && + threadId !== 'search' && + ['PATCH', 'DELETE'].includes(method)) || + (route[1] === 'store/items' && ['PUT', 'DELETE'].includes(method)) || + (route[1] === 'store/items/search' && method === 'POST'); + if (!known) return false; + directoryRequests.push({ + path: pathname, + method, + body, + key: request.headers['x-api-key'] ?? null, + }); + if (route[1] === 'threads/search') { + const ids = [...threads]; + const offset = Number.isInteger(body.offset) ? body.offset : 0, + limit = Number.isInteger(body.limit) ? body.limit : 10; + const page = []; + for (const id of ids.slice(offset, offset + limit)) + page.push({ + thread_id: id, + status: 'idle', + metadata: await searchMetadata(id), + }); + json(response, page); + return true; + } + if (threadId !== undefined) { + if (!threads.has(threadId)) { + json(response, {}, 404); + return true; + } + if (method === 'DELETE') { + threads.delete(threadId); + metadata.delete(threadId); + response.writeHead(204); + response.end(); + return true; + } + if ( + body.metadata === null || + typeof body.metadata !== 'object' || + Array.isArray(body.metadata) + ) { + json(response, {}, 400); + return true; + } + const next = { ...metadata.get(threadId), ...body.metadata }; + metadata.set(threadId, next); + json(response, { thread_id: threadId, status: 'idle', metadata: next }); + return true; + } + if (route[1] === 'store/items/search') { + const prefix = body.namespace_prefix ?? []; + const items = [...store.values()].filter( + (item) => + Array.isArray(prefix) && + prefix.every((part, index) => item.namespace[index] === part) + ); + json(response, { items: items.slice(0, body.limit ?? 10) }); + return true; + } + const id = namespaceKey(body.namespace, body.key); + if ( + !id || + (method === 'PUT' && + (body.value === null || + typeof body.value !== 'object' || + Array.isArray(body.value))) + ) { + json(response, {}, 400); + return true; + } + if (method === 'PUT') + store.set(id, { + namespace: [...body.namespace], + key: body.key, + value: body.value, + }); + else store.delete(id); + response.writeHead(204); + response.end(); + return true; + } const handle = async (request, response, pathname) => { if (pathname === '/__lifetime') { json(response, { @@ -209,6 +334,10 @@ export function createChatThreadsFixture({ json(response, requests); return true; } + if (pathname === '/__directory-requests') { + json(response, directoryRequests); + return true; + } if (pathname === '/__graph-proof') { json(response, proofs); return true; @@ -298,6 +427,9 @@ export function createChatThreadsFixture({ for await (const chunk of request) input += chunk; const body = input ? JSON.parse(input) : {}, captured = epoch; + // The thread sidebar's directory traffic is logged apart from the + // conversation runtime wire so each log proves its own contract. + if (await directory(request, response, pathname, body)) return true; requests.push({ path: pathname, method: request.method, @@ -367,6 +499,7 @@ export function createChatThreadsFixture({ const mode = titleMode, wire = await operate({ op: 'title', threadId }), value = wire.thread; + value.metadata = { ...value.metadata, ...metadata.get(threadId) }; if (!['safe', 'hold'].includes(mode)) injections.push({ kind: 'title', mode, threadId }); if (mode === 'titlefailure') throw new Error('Title unavailable'); diff --git a/scripts/react-cockpit/chat-threads-fixture.spec.mjs b/scripts/react-cockpit/chat-threads-fixture.spec.mjs index c2d3b0712..1cda303ab 100644 --- a/scripts/react-cockpit/chat-threads-fixture.spec.mjs +++ b/scripts/react-cockpit/chat-threads-fixture.spec.mjs @@ -306,10 +306,10 @@ test('only confirmed UUID creation and exact supported routes are admitted', asy 400 ); for (const [path, method, body] of [ - ['/api/threads/search', 'POST', {}], ['/api/threads', 'GET'], - [`/api/threads/${id}`, 'DELETE'], [`/api/threads/${id}`, 'PATCH', {}], + [`/api/threads/${randomUUID()}`, 'DELETE'], + ['/api/store/items', 'PUT', { namespace: [], key: 'p' }], [`/api/threads/${id}/runs/x/cancel`, 'POST', {}], [`/api/threads/${id}/runs/x/stream`, 'GET'], [`/api/threads/${id}/state`, 'GET'], @@ -334,7 +334,92 @@ test('only confirmed UUID creation and exact supported routes are admitted', asy ], ]) assert((await f.request(path, body, method)).status >= 400, path); - assert((await f.json('/__requests')).length >= 12); + assert((await f.json('/__requests')).length >= 10); + assert.equal((await f.json('/__directory-requests')).length, 3); +}); + +test('sidebar directory routes list, patch and delete threads and keep Store items apart from the runtime wire', async (t) => { + const f = await fixture(t), + first = await f.create(), + second = await f.create(); + await (await f.submit(first, 'Hello')).text(); + assert.deepEqual( + (await f.json('/api/threads/search', { limit: 50, offset: 0 })).map( + (thread) => [thread.thread_id, thread.metadata.title] + ), + [ + [first, 'Authored conversation title'], + [second, undefined], + ] + ); + assert.deepEqual( + ( + await f.json( + `/api/threads/${second}`, + { metadata: { title: 'Renamed', pinned: true } }, + 'PATCH' + ) + ).metadata, + { title: 'Renamed', pinned: true } + ); + await f.json(`/api/threads/${second}`, { metadata: { pinnedOrder: 0 } }, 'PATCH'); + assert.deepEqual((await f.title(second)).metadata, { + title: 'Renamed', + pinned: true, + pinnedOrder: 0, + }); + await f.json('/__title/missing'); + assert.deepEqual( + (await f.json('/api/threads/search', { limit: 50, offset: 0 })).map( + (thread) => thread.metadata.title + ), + [undefined, 'Renamed'] + ); + const namespace = ['threadplane', 'projects']; + assert.equal( + ( + await f.request( + '/api/store/items', + { namespace, key: 'p1', value: { name: 'Research' } }, + 'PUT' + ) + ).status, + 204 + ); + assert.deepEqual( + ( + await f.json('/api/store/items/search', { + namespace_prefix: namespace, + limit: 100, + }) + ).items, + [{ namespace, key: 'p1', value: { name: 'Research' } }] + ); + assert.equal( + (await f.request('/api/store/items', { namespace, key: 'p1' }, 'DELETE')) + .status, + 204 + ); + assert.deepEqual( + (await f.json('/api/store/items/search', { namespace_prefix: namespace })) + .items, + [] + ); + assert.equal( + (await f.request(`/api/threads/${second}`, undefined, 'DELETE')).status, + 204 + ); + assert.equal((await f.request(`/api/threads/${second}`, undefined, 'GET')).status, 404); + assert.deepEqual( + (await f.json('/api/threads/search', {})).map((thread) => thread.thread_id), + [first] + ); + const runtime = await f.json('/__requests'); + assert(runtime.every((item) => !/search|store/.test(item.path))); + assert(runtime.every((item) => item.method !== 'PATCH' && item.method !== 'DELETE')); + assert.equal((await f.json('/__directory-requests')).length, 10); + await f.json('/__reset'); + assert.deepEqual(await f.json('/__directory-requests'), []); }); test('history injections preserve separate actual proof and restore real saved data', async (t) => { diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index e4a5a99cd..db5a6f4d0 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -19206,16 +19206,6 @@ "reason": "Private arrival-time measurement of root assistant reasoning at publication: from the first publication with reasoning and nothing else to the first with text, a tool call or a completed delivery, published as Message.reasoningDurationMs.", "note": "Reasoning first seen already settled (saved history, or delivered whole) stays unmeasured. Nothing is stored, so a new session knows no durations. Subgraph messages are not timed. Rich blocks, event-only retention and full T09/T15 parity remain open." }, - { - "id": "source:libs/langgraph/src/runtime/thread-directory.ts", - "taskIds": [ - "T11" - ], - "treatment": "shared", - "status": "in-progress", - "reason": "Framework-neutral directory of a deployment's saved conversations: an observable list read from thread metadata (title, archived, pinned, pinned order, project) with create, rename, delete, archive, pin, move and reorder commands that write metadata and read the list again.", - "note": "Staged beside the private session; not exported from a published entry. The Angular LangGraphThreadsAdapter is unchanged and not yet built on it. Reads one page of the configured size; no paging, search or cross-tab refresh." - }, { "id": "source:libs/ag-ui/src/runtime/agent-session.ts", "taskIds": [ @@ -19425,6 +19415,248 @@ "treatment": "react", "status": "in-progress", "note": "Turns RenderSpec lifecycle, stateChange and handler events into first-mount, mount-count and latest-activity timings, the React counterpart of Angular RENDER_LIFECYCLE." + }, + { + "id": "export:libs/chat/src/public-api.ts#ProjectEntry", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadDirectory", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadDirectoryError", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadDirectorySnapshot", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadDirectoryStatus", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadEntry", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "source:libs/chat/src/lib/thread-directory/thread-directory.ts", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular copy of the core ThreadDirectory contract; replaced by a re-export when the Angular packages export core. A type spec in libs/langgraph pins it to @threadplane/core." + }, + { + "id": "source:libs/langgraph/src/runtime/project-store.ts", + "taskIds": [ + "T29" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private staged LangGraph runtime subset: framework-neutral thread directory and LangGraph Store project names behind the React ThreadSidebar." + }, + { + "id": "source:libs/langgraph/src/runtime/thread-directory.ts", + "taskIds": [ + "T29" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private staged LangGraph runtime subset: framework-neutral thread directory and LangGraph Store project names behind the React ThreadSidebar." + }, + { + "id": "source:libs/langgraph/src/runtime/thread-metadata.ts", + "taskIds": [ + "T29" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private staged LangGraph runtime subset: framework-neutral thread directory and LangGraph Store project names behind the React ThreadSidebar." + }, + { + "id": "source:libs/langgraph/src/runtime/testing/fake-threads-client.ts", + "taskIds": [ + "T29" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private test fixture: in-memory LangGraph threads/store client and the shared ThreadDirectory conformance suite run against both the runtime directory and the Angular adapter." + }, + { + "id": "source:libs/langgraph/src/runtime/testing/thread-directory-conformance.ts", + "taskIds": [ + "T29" + ], + "treatment": "internal", + "status": "in-progress", + "reason": "Private test fixture: in-memory LangGraph threads/store client and the shared ThreadDirectory conformance suite run against both the runtime directory and the Angular adapter." + }, + { + "id": "source:libs/langgraph/src/lib/threads/thread-entries.ts", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular-side copy of the runtime thread metadata projection and publication helpers behind LangGraphThreadsAdapter.directory; deleted when the adapter is rebuilt on the shared directory in phase 2." + }, + { + "id": "source:libs/langgraph/src/lib/threads/thread-projects.ts", + "taskIds": [ + "T29" + ], + "treatment": "shared", + "status": "in-progress", + "reason": "Phase 1 Angular-side copy of the runtime LangGraph Store project store behind LangGraphThreadsAdapter.directory; deleted when the adapter is rebuilt on the shared directory in phase 2." + }, + { + "id": "source:libs/react/src/chat/thread-sidebar.tsx", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "reason": "Connected conversation sidebar: reads a ThreadDirectory through useSyncExternalStore, refreshes on mount and after each run, and composes ChatSidenavSections with action adapters derived from the directory commands and feature switches. Never disposes the app-owned directory." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadSidebar", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "reason": "Connected sidebar over a ThreadDirectory with New chat, Projects, Recent and Archived, load error with Retry, empty state, row slots and before and after sections." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadSidebarProps", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "reason": "Readonly directory, optional session, selection callbacks, feature switches, row override, extra row actions, before and after content, labels and className." + }, + { + "id": "export:libs/react/src/chat/index.ts#ThreadSidebarFeatures", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "reason": "Readonly optional switches for projects, archive, pin, reorder, rename and remove; each defaults to on when the directory supports it." + }, + { + "id": "source:libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Connected Angular conversation sidebar: reads a ThreadDirectory through a signal bumped by subscribe, refreshes on mount and when the agent leaves running, and composes chat-thread-list and chat-project-list with action adapters derived from the directory commands and feature switches. Never disposes the app-owned directory." + }, + { + "id": "component:libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts#ChatThreadSidebarComponent", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Angular counterpart of ThreadSidebar with New chat, Projects, Recent and Archived, load error with Retry, empty state, row template, extra actions and before and after content." + }, + { + "id": "component:libs/chat/src/lib/compositions/chat-thread-sidebar/chat-thread-sidebar.component.ts#ChatThreadRowTemplateDirective", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Row override for chat-thread-sidebar; React passes renderThread. Rows drawn by the template get no row menu, as in React." + }, + { + "id": "export:libs/chat/src/public-api.ts#ChatThreadSidebarComponent", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Connected sidebar over a ThreadDirectory with New chat, Projects, Recent and Archived, load error with Retry, empty state, row slots and before and after sections." + }, + { + "id": "export:libs/chat/src/public-api.ts#ChatThreadRowTemplateDirective", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "ng-template[chatThreadRow] row override; React passes renderThread." + }, + { + "id": "export:libs/chat/src/public-api.ts#ChatThreadRowTemplateContext", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Row template context with the thread and isActive; mirrors the renderThread arguments." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadSidebarFeatures", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-sidebar.tsx", + "reason": "Readonly optional switches for projects, archive, pin, reorder, rename and remove; same shape as the React ThreadSidebarFeatures." + }, + { + "id": "export:libs/chat/src/public-api.ts#ThreadRowAction", + "taskIds": [ + "T30" + ], + "treatment": "react", + "status": "in-progress", + "target": "libs/react/src/chat/thread-list.tsx", + "reason": "App command appended to each conversation row menu; mirrors the React ThreadList extraActions item shape." } ] } diff --git a/scripts/react-parity/verify-langgraph-candidate.mjs b/scripts/react-parity/verify-langgraph-candidate.mjs index 9b30e5186..59af12035 100644 --- a/scripts/react-parity/verify-langgraph-candidate.mjs +++ b/scripts/react-parity/verify-langgraph-candidate.mjs @@ -131,7 +131,7 @@ const original = globalThis.fetch; globalThis.fetch = async () => { calls++; throw new Error('Unexpected candidate fetch'); }; try { const imported = await import('@threadplane/langgraph'); - assert.deepEqual(Object.keys(imported), ['createSession']); + assert.deepEqual(Object.keys(imported), ['createLangGraphProjectStore', 'createLangGraphThreadDirectory', 'createSession']); const session = imported.createSession({ assistantId: 'inert', threadId: 'fixed', apiUrl: 'http://127.0.0.1:1' }); const snapshot = session.getSnapshot(); assert.ok(Object.isFrozen(snapshot)); @@ -142,6 +142,12 @@ try { await session.dispose(); await session.dispose(); assert.equal(session.getSnapshot(), snapshot); assert.equal(notifications, 0); + const directory = imported.createLangGraphThreadDirectory({ apiUrl: 'http://127.0.0.1:1', browserOrigin: 'http://127.0.0.1:1' }); + const listing = directory.getSnapshot(); + assert.ok(Object.isFrozen(listing)); + assert.deepEqual(listing, { threads: [], archived: [], projects: [], status: 'idle' }); + directory.dispose(); + assert.equal(directory.getSnapshot(), listing); assert.equal(calls, 0); console.log(JSON.stringify({ import: true, inertObservation: true, stable: true, fetches: calls })); } finally { globalThis.fetch = original; } @@ -385,7 +391,7 @@ export async function verifyLangGraphCandidate({ const emission = emitCandidate(root, candidate); assert.equal( emission.sources.length, - 31, + 34, 'Complete reviewed backend graph' ); const packed = packCandidate(candidate, temporary); diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index 588e0b402..6d3595946 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -482,6 +482,7 @@ const SUPPORTED_EXPORTS = { 'ChatSidenav', 'ChatSidenavScrim', 'ChatSidenavSections', + 'ThreadSidebar', 'ChatInput', 'Citations', 'CitationCard', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index fc10c7659..eb5a4c652 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1046,7 +1046,7 @@ for (const [name, entry, files] of [ }); test('React chat requires its real supported export', () => { const component = () => undefined; - const supported = { Trace: component, LauncherButton: component, ChatWindow: component, Welcome: component, WelcomeSuggestion: component, Timeline: component, HistorySearchPalette: component, ProjectNameForm: component, ProjectList: component, OverflowMenu: component, ApprovalCard: component, Chat: component, ChatPopup: component, ChatSidebar: component, ChatSidenav: component, ChatSidenavScrim: component, ChatSidenavSections: component, ChatInput: component, Citations: component, MessageList: component, MessageActions: component, Reasoning: component, TextTranscript: component, ToolObservation: component, ThreadList: component, ThreadRenameForm: component, ConfirmDialog: component }; + const supported = { Trace: component, LauncherButton: component, ChatWindow: component, Welcome: component, WelcomeSuggestion: component, Timeline: component, HistorySearchPalette: component, ProjectNameForm: component, ProjectList: component, OverflowMenu: component, ApprovalCard: component, Chat: component, ChatPopup: component, ChatSidebar: component, ChatSidenav: component, ChatSidenavScrim: component, ChatSidenavSections: component, ThreadSidebar: component, ChatInput: component, Citations: component, MessageList: component, MessageActions: component, Reasoning: component, TextTranscript: component, ToolObservation: component, ThreadList: component, ThreadRenameForm: component, ConfirmDialog: component }; supported.Suggestions = component; supported.Select = component; supported.MessageRating = component;