diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.test.ts b/apps/server/src/mcp/ThreadMetadataMcpService.test.ts new file mode 100644 index 0000000000000..04188a3374058 --- /dev/null +++ b/apps/server/src/mcp/ThreadMetadataMcpService.test.ts @@ -0,0 +1,192 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import { + applyCollaborationUpdate, + EnvironmentId, + type OrchestrationV2ServerCommand, + type OrchestrationV2ThreadShell, + ProviderInstanceId, + ThreadId, + type ThreadMetadataMcpUpdateInput, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import type * as McpInvocationContext from "./McpInvocationContext.ts"; +import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts"; + +const room = ThreadId.make("thread-room"); +const growth = ThreadId.make("thread-growth"); +const cfo = ThreadId.make("thread-cfo"); +const gone = ThreadId.make("thread-gone"); +const deleted = ThreadId.make("thread-deleted"); +const NOW = "2026-11-24T15:00:00.000Z"; + +const scope: McpInvocationContext.McpInvocationScope = { + environmentId: EnvironmentId.make("environment-room-test"), + requestNamespace: "provider-session-room-test", + thread: { + threadId: room, + providerSessionId: "provider-session-room-test", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, +}; + +const shell = (id: ThreadId, overrides: Partial = {}) => + ({ + id, + title: id, + titleRegeneration: null, + linkedPullRequest: null, + updatedAt: DateTime.makeUnsafe(NOW), + deletedAt: null, + ...overrides, + }) as OrchestrationV2ThreadShell; + +/** + * The service against an in-memory thread table whose dispatch applies the collaboration update. + * Like the orchestrator, a repeated command id replays the first receipt without applying again. + */ +const makeHarness = () => { + const threads = new Map([ + [room, shell(room)], + [growth, shell(growth)], + [cfo, shell(cfo)], + [deleted, shell(deleted, { deletedAt: DateTime.makeUnsafe(NOW) })], + ]); + const dispatched: OrchestrationV2ServerCommand[] = []; + const receipts = new Map(); + const layer = ThreadMetadataMcpService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: (threadId) => Effect.succeed(threads.get(threadId) ?? null), + dispatch: (command) => + Effect.sync(() => { + const replayed = receipts.get(command.commandId); + if (replayed !== undefined) return { sequence: replayed, storedEvents: [] }; + dispatched.push(command); + receipts.set(command.commandId, dispatched.length); + if (command.type === "thread.metadata.update" && command.collaboration) { + const current = threads.get(command.threadId)!; + threads.set(command.threadId, { + ...current, + collaboration: applyCollaborationUpdate( + current.collaboration, + command.collaboration, + NOW, + ), + }); + } + // No stored events: the service answers from the projection, as on a retry. + return { sequence: dispatched.length, storedEvents: [] }; + }), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + const update = (input: ThreadMetadataMcpUpdateInput) => + Effect.gen(function* () { + const service = yield* ThreadMetadataMcpService.ThreadMetadataMcpService; + return yield* service.update(scope, input); + }).pipe(Effect.provide(layer)); + return { dispatched, update }; +}; + +const openRoom = (members: ReadonlyArray): ThreadMetadataMcpUpdateInput => ({ + action: "collaborate", + collaboration: { + type: "open_room", + room: { topic: "How we set up Growth", members, linearIssue: "ENG-123" }, + }, +}); + +describe("t3_thread_update collaborate", () => { + it.effect("refuses a room member that does not exist or was deleted, before dispatching", () => + Effect.gen(function* () { + const { dispatched, update } = makeHarness(); + const missing = yield* Effect.flip(update(openRoom([growth, gone]))); + expect(missing.code).toBe("invalid_request"); + expect(missing.message).toBe(`Room member ${gone} was not found.`); + const removed = yield* Effect.flip(update(openRoom([deleted, cfo]))); + expect(removed.message).toBe(`Room member ${deleted} was not found.`); + expect(dispatched).toEqual([]); + }), + ); + + it.effect("refuses the room thread as its own member", () => + Effect.gen(function* () { + const { dispatched, update } = makeHarness(); + const error = yield* Effect.flip(update(openRoom([room, growth]))); + expect(error.code).toBe("invalid_request"); + expect(error.message).toMatch(/the room thread itself facilitates/); + expect(dispatched).toEqual([]); + }), + ); + + it.effect("opens a room, then closes it once and returns the Linear and memory record", () => + Effect.gen(function* () { + const { dispatched, update } = makeHarness(); + const opened = yield* update(openRoom([growth, cfo])); + expect(opened.collaboration?.room?.members).toEqual([growth, cfo]); + expect(opened.roomRecord).toBeUndefined(); + + const close: ThreadMetadataMcpUpdateInput = { + action: "collaborate", + collaboration: { + type: "close_room", + close: { + summary: "Growth owns outbound.", + decisions: [{ text: "Growth runs the list" }], + }, + }, + }; + const closed = yield* update(close); + expect(closed.roomRecord?.linearIssue).toBe("ENG-123"); + expect(closed.roomRecord?.linearComment).toContain("- Growth runs the list"); + expect(closed.roomRecord?.memoryEntry).toContain("How we set up Growth"); + + const again = yield* Effect.flip(update(close)); + expect(again.message).toMatch(/no open room/); + expect(dispatched).toHaveLength(2); + }), + ); + + it.effect("keeps a closed room's record when asked to open it again", () => + Effect.gen(function* () { + const { dispatched, update } = makeHarness(); + yield* update(openRoom([growth, cfo])); + yield* update({ + action: "collaborate", + collaboration: { type: "close_room", close: { summary: "Done.", decisions: [] } }, + }); + const reopened = yield* Effect.flip(update(openRoom([growth, cfo]))); + expect(reopened.code).toBe("invalid_request"); + expect(reopened.message).toMatch(/room is closed/); + expect(dispatched).toHaveLength(2); + }), + ); + + it.effect("opens then closes a room under one clientRequestId", () => + Effect.gen(function* () { + const { dispatched, update } = makeHarness(); + const clientRequestId = "request-reused"; + yield* update({ ...openRoom([growth, cfo]), clientRequestId }); + const closed = yield* update({ + action: "collaborate", + clientRequestId, + collaboration: { type: "close_room", close: { summary: "Done.", decisions: [] } }, + }); + expect(closed.collaboration?.room?.closedAt).toBe(NOW); + expect(closed.roomRecord?.linearIssue).toBe("ENG-123"); + expect(dispatched.map((command) => command.commandId)).toHaveLength(2); + expect(new Set(dispatched.map((command) => command.commandId)).size).toBe(2); + }), + ); +}); diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 3429348ba3f31..330856f19a68a 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -1,5 +1,6 @@ import { agentInboxRoutingError, + collaborationUpdateError, CommandId, makeThreadInbox, OrchestratorMcpFailure, @@ -9,6 +10,7 @@ import { type ThreadMetadataMcpUpdateInput, type ThreadMetadataMcpUpdateResult, ThreadId, + roomCloseRecord, routeThreadInbox, withLegacyPeerInboxReason, } from "@t3tools/contracts"; @@ -47,7 +49,8 @@ function stablePart(value: string): string { function commandId(input: { readonly scope: McpInvocationScope; readonly threadId: ThreadId; - readonly action: ThreadMetadataMcpAction; + /** The action, with collaborate's sub-action, so one clientRequestId can open then close a room. */ + readonly operation: string; readonly requestKey: string; }): CommandId { return CommandId.make( @@ -57,7 +60,7 @@ function commandId(input: { stablePart(input.scope.requestNamespace), "thread-update", stablePart(input.threadId), - stablePart(input.action), + stablePart(input.operation), stablePart(input.requestKey), ].join(":"), ); @@ -129,19 +132,42 @@ function metadataCommand(input: { threadId: input.threadId, decisionRequest: null, }; + case "collaborate": + return { + type: "thread.metadata.update", + commandId: input.commandId, + threadId: input.threadId, + collaboration: input.update.collaboration!, + }; } } function resultFromThread(input: { readonly action: ThreadMetadataMcpAction; + /** close_room answers with the record the facilitator writes to Linear and memory. */ + readonly closedRoom: boolean; readonly commandId: CommandId; readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" | "standing" | "delegationNudge" + | "id" + | "title" + | "titleRegeneration" + | "linkedPullRequest" + | "updatedAt" + | "inbox" + | "standing" + | "delegationNudge" + | "collaboration" >; }): ThreadMetadataMcpUpdateResult { + const room = input.thread.collaboration?.room; + const roomRecord = input.closedRoom && room !== undefined ? roomCloseRecord(room) : null; return { + ...(input.action !== "collaborate" || input.thread.collaboration === undefined + ? {} + : { collaboration: input.thread.collaboration }), + ...(roomRecord === null ? {} : { roomRecord }), ...(input.thread.inbox === undefined ? {} : { inbox: input.thread.inbox }), ...(input.thread.standing === undefined ? {} : { standing: input.thread.standing }), ...(input.thread.delegationNudge === undefined @@ -214,6 +240,28 @@ const make = Effect.gen(function* () { input.inboxRouting, ); if (inboxError !== null) return yield* failure("invalid_request", inboxError); + if (input.collaboration !== undefined) { + const collaborationError = collaborationUpdateError(shell.collaboration, input.collaboration); + if (collaborationError !== null) return yield* failure("invalid_request", collaborationError); + if (input.collaboration.type === "open_room") { + const members = input.collaboration.room.members; + if (members.includes(threadId)) { + return yield* failure( + "invalid_request", + "A room's members are other threads; the room thread itself facilitates.", + ); + } + // Only existence is checked here; t3_thread_send applies the mode and link checks per message. + for (const member of members) { + const memberShell = yield* threadManagement + .getThreadShell(member) + .pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error)))); + if (memberShell === null || memberShell.deletedAt !== null) { + return yield* failure("invalid_request", `Room member ${member} was not found.`); + } + } + } + } if ( input.action === "set_delegation_nudge" && scope.thread?.threadId === threadId @@ -228,7 +276,10 @@ const make = Effect.gen(function* () { const updateCommandId = commandId({ scope, threadId, - action: input.action, + operation: + input.collaboration === undefined + ? input.action + : `${input.action}.${input.collaboration.type}`, requestKey, }); const dispatched = yield* threadManagement @@ -271,6 +322,7 @@ const make = Effect.gen(function* () { } return resultFromThread({ action: input.action, + closedRoom: input.collaboration?.type === "close_room", commandId: updateCommandId, sequence: dispatched.sequence, thread, diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 330ca0c720585..68b4e3e67e447 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -270,7 +270,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Default: this thread. Founder must decide/review/approve: `request_decision` with `decision`; stays in their inbox until reply, `resolve_decision` or settle. `route`: `inboxRouting`, `reason` for founder/shared. `rename`: `title`; `set_standing`: `standing`; `set_delegation_nudge`: `delegationNudge` {enabled, thresholds?}, not on itself. Not workspace/branch.", + "Default: this thread. Founder must decide/review/approve: `request_decision` with `decision`; stays in their inbox until reply, `resolve_decision` or settle. `route`: `inboxRouting`, `reason` for founder/shared. `rename`: `title`; `set_standing`: `standing`; `set_delegation_nudge`: `delegationNudge` {enabled, thresholds?}, not on itself. `collaborate`: room, promise, handoff. Not workspace/branch.", // 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/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 14c3d07d8b737..b47b46dd01294 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -19,6 +19,7 @@ import { RunAttemptId, RunId, RuntimeRequestId, + type ThreadCollaborationUpdate, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -593,6 +594,68 @@ const completeAndSnoozeThread = Effect.fn("test.completeAndSnoozeThread")(functi return { threadId, completedAt, snoozedUntil }; }); +it.effect("a room opens, closes once, and reaches the thread shell", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:room"); + const members = [ThreadId.make("thread:room-growth"), ThreadId.make("thread:room-cfo")]; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-room"), + threadId, + projectId: ProjectId.make("project:room"), + title: "Room", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + let step = 0; + const collaborate = (collaboration: ThreadCollaborationUpdate) => + Effect.gen(function* () { + yield* TestClock.adjust("1 minute"); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`room-${++step}`), + threadId, + collaboration, + }); + return (yield* projections.getThreadShell(threadId))?.collaboration; + }); + + const opened = yield* collaborate({ + type: "open_room", + room: { topic: "Who owns outbound", members, linearIssue: "ENG-1" }, + }); + assert.deepEqual(opened?.room?.members, members); + const promised = yield* collaborate({ + type: "set_promise", + promise: { id: "list", text: "Send the outbound list", dueAt: "2026-11-25T22:00:00Z" }, + }); + assert.equal(promised?.room?.openedAt, opened?.room?.openedAt); + assert.deepEqual( + promised?.promises?.map((promise) => promise.id), + ["list"], + ); + + const closed = yield* collaborate({ + type: "close_room", + close: { summary: "Growth owns outbound.", decisions: [{ text: "Growth runs it" }] }, + }); + assert.isDefined(closed?.room?.closedAt); + const replayed = yield* collaborate({ + type: "close_room", + close: { summary: "A second close.", decisions: [] }, + }); + assert.deepEqual(replayed?.room, closed?.room); + assert.deepEqual(replayed?.promises, promised?.promises); + }).pipe(Effect.provide(layerTest)), +); + it.effect("mark unread retires an expired snooze so a dismissed wake stays dismissed", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 30ab333c6ba15..e4ccc5958d38f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8,6 +8,7 @@ import type { ProjectId, } from "@t3tools/contracts"; import { + applyCollaborationUpdate, inboxAfterStandingSet, makeThreadInbox, nextFounderSeenMessage, @@ -5744,6 +5745,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { inbox: askedInbox(thread.inbox, command, now) }), ...(command.title === undefined ? {} : { title: command.title }), + ...(command.collaboration === undefined + ? {} + : { + collaboration: applyCollaborationUpdate( + thread.collaboration, + command.collaboration, + DateTime.formatIso(now), + ), + }), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && limitRecovery?.snooze === true && diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2e68921fd20ce..18a8b742f2455 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1975,6 +1975,7 @@ export function threadShellFromProjection( ...(projection.thread.delegationNudge ? { delegationNudge: projection.thread.delegationNudge } : {}), + ...(projection.thread.collaboration ? { collaboration: projection.thread.collaboration } : {}), lastVisitedAt: projection.thread.lastVisitedAt, ...(projection.thread.visitsByFounder === undefined ? {} @@ -2295,6 +2296,9 @@ function shellFromState(input: { ...(input.state.thread.delegationNudge ? { delegationNudge: input.state.thread.delegationNudge } : {}), + ...(input.state.thread.collaboration + ? { collaboration: input.state.thread.collaboration } + : {}), lastVisitedAt: input.state.thread.lastVisitedAt, opens: input.state.thread.opens ?? null, titleRegeneration: input.state.thread.titleRegeneration ?? null, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 22fe4136dfaab..cb0de86253f01 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -8,6 +8,7 @@ import { import { CommandId, latestProviderTurnForAttempt, + roomFacilitatorNote, type OrchestrationV2DomainEvent, type OrchestrationV2ContextHandoff, type OrchestrationV2ExecutionNode, @@ -981,7 +982,10 @@ export const layer: Layer.Layer< .filter((source) => source.ordinal < run.ordinal) .toSorted((left, right) => right.ordinal - left.ordinal)[0]; const deferredNudge = previousRun?.delegationNudge?.deferredNote ?? ""; - const runNote = [restartNote, deferredNudge].filter((part) => part !== "").join("\n\n"); + const roomNote = roomFacilitatorNote(projection.thread.collaboration?.room); + const runNote = [restartNote, deferredNudge, roomNote] + .filter((part) => part !== "") + .join("\n\n"); const tokenCap = yield* handoffTokenCapConfig.pipe( Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), ); diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index a7238bfb8b563..3382d549dcb3f 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -1,6 +1,8 @@ import { assert, it } from "@effect/vitest"; import { + applyCollaborationUpdate, makeThreadInbox, + roomFacilitatorNote, matchesInboxView, CommandId, EnvironmentId, @@ -90,7 +92,7 @@ function makeParentThread(): OrchestrationV2AppThread { }; } -it("resets a subagent child's snooze, title job and remote delegation but keeps its workspace", () => { +it("resets a subagent child's snooze, title job, remote delegation and room but keeps its workspace", () => { const parentThread: OrchestrationV2AppThread = { ...makeParentThread(), inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), @@ -100,6 +102,17 @@ it("resets a subagent child's snooze, title job and remote delegation but keeps threadId: ThreadId.make("linked-parent"), title: "Linked parent", }, + collaboration: applyCollaborationUpdate( + undefined, + { + type: "open_room", + room: { + topic: "Who owns outbound", + members: [ThreadId.make("thread:room-member-a"), ThreadId.make("thread:room-member-b")], + }, + }, + "2026-07-24T09:00:00.000Z", + ), }; const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child"); const parentNodeId = NodeId.make("node:subagent-parent"); @@ -126,6 +139,10 @@ it("resets a subagent child's snooze, title job and remote delegation but keeps assert.isNull(childThread.snoozedAt); assert.isNull(childThread.titleRegeneration); assert.isUndefined(childThread.delegatedFrom); + // The parent facilitates its room; the subagent's turns carry no facilitator note. + assert.notEqual(roomFacilitatorNote(parentThread.collaboration?.room), ""); + assert.equal(roomFacilitatorNote(childThread.collaboration?.room), ""); + assert.isUndefined(childThread.collaboration); assert.equal(childThread.projectId, parentThread.projectId); assert.equal(childThread.runtimeMode, parentThread.runtimeMode); assert.equal(childThread.interactionMode, parentThread.interactionMode); diff --git a/apps/server/src/orchestration-v2/ThreadForkService.test.ts b/apps/server/src/orchestration-v2/ThreadForkService.test.ts index f9f6ff25b2f0a..5a65aaf12dc53 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + applyCollaborationUpdate, CommandId, ContextTransferId, EnvironmentId, @@ -11,6 +12,7 @@ import { ProjectId, ProviderInstanceId, ProviderThreadId, + roomFacilitatorNote, RunId, ThreadId, type ThreadPullRequestLink, @@ -134,7 +136,7 @@ const planFork = ( }); }).pipe(Effect.provide(ThreadForkService.layer)); -it.effect("resets a fork's pin, snooze, settle and delegation state but keeps its origin", () => +it.effect("resets a fork's pin, snooze, settle, delegation and room but keeps its origin", () => Effect.gen(function* () { const linkOrigin = { sessionId: "mcp-session:fork-source", label: "Linked laptop" }; const sourceThread: OrchestrationV2AppThread = { @@ -149,6 +151,17 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it threadId: ThreadId.make("linked-parent"), title: "Linked parent", }, + collaboration: applyCollaborationUpdate( + undefined, + { + type: "open_room", + room: { + topic: "Who owns outbound", + members: [ThreadId.make("thread:room-member-a"), ThreadId.make("thread:room-member-b")], + }, + }, + "2026-07-24T09:00:00.000Z", + ), historyOrigin: "v1_import", linkOrigin, tags: ["private"], @@ -167,6 +180,10 @@ it.effect("resets a fork's pin, snooze, settle and delegation state but keeps it assert.isNull(result.targetThread.activeOrderKey); assert.isNull(result.targetThread.autoSettleDisabledAt); assert.isUndefined(result.targetThread.delegatedFrom); + // The source facilitates its room; the fork's turns carry no facilitator note. + assert.notEqual(roomFacilitatorNote(sourceThread.collaboration?.room), ""); + assert.equal(roomFacilitatorNote(result.targetThread.collaboration?.room), ""); + assert.isUndefined(result.targetThread.collaboration); assert.equal(result.targetThread.historyOrigin, "v1_import"); assert.deepEqual(result.targetThread.linkOrigin, linkOrigin); assert.deepEqual(result.targetThread.tags, ["private"]); diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index 1dc6d1eaf4a54..d0851dbad1401 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -99,8 +99,13 @@ export const layer: Layer.Layer = Layer.succeed( cause: forkableSourceRunStatusError(sourceRun), }); } - // The remote parent delegated the source thread, not its forks. - const { delegatedFrom: _delegatedFrom, ...inherited } = input.sourceProjection.thread; + // The remote parent delegated the source thread, not its forks. A room, its promises and + // handoff stay with the source too; a fork would facilitate the room a second time. + const { + delegatedFrom: _delegatedFrom, + collaboration: _collaboration, + ...inherited + } = input.sourceProjection.thread; const targetThread: OrchestrationV2AppThread = { ...inherited, // PR context follows the conversation; watching remains the source thread's responsibility. diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a83f96fbae2d6..9108cf5ef1f31 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -289,6 +289,7 @@ import { } from "../state/entities"; import { useEnvironmentShellHasSnapshot } from "../state/shell"; import { CatchMeUpControl } from "./chat/CatchMeUpControl"; +import { useCollaborationBannerItems } from "./chat/ComposerCollaboration"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog"; @@ -1378,6 +1379,16 @@ export default function ChatView(props: ChatViewProps) { automaticEnvironment, autoUpdateEnvironments, }); + const collaborationBannerItems = useCollaborationBannerItems({ + environmentId, + shell: activeThreadShell?.source ?? null, + viewerFounder, + timestampFormat, + onCompose: (text) => { + composerRef.current?.insertTextAtEnd(text, { ensureLeadingBoundary: true }); + composerRef.current?.focusAtEnd(); + }, + }); const providerInstanceEntries = providerInstanceEntriesFor( providerStatuses, settings, @@ -2819,6 +2830,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...collaborationBannerItems, ...systemComposerBannerItems, ]; } @@ -2830,6 +2842,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...collaborationBannerItems, ...systemComposerBannerItems, branchMismatchBannerItem({ mismatchKey: activeBranchMismatchKey, diff --git a/apps/web/src/components/chat/ComposerCollaboration.tsx b/apps/web/src/components/chat/ComposerCollaboration.tsx new file mode 100644 index 0000000000000..3e74d69bcbb97 --- /dev/null +++ b/apps/web/src/components/chat/ComposerCollaboration.tsx @@ -0,0 +1,182 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isRoomOpen, + openPromises, + promiseState, + type EnvironmentId, + type OrchestrationV2ThreadShell, + type ThreadDecisionRequest, + type ThreadHandoff, + type ThreadId, + type ThreadRoom, +} from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import { ArrowRightLeftIcon, ClockIcon, SignpostIcon, UsersIcon } from "lucide-react"; + +import { useNowAcross } from "../../hooks/useDeadline"; +import { useQuietThreadShell } from "../../state/entities"; +import { formatUpcomingTimestamp } from "../../timestampFormat"; +import { Button } from "../ui/button"; +import { ComposerBanner } from "./ComposerBanner"; +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; + +/** + * Cards for a thread's room, promises, handoff, and a founder decision with options. They only + * read the shell; every action fills the composer, so the person still sends the words. + */ +export function useCollaborationBannerItems({ + environmentId, + shell, + viewerFounder, + timestampFormat, + onCompose, +}: { + readonly environmentId: EnvironmentId; + readonly shell: OrchestrationV2ThreadShell | null; + readonly viewerFounder: string | null; + readonly timestampFormat: TimestampFormat; + readonly onCompose: (text: string) => void; +}): ReadonlyArray { + const collaboration = shell?.collaboration; + const promises = openPromises(collaboration); + const handoffDueAt = collaboration?.handoff?.dueAt; + const nowMs = useNowAcross([ + ...promises.map((promise) => Date.parse(promise.dueAt)), + ...(handoffDueAt === undefined ? [] : [Date.parse(handoffDueAt)]), + ]); + const decision = shell?.inbox?.decisionRequest; + const items: ComposerBannerStackItem[] = []; + if (decision?.options !== undefined && (viewerFounder ?? decision.founder) === decision.founder) { + items.push(decisionItem(decision, onCompose)); + } + if (isRoomOpen(collaboration?.room)) { + items.push(roomItem(environmentId, collaboration.room, onCompose)); + } + if (promises.length > 0) { + const overdue = promises.filter((promise) => promiseState(promise, nowMs) === "overdue"); + const [first] = overdue.length > 0 ? overdue : promises; + items.push({ + id: "collaboration-promises", + variant: overdue.length > 0 ? "error" : "info", + icon: , + title: `${overdue.length > 0 ? "Overdue" : "Promised"}: ${first!.text}`, + description: [ + `${overdue.length > 0 ? "was due" : "due"} ${formatUpcomingTimestamp(first!.dueAt, timestampFormat, nowMs)}`, + ...(first!.owner === undefined ? [] : [first!.owner]), + ...(promises.length > 1 + ? [ + `${promises.length - 1} more open${overdue.length > 1 ? `, ${overdue.length - 1} overdue` : ""}`, + ] + : []), + ].join(" · "), + }); + } + if (collaboration?.handoff !== undefined) { + items.push(handoffItem(collaboration.handoff, timestampFormat, nowMs)); + } + return items; +} + +const replyPrefix = { decision: "Decision", review: "Review", approval: "Approval" } as const; + +function decisionItem( + decision: ThreadDecisionRequest, + onCompose: (text: string) => void, +): ComposerBannerStackItem { + return { + id: "collaboration-decision", + variant: "warning", + icon: , + title: decision.question, + description: "Pick one to draft your reply.", + children: ( + + {decision.options!.map((option) => { + const recommended = option.label === decision.recommendation; + return ( +
+ + + {recommended ? "Recommended. " : ""} + {option.effect} + +
+ ); + })} +
+ ), + }; +} + +function roomItem( + environmentId: EnvironmentId, + room: ThreadRoom, + onCompose: (text: string) => void, +): ComposerBannerStackItem { + return { + id: "collaboration-room", + variant: "info", + icon: , + title: `Room: ${room.topic}`, + description: ( + <> + {room.members.map((member, index) => ( + + {index > 0 ? ", " : ""} + + + ))} + {room.linearIssue === undefined ? null : ` · records to ${room.linearIssue}`} + + ), + actions: ( + + ), + }; +} + +function RoomMember({ + environmentId, + threadId, +}: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const member = useQuietThreadShell(scopeThreadRef(environmentId, threadId)); + return member?.title ?? threadId; +} + +function handoffItem( + handoff: ThreadHandoff, + timestampFormat: TimestampFormat, + nowMs: number, +): ComposerBannerStackItem { + const overdue = handoff.dueAt !== undefined && Date.parse(handoff.dueAt) <= nowMs; + return { + id: "collaboration-handoff", + variant: overdue ? "error" : "default", + icon: , + title: `${handoff.from} → ${handoff.to}: ${handoff.what}`, + ...(handoff.dueAt === undefined + ? {} + : { + description: `${overdue ? "was due" : "due"} ${formatUpcomingTimestamp(handoff.dueAt, timestampFormat, nowMs)}`, + }), + }; +} diff --git a/apps/web/src/hooks/useDeadline.browser.test.tsx b/apps/web/src/hooks/useDeadline.browser.test.tsx index f261af96f3b84..2520e27dfd049 100644 --- a/apps/web/src/hooks/useDeadline.browser.test.tsx +++ b/apps/web/src/hooks/useDeadline.browser.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { act, fakeTimers, render } from "../../test/render"; -import { useNowAfter } from "./useDeadline"; +import { useNowAcross, useNowAfter } from "./useDeadline"; function Probe(props: { deadlineMs: number }) { const nowMs = useNowAfter(props.deadlineMs); @@ -23,3 +23,24 @@ describe("useNowAfter", () => { await expect.element(screen.getByText("passed")).toBeInTheDocument(); }); }); + +function DueProbe(props: { deadlinesMs: ReadonlyArray }) { + const nowMs = useNowAcross(props.deadlinesMs); + return ( + {`${props.deadlinesMs.filter((deadline) => deadline <= nowMs).length} due`} + ); +} + +describe("useNowAcross", () => { + it("flips once at each deadline, in order", async () => { + using _timers = fakeTimers({ now: 0 }); + await using screen = await render(, { + router: false, + }); + await expect.element(screen.getByText("0 due")).toBeInTheDocument(); + await act(() => vi.advanceTimersByTime(1_000)); + await expect.element(screen.getByText("1 due")).toBeInTheDocument(); + await act(() => vi.advanceTimersByTime(2_000)); + await expect.element(screen.getByText("2 due")).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/hooks/useDeadline.ts b/apps/web/src/hooks/useDeadline.ts index 71634d67cd658..f9d87741e96eb 100644 --- a/apps/web/src/hooks/useDeadline.ts +++ b/apps/web/src/hooks/useDeadline.ts @@ -21,3 +21,20 @@ export function useNowAfter(deadlineMs: number | null): number { if (snapshot.deadlineMs !== deadlineMs || snapshot.passed !== passed) setSnapshot(readNow); return snapshot.nowMs; } + +/** + * `Date.now()` re-read as each of `deadlinesMs` passes, one timer at a time, so every + * comparison against any of them flips exactly once. + */ +export function useNowAcross(deadlinesMs: ReadonlyArray): number { + const [nowMs, setNowMs] = useState(() => Date.now()); + const next = deadlinesMs.reduce( + (soonest, deadline) => + deadline > nowMs && (soonest === null || deadline < soonest) ? deadline : soonest, + null, + ); + const passed = useDeadlinePassed(next); + // As in useNowAfter, the clock is read inside the updater. + if (passed) setNowMs(() => Date.now()); + return nowMs; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index a105f5a65fe1c..79d24d2e8aa56 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -80,5 +80,6 @@ export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; export * from "./threadInbox.ts"; +export * from "./threadCollaboration.ts"; export * from "./botAttention.ts"; export * from "./typingPresence.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6230383c9a84c..d3692f00abe80 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -57,6 +57,7 @@ import { ChatAttachment } from "./chatAttachment.ts"; import { ThreadGuestShare } from "./guestShare.ts"; import { StoredThreadTags, ThreadTag } from "./threadTags.ts"; import { StoredThreadStanding, ThreadStanding } from "./threadStanding.ts"; +import { StoredThreadCollaboration, ThreadCollaborationUpdate } from "./threadCollaboration.ts"; import { DelegationNudgeChangedBy, DelegationNudgeUpdate, @@ -571,6 +572,8 @@ export const OrchestrationV2AppThread = Schema.Struct({ standing: Schema.optional(StoredThreadStanding), /** Opt-in reminder to delegate once the thread does work itself; absent or null is off. */ delegationNudge: Schema.optional(StoredThreadDelegationNudge), + /** Room, promises and handoff; absent on ordinary threads. */ + collaboration: Schema.optional(StoredThreadCollaboration), lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), @@ -2613,6 +2616,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ standing: Schema.optional(StoredThreadStanding), /** Opt-in reminder to delegate; absent or null is off. */ delegationNudge: Schema.optional(StoredThreadDelegationNudge), + /** Room, promises and handoff; absent on ordinary threads. */ + collaboration: Schema.optional(StoredThreadCollaboration), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), /** Per-founder read cursors. Older servers omit them; clients then keep the shared cursor. */ visitsByFounder: Schema.optional(FounderVisits), @@ -3689,6 +3694,8 @@ export const OrchestrationV2Command = Schema.Union([ limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)), /** Link (object) or unlink (null) a pull request; absent leaves it unchanged. */ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + /** Open or close a room, set or keep a promise, or set the handoff. */ + collaboration: Schema.optionalKey(ThreadCollaborationUpdate), }), Schema.Struct({ type: Schema.Literal("thread.pull-request.link"), diff --git a/packages/contracts/src/threadCollaboration.test.ts b/packages/contracts/src/threadCollaboration.test.ts new file mode 100644 index 0000000000000..b1118d950aead --- /dev/null +++ b/packages/contracts/src/threadCollaboration.test.ts @@ -0,0 +1,220 @@ +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { ThreadId } from "./baseSchemas.ts"; +import { + applyCollaborationUpdate, + collaborationUpdateError, + openPromises, + promiseState, + roomCloseRecord, + roomFacilitatorNote, + StoredThreadCollaboration, + THREAD_MAX_PROMISES, + ThreadCollaborationUpdate, + type ThreadCollaboration, +} from "./threadCollaboration.ts"; +import { ThreadDecisionAsk } from "./threadInbox.ts"; + +const cos = ThreadId.make("thread-cos"); +const growth = ThreadId.make("thread-growth"); +const T0 = "2026-11-24T15:00:00.000Z"; +const T1 = "2026-11-24T16:00:00.000Z"; +const decodeUpdate = Schema.decodeUnknownSync(ThreadCollaborationUpdate); +const isDecisionAsk = Schema.is(ThreadDecisionAsk); +const decodeStored = Schema.decodeUnknownSync(StoredThreadCollaboration); + +const openRoom = applyCollaborationUpdate( + undefined, + { + type: "open_room", + room: { topic: "How we set up Growth", members: [cos, growth], linearIssue: "ENG-123" }, + }, + T0, +); + +describe("rooms", () => { + it("rejects a room with fewer than two members or a repeated member", () => { + expect(() => + decodeUpdate({ type: "open_room", room: { topic: "x", members: [cos] } }), + ).toThrow(); + expect(() => + decodeUpdate({ type: "open_room", room: { topic: "x", members: [cos, cos] } }), + ).toThrow(); + expect(() => + decodeUpdate({ + type: "open_room", + room: { topic: "x", members: [cos, growth], linearIssue: "not an issue" }, + }), + ).toThrow(); + }); + + it("keeps the opening time when members change and refuses to close twice", () => { + const changed = applyCollaborationUpdate( + openRoom, + { + type: "open_room", + room: { topic: "How we set up Growth", members: [cos, growth, ThreadId.make("cfo")] }, + }, + T1, + ); + expect(changed.room?.openedAt).toBe(T0); + expect(changed.room?.members).toHaveLength(3); + + const close = { + type: "close_room" as const, + close: { + summary: "Growth owns outbound.", + decisions: [{ text: "Growth runs the weekly list", owner: "Growth" }], + }, + }; + const closed = applyCollaborationUpdate(openRoom, close, T1); + expect(closed.room?.closedAt).toBe(T1); + expect(collaborationUpdateError(closed, close)).toMatch(/no open room/); + // A replayed close leaves the first close in place. + expect( + applyCollaborationUpdate( + closed, + { ...close, close: { summary: "other", decisions: [] } }, + T1, + ), + ).toEqual(closed); + expect(roomFacilitatorNote(closed.room!)).toBe(""); + }); + + it("refuses to reopen a closed room so its close record stays intact", () => { + const closed = applyCollaborationUpdate( + openRoom, + { type: "close_room", close: { summary: "Growth owns outbound.", decisions: [] } }, + T1, + ); + const reopen = { + type: "open_room" as const, + room: { topic: "Another topic", members: [cos, growth] }, + }; + expect(collaborationUpdateError(closed, reopen)).toMatch(/room is closed/); + expect(applyCollaborationUpdate(closed, reopen, T1)).toEqual(closed); + expect(closed.room?.close?.summary).toBe("Growth owns outbound."); + }); + + it("writes the close record for Linear and memory", () => { + const closed = applyCollaborationUpdate( + openRoom, + { + type: "close_room", + close: { + summary: "Growth owns outbound.", + decisions: [ + { text: "Growth runs the weekly list", owner: "Growth", dueAt: "2026-11-28T17:00:00Z" }, + { text: "CoS reviews it Fridays" }, + ], + }, + }, + T1, + ); + const record = roomCloseRecord(closed.room!); + expect(record?.linearIssue).toBe("ENG-123"); + expect(record?.linearComment).toContain("## Room closed: How we set up Growth"); + expect(record?.linearComment).toContain( + "- Growth runs the weekly list (owner: Growth, due 2026-11-28T17:00:00Z)", + ); + expect(record?.memoryEntry).toContain("- CoS reviews it Fridays"); + expect(roomCloseRecord(openRoom.room!)).toBeNull(); + }); + + it("tells an open room's facilitator who to fan out to", () => { + const note = roomFacilitatorNote(openRoom.room!); + expect(note).toContain(`${cos}, ${growth}`); + expect(note).toContain("on ENG-123"); + }); +}); + +describe("promises", () => { + const promise = (id: string, dueAt: string) => ({ + type: "set_promise" as const, + promise: { id, text: `Ship ${id}`, dueAt }, + }); + + it("turns overdue at its due time and stops counting once kept", () => { + const state = applyCollaborationUpdate(undefined, promise("a", T1), T0); + const [stored] = state.promises!; + expect(promiseState(stored!, Date.parse(T0))).toBe("open"); + expect(promiseState(stored!, Date.parse(T1))).toBe("overdue"); + const kept = applyCollaborationUpdate(state, { type: "keep_promise", promiseId: "a" }, T1); + expect(promiseState(kept.promises![0]!, Date.parse(T1) + 1)).toBe("kept"); + expect(openPromises(kept)).toEqual([]); + }); + + it("updates a promise by id and lists open ones soonest first", () => { + let state: ThreadCollaboration = applyCollaborationUpdate(undefined, promise("late", T1), T0); + state = applyCollaborationUpdate(state, promise("soon", T0), T0); + state = applyCollaborationUpdate(state, promise("late", "2026-11-30T00:00:00Z"), T0); + expect(openPromises(state).map((entry) => entry.id)).toEqual(["soon", "late"]); + }); + + it("caps open promises and lets kept ones make room", () => { + let state: ThreadCollaboration = {}; + for (let index = 0; index < THREAD_MAX_PROMISES; index += 1) { + state = applyCollaborationUpdate(state, promise(`p${index}`, T1), T0); + } + expect(collaborationUpdateError(state, promise("extra", T1))).toMatch(/at most/); + state = applyCollaborationUpdate(state, { type: "keep_promise", promiseId: "p0" }, T0); + state = applyCollaborationUpdate(state, promise("extra", T1), T0); + expect(state.promises).toHaveLength(THREAD_MAX_PROMISES); + expect(state.promises!.some((entry) => entry.id === "p0")).toBe(false); + expect(collaborationUpdateError(state, { type: "keep_promise", promiseId: "gone" })).toMatch( + /No promise/, + ); + }); +}); + +describe("handoff", () => { + it("sets and clears the handoff", () => { + const set = applyCollaborationUpdate( + undefined, + { + type: "set_handoff", + handoff: { from: "CoS", to: "Growth", what: "Draft the outbound list" }, + }, + T0, + ); + expect(set.handoff?.to).toBe("Growth"); + expect(applyCollaborationUpdate(set, { type: "set_handoff", handoff: null }, T0)).toEqual({}); + }); +}); + +describe("stored collaboration", () => { + it("reads a value a later rule rejects as no collaboration", () => { + expect(decodeStored({ room: { topic: 3 } })).toEqual({}); + }); +}); + +describe("decision cards", () => { + const ask = { + founder: "kameron", + kind: "decision", + question: "Who owns outbound?", + options: [ + { label: "Growth", effect: "Growth runs the list weekly." }, + { label: "Sales", effect: "Sales keeps it." }, + ], + }; + + it("accepts options with a recommendation that names one of them", () => { + expect(isDecisionAsk({ ...ask, recommendation: "Growth" })).toBe(true); + expect(isDecisionAsk({ ...ask, recommendation: "Lead" })).toBe(false); + expect(isDecisionAsk({ ...ask, options: undefined, recommendation: "Growth" })).toBe(false); + expect(isDecisionAsk({ ...ask, options: [ask.options[0]] })).toBe(false); + }); + + it("keeps each option label on one line", () => { + const options = [{ label: "Growth\nand Sales", effect: "Both run it." }, ask.options[1]]; + expect(isDecisionAsk({ ...ask, options })).toBe(false); + }); + + it("still accepts a plain question", () => { + expect(isDecisionAsk({ founder: "kameron", kind: "decision", question: "Ship it?" })).toBe( + true, + ); + }); +}); diff --git a/packages/contracts/src/threadCollaboration.ts b/packages/contracts/src/threadCollaboration.ts new file mode 100644 index 0000000000000..6faf7635193f2 --- /dev/null +++ b/packages/contracts/src/threadCollaboration.ts @@ -0,0 +1,270 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { IsoDateTime, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** + * Collaboration state a thread carries: a room it facilitates, promises it made, and the handoff + * that started it. All of it rides the thread's metadata update and is small enough for the shell. + */ + +export const ROOM_MAX_MEMBERS = 8; +export const THREAD_MAX_PROMISES = 10; +export const ROOM_MAX_DECISIONS = 20; + +const singleLine = (max: number) => + TrimmedNonEmptyString.check( + Schema.isMaxLength(max), + Schema.makeFilter((value) => + /[\p{Cc}]/u.test(value) ? "Must be a single line of text." : true, + ), + ); + +const text = (max: number) => TrimmedNonEmptyString.check(Schema.isMaxLength(max)); + +const DueAt = IsoDateTime.check( + Schema.makeFilter((value) => + Number.isNaN(Date.parse(value)) + ? "Must be an ISO date-time, such as 2026-11-25T22:00:00Z." + : true, + ), +); + +export const LinearIssueKey = singleLine(32) + .check( + Schema.makeFilter((value) => + /^[A-Z][A-Z0-9]*-\d+$/.test(value) ? true : "Must be a Linear issue key, such as ENG-123.", + ), + ) + .annotate({ + description: "Linear issue key the room records its decisions on, such as ENG-123.", + }); + +/** What opening (or re-opening to change members of) a room writes. */ +export const ThreadRoomOpen = Schema.Struct({ + topic: singleLine(200), + members: Schema.Array(ThreadId).check( + Schema.isMinLength(2), + Schema.isMaxLength(ROOM_MAX_MEMBERS), + Schema.makeFilter((members) => + new Set(members).size === members.length ? true : "Each member is listed once.", + ), + ), + linearIssue: Schema.optionalKey(LinearIssueKey), +}); +export type ThreadRoomOpen = typeof ThreadRoomOpen.Type; + +export const RoomDecision = Schema.Struct({ + text: text(1000), + owner: Schema.optionalKey(singleLine(80)), + dueAt: Schema.optionalKey(DueAt), +}); +export type RoomDecision = typeof RoomDecision.Type; + +/** What the facilitator writes when the room closes. */ +export const ThreadRoomClose = Schema.Struct({ + summary: text(4000), + decisions: Schema.Array(RoomDecision).check(Schema.isMaxLength(ROOM_MAX_DECISIONS)), +}); +export type ThreadRoomClose = typeof ThreadRoomClose.Type; + +export const ThreadRoom = Schema.Struct({ + ...ThreadRoomOpen.fields, + openedAt: IsoDateTime, + closedAt: Schema.optionalKey(IsoDateTime), + close: Schema.optionalKey(ThreadRoomClose), +}); +export type ThreadRoom = typeof ThreadRoom.Type; + +export const ThreadPromise = Schema.Struct({ + /** Stable key the thread picks, so it can update or keep the promise later. */ + id: singleLine(64), + text: singleLine(300), + dueAt: DueAt, + owner: Schema.optionalKey(singleLine(80)), +}); +export type ThreadPromise = typeof ThreadPromise.Type; + +export const StoredThreadPromise = Schema.Struct({ + ...ThreadPromise.fields, + keptAt: Schema.optionalKey(IsoDateTime), +}); +export type StoredThreadPromise = typeof StoredThreadPromise.Type; + +export const ThreadHandoff = Schema.Struct({ + from: singleLine(80), + to: singleLine(80), + what: text(1000), + dueAt: Schema.optionalKey(DueAt), +}); +export type ThreadHandoff = typeof ThreadHandoff.Type; + +export const ThreadCollaboration = Schema.Struct({ + room: Schema.optionalKey(ThreadRoom), + promises: Schema.optionalKey(Schema.Array(StoredThreadPromise)), + handoff: Schema.optionalKey(ThreadHandoff), +}); +export type ThreadCollaboration = typeof ThreadCollaboration.Type; + +/** Read back from storage or a peer. A value a later rule rejects reads as no collaboration. */ +export const StoredThreadCollaboration = ThreadCollaboration.pipe( + Schema.catchDecoding(() => Effect.succeedSome({})), +); + +export const ThreadCollaborationUpdate = Schema.Union([ + Schema.Struct({ type: Schema.Literal("open_room"), room: ThreadRoomOpen }), + Schema.Struct({ type: Schema.Literal("close_room"), close: ThreadRoomClose }), + Schema.Struct({ type: Schema.Literal("set_promise"), promise: ThreadPromise }), + Schema.Struct({ type: Schema.Literal("keep_promise"), promiseId: singleLine(64) }), + Schema.Struct({ type: Schema.Literal("set_handoff"), handoff: Schema.NullOr(ThreadHandoff) }), +]); +export type ThreadCollaborationUpdate = typeof ThreadCollaborationUpdate.Type; + +export function isRoomOpen(room: ThreadRoom | undefined): room is ThreadRoom { + return room !== undefined && room.closedAt === undefined; +} + +/** Why an update cannot apply to the current state, or null when it can. */ +export function collaborationUpdateError( + current: ThreadCollaboration | undefined, + update: ThreadCollaborationUpdate, +): string | null { + switch (update.type) { + case "close_room": + return isRoomOpen(current?.room) ? null : "This thread has no open room to close."; + case "keep_promise": + return current?.promises?.some((promise) => promise.id === update.promiseId) + ? null + : `No promise with id '${update.promiseId}' on this thread.`; + case "set_promise": { + const open = (current?.promises ?? []).filter( + (promise) => promise.keptAt === undefined && promise.id !== update.promise.id, + ); + return open.length >= THREAD_MAX_PROMISES + ? `A thread holds at most ${THREAD_MAX_PROMISES} open promises. Keep one first.` + : null; + } + case "open_room": + // A closed room keeps its close record; only an open room takes new topic or members. + return current?.room !== undefined && !isRoomOpen(current.room) + ? "This thread's room is closed and keeps its record. Open a new room on another thread." + : null; + case "set_handoff": + return null; + } +} + +/** + * The state after an update. Updates that `collaborationUpdateError` rejects leave the state as it + * was, so a replayed command can never fail the decider. + */ +export function applyCollaborationUpdate( + current: ThreadCollaboration | undefined, + update: ThreadCollaborationUpdate, + nowIso: string, +): ThreadCollaboration { + const base = current ?? {}; + if (collaborationUpdateError(base, update) !== null) return base; + switch (update.type) { + case "open_room": { + // Re-opening an open room changes its topic or members without restarting it. + const openedAt = isRoomOpen(base.room) ? base.room.openedAt : nowIso; + return { ...base, room: { ...update.room, openedAt } }; + } + case "close_room": + return { ...base, room: { ...base.room!, closedAt: nowIso, close: update.close } }; + case "set_promise": { + const others = (base.promises ?? []).filter((promise) => promise.id !== update.promise.id); + // Kept promises make room for new ones, earliest due first. + const kept = others.filter((promise) => promise.keptAt !== undefined); + const open = others.filter((promise) => promise.keptAt === undefined); + const keptRoom = Math.max(0, THREAD_MAX_PROMISES - open.length - 1); + return { + ...base, + promises: [...open, ...kept.slice(kept.length - keptRoom), update.promise].sort(byDueAt), + }; + } + case "keep_promise": + return { + ...base, + promises: base.promises!.map((promise) => + promise.id === update.promiseId && promise.keptAt === undefined + ? { ...promise, keptAt: nowIso } + : promise, + ), + }; + case "set_handoff": { + if (update.handoff !== null) return { ...base, handoff: update.handoff }; + const { handoff: _cleared, ...rest } = base; + return rest; + } + } +} + +function byDueAt(left: { readonly dueAt: string }, right: { readonly dueAt: string }): number { + return Date.parse(left.dueAt) - Date.parse(right.dueAt); +} + +export type PromiseState = "open" | "overdue" | "kept"; + +export function promiseState(promise: StoredThreadPromise, nowMs: number): PromiseState { + if (promise.keptAt !== undefined) return "kept"; + return Date.parse(promise.dueAt) <= nowMs ? "overdue" : "open"; +} + +/** Open promises, soonest first. */ +export function openPromises( + collaboration: ThreadCollaboration | undefined, +): ReadonlyArray { + return (collaboration?.promises ?? []) + .filter((promise) => promise.keptAt === undefined) + .sort(byDueAt); +} + +/** + * The turn note a room's facilitator reads. The facilitator does the fan-out itself with + * t3_thread_send / t3_thread_wait / t3_thread_read, so the server never runs member turns. + */ +export function roomFacilitatorNote(room: ThreadRoom | undefined): string { + if (room === undefined || !isRoomOpen(room)) return ""; + return [ + `You facilitate the room "${room.topic}" with members ${room.members.join(", ")}.`, + "For each founder message: t3_thread_send it to every member (say it comes from this room), t3_thread_wait each, t3_thread_read its reply, then answer here with each member's view attributed by name and a short synthesis. Keep turns fair and ask the founder when members disagree.", + `When the founder closes the room: t3_thread_update action:'close_room' with the summary and decisions, then post the returned linearComment${room.linearIssue === undefined ? "" : ` on ${room.linearIssue}`} and save the returned memoryEntry with your Linear and memory tools.`, + ].join("\n"); +} + +function decisionLine(decision: RoomDecision): string { + const owner = decision.owner === undefined ? "" : ` (owner: ${decision.owner}`; + const due = + decision.dueAt === undefined ? "" : `${owner === "" ? " (" : ", "}due ${decision.dueAt}`; + return `- ${decision.text}${owner}${due}${owner === "" && due === "" ? "" : ")"}`; +} + +/** What a closed room writes out: a Linear comment and a memory entry, as plain text. */ +export function roomCloseRecord(room: ThreadRoom): { + readonly linearIssue: string | null; + readonly linearComment: string; + readonly memoryEntry: string; +} | null { + if (room.close === undefined || room.closedAt === undefined) return null; + const decisions = + room.close.decisions.length === 0 + ? ["- No decisions."] + : room.close.decisions.map(decisionLine); + const linearComment = [ + `## Room closed: ${room.topic}`, + "", + room.close.summary, + "", + "### Decisions", + ...decisions, + "", + `Members: ${room.members.join(", ")}. Opened ${room.openedAt}, closed ${room.closedAt}.`, + ].join("\n"); + const memoryEntry = [ + `Room decision record: ${room.topic} (closed ${room.closedAt}${room.linearIssue === undefined ? "" : `, ${room.linearIssue}`}).`, + ...decisions, + ].join("\n"); + return { linearIssue: room.linearIssue ?? null, linearComment, memoryEntry }; +} diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index 9c29b4080a47b..ccc0d630d882b 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -58,10 +58,37 @@ const jointSignOffEntries = Schema.Array(FounderSignOff).check( }), ); +/** One choice on a decision card, with what picking it does. */ +export const ThreadDecisionOption = Schema.Struct({ + // A label is a button and the drafted reply line, so it stays on one line. + label: TrimmedNonEmptyString.check( + Schema.isMaxLength(120), + Schema.makeFilter((value) => + /[\p{Cc}]/u.test(value) ? "Must be a single line of text." : true, + ), + ), + effect: TrimmedNonEmptyString.check(Schema.isMaxLength(500)), +}); +export type ThreadDecisionOption = typeof ThreadDecisionOption.Type; + +const decisionOptions = Schema.Array(ThreadDecisionOption).check( + Schema.isMinLength(2), + Schema.isMaxLength(5), + Schema.makeFilter((options) => + new Set(options.map((option) => option.label)).size === options.length + ? true + : "Each option label is used once.", + ), +); + export const ThreadDecisionAsk = Schema.Struct({ founder: Founder, kind: Schema.Literals(["decision", "review", "approval"]), question: TrimmedNonEmptyString.check(Schema.isMaxLength(2000)), + /** The choices a decision card shows. The founder picks one by replying on the thread. */ + options: Schema.optional(decisionOptions), + /** The label of the option the asker recommends. Requires options. */ + recommendation: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(120))), /** * Set only when both founders must answer. Absent, the ask is the one * `founder`'s alone. A stored ask from before this field decodes without it. @@ -71,7 +98,14 @@ export const ThreadDecisionAsk = Schema.Struct({ description: "Both founders' answers, when the call needs each of them.", }), ), -}); +}).check( + Schema.makeFilter((ask) => + ask.recommendation === undefined || + ask.options?.some((option) => option.label === ask.recommendation) === true + ? true + : "recommendation must be the label of one of the options.", + ), +); export type ThreadDecisionAsk = typeof ThreadDecisionAsk.Type; export const ThreadDecisionRequest = Schema.Struct({ ...ThreadDecisionAsk.fields, diff --git a/packages/contracts/src/threadMetadataMcp.ts b/packages/contracts/src/threadMetadataMcp.ts index e0b5058e520f4..f93a65a455dbb 100644 --- a/packages/contracts/src/threadMetadataMcp.ts +++ b/packages/contracts/src/threadMetadataMcp.ts @@ -12,6 +12,7 @@ import { ThreadLinkedPullRequest } from "./threadPullRequest.ts"; import { StoredThreadStanding, ThreadStanding } from "./threadStanding.ts"; import { DelegationNudgeUpdate, StoredThreadDelegationNudge } from "./delegationNudge.ts"; import { ThreadTitleRegeneration } from "./threadTitle.ts"; +import { ThreadCollaboration, ThreadCollaborationUpdate } from "./threadCollaboration.ts"; export function hasOnlyPairedSurrogates(value: string): boolean { for (let index = 0; index < value.length; index += 1) { @@ -51,6 +52,7 @@ export const ThreadMetadataMcpAction = Schema.Literals([ "resolve_decision", "set_standing", "set_delegation_nudge", + "collaborate", ]); export type ThreadMetadataMcpAction = typeof ThreadMetadataMcpAction.Type; @@ -72,6 +74,13 @@ export const ThreadMetadataMcpUpdateInput = Schema.Struct({ "Required only when action is set_delegation_nudge: {enabled, thresholds?}. When on, the thread is reminded to delegate after that many of its own tool calls in one request (default [5, 10]). A thread cannot change its own setting.", }), ), + // The schema shows each update's fields; its description says only what they cannot. + collaboration: Schema.optional( + ThreadCollaborationUpdate.annotate({ + description: + "Only with collaborate. Room members are thread ids; open_room again to change them.", + }), + ), clientRequestId: Schema.optional(ThreadMetadataClientRequestId), }).check( Schema.makeFilter((input) => @@ -79,9 +88,10 @@ export const ThreadMetadataMcpUpdateInput = Schema.Struct({ (input.action === "route") === (input.inboxRouting !== undefined) && (input.action === "request_decision") === (input.decision !== undefined) && (input.action === "set_standing") === (input.standing !== undefined) && - (input.action === "set_delegation_nudge") === (input.delegationNudge !== undefined) + (input.action === "set_delegation_nudge") === (input.delegationNudge !== undefined) && + (input.action === "collaborate") === (input.collaboration !== undefined) ? true - : "rename requires title; route requires inboxRouting; request_decision requires decision; set_standing requires standing; set_delegation_nudge requires delegationNudge; other actions reject those fields.", + : "rename requires title; route requires inboxRouting; request_decision requires decision; set_standing requires standing; set_delegation_nudge requires delegationNudge; collaborate requires collaboration; other actions reject those fields.", ), ); export type ThreadMetadataMcpUpdateInput = typeof ThreadMetadataMcpUpdateInput.Type; @@ -97,6 +107,15 @@ export const ThreadMetadataMcpUpdateResult = Schema.Struct({ inbox: Schema.optionalKey(ThreadInbox), standing: Schema.optionalKey(StoredThreadStanding), delegationNudge: Schema.optionalKey(StoredThreadDelegationNudge), + collaboration: Schema.optionalKey(ThreadCollaboration), + /** Set when close_room lands: the text to post on Linear and save to memory. */ + roomRecord: Schema.optionalKey( + Schema.Struct({ + linearIssue: Schema.NullOr(Schema.String), + linearComment: Schema.String, + memoryEntry: Schema.String, + }), + ), 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 b14a23489b336..c1f2fb3bb90de 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -65,8 +65,13 @@ export function makeSubagentChildThread(input: { readonly createdBy: OrchestrationV2Actor; readonly creationSource: OrchestrationV2CreationSource; }): OrchestrationV2AppThread { - // The remote parent delegated the parent thread, not its subagents. - const { delegatedFrom: _delegatedFrom, ...inherited } = input.parentThread; + // The remote parent delegated the parent thread, not its subagents. A room, its promises and + // handoff belong to the parent too; a copy would facilitate the room a second time. + const { + delegatedFrom: _delegatedFrom, + collaboration: _collaboration, + ...inherited + } = input.parentThread; return { ...inherited, inbox: makeThreadInbox({