From 09002cc3469e41aa5f3a0692f2b75c3b60b1d75a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 14 Nov 2026 09:58:03 +0000 Subject: [PATCH] feat(threads): tag threads with owner and type for founder inboxes Shared threads can record who they are for, what kind of work they are, and who started them. Founder inboxes hide bot-to-bot threads until search or a toggle asks for them, and untagged threads stay on the shared list. Model: Grok 4.7 Task: feature Agent: cursor Co-authored-by: Kameron Smith --- .../src/features/home/homeThreadList.ts | 14 ++ .../src/features/threads/threadListV2.ts | 10 ++ apps/mobile/src/lib/projectThreadStartTurn.ts | 7 + apps/server/src/mcp/McpHttpServer.ts | 7 + .../src/mcp/toolkits/threads/handlers.test.ts | 145 ++++++++++++++++++ .../src/mcp/toolkits/threads/handlers.ts | 79 ++++++++++ apps/server/src/mcp/toolkits/threads/tools.ts | 97 ++++++++++++ .../Layers/ProjectionPipeline.test.ts | 96 ++++++++++++ .../Layers/ProjectionPipeline.ts | 10 ++ .../Layers/ProjectionSnapshotQuery.ts | 31 ++++ .../src/orchestration/decider.inbox.test.ts | 137 +++++++++++++++++ apps/server/src/orchestration/decider.ts | 6 + apps/server/src/orchestration/projector.ts | 6 + .../Layers/ProjectionRepositories.test.ts | 56 +++++++ .../persistence/Layers/ProjectionThreads.ts | 12 ++ apps/server/src/persistence/Migrations.ts | 2 + .../057_ProjectionThreadsInboxRouting.ts | 29 ++++ .../persistence/Services/ProjectionThreads.ts | 4 + apps/server/src/ws.ts | 18 +++ apps/web/src/components/ChatView.tsx | 4 +- apps/web/src/components/Sidebar.tsx | 59 ++++++- .../components/sidebar/SidebarInboxBar.tsx | 117 ++++++++++++++ .../components/threadActionMenu.logic.test.ts | 12 +- .../src/components/threadActionMenu.logic.ts | 66 +++++++- apps/web/src/contextMenuFallback.ts | 13 ++ apps/web/src/hooks/useThreadActionMenu.ts | 17 ++ apps/web/src/uiStateStore.test.ts | 15 ++ apps/web/src/uiStateStore.ts | 97 +++++++++++- packages/client-runtime/package.json | 4 + .../client-runtime/src/state/threadDetail.ts | 3 + .../src/state/threadInbox.test.ts | 56 +++++++ .../client-runtime/src/state/threadInbox.ts | 56 +++++++ .../src/state/threadReducer.test.ts | 45 ++++++ .../client-runtime/src/state/threadReducer.ts | 10 ++ .../src/work-log/presentation.ts | 1 + packages/contracts/src/orchestration.test.ts | 4 + packages/contracts/src/orchestration.ts | 31 ++++ 37 files changed, 1365 insertions(+), 11 deletions(-) create mode 100644 apps/server/src/mcp/toolkits/threads/handlers.test.ts create mode 100644 apps/server/src/mcp/toolkits/threads/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/threads/tools.ts create mode 100644 apps/server/src/orchestration/decider.inbox.test.ts create mode 100644 apps/server/src/persistence/Migrations/057_ProjectionThreadsInboxRouting.ts create mode 100644 apps/web/src/components/sidebar/SidebarInboxBar.tsx create mode 100644 packages/client-runtime/src/state/threadInbox.test.ts create mode 100644 packages/client-runtime/src/state/threadInbox.ts diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 895c73bbe266e..aee22f155f5bf 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -1,4 +1,5 @@ import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; +import { threadVisibleInInbox } from "@t3tools/client-runtime/state/thread-inbox"; import { buildProjectGroups, derivePhysicalProjectKey, @@ -218,8 +219,13 @@ export function buildHomeThreadGroups(input: { readonly projectGroupingMode: SidebarProjectGroupingMode; /** Current time used for the recency window; defaults to now. Injectable for tests. */ readonly now?: number; + /** Founder inbox. Null keeps the shared list. */ + readonly inboxIdentity?: string | null; + /** Bot-to-bot threads stay hidden unless this or a search query asks for them. */ + readonly showBotWork?: boolean; }): ReadonlyArray { const now = input.now ?? Date.now(); + const searching = input.searchQuery.trim().length > 0; const groups = new Map(); const groupTitleByKey = new Map(); const groupKeyByProjectKey = new Map(); @@ -279,6 +285,14 @@ export function buildHomeThreadGroups(input: { if (thread.archivedAt !== null) { continue; } + if ( + !threadVisibleInInbox(thread, { + identity: input.inboxIdentity ?? null, + showBotWork: input.showBotWork ?? searching, + }) + ) { + continue; + } if (input.environmentId !== null && thread.environmentId !== input.environmentId) { continue; } diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index e1cb8e9ece7f0..16a8c1c087fc1 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -9,6 +9,7 @@ import { import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { threadVisibleInInbox } from "@t3tools/client-runtime/state/thread-inbox"; import { sortActiveThreadsByOrderKey, resolveSettledThreadTimestamp, @@ -183,6 +184,7 @@ export function getThreadListV2OrderedSection(input: { }): EnvironmentThreadShell[] { const threads = input.threads.filter((thread) => { if (thread.archivedAt !== null) return false; + if (!threadVisibleInInbox(thread, { identity: null, showBotWork: false })) return false; if ( (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) && thread.settledOverride === "settled" && @@ -395,6 +397,14 @@ export function buildThreadListV2Items(input: { for (const thread of input.threads) { // Callers pass live shells. The server stamps settledOverride for the tail. if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue; + if ( + !threadVisibleInInbox(thread, { + identity: null, + showBotWork: query.length > 0, + }) + ) { + continue; + } if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) { continue; } diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts index b843475dc52fa..b09c042f370e2 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -7,6 +7,7 @@ import { type ProjectId, type ProviderInteractionMode, type RuntimeMode, + type ThreadInboxType, } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; @@ -43,6 +44,9 @@ export interface ProjectThreadStartTurnSpec { readonly startFromOrigin: boolean; /** Generated temp branch for worktree mode; unused for local mode. */ readonly worktreeBranchName: string; + readonly owner?: string | null; + readonly threadType?: ThreadInboxType | null; + readonly startedBy?: string | null; } /** @@ -81,6 +85,9 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe // Coordinator gets its dedicated scratch directory from the server. worktreePath: null, createdAt: spec.createdAt, + ...(spec.owner !== undefined ? { owner: spec.owner } : {}), + ...(spec.threadType !== undefined ? { threadType: spec.threadType } : {}), + ...(spec.startedBy !== undefined ? { startedBy: spec.startedBy } : {}), }, ...(isWorktree ? { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5a8cb573ad88b..a1688177b92b6 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -31,6 +31,8 @@ import { } from "./toolkits/preview/tools.ts"; import { PullRequestsToolkitHandlersLive } from "./toolkits/pullRequests/handlers.ts"; import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts"; +import { ThreadRoutingToolkitHandlersLive } from "./toolkits/threads/handlers.ts"; +import { ThreadRoutingToolkit } from "./toolkits/threads/tools.ts"; import { DeviceScreenshotToolkitHandlersLive, DeviceStandardToolkitHandlersLive, @@ -608,6 +610,10 @@ export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequest Layer.provide(PullRequestsToolkitHandlersLive), ); +export const ThreadRoutingToolkitRegistrationLive = McpServer.toolkit(ThreadRoutingToolkit).pipe( + Layer.provide(ThreadRoutingToolkitHandlersLive), +); + const DeviceStandardToolkitRegistrationLive = McpServer.toolkit(DeviceStandardToolkit).pipe( Layer.provide(DeviceStandardToolkitHandlersLive), ); @@ -631,5 +637,6 @@ const McpTransportLive = McpServer.layerHttp({ export const layer = Layer.mergeAll( PreviewToolkitRegistrationLive, PullRequestsToolkitRegistrationLive, + ThreadRoutingToolkitRegistrationLive, DeviceToolkitRegistrationLive, ).pipe(Layer.provideMerge(McpTransportLive)); diff --git a/apps/server/src/mcp/toolkits/threads/handlers.test.ts b/apps/server/src/mcp/toolkits/threads/handlers.test.ts new file mode 100644 index 0000000000000..c775e12e1965c --- /dev/null +++ b/apps/server/src/mcp/toolkits/threads/handlers.test.ts @@ -0,0 +1,145 @@ +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationCommand, + type OrchestrationThreadShell, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import type { Tool } from "effect/unstable/ai"; + +import { + OrchestrationEngineService, + type OrchestrationEngineShape, +} from "../../../orchestration/Services/OrchestrationEngine.ts"; +import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { ThreadRoutingToolkitHandlersLive } from "./handlers.ts"; +import { ThreadRoutingToolkit } from "./tools.ts"; + +const THREAD_ID = ThreadId.make("thread-1"); + +const testCrypto = Crypto.make({ + randomBytes: (size) => new Uint8Array(size).fill(7), + digest: (_algorithm, data) => Effect.succeed(data), +}); + +const invocation = (): McpInvocationContext.McpInvocationScope => ({ + environmentId: EnvironmentId.make("environment-1"), + threadId: THREAD_ID, + providerSessionId: "provider-session-1", + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["pull-requests"]), + issuedAt: 1, +}); + +function makeThread(patch: Partial = {}): OrchestrationThreadShell { + return { + id: THREAD_ID, + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + pullRequests: [], + latestTurn: null, + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-20T00:00:00.000Z", + archivedAt: null, + settledOverride: null, + settledAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + ...patch, + }; +} + +const makeHarness = Effect.fn(function* ( + options: { readonly thread?: OrchestrationThreadShell | null } = {}, +) { + const commands = yield* Ref.make>([]); + const thread = options.thread === undefined ? makeThread() : options.thread; + const dispatch: OrchestrationEngineShape["dispatch"] = (command) => + Effect.gen(function* () { + yield* Ref.update(commands, (recorded) => [...recorded, command]); + return { sequence: 1 }; + }); + const dependencies = Layer.mergeAll( + Layer.mock(ProjectionSnapshotQuery)({ + getThreadShellById: (threadId) => + Effect.succeed( + thread !== null && threadId === thread.id ? Option.some(thread) : Option.none(), + ), + }), + Layer.mock(OrchestrationEngineService)({ + readEvents: () => Stream.empty, + dispatch, + streamDomainEvents: Stream.empty, + latestSequence: Effect.succeed(0), + }), + Layer.succeed(Crypto.Crypto, testCrypto), + ); + const toolkit = yield* ThreadRoutingToolkit.pipe( + Effect.provide(ThreadRoutingToolkitHandlersLive.pipe(Layer.provide(dependencies))), + ); + const call = (params: Parameters>[1]) => + toolkit.handle("set_thread_routing", params).pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map( + (chunk) => + chunk.at(-1)!.result as Tool.Success< + (typeof ThreadRoutingToolkit.tools)["set_thread_routing"] + >, + ), + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation()), + Effect.provide(dependencies), + ); + return { commands, call }; +}); + +describe("thread routing toolkit", () => { + it.effect("tags the calling thread and leaves omitted fields alone", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + thread: makeThread({ owner: "Jeff", startedBy: "Lead" }), + }); + const result = yield* harness.call({ threadType: "needs-human" }); + expect(result).toEqual({ + threadId: THREAD_ID, + owner: "Jeff", + threadType: "needs-human", + startedBy: "Lead", + }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { + type: "thread.meta.update", + threadId: THREAD_ID, + threadType: "needs-human", + }, + ]); + expect((yield* Ref.get(harness.commands))[0]).not.toHaveProperty("owner"); + }), + ); + + it.effect("rejects a call that changes nothing", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const error = yield* harness.call({}).pipe(Effect.flip); + expect(error._tag).toBe("ThreadRoutingInvalidError"); + expect(yield* Ref.get(harness.commands)).toEqual([]); + }), + ); +}); diff --git a/apps/server/src/mcp/toolkits/threads/handlers.ts b/apps/server/src/mcp/toolkits/threads/handlers.ts new file mode 100644 index 0000000000000..4438f1391bdf8 --- /dev/null +++ b/apps/server/src/mcp/toolkits/threads/handlers.ts @@ -0,0 +1,79 @@ +import { CommandId, type OrchestrationThreadShell, type ThreadId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts"; +import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import { + type SetThreadRoutingInput, + type SetThreadRoutingResult, + ThreadRoutingFailedError, + ThreadRoutingInvalidError, + ThreadRoutingNotFoundError, + ThreadRoutingToolkit, +} from "./tools.ts"; + +const make = Effect.gen(function* () { + const engine = yield* OrchestrationEngine.OrchestrationEngineService; + const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery; + const crypto = yield* Crypto.Crypto; + + const commandId = (threadId: ThreadId) => + crypto.randomUUIDv4.pipe( + Effect.orDie, + Effect.map((uuid) => CommandId.make(`server:mcp-thread-routing:${threadId}:${uuid}`)), + ); + + const failRouting = (cause: Cause.Cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.fail(new ThreadRoutingFailedError({ cause })); + + return ThreadRoutingToolkit.of({ + set_thread_routing: Effect.fn("ThreadRoutingToolkit.setThreadRouting")(function* (input) { + if ( + input.owner === undefined && + input.threadType === undefined && + input.startedBy === undefined + ) { + return yield* new ThreadRoutingInvalidError({}); + } + const scope = yield* McpInvocationContext.McpInvocationContext; + const threadId = input.threadId ?? scope.threadId; + const thread = yield* snapshots + .getThreadShellById(threadId) + .pipe(Effect.mapError((cause) => new ThreadRoutingFailedError({ cause }))); + if (Option.isNone(thread)) { + return yield* new ThreadRoutingNotFoundError({ threadId }); + } + yield* engine + .dispatch({ + type: "thread.meta.update", + commandId: yield* commandId(threadId), + threadId, + ...(input.owner !== undefined ? { owner: input.owner } : {}), + ...(input.threadType !== undefined ? { threadType: input.threadType } : {}), + ...(input.startedBy !== undefined ? { startedBy: input.startedBy } : {}), + }) + .pipe(Effect.catchCause(failRouting)); + return routingResult(thread.value, input); + }), + }); +}); + +function routingResult( + thread: OrchestrationThreadShell, + input: SetThreadRoutingInput, +): SetThreadRoutingResult { + return { + threadId: input.threadId ?? thread.id, + owner: input.owner !== undefined ? input.owner : (thread.owner ?? null), + threadType: input.threadType !== undefined ? input.threadType : (thread.threadType ?? null), + startedBy: input.startedBy !== undefined ? input.startedBy : (thread.startedBy ?? null), + }; +} + +export const ThreadRoutingToolkitHandlersLive = ThreadRoutingToolkit.toLayer(make); diff --git a/apps/server/src/mcp/toolkits/threads/tools.ts b/apps/server/src/mcp/toolkits/threads/tools.ts new file mode 100644 index 0000000000000..b1da0ab67b45d --- /dev/null +++ b/apps/server/src/mcp/toolkits/threads/tools.ts @@ -0,0 +1,97 @@ +import { ThreadId, ThreadInboxType, TrimmedNonEmptyString } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import * as Tool from "effect/unstable/ai/Tool"; +import * as Toolkit from "effect/unstable/ai/Toolkit"; + +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts"; +import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts"; + +const dependencies = [ + McpInvocationContext.McpInvocationContext, + OrchestrationEngine.OrchestrationEngineService, + ProjectionSnapshotQuery.ProjectionSnapshotQuery, +]; + +export const SetThreadRoutingInput = Schema.Struct({ + threadId: Schema.optional( + Schema.NullOr(ThreadId).annotate({ + description: "Thread to tag. Omit to tag the calling thread.", + }), + ), + owner: Schema.optional( + Schema.NullOr(TrimmedNonEmptyString).annotate({ + description: + "Who the thread is for. Free-form. Known values: Kameron, Jeff, Lead, Jeff's Lead. Null clears the owner.", + }), + ), + threadType: Schema.optional( + Schema.NullOr(ThreadInboxType).annotate({ + description: + "needs-human when a person should act, fyi for context, bot-work for bot-to-bot threads. Null clears the type.", + }), + ), + startedBy: Schema.optional( + Schema.NullOr(TrimmedNonEmptyString).annotate({ + description: "Who opened the thread. Null clears it. Usually set at creation.", + }), + ), +}); +export type SetThreadRoutingInput = typeof SetThreadRoutingInput.Type; + +export const SetThreadRoutingResult = Schema.Struct({ + threadId: ThreadId, + owner: Schema.NullOr(Schema.String), + threadType: Schema.NullOr(ThreadInboxType), + startedBy: Schema.NullOr(Schema.String), +}); +export type SetThreadRoutingResult = typeof SetThreadRoutingResult.Type; + +export class ThreadRoutingInvalidError extends Schema.TaggedError()( + "ThreadRoutingInvalidError", + {}, +) { + override get message(): string { + return "Pass owner, threadType, or startedBy. Omit a field to leave it unchanged; null clears it."; + } +} + +export class ThreadRoutingNotFoundError extends Schema.TaggedError()( + "ThreadRoutingNotFoundError", + { threadId: ThreadId }, +) { + override get message(): string { + return `Thread ${this.threadId} was not found.`; + } +} + +export class ThreadRoutingFailedError extends Schema.TaggedError()( + "ThreadRoutingFailedError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not update the thread's owner or type."; + } +} + +const ThreadRoutingError = Schema.Union([ + ThreadRoutingInvalidError, + ThreadRoutingNotFoundError, + ThreadRoutingFailedError, +]); + +const SetThreadRoutingTool = Tool.make("set_thread_routing", { + description: + "Tag a thread in the shared inbox. owner is who it is for (Kameron, Jeff, Lead, Jeff's Lead, or any other name). threadType is needs-human, fyi, or bot-work. startedBy is who opened it. Bot-work stays out of founder inboxes until someone shows it. Pass the same fields on thread.create and thread.turn.start bootstrap.createThread when opening a thread. Omit threadId to tag this thread. Omit a field to leave it; null clears it.", + parameters: SetThreadRoutingInput, + success: SetThreadRoutingResult, + failure: ThreadRoutingError, + dependencies, +}) + .annotate(Tool.Title, "Set thread owner and type") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false); + +export const ThreadRoutingToolkit = Toolkit.make(SetThreadRoutingTool); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 3bc2abd62638d..477833a49184b 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -4821,3 +4821,99 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { }), ); }); + +it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-inbox-routing-")))( + "OrchestrationProjectionPipeline inbox routing", + (it) => { + it.effect("persists owner, type, and starter, then a later retag", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const now = "2026-11-14T00:00:00.000Z"; + const later = "2026-11-14T00:00:01.000Z"; + const projectId = ProjectId.make("project-inbox"); + const threadId = ThreadId.make("thread-inbox"); + + yield* eventStore.append({ + type: "project.created", + eventId: EventId.make("evt-inbox-1"), + aggregateKind: "project", + aggregateId: projectId, + occurredAt: now, + commandId: CommandId.make("cmd-inbox-1"), + causationEventId: null, + correlationId: CommandId.make("cmd-inbox-1"), + metadata: {}, + payload: { + projectId, + title: "Inbox", + workspaceRoot: "/tmp/inbox", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + }, + }); + yield* eventStore.append({ + type: "thread.created", + eventId: EventId.make("evt-inbox-2"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("cmd-inbox-2"), + causationEventId: null, + correlationId: CommandId.make("cmd-inbox-2"), + metadata: {}, + payload: { + threadId, + projectId, + title: "Needs Kameron", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + createdAt: now, + updatedAt: now, + }, + }); + yield* eventStore.append({ + type: "thread.meta-updated", + eventId: EventId.make("evt-inbox-3"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: later, + commandId: CommandId.make("cmd-inbox-3"), + causationEventId: null, + correlationId: CommandId.make("cmd-inbox-3"), + metadata: {}, + payload: { + threadId, + threadType: "bot-work", + owner: null, + updatedAt: later, + }, + }); + + yield* projectionPipeline.bootstrap; + const rows = yield* sql<{ + readonly owner: string | null; + readonly threadType: string | null; + readonly startedBy: string | null; + }>` + SELECT owner, thread_type AS "threadType", started_by AS "startedBy" + FROM projection_threads + WHERE thread_id = ${threadId} + `; + assert.deepEqual(rows, [{ owner: null, threadType: "bot-work", startedBy: "Lead" }]); + }), + ); + }, +); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index f73c036562e14..061af2805ce7a 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -620,6 +620,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti branch: event.payload.branch, worktreePath: event.payload.worktreePath, executionScope: event.payload.executionScope ?? null, + owner: event.payload.owner ?? null, + threadType: event.payload.threadType ?? null, + startedBy: event.payload.startedBy ?? null, linkedPullRequest: null, branchPullRequest: null, latestTurnId: null, @@ -833,6 +836,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...(event.payload.branchPullRequest !== undefined ? { branchPullRequest: event.payload.branchPullRequest } : {}), + ...(event.payload.owner !== undefined ? { owner: event.payload.owner } : {}), + ...(event.payload.threadType !== undefined + ? { threadType: event.payload.threadType } + : {}), + ...(event.payload.startedBy !== undefined + ? { startedBy: event.payload.startedBy } + : {}), updatedAt: event.payload.updatedAt, }); // Legacy single-link events replay into the link table. The old diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 0c80c49b15508..8ad38694b6e03 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -378,6 +378,19 @@ function mapTitleRegeneration(row: Schema.Schema.Type, ): OrchestrationSession { @@ -596,6 +609,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { snoozed_until AS "snoozedUntil", snoozed_at AS "snoozedAt", pinned_at AS "pinnedAt", + owner, + thread_type AS "threadType", + started_by AS "startedBy", pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", title_regeneration_request_id AS "titleRegenerationRequestId", @@ -638,6 +654,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { snoozed_until AS "snoozedUntil", snoozed_at AS "snoozedAt", pinned_at AS "pinnedAt", + owner, + thread_type AS "threadType", + started_by AS "startedBy", pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", title_regeneration_request_id AS "titleRegenerationRequestId", @@ -712,6 +731,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { snoozed_until AS "snoozedUntil", snoozed_at AS "snoozedAt", pinned_at AS "pinnedAt", + owner, + thread_type AS "threadType", + started_by AS "startedBy", pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", title_regeneration_request_id AS "titleRegenerationRequestId", @@ -1278,6 +1300,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { snoozed_until AS "snoozedUntil", snoozed_at AS "snoozedAt", pinned_at AS "pinnedAt", + owner, + thread_type AS "threadType", + started_by AS "startedBy", pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", title_regeneration_request_id AS "titleRegenerationRequestId", @@ -2356,6 +2381,7 @@ pending_approval_requests AS ( snoozedAt: row.snoozedAt, pinnedAt: row.pinnedAt, pinOrderKey: row.pinOrderKey ?? null, + ...threadRoutingFromRow(row), activeOrderKey: row.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, @@ -2602,6 +2628,7 @@ pending_approval_requests AS ( snoozedAt: row.snoozedAt, pinnedAt: row.pinnedAt, pinOrderKey: row.pinOrderKey ?? null, + ...threadRoutingFromRow(row), activeOrderKey: row.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, @@ -2760,6 +2787,7 @@ pending_approval_requests AS ( snoozedAt: row.snoozedAt, pinnedAt: row.pinnedAt, pinOrderKey: row.pinOrderKey ?? null, + ...threadRoutingFromRow(row), activeOrderKey: row.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, @@ -2926,6 +2954,7 @@ pending_approval_requests AS ( snoozedAt: row.snoozedAt, pinnedAt: row.pinnedAt, pinOrderKey: row.pinOrderKey ?? null, + ...threadRoutingFromRow(row), activeOrderKey: row.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, @@ -3286,6 +3315,7 @@ pending_approval_requests AS ( snoozedAt: threadRow.value.snoozedAt, pinnedAt: threadRow.value.pinnedAt, pinOrderKey: threadRow.value.pinOrderKey ?? null, + ...threadRoutingFromRow(threadRow.value), activeOrderKey: threadRow.value.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(threadRow.value), titleState: threadRow.value.titleState, @@ -3589,6 +3619,7 @@ pending_approval_requests AS ( snoozedAt: threadRow.value.snoozedAt, pinnedAt: threadRow.value.pinnedAt, pinOrderKey: threadRow.value.pinOrderKey ?? null, + ...threadRoutingFromRow(threadRow.value), activeOrderKey: threadRow.value.activeOrderKey ?? null, titleRegeneration: mapTitleRegeneration(threadRow.value), titleState: threadRow.value.titleState, diff --git a/apps/server/src/orchestration/decider.inbox.test.ts b/apps/server/src/orchestration/decider.inbox.test.ts new file mode 100644 index 0000000000000..b3cb937e596ba --- /dev/null +++ b/apps/server/src/orchestration/decider.inbox.test.ts @@ -0,0 +1,137 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { CommandId, EventId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import { decideOrchestrationCommand } from "./decider.ts"; +import { createEmptyReadModel, projectEvent } from "./projector.ts"; + +it.layer(NodeServices.layer)("thread inbox routing", (it) => { + it.effect("copies owner, type, and starter onto the created event", () => + Effect.gen(function* () { + const createdAt = "2026-11-14T08:00:00.000Z"; + const projectId = ProjectId.make("project-1"); + const readModel = yield* projectEvent(createEmptyReadModel(createdAt), { + sequence: 1, + eventId: EventId.make("event-project-created"), + aggregateKind: "project", + aggregateId: projectId, + type: "project.created", + occurredAt: createdAt, + commandId: CommandId.make("command-project-created"), + causationEventId: null, + correlationId: CommandId.make("command-project-created"), + metadata: {}, + payload: { + projectId, + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: null, + scripts: [], + createdAt, + updatedAt: createdAt, + }, + }); + + const created = yield* decideOrchestrationCommand({ + command: { + type: "thread.create", + commandId: CommandId.make("command-create"), + threadId: ThreadId.make("thread-1"), + projectId, + title: "Shared pool", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + createdAt, + }, + readModel, + }); + expect(created).toMatchObject({ + type: "thread.created", + payload: { owner: "Kameron", threadType: "needs-human", startedBy: "Lead" }, + }); + }), + ); + + it.effect("retags an existing thread without dropping the starter", () => + Effect.gen(function* () { + const createdAt = "2026-11-14T08:00:00.000Z"; + const projectId = ProjectId.make("project-1"); + const threadId = ThreadId.make("thread-1"); + const withProject = yield* projectEvent(createEmptyReadModel(createdAt), { + sequence: 1, + eventId: EventId.make("event-project-created"), + aggregateKind: "project", + aggregateId: projectId, + type: "project.created", + occurredAt: createdAt, + commandId: CommandId.make("command-project-created"), + causationEventId: null, + correlationId: CommandId.make("command-project-created"), + metadata: {}, + payload: { + projectId, + title: "Project", + workspaceRoot: "/tmp/project", + defaultModelSelection: null, + scripts: [], + createdAt, + updatedAt: createdAt, + }, + }); + const readModel = yield* projectEvent(withProject, { + sequence: 2, + eventId: EventId.make("event-thread-created"), + aggregateKind: "thread", + aggregateId: threadId, + type: "thread.created", + occurredAt: createdAt, + commandId: CommandId.make("command-create"), + causationEventId: null, + correlationId: CommandId.make("command-create"), + metadata: {}, + payload: { + threadId, + projectId, + title: "Shared pool", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + createdAt, + updatedAt: createdAt, + }, + }); + expect(readModel.threads[0]).toMatchObject({ + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + }); + + const updated = yield* decideOrchestrationCommand({ + command: { + type: "thread.meta.update", + commandId: CommandId.make("command-update"), + threadId, + threadType: "bot-work", + owner: null, + }, + readModel, + }); + expect(updated).toMatchObject({ + type: "thread.meta-updated", + payload: { threadType: "bot-work", owner: null }, + }); + }), + ); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index db8796de67fe2..e4623a30c8524 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -406,6 +406,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" worktreePath: command.worktreePath, executionScope: command.executionScope ?? (command.historyImport === true ? null : "coding"), + ...(command.owner !== undefined ? { owner: command.owner } : {}), + ...(command.threadType !== undefined ? { threadType: command.threadType } : {}), + ...(command.startedBy !== undefined ? { startedBy: command.startedBy } : {}), createdAt: command.createdAt, updatedAt: command.createdAt, }, @@ -1031,6 +1034,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.linkedPullRequest !== undefined ? { linkedPullRequest: command.linkedPullRequest } : {}), + ...(command.owner !== undefined ? { owner: command.owner } : {}), + ...(command.threadType !== undefined ? { threadType: command.threadType } : {}), + ...(command.startedBy !== undefined ? { startedBy: command.startedBy } : {}), updatedAt: occurredAt, }, }; diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index dad0bf1fbfea9..3f67b694d8b79 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -431,6 +431,9 @@ export function projectEvent( branch: payload.branch, worktreePath: payload.worktreePath, executionScope: payload.executionScope ?? null, + ...(payload.owner !== undefined ? { owner: payload.owner } : {}), + ...(payload.threadType !== undefined ? { threadType: payload.threadType } : {}), + ...(payload.startedBy !== undefined ? { startedBy: payload.startedBy } : {}), pullRequests: [], branchPullRequest: null, latestTurn: null, @@ -627,6 +630,9 @@ export function projectEvent( ...(payload.activeOrderKey !== undefined ? { activeOrderKey: payload.activeOrderKey } : {}), + ...(payload.owner !== undefined ? { owner: payload.owner } : {}), + ...(payload.threadType !== undefined ? { threadType: payload.threadType } : {}), + ...(payload.startedBy !== undefined ? { startedBy: payload.startedBy } : {}), ...(payload.branchPullRequest !== undefined ? { branchPullRequest: payload.branchPullRequest } : {}), diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index 4be65bd5650c5..c4ef1f968886f 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -468,6 +468,62 @@ projectionRepositoriesLayer("Projection repositories", (it) => { }), ); + it.effect("round-trips inbox owner, type, and starter", () => + Effect.gen(function* () { + const threads = yield* ProjectionThreadRepository; + yield* threads.upsert({ + threadId: ThreadId.make("thread-inbox"), + projectId: ProjectId.make("project-1"), + title: "Inbox thread", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + latestTurnId: null, + createdAt: "2026-11-14T00:00:00.000Z", + updatedAt: "2026-11-14T00:00:00.000Z", + archivedAt: null, + settledOverride: null, + settledAt: null, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + pinnedAt: null, + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + latestUserMessageAt: null, + pendingApprovalCount: 0, + pendingUserInputCount: 0, + hasActionableProposedPlan: 0, + deletedAt: null, + }); + const row = Option.getOrNull( + yield* threads.getById({ threadId: ThreadId.make("thread-inbox") }), + ); + assert.strictEqual(row?.owner, "Kameron"); + assert.strictEqual(row?.threadType, "needs-human"); + assert.strictEqual(row?.startedBy, "Lead"); + if (!row) return yield* Effect.die("Expected inbox projection row."); + + yield* threads.upsert({ + ...row, + owner: null, + threadType: "bot-work", + }); + const cleared = Option.getOrNull( + yield* threads.getById({ threadId: ThreadId.make("thread-inbox") }), + ); + assert.strictEqual(cleared?.owner, null); + assert.strictEqual(cleared?.threadType, "bot-work"); + assert.strictEqual(cleared?.startedBy, "Lead"); + }), + ); + it.effect("round-trips manual and branch pull requests through the thread row", () => Effect.gen(function* () { const threads = yield* ProjectionThreadRepository; diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 56bc8de78148c..ac2019a560aa6 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -53,6 +53,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () { snoozed_until, snoozed_at, pinned_at, + owner, + thread_type, + started_by, pin_order_key, active_order_key, title_regeneration_request_id, @@ -86,6 +89,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.snoozedUntil}, ${row.snoozedAt}, ${row.pinnedAt}, + ${row.owner ?? null}, + ${row.threadType ?? null}, + ${row.startedBy ?? null}, ${row.pinOrderKey ?? null}, ${row.activeOrderKey ?? null}, ${row.titleRegenerationRequestId ?? null}, @@ -119,6 +125,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () { snoozed_until = excluded.snoozed_until, snoozed_at = excluded.snoozed_at, pinned_at = excluded.pinned_at, + owner = excluded.owner, + thread_type = excluded.thread_type, + started_by = excluded.started_by, pin_order_key = excluded.pin_order_key, active_order_key = excluded.active_order_key, title_regeneration_request_id = excluded.title_regeneration_request_id, @@ -159,6 +168,9 @@ const makeProjectionThreadRepository = Effect.gen(function* () { snoozed_until AS "snoozedUntil", snoozed_at AS "snoozedAt", pinned_at AS "pinnedAt", + owner, + thread_type AS "threadType", + started_by AS "startedBy", pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", title_regeneration_request_id AS "titleRegenerationRequestId", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 4276b84f55536..b8b79bac9a051 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -68,6 +68,7 @@ import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts"; import Migration0054 from "./Migrations/054_ProviderSessionHistory.ts"; import Migration0055 from "./Migrations/055_ThreadRouteEvents.ts"; import Migration0056 from "./Migrations/056_ThreadExecutionScope.ts"; +import Migration0057 from "./Migrations/057_ProjectionThreadsInboxRouting.ts"; /** * Migration loader with all migrations defined inline. @@ -136,6 +137,7 @@ const migrationEntries = [ [54, "ProviderSessionHistory", Migration0054], [55, "ThreadRouteEvents", Migration0055], [56, "ThreadExecutionScope", Migration0056], + [57, "ProjectionThreadsInboxRouting", Migration0057], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/057_ProjectionThreadsInboxRouting.ts b/apps/server/src/persistence/Migrations/057_ProjectionThreadsInboxRouting.ts new file mode 100644 index 0000000000000..e3356f8d5b968 --- /dev/null +++ b/apps/server/src/persistence/Migrations/057_ProjectionThreadsInboxRouting.ts @@ -0,0 +1,29 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + const names = new Set(columns.map((column) => column.name)); + + if (!names.has("owner")) { + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN owner TEXT + `; + } + if (!names.has("thread_type")) { + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN thread_type TEXT + `; + } + if (!names.has("started_by")) { + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN started_by TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 3f2958fc7b233..ed416ea6112e9 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -18,6 +18,7 @@ import { ThreadTitleState, ThreadId, ThreadExecutionScope, + ThreadInboxType, TurnId, } from "@t3tools/contracts"; import * as Option from "effect/Option"; @@ -50,6 +51,9 @@ export const ProjectionThread = Schema.Struct({ snoozedUntil: Schema.NullOr(IsoDateTime), snoozedAt: Schema.NullOr(IsoDateTime), pinnedAt: Schema.NullOr(IsoDateTime), + owner: Schema.optional(Schema.NullOr(Schema.String)), + threadType: Schema.optional(Schema.NullOr(ThreadInboxType)), + startedBy: Schema.optional(Schema.NullOr(Schema.String)), pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)), activeOrderKey: Schema.optional(Schema.NullOr(Schema.String)), titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index be4dd6d548ac9..fd17a2350d16f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1573,6 +1573,15 @@ const makeWsRpcLayer = ( branch: bootstrap.createThread.branch, worktreePath: bootstrap.createThread.worktreePath, executionScope: bootstrap.createThread.executionScope ?? "coding", + ...(bootstrap.createThread.owner !== undefined + ? { owner: bootstrap.createThread.owner } + : {}), + ...(bootstrap.createThread.threadType !== undefined + ? { threadType: bootstrap.createThread.threadType } + : {}), + ...(bootstrap.createThread.startedBy !== undefined + ? { startedBy: bootstrap.createThread.startedBy } + : {}), createdAt: bootstrap.createThread.createdAt, }); // The successful create is a fence in the engine command queue: @@ -1753,6 +1762,15 @@ const makeWsRpcLayer = ( branch, worktreePath: targetWorktreePath, executionScope: "coding", + ...(bootstrap.createThread.owner !== undefined + ? { owner: bootstrap.createThread.owner } + : {}), + ...(bootstrap.createThread.threadType !== undefined + ? { threadType: bootstrap.createThread.threadType } + : {}), + ...(bootstrap.createThread.startedBy !== undefined + ? { startedBy: bootstrap.createThread.startedBy } + : {}), createdAt: bootstrap.createThread.createdAt, }); createdThread = true; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d906892913150..195cf267c105e 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -158,7 +158,7 @@ import { togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../pendingUserInput"; -import { useUiStateStore } from "../uiStateStore"; +import { readInboxCreateRouting, useUiStateStore } from "../uiStateStore"; import { latestWorkspaceMutationId, useWorkspaceMutationRefresh, @@ -8085,6 +8085,7 @@ export default function ChatView(props: ChatViewProps) { branch: activeThreadBranch, worktreePath: null, createdAt: messageCreatedAt, + ...readInboxCreateRouting(), }, prepareWorktree: { projectCwd: activeProject.workspaceRoot, @@ -8423,6 +8424,7 @@ export default function ChatView(props: ChatViewProps) { branch: activeThreadBranch, worktreePath: activeThread.worktreePath, createdAt: activeThread.createdAt, + ...readInboxCreateRouting(), }, } : {}), diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 95f0e062d8e03..865abb48ef236 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -26,6 +26,7 @@ import { threadSearchMatchKey, type EnvironmentThreadSearchMatch, } from "@t3tools/client-runtime/state/thread-search"; +import { inboxOwnerNames, threadVisibleInInbox } from "@t3tools/client-runtime/state/thread-inbox"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; import { parseScopedThreadKey, @@ -151,7 +152,10 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { cn } from "~/lib/utils"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; -import { buildThreadActionMenuItems } from "./threadActionMenu.logic"; +import { + buildThreadActionMenuItems, + threadRoutingUpdateFromMenuAction, +} from "./threadActionMenu.logic"; import { animateSidebarLayoutChanges, applySidebarThreadDrop, @@ -234,6 +238,7 @@ import { } from "./ui/combobox"; import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; +import { SidebarInboxBar } from "./sidebar/SidebarInboxBar"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; @@ -2529,6 +2534,11 @@ export default function Sidebar() { override holds until all of them appear in canonical state. */ readonly assignedKeys: ReadonlyMap; } | null>(null); + const threadSearchInputRef = useRef(null); + const [threadSearchQuery, setThreadSearchQuery] = useState(""); + const isSearchingThreads = threadSearchQuery.trim().length > 0; + const inboxIdentity = useUiStateStore((state) => state.inboxIdentity); + const showBotWork = useUiStateStore((state) => state.showBotWork); const { pinnedThreads, draggableThreadKeys, @@ -2548,7 +2558,11 @@ export default function Sidebar() { (thread) => thread.archivedAt === null && (scopedProjectKeys === null || - scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), + scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)) && + threadVisibleInInbox(thread, { + identity: inboxIdentity, + showBotWork: showBotWork || isSearchingThreads, + }), ); const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; @@ -2634,12 +2648,19 @@ export default function Sidebar() { settledThreads: sortSettledThreadsForSidebar(settled), snoozeNow: preciseNow, }; - }, [nowMinute, optimisticDrop, scopedProjectKeys, serverConfigs, snoozeWakeTick, threads]); + }, [ + inboxIdentity, + isSearchingThreads, + nowMinute, + optimisticDrop, + scopedProjectKeys, + serverConfigs, + showBotWork, + snoozeWakeTick, + threads, + ]); - const threadSearchInputRef = useRef(null); - const [threadSearchQuery, setThreadSearchQuery] = useState(""); const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0); - const isSearchingThreads = threadSearchQuery.trim().length > 0; const searchableThreads = useMemo( () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads], [activeThreads, pinnedThreads, settledThreads, snoozedThreads], @@ -4076,11 +4097,36 @@ export default function Sidebar() { titleRegeneration: supportsTitleRegeneration, }, snoozePresets, + routing: { + owners: inboxOwnerNames(useUiStateStore.getState().inboxOwners), + owner: thread.owner ?? null, + threadType: thread.threadType ?? null, + }, }), position, ), ); if (clicked._tag === "Failure") return; + const routingUpdate = clicked.value + ? threadRoutingUpdateFromMenuAction(clicked.value) + : null; + if (routingUpdate) { + const result = await updateThreadMetadata({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, ...routingUpdate }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to update thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return; + } if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" @@ -4551,6 +4597,7 @@ export default function Sidebar() { activeSearchResultIndex={activeSearchResultIndex} onClearSearch={clearThreadSearch} /> + } > diff --git a/apps/web/src/components/sidebar/SidebarInboxBar.tsx b/apps/web/src/components/sidebar/SidebarInboxBar.tsx new file mode 100644 index 0000000000000..bf4bfd76a8861 --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarInboxBar.tsx @@ -0,0 +1,117 @@ +import type { ThreadInboxType } from "@t3tools/contracts"; +import { + inboxOwnerNames, + THREAD_INBOX_TYPE_LABELS, +} from "@t3tools/client-runtime/state/thread-inbox"; +import { useState } from "react"; + +import { Button } from "../ui/button"; +import { useUiStateStore } from "../../uiStateStore"; + +const TYPE_OPTIONS: ReadonlyArray = ["needs-human", "fyi", "bot-work"]; + +/** + * Founder inbox for the shared thread pool. The selection is local to this + * browser; the tags themselves live on the thread. + */ +export function SidebarInboxBar() { + const inboxIdentity = useUiStateStore((state) => state.inboxIdentity); + const showBotWork = useUiStateStore((state) => state.showBotWork); + const inboxOwners = useUiStateStore((state) => state.inboxOwners); + const createOwner = useUiStateStore((state) => state.createOwner); + const createThreadType = useUiStateStore((state) => state.createThreadType); + const setInboxIdentity = useUiStateStore((state) => state.setInboxIdentity); + const setShowBotWork = useUiStateStore((state) => state.setShowBotWork); + const setInboxOwners = useUiStateStore((state) => state.setInboxOwners); + const setCreateOwner = useUiStateStore((state) => state.setCreateOwner); + const setCreateThreadType = useUiStateStore((state) => state.setCreateThreadType); + const [draftOwner, setDraftOwner] = useState(""); + const owners = inboxOwnerNames(inboxOwners); + + return ( +
+ + + +
{ + event.preventDefault(); + const name = draftOwner.trim(); + if (name.length === 0 || owners.includes(name)) { + setDraftOwner(""); + return; + } + setInboxOwners([...inboxOwners, name]); + setDraftOwner(""); + }} + > + setDraftOwner(event.target.value)} + /> +
+
+ ); +} diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index 14965d4add586..61b5c9d024799 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -15,6 +15,7 @@ const baseState: ThreadActionMenuState = { snoozePresets: [ { id: "hour", label: "In 1 hour", whenLabel: "3:00 PM", snoozedUntil: "2026-08-07T15:00:00Z" }, ], + routing: { owners: ["Kameron", "Jeff"], owner: null, threadType: null }, }; function ids(state: ThreadActionMenuState): string[] { @@ -34,7 +35,16 @@ describe("buildThreadActionMenuItems", () => { ...baseState, supports: { settlement: false, snooze: false, pinning: false, titleRegeneration: false }, }), - ).toEqual(["rename", "mark-unread", "copy", "project-settings", "archive", "delete"]); + ).toEqual([ + "routing-owner", + "routing-type", + "rename", + "mark-unread", + "copy", + "project-settings", + "archive", + "delete", + ]); }); it("groups project settings with utility actions before archive", () => { diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index c37ec31f929cd..acb286d60a479 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -1,6 +1,13 @@ -import type { ContextMenuItem } from "@t3tools/contracts"; +import type { ContextMenuItem, ThreadInboxType } from "@t3tools/contracts"; +import { THREAD_INBOX_TYPE_LABELS } from "@t3tools/client-runtime/state/thread-inbox"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +const THREAD_INBOX_TYPES = [ + "needs-human", + "fyi", + "bot-work", +] as const satisfies readonly ThreadInboxType[]; + /** * Ids for the per-thread action menu. Snooze presets are dispatched as * `snooze:` so the union stays closed while the preset list @@ -17,6 +24,10 @@ export type ThreadActionMenuId = | "snooze" | `snooze:${string}` | "unsnooze" + | "routing-owner" + | `owner:${string}` + | "routing-type" + | `type:${string}` | "rename" | "regenerate-title" | "mark-unread" @@ -52,6 +63,32 @@ export interface ThreadActionMenuState { readonly titleRegeneration: boolean; }; readonly snoozePresets: ReadonlyArray; + readonly routing: { + readonly owners: readonly string[]; + readonly owner: string | null; + readonly threadType: ThreadInboxType | null; + }; +} + +const ROUTING_CLEAR = "__clear__"; + +/** Menu id for an owner or type change, or null when the id is something else. */ +export function threadRoutingUpdateFromMenuAction(action: string): { + readonly owner?: string | null; + readonly threadType?: ThreadInboxType | null; +} | null { + if (action.startsWith("owner:")) { + const value = action.slice("owner:".length); + return { owner: value === ROUTING_CLEAR ? null : value }; + } + if (action.startsWith("type:")) { + const value = action.slice("type:".length); + if (value === ROUTING_CLEAR) return { threadType: null }; + if ((THREAD_INBOX_TYPES as readonly string[]).includes(value)) { + return { threadType: value as ThreadInboxType }; + } + } + return null; } /** @@ -108,6 +145,33 @@ export function buildThreadActionMenuItems( }, ] : []), + { + id: "routing-owner", + label: state.routing.owner ? `Owner: ${state.routing.owner}` : "Set owner", + icon: "user", + separatorBefore: true, + children: [ + { id: "owner:__clear__", label: "Unassigned" }, + ...state.routing.owners.map((owner) => ({ + id: `owner:${owner}` as const, + label: owner, + })), + ], + }, + { + id: "routing-type", + label: state.routing.threadType + ? `Type: ${THREAD_INBOX_TYPE_LABELS[state.routing.threadType]}` + : "Set type", + icon: "tag", + children: [ + { id: "type:__clear__", label: "Untyped" }, + ...THREAD_INBOX_TYPES.map((type) => ({ + id: `type:${type}` as const, + label: THREAD_INBOX_TYPE_LABELS[type], + })), + ], + }, { id: "rename", label: "Rename thread", icon: "pencil", separatorBefore: true }, ...(state.supports.titleRegeneration ? [ diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 2c43641b2b567..f7966234509c3 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -45,6 +45,19 @@ const ICON_PATHS: Record api.contextMenu.show(items, position)); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -186,6 +193,16 @@ export function useThreadActionMenu(input: { failureToast(title, squashAtomCommandFailure(result)); } }; + const routingUpdate = threadRoutingUpdateFromMenuAction(action); + if (routingUpdate) { + await reportFailure("Failed to update thread", () => + updateThreadMetadata({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId, ...routingUpdate }, + }), + ); + return; + } switch (action) { case "project-settings": { const project = projects.find( diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 4d68a3231b316..c7097b481f726 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -27,6 +27,11 @@ function makeUiState(overrides: Partial = {}): UiState { threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, pullRequestMergeMethod: "merge", + inboxIdentity: null, + showBotWork: false, + inboxOwners: [], + createOwner: null, + createThreadType: null, ...overrides, }; } @@ -203,6 +208,11 @@ describe("parsePersistedState", () => { defaultAdvertisedEndpointKey: "desktop-core:lan:http", sidebarProjectScopeKey: null, pullRequestMergeMethod: "merge", + inboxIdentity: null, + showBotWork: false, + inboxOwners: [], + createOwner: null, + createThreadType: null, threadChangedFilesExpandedById: { "environment:thread-1": { "turn-1": false, @@ -332,6 +342,11 @@ describe("uiStateStore persistence", () => { }, }, pullRequestMergeMethod: "merge", + inboxIdentity: null, + showBotWork: false, + inboxOwners: [], + createOwner: null, + createThreadType: null, }); expect(parsePersistedState(persisted)).toEqual({ ...state, diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index e82c86f26404d..d43d3d3691ee0 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -1,8 +1,10 @@ import { Debouncer } from "@tanstack/react-pacer"; -import type { PullRequestMergeMethod } from "@t3tools/contracts"; +import type { PullRequestMergeMethod, ThreadInboxType } from "@t3tools/contracts"; import { create } from "zustand"; import { normalizeProjectPathForComparison } from "./lib/projectPaths"; +const THREAD_INBOX_TYPES = ["needs-human", "fyi", "bot-work"] as const; + export const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; // Version 1 stored card visibility, not folder expansion. const THREAD_CHANGED_FILES_EXPANSION_VERSION = 2; @@ -31,6 +33,11 @@ export interface PersistedUiState { threadChangedFilesExpansionVersion?: number; threadChangedFilesExpandedById?: Record>; pullRequestMergeMethod?: string; + inboxIdentity?: string | null; + showBotWork?: boolean; + inboxOwners?: string[]; + createOwner?: string | null; + createThreadType?: string | null; } export interface UiProjectState { @@ -55,8 +62,21 @@ export interface UiPullRequestState { pullRequestMergeMethod: PullRequestMergeMethod; } +export interface UiInboxState { + /** Founder whose filtered inbox is showing. Null is every untagged and tagged thread. */ + inboxIdentity: string | null; + /** Reveals bot-to-bot threads. Search does this on its own. */ + showBotWork: boolean; + /** Extra owner names beyond the built-in founders. */ + inboxOwners: string[]; + /** Owner stamped on threads this browser starts. */ + createOwner: string | null; + /** Type stamped on threads this browser starts. */ + createThreadType: ThreadInboxType | null; +} + export interface UiState - extends UiProjectState, UiThreadState, UiEndpointState, UiPullRequestState {} + extends UiProjectState, UiThreadState, UiEndpointState, UiPullRequestState, UiInboxState {} const initialState: UiState = { projectExpandedById: {}, @@ -66,6 +86,11 @@ const initialState: UiState = { threadChangedFilesExpandedById: {}, defaultAdvertisedEndpointKey: null, pullRequestMergeMethod: "merge", + inboxIdentity: null, + showBotWork: false, + inboxOwners: [], + createOwner: null, + createThreadType: null, }; const LEGACY_PROJECT_CWD_PREFERENCE_PREFIX = "legacy-project-cwd:"; @@ -121,6 +146,16 @@ function isPullRequestMergeMethod(value: unknown): value is PullRequestMergeMeth return value === "merge" || value === "squash" || value === "rebase"; } +function isThreadInboxType(value: unknown): value is ThreadInboxType { + return typeof value === "string" && (THREAD_INBOX_TYPES as readonly string[]).includes(value); +} + +function sanitizeOwner(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= 80 ? trimmed : null; +} + export function parsePersistedState(parsed: PersistedUiState): UiState { const projectExpandedById = parsed.projectExpandedById === undefined @@ -158,6 +193,11 @@ export function parsePersistedState(parsed: PersistedUiState): UiState { pullRequestMergeMethod: isPullRequestMergeMethod(parsed.pullRequestMergeMethod) ? parsed.pullRequestMergeMethod : initialState.pullRequestMergeMethod, + inboxIdentity: sanitizeOwner(parsed.inboxIdentity), + showBotWork: parsed.showBotWork === true, + inboxOwners: sanitizeStringArray(parsed.inboxOwners), + createOwner: sanitizeOwner(parsed.createOwner), + createThreadType: isThreadInboxType(parsed.createThreadType) ? parsed.createThreadType : null, }; } @@ -232,6 +272,11 @@ export function persistState(state: UiState): void { threadChangedFilesExpansionVersion: THREAD_CHANGED_FILES_EXPANSION_VERSION, threadChangedFilesExpandedById: state.threadChangedFilesExpandedById, pullRequestMergeMethod: state.pullRequestMergeMethod, + inboxIdentity: state.inboxIdentity, + showBotWork: state.showBotWork, + inboxOwners: state.inboxOwners, + createOwner: state.createOwner, + createThreadType: state.createThreadType, } satisfies PersistedUiState), ); if (!legacyKeysCleanedUp) { @@ -340,6 +385,32 @@ export function setSidebarProjectScopeKey(state: UiState, projectKey: string | n }; } +function setInboxIdentity(state: UiState, identity: string | null): UiState { + const next = sanitizeOwner(identity); + return state.inboxIdentity === next ? state : { ...state, inboxIdentity: next }; +} + +function setShowBotWork(state: UiState, showBotWork: boolean): UiState { + return state.showBotWork === showBotWork ? state : { ...state, showBotWork }; +} + +function setInboxOwners(state: UiState, owners: readonly string[]): UiState { + const inboxOwners = sanitizeStringArray(owners); + return state.inboxOwners.join("\0") === inboxOwners.join("\0") + ? state + : { ...state, inboxOwners }; +} + +function setCreateOwner(state: UiState, owner: string | null): UiState { + const next = sanitizeOwner(owner); + return state.createOwner === next ? state : { ...state, createOwner: next }; +} + +function setCreateThreadType(state: UiState, threadType: ThreadInboxType | null): UiState { + const next = threadType && isThreadInboxType(threadType) ? threadType : null; + return state.createThreadType === next ? state : { ...state, createThreadType: next }; +} + function setPullRequestMergeMethod(state: UiState, method: PullRequestMergeMethod): UiState { return state.pullRequestMergeMethod === method ? state @@ -430,6 +501,11 @@ interface UiStateStore extends UiState { setDefaultAdvertisedEndpointKey: (key: string | null) => void; setSidebarProjectScopeKey: (projectKey: string | null) => void; setPullRequestMergeMethod: (method: PullRequestMergeMethod) => void; + setInboxIdentity: (identity: string | null) => void; + setShowBotWork: (showBotWork: boolean) => void; + setInboxOwners: (owners: readonly string[]) => void; + setCreateOwner: (owner: string | null) => void; + setCreateThreadType: (threadType: ThreadInboxType | null) => void; setProjectExpanded: (projectIds: string | readonly string[], expanded: boolean) => void; reorderProjects: ( currentProjectOrder: readonly string[], @@ -451,6 +527,11 @@ export const useUiStateStore = create((set) => ({ setSidebarProjectScopeKey: (projectKey) => set((state) => setSidebarProjectScopeKey(state, projectKey)), setPullRequestMergeMethod: (method) => set((state) => setPullRequestMergeMethod(state, method)), + setInboxIdentity: (identity) => set((state) => setInboxIdentity(state, identity)), + setShowBotWork: (showBotWork) => set((state) => setShowBotWork(state, showBotWork)), + setInboxOwners: (owners) => set((state) => setInboxOwners(state, owners)), + setCreateOwner: (owner) => set((state) => setCreateOwner(state, owner)), + setCreateThreadType: (threadType) => set((state) => setCreateThreadType(state, threadType)), setProjectExpanded: (projectIds, expanded) => set((state) => setProjectExpanded(state, projectIds, expanded)), reorderProjects: (currentProjectOrder, draggedProjectIds, targetProjectIds) => @@ -461,6 +542,18 @@ export const useUiStateStore = create((set) => ({ useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); +export function readInboxCreateRouting(state: UiState = useUiStateStore.getState()): { + readonly owner?: string; + readonly threadType?: ThreadInboxType; + readonly startedBy?: string; +} { + return { + ...(state.inboxIdentity ? { startedBy: state.inboxIdentity } : {}), + ...(state.createOwner ? { owner: state.createOwner } : {}), + ...(state.createThreadType ? { threadType: state.createThreadType } : {}), + }; +} + if (typeof window !== "undefined" && typeof window.addEventListener === "function") { window.addEventListener("beforeunload", () => { debouncedPersistState.flush(); diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index ed024846605f5..381220f02fad8 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -235,6 +235,10 @@ "types": "./src/state/threadSettled.ts", "default": "./src/state/threadSettled.ts" }, + "./state/thread-inbox": { + "types": "./src/state/threadInbox.ts", + "default": "./src/state/threadInbox.ts" + }, "./state/thread-search": { "types": "./src/state/threadSearch.ts", "default": "./src/state/threadSearch.ts" diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index 379985b712431..72b0acdbcc9b7 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -64,6 +64,9 @@ export function mergeEnvironmentThread( snoozedAt: shell.snoozedAt, pinnedAt: shell.pinnedAt, pinOrderKey: shell.pinOrderKey, + owner: shell.owner ?? null, + threadType: shell.threadType ?? null, + startedBy: shell.startedBy ?? null, session: shell.session, }; } diff --git a/packages/client-runtime/src/state/threadInbox.test.ts b/packages/client-runtime/src/state/threadInbox.test.ts new file mode 100644 index 0000000000000..ebebfe325fe4a --- /dev/null +++ b/packages/client-runtime/src/state/threadInbox.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { inboxOwnerNames, threadVisibleInInbox, type ThreadInboxSubject } from "./threadInbox.ts"; + +const thread = (patch: Partial = {}): ThreadInboxSubject => ({ + owner: null, + threadType: null, + startedBy: null, + ...patch, +}); + +describe("threadVisibleInInbox", () => { + it("keeps untagged threads on the shared list", () => { + expect(threadVisibleInInbox(thread(), { identity: null, showBotWork: false })).toBe(true); + expect(threadVisibleInInbox({}, { identity: null, showBotWork: false })).toBe(true); + }); + + it("hides bot work until someone asks to see it", () => { + const bot = thread({ owner: "Lead", threadType: "bot-work", startedBy: "Lead" }); + expect(threadVisibleInInbox(bot, { identity: null, showBotWork: false })).toBe(false); + expect(threadVisibleInInbox(bot, { identity: "Lead", showBotWork: false })).toBe(false); + expect(threadVisibleInInbox(bot, { identity: "Lead", showBotWork: true })).toBe(true); + }); + + it("shows a founder threads they own, that need them, or that they started", () => { + const options = { identity: "Kameron", showBotWork: false }; + expect(threadVisibleInInbox(thread({ owner: "Kameron", threadType: "fyi" }), options)).toBe( + true, + ); + expect( + threadVisibleInInbox(thread({ owner: "Kameron", threadType: "needs-human" }), options), + ).toBe(true); + expect( + threadVisibleInInbox( + thread({ owner: "Jeff", threadType: "fyi", startedBy: "Kameron" }), + options, + ), + ).toBe(true); + expect( + threadVisibleInInbox(thread({ owner: "Jeff", threadType: "needs-human" }), options), + ).toBe(false); + expect(threadVisibleInInbox(thread(), options)).toBe(false); + }); +}); + +describe("inboxOwnerNames", () => { + it("keeps the known founders and appends configured names once", () => { + expect(inboxOwnerNames(["Ops", "Kameron", " Ops "])).toEqual([ + "Kameron", + "Jeff", + "Lead", + "Jeff's Lead", + "Ops", + ]); + }); +}); diff --git a/packages/client-runtime/src/state/threadInbox.ts b/packages/client-runtime/src/state/threadInbox.ts new file mode 100644 index 0000000000000..586021692d396 --- /dev/null +++ b/packages/client-runtime/src/state/threadInbox.ts @@ -0,0 +1,56 @@ +import { DEFAULT_THREAD_OWNERS, type ThreadInboxType } from "@t3tools/contracts"; + +/** + * Fields a shared inbox uses to decide who should see a thread. + * Missing values are untagged history and stay on the all-threads list. + */ +export interface ThreadInboxSubject { + readonly owner?: string | null | undefined; + readonly threadType?: ThreadInboxType | null | undefined; + readonly startedBy?: string | null | undefined; +} + +export interface ThreadInboxVisibility { + /** Selected founder. Null is the shared list. */ + readonly identity: string | null; + /** Bot-to-bot threads stay out until this is set, including while searching. */ + readonly showBotWork: boolean; +} + +/** + * Founder inbox: owner is me, a needs-human thread addressed to me, or a + * thread I started. Untagged threads stay on the all-threads list. Bot work + * stays hidden until `showBotWork` is set. + */ +export function threadVisibleInInbox( + thread: ThreadInboxSubject, + options: ThreadInboxVisibility, +): boolean { + if (thread.threadType === "bot-work" && !options.showBotWork) { + return false; + } + const identity = options.identity?.trim() ?? ""; + if (identity.length === 0) { + return true; + } + const addressedToMe = thread.threadType === "needs-human" && thread.owner === identity; + return thread.owner === identity || addressedToMe || thread.startedBy === identity; +} + +export function inboxOwnerNames(extraOwners: readonly string[]): readonly string[] { + const names: string[] = []; + const seen = new Set(); + for (const name of [...DEFAULT_THREAD_OWNERS, ...extraOwners]) { + const trimmed = name.trim(); + if (trimmed.length === 0 || seen.has(trimmed)) continue; + seen.add(trimmed); + names.push(trimmed); + } + return names; +} + +export const THREAD_INBOX_TYPE_LABELS: Record = { + "needs-human": "Needs a human", + fyi: "FYI", + "bot-work": "Bot work", +}; diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts index dbee48d7808cb..155748b8d0b79 100644 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ b/packages/client-runtime/src/state/threadReducer.test.ts @@ -318,6 +318,51 @@ describe("applyThreadDetailEvent", () => { }, ); + it("sets and clears inbox routing", () => { + const tagged = applyThreadDetailEvent(baseThread, { + ...baseEventFields, + sequence: 5, + occurredAt: "2026-04-01T05:00:00.000Z", + aggregateKind: "thread", + aggregateId: baseThread.id, + type: "thread.meta-updated", + payload: { + threadId: baseThread.id, + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + updatedAt: "2026-04-01T05:00:00.000Z", + }, + }); + expect(tagged.kind).toBe("updated"); + if (tagged.kind !== "updated") return; + expect(tagged.thread).toMatchObject({ + owner: "Kameron", + threadType: "needs-human", + startedBy: "Lead", + }); + + const cleared = applyThreadDetailEvent(tagged.thread, { + ...baseEventFields, + sequence: 6, + occurredAt: "2026-04-01T06:00:00.000Z", + aggregateKind: "thread", + aggregateId: baseThread.id, + type: "thread.meta-updated", + payload: { + threadId: baseThread.id, + owner: null, + threadType: null, + updatedAt: "2026-04-01T06:00:00.000Z", + }, + }); + expect(cleared.kind).toBe("updated"); + if (cleared.kind !== "updated") return; + expect(cleared.thread.owner).toBeNull(); + expect(cleared.thread.threadType).toBeNull(); + expect(cleared.thread.startedBy).toBe("Lead"); + }); + it("patches title and branch", () => { const result = applyThreadDetailEvent( { ...baseThread, activeOrderKey: "m" }, diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index 101bb34fba912..9c96f6ce701b6 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -122,6 +122,11 @@ export function applyThreadDetailEvent( interactionMode: event.payload.interactionMode, branch: event.payload.branch, worktreePath: event.payload.worktreePath, + ...(event.payload.owner !== undefined ? { owner: event.payload.owner } : {}), + ...(event.payload.threadType !== undefined + ? { threadType: event.payload.threadType } + : {}), + ...(event.payload.startedBy !== undefined ? { startedBy: event.payload.startedBy } : {}), branchPullRequest: null, latestTurn: null, createdAt: event.payload.createdAt, @@ -278,6 +283,11 @@ export function applyThreadDetailEvent( ...(event.payload.activeOrderKey !== undefined ? { activeOrderKey: event.payload.activeOrderKey } : {}), + ...(event.payload.owner !== undefined ? { owner: event.payload.owner } : {}), + ...(event.payload.threadType !== undefined + ? { threadType: event.payload.threadType } + : {}), + ...(event.payload.startedBy !== undefined ? { startedBy: event.payload.startedBy } : {}), updatedAt: event.payload.updatedAt, }, }; diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index 9f9f049d29fe8..6d72fea0e0013 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -87,6 +87,7 @@ const T3_MCP_TOOL_LABELS: Record< update_scheduled_task: ["Update", "Updating", "Updated", "a scheduled task"], delete_scheduled_task: ["Delete", "Deleting", "Deleted", "a scheduled task"], create_threads: ["Create", "Creating", "Created", "T3 threads"], + set_thread_routing: ["Tag", "Tagging", "Tagged", "a T3 thread"], t3_thread_start: ["Start", "Starting", "Started", "a T3 thread"], t3_thread_list: ["List", "Listing", "Listed", "T3 threads"], t3_thread_read: ["Read", "Reading", "Read", "a T3 thread"], diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 7c7bade4502e2..2b1e4c3c4a48d 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -699,6 +699,10 @@ it.effect("defaults settled fields when decoding historical thread data", () => assert.strictEqual(thread.settledAt, null); assert.strictEqual(shell.settledOverride, null); assert.strictEqual(shell.settledAt, null); + assert.strictEqual(thread.owner, undefined); + assert.strictEqual(thread.threadType, undefined); + assert.strictEqual(thread.startedBy, undefined); + assert.strictEqual(shell.owner, undefined); // Pre-link servers omit the array entirely. assert.deepStrictEqual(thread.pullRequests, []); assert.deepStrictEqual(shell.pullRequests, []); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 9a82c5599f0ee..b5abea589f1d4 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -841,6 +841,27 @@ export type ThreadPullRequestLink = typeof ThreadPullRequestLink.Type; export const ThreadExecutionScope = Schema.Literals(["coding", "coordinator"]); export type ThreadExecutionScope = typeof ThreadExecutionScope.Type; +/** + * How a thread should show up in a shared inbox. + * `needs-human` is work a person should act on, `fyi` is visible context, + * and `bot-work` is bot-to-bot traffic hidden until someone asks for it. + * Absent means the thread predates tagging and keeps today's placement. + */ +export const ThreadInboxType = Schema.Literals(["needs-human", "fyi", "bot-work"]); +export type ThreadInboxType = typeof ThreadInboxType.Type; + +/** Suggested owner names. The field itself stays a free-form string. */ +export const DEFAULT_THREAD_OWNERS = ["Kameron", "Jeff", "Lead", "Jeff's Lead"] as const; + +const threadRoutingFields = { + /** Who the thread is for. Null clears a previous owner. */ + owner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + /** Inbox class. Null clears a previous type. */ + threadType: Schema.optional(Schema.NullOr(ThreadInboxType)), + /** Who opened the thread. Null clears a previous starter. */ + startedBy: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), +}; + export const OrchestrationThread = Schema.Struct({ id: ThreadId, projectId: ProjectId, @@ -890,6 +911,9 @@ export const OrchestrationThread = Schema.Struct({ // Manual Active placement. Keyless threads retain their creation/re-entry // order above the arranged run. Settling clears this slot. activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + // Shared-inbox routing. Optional so threads and servers from before + // tagging still decode; absent means untagged and listed as today. + ...threadRoutingFields, // Pending-only state. Optional so older servers remain compatible. titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)), titleState: Schema.optional(Schema.NullOr(ThreadTitleState)), @@ -961,6 +985,8 @@ export const OrchestrationThreadShell = Schema.Struct({ pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)), pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + // See OrchestrationThread routing fields. + ...threadRoutingFields, titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)), titleState: Schema.optional(Schema.NullOr(ThreadTitleState)), session: Schema.NullOr(OrchestrationSession), @@ -1181,6 +1207,7 @@ const ThreadCreateCommand = Schema.Struct({ branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), executionScope: Schema.optional(Schema.NullOr(ThreadExecutionScope)), + ...threadRoutingFields, createdAt: IsoDateTime, historyImport: Schema.optional(Schema.Literal(true)), }); @@ -1293,6 +1320,7 @@ const ThreadMetaUpdateCommand = Schema.Struct({ expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + ...threadRoutingFields, }).check( Schema.makeFilter( (input) => @@ -1342,6 +1370,7 @@ const ThreadTurnStartBootstrapCreateThread = Schema.Struct({ branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), executionScope: Schema.optional(Schema.NullOr(ThreadExecutionScope)), + ...threadRoutingFields, createdAt: IsoDateTime, }); @@ -1825,6 +1854,7 @@ export const ThreadCreatedPayload = Schema.Struct({ branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), executionScope: Schema.optional(Schema.NullOr(ThreadExecutionScope)), + ...threadRoutingFields, createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -1915,6 +1945,7 @@ export const ThreadMetaUpdatedPayload = Schema.Struct({ // thread.pull-request-linked still decode and replay into the link table. linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), branchPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + ...threadRoutingFields, updatedAt: IsoDateTime, });