diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2c79189878e8a..599066dd7e8af 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -290,6 +290,7 @@ export const make = Effect.gen(function* () { ...(desktopAppUpdate ? { desktopAppUpdate: true, desktopAppChannelSwitch: true } : {}), serverBrowser: true, peerLinks: true, + threadInbox: true, mcpModeLimitHeader: true, linkFence: true, mcpApprovalCodes: true, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index e3cbb4aca9417..ef2cc7f934216 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -877,6 +877,7 @@ function listItemFromShell( nowMs: number, ): OrchestratorMcpThreadListItem { return { + ...(shell.inbox === undefined ? {} : { inbox: shell.inbox }), threadId: shell.id, projectId: shell.projectId, title: shell.title, @@ -913,6 +914,7 @@ function threadDetail( const latest = ThreadManagementService.latestRun(projection); const active = ThreadManagementService.latestActiveRun(projection); return { + ...(projection.thread.inbox === undefined ? {} : { inbox: projection.thread.inbox }), threadId: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, @@ -2985,6 +2987,12 @@ const make = Effect.gen(function* () { yield* threadManagement .dispatch({ type: "thread.create", + inboxOrigin: { kind: "agent", id: parent.thread.id }, + ...(request.inboxRouting !== undefined + ? { inboxRouting: request.inboxRouting } + : parent.thread.inbox === undefined + ? {} + : { inboxRouting: parent.thread.inbox }), createdBy: "agent", creationSource: "mcp", commandId, diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 44f0a610e585a..3fa5ea0102f9e 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -65,6 +65,13 @@ function metadataCommand(input: { readonly update: ThreadMetadataMcpUpdateInput; }): Extract { switch (input.update.action) { + case "route": + return { + type: "thread.metadata.update", + commandId: input.commandId, + threadId: input.threadId, + inboxRouting: input.update.inboxRouting!, + }; case "rename": return { type: "thread.metadata.update", @@ -88,10 +95,11 @@ function resultFromThread(input: { readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" + "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" >; }): ThreadMetadataMcpUpdateResult { return { + ...(input.thread.inbox === undefined ? {} : { inbox: input.thread.inbox }), threadId: input.thread.id, action: input.action, commandId: input.commandId, diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index d85786c9f5c17..9243c6f16c2f4 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -260,7 +260,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.", + "Route a thread with action:'route' and inboxRouting (owner, assignee, audience, attentionKind), or rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.", // Keeps the input's action/field check, which rebuilding the struct would drop. parameters: ThreadMetadataMcpUpdateInput.mapFields( Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 2ad7161cb630b..0693d2e88c4fe 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -255,6 +255,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }); } const result = yield* ThreadMessageIntake.launchThread({ + inboxOrigin: { kind: "agent", id: caller?.id ?? "agent" }, + ...(input.inboxRouting !== undefined + ? { inboxRouting: input.inboxRouting } + : caller?.inbox === undefined + ? {} + : { inboxRouting: caller.inbox }), commandId, threadId, projectId, diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 56799959f6cd8..93aece44cba76 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -1,5 +1,6 @@ import { McpAttachmentInput } from "../attachment/input.ts"; import { + ThreadInboxRoutingPatch, NonNegativeInt, ModelSelection, TrimmedNonEmptyString, @@ -134,6 +135,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { "No project: a new Scratch folder. Not with `projectId` or `workspaceStrategy`.", }), ), + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), title: TrimmedNonEmptyString, modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00f9dfae8d9e1..18067d57a63fa 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5,6 +5,8 @@ import type { OrchestrationV2SearchThreadResult, OrchestrationV2ThreadHistoryPage, } from "@t3tools/contracts"; +import { makeThreadInbox, routeThreadInbox } from "@t3tools/contracts"; +import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -3644,6 +3646,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const emitEvent = emit(events, command); const thread: OrchestrationV2AppThread = { + ...(command.inboxOrigin === undefined && + command.inboxRouting === undefined && + command.createdBy !== "agent" + ? {} + : { + inbox: makeThreadInbox({ + actor: + command.inboxOrigin ?? + (command.createdBy === "agent" ? { kind: "agent", id: "agent" } : null), + ...(command.inboxRouting === undefined ? {} : { routing: command.inboxRouting }), + executorEnvironmentId: yield* Effect.serviceOption(ServerEnvironmentIdentity).pipe( + Effect.flatMap((identity) => + Option.isSome(identity) ? identity.value.getEnvironmentId : Effect.succeed(null), + ), + ), + }), + }), createdBy: command.createdBy, creationSource: command.creationSource, id: command.threadId, @@ -4672,6 +4691,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }; return { ...thread, + ...(command.inboxRouting === undefined + ? {} + : { + inbox: routeThreadInbox( + thread.inbox ?? makeThreadInbox({ actor: null }), + command.inboxRouting, + ), + }), ...(command.title === undefined ? {} : { title: command.title }), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e90a82786953f..7e68b50098bf8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1727,6 +1727,7 @@ export function threadShellFromProjection( }); return { createdBy: projection.thread.createdBy, + ...(projection.thread.inbox === undefined ? {} : { inbox: projection.thread.inbox }), creationSource: projection.thread.creationSource, id: projection.thread.id, projectId: projection.thread.projectId, @@ -2066,6 +2067,7 @@ function shellFromState(input: { ...(input.state.thread.historyOrigin === undefined ? {} : { historyOrigin: input.state.thread.historyOrigin }), + ...(input.state.thread.inbox === undefined ? {} : { inbox: input.state.thread.inbox }), ...(input.state.thread.linkOrigin === undefined ? {} : { linkOrigin: input.state.thread.linkOrigin }), diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index 29deb33a3ae6e..bd5b033c1b343 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -1,5 +1,7 @@ import { assert, it } from "@effect/vitest"; import { + makeThreadInbox, + matchesInboxView, CommandId, type ModelSelection, NodeId, @@ -85,6 +87,7 @@ function makeParentThread(): OrchestrationV2AppThread { it("keeps a subagent child awake when its parent thread is snoozed", () => { const parentThread: OrchestrationV2AppThread = { ...makeParentThread(), + inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), titleRegeneration: { requestId: CommandId.make("command:parent-title"), startedAt: snoozedAt }, }; const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child"); @@ -102,6 +105,12 @@ it("keeps a subagent child awake when its parent thread is snoozed", () => { creationSource: "provider", }); + assert.equal(childThread.inbox?.owner, "jeff"); + assert.deepEqual(childThread.inbox?.requestedBy, parentThread.inbox?.requestedBy); + assert.isFalse(matchesInboxView(childThread.inbox, "jeff")); + assert.isFalse(matchesInboxView(childThread.inbox, "kameron")); + assert.isTrue(matchesInboxView(childThread.inbox, "agents")); + assert.isTrue(matchesInboxView(childThread.inbox, "all")); assert.isNull(childThread.snoozedUntil); assert.isNull(childThread.snoozedAt); assert.isNull(childThread.titleRegeneration); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index c44c3a70f19b9..0fc06fe0eff06 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -2903,3 +2903,35 @@ it.effect("replays an accepted send after the project disables the instance", () } }).pipe(Effect.provide(Layer.mergeAll(harness.layer, layerFiles))); }); + +it.effect( + "persists founder routing in projections and shells and retains it on launch replay", + () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = { + ...launchInput({ command: "inbox-launch", thread: "inbox-thread" }), + inboxOrigin: { kind: "human" as const, id: "jeff" as const }, + }; + const launched = yield* launches.launch(input); + const original = (yield* threads.getThreadProjection(launched.threadId)).thread.inbox; + assert.equal(original?.owner, "jeff"); + assert.deepEqual((yield* threads.getThreadShell(launched.threadId))?.inbox, original); + yield* threads.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("route-inbox"), + threadId: launched.threadId, + inboxRouting: { assignee: { kind: "human", id: "kameron" }, attentionKind: "FYI" }, + }); + yield* launches.launch(input); + const routed = (yield* threads.getThreadProjection(launched.threadId)).thread.inbox; + assert.equal(routed?.owner, "kameron"); + assert.equal(routed?.attentionKind, "FYI"); + assert.deepEqual(routed?.origin, original?.origin); + assert.deepEqual(routed?.requestedBy, original?.requestedBy); + assert.deepEqual((yield* threads.getThreadShell(launched.threadId))?.inbox, routed); + }).pipe(Effect.provide(harness.layer)); + }, +); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index b354ba6737e30..fa67e49bb450e 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -4,6 +4,8 @@ import * as TerminalManager from "../terminal/Manager.ts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, + type InboxActor, + type ThreadInboxRoutingPatch, type ChatAttachment, type MessageId, type ModelSelection, @@ -83,6 +85,8 @@ export interface ThreadLaunchInitialMessage { export interface ThreadLaunchInput { readonly commandId: CommandId; + readonly inboxOrigin?: InboxActor; + readonly inboxRouting?: ThreadInboxRoutingPatch; readonly threadId?: ThreadId; readonly reuseExistingThread?: boolean; readonly projectId: ProjectId; @@ -1142,6 +1146,8 @@ const make = Effect.gen(function* () { : { delegatedFrom: input.delegatedFrom }), createdBy: input.createdBy, creationSource: input.creationSource, + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), }); const claimed = yield* claimDispatch.pipe( Effect.mapError( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1f2a148734d4e..32bf641af2d21 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2150,6 +2150,12 @@ export const layerWsRpc = ( Effect.andThen( ThreadMessageIntake.launchThread({ commandId: input.commandId, + ...(input.inboxOrigin === undefined + ? {} + : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined + ? {} + : { inboxRouting: input.inboxRouting }), ...(input.threadId === undefined ? {} : { threadId: input.threadId }), ...(input.reuseExistingThread === undefined ? {} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index a94b9e9497c6b..5af60d06d2ace 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,3 +1,6 @@ +import { matchesInboxView } from "@t3tools/contracts"; +import { SidebarInboxBar } from "./sidebar/SidebarInboxBar"; +import { threadRoutingUpdateFromMenuAction } from "./threadActionMenu.logic"; import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -1118,10 +1121,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const threads = useQuietThreadShells(); const promotingDraftThreadKeys = usePromotingDraftThreadKeys(); + const inboxView = useClientSettings((settings) => settings.founderInboxView); + const inboxThreads = threads.filter( + (thread) => + threadSearchQuery.trim().length > 0 || + matchesInboxView(thread.source.inbox, inboxView) || + (inboxView === "agents" && thread.source.createdBy === "agent"), + ); const listedThreads = promotingDraftThreadKeys.length === 0 - ? threads - : threads.map((thread) => + ? inboxThreads + : inboxThreads.map((thread) => promotingDraftThreadKeys.includes(threadShellKey(thread)) ? asLaunchingThread(thread) : thread, @@ -2671,6 +2681,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), canTurnIntoProject: canTurnThreadIntoProject(threadRef), supports: { + inboxRouting: + serverConfigs.get(thread.environmentId)?.environment.capabilities.threadInbox === + true, settlement: configLoaded, autoSettleOptOut: supportsAutoSettleOptOut, snooze: configLoaded, @@ -2684,6 +2697,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); if (clicked._tag === "Failure" || clicked.value === null) return; if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return; + const inboxRouting = threadRoutingUpdateFromMenuAction(clicked.value); + if (inboxRouting) { + await updateThreadMetadata({ + environmentId: thread.environmentId, + input: { threadId: thread.id, inboxRouting }, + }); + return; + } if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" @@ -3208,6 +3229,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve activeSearchResultIndex={activeSearchResultIndex} onClearSearch={clearThreadSearch} /> + } > diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 6e6b2b37b6830..40c1e802c4407 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -1,3 +1,4 @@ +import { matchesInboxView } from "@t3tools/contracts"; import { type EnvironmentThreadShell, type PendingSubagentRequest, @@ -111,7 +112,15 @@ export function startThreadNotifications( const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom) ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey)) : null; - const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key)); + const outsideInbox = new Set(); + for (const [environmentId, state] of watched) { + for (const [threadId, entry] of state.previous) { + if (!matchesInboxView(entry.thread.source.inbox, getClientSettings().founderInboxView)) + outsideInbox.add(threadKey({ environmentId, threadId })); + } + } + const shouldClose = (key: string) => + outsideInbox.has(key) || hidden.has(key) || (live !== null && !live.has(key)); closeToasts(shouldClose); const count = pending.size; for (const [tag, entry] of pending) { @@ -133,6 +142,7 @@ export function startThreadNotifications( kind: ThreadNotificationKind, ) => { const { thread, status } = state; + if (!matchesInboxView(thread.source.inbox, getClientSettings().founderInboxView)) return; if ( registry .get(environmentThreadShells.hiddenThreadKeysAtom) @@ -415,6 +425,7 @@ export function startThreadNotifications( }; const onSettings = () => { + closeHiddenPending(); applyMode(); syncEnvironments(); }; diff --git a/apps/web/src/components/sidebar/SidebarInboxBar.tsx b/apps/web/src/components/sidebar/SidebarInboxBar.tsx new file mode 100644 index 0000000000000..8307abc3069d1 --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarInboxBar.tsx @@ -0,0 +1,49 @@ +import type { InboxView } from "@t3tools/contracts"; +import { updateClientSettings, useClientSettings } from "../../hooks/useSettings"; + +/** A local view of the shared pool; All and search always include every thread. */ +export function SidebarInboxBar() { + const view = useClientSettings((settings) => settings.founderInboxView); + const owner = useClientSettings((settings) => settings.founderInboxOwner); + return ( +
+ + +
+ ); +} diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index bd9dfdcdcc4b6..12234c2d70a28 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { buildThreadActionMenuItems, type ThreadActionMenuState } from "./threadActionMenu.logic"; +import { + threadRoutingUpdateFromMenuAction, + buildThreadActionMenuItems, + type ThreadActionMenuState, +} from "./threadActionMenu.logic"; const baseState: ThreadActionMenuState = { canOperate: true, @@ -75,3 +79,29 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); }); + +it("offers inbox routing only on capable environments and retains ordinary operate grants", () => { + expect(buildThreadActionMenuItems(baseState).some((item) => item.id === "inbox")).toBe(false); + const items = buildThreadActionMenuItems({ + ...baseState, + canOperate: false, + supports: { ...baseState.supports, inboxRouting: true }, + }); + expect( + items.find((item) => item.id === "inbox")?.children?.every((child) => child.disabled), + ).toBe(true); + expect(threadRoutingUpdateFromMenuAction("inbox:jeff")).toEqual({ + owner: "jeff", + assignee: { kind: "human", id: "jeff" }, + audience: "jeff", + attentionKind: "action", + }); + expect(threadRoutingUpdateFromMenuAction("inbox:agents")).toEqual({ + owner: null, + assignee: null, + audience: "agent-only", + attentionKind: "background", + }); + expect(threadRoutingUpdateFromMenuAction("attention:FYI")).toEqual({ attentionKind: "FYI" }); + expect(threadRoutingUpdateFromMenuAction("rename")).toBeNull(); +}); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 1e3eddd0b9389..4882857251d44 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -1,7 +1,12 @@ +import type { ThreadInboxRoutingPatch } from "@t3tools/contracts"; import type { ContextMenuItem } from "@t3tools/contracts"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; export type ThreadActionMenuId = + | "inbox" + | `inbox:${"kameron" | "jeff" | "shared" | "agents"}` + | "attention" + | `attention:${"action" | "FYI" | "background"}` | "find" | "new-thread-on-branch" | "filter-by-project" @@ -84,6 +89,7 @@ export interface ThreadActionMenuState { /** Archive rejects attached providers, so disable it while running. */ readonly isRunning: boolean; readonly supports: { + readonly inboxRouting?: boolean; readonly settlement: boolean; readonly autoSettleOptOut: boolean; readonly snooze: boolean; @@ -117,6 +123,29 @@ export function buildThreadActionMenuItems( state: ThreadActionMenuState, ): ReadonlyArray> { const items: ReadonlyArray> = [ + ...(state.supports.inboxRouting + ? [ + { + id: "inbox" as const, + label: "Route to inbox", + children: [ + { id: "inbox:kameron" as const, label: "Kameron" }, + { id: "inbox:jeff" as const, label: "Jeff" }, + { id: "inbox:shared" as const, label: "Shared" }, + { id: "inbox:agents" as const, label: "Agents / neither founder" }, + ], + }, + { + id: "attention" as const, + label: "Attention", + children: [ + { id: "attention:action" as const, label: "Needs action" }, + { id: "attention:FYI" as const, label: "FYI" }, + { id: "attention:background" as const, label: "Background" }, + ], + }, + ] + : []), ...(state.canFind ? [{ id: "find" as const, label: "Find in thread", icon: "text-search" }] : []), @@ -267,3 +296,23 @@ export function buildThreadActionMenuItems( : item, ); } + +export function threadRoutingUpdateFromMenuAction(action: string): ThreadInboxRoutingPatch | null { + if (action === "inbox:kameron" || action === "inbox:jeff") { + const founder = action === "inbox:kameron" ? "kameron" : "jeff"; + return { + owner: founder, + assignee: { kind: "human", id: founder }, + audience: founder, + attentionKind: "action", + }; + } + if (action === "inbox:shared") + return { owner: null, assignee: null, audience: "shared", attentionKind: "FYI" }; + if (action === "inbox:agents") + return { owner: null, assignee: null, audience: "agent-only", attentionKind: "background" }; + if (action === "attention:action") return { attentionKind: "action" }; + if (action === "attention:FYI") return { attentionKind: "FYI" }; + if (action === "attention:background") return { attentionKind: "background" }; + return null; +} diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6d2ce2a07c90b..bfa59ed5af3f9 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -20,6 +20,7 @@ import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { serverEnvironment } from "./server"; import { environmentShell } from "./shell"; +import { getClientSettings } from "../hooks/useSettings"; export const threadFamilies = createThreadFamilyAtoms( connectionAtomRuntime, @@ -32,6 +33,7 @@ export const olderSettledThreads = createOlderSettledThreadAtoms( export const threadEnvironment = createThreadEnvironmentAtoms( connectionAtomRuntime, threadFamilies.snapshotAtom, + { getInboxOrigin: () => ({ kind: "human", id: getClientSettings().founderInboxOwner }) }, ); const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime); export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index c6f5c8c34166e..bb976e3656f69 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1,6 +1,8 @@ import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences"; import { type ThreadLinkedPullRequest, + type InboxActor, + type ThreadInboxRoutingPatch, CommandId, CheckpointId, CheckpointScopeId, @@ -47,6 +49,8 @@ import { } from "../rpc/client.ts"; interface CommandMetadata { + readonly inboxOrigin?: InboxActor; + readonly inboxRouting?: ThreadInboxRoutingPatch; readonly commandId?: CommandId; readonly createdAt?: string; readonly creationSource?: OrchestrationV2CreationSource; @@ -470,6 +474,8 @@ export const createThread = Effect.fn("EnvironmentCommands.createThread")(functi return yield* dispatch({ type: "thread.create", commandId: yield* allocateCommandId(input), + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), createdBy: "user", creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -687,10 +693,12 @@ export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadM input.worktreePath !== undefined || input.regenerateTitle !== undefined || input.linkedPullRequest !== undefined || - input.limitRecovery !== undefined + input.limitRecovery !== undefined || + input.inboxRouting !== undefined ) { result = yield* dispatch({ type: "thread.metadata.update", + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), ...(input.limitRecovery === undefined ? {} : { limitRecovery: input.limitRecovery }), commandId, threadId: input.threadId, @@ -782,6 +790,8 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( }; return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, + ...(input.inboxOrigin === undefined ? {} : { inboxOrigin: input.inboxOrigin }), + ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), creationSource: input.creationSource ?? "web", threadId: input.threadId, ...(bootstrap === undefined ? { reuseExistingThread: true } : {}), diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 865f6273b20ad..7a772beafd803 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -1,4 +1,4 @@ -import { CommandId, type ModelSelection, type ThreadId } from "@t3tools/contracts"; +import { CommandId, type ModelSelection, type ThreadId, type InboxActor } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -24,6 +24,8 @@ import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts"; import { type InterruptThreadTurnInput, type UpdateThreadMetadataInput, + type CreateThreadInput, + type StartThreadTurnInput, archiveThread, closeGuestShare, resolveGuestMessage, @@ -77,7 +79,12 @@ export type LoadEarlierThreadHistoryInput = { export function createThreadEnvironmentAtoms( runtime: Atom.AtomRuntime, snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom, + options: { readonly getInboxOrigin?: () => InboxActor | undefined } = {}, ) { + const withInboxOrigin = (input: I) => { + const origin = input.inboxOrigin ?? options.getInboxOrigin?.(); + return origin === undefined ? input : { ...input, inboxOrigin: origin }; + }; const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, @@ -162,7 +169,7 @@ export function createThreadEnvironmentAtoms( create: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:create", - execute: createThread, + execute: (input: CreateThreadInput) => createThread(withInboxOrigin(input)), scheduler, concurrency, }), @@ -307,7 +314,7 @@ export function createThreadEnvironmentAtoms( }), startTurn: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:start-turn", - execute: startThreadTurn, + execute: (input: StartThreadTurnInput) => startThreadTurn(withInboxOrigin(input)), scheduler, concurrency, }), diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index e305efb51f838..5996294054e07 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -174,6 +174,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ in them. Absent on servers from before linking, which clients must not offer linking for. */ peerLinks: Schema.optionalKey(Schema.Boolean), + threadInbox: Schema.optionalKey(Schema.Boolean), /** Server's `/mcp` narrows an OAuth client's modes from `T3-Mode-Limit`, so a linked environment's calls keep its agent's limits. Another environment links to this one only when it is set. */ diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 8dd47df33a21f..7087bc252e443 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -73,3 +73,5 @@ export * from "./secretRequest.ts"; export * from "./secretReference.ts"; export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; + +export * from "./threadInbox.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index bf6b53666f4d7..e550233a74305 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3,6 +3,7 @@ import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import { ThreadInbox, ThreadInboxRoutingPatch, InboxActor } from "./threadInbox.ts"; import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; @@ -465,6 +466,7 @@ const OrchestrationV2LastTitleRegeneration = Schema.Struct({ export const OrchestrationV2AppThread = Schema.Struct({ ...OrchestrationV2CreationFields, + inbox: Schema.optionalKey(ThreadInbox), id: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, @@ -2171,6 +2173,7 @@ export type OrchestrationV2LatestVisibleMessageSummary = export const OrchestrationV2ThreadShell = Schema.Struct({ ...OrchestrationV2CreationFields, + inbox: Schema.optionalKey(ThreadInbox), id: ThreadId, projectId: ProjectId, title: Schema.String, @@ -3064,6 +3067,8 @@ export const OrchestrationV2Command = Schema.Union([ Schema.Struct({ type: Schema.Literal("thread.create"), ...OrchestrationV2CreationFields, + inboxOrigin: Schema.optionalKey(InboxActor), + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), commandId: CommandId, threadId: ThreadId, projectId: ProjectId, @@ -3204,6 +3209,7 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.metadata.update"), commandId: CommandId, threadId: ThreadId, + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), title: Schema.optional(TrimmedNonEmptyString), regenerateTitle: Schema.optional(Schema.Boolean), branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), @@ -3840,6 +3846,8 @@ export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2Archive export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ commandId: CommandId, + inboxOrigin: Schema.optionalKey(InboxActor), + inboxRouting: Schema.optionalKey(ThreadInboxRoutingPatch), creationSource: Schema.optional(OrchestrationV2CreationSource), threadId: Schema.optional(ThreadId), reuseExistingThread: Schema.optional(Schema.Boolean), diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 7148eed570ef7..7ef98d4100eef 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -267,7 +267,10 @@ export const OrchestratorMcpTaskCancelResult = Schema.Struct({ }); export type OrchestratorMcpTaskCancelResult = typeof OrchestratorMcpTaskCancelResult.Type; +import { ThreadInbox, ThreadInboxRoutingPatch } from "./threadInbox.ts"; + export const OrchestratorMcpCreateThreadRequest = Schema.Struct({ + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), prompt: Schema.optional(OrchestratorMcpPrompt), title: Schema.optional(OrchestratorMcpTitle), target: Schema.optional(OrchestratorMcpTarget), @@ -375,6 +378,7 @@ export const OrchestratorMcpThreadBackgroundTask = Schema.Struct({ export type OrchestratorMcpThreadBackgroundTask = typeof OrchestratorMcpThreadBackgroundTask.Type; export const OrchestratorMcpThreadListItem = Schema.Struct({ + inbox: Schema.optionalKey(ThreadInbox), threadId: ThreadId, projectId: ProjectId, title: Schema.String, @@ -449,6 +453,7 @@ export const OrchestratorMcpThreadReadInput = Schema.Struct({ export type OrchestratorMcpThreadReadInput = typeof OrchestratorMcpThreadReadInput.Type; export const OrchestratorMcpThreadDetail = Schema.Struct({ + inbox: Schema.optionalKey(ThreadInbox), threadId: ThreadId, projectId: ProjectId, title: Schema.String, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 3bb9374ec567d..fddbde4650281 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1,4 +1,5 @@ import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts"; +import { Founder, InboxView } from "./threadInbox.ts"; import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, @@ -397,6 +398,8 @@ export const VoiceTranscriptionDestination = Schema.Union([ export type VoiceTranscriptionDestination = typeof VoiceTranscriptionDestination.Type; export const ClientSettingsSchema = Schema.Struct({ + founderInboxOwner: Founder.pipe(Schema.withDecodingDefault(Effect.succeed("kameron" as const))), + founderInboxView: InboxView.pipe(Schema.withDecodingDefault(Effect.succeed("kameron" as const))), notificationMode: NotificationMode.pipe( Schema.withDecodingDefault(Effect.succeed("off" as const)), ), @@ -2006,6 +2009,8 @@ export function requiredScopesForProjectMutation( } export const ClientSettingsPatch = Schema.Struct({ + founderInboxOwner: Schema.optionalKey(Founder), + founderInboxView: Schema.optionalKey(InboxView), notificationMode: Schema.optionalKey(NotificationMode), inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean), diffColorScheme: Schema.optionalKey(DiffColorScheme), diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts new file mode 100644 index 0000000000000..fba1beb843e84 --- /dev/null +++ b/packages/contracts/src/threadInbox.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from "vite-plus/test"; +import { EnvironmentId } from "./baseSchemas.ts"; +import { + makeThreadInbox, + routeThreadInbox, + matchesInboxView, + founderInboxLane, + compositeThreadKey, +} from "./threadInbox.ts"; +const kameron = { kind: "human", id: "kameron" } as const; +const jeff = { kind: "human", id: "jeff" } as const; +const bot = { kind: "agent", id: "lead" } as const; +describe("shared fleet organizational inbox", () => { + it("keeps host collisions distinct", () => { + expect(compositeThreadKey("crown", "same")).not.toBe(compositeThreadKey("air", "same")); + expect(compositeThreadKey("a:b", "c")).not.toBe(compositeThreadKey("a", "b:c")); + }); + it("defaults founder-created work into that founder's inbox", () => { + const k = makeThreadInbox({ actor: kameron }); + const j = makeThreadInbox({ actor: jeff }); + expect(matchesInboxView(k, "kameron")).toBe(true); + expect(matchesInboxView(j, "kameron")).toBe(false); + expect(matchesInboxView(j, "jeff")).toBe(true); + expect(matchesInboxView(k, "jeff")).toBe(false); + expect(matchesInboxView(j, "all")).toBe(true); + expect(matchesInboxView(k, "all")).toBe(true); + }); + it("hides bot-only work by default while All and Agents retain it", () => { + const inbox = makeThreadInbox({ actor: bot }); + expect(matchesInboxView(inbox, "kameron")).toBe(false); + expect(matchesInboxView(inbox, "jeff")).toBe(false); + expect(matchesInboxView(inbox, "all")).toBe(true); + expect(matchesInboxView(inbox, "agents")).toBe(true); + }); + it("routes bot action and FYI assignments to either founder", () => { + for (const id of ["kameron", "jeff"] as const) { + const inbox = makeThreadInbox({ actor: bot, routing: { assignee: { kind: "human", id } } }); + expect(matchesInboxView(inbox, id)).toBe(true); + expect(founderInboxLane(inbox, id)).toBe("action"); + expect(founderInboxLane(routeThreadInbox(inbox, { attentionKind: "FYI" }), id)).toBe("FYI"); + expect(matchesInboxView(inbox, "all")).toBe(true); + } + }); + it("explicit reassignment wins over origin and retains provenance", () => { + const original = makeThreadInbox({ + actor: jeff, + executorEnvironmentId: EnvironmentId.make("air"), + }); + const assigned = routeThreadInbox(original, { assignee: kameron, owner: "kameron" }); + expect(matchesInboxView(assigned, "kameron")).toBe(true); + expect(matchesInboxView(assigned, "jeff")).toBe(false); + expect(assigned.origin).toEqual(jeff); + expect(assigned.requestedBy).toEqual(jeff); + expect(assigned.executorEnvironmentId).toEqual(original.executorEnvironmentId); + }); + it("inherits parent routing for child work without changing its requester", () => { + const parent = makeThreadInbox({ actor: jeff, routing: { attentionKind: "FYI" } }); + const child = makeThreadInbox({ + actor: bot, + parent, + executorEnvironmentId: EnvironmentId.make("r720"), + }); + expect(child.owner).toBe("jeff"); + expect(child.assignee).toEqual(jeff); + expect(child.requestedBy).toEqual(jeff); + expect(child.origin).toEqual(bot); + expect(founderInboxLane(child, "jeff")).toBe("FYI"); + expect(child.executorEnvironmentId).toBe("r720"); + }); + it("supports shared views and routing to neither founder", () => { + const shared = makeThreadInbox({ actor: kameron, routing: { audience: "shared" } }); + expect(matchesInboxView(shared, "shared")).toBe(true); + const neither = routeThreadInbox(shared, { + owner: null, + assignee: bot, + audience: "agent-only", + attentionKind: "background", + }); + expect(matchesInboxView(neither, "kameron")).toBe(false); + expect(matchesInboxView(neither, "jeff")).toBe(false); + expect(matchesInboxView(neither, "all")).toBe(true); + }); + it("keeps unclassified history visible in All without rewriting it", () => { + expect(matchesInboxView(undefined, "all")).toBe(true); + expect(matchesInboxView(undefined, "kameron")).toBe(false); + expect(matchesInboxView(undefined, "jeff")).toBe(false); + expect(founderInboxLane(undefined, "kameron")).toBe("unknown"); + }); +}); + +it("keeps unassigned agent-only action out of both founder inboxes", () => { + const inbox = makeThreadInbox({ + actor: bot, + routing: { owner: null, assignee: null, attentionKind: "action" }, + }); + expect(matchesInboxView(inbox, "kameron")).toBe(false); + expect(matchesInboxView(inbox, "jeff")).toBe(false); + expect(matchesInboxView(inbox, "agents")).toBe(true); + expect(matchesInboxView(inbox, "all")).toBe(true); + const assigned = routeThreadInbox(inbox, { owner: "jeff", assignee: jeff }); + expect(matchesInboxView(assigned, "jeff")).toBe(true); + expect(matchesInboxView(assigned, "kameron")).toBe(false); +}); + +it("keeps founder-owned agent-only children out of founder inboxes", () => { + const parent = makeThreadInbox({ actor: jeff }); + const child = makeThreadInbox({ + actor: bot, + parent, + routing: { audience: "agent-only", assignee: bot, attentionKind: "action" }, + }); + expect(child.owner).toBe("jeff"); + expect(matchesInboxView(child, "kameron")).toBe(false); + expect(matchesInboxView(child, "jeff")).toBe(false); + expect(matchesInboxView(child, "agents")).toBe(true); + expect(matchesInboxView(child, "all")).toBe(true); + const assigned = routeThreadInbox(child, { assignee: jeff }); + expect(matchesInboxView(assigned, "jeff")).toBe(true); + expect(matchesInboxView(assigned, "kameron")).toBe(false); +}); diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts new file mode 100644 index 0000000000000..d1095320294f0 --- /dev/null +++ b/packages/contracts/src/threadInbox.ts @@ -0,0 +1,112 @@ +import * as Schema from "effect/Schema"; +import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** Organizational labels on the shared fleet. These never authorize access. */ +export const Founder = Schema.Literals(["kameron", "jeff"]); +export type Founder = typeof Founder.Type; +export const InboxActor = Schema.Union([ + Schema.Struct({ kind: Schema.Literal("human"), id: Founder }), + Schema.Struct({ kind: Schema.Literal("agent"), id: TrimmedNonEmptyString }), +]); +export type InboxActor = typeof InboxActor.Type; +export const ThreadInboxRouting = Schema.Struct({ + owner: Schema.NullOr(Founder), + assignee: Schema.NullOr(InboxActor), + audience: Schema.Literals(["kameron", "jeff", "shared", "agent-only"]), + attentionKind: Schema.Literals(["action", "FYI", "background"]), +}); +export type ThreadInboxRouting = typeof ThreadInboxRouting.Type; +export const ThreadInboxRoutingPatch = Schema.Struct({ + owner: Schema.optionalKey(ThreadInboxRouting.fields.owner), + assignee: Schema.optionalKey(ThreadInboxRouting.fields.assignee), + audience: Schema.optionalKey(ThreadInboxRouting.fields.audience), + attentionKind: Schema.optionalKey(ThreadInboxRouting.fields.attentionKind), +}); +export type ThreadInboxRoutingPatch = typeof ThreadInboxRoutingPatch.Type; +export const ThreadInbox = Schema.Struct({ + ...ThreadInboxRouting.fields, + origin: Schema.NullOr(InboxActor), + requestedBy: Schema.NullOr(InboxActor), + actor: Schema.NullOr(InboxActor), + executorEnvironmentId: Schema.NullOr(EnvironmentId), +}); +export type ThreadInbox = typeof ThreadInbox.Type; +export const INBOX_CAPABILITY = "closura-founder-inbox-v2" as const; +export const InboxView = Schema.Literals(["kameron", "jeff", "shared", "agents", "all"]); +export type InboxView = typeof InboxView.Type; +export const compositeThreadKey = (environmentId: string, threadId: string) => + JSON.stringify([environmentId, threadId]); +export const InboxThreadRef = Schema.Struct({ environmentId: EnvironmentId, threadId: ThreadId }); + +export function makeThreadInbox(input: { + readonly actor: InboxActor | null; + readonly requestedBy?: InboxActor | null; + readonly executorEnvironmentId?: EnvironmentId | null; + readonly parent?: ThreadInbox | null; + readonly routing?: ThreadInboxRoutingPatch; +}): ThreadInbox { + const actor = input.actor; + const routing = input.routing; + const target = routing?.assignee?.kind === "human" ? routing.assignee.id : undefined; + const owner = + routing?.owner !== undefined + ? routing.owner + : (target ?? input.parent?.owner ?? (actor?.kind === "human" ? actor.id : null)); + const assignee = + routing?.assignee !== undefined + ? routing.assignee + : (input.parent?.assignee ?? (owner ? { kind: "human" as const, id: owner } : actor)); + const audience = routing?.audience ?? target ?? input.parent?.audience ?? owner ?? "agent-only"; + return { + owner, + assignee, + audience, + attentionKind: + routing?.attentionKind ?? + (target ? "action" : (input.parent?.attentionKind ?? (owner ? "action" : "background"))), + origin: actor, + actor, + requestedBy: input.requestedBy ?? input.parent?.requestedBy ?? actor, + executorEnvironmentId: input.executorEnvironmentId ?? null, + }; +} + +/** Preserve immutable origin/requester/executor when routing an existing thread. */ +export const routeThreadInbox = ( + inbox: ThreadInbox, + routing: ThreadInboxRoutingPatch, +): ThreadInbox => ({ + ...inbox, + ...routing, + ...(routing.assignee?.kind === "human" + ? { + owner: routing.owner === undefined ? routing.assignee.id : routing.owner, + audience: routing.audience ?? routing.assignee.id, + attentionKind: + routing.attentionKind ?? + (inbox.attentionKind === "background" ? "action" : inbox.attentionKind), + } + : {}), +}); + +export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: Founder) { + if (!inbox) return "unknown"; + const assigned = inbox.assignee?.kind === "human" ? inbox.assignee.id : inbox.owner; + if (inbox.audience === "agent-only" && inbox.assignee?.kind !== "human") return "hidden"; + if (assigned !== founder) return "hidden"; + return inbox.attentionKind; +} + +/** All deliberately includes every thread, including unclassified history. */ +export function matchesInboxView(inbox: ThreadInbox | null | undefined, view: InboxView) { + if (view === "all") return true; + if (view === "agents") + return ( + inbox?.origin?.kind === "agent" || + inbox?.assignee?.kind === "agent" || + inbox?.audience === "agent-only" + ); + if (view === "shared") return inbox?.audience === "shared"; + const lane = founderInboxLane(inbox, view); + return lane === "action" || lane === "FYI"; +} diff --git a/packages/contracts/src/threadMetadataMcp.test.ts b/packages/contracts/src/threadMetadataMcp.test.ts index 884741b762d65..022e197ef5c40 100644 --- a/packages/contracts/src/threadMetadataMcp.test.ts +++ b/packages/contracts/src/threadMetadataMcp.test.ts @@ -20,3 +20,16 @@ describe("ThreadMetadataMcpUpdateInput", () => { ); }); }); + +it("accepts agent routing and rejects ambiguous metadata actions", () => { + assert.deepEqual( + decodeUpdate({ + action: "route", + inboxRouting: { assignee: { kind: "human", id: "jeff" }, attentionKind: "FYI" }, + }).inboxRouting, + { assignee: { kind: "human", id: "jeff" }, attentionKind: "FYI" }, + ); + assert.throws(() => decodeUpdate({ action: "route" })); + assert.throws(() => decodeUpdate({ action: "rename", title: "x", inboxRouting: {} })); + assert.throws(() => decodeUpdate({ action: "route", inboxRouting: { owner: "other" } })); +}); diff --git a/packages/contracts/src/threadMetadataMcp.ts b/packages/contracts/src/threadMetadataMcp.ts index e5332ac56ab47..6fcb89671c48d 100644 --- a/packages/contracts/src/threadMetadataMcp.ts +++ b/packages/contracts/src/threadMetadataMcp.ts @@ -7,6 +7,7 @@ import { ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; +import { ThreadInbox, ThreadInboxRoutingPatch } from "./threadInbox.ts"; import { ThreadLinkedPullRequest } from "./threadPullRequest.ts"; import { ThreadTitleRegeneration } from "./threadTitle.ts"; @@ -40,19 +41,21 @@ const ThreadMetadataClientRequestId = TrimmedNonEmptyString.check(Schema.isMaxLe ) .annotate({ description: "Stable idempotency key to reuse when retrying this mutation." }); -export const ThreadMetadataMcpAction = Schema.Literals(["rename", "regenerate_title"]); +export const ThreadMetadataMcpAction = Schema.Literals(["rename", "regenerate_title", "route"]); export type ThreadMetadataMcpAction = typeof ThreadMetadataMcpAction.Type; export const ThreadMetadataMcpUpdateInput = Schema.Struct({ threadId: Schema.optional(ThreadId), action: ThreadMetadataMcpAction, title: Schema.optional(ThreadMetadataTitle), + inboxRouting: Schema.optional(ThreadInboxRoutingPatch), clientRequestId: Schema.optional(ThreadMetadataClientRequestId), }).check( Schema.makeFilter((input) => - (input.action === "rename") === (input.title !== undefined) + (input.action === "rename") === (input.title !== undefined) && + (input.action === "route") === (input.inboxRouting !== undefined) ? true - : "rename requires title; regenerate_title does not accept one.", + : "rename requires title; route requires inboxRouting; other actions reject those fields.", ), ); export type ThreadMetadataMcpUpdateInput = typeof ThreadMetadataMcpUpdateInput.Type; @@ -65,6 +68,7 @@ export const ThreadMetadataMcpUpdateResult = Schema.Struct({ title: Schema.String, titleRegeneration: Schema.NullOr(ThreadTitleRegeneration), linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest), + inbox: Schema.optionalKey(ThreadInbox), updatedAt: IsoDateTime, }); export type ThreadMetadataMcpUpdateResult = typeof ThreadMetadataMcpUpdateResult.Type; diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index f476bdc70ff80..b650652b4910f 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -18,6 +18,7 @@ import type { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { makeThreadInbox } from "@t3tools/contracts"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import * as DateTime from "effect/DateTime"; @@ -63,6 +64,16 @@ export function makeSubagentChildThread(input: { }): OrchestrationV2AppThread { return { ...input.parentThread, + inbox: makeThreadInbox({ + actor: { kind: "agent", id: input.childThreadId }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: input.childThreadId }, + attentionKind: "background", + }, + ...(input.parentThread.inbox === undefined ? {} : { parent: input.parentThread.inbox }), + executorEnvironmentId: input.parentThread.inbox?.executorEnvironmentId ?? null, + }), createdBy: input.createdBy, creationSource: input.creationSource, id: input.childThreadId,