From a346cab73c9907e635dcfb2c185599ba03a75336 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:07:25 +0000 Subject: [PATCH 1/3] feat(threads): quiet shared bots until a founder is asked A shared standing bot shows a faint dot for co-founder FYI chatter. The bright badge appears only for a decision request or an @Kameron / @Jeff mention. A joint sign-off lists both founders, and each reply signs only the founder who wrote it. /note leaves a side note on a shared thread without starting a turn. Typing on that thread is shown to the other founder and expires on its own. Model: grok-4.7 Task: WS1b shared bot attention Agent: grok Harness: grok --- apps/server/src/auth/RpcAuthorization.ts | 2 + .../src/observability/RpcInstrumentation.ts | 2 + .../src/orchestration-v2/HumanNote.test.ts | 186 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 74 +++++++ .../src/orchestration-v2/ProjectionStore.ts | 73 ++++++- .../src/orchestration-v2/TypingPresence.ts | 82 ++++++++ apps/server/src/ws.ts | 22 +++ apps/web/src/components/chat/ChatComposer.tsx | 12 +- .../chat/TimelineUserMessageRow.tsx | 5 + .../chat/composerSlashCommandSearch.ts | 3 +- .../components/chat/useComposerMenuItems.ts | 13 ++ .../src/components/chat/useComposerSend.ts | 96 ++++++++- .../components/chat/useSharedThreadTyping.ts | 72 +++++++ .../components/sidebar/SidebarBotsGroup.tsx | 143 +++++++++++++- apps/web/src/composer-logic.ts | 2 +- apps/web/src/session-logic.ts | 1 + apps/web/src/types.ts | 2 + .../client-runtime/src/operations/commands.ts | 4 + packages/client-runtime/src/rpc/client.ts | 1 + .../client-runtime/src/state/orchestration.ts | 14 ++ packages/contracts/src/botAttention.test.ts | 137 +++++++++++++ packages/contracts/src/botAttention.ts | 104 ++++++++++ packages/contracts/src/index.ts | 2 + packages/contracts/src/orchestrationV2.ts | 36 ++++ packages/contracts/src/rpc.ts | 15 ++ packages/contracts/src/threadInbox.test.ts | 96 +++++++++ packages/contracts/src/threadInbox.ts | 117 ++++++++++- packages/contracts/src/typingPresence.test.ts | 38 ++++ packages/contracts/src/typingPresence.ts | 77 ++++++++ packages/shared/src/composerTrigger.test.ts | 15 ++ packages/shared/src/composerTrigger.ts | 6 + 31 files changed, 1436 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/orchestration-v2/HumanNote.test.ts create mode 100644 apps/server/src/orchestration-v2/TypingPresence.ts create mode 100644 apps/web/src/components/chat/useSharedThreadTyping.ts create mode 100644 packages/contracts/src/botAttention.test.ts create mode 100644 packages/contracts/src/botAttention.ts create mode 100644 packages/contracts/src/typingPresence.test.ts create mode 100644 packages/contracts/src/typingPresence.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 3d507828afe78..fdb59a56604ab 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -63,6 +63,8 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.reportTyping]: AuthOrchestrationOperateScope, + [ORCHESTRATION_V2_WS_METHODS.subscribeTyping]: AuthOrchestrationReadScope, [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope, [WS_METHODS.serverProbe]: AuthOrchestrationReadScope, [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 30d3c2f575f26..748bad3393a83 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -36,6 +36,8 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: "orchestrationV2", + [ORCHESTRATION_V2_WS_METHODS.reportTyping]: "orchestrationV2", + [ORCHESTRATION_V2_WS_METHODS.subscribeTyping]: "orchestrationV2", [WS_METHODS.projectsMutate]: "orchestration", [WS_METHODS.serverProbe]: "server", [WS_METHODS.serverGetConfig]: "server", diff --git a/apps/server/src/orchestration-v2/HumanNote.test.ts b/apps/server/src/orchestration-v2/HumanNote.test.ts new file mode 100644 index 0000000000000..68a69415acd39 --- /dev/null +++ b/apps/server/src/orchestration-v2/HumanNote.test.ts @@ -0,0 +1,186 @@ +import { assert, it } from "@effect/vitest"; +import { + AuthSessionId, + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("A note must not start a provider session"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "human-note" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +const sentBy = (founder: "kameron" | "jeff") => ({ + sessionId: AuthSessionId.make(`session:${founder}`), + device: "laptop", + deviceType: "desktop" as const, + founder, +}); + +const createThread = (threadId: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:human-note"), + title: "Before", + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + }); + +it.layer(layerTest)("human notes", (it) => { + it.effect("records a shared note, signs only that founder, and starts no run", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:human-note"); + yield* createThread(threadId); + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("settle:human-note"), + threadId, + }); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("share:human-note"), + threadId, + inboxRouting: { + owner: null, + assignee: null, + audience: "shared", + attentionKind: "FYI", + reason: "decision", + }, + decisionRequest: { + founder: "kameron", + kind: "decision", + question: "Ship it?", + signOff: [ + { founder: "kameron", signed: false }, + { founder: "jeff", signed: false }, + ], + }, + }); + yield* TestClock.adjust("20 millis"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("note:kameron"), + threadId, + messageId: MessageId.make("message:note:kameron"), + text: " please look @Jeff ", + attachments: [], + humanNote: true, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + sentBy: sentBy("kameron"), + }); + const projection = yield* projections.getThreadProjection(threadId); + assert.equal(projection.runs.length, 0); + assert.equal(projection.messages.length, 1); + assert.equal(projection.messages[0]?.text, "please look @Jeff"); + assert.equal(projection.messages[0]?.humanNote, true); + assert.equal(projection.messages[0]?.runId, null); + const note = projection.turnItems.find((item) => item.type === "user_message"); + assert.equal(note?.type === "user_message" ? note.humanNote : undefined, true); + assert.equal(note?.status, "completed"); + assert.deepEqual(yield* projections.getTurnStartHistory(threadId), []); + const shell = yield* projections.getThreadShell(threadId); + assert.equal(shell?.settledOverride, null); + assert.deepEqual(shell?.attentionMentions, ["jeff"]); + assert.deepEqual(shell?.inbox?.decisionRequest?.signOff, [ + { founder: "kameron", signed: true }, + { founder: "jeff", signed: false }, + ]); + + yield* TestClock.adjust("20 millis"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("note:jeff"), + threadId, + messageId: MessageId.make("message:note:jeff"), + text: "signed", + attachments: [], + humanNote: true, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + sentBy: sentBy("jeff"), + }); + const closed = yield* projections.getThreadShell(threadId); + assert.equal(closed?.inbox?.decisionRequest, undefined); + assert.equal((yield* projections.getThreadProjection(threadId)).runs.length, 0); + assert.deepEqual(yield* projections.getTurnStartHistory(threadId), []); + }), + ); + + it.effect("rejects a note off a shared thread without waking it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:human-note-private"); + yield* createThread(threadId); + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("settle:private"), + threadId, + }); + const refused = yield* orchestrator + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make("note:private"), + threadId, + messageId: MessageId.make("message:note:private"), + text: "just us", + attachments: [], + humanNote: true, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + sentBy: sentBy("kameron"), + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + const shell = yield* projections.getThreadShell(threadId); + assert.equal(shell?.title, "Before"); + assert.equal(shell?.settledOverride, "settled"); + assert.equal((yield* projections.getThreadProjection(threadId)).messages.length, 0); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ad3cce997779b..bc97af84a995e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6847,6 +6847,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } : undefined, ); + if (command.humanNote === true) { + const noteText = command.text.trim(); + if ( + command.createdBy !== "user" || + projection.thread.inbox?.audience !== "shared" || + noteText.length === 0 || + command.attachments.length > 0 + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "A note is a text message on a shared thread, and it does not wake the bot.", + }); + } + } if (command.steerFollowUpOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); if ( @@ -7107,6 +7122,65 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); projection = applyToProjection(projection, event); } + if (command.humanNote === true) { + const now = yield* DateTime.now; + const text = command.text.trim(); + const message: OrchestrationV2ConversationMessage = { + createdBy: command.createdBy, + creationSource: command.creationSource, + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), + id: command.messageId, + threadId: command.threadId, + runId: null, + nodeId: null, + role: "user", + text, + attachments: [], + streaming: false, + humanNote: true, + createdAt: now, + updatedAt: now, + }; + const noteItem: OrchestrationV2TurnItem = { + createdBy: command.createdBy, + creationSource: command.creationSource, + ...(command.sentBy === undefined ? {} : { sentBy: command.sentBy }), + id: idAllocator.derive.userTurnItem({ messageId: command.messageId }), + threadId: command.threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: yield* nextTurnItemOrdinal(projection), + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "user_message", + messageId: command.messageId, + inputIntent: "turn_start", + text, + attachments: [], + humanNote: true, + }; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "message.updated", + threadId: command.threadId, + occurredAt: now, + payload: message, + }); + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + occurredAt: now, + payload: noteItem, + }); + return; + } const userMessages = projection.messages.filter((message) => message.role === "user"); // The recent runs of a compacted thread can hold only a `/compact` while an older prompt // exists. Every prompt's turn item is loaded; without one, every user message is checked. diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 06ff339bac6b5..cb8e0fcdab5c4 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,6 +1,9 @@ import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwareness"; import { applyOrchestrationV2ThreadVisit, + attentionMentionsFromText, + ATTENTION_MENTION_TEXT_LIMIT, + inboxAfterFounderReply, pendingGuestMessageCount, projectThreadInbox, } from "@t3tools/contracts"; @@ -1073,11 +1076,17 @@ export function applyToProjection( ...base, runtimeRequests: upsertById(base.runtimeRequests, event.payload), }; - case "message.updated": + case "message.updated": { + const inbox = inboxAfterFounderReply(base.thread.inbox, event.payload); return { ...base, + thread: + inbox === undefined || inbox === base.thread.inbox + ? base.thread + : { ...base.thread, inbox }, messages: upsertById(base.messages, event.payload), }; + } case "turn-item.updated": return withLocalVisibleTurnItems({ ...base, @@ -1169,6 +1178,7 @@ type ShellThreadRow = { readonly pending_link_request_payload_json: string | null; readonly latest_user_message_at: string | null; readonly latest_user_authored_message_at: string | null; + readonly latest_visible_text: string | null; readonly has_actionable_proposed_plan: number; }; @@ -1744,6 +1754,11 @@ const linkCardStillAsks = ( latestUserAuthoredMessageAt === null || !DateTime.isGreaterThan(latestUserAuthoredMessageAt, item.startedAt ?? item.updatedAt); +const shellAttentionMentions = (text: string | null | undefined) => { + const attentionMentions = attentionMentionsFromText(text); + return attentionMentions === undefined ? {} : { attentionMentions }; +}; + const shellInbox = ( inbox: ThreadInbox | undefined, pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null, @@ -1828,6 +1843,14 @@ export function threadShellFromProjection( } } const latestUserMessage = userMessages[0] ?? null; + const latestVisibleText = + projection.messages + .filter((message) => idleCompactionOf(message) === undefined) + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) || + right.id.localeCompare(left.id), + )[0]?.text ?? null; const pendingBackgroundTasks = derivePendingBackgroundWork({ latestRun, providerThreads: projection.providerThreads, @@ -1897,6 +1920,7 @@ export function threadShellFromProjection( // Thread detail owns message bodies. Keeping them out of shell rows makes // initial hydration and streaming updates independent of transcript size. latestVisibleMessage: null, + ...shellAttentionMentions(latestVisibleText), latestUserMessageAt: latestUserMessage?.updatedAt ?? null, latestUserAuthoredMessageAt, hasActionableProposedPlan: projection.plans.some( @@ -2032,6 +2056,7 @@ type ShellThreadState = { readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null; readonly latestUserMessageAt: DateTime.Utc | null; readonly latestUserAuthoredMessageAt: DateTime.Utc | null; + readonly attentionMentions: OrchestrationV2ThreadShell["attentionMentions"]; readonly hasActionableProposedPlan: boolean; readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"]; readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"]; @@ -2211,6 +2236,9 @@ function shellFromState(input: { pendingRuntimeRequest: input.state.pendingRuntimeRequest, pendingGuestMessageCount: pendingGuestMessageCount(input.state.thread.guestShare), latestVisibleMessage: null, + ...(input.state.attentionMentions === undefined + ? {} + : { attentionMentions: input.state.attentionMentions }), latestUserMessageAt: input.state.latestUserMessageAt, latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt, hasActionableProposedPlan: input.state.hasActionableProposedPlan, @@ -2967,6 +2995,36 @@ export const layer: Layer.Layer = payload_json = excluded.payload_json, search_text = excluded.search_text `; + const founder = event.payload.sentBy?.founder; + if ( + event.payload.role === "user" && + event.payload.createdBy === "user" && + event.payload.idleCompaction === undefined && + (founder === "kameron" || founder === "jeff") + ) { + const threadRows = yield* sql` + SELECT payload_json + FROM orchestration_v2_projection_threads + WHERE thread_id = ${event.payload.threadId} + LIMIT 1 + `; + const threadRow = threadRows[0]; + if (threadRow !== undefined) { + const thread = yield* decodeThreadPayload(threadRow.payload_json); + const inbox = inboxAfterFounderReply(thread.inbox, event.payload); + if (inbox !== undefined && inbox !== thread.inbox) { + const updatedThread = { ...thread, inbox, updatedAt: event.payload.updatedAt }; + const updatedThreadPayloadJson = yield* encodeThreadPayload(updatedThread); + yield* sql` + UPDATE orchestration_v2_projection_threads + SET + updated_at = ${updatedAt}, + payload_json = ${updatedThreadPayloadJson} + WHERE thread_id = ${event.payload.threadId} + `; + } + } + } break; } case "plan.updated": { @@ -5312,6 +5370,10 @@ export const layer: Layer.Layer = WHERE thread_id = ${threadId} AND type IN ('user_message','assistant_message','command_execution','error', 'run_interrupt_result','file_change','proposed_plan') + AND ( + type <> 'user_message' + OR json_extract(payload_json, '$.humanNote') IS NOT 1 + ) AND ${runIds === undefined ? sql`1` : sql`run_id IN ${sql.in(runIds)}`} ORDER BY ordinal ASC, turn_item_id ASC `; @@ -8150,6 +8212,14 @@ export const layer: Layer.Layer = ORDER BY message.updated_at DESC, message.message_id DESC LIMIT 1 ) AS latest_user_authored_message_at, + ( + SELECT substr(json_extract(message.payload_json, '$.text'), 1, ${ATTENTION_MENTION_TEXT_LIMIT}) + FROM orchestration_v2_projection_messages message + WHERE message.thread_id = t.thread_id + AND NOT ${isIdleCompactionMessage("message")} + ORDER BY message.updated_at DESC, message.message_id DESC + LIMIT 1 + ) AS latest_visible_text, EXISTS ( SELECT 1 FROM orchestration_v2_projection_plans plan @@ -8838,6 +8908,7 @@ export const layer: Layer.Layer = ? null : DateTime.makeUnsafe(row.latest_user_message_at), latestUserAuthoredMessageAt, + attentionMentions: attentionMentionsFromText(row.latest_visible_text), hasActionableProposedPlan: row.has_actionable_proposed_plan === 1, pendingBackgroundTasks, providerInstanceHistory: providerInstanceHistoryForShell({ diff --git a/apps/server/src/orchestration-v2/TypingPresence.ts b/apps/server/src/orchestration-v2/TypingPresence.ts new file mode 100644 index 0000000000000..27d2abbbc63c1 --- /dev/null +++ b/apps/server/src/orchestration-v2/TypingPresence.ts @@ -0,0 +1,82 @@ +import { + ThreadId, + TYPING_TTL_MS, + liveFounders, + rosterAfterReport, + type Founder, + type OrchestrationV2TypingSnapshot, + type TypingRoster, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as PubSub from "effect/PubSub"; +import * as Stream from "effect/Stream"; + +/** + * Who is typing, for every socket. The map lives for the server, not for one connection, so + * Kameron and Jeff see each other. Nothing here is stored. + */ +export interface TypingPresence { + readonly report: (input: { + readonly threadId: ThreadId; + readonly sessionId: string; + readonly founder: Founder | null; + readonly typing: boolean; + }) => Effect.Effect; + readonly subscribe: Stream.Stream; +} + +const emptyRoster: TypingRoster = new Map(); + +export const makeTypingPresence: Effect.Effect = Effect.gen(function* () { + const pubsub = yield* PubSub.unbounded(); + const threads = new Map(); + + const publish = (threadId: ThreadId, now: number) => + PubSub.publish(pubsub, { + threadId, + founders: liveFounders(threads.get(threadId) ?? emptyRoster, now), + }); + + const report: TypingPresence["report"] = Effect.fn("TypingPresence.report")(function* (input) { + const now = yield* Clock.currentTimeMillis; + const current = threads.get(input.threadId) ?? emptyRoster; + const next = rosterAfterReport(current, input.sessionId, input.founder, input.typing, now); + if (next === current) return; + if (next.size === 0) threads.delete(input.threadId); + else threads.set(input.threadId, next); + yield* publish(input.threadId, now); + if (!input.typing || input.founder === null) return; + const at = next.get(input.sessionId)?.at; + if (at === undefined) return; + yield* Effect.forkDetach( + Effect.gen(function* () { + yield* Effect.sleep(TYPING_TTL_MS); + const roster = threads.get(input.threadId); + const beat = roster?.get(input.sessionId); + if (roster === undefined || beat?.at !== at) return; + const clearedAt = yield* Clock.currentTimeMillis; + const cleared = rosterAfterReport(roster, input.sessionId, beat.founder, false, clearedAt); + if (cleared.size === 0) threads.delete(input.threadId); + else threads.set(input.threadId, cleared); + yield* publish(input.threadId, clearedAt); + }), + ); + }); + + // Subscribe first so a beat between the snapshot and the live stream is a repeat, not a miss. + const subscribe = Stream.unwrap( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(pubsub); + const now = yield* Clock.currentTimeMillis; + const snapshot: OrchestrationV2TypingSnapshot[] = []; + for (const [threadId, roster] of threads) { + const founders = liveFounders(roster, now); + if (founders.length > 0) snapshot.push({ threadId: ThreadId.make(threadId), founders }); + } + return Stream.concat(Stream.fromIterable(snapshot), Stream.fromSubscription(subscription)); + }), + ); + + return { report, subscribe }; +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index f40c62181701d..9e199ac0aa2e1 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -6,6 +6,13 @@ import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; +import { makeTypingPresence, type TypingPresence } from "./orchestration-v2/TypingPresence.ts"; + +/** A socket built without the server-lifetime hub, as the websocket tests do. */ +const idleTypingPresence: TypingPresence = { + report: () => Effect.void, + subscribe: Stream.empty, +}; import * as PeerLinkRequests from "./peer/PeerLinkRequests.ts"; import * as PeerForwarding from "./peer/PeerForwarding.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; @@ -1432,6 +1439,7 @@ export const layerWsRpc = ( serverBrowser: ServerBrowser.ServerBrowser["Service"], reportProfiles: ServerBrowser.ProfileReporter, settingsClient: { readonly secretReferences: boolean }, + typingPresence: TypingPresence = idleTypingPresence, ) => Layer.effectContext( Effect.gen(function* () { @@ -2403,6 +2411,18 @@ export const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), + [ORCHESTRATION_V2_WS_METHODS.reportTyping]: (input) => + serverAuth.messageSenderOf(currentSessionId).pipe( + Effect.flatMap((sentBy) => + typingPresence.report({ + threadId: input.threadId, + sessionId: currentSessionId, + founder: sentBy.founder, + typing: input.typing, + }), + ), + ), + [ORCHESTRATION_V2_WS_METHODS.subscribeTyping]: () => typingPresence.subscribe, [WS_METHODS.scheduledTasksSubscribe]: (_input) => scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)), [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), @@ -3694,6 +3714,7 @@ export const layer = Layer.unwrap( const peerForwarding = yield* PeerForwarding.PeerForwarding; const peerLinkRequests = yield* PeerLinkRequests.PeerLinkRequests; const sql = yield* SqlClient.SqlClient; + const typingPresence = yield* makeTypingPresence; return HttpRouter.add( "GET", "/ws", @@ -3768,6 +3789,7 @@ export const layer = Layer.unwrap( serverBrowser, reportProfiles, readSettingsClient(url.value), + typingPresence, ).pipe( Layer.provideMerge(RpcSerialization.layerJson), // Handler-context reporters see only request defects, not server-wide defects. diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 56c3d172c0b89..9bd54f6e7ffa7 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -285,6 +285,7 @@ import { import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { usePromptSuggestion } from "./usePromptSuggestion"; +import { useSharedThreadTyping } from "./useSharedThreadTyping"; import { useFreshSessionArmed } from "./freshSessionArms"; function consumePasteAsTextShortcut(deadline: { current: number }): boolean { @@ -1133,6 +1134,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) threadPullRequests, sideChatAvailable: props.sideChatAvailable === true, sideChatDisabledReason: props.sideChatDisabledReason ?? null, + noteAvailable: activeThread?.source.inbox?.audience === "shared", freshSessionAvailable: props.onFreshSession !== undefined, compactSlashCommandAvailable, selectedProvider, @@ -1933,8 +1935,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } return; } - if (item.command === "side" || item.command === "btw") { - if (props.sideChatDisabledReason) return; + if (item.command === "side" || item.command === "btw" || item.command === "note") { + if (item.command !== "note" && props.sideChatDisabledReason) return; const applied = applyPromptReplacement( trigger.rangeStart, trigger.rangeEnd, @@ -2307,6 +2309,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeThread, activeThreadRuns, ); + const typingStatus = useSharedThreadTyping(environmentId, activeThread, prompt); // After /clear the next message starts a fresh session that cannot see what the suggestion refers to. const freshSessionArmed = useFreshSessionArmed(scopedThreadKey(routeThreadRef)); // Offered only where the default placeholder would show, so it never hides a pending question. @@ -3540,6 +3543,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComposerCollapsedMobile && "hidden", )} > + {typingStatus ? ( +

+ {typingStatus} +

+ ) : null} {isStashMenuOpen && !composerMenuOpen && ( ) : null} + {row.message.humanNote ? ( +

+ Note +

+ ) : null} {showSender ? (
diff --git a/apps/web/src/components/chat/composerSlashCommandSearch.ts b/apps/web/src/components/chat/composerSlashCommandSearch.ts index ba1aacb83de31..9c0ed7ed38ca9 100644 --- a/apps/web/src/components/chat/composerSlashCommandSearch.ts +++ b/apps/web/src/components/chat/composerSlashCommandSearch.ts @@ -12,7 +12,7 @@ type SlashSearchItem = Extract< { type: "slash-command" | "provider-slash-command" | "skill" } >; -/** Provider commands, `/side`, `/btw` and `/clear` work only at the message start. */ +/** Provider commands, `/side`, `/btw`, `/note` and `/clear` work only at the message start. */ export function slashCommandItemsForPromptPosition( items: ReadonlyArray, isAtPromptStart: boolean, @@ -26,6 +26,7 @@ export function slashCommandItemsForPromptPosition( (item.type === "slash-command" && item.command !== "side" && item.command !== "btw" && + item.command !== "note" && item.command !== "clear"), ); } diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts index cea8f649cc1eb..1b6e520443ba5 100644 --- a/apps/web/src/components/chat/useComposerMenuItems.ts +++ b/apps/web/src/components/chat/useComposerMenuItems.ts @@ -73,6 +73,7 @@ export function useComposerMenuItems({ threadPullRequests, sideChatAvailable, sideChatDisabledReason, + noteAvailable, freshSessionAvailable, compactSlashCommandAvailable, selectedProvider, @@ -93,6 +94,7 @@ export function useComposerMenuItems({ readonly threadPullRequests: ReadonlyArray | undefined; readonly sideChatAvailable: boolean; readonly sideChatDisabledReason: string | null; + readonly noteAvailable: boolean; readonly freshSessionAvailable: boolean; readonly compactSlashCommandAvailable: boolean; readonly selectedProvider: ProviderDriverKind; @@ -265,6 +267,17 @@ export function useComposerMenuItems({ }, ] as const) : []), + ...(noteAvailable + ? ([ + { + id: "slash:note", + type: "slash-command", + command: "note", + label: "/note", + description: "Leave a note for the other founder. It does not wake the bot.", + }, + ] as const) + : []), ...(freshSessionAvailable ? ([ { diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 44c155dd95859..24260c664e8e7 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1,4 +1,8 @@ -import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger"; +import { + isClearComposerCommand, + parseNoteCommand, + parseSideChatCommand, +} from "@t3tools/shared/composerTrigger"; import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms"; import { mergeDirectPreviewAnnotation, @@ -431,13 +435,14 @@ export function useComposerSend(input: ComposerSendInput) { sendCtx && !directAnnotation && !queuedRunEdit.isEditing ? parseSideChatCommand(promptAtSend) : null; + const noteCommand = !directAnnotation ? parseNoteCommand(promptAtSend) : null; const answeringQuestion = Boolean(activePendingUserInput) && sendCtx?.answeringPendingUserInput !== false; const startsSideChat = onSideChat !== undefined && sideChatCommand !== null && sideChatDisabledReason === null; // An answer responds to the open request rather than starting a turn, so the new-message // guards below (loading, busy, provider) must not swallow it. - if (answeringQuestion && !startsSideChat && !directAnnotation) { + if (answeringQuestion && !startsSideChat && noteCommand === null && !directAnnotation) { if (readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) && activeThread) { onAdvanceActivePendingUserInput(); } @@ -552,6 +557,93 @@ export function useComposerSend(input: ComposerSendInput) { } return; } + if (noteCommand) { + if (queuedRunEdit.isEditing) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Queued message not updated", + description: "A queued message can't be a note. Remove /note to save it.", + }), + ); + return; + } + if (activeThread.source.inbox?.audience !== "shared") { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Note not sent", + description: "A note is for a thread you share with the other founder.", + }), + ); + return; + } + if (noteCommand.prompt.length === 0) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Note not sent", + description: "Write the note after /note.", + }), + ); + return; + } + if ( + !sendCtx || + sendCtx.images.length > 0 || + sendCtx.files.length > 0 || + filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 || + sendCtx.previewAnnotations.length > 0 || + sendCtx.reviewComments.length > 0 || + sendCtx.threadContexts.length > 0 || + sendCtx.environmentContexts.length > 0 || + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo + ) { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Notes take text only", + description: "Remove the attachments and context, then send it again.", + }), + ); + return; + } + const noted = await startThreadTurn({ + environmentId, + input: { + threadId: activeThread.id, + message: { + messageId: newMessageId(), + role: "user", + text: noteCommand.prompt, + attachments: [], + humanNote: true, + }, + runtimeMode: activeThread.runtimeMode, + interactionMode: activeThread.interactionMode, + dispatchMode: "start", + }, + }); + if (noted._tag === "Failure") { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Note not saved", + description: "Try again.", + }), + ); + return; + } + if ( + currentRouteThreadKeyRef.current === routeThreadKey && + promptRef.current === promptAtSend + ) { + promptRef.current = ""; + setComposerDraftPrompt(composerDraftTarget, ""); + composerRef.current?.resetCursorState(); + } + return; + } if (answeringQuestion) { if (directAnnotation) { notifyDirectAnnotationAttached(); diff --git a/apps/web/src/components/chat/useSharedThreadTyping.ts b/apps/web/src/components/chat/useSharedThreadTyping.ts new file mode 100644 index 0000000000000..1b4fd09aaf1bf --- /dev/null +++ b/apps/web/src/components/chat/useSharedThreadTyping.ts @@ -0,0 +1,72 @@ +import { TYPING_TTL_MS, typingLabel, type EnvironmentId, type Founder } from "@t3tools/contracts"; +import { useEffect, useRef } from "react"; + +import { useClientSettings } from "../../hooks/useSettings"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useEnvironmentQuery } from "../../state/query"; +import { useOrchestrationCommand } from "../../state/use-orchestration-command"; +import type { Thread } from "../../types"; + +const REPORT_DEBOUNCE_MS = 200; +const REPORT_HEARTBEAT_MS = 2_000; + +/** + * On a shared thread, tell the server this founder is typing while the draft changes, and + * read who else is. The local founder is hidden. A draft left alone goes quiet on its own. + */ +export function useSharedThreadTyping( + environmentId: EnvironmentId, + thread: Thread | undefined, + prompt: string, +): string | null { + const self = useClientSettings((state) => state.founderInboxOwner); + const report = useOrchestrationCommand(orchestrationEnvironment.v2.reportTyping, { + reportFailure: false, + }); + const reportRef = useRef(report); + reportRef.current = report; + const shared = thread?.source.inbox?.audience === "shared"; + const threadId = thread?.id; + const { data } = useEnvironmentQuery( + shared && threadId ? orchestrationEnvironment.v2.typing({ environmentId, input: {} }) : null, + ); + const reportingRef = useRef(false); + const lastEditRef = useRef(0); + + useEffect(() => { + if (!shared || threadId === undefined) return; + const text = prompt.trim(); + if (text.length === 0) { + if (!reportingRef.current) return; + reportingRef.current = false; + void reportRef.current({ environmentId, input: { threadId, typing: false } }); + return; + } + lastEditRef.current = Date.now(); + const send = () => { + reportingRef.current = true; + void reportRef.current({ environmentId, input: { threadId, typing: true } }); + }; + const debounce = window.setTimeout(send, REPORT_DEBOUNCE_MS); + const heartbeat = window.setInterval(() => { + if (Date.now() - lastEditRef.current < TYPING_TTL_MS) send(); + }, REPORT_HEARTBEAT_MS); + return () => { + window.clearTimeout(debounce); + window.clearInterval(heartbeat); + }; + }, [environmentId, prompt, shared, threadId]); + + useEffect(() => { + return () => { + if (!reportingRef.current || threadId === undefined) return; + reportingRef.current = false; + void reportRef.current({ environmentId, input: { threadId, typing: false } }); + }; + }, [environmentId, threadId]); + + const founders = ((threadId ? data?.[threadId] : undefined) ?? []).filter( + (founder): founder is Founder => founder !== self, + ); + return typingLabel(founders); +} diff --git a/apps/web/src/components/sidebar/SidebarBotsGroup.tsx b/apps/web/src/components/sidebar/SidebarBotsGroup.tsx index 1b4b1d1189d17..f7b6acadd0087 100644 --- a/apps/web/src/components/sidebar/SidebarBotsGroup.tsx +++ b/apps/web/src/components/sidebar/SidebarBotsGroup.tsx @@ -1,15 +1,33 @@ -import type { ContextMenuSource, ScopedThreadRef } from "@t3tools/contracts"; +import { + founderName, + resolveBotAttention, + typingLabel, + type ContextMenuSource, + type EnvironmentId, + type ScopedThreadRef, + type TypingByThread, +} from "@t3tools/contracts"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import { memo, type MouseEvent as ReactMouseEvent, type KeyboardEvent } from "react"; +import { + memo, + useCallback, + useEffect, + useState, + type MouseEvent as ReactMouseEvent, + type KeyboardEvent, +} from "react"; import { cn } from "~/lib/utils"; +import { orchestrationEnvironment } from "~/state/orchestration"; +import { useEnvironmentQuery } from "~/state/query"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { useThreadSelectionStore } from "../../threadSelectionStore"; import { useUiStateStore } from "../../uiStateStore"; import { BotAvatar, BOT_ACCENT_CLASSES } from "../bots/BotAvatar"; import { resolveBotPresence } from "../bots/botPresence"; import { resolveThreadLastVisitedAt, resolveThreadStatusPill } from "../Sidebar.logic"; +import { useClientSettings } from "../../hooks/useSettings"; interface BotRowHandlers { readonly onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; @@ -32,9 +50,21 @@ export function SidebarBotsGroup( readonly activeThreadKey: string | null; }, ) { + const [typingByEnvironment, setTypingByEnvironment] = useState< + Readonly> + >({}); + const onTyping = useCallback((environmentId: string, next: TypingByThread) => { + setTypingByEnvironment((current) => + current[environmentId] === next ? current : { ...current, [environmentId]: next }, + ); + }, []); if (props.threads.length === 0) return null; + const environmentIds = [...new Set(props.threads.map((thread) => thread.environmentId))]; return (
+ {environmentIds.map((environmentId) => ( + + ))}
Bots @@ -48,6 +78,7 @@ export function SidebarBotsGroup( thread={thread} threadKey={key} isActive={props.activeThreadKey === key} + typing={typingByEnvironment[thread.environmentId]} onThreadClick={props.onThreadClick} onThreadActivate={props.onThreadActivate} onContextMenu={props.onContextMenu} @@ -59,11 +90,30 @@ export function SidebarBotsGroup( ); } +/** One environment's typing stream. A hook cannot loop over a changing set of environments. */ +function TypingFeed(props: { + readonly environmentId: EnvironmentId; + readonly onTyping: (environmentId: string, next: TypingByThread) => void; +}) { + const { environmentId, onTyping } = props; + const { data } = useEnvironmentQuery( + orchestrationEnvironment.v2.typing({ + environmentId, + input: {}, + }), + ); + useEffect(() => { + onTyping(environmentId, data ?? {}); + }, [data, environmentId, onTyping]); + return null; +} + const SidebarBotRow = memo(function SidebarBotRow( props: BotRowHandlers & { readonly thread: EnvironmentThreadShell; readonly threadKey: string; readonly isActive: boolean; + readonly typing: TypingByThread | undefined; }, ) { const { thread, threadKey } = props; @@ -73,6 +123,17 @@ const SidebarBotRow = memo(function SidebarBotRow( const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const pill = resolveThreadStatusPill({ thread: { ...thread, lastVisitedAt } }); + const viewingFounder = useClientSettings((state) => state.founderInboxOwner); + const attention = resolveBotAttention({ + inbox: thread.source.inbox, + viewingFounder, + mentioned: thread.source.attentionMentions, + }); + const typingText = props.isActive + ? null + : typingLabel( + (props.typing?.[thread.id] ?? []).filter((founder) => founder !== viewingFounder), + ); const presence = resolveBotPresence( pill === null ? null : { ...pill, errorClass: thread.runtime?.lastErrorClass }, standing.role, @@ -93,7 +154,9 @@ const SidebarBotRow = memo(function SidebarBotRow( data-testid="sidebar-bot-row" data-bot-state={presence.avatarState} aria-current={props.isActive ? "page" : undefined} - aria-label={`${standing.name}${presence.line ? `, ${presence.line}` : ""}${ + aria-label={`${standing.name}${typingText ? `, ${typingText}` : presence.line ? `, ${presence.line}` : ""}${attentionLabel( + attention, + )}${ presence.badge === "needs-you" ? ", needs you" : presence.badge === "unread" @@ -133,7 +196,15 @@ const SidebarBotRow = memo(function SidebarBotRow( {standing.name} - {presence.line ? ( + {typingText ? ( + + {typingText} + + ) : presence.line ? ( )} + {presence.badge ? ( ); }); + +/** What a screen reader adds for the attention mark; the mark itself is hidden. */ +function attentionLabel(attention: ReturnType): string { + if (attention.kind === "fyi") return ", update"; + if (attention.kind === "badge") return `, ${attention.label}`; + if (attention.kind === "sign-off") { + return `, ${attention.founders + .map((entry) => `${founderName(entry.founder)} ${entry.signed ? "signed" : "waiting"}`) + .join(", ")}`; + } + return ""; +} + +/** + * The one attention mark on a bot row. FYI is a faint dot; a decision or a + * founder mention is a bright pill; a call both founders make lists each one. + */ +function BotAttentionMark(props: { + readonly attention: ReturnType; + readonly accentClass: string; +}) { + const { attention } = props; + if (attention.kind === "quiet") return null; + if (attention.kind === "fyi") { + return ( + + ); + } + if (attention.kind === "sign-off") { + return ( + + {attention.founders.map((entry, index) => ( + + {index > 0 ? · : null} + + {founderName(entry.founder)} {entry.signed ? "✓" : "○"} + + + ))} + + ); + } + return ( + + {attention.label} + + ); +} diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index ca266c77e0d45..ca02fee3a48f1 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -22,7 +22,7 @@ import { } from "./keybindings"; export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill"; -export type ComposerSlashCommand = "model" | "side" | "btw" | "clear"; +export type ComposerSlashCommand = "model" | "side" | "btw" | "clear" | "note"; export type ComposerSubmissionIntent = "foreground" | "background" | "alternate"; export interface ComposerTrigger { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 13a1ead0e5379..84bf275151774 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -609,6 +609,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems( ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}), ...(item.sentBy !== undefined ? { sentBy: item.sentBy } : {}), ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}), + ...(item.humanNote === true ? { humanNote: true as const } : {}), ...(item.scheduledTaskId !== undefined ? { scheduledTaskId: item.scheduledTaskId } : {}), diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index ae306ff5b8fd7..7d6cf452890d6 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -88,6 +88,8 @@ export interface ChatMessage { /** The signed-in client a person sent it from, stamped by the server. */ readonly sentBy?: import("@t3tools/contracts").OrchestrationV2MessageSentBy; readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction; + /** A side note between founders. The bot never sees it. */ + readonly humanNote?: true; readonly createdAt: string; readonly updatedAt: string; readonly inputIntent?: OrchestrationV2UserMessageInputIntent | undefined; diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 5b7f7dfe39030..19f8510786a2e 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -191,6 +191,8 @@ export interface StartThreadTurnInput extends ThreadCommandInput { readonly attachments: ReadonlyArray; readonly context?: import("@t3tools/contracts").OrchestrationMessageContext; readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction; + /** A side note on a shared thread. The server stores it and does not start a turn. */ + readonly humanNote?: true; }; readonly modelSelection?: ModelSelection; readonly titleSeed?: string; @@ -850,6 +852,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.message.idleCompaction === undefined ? {} : { idleCompaction: input.message.idleCompaction }), + ...(input.message.humanNote === true ? { humanNote: true as const } : {}), attachments, ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), ...(input.sourceProposedPlan === undefined @@ -880,6 +883,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.message.idleCompaction === undefined ? {} : { idleCompaction: input.message.idleCompaction }), + ...(input.message.humanNote === true ? { humanNote: true as const } : {}), attachments, ...(input.titleSeed === undefined ? {} : { titleSeed: input.titleSeed }), ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index ee70400ca47a5..4667f57a8d94e 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -55,6 +55,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread | typeof ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput | typeof ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion + | typeof ORCHESTRATION_V2_WS_METHODS.subscribeTyping | typeof ORCHESTRATION_V2_WS_METHODS.searchThreadStream | typeof WS_METHODS.subscribeAuthAccess | typeof WS_METHODS.subscribeServerConfig diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index ed34100adec7b..21d26e524fafe 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -1,10 +1,12 @@ import { ORCHESTRATION_V2_WS_METHODS, + applyTypingSnapshot, type EnvironmentId, type ThreadId, type OrchestrationV2ThreadLinkMetadata, type OrchestrationGetTurnDiffResult, type OrchestrationV2GetTurnItemInput, + type TypingByThread, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -179,6 +181,18 @@ export function createOrchestrationEnvironmentAtoms( tag: ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion, idleTtlMs: 0, }), + // Every thread's typists. The atom keeps one value, so snapshots fold into a map. + typing: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:orchestration-v2:typing", + tag: ORCHESTRATION_V2_WS_METHODS.subscribeTyping, + idleTtlMs: 0, + transform: (events) => + events.pipe(Stream.scan((): TypingByThread => ({}), applyTypingSnapshot)), + }), + reportTyping: createEnvironmentRpcCommand(runtime, { + label: "environment-data:orchestration-v2:report-typing", + tag: ORCHESTRATION_V2_WS_METHODS.reportTyping, + }), }, turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:turn-diff", diff --git a/packages/contracts/src/botAttention.test.ts b/packages/contracts/src/botAttention.test.ts new file mode 100644 index 0000000000000..e9ca8205a4b35 --- /dev/null +++ b/packages/contracts/src/botAttention.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { mentionedFounders, resolveBotAttention } from "./botAttention.ts"; +import { makeThreadInbox, type ThreadInbox } from "./threadInbox.ts"; + +const bot = { kind: "agent", id: "lead" } as const; + +const inbox = (patch: Partial = {}): ThreadInbox => ({ + ...makeThreadInbox({ actor: bot }), + ...patch, +}); + +const ask = (founder: "kameron" | "jeff") => ({ + founder, + kind: "decision" as const, + question: "Ship it?", + requestedAt: "2026-11-20T00:00:00.000Z", +}); + +describe("mentionedFounders", () => { + it("names only a whole founder mention", () => { + expect(mentionedFounders("loop in @Jeff and @kameron")).toEqual(["kameron", "jeff"]); + expect(mentionedFounders("mail @jefferson about it")).toEqual([]); + expect(mentionedFounders("@Jeff's draft")).toEqual(["jeff"]); + expect(mentionedFounders(null)).toEqual([]); + }); +}); + +describe("resolveBotAttention", () => { + it("stays quiet for ordinary work, even when its attention is action", () => { + expect( + resolveBotAttention({ + inbox: inbox({ attentionKind: "action" }), + viewingFounder: "kameron", + }), + ).toEqual({ kind: "quiet" }); + expect(resolveBotAttention({ inbox: null, viewingFounder: "jeff" })).toEqual({ + kind: "quiet", + }); + }); + + it("shows a subtle dot for FYI chatter", () => { + const shared = inbox({ audience: "shared", attentionKind: "FYI", reason: "fyi" }); + expect(resolveBotAttention({ inbox: shared, viewingFounder: "kameron" })).toEqual({ + kind: "fyi", + }); + // FYI stays a dot even when nobody is signed in as a founder. + expect(resolveBotAttention({ inbox: shared, viewingFounder: undefined })).toEqual({ + kind: "fyi", + }); + }); + + it("badges only an open decision or a founder mention", () => { + expect( + resolveBotAttention({ + inbox: inbox({ decisionRequest: ask("jeff") }), + viewingFounder: "jeff", + }).kind, + ).toBe("badge"); + expect( + resolveBotAttention({ + inbox: inbox({ decisionRequest: { ...ask("kameron"), kind: "approval" } }), + viewingFounder: "kameron", + }), + ).toEqual({ kind: "badge", label: "Approval" }); + expect( + resolveBotAttention({ + inbox: inbox(), + viewingFounder: "kameron", + latestText: "please look @Jeff", + }), + ).toEqual({ kind: "badge", label: "Jeff" }); + }); + + it("lets a mention or a decision outrank the FYI dot", () => { + const shared = inbox({ audience: "shared", attentionKind: "FYI", reason: "fyi" }); + expect( + resolveBotAttention({ inbox: shared, viewingFounder: "jeff", latestText: "cc @Kameron" }) + .kind, + ).toBe("badge"); + expect( + resolveBotAttention({ + inbox: { ...shared, decisionRequest: ask("jeff") }, + viewingFounder: "jeff", + }).kind, + ).toBe("badge"); + }); + + it("shows both founders' answers on a joint sign-off", () => { + const signOff = [ + { founder: "jeff" as const, signed: false }, + { founder: "kameron" as const, signed: true }, + ]; + expect( + resolveBotAttention({ + inbox: inbox({ decisionRequest: { ...ask("kameron"), signOff } }), + viewingFounder: "jeff", + }), + ).toEqual({ + kind: "sign-off", + founders: [ + { founder: "kameron", signed: true }, + { founder: "jeff", signed: false }, + ], + }); + }); + + it("badges names the shell already resolved, and not text it was not given", () => { + expect( + resolveBotAttention({ + inbox: inbox(), + viewingFounder: "kameron", + mentioned: ["jeff"], + latestText: "cc @Kameron", + }), + ).toEqual({ kind: "badge", label: "Jeff" }); + expect( + resolveBotAttention({ + inbox: inbox(), + viewingFounder: "kameron", + mentioned: [], + latestText: "cc @Kameron", + }), + ).toEqual({ kind: "quiet" }); + }); + + it("keeps a one-founder ask as a badge", () => { + expect( + resolveBotAttention({ + inbox: inbox({ + decisionRequest: { ...ask("kameron"), signOff: [{ founder: "kameron", signed: false }] }, + }), + viewingFounder: "kameron", + }).kind, + ).toBe("badge"); + }); +}); diff --git a/packages/contracts/src/botAttention.ts b/packages/contracts/src/botAttention.ts new file mode 100644 index 0000000000000..169a2a7aded35 --- /dev/null +++ b/packages/contracts/src/botAttention.ts @@ -0,0 +1,104 @@ +import { + Founder, + founderInboxLane, + jointSignOff, + type FounderSignOff, + type ThreadInbox, +} from "./threadInbox.ts"; + +/** + * What a standing bot shows the founder looking at it. A subtle dot is FYI + * chatter; the bright badge is reserved for a decision being asked or a founder + * being named. A joint sign-off shows both founders' answers instead of either. + */ +export type BotAttention = + | { readonly kind: "quiet" } + | { readonly kind: "fyi" } + | { readonly kind: "badge"; readonly label: string } + | { readonly kind: "sign-off"; readonly founders: ReadonlyArray }; + +/** Both founders, in the order the pill writes them. */ +export const JOINT_SIGN_OFF_FOUNDERS: readonly Founder[] = Founder.literals; + +/** How much of a message is scanned for an @-mention. The shell stores the names, not the text. */ +export const ATTENTION_MENTION_TEXT_LIMIT = 2000; + +const FOUNDER_MENTION = /@(kameron|jeff)\b/gi; + +/** The founders an @-mention names. `@jefferson` is not Jeff. */ +export function mentionedFounders(text: string | null | undefined): ReadonlyArray { + if (!text) return []; + const found = new Set(); + for (const match of text.matchAll(FOUNDER_MENTION)) { + const name = match[1]?.toLowerCase(); + if (name === "kameron" || name === "jeff") found.add(name); + } + return JOINT_SIGN_OFF_FOUNDERS.filter((founder) => found.has(founder)); +} + +/** Founders named in a message, or nothing when the text names nobody. */ +export function attentionMentionsFromText( + text: string | null | undefined, +): ReadonlyArray | undefined { + const found = mentionedFounders(text?.slice(0, ATTENTION_MENTION_TEXT_LIMIT)); + return found.length > 0 ? found : undefined; +} + +/** True when the ask lists both founders, so one founder's answer is not enough. */ +export function isJointSignOff(signOff: ReadonlyArray | null | undefined): boolean { + return jointSignOff(signOff) !== null; +} + +/** + * The one thing the bot row shows. A joint sign-off outranks a badge, and a + * badge outranks the FYI dot: a founder being asked must not look like chatter. + */ +export function resolveBotAttention(input: { + readonly inbox: ThreadInbox | null | undefined; + readonly viewingFounder: Founder | undefined; + /** Used only when `mentioned` is omitted. The shell passes names and no message text. */ + readonly latestText?: string | null | undefined; + readonly mentioned?: ReadonlyArray | undefined; +}): BotAttention { + const ordered = jointSignOff(input.inbox?.decisionRequest?.signOff); + if (ordered !== null) { + return { kind: "sign-off", founders: ordered }; + } + const ask = input.inbox?.decisionRequest; + if (ask !== undefined) { + return { kind: "badge", label: decisionBadgeLabel(ask.kind) }; + } + const mentioned = + input.mentioned !== undefined ? input.mentioned : mentionedFounders(input.latestText); + if (mentioned.length > 0) { + return { kind: "badge", label: mentionBadgeLabel(mentioned) }; + } + if (isFyi(input.inbox, input.viewingFounder)) return { kind: "fyi" }; + return { kind: "quiet" }; +} + +function decisionBadgeLabel(kind: "decision" | "review" | "approval"): string { + if (kind === "approval") return "Approval"; + if (kind === "review") return "Review"; + return "Decision"; +} + +function mentionBadgeLabel(founders: ReadonlyArray): string { + return founders.map(founderName).join(" · "); +} + +function isFyi( + inbox: ThreadInbox | null | undefined, + viewingFounder: Founder | undefined, +): boolean { + if (!inbox) return false; + if (viewingFounder !== undefined && founderInboxLane(inbox, viewingFounder) === "FYI") { + return true; + } + return inbox.attentionKind === "FYI"; +} + +/** The name the pill writes, capitalized. */ +export function founderName(founder: Founder): string { + return founder === "kameron" ? "Kameron" : "Jeff"; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 9dacb77c54884..4a7fe499f9b0b 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -77,3 +77,5 @@ export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; export * from "./threadInbox.ts"; +export * from "./botAttention.ts"; +export * from "./typingPresence.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 1d0863345b133..1f948933f1acc 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1458,6 +1458,8 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({ linkedSender: Schema.optional(OrchestrationV2LinkedSender), sentBy: Schema.optional(OrchestrationV2MessageSentBy), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), + /** A human side note. It is stored and shown, and never sent to the provider. */ + humanNote: Schema.optional(Schema.Literal(true)), seenMarker: Schema.optional(ThreadSeenMarkerSummary), /** * The message is the script a provider-native workflow run executes, not prose. Clients show @@ -1784,6 +1786,7 @@ export const OrchestrationV2TurnItem = Schema.Union([ linkedSender: Schema.optional(OrchestrationV2LinkedSender), sentBy: Schema.optional(OrchestrationV2MessageSentBy), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), + humanNote: Schema.optional(Schema.Literal(true)), workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript, freshContext: OrchestrationV2Run.fields.freshContext, inputIntent: OrchestrationV2UserMessageInputIntent, @@ -2310,6 +2313,11 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ /** Guest messages waiting for the owner to send or dismiss. Absent from older servers. */ pendingGuestMessageCount: Schema.optional(NonNegativeInt), latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary), + /** + * Founders named in the latest visible message. Omitted when nobody is named, so a shell + * row never carries message text just to badge a mention. + */ + attentionMentions: Schema.optional(Schema.Array(Founder)), latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc), /** Excludes wakes and agent messages that advance latestUserMessageAt through the user role. */ latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -2704,6 +2712,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ linkedSender: Schema.optional(OrchestrationV2LinkedSender), sentBy: Schema.optional(OrchestrationV2MessageSentBy), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), + humanNote: Schema.optional(Schema.Literal(true)), workflowScript: OrchestrationV2ConversationMessage.fields.workflowScript, freshContext: OrchestrationV2Run.fields.freshContext, inputIntent: OrchestrationV2UserMessageInputIntent, @@ -3472,6 +3481,8 @@ export const OrchestrationV2Command = Schema.Union([ linkedSender: Schema.optional(OrchestrationV2LinkedSender), sentBy: Schema.optional(OrchestrationV2MessageSentBy), idleCompaction: Schema.optional(OrchestrationV2IdleCompaction), + /** Record a human side note on a shared thread. It does not start a provider turn. */ + humanNote: Schema.optional(Schema.Literal(true)), seenMarker: Schema.optional(ThreadSeenMarker), /** Start a new provider session without the thread's earlier context. Never steers. */ freshContext: Schema.optional(Schema.Boolean), @@ -3965,6 +3976,8 @@ export const ORCHESTRATION_V2_WS_METHODS = { subscribeThread: "orchestration.subscribeThread", subscribeCommandOutput: "orchestration.subscribeCommandOutput", subscribePromptSuggestion: "orchestration.subscribePromptSuggestion", + reportTyping: "orchestration.reportTyping", + subscribeTyping: "orchestration.subscribeTyping", } as const; export const OrchestrationV2SubscribeCommandOutputInput = Schema.Struct({ @@ -3998,6 +4011,21 @@ export const OrchestrationV2SubscribePromptSuggestionInput = Schema.Struct({ threadId: ThreadId, }); +export const OrchestrationV2ReportTypingInput = Schema.Struct({ + threadId: ThreadId, + typing: Schema.Boolean, +}); +export type OrchestrationV2ReportTypingInput = typeof OrchestrationV2ReportTypingInput.Type; + +/** Who is typing on one thread. An empty list means nobody. */ +export const OrchestrationV2TypingSnapshot = Schema.Struct({ + threadId: ThreadId, + founders: Schema.Array(Founder), +}); +export type OrchestrationV2TypingSnapshot = typeof OrchestrationV2TypingSnapshot.Type; + +export const OrchestrationV2SubscribeTypingInput = Schema.Struct({}); + /** Unpersisted predicted next prompt for the run that produced it; null when there is none. */ export const OrchestrationV2PromptSuggestion = Schema.NullOr( Schema.Struct({ runId: RunId, text: Schema.String }), @@ -4752,6 +4780,14 @@ export const OrchestrationV2RpcSchemas = { input: OrchestrationV2SubscribePromptSuggestionInput, output: OrchestrationV2PromptSuggestion, }, + reportTyping: { + input: OrchestrationV2ReportTypingInput, + output: Schema.Void, + }, + subscribeTyping: { + input: OrchestrationV2SubscribeTypingInput, + output: OrchestrationV2TypingSnapshot, + }, } as const; export const ProviderReplayEntry = Schema.Union([ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b82deb7bfad94..7bb56b6561f38 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -2027,6 +2027,19 @@ const WsOrchestrationV2SubscribePromptSuggestionRpc = Rpc.make( }, ); +const WsOrchestrationV2ReportTypingRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.reportTyping, { + payload: OrchestrationV2RpcSchemas.reportTyping.input, + success: OrchestrationV2RpcSchemas.reportTyping.output, + error: EnvironmentAuthorizationError, +}); + +const WsOrchestrationV2SubscribeTypingRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.subscribeTyping, { + payload: OrchestrationV2RpcSchemas.subscribeTyping.input, + success: OrchestrationV2RpcSchemas.subscribeTyping.output, + error: EnvironmentAuthorizationError, + stream: true, +}); + const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, { payload: Schema.Struct({}), success: TerminalMetadataStreamEvent, @@ -2380,4 +2393,6 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2SubscribeThreadRpc, WsOrchestrationV2SubscribeCommandOutputRpc, WsOrchestrationV2SubscribePromptSuggestionRpc, + WsOrchestrationV2ReportTypingRpc, + WsOrchestrationV2SubscribeTypingRpc, ).middleware(RpcScopeAuthorization); diff --git a/packages/contracts/src/threadInbox.test.ts b/packages/contracts/src/threadInbox.test.ts index 97fb266ed09e7..ab0151c95ac47 100644 --- a/packages/contracts/src/threadInbox.test.ts +++ b/packages/contracts/src/threadInbox.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId } from "./baseSchemas.ts"; import { ClientSettingsSchema } from "./settings.ts"; import { + ThreadDecisionAsk, makeThreadInbox, routeThreadInbox, matchesInboxView, @@ -16,6 +17,7 @@ import { agentLaunchInboxError, agentInboxRoutingError, projectThreadInbox, + inboxAfterFounderReply, inboxRoutingFor, primaryInbox, withLegacyPeerInboxReason, @@ -420,3 +422,97 @@ describe("staysActiveWhileWorking", () => { expect(staysActiveWhileWorking(makeThreadInbox({ actor: bot }), ["kameron"])).toBe(false); }); }); + +describe("joint sign-off", () => { + const signOff = [ + { founder: "jeff" as const, signed: false }, + { founder: "kameron" as const, signed: false }, + ]; + const asked = { + ...makeThreadInbox({ actor: bot, routing: inboxRoutingFor("shared") }), + decisionRequest: { + founder: "kameron" as const, + kind: "decision" as const, + question: "Ship it?", + requestedAt: "2026-11-20T00:00:00.000Z", + signOff, + }, + }; + const reply = ( + founder: "kameron" | "jeff" | null, + updatedAt: string | { epochMilliseconds: number } = "2026-11-20T00:00:01.000Z", + ) => ({ + role: "user", + createdBy: "user", + sentBy: { founder }, + updatedAt, + }); + + it("decodes only a sign-off that lists each founder once", () => { + const ask = { + founder: "kameron", + kind: "decision", + question: "Ship it?", + } as const; + expect( + Schema.is(ThreadDecisionAsk)({ + ...ask, + signOff: [ + { founder: "kameron", signed: false }, + { founder: "jeff", signed: true }, + ], + }), + ).toBe(true); + expect( + Schema.is(ThreadDecisionAsk)({ + ...ask, + signOff: [ + { founder: "kameron", signed: false }, + { founder: "kameron", signed: true }, + ], + }), + ).toBe(false); + }); + + it("lets each founder sign only themselves, and closes once both have", () => { + const once = inboxAfterFounderReply(asked, reply("kameron")); + expect(once).not.toBe(asked); + expect(once?.decisionRequest?.signOff).toEqual([ + { founder: "kameron", signed: true }, + { founder: "jeff", signed: false }, + ]); + expect(inboxAfterFounderReply(once, reply("kameron", "2026-11-20T00:00:02.000Z"))).toBe(once); + expect(inboxAfterFounderReply(asked, reply(null))).toBe(asked); + expect( + inboxAfterFounderReply( + asked, + reply("jeff", { epochMilliseconds: Date.parse(asked.decisionRequest.requestedAt) }), + ), + ).toBe(asked); + const both = inboxAfterFounderReply(once, reply("jeff", "2026-11-20T00:00:03.000Z")); + expect(both?.decisionRequest).toBeUndefined(); + const plain = { ...asked, decisionRequest: { ...asked.decisionRequest, signOff: undefined } }; + const closed = projectThreadInbox(plain, { + latestHumanMessageAt: "2026-11-20T00:00:02.000Z", + pendingHumanRequest: false, + }); + expect(closed.decisionRequest).toBeUndefined(); + }); + + it("keeps a joint ask open for the founder who has not signed", () => { + const signed = inboxAfterFounderReply(asked, reply("kameron"))!; + const projected = projectThreadInbox(signed, { + latestHumanMessageAt: "2026-11-20T00:00:05.000Z", + pendingHumanRequest: false, + }); + expect(projected.decisionRequest?.signOff?.[1]?.signed).toBe(false); + expect([founderInboxLane(projected, "kameron"), founderInboxLane(projected, "jeff")]).toEqual([ + "hidden", + "action", + ]); + expect([founderInboxLane(asked, "kameron"), founderInboxLane(asked, "jeff")]).toEqual([ + "action", + "action", + ]); + }); +}); diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index c13d8c0ea84c8..76acd65c7b779 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -36,10 +36,41 @@ export const ThreadInboxRoutingPatch = Schema.Struct({ reason: Schema.optionalKey(InboxReason), }); export type ThreadInboxRoutingPatch = typeof ThreadInboxRoutingPatch.Type; +/** + * One founder's answer on a call both founders make. `signed` is set once they + * reply; an open ask lists both with none signed. + */ +export const FounderSignOff = Schema.Struct({ + founder: Founder, + signed: Schema.Boolean, +}); +export type FounderSignOff = typeof FounderSignOff.Type; + +const jointSignOffEntries = Schema.Array(FounderSignOff).check( + Schema.isMinLength(2), + Schema.isMaxLength(2), + Schema.makeFilter((entries) => { + const founders = new Set(entries.map((entry) => entry.founder)); + return founders.size === Founder.literals.length && + Founder.literals.every((founder) => founders.has(founder)) + ? true + : "A joint sign-off lists Kameron and Jeff once each."; + }), +); + export const ThreadDecisionAsk = Schema.Struct({ founder: Founder, kind: Schema.Literals(["decision", "review", "approval"]), question: TrimmedNonEmptyString.check(Schema.isMaxLength(2000)), + /** + * 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. + */ + signOff: Schema.optional( + jointSignOffEntries.annotate({ + description: "Both founders' answers, when the call needs each of them.", + }), + ), }); export type ThreadDecisionAsk = typeof ThreadDecisionAsk.Type; export const ThreadDecisionRequest = Schema.Struct({ @@ -50,7 +81,10 @@ export type ThreadDecisionRequest = typeof ThreadDecisionRequest.Type; export const ThreadInbox = Schema.Struct({ ...ThreadInboxRouting.fields, reason: Schema.optionalKey(InboxReason), - /** Open until the founder writes on the thread after `requestedAt`, or it is resolved or settled. */ + /** + * Open until the asked founder writes after `requestedAt`. A joint sign-off stays open until + * each founder has written. Resolving or settling the thread also closes it. + */ decisionRequest: Schema.optionalKey(ThreadDecisionRequest), /** Set only on projected shells: the thread waits on an approval or user input. Never stored. */ pendingHumanRequest: Schema.optionalKey(Schema.Boolean), @@ -222,19 +256,85 @@ export const agentLaunchInboxError = (input: Parameters | null | undefined, +): ReadonlyArray | null { + if (signOff == null || signOff.length !== Founder.literals.length) return null; + const byFounder = new Map(signOff.map((entry) => [entry.founder, entry])); + if (byFounder.size !== Founder.literals.length) return null; + const ordered: FounderSignOff[] = []; + for (const founder of Founder.literals) { + const entry = byFounder.get(founder); + if (entry === undefined) return null; + ordered.push(entry); + } + return ordered; +} + +type ReplyClock = string | { readonly epochMilliseconds: number }; + +const replyMillis = (value: ReplyClock): number => + typeof value === "string" ? Date.parse(value) : value.epochMilliseconds; + +/** + * A founder's own reply signs only that founder on a joint ask. The ask stays until both have + * signed. A message that signs nobody returns the same inbox, so a writer can skip the rewrite. + */ +export function inboxAfterFounderReply( + inbox: Inbox, + message: { + readonly role: string; + readonly createdBy?: string | undefined; + readonly idleCompaction?: unknown; + readonly sentBy?: { readonly founder: Founder | null } | undefined; + readonly updatedAt: ReplyClock; + }, +): Inbox { + if (inbox === undefined) return inbox; + const request = inbox.decisionRequest; + const ordered = jointSignOff(request?.signOff); + if (request === undefined || ordered === null) return inbox; + const founder = message.sentBy?.founder; + if ( + message.role !== "user" || + message.createdBy !== "user" || + message.idleCompaction != null || + (founder !== "kameron" && founder !== "jeff") || + replyMillis(message.updatedAt) <= replyMillis(request.requestedAt) + ) { + return inbox; + } + const entry = ordered.find((item) => item.founder === founder); + if (entry === undefined || entry.signed) return inbox; + const next = ordered.map((item) => (item.founder === founder ? { ...item, signed: true } : item)); + if (next.every((item) => item.signed)) { + const { decisionRequest: _closed, ...rest } = inbox; + return rest as Inbox; + } + return { ...inbox, decisionRequest: { ...request, signOff: next } }; +} + /** * The inbox clients read. A decision request closes once a person writes on the thread after it - * was asked; a pending approval or user-input request surfaces to the owner. + * was asked. A joint sign-off stays open until each founder has signed. A pending approval or + * user-input request surfaces to the owner. */ export function projectThreadInbox( inbox: ThreadInbox, state: { readonly pendingHumanRequest: boolean; readonly latestHumanMessageAt: string | null }, ): ThreadInbox { const { decisionRequest, pendingHumanRequest: _stored, ...rest } = inbox; + const joint = jointSignOff(decisionRequest?.signOff); const open = decisionRequest !== undefined && - (state.latestHumanMessageAt === null || - Date.parse(state.latestHumanMessageAt) <= Date.parse(decisionRequest.requestedAt)); + (joint !== null + ? joint.some((entry) => !entry.signed) + : state.latestHumanMessageAt === null || + Date.parse(state.latestHumanMessageAt) <= Date.parse(decisionRequest.requestedAt)); return { ...rest, ...(open ? { decisionRequest } : {}), @@ -250,7 +350,14 @@ export function projectThreadInbox( */ export function founderInboxLane(inbox: ThreadInbox | null | undefined, founder: Founder) { if (!inbox) return "unknown"; - if (inbox.decisionRequest?.founder === founder) return "action"; + const joint = jointSignOff(inbox.decisionRequest?.signOff); + if (joint !== null) { + const mine = joint.find((entry) => entry.founder === founder); + // A founder who has already signed is no longer waiting, even if the ask names them. + if (mine !== undefined && !mine.signed) return "action"; + } else if (inbox.decisionRequest?.founder === founder) { + return "action"; + } if (inbox.pendingHumanRequest === true && inbox.owner === founder) return "action"; const assigned = inbox.assignee?.kind === "human" ? inbox.assignee.id : inbox.owner; if (inbox.audience === "agent-only" && inbox.assignee?.kind !== "human") return "hidden"; diff --git a/packages/contracts/src/typingPresence.test.ts b/packages/contracts/src/typingPresence.test.ts new file mode 100644 index 0000000000000..6ca530901493c --- /dev/null +++ b/packages/contracts/src/typingPresence.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + TYPING_TTL_MS, + applyTypingSnapshot, + liveFounders, + rosterAfterReport, + typingLabel, +} from "./typingPresence.ts"; + +describe("typing presence", () => { + it("keeps a beat until the window ends, and never shows a session assigned to nobody", () => { + const now = 10_000; + const typing = rosterAfterReport(new Map(), "kameron-laptop", "kameron", true, now); + const both = rosterAfterReport(typing, "jeff-phone", "jeff", true, now + 10); + expect(liveFounders(both, now + 10)).toEqual(["kameron", "jeff"]); + const nobody = rosterAfterReport(both, "guest", null, true, now + 10); + expect(liveFounders(nobody, now + 10)).toEqual(["kameron", "jeff"]); + expect(liveFounders(both, now + TYPING_TTL_MS)).toEqual(["jeff"]); + expect(liveFounders(both, now + 10 + TYPING_TTL_MS)).toEqual([]); + const stopped = rosterAfterReport(both, "jeff-phone", "jeff", false, now + 20); + expect(stopped.has("jeff-phone")).toBe(false); + expect(rosterAfterReport(stopped, "missing", "jeff", false, now)).toBe(stopped); + }); + + it("folds snapshots and drops a thread when nobody is left", () => { + const once = applyTypingSnapshot({}, { threadId: "a", founders: ["jeff"] }); + const both = applyTypingSnapshot(once, { threadId: "b", founders: ["kameron", "jeff"] }); + expect(both).toEqual({ a: ["jeff"], b: ["kameron", "jeff"] }); + expect(applyTypingSnapshot(both, { threadId: "missing", founders: [] })).toBe(both); + expect(applyTypingSnapshot(both, { threadId: "a", founders: [] })).toEqual({ + b: ["kameron", "jeff"], + }); + expect(typingLabel(["jeff"])).toBe("Jeff is typing"); + expect(typingLabel(["kameron", "jeff"])).toBe("Kameron and Jeff are typing"); + expect(typingLabel([])).toBeNull(); + }); +}); diff --git a/packages/contracts/src/typingPresence.ts b/packages/contracts/src/typingPresence.ts new file mode 100644 index 0000000000000..acd373178e553 --- /dev/null +++ b/packages/contracts/src/typingPresence.ts @@ -0,0 +1,77 @@ +import { founderName } from "./botAttention.ts"; +import { Founder, type Founder as FounderName } from "./threadInbox.ts"; + +/** A typing beat older than this is gone. Clients refresh inside the window. */ +export const TYPING_TTL_MS = 4000; + +export interface TypingBeat { + readonly founder: FounderName | null; + readonly at: number; +} + +export type TypingRoster = ReadonlyMap; + +/** Latest founders typing on each thread. An empty list deletes the thread. */ +export type TypingByThread = Readonly>>; + +export interface TypingSnapshot { + readonly threadId: string; + readonly founders: ReadonlyArray; +} + +/** + * One session's beat. Stopping, or a session assigned to nobody, drops that session. + * The same roster comes back when nothing changed. + */ +export function rosterAfterReport( + roster: TypingRoster, + sessionId: string, + founder: FounderName | null, + typing: boolean, + now: number, +): TypingRoster { + if (!typing || founder === null) { + if (!roster.has(sessionId)) return roster; + const next = new Map(roster); + next.delete(sessionId); + return next; + } + const current = roster.get(sessionId); + if (current?.founder === founder && current.at === now) return roster; + const next = new Map(roster); + next.set(sessionId, { founder, at: now }); + return next; +} + +/** Founders with a beat inside the window, Kameron then Jeff. A null founder is nobody. */ +export function liveFounders( + roster: TypingRoster, + now: number, + ttl = TYPING_TTL_MS, +): ReadonlyArray { + const live = new Set(); + for (const beat of roster.values()) { + if (beat.founder === null || now - beat.at >= ttl) continue; + live.add(beat.founder); + } + return Founder.literals.filter((founder) => live.has(founder)); +} + +/** Fold one thread's snapshot into the map the sidebar and the composer both read. */ +export function applyTypingSnapshot(state: TypingByThread, event: TypingSnapshot): TypingByThread { + if (event.founders.length === 0) { + if (!(event.threadId in state)) return state; + const next = { ...state }; + delete next[event.threadId]; + return next; + } + return { ...state, [event.threadId]: event.founders }; +} + +/** "Jeff is typing", or both names. Nothing when nobody else is typing. */ +export function typingLabel(founders: ReadonlyArray): string | null { + if (founders.length === 0) return null; + const names = founders.map(founderName); + if (names.length === 1) return `${names[0]} is typing`; + return `${names[0]} and ${names[1]} are typing`; +} diff --git a/packages/shared/src/composerTrigger.test.ts b/packages/shared/src/composerTrigger.test.ts index 97d1250c4784a..7dd2b0e4ecb81 100644 --- a/packages/shared/src/composerTrigger.test.ts +++ b/packages/shared/src/composerTrigger.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test"; import { detectComposerTrigger, + parseNoteCommand, parseSideChatCommand, serializeComposerFileLink, } from "./composerTrigger.ts"; @@ -136,3 +137,17 @@ describe("parseSideChatCommand", () => { expect(parseSideChatCommand("ask /side later")).toBeNull(); }); }); + +describe("parseNoteCommand", () => { + it("reads an optional note after /note", () => { + expect(parseNoteCommand("/note")).toEqual({ prompt: "" }); + expect(parseNoteCommand(" /NOTE don't wake the bot ")).toEqual({ + prompt: "don't wake the bot", + }); + }); + + it("ignores other words", () => { + expect(parseNoteCommand("/notebook")).toBeNull(); + expect(parseNoteCommand("see /note")).toBeNull(); + }); +}); diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 223375a17dcf8..d52d371a07936 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -140,3 +140,9 @@ export function parseSideChatCommand(text: string): { prompt: string } | null { const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim()); return match ? { prompt: match[1]?.trim() ?? "" } : null; } + +/** `/note [text]` as the whole message. A note is for the other founder, not the bot. */ +export function parseNoteCommand(text: string): { prompt: string } | null { + const match = /^\/note(?:\s+([\s\S]*))?$/i.exec(text.trim()); + return match ? { prompt: match[1]?.trim() ?? "" } : null; +} From e146e2bccb982c89d886a6fcd1e71427d75992e0 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:15:26 +0000 Subject: [PATCH 2/3] fix(server): stop typing presence from requiring Clock The typing methods named Clock in their Effect requirements. Clock is a default reference, so that annotation made every CLI command that builds the websocket layer require Clock, and the server typecheck failed. Model: grok-4.7 Task: fix Agent: grok Harness: grok --- apps/server/src/orchestration-v2/TypingPresence.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/TypingPresence.ts b/apps/server/src/orchestration-v2/TypingPresence.ts index 27d2abbbc63c1..179ae5f667158 100644 --- a/apps/server/src/orchestration-v2/TypingPresence.ts +++ b/apps/server/src/orchestration-v2/TypingPresence.ts @@ -15,6 +15,9 @@ import * as Stream from "effect/Stream"; /** * Who is typing, for every socket. The map lives for the server, not for one connection, so * Kameron and Jeff see each other. Nothing here is stored. + * + * Time uses the default Clock reference. These methods must not require Clock: the CLI + * runtime does not list it, and an explicit requirement fails the server typecheck. */ export interface TypingPresence { readonly report: (input: { @@ -22,8 +25,8 @@ export interface TypingPresence { readonly sessionId: string; readonly founder: Founder | null; readonly typing: boolean; - }) => Effect.Effect; - readonly subscribe: Stream.Stream; + }) => Effect.Effect; + readonly subscribe: Stream.Stream; } const emptyRoster: TypingRoster = new Map(); From 39d740a2975f689cc4a4990edfdb6245ec3d57a3 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:11:27 +0000 Subject: [PATCH 3/3] fix(web): keep draft-send reload tests inside the unit timeout The first chatViewSend reload test evaluated ChatView and the draft store inside the 15s unit timeout. On the loaded ARC runner that import ran past 15s, and the abandoned test then reset modules under the next test, so the retried-upload draft was gone. The file now evaluates that graph while it loads, and a storage run that lost the epoch stops instead of clearing the run that replaced it. Model: grok-4.7 Task: fix Agent: grok Harness: grok --- .../src/components/chat/chatViewSend.test.ts | 98 ++++++++++++++++--- 1 file changed, 84 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/chatViewSend.test.ts b/apps/web/src/components/chat/chatViewSend.test.ts index 83de6940aa184..295cff05a6db0 100644 --- a/apps/web/src/components/chat/chatViewSend.test.ts +++ b/apps/web/src/components/chat/chatViewSend.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import * as NodeAsyncHooks from "node:async_hooks"; import { describe, expect, it, vi } from "vite-plus/test"; import { createMemoryStorage } from "../../lib/storage"; @@ -46,7 +47,19 @@ const modelSelection = { model: "claude-sonnet-4-6", }; -async function openTab() { +// A timed-out test is not cancelled: its import can finish after the next test has +// stubbed storage. The epoch is the test that owns the globals; a continuation +// whose epoch lost that race stops instead of resetting the next test's modules. +const storageRuns = new NodeAsyncHooks.AsyncLocalStorage(); +let storageEpoch = 0; + +class SupersededStorageRun extends Error {} + +function assertStorageOwner() { + if (storageRuns.getStore() !== storageEpoch) throw new SupersededStorageRun(); +} + +async function loadTab() { return { store: await import("../../composerDraftStore"), send: await import("./chatViewSend"), @@ -55,6 +68,13 @@ async function openTab() { uploads: await import("../../lib/attachmentUploadQueue"), }; } + +async function openTab() { + const epoch = storageRuns.getStore(); + const tab = await loadTab(); + if (epoch !== storageEpoch) throw new SupersededStorageRun(); + return tab; +} type Tab = Awaited>; // Storage that can refuse a write, drop it without saying so, or take it and fail the read after. @@ -85,29 +105,49 @@ function faultyStorage() { } async function withReloadableStorage(run: () => Promise) { - vi.stubGlobal("localStorage", faultyStorage()); - vi.stubGlobal("window", new EventTarget()); - vi.stubGlobal("FileReader", BlobFileReader); - vi.useFakeTimers(); - vi.resetModules(); - try { - await run(); - } finally { - gate = null; - resetStorageFaults(); - vi.useRealTimers(); - vi.unstubAllGlobals(); + const epoch = ++storageEpoch; + return storageRuns.run(epoch, async () => { + vi.stubGlobal("localStorage", faultyStorage()); + vi.stubGlobal("window", new EventTarget()); + vi.stubGlobal("FileReader", BlobFileReader); + vi.useFakeTimers(); vi.resetModules(); - } + try { + await run(); + } catch (error) { + if (error instanceof SupersededStorageRun) return; + throw error; + } finally { + if (storageRuns.getStore() === storageEpoch) { + gate = null; + resetStorageFaults(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + } + }); } /** The renderer dies: the next tab reads only what storage holds. */ async function reload() { + assertStorageOwner(); vi.clearAllTimers(); vi.resetModules(); return openTab(); } +// Evaluating ChatView and the draft store the first time exceeds the 15s unit +// timeout on a loaded CI worker, and that abandoned test then races the next one. +// Pay for the graph while this file loads. Each test still resets and re-imports +// after it stubs storage; a repeat evaluation stays inside the timeout. +vi.stubGlobal("localStorage", createMemoryStorage()); +vi.stubGlobal("window", new EventTarget()); +vi.stubGlobal("FileReader", BlobFileReader); +await loadTab(); +vi.resetModules(); +vi.unstubAllGlobals(); + const launchRequest = (tab: Tab, branch: string | null = null) => tab.logic.draftLaunchRequest({ modelSelection, @@ -261,6 +301,7 @@ async function sendDraft( gate = null; } const composer = await sentComposer; + assertStorageOwner(); if (options.bindFault) storageFaults[options.bindFault] = true; const bound = tab.store.markPromotedDraftThreadByRef(sentRef, { ...operation, composer }); resetStorageFaults(); @@ -287,6 +328,7 @@ async function sendDraft( if (!bound) return { bound, committed: false, cleared: false, failed: cleanUp(false), before }; if (options.stopAfterBind) return null; const attachments = await prepared; + assertStorageOwner(); options.editBeforeCommit?.(); const turn = { environmentId, @@ -691,3 +733,31 @@ describe("a draft launch whose file's first upload failed", () => { }); }); }); + +describe("a storage run that the timeout did not cancel", () => { + it("leaves the run that replaced it still owning storage and timers", async () => { + let release!: () => void; + let reached!: () => void; + const held = new Promise((resolve) => { + release = resolve; + }); + const ready = new Promise((resolve) => { + reached = resolve; + }); + const older = withReloadableStorage(async () => { + await openTab(); + reached(); + await held; + await reload(); + }); + await ready; + await withReloadableStorage(async () => { + await openTab(); + release(); + await older; + expect(vi.isFakeTimers()).toBe(true); + expect(typeof localStorage.getItem).toBe("function"); + expect(localStorage.getItem("t3code:composer-drafts:v1")).toBeNull(); + }); + }); +});