From 5b338106fd1f9e1c507fbfeb7a00ea59cc6a81c2 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:56:19 +0000 Subject: [PATCH 1/2] Calm sidebar part 2: thread roles and the calm grouping (client-runtime) Adds packages/client-runtime/src/state/threadRoles.ts, read by nothing yet (the sidebar comes in part 3): - resolveThreadRoles: the threadRoles pointers whose thread can hold the role now. A pointer to a missing, deleted or archived thread, a sub-agent, a side chat, a delegated task or (orchestrator) a thread of another project counts as no role; the pointer is left alone. Read leniently: a bad entry is skipped alone. - threadRole: a row's role, checking the row again. - calmPartition: off (the list as given), no-roles (the list plus a hint) or calm (assistants, then orchestrators on top; the rest folded, with how many wait on the person). - createThreadRolesAtom: the resolved roles of every enabled server; reads threads only where a role is named; stable while equal. Seam list: forkFiles gains threadRoles* in client-runtime and in contracts (part 1's file was missing, so any later edit of it was refused), and the one-line client-runtime export part 3 adds is announced. Co-Authored-By: Claude Opus 5.5 --- .github/fork-seams.json | 10 + .../src/state/threadRoles.test.ts | 543 ++++++++++++++++++ .../client-runtime/src/state/threadRoles.ts | 248 ++++++++ 3 files changed, 801 insertions(+) create mode 100644 packages/client-runtime/src/state/threadRoles.test.ts create mode 100644 packages/client-runtime/src/state/threadRoles.ts diff --git a/.github/fork-seams.json b/.github/fork-seams.json index d28893619d73e..864d8fe040af1 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -25,6 +25,14 @@ "added": ["...ForkSettings.ForkClientSettingsPatchFields,"] } }, + "packages/client-runtime/package.json": { + "why": "The calm sidebar's shared logic (fork file src/state/threadRoles.ts) is exported for the web and phone lists with one line; it is announced for the sidebar PR that first imports it. One line, since the four-line form's closing brace is a line upstream already has.", + "added": [], + "announced": { + "since": "2026-11-22", + "added": ["\"./state/thread-roles\": \"./src/state/threadRoles.ts\","] + } + }, "packages/shared/src/serverSettings.ts": { "why": "A settings patch's fork fields are applied by forkSettingsPatch.ts, by the rules in forkSettings.ts.", "added": [ @@ -549,6 +557,7 @@ "apps/web/src/clientPersistenceStorage.removedKeys.test.ts", "apps/web/src/components/settings/WaitsAndSlotsSettings*", "apps/web/src/components/settings/waitsAndSlotsSettings*", + "packages/client-runtime/src/state/threadRoles*", "packages/contracts/src/editor.test.ts", "packages/contracts/src/handoff.test.ts", "packages/contracts/src/handoff.ts", @@ -556,6 +565,7 @@ "packages/contracts/src/modelPolicy*", "packages/contracts/src/playtest*", "packages/contracts/src/reviewRules*", + "packages/contracts/src/threadRoles*", "packages/contracts/src/usagePacing.ts", "packages/contracts/src/waitFor*", "packages/shared/src/agentSlots*", diff --git a/packages/client-runtime/src/state/threadRoles.test.ts b/packages/client-runtime/src/state/threadRoles.test.ts new file mode 100644 index 0000000000000..e785489d4e2a4 --- /dev/null +++ b/packages/client-runtime/src/state/threadRoles.test.ts @@ -0,0 +1,543 @@ +import { + EnvironmentId, + ProjectId, + ThreadId, + type ThreadRoles, + ThreadRolesFromSettingsFile, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import type { EnvironmentCatalogState } from "./connections.ts"; +import { + calmPartition, + createThreadRolesAtom, + isWaitingOnPerson, + NO_THREAD_ROLES, + type ResolvedThreadRoles, + resolveThreadRoles, + threadRole, +} from "./threadRoles.ts"; + +const local = EnvironmentId.make("local"); +const linked = EnvironmentId.make("linked"); +const game = ProjectId.make("project-game"); +const site = ProjectId.make("project-site"); + +interface Row { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly lineage: { + readonly parentThreadId: ThreadId | null; + readonly relationshipToParent: "fork" | "subagent" | null; + readonly rootThreadId: ThreadId; + readonly sideChat?: boolean; + }; + readonly delegatedFrom: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly title: string; + } | null; + readonly archivedAt: string | null; + readonly deletedAt: string | null; + readonly settledAt: string | null; + readonly snoozedUntil: string | null; + readonly hasPendingApprovals: boolean; + readonly hasPendingUserInput: boolean; + readonly pendingSubagentRequest: "approval" | "user_input" | null; + readonly pendingGuestMessageCount: number; +} + +const row = (id: string, projectId: ProjectId, changes: Partial = {}): Row => ({ + environmentId: local, + id: ThreadId.make(id), + projectId, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: ThreadId.make(id) }, + delegatedFrom: null, + archivedAt: null, + deletedAt: null, + settledAt: null, + snoozedUntil: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + pendingSubagentRequest: null, + pendingGuestMessageCount: 0, + ...changes, +}); + +const child = (id: string, parent: Row, changes: Partial = {}): Row => + row(id, parent.projectId, { + lineage: { + parentThreadId: parent.id, + relationshipToParent: "subagent", + rootThreadId: parent.id, + }, + ...changes, + }); + +const index = (...threads: ReadonlyArray) => + new Map(threads.map((thread) => [thread.id, thread] as const)); + +const roles = ( + assistant: string | null, + orchestrators: Record = {}, +): ThreadRoles => ({ + assistant: assistant === null ? null : ThreadId.make(assistant), + orchestrators: Object.fromEntries( + Object.entries(orchestrators).map(([projectId, threadId]) => [ + ProjectId.make(projectId), + ThreadId.make(threadId), + ]), + ), +}); + +const byLocal = (resolved: ResolvedThreadRoles) => new Map([[local, resolved]]); + +/** The calm view's rows as short text: role rows first, then the folded ones. */ +const shown = ( + threads: ReadonlyArray, + resolved: ReadonlyMap, +) => { + const partition = calmPartition(threads, resolved, true); + if (partition.kind !== "calm") return { kind: partition.kind }; + return { + kind: partition.kind, + top: partition.roleRows.map(({ thread, role }) => `${role}:${thread.id}`), + other: partition.otherThreads.map((thread) => String(thread.id)), + waiting: partition.waitingCount, + }; +}; + +const decodeOldSettingsFile = Schema.decodeSync( + Schema.Struct({ threadRoles: ThreadRolesFromSettingsFile }), +); + +const orchestrator = row("orch", game); +const assistant = row("assistant", site); +const plain = row("plain", game); +const subagent = child("sub", orchestrator); +const sideChat = row("side", game, { + lineage: { + parentThreadId: orchestrator.id, + relationshipToParent: null, + rootThreadId: orchestrator.id, + sideChat: true, + }, +}); + +describe("resolveThreadRoles", () => { + it("reads no roles from no settings, an empty value or pointers to nothing", () => { + const threads = index(orchestrator, plain); + expect(resolveThreadRoles(undefined, threads)).toBe(NO_THREAD_ROLES); + expect(resolveThreadRoles(null, threads)).toBe(NO_THREAD_ROLES); + expect(resolveThreadRoles(roles(null), threads)).toBe(NO_THREAD_ROLES); + expect(resolveThreadRoles(roles("gone", { [game]: "gone-too" }), threads)).toBe( + NO_THREAD_ROLES, + ); + }); + + it("reads an old settings file (no threadRoles key) as no roles", () => { + const decoded = decodeOldSettingsFile({}); + expect(resolveThreadRoles(decoded.threadRoles, index(orchestrator))).toBe(NO_THREAD_ROLES); + }); + + it("keeps pointers that name a live top-level thread of the right project", () => { + const resolved = resolveThreadRoles( + roles("assistant", { [game]: "orch" }), + index(orchestrator, assistant), + ); + expect(resolved.assistant).toBe(assistant.id); + expect([...resolved.orchestrators]).toEqual([[game, orchestrator.id]]); + }); + + it("drops a bad hand-edited entry alone", () => { + const threads = index(orchestrator, row("site-orch", site)); + const bad = { + assistant: 42, + orchestrators: { [game]: "orch", [site]: 7, "": "site-orch", " padded": "site-orch" }, + } as unknown as ThreadRoles; + const resolved = resolveThreadRoles(bad, threads); + expect(resolved.assistant).toBeNull(); + expect([...resolved.orchestrators]).toEqual([[game, orchestrator.id]]); + expect(resolveThreadRoles("nonsense" as unknown as ThreadRoles, threads)).toBe(NO_THREAD_ROLES); + expect( + resolveThreadRoles({ assistant: null, orchestrators: [] } as unknown as ThreadRoles, threads), + ).toBe(NO_THREAD_ROLES); + }); + + it.each([ + { name: "archived", thread: row("orch", game, { archivedAt: "2026-11-20T10:00:00.000Z" }) }, + { name: "deleted", thread: row("orch", game, { deletedAt: "2026-11-20T10:00:00.000Z" }) }, + { name: "a sub-agent", thread: child("orch", plain) }, + { name: "a side chat", thread: { ...sideChat, id: ThreadId.make("orch") } }, + { + name: "a task delegated from a linked machine", + thread: row("orch", game, { + delegatedFrom: { environmentId: linked, threadId: ThreadId.make("p"), title: "p" }, + }), + }, + ])("counts a pointer to a thread that is $name as no role", ({ thread }) => { + expect(resolveThreadRoles(roles("orch", { [game]: "orch" }), index(thread))).toBe( + NO_THREAD_ROLES, + ); + }); + + it("drops an orchestrator moved to another project, but keeps it as the assistant", () => { + const moved = resolveThreadRoles(roles("orch", { [game]: "orch" }), index(row("orch", site))); + expect(moved.assistant).toBe(orchestrator.id); + expect(moved.orchestrators.size).toBe(0); + }); + + it("brings the role back when an archived thread is unarchived (the pointer is kept)", () => { + const setting = roles(null, { [game]: "orch" }); + const archived = row("orch", game, { archivedAt: "2026-11-20T10:00:00.000Z" }); + expect(resolveThreadRoles(setting, index(archived))).toBe(NO_THREAD_ROLES); + expect(resolveThreadRoles(setting, index(orchestrator)).orchestrators.get(game)).toBe( + orchestrator.id, + ); + }); +}); + +describe("threadRole", () => { + const resolved = resolveThreadRoles( + roles("assistant", { [game]: "orch" }), + index(orchestrator, assistant), + ); + + it("names each kind of thread", () => { + expect(threadRole(assistant, resolved)).toBe("assistant"); + expect(threadRole(orchestrator, resolved)).toBe("orchestrator"); + expect(threadRole(plain, resolved)).toBe("plain"); + expect(threadRole(subagent, resolved)).toBe("child"); + expect(threadRole(sideChat, resolved)).toBe("child"); + expect( + threadRole( + row("task", game, { + delegatedFrom: { environmentId: linked, threadId: ThreadId.make("p"), title: "p" }, + }), + resolved, + ), + ).toBe("child"); + expect(threadRole(orchestrator, undefined)).toBe("plain"); + }); + + it("makes a fork of the orchestrator plain (a new thread id, no second orchestrator)", () => { + const fork = row("orch-fork", game, { + lineage: { + parentThreadId: orchestrator.id, + relationshipToParent: "fork", + rootThreadId: orchestrator.id, + }, + }); + expect(threadRole(fork, resolved)).toBe("plain"); + }); + + it("checks the row again: roles read before the row was archived or moved lift nothing", () => { + expect(threadRole({ ...orchestrator, archivedAt: "2026-11-21T00:00:00.000Z" }, resolved)).toBe( + "plain", + ); + expect(threadRole({ ...orchestrator, deletedAt: "2026-11-21T00:00:00.000Z" }, resolved)).toBe( + "plain", + ); + expect(threadRole({ ...orchestrator, projectId: site }, resolved)).toBe("plain"); + }); + + it("keeps a thread that is both assistant and orchestrator as the assistant", () => { + const both = resolveThreadRoles(roles("orch", { [game]: "orch" }), index(orchestrator)); + expect(threadRole(orchestrator, both)).toBe("assistant"); + }); +}); + +describe("calmPartition", () => { + const list = [plain, orchestrator, assistant, row("site-plain", site)]; + const resolved = byLocal( + resolveThreadRoles(roles("assistant", { [game]: "orch" }), index(...list)), + ); + + it("is upstream's list, the same array, while calm is off", () => { + expect(calmPartition(list, resolved, false)).toEqual({ kind: "off", threads: list }); + expect((calmPartition(list, resolved, false) as { threads: unknown }).threads).toBe(list); + }); + + it("puts the assistant, then orchestrators, on top and folds the rest in list order", () => { + expect(shown(list, resolved)).toEqual({ + kind: "calm", + top: ["assistant:assistant", "orchestrator:orch"], + other: ["plain", "site-plain"], + waiting: 0, + }); + }); + + it("shows the normal list (with the hint) when no listed thread holds a role", () => { + expect(calmPartition(list, new Map(), true)).toEqual({ kind: "no-roles", threads: list }); + const toArchived = byLocal( + resolveThreadRoles( + roles(null, { [game]: "orch" }), + index({ ...orchestrator, archivedAt: "2026-11-20T10:00:00.000Z" }), + ), + ); + expect(calmPartition([plain], toArchived, true).kind).toBe("no-roles"); + }); + + it("gives an empty list for a new install with no threads", () => { + expect(calmPartition([], resolved, true)).toEqual({ kind: "no-roles", threads: [] }); + expect(calmPartition([], new Map(), false)).toEqual({ kind: "off", threads: [] }); + }); + + it("returns every thread exactly once and leaves the input as it was", () => { + const input = [...list]; + const partition = calmPartition(input, resolved, true); + if (partition.kind !== "calm") throw new Error("expected calm"); + const ids = [ + ...partition.roleRows.map(({ thread }) => thread.id), + ...partition.otherThreads.map((thread) => thread.id), + ]; + expect(ids.toSorted()).toEqual(list.map((thread) => thread.id).toSorted()); + expect(input).toEqual(list); + }); + + it("folds a project with no orchestrator into the group, with no error", () => { + const sitePlain = row("site-plain", site); + expect(shown([orchestrator, sitePlain], resolved).other).toEqual(["site-plain"]); + }); + + it("keeps a settled or snoozed role thread on top", () => { + const settled = { ...orchestrator, settledAt: "2026-11-20T10:00:00.000Z" }; + const snoozed = { ...assistant, snoozedUntil: "2099-01-01T00:00:00.000Z" }; + expect(shown([settled, snoozed, plain], resolved).top).toEqual([ + "assistant:assistant", + "orchestrator:orch", + ]); + }); + + it("shows an assistant and an orchestrator of the same project both on top", () => { + const helper = row("helper", game); + const sameProject = byLocal( + resolveThreadRoles(roles("helper", { [game]: "orch" }), index(orchestrator, helper)), + ); + expect(shown([orchestrator, helper, plain], sameProject).top).toEqual([ + "assistant:helper", + "orchestrator:orch", + ]); + }); + + it("lists a thread that holds two roles once, as the assistant", () => { + const both = byLocal( + resolveThreadRoles(roles("orch", { [game]: "orch" }), index(orchestrator)), + ); + expect(shown([orchestrator, plain], both)).toEqual({ + kind: "calm", + top: ["assistant:orch"], + other: ["plain"], + waiting: 0, + }); + }); + + it("moves the row on a handoff: the new thread on top, the old one folded", () => { + const next = row("orch-2", game); + const threads = index(orchestrator, next, plain); + const before = byLocal(resolveThreadRoles(roles(null, { [game]: "orch" }), threads)); + const after = byLocal(resolveThreadRoles(roles(null, { [game]: "orch-2" }), threads)); + expect(shown([orchestrator, next, plain], before).top).toEqual(["orchestrator:orch"]); + expect(shown([orchestrator, next, plain], after)).toEqual({ + kind: "calm", + top: ["orchestrator:orch-2"], + other: ["orch", "plain"], + waiting: 0, + }); + }); + + it("counts folded threads waiting on the person, not role rows", () => { + const waitingOrchestrator = { ...orchestrator, hasPendingApprovals: true }; + const threads = [ + waitingOrchestrator, + row("approval", game, { hasPendingApprovals: true }), + row("question", game, { hasPendingUserInput: true }), + row("child-approval", game, { pendingSubagentRequest: "approval" }), + row("guest", game, { pendingGuestMessageCount: 2 }), + plain, + ]; + expect(shown(threads, resolved)).toMatchObject({ + top: ["orchestrator:orch"], + waiting: 4, + }); + }); + + it("folds a delegated task whose parent is archived, and counts it when it waits", () => { + // Upstream lists such a task on its own again; it can never hold a role. + const task = row("task", game, { + environmentId: linked, + delegatedFrom: { environmentId: local, threadId: orchestrator.id, title: "o" }, + hasPendingApprovals: true, + }); + const pointsAtTask = new Map([ + [local, resolved.get(local)!], + [linked, resolveThreadRoles(roles("task"), index(task))], + ]); + expect(shown([orchestrator, task], pointsAtTask)).toEqual({ + kind: "calm", + top: ["orchestrator:orch"], + other: ["task"], + waiting: 1, + }); + }); + + it("keeps each server's roles to its own threads", () => { + const sameIdElsewhere = { ...orchestrator, environmentId: linked }; + expect(shown([orchestrator, sameIdElsewhere], resolved)).toEqual({ + kind: "calm", + top: ["orchestrator:orch"], + other: ["orch"], + waiting: 0, + }); + }); +}); + +it("isWaitingOnPerson follows the sidebar's approval, input and guest pills", () => { + expect(isWaitingOnPerson(plain)).toBe(false); + expect(isWaitingOnPerson({ ...plain, pendingSubagentRequest: "user_input" })).toBe(true); + expect(isWaitingOnPerson({ hasPendingApprovals: false, hasPendingUserInput: false })).toBe(false); +}); + +describe("createThreadRolesAtom", () => { + type Settings = { readonly threadRoles?: ThreadRoles } | null; + + const catalog = (entries: ReadonlyArray<[EnvironmentId, boolean]>): EnvironmentCatalogState => ({ + isReady: true, + entries: new Map( + entries.map(([environmentId, enabled]) => [ + environmentId, + { enabled } as unknown as EnvironmentCatalogState["entries"] extends ReadonlyMap< + unknown, + infer Entry + > + ? Entry + : never, + ]), + ), + }); + + const setup = () => { + const catalogAtom = Atom.make( + catalog([ + [local, true], + [linked, true], + ]), + ); + const settingsAtoms = new Map([ + [local, Atom.make(null)], + [linked, Atom.make(null)], + ]); + const threadAtoms = new Map([ + [local, Atom.make(index(orchestrator, assistant, plain))], + [linked, Atom.make(index({ ...plain, environmentId: linked, id: ThreadId.make("l") }))], + ]); + let threadReads = 0; + const rolesAtom = createThreadRolesAtom({ + catalogValueAtom: catalogAtom, + settingsValueAtom: (environmentId) => settingsAtoms.get(environmentId)!, + environmentThreadIndexAtom: (environmentId) => + Atom.make((get) => { + threadReads += 1; + return get(threadAtoms.get(environmentId)!); + }), + }); + const registry = AtomRegistry.make(); + return { + registry, + rolesAtom, + catalogAtom, + settingsAtoms, + threadAtoms, + threadReads: () => threadReads, + }; + }; + + it("is empty for servers without the setting (older servers) or not loaded yet", () => { + const { registry, rolesAtom, settingsAtoms } = setup(); + registry.set(settingsAtoms.get(local)!, {}); + expect(registry.get(rolesAtom).size).toBe(0); + registry.dispose(); + }); + + it("reads no threads while no server names a role", () => { + const { registry, rolesAtom, settingsAtoms, threadReads } = setup(); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null) }); + registry.get(rolesAtom); + expect(threadReads()).toBe(0); + registry.dispose(); + }); + + it("follows a settings change while the list is open", () => { + const { registry, rolesAtom, settingsAtoms } = setup(); + const seen: Array> = []; + const stop = registry.subscribe(rolesAtom, (value) => seen.push(value), { immediate: true }); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null, { [game]: "orch" }) }); + registry.set(settingsAtoms.get(local)!, { + threadRoles: roles("assistant", { [game]: "orch" }), + }); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null) }); + expect( + seen.map((value) => ({ + assistant: value.get(local)?.assistant ?? null, + orchestrator: value.get(local)?.orchestrators.get(game) ?? null, + })), + ).toEqual([ + { assistant: null, orchestrator: null }, + { assistant: null, orchestrator: orchestrator.id }, + { assistant: assistant.id, orchestrator: orchestrator.id }, + { assistant: null, orchestrator: null }, + ]); + stop(); + registry.dispose(); + }); + + it("keeps the same map when the same roles arrive again (a resave or a server restart)", () => { + const { registry, rolesAtom, settingsAtoms, threadAtoms } = setup(); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null, { [game]: "orch" }) }); + const first = registry.get(rolesAtom); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null, { [game]: "orch" }) }); + registry.set(threadAtoms.get(local)!, index(orchestrator, assistant, plain, row("new", game))); + expect(registry.get(rolesAtom)).toBe(first); + registry.dispose(); + }); + + it("drops the role when its thread is archived and brings it back on unarchive", () => { + const { registry, rolesAtom, settingsAtoms, threadAtoms } = setup(); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null, { [game]: "orch" }) }); + registry.set( + threadAtoms.get(local)!, + index({ ...orchestrator, archivedAt: "2026-11-20T10:00:00.000Z" }, plain), + ); + expect(registry.get(rolesAtom).has(local)).toBe(false); + registry.set(threadAtoms.get(local)!, index(orchestrator, plain)); + expect(registry.get(rolesAtom).get(local)?.orchestrators.get(game)).toBe(orchestrator.id); + registry.dispose(); + }); + + it("drops a server that goes offline or is turned off, and brings it back with it", () => { + const { registry, rolesAtom, settingsAtoms, catalogAtom } = setup(); + registry.set(settingsAtoms.get(local)!, { threadRoles: roles(null, { [game]: "orch" }) }); + registry.set(settingsAtoms.get(linked)!, { threadRoles: roles("l") }); + expect([...registry.get(rolesAtom).keys()]).toEqual([local, linked]); + registry.set( + catalogAtom, + catalog([ + [local, true], + [linked, false], + ]), + ); + expect([...registry.get(rolesAtom).keys()]).toEqual([local]); + registry.set( + catalogAtom, + catalog([ + [local, true], + [linked, true], + ]), + ); + expect(registry.get(rolesAtom).get(linked)?.assistant).toBe(ThreadId.make("l")); + registry.dispose(); + }); +}); diff --git a/packages/client-runtime/src/state/threadRoles.ts b/packages/client-runtime/src/state/threadRoles.ts new file mode 100644 index 0000000000000..4958db49a54b6 --- /dev/null +++ b/packages/client-runtime/src/state/threadRoles.ts @@ -0,0 +1,248 @@ +/** + * Fork (calm sidebar): which listed threads hold a role, and how the calm view groups a list. + * Roles are the `threadRoles` setting's pointers (docs/fork/README.md), worked out on each read and + * never stored. A pointer to a missing, deleted, archived or child thread, or to another project's + * thread for an orchestrator, counts as no role; the pointer itself is left alone. + */ +import { + type EnvironmentId, + isListedThreadLineage, + type OrchestrationV2ThreadShell, + type ProjectId, + type ThreadId, + type ThreadRoles, +} from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts"; + +/** A thread's role. `child`: a sub-agent, side chat or delegated task, shown inside its parent. */ +export type ThreadRole = "assistant" | "orchestrator" | "child" | "plain"; + +/** What the role rule reads of a thread: a live shell (dates) or a list row (text) both fit. */ +export interface ThreadRoleCandidate { + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly lineage: OrchestrationV2ThreadShell["lineage"]; + readonly delegatedFrom?: unknown; + readonly archivedAt: unknown; + readonly deletedAt?: unknown; +} + +/** One server's role pointers that name a thread able to hold the role. */ +export interface ResolvedThreadRoles { + readonly assistant: ThreadId | null; + /** Project id to its orchestrator thread. */ + readonly orchestrators: ReadonlyMap; +} + +export const NO_THREAD_ROLES: ResolvedThreadRoles = Object.freeze({ + assistant: null, + orchestrators: new Map(), +}); + +const NO_ROLES_BY_ENVIRONMENT: ReadonlyMap = new Map(); + +const isRecord = (value: unknown): value is Readonly> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isIdText = (value: unknown): value is string => + typeof value === "string" && value.length > 0 && value.trim() === value; + +/** A sub-agent, side chat or a task a linked machine delegated (upstream's `delegatedFrom != null`). */ +const isChild = (thread: ThreadRoleCandidate): boolean => + !isListedThreadLineage(thread.lineage) || thread.delegatedFrom != null; + +/** + * Whether `thread` can hold a role now: it exists, is neither deleted nor archived, is top-level + * and, for an orchestrator (`projectId` given), belongs to that project. The server's save check + * uses the same rule except archive, which only pauses a role. + */ +function canHoldRole( + thread: ThreadRoleCandidate | undefined, + projectId: string | null, +): thread is ThreadRoleCandidate { + return ( + thread !== undefined && + thread.deletedAt == null && + thread.archivedAt == null && + !isChild(thread) && + (projectId === null || thread.projectId === projectId) + ); +} + +/** + * The pointers in `roles` whose thread (looked up in `threads`, one server's) can hold the role. + * Read leniently, so a settings value from an older server or a bad hand edit gives no role for + * that entry alone: a missing or non-object value, a non-id assistant or an entry that is not an + * id pair is skipped. + */ +export function resolveThreadRoles( + roles: ThreadRoles | null | undefined, + threads: ReadonlyMap, +): ResolvedThreadRoles { + const raw: unknown = roles; + if (!isRecord(raw)) return NO_THREAD_ROLES; + const assistantId = isIdText(raw.assistant) ? (raw.assistant as ThreadId) : null; + const assistant = + assistantId !== null && canHoldRole(threads.get(assistantId), null) ? assistantId : null; + const orchestrators = new Map(); + if (isRecord(raw.orchestrators)) { + for (const [projectId, threadId] of Object.entries(raw.orchestrators)) { + if (!isIdText(projectId) || !isIdText(threadId)) continue; + if (canHoldRole(threads.get(threadId as ThreadId), projectId)) { + orchestrators.set(projectId as ProjectId, threadId as ThreadId); + } + } + } + return assistant === null && orchestrators.size === 0 + ? NO_THREAD_ROLES + : { assistant, orchestrators }; +} + +/** + * `thread`'s role on its server. The thread is checked again, so roles read a moment earlier than + * the list still never lift an archived, moved or child thread. A thread that is both the assistant + * and its project's orchestrator is the assistant. + */ +export function threadRole( + thread: ThreadRoleCandidate, + roles: ResolvedThreadRoles | undefined, +): ThreadRole { + if (isChild(thread)) return "child"; + if (roles === undefined || !canHoldRole(thread, null)) return "plain"; + if (roles.assistant === thread.id) return "assistant"; + if (roles.orchestrators.get(thread.projectId) === thread.id) return "orchestrator"; + return "plain"; +} + +/** The parts of a list row that say it waits on the person: as the sidebar's own status pills. */ +export interface CalmWaitingInput { + readonly hasPendingApprovals: boolean; + readonly hasPendingUserInput: boolean; + readonly pendingSubagentRequest?: "approval" | "user_input" | null; + readonly pendingGuestMessageCount?: number; +} + +/** Waits on the person: an approval, a question or user-only card, or a guest message. */ +export function isWaitingOnPerson(thread: CalmWaitingInput): boolean { + return ( + thread.hasPendingApprovals || + thread.hasPendingUserInput || + thread.pendingSubagentRequest != null || + (thread.pendingGuestMessageCount ?? 0) > 0 + ); +} + +export interface CalmRoleRow { + readonly thread: T; + readonly role: "assistant" | "orchestrator"; +} + +/** + * `off`: the list as given. `no-roles`: on, but no row holds a role; the list as given plus a hint, + * never all folded. `calm`: role rows on top (assistants, then orchestrators, in list order), every + * other thread in `otherThreads` in list order, and how many of those wait on the person. + */ +export type CalmPartition = + | { readonly kind: "off"; readonly threads: ReadonlyArray } + | { readonly kind: "no-roles"; readonly threads: ReadonlyArray } + | { + readonly kind: "calm"; + readonly roleRows: ReadonlyArray>; + readonly otherThreads: ReadonlyArray; + readonly waitingCount: number; + }; + +/** + * Groups a list of threads (normally the navigation list: no archived, child or tag-hidden rows) + * for the calm view. Grouping only: every thread given comes back once, so search, drafts and + * links are untouched. Settle and snooze do not matter; a role row stays on top. + */ +export function calmPartition< + T extends ThreadRoleCandidate & CalmWaitingInput & { readonly environmentId: EnvironmentId }, +>( + threads: ReadonlyArray, + rolesByEnvironment: ReadonlyMap, + enabled: boolean, +): CalmPartition { + if (!enabled) return { kind: "off", threads }; + const assistants: Array> = []; + const orchestrators: Array> = []; + const otherThreads: Array = []; + let waitingCount = 0; + for (const thread of threads) { + const role = threadRole(thread, rolesByEnvironment.get(thread.environmentId)); + if (role === "assistant") assistants.push({ thread, role }); + else if (role === "orchestrator") orchestrators.push({ thread, role }); + else { + otherThreads.push(thread); + if (isWaitingOnPerson(thread)) waitingCount += 1; + } + } + if (assistants.length === 0 && orchestrators.length === 0) return { kind: "no-roles", threads }; + return { kind: "calm", roleRows: [...assistants, ...orchestrators], otherThreads, waitingCount }; +} + +function sameRoles(a: ResolvedThreadRoles, b: ResolvedThreadRoles): boolean { + if (a === b) return true; + if (a.assistant !== b.assistant || a.orchestrators.size !== b.orchestrators.size) return false; + for (const [projectId, threadId] of a.orchestrators) { + if (b.orchestrators.get(projectId) !== threadId) return false; + } + return true; +} + +function sameRolesByEnvironment( + a: ReadonlyMap, + b: ReadonlyMap, +): boolean { + if (a.size !== b.size) return false; + for (const [environmentId, roles] of a) { + const other = b.get(environmentId); + if (other === undefined || !sameRoles(roles, other)) return false; + } + return true; +} + +const hasPointer = (roles: ThreadRoles | null | undefined): boolean => { + const raw: unknown = roles; + return ( + isRecord(raw) && + (raw.assistant != null || + (isRecord(raw.orchestrators) && Object.keys(raw.orchestrators).length > 0)) + ); +}; + +/** + * The resolved roles of every connected, enabled server, by environment; a server with none (or an + * older one without the setting) is left out. It follows settings pushes and thread changes, and + * keeps the same map while the result is equal, so a list that reads it redraws only on a change. + * Threads are read only on servers that name a role, so streaming costs nothing while none do. + */ +export function createThreadRolesAtom(input: { + readonly catalogValueAtom: Atom.Atom; + readonly settingsValueAtom: ( + environmentId: EnvironmentId, + ) => Atom.Atom<{ readonly threadRoles?: ThreadRoles } | null>; + readonly environmentThreadIndexAtom: ( + environmentId: EnvironmentId, + ) => Atom.Atom>; +}): Atom.Atom> { + let previous = NO_ROLES_BY_ENVIRONMENT; + return Atom.make((get) => { + const next = new Map(); + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + const roles = get(input.settingsValueAtom(environmentId))?.threadRoles; + if (!hasPointer(roles)) continue; + const resolved = resolveThreadRoles( + roles, + get(input.environmentThreadIndexAtom(environmentId)), + ); + if (resolved !== NO_THREAD_ROLES) next.set(environmentId, resolved); + } + if (sameRolesByEnvironment(previous, next)) return previous; + previous = next.size === 0 ? NO_ROLES_BY_ENVIRONMENT : next; + return previous; + }).pipe(Atom.withLabel("fork-thread-roles")); +} From 2f06950993f4e4dbcf76b76b599a210d054e3c62 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:10:35 +0000 Subject: [PATCH 2/2] Calm sidebar part 2: no hint on an empty list; say why usage limits are not counted Review follow-up. A new install with no threads now gets the list as given (kind "off"), as the design's empty-state row says, so the sidebar never shows the pick-a-role hint on an empty list. The waiting count leaves out a usage-limit stop on purpose (it clears without the person); the doc comment now says so. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/state/threadRoles.test.ts | 5 +++-- packages/client-runtime/src/state/threadRoles.ts | 11 +++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/client-runtime/src/state/threadRoles.test.ts b/packages/client-runtime/src/state/threadRoles.test.ts index e785489d4e2a4..5b2c6c2d4e0d4 100644 --- a/packages/client-runtime/src/state/threadRoles.test.ts +++ b/packages/client-runtime/src/state/threadRoles.test.ts @@ -281,8 +281,9 @@ describe("calmPartition", () => { expect(calmPartition([plain], toArchived, true).kind).toBe("no-roles"); }); - it("gives an empty list for a new install with no threads", () => { - expect(calmPartition([], resolved, true)).toEqual({ kind: "no-roles", threads: [] }); + it("gives an empty list without the hint for a new install with no threads", () => { + expect(calmPartition([], resolved, true)).toEqual({ kind: "off", threads: [] }); + expect(calmPartition([], new Map(), true)).toEqual({ kind: "off", threads: [] }); expect(calmPartition([], new Map(), false)).toEqual({ kind: "off", threads: [] }); }); diff --git a/packages/client-runtime/src/state/threadRoles.ts b/packages/client-runtime/src/state/threadRoles.ts index 4958db49a54b6..7303d69748bd6 100644 --- a/packages/client-runtime/src/state/threadRoles.ts +++ b/packages/client-runtime/src/state/threadRoles.ts @@ -124,7 +124,10 @@ export interface CalmWaitingInput { readonly pendingGuestMessageCount?: number; } -/** Waits on the person: an approval, a question or user-only card, or a guest message. */ +/** + * Waits on the person: an approval, a question or user-only card, or a guest message. A usage-limit + * stop is left out on purpose: it clears without the person. + */ export function isWaitingOnPerson(thread: CalmWaitingInput): boolean { return ( thread.hasPendingApprovals || @@ -140,8 +143,8 @@ export interface CalmRoleRow { } /** - * `off`: the list as given. `no-roles`: on, but no row holds a role; the list as given plus a hint, - * never all folded. `calm`: role rows on top (assistants, then orchestrators, in list order), every + * `off`: the list as given (calm off, or no threads). `no-roles`: no row holds a role; the list as + * given plus a hint, never all folded. `calm`: role rows on top (assistants, then orchestrators, in list order), every * other thread in `otherThreads` in list order, and how many of those wait on the person. */ export type CalmPartition = @@ -166,7 +169,7 @@ export function calmPartition< rolesByEnvironment: ReadonlyMap, enabled: boolean, ): CalmPartition { - if (!enabled) return { kind: "off", threads }; + if (!enabled || threads.length === 0) return { kind: "off", threads }; const assistants: Array> = []; const orchestrators: Array> = []; const otherThreads: Array = [];