diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 18e66ef9f261f..a43bf4ce176f0 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -257,6 +257,7 @@ export const make = Effect.gen(function* () { usagePriceOverrides: true, usageModelAliases: true, threadPinning: true, + threadStanding: true, threadPinReorder: true, threadActiveReorder: true, threadAutoSettleOptOut: true, diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index ef010ff79abf3..350d0b9da4858 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -66,8 +66,18 @@ function metadataCommand(input: { readonly commandId: CommandId; readonly threadId: ThreadId; readonly update: ThreadMetadataMcpUpdateInput; -}): Extract { +}): Extract< + OrchestrationV2Command, + { readonly type: "thread.metadata.update" | "thread.standing.set" } +> { switch (input.update.action) { + case "set_standing": + return { + type: "thread.standing.set", + commandId: input.commandId, + threadId: input.threadId, + standing: input.update.standing ?? null, + }; case "route": return { type: "thread.metadata.update", @@ -112,11 +122,12 @@ function resultFromThread(input: { readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" + "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "updatedAt" | "inbox" | "standing" >; }): ThreadMetadataMcpUpdateResult { return { ...(input.thread.inbox === undefined ? {} : { inbox: input.thread.inbox }), + ...(input.thread.standing === undefined ? {} : { standing: input.thread.standing }), threadId: input.thread.id, action: input.action, commandId: input.commandId, @@ -207,11 +218,14 @@ const make = Effect.gen(function* () { ), ); const metadataEvent = dispatched.storedEvents.find( - (stored) => stored.event.type === "thread.metadata-updated", + (stored) => + stored.event.type === "thread.metadata-updated" || + stored.event.type === "thread.standing-updated", ); // Retries may find stored events compacted away; answer from the projection. const thread = - metadataEvent?.event.type === "thread.metadata-updated" + metadataEvent?.event.type === "thread.metadata-updated" || + metadataEvent?.event.type === "thread.standing-updated" ? metadataEvent.event.payload : yield* threadManagement .getThreadShell(threadId) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts index 65b88a120b1a3..a947679ba03a5 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts @@ -27,3 +27,24 @@ it("refuses a t3_thread_update whose fields do not fit its action", () => { true, ); }); + +it("takes a bot persona, or null, only with set_standing", () => { + const decode = Schema.decodeUnknownExit( + OrchestratorToolkit.tools.t3_thread_update.parametersSchema, + ); + const standing = { name: "Synthetic Bot", avatarId: "visor", accent: "teal" }; + expect(Exit.isSuccess(decode({ action: "set_standing", standing }))).toBe(true); + expect(Exit.isSuccess(decode({ action: "set_standing", standing: null }))).toBe(true); + expect(Exit.isFailure(decode({ action: "set_standing" }))).toBe(true); + expect(Exit.isFailure(decode({ action: "rename", title: "New", standing }))).toBe(true); + expect( + Exit.isFailure( + decode({ action: "set_standing", standing: { ...standing, avatarId: "grok" } }), + ), + ).toBe(true); + expect( + Exit.isFailure( + decode({ action: "set_standing", standing: { ...standing, name: "two\nlines" } }), + ), + ).toBe(true); +}); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index e27a98031e0b3..ffcb93de70244 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -268,7 +268,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Update a thread; omit `threadId` for this one. When a founder must decide, review or approve, use `action:'request_decision'` with `decision`: the thread shows in their inbox until they reply there, `resolve_decision`, or settle. `action:'route'` refiles it with `inboxRouting`; a founder's or the shared inbox needs `inboxRouting.reason`. `rename` takes `title`; `regenerate_title`. Workspace and branch cannot change here.", + "Update a thread; omit `threadId` for this one. When a founder must decide, review or approve, use `action:'request_decision'` with `decision`: the thread shows in their inbox until they reply there, `resolve_decision`, or settle. `action:'route'` refiles it with `inboxRouting`; a founder's or the shared inbox needs `inboxRouting.reason`. `rename` takes `title`; `regenerate_title`. `set_standing` takes `standing` (bot persona, or null for an ordinary thread). Workspace and branch cannot change here.", // Keeps the input's action/field check, which rebuilding the struct would drop. parameters: ThreadMetadataMcpUpdateInput.mapFields( Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index d6b43fa3a67b4..f116e1d7da6d9 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -483,6 +483,26 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }), ); const thread = result.projection.thread; + // Derived from the launch command, so a retry replays rather than repeats it. The thread + // is already running, so a failure here is reported, not turned into a failed launch. + const standingApplied = + input.standing === undefined + ? undefined + : yield* context.threads + .dispatch({ + type: "thread.standing.set", + commandId: CommandId.make(`${commandId}:standing`), + threadId: thread.id, + standing: input.standing, + }) + .pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logWarning("mcp.thread_launch.standing_failed", error).pipe( + Effect.as(false), + ), + ), + ); const run = result.projection.runs.find((run) => run.userMessageId === messageId); return { threadId: thread.id, @@ -491,6 +511,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { modelSelection: thread.modelSelection, runId: run?.id ?? null, status: run?.status ?? null, + ...(standingApplied === undefined ? {} : { standingApplied }), }; }), // The launched thread carries the caller's link, if it has one. diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 2f58e7d9e650b..4b75605d9977a 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -3,6 +3,7 @@ import { clampedPositiveInt, InboxChoiceParameter, ThreadInboxRoutingPatch, + ThreadStanding, NonNegativeInt, ModelSelection, TrimmedNonEmptyString, @@ -145,6 +146,12 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { inbox: Schema.optional(InboxChoiceParameter), inboxRouting: Schema.optional(ThreadInboxRoutingPatch), title: TrimmedNonEmptyString, + standing: Schema.optional( + ThreadStanding.annotate({ + description: + "Make it a standing bot thread with this persona ({name, role?, avatarId, accent}). Change later with t3_thread_update set_standing.", + }), + ), modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), interactionMode: Schema.optional(ProviderInteractionMode), @@ -179,6 +186,8 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { modelSelection: ModelSelection, runId: Schema.NullOr(RunId), status: Schema.NullOr(OrchestrationV2RunStatus), + /** Present when `standing` was passed; false means the thread launched but is not a bot yet. */ + standingApplied: Schema.optional(Schema.Boolean), }), dependencies: [ ...shared.dependencies, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 92d608cb83056..10453a2a54fb3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -641,6 +641,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.pin.reorder": case "thread.active.reorder": case "thread.tag.set": + case "thread.standing.set": case "thread.visit": case "thread.mark-unread": case "thread.metadata.update": @@ -4174,6 +4175,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.unpin" | "thread.pin.reorder" | "thread.tag.set" + | "thread.standing.set" | "thread.active.reorder" | "thread.mark-unread" | "thread.metadata.update" @@ -4861,6 +4863,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio updatedAt: thread.updatedAt, }; } + case "thread.standing.set": { + // Standing is identity, not activity: it never bumps updatedAt. + return { ...thread, standing: command.standing }; + } case "thread.tag.set": { const current = thread.tags ?? []; return { @@ -5295,6 +5301,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return "thread.active-reordered" as const; case "thread.tag.set": return "thread.tags-updated" as const; + case "thread.standing.set": + return "thread.standing-updated" as const; case "thread.mark-unread": return "thread.marked-unread" as const; case "thread.metadata.update": @@ -15122,6 +15130,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.pin.reorder": case "thread.active.reorder": case "thread.tag.set": + case "thread.standing.set": case "thread.mark-unread": case "thread.pull-request.link": case "thread.pull-request.unlink": diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..df6170bcd3c59 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -326,6 +326,16 @@ it.effect( new Set(eligible.map((thread) => thread.id)), new Set([idle, completed, queued, woke, background, persistent, rolledBack]), ); + const idleCandidate = candidates.find((thread) => thread.id === idle)!; + assert.isFalse( + isAutoSettlementCandidate( + { + ...idleCandidate, + standing: { name: "Ops", role: null, avatarId: "bolt", accent: "sky" }, + }, + DateTime.toEpochMillis(now), + ), + ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), new Set( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index de25669b4feb5..a97180024c12e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -227,6 +227,7 @@ export type ProjectionSettlementCandidate = Pick< | "settledOverride" | "pinnedAt" | "autoSettleDisabledAt" + | "standing" | "snoozedUntil" | "snoozedAt" | "latestRunId" @@ -967,6 +968,7 @@ export function applyToProjection( // Reordering and PR refreshes preserve the orchestrator's activity timestamp. case "thread.active-reordered": case "thread.tags-updated": + case "thread.standing-updated": case "thread.pull-request-synced": return { ...base, @@ -1919,6 +1921,7 @@ export function threadShellFromProjection( autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null, pinOrderKey: projection.thread.pinOrderKey ?? null, ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}), + ...(projection.thread.standing ? { standing: projection.thread.standing } : {}), lastVisitedAt: projection.thread.lastVisitedAt, opens: projection.thread.opens ?? null, titleRegeneration: projection.thread.titleRegeneration ?? null, @@ -2224,6 +2227,7 @@ function shellFromState(input: { autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null, pinOrderKey: input.state.thread.pinOrderKey ?? null, ...(input.state.thread.tags?.length ? { tags: input.state.thread.tags } : {}), + ...(input.state.thread.standing ? { standing: input.state.thread.standing } : {}), lastVisitedAt: input.state.thread.lastVisitedAt, opens: input.state.thread.opens ?? null, titleRegeneration: input.state.thread.titleRegeneration ?? null, @@ -2398,6 +2402,7 @@ export const layer: Layer.Layer = case "thread.pin-reordered": case "thread.active-reordered": case "thread.tags-updated": + case "thread.standing-updated": case "thread.visited": case "thread.marked-unread": case "thread.metadata-updated": @@ -3218,6 +3223,7 @@ export const layer: Layer.Layer = event.type !== "thread.pin-reordered" && event.type !== "thread.active-reordered" && event.type !== "thread.tags-updated" && + event.type !== "thread.standing-updated" && event.type !== "thread.visited" && event.type !== "thread.visit-recorded" && event.type !== "thread.marked-unread" && @@ -7841,6 +7847,7 @@ export const layer: Layer.Layer = AND json_extract(${thread}.payload_json, '$.lineage.sideChat') IS NOT 1 AND json_extract(${thread}.payload_json, '$.settledOverride') = 'settled' AND json_extract(${thread}.payload_json, '$.settledAt') IS NOT NULL + AND json_extract(${thread}.payload_json, '$.standing') IS NULL )`; }; // Mirrors senderNeedsParent: the parent a thread's sender comes from, else NULL. diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index c41d5553afc13..b6d33ea1c88d4 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -164,6 +164,8 @@ export function isAutoSettlementCandidate( ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; + // A standing bot is a long-lived lane, never finished work. + if (thread.standing != null) return false; if (thread.pendingRuntimeRequest !== null) return false; // A guest is waiting on the owner; settling would hide the Request. if ((thread.pendingGuestMessageCount ?? 0) > 0) return false; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b2d12935aa2f8..a8fa42fe34afb 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3749,6 +3749,35 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { DateTime.toEpochMillis(untaggedShell.updatedAt), ); + assert.isUndefined(taggedShell.standing ?? undefined); + const persona = { + name: "Synthetic Bot", + role: "Watches the demo lane", + avatarId: "visor", + accent: "teal", + } as const; + yield* orchestrator.dispatch({ + type: "thread.standing.set", + commandId: CommandId.make("runtime-layer-lifecycle-standing-set"), + threadId, + standing: persona, + }); + const standingShell = shellOf(yield* orchestrator.getShellSnapshot()); + assert.deepEqual(standingShell.standing, persona); + assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).thread.standing, persona); + // Standing is identity, not activity: the thread keeps its place. + assert.equal( + DateTime.toEpochMillis(standingShell.updatedAt), + DateTime.toEpochMillis(untaggedShell.updatedAt), + ); + yield* orchestrator.dispatch({ + type: "thread.standing.set", + commandId: CommandId.make("runtime-layer-lifecycle-standing-clear"), + threadId, + standing: null, + }); + assert.isUndefined(shellOf(yield* orchestrator.getShellSnapshot()).standing ?? undefined); + const preAutoProjection = yield* orchestrator.getThreadProjection(threadId); const staleAutoSettle = yield* orchestrator .dispatch({ diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 0d428e1a6e1e0..1c6f58d0f66af 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -155,6 +155,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray {}; +/** Bot threads whose details card was folded once; after that the user's choice stands. */ +const BOT_DETAILS_FOLDED_KEY = "t3code:bot-details-folded:v1"; +const BotDetailsFoldedKeys = Schema.Array(Schema.String); +function foldBotDetailsOnce(threadKey: string): boolean { + const folded = getLocalStorageItem(BOT_DETAILS_FOLDED_KEY, BotDetailsFoldedKeys) ?? []; + if (folded.includes(threadKey)) return false; + setLocalStorageItem( + BOT_DETAILS_FOLDED_KEY, + [...folded, threadKey].slice(-500), + BotDetailsFoldedKeys, + ); + return true; +} + export default function ChatView(props: ChatViewProps) { const { environmentId, @@ -1789,8 +1803,25 @@ export default function ChatView(props: ChatViewProps) { providerSubagentModels, reportedModelSelection, ); + const activeStanding = activeThreadShell?.standing ?? null; + const botDetailsOpen = useRightPanelStore( + (state) => + activeStanding !== null && + selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"), + ); + const isStandingBot = activeStanding !== null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- folds a bot's details card (branch, worktree, PR) the first time this client shows that bot; the panel toggle reopens it and that choice persists + useEffect(() => { + if (!isStandingBot || !activeThreadRef || !activeThreadKey) return; + if (!foldBotDetailsOnce(activeThreadKey)) return; + const store = useRightPanelStore.getState(); + store.setThreadPanelOpen(activeThreadRef, "inline", false); + store.setThreadPanelOpen(activeThreadRef, "popover", false); + }, [isStandingBot, activeThreadKey, activeThreadRef]); + // A standing bot keeps branch, worktree and PR folded with its details card. const showComposerContextStrip = !embedded && + (activeStanding === null || botDetailsOpen) && shouldShowComposerContextStrip({ isDraftHeroState, persistInActiveThreads: settings.persistComposerContextStrip, @@ -3385,6 +3416,7 @@ export default function ChatView(props: ChatViewProps) { ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable } : {})} {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})} + standing={activeStanding} /> )} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 4bb53c5f73a33..405a2b7749bca 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -190,6 +190,9 @@ import { } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; +import { runBotMenuAction } from "./bots/botMenuActions"; +import { sortBotThreads, splitStandingThreads } from "./bots/botPresence"; +import { SidebarBotsGroup } from "./sidebar/SidebarBotsGroup"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -521,8 +524,14 @@ function useSidebarThreads(input: { clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); - const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } = - partition; + const { + botThreads, + pinnedThreads, + activeThreads, + workingThreads, + snoozedThreads, + settledThreads, + } = partition; // Older settled threads load in pages; the shelf lists them only as far as they are loaded. const olderSettledShelf = useOlderSettledShelf({ scopes: olderSettledScopes([...serverConfigs.keys()], scopedProjectKeys), @@ -581,6 +590,7 @@ function useSidebarThreads(input: { }; }); const orderedThreads = [ + ...botThreads, ...pinnedThreads, ...(projectFolders === null ? activeThreads @@ -604,6 +614,7 @@ function useSidebarThreads(input: { threads, workingShelfEnabled, searchableThreads: [ + ...botThreads, ...pinnedThreads, ...activeThreads, ...workingThreads, @@ -667,6 +678,9 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const preciseNow = new Date().toISOString(); const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); const inboxObservation = inboxReturns.observe(workingShelfEnabled ? threads : null); + // Standing bots live in their own group whatever their pin, settle or snooze state. A bot + // that is a delegated child stays nested under its parent instead, so it is listed once. + const { bots, rest } = splitStandingThreads(visible); const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; const working: EnvironmentThreadShell[] = []; @@ -679,11 +693,12 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const snoozed: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = []; const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({ - threads: visible, + // Bots sit outside the sortable sections, so they are never drag targets. + threads: rest, serverConfigs, connectedEnvironmentIds: input.connectedEnvironmentIds, }); - for (const thread of visible) { + for (const thread of rest) { const configLoaded = serverConfigs.has(thread.environmentId); const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); if (optimisticDrop?.key === threadKey) { @@ -732,6 +747,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt) : sortThreadsForSidebar(active); return { + botThreads: sortBotThreads(bots), pinnedThreads: optimisticDrop?.section !== "pinned" || optimisticDrop.order === null ? sortedPinned @@ -975,6 +991,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve unpinThread, confirmAndUnpinThread, setThreadAutoSettle, + setThreadStanding, turnThreadIntoProject, reorderPinnedThread, reorderActiveThread, @@ -1377,6 +1394,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const { workingShelfEnabled, + botThreads, pinnedThreads, draggableThreadKeys, activeReorderableThreadKeys, @@ -2745,8 +2763,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve autoSettleOptOut: supportsAutoSettleOptOut, snooze: configLoaded, pinning: configLoaded, + standing: + serverConfigs.get(thread.environmentId)?.environment.capabilities + .threadStanding === true, titleRegeneration: configLoaded, }, + isStanding: thread.standing !== null, snoozePresets, }), position, @@ -2763,6 +2785,28 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }); return; } + if ( + await runBotMenuAction({ + action: clicked.value, + threadRef, + thread, + setThreadStanding, + report: async (title, run) => { + const result = await run(); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + }, + }) + ) + return; if (clicked.value?.startsWith("snooze:")) { const preset = clicked.value === "snooze:custom" @@ -3388,7 +3432,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve {!isSearchingThreads && !hasProjectFolders && visibleDraftSessionCount === 0 && - pinnedThreads.length + + botThreads.length + + pinnedThreads.length + activeThreads.length + workingThreads.length + snoozedThreads.length === @@ -3429,6 +3474,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} ) : null} + {!isSearchingThreads ? ( + + ) : null} {!isSearchingThreads ? ( { + it("rings needs-you in the accent and failed in destructive", () => { + const needsYou = renderToStaticMarkup( + , + ); + expect(needsYou).toContain("ring-2"); + expect(needsYou).toContain("ring-rose-500/70"); + const failed = renderToStaticMarkup(); + expect(failed).toContain("ring-destructive/80"); + expect(renderToStaticMarkup()).not.toContain( + "ring-2", + ); + }); + + it("blinks only while running, and only when motion is allowed", () => { + expect( + renderToStaticMarkup(), + ).toContain("motion-safe:animate-bot-blink"); + expect(renderToStaticMarkup()).not.toContain( + "animate-bot-blink", + ); + }); + + it("draws every avatar and falls back for unknown ids", () => { + for (const avatarId of THREAD_STANDING_AVATAR_IDS) { + expect(renderToStaticMarkup()).toContain( + ")).toBe( + renderToStaticMarkup(), + ); + }); +}); diff --git a/apps/web/src/components/bots/BotAvatar.tsx b/apps/web/src/components/bots/BotAvatar.tsx new file mode 100644 index 0000000000000..ccbadb1d99d55 --- /dev/null +++ b/apps/web/src/components/bots/BotAvatar.tsx @@ -0,0 +1,275 @@ +import { + resolveThreadStandingAccent, + resolveThreadStandingAvatarId, + type ThreadStandingAccent, + type ThreadStandingAvatarId, +} from "@t3tools/contracts"; +import type { ReactNode } from "react"; + +import { cn } from "~/lib/utils"; + +/** + * Original robot heads drawn for T3 Code (no third-party art). Each is a + * 24×24 line drawing in currentColor so the accent and theme set its color; + * the eyes sit in one group so the running state can blink them. + */ +const FACE = ( + +); + +const AVATARS: Record< + ThreadStandingAvatarId, + { readonly head: ReactNode; readonly eyes: ReactNode } +> = { + bolt: { + head: ( + <> + {FACE} + + + + ), + eyes: ( + <> + + + + ), + }, + dish: { + head: ( + <> + {FACE} + + + + + ), + eyes: ( + <> + + + + ), + }, + visor: { + head: ( + <> + {FACE} + + + + + ), + eyes: ( + + ), + }, + cyclops: { + head: ( + <> + {FACE} + + + + ), + eyes: ( + <> + + + + ), + }, + periscope: { + head: ( + <> + {FACE} + + + + + ), + eyes: ( + <> + + + + ), + }, + twin: { + head: ( + <> + {FACE} + + + + + + ), + eyes: ( + <> + + + + ), + }, + sprout: { + head: ( + <> + {FACE} + + + + + + ), + eyes: ( + <> + + + + ), + }, + halo: { + head: ( + <> + {FACE} + + + + ), + eyes: ( + <> + + + ), + }, + grill: { + head: ( + <> + {FACE} + + + + + ), + eyes: ( + <> + + + + ), + }, + monocle: { + head: ( + <> + {FACE} + + + + + ), + eyes: ( + <> + + + + + ), + }, +}; + +/** Literal classes so Tailwind keeps them; tuned per theme for contrast on the sidebar. */ +export const BOT_ACCENT_CLASSES: Record< + ThreadStandingAccent, + { readonly text: string; readonly ring: string; readonly swatch: string } +> = { + sky: { + text: "text-sky-700 dark:text-sky-300", + ring: "ring-sky-500/70 dark:ring-sky-300/70", + swatch: "bg-sky-500 dark:bg-sky-300", + }, + violet: { + text: "text-violet-700 dark:text-violet-300", + ring: "ring-violet-500/70 dark:ring-violet-300/70", + swatch: "bg-violet-500 dark:bg-violet-300", + }, + emerald: { + text: "text-emerald-700 dark:text-emerald-300", + ring: "ring-emerald-500/70 dark:ring-emerald-300/70", + swatch: "bg-emerald-500 dark:bg-emerald-300", + }, + amber: { + text: "text-amber-700 dark:text-amber-300", + ring: "ring-amber-500/70 dark:ring-amber-300/70", + swatch: "bg-amber-500 dark:bg-amber-300", + }, + rose: { + text: "text-rose-700 dark:text-rose-300", + ring: "ring-rose-500/70 dark:ring-rose-300/70", + swatch: "bg-rose-500 dark:bg-rose-300", + }, + teal: { + text: "text-teal-700 dark:text-teal-300", + ring: "ring-teal-500/70 dark:ring-teal-300/70", + swatch: "bg-teal-500 dark:bg-teal-300", + }, + indigo: { + text: "text-indigo-700 dark:text-indigo-300", + ring: "ring-indigo-500/70 dark:ring-indigo-300/70", + swatch: "bg-indigo-500 dark:bg-indigo-300", + }, + orange: { + text: "text-orange-700 dark:text-orange-300", + ring: "ring-orange-500/70 dark:ring-orange-300/70", + swatch: "bg-orange-500 dark:bg-orange-300", + }, +}; + +export type BotAvatarState = "idle" | "running" | "needs-you" | "failed"; + +export function BotAvatar(props: { + readonly avatarId: string; + readonly accent: string; + readonly state?: BotAvatarState; + readonly size?: "sm" | "md" | "lg"; + readonly className?: string; +}) { + const avatar = AVATARS[resolveThreadStandingAvatarId(props.avatarId)]; + const accent = BOT_ACCENT_CLASSES[resolveThreadStandingAccent(props.accent)]; + const state = props.state ?? "idle"; + return ( + + ); +} diff --git a/apps/web/src/components/bots/BotPersonaDialog.tsx b/apps/web/src/components/bots/BotPersonaDialog.tsx new file mode 100644 index 0000000000000..63223549ef43f --- /dev/null +++ b/apps/web/src/components/bots/BotPersonaDialog.tsx @@ -0,0 +1,194 @@ +import { + THREAD_STANDING_ACCENTS, + THREAD_STANDING_AVATAR_IDS, + type ThreadStanding, + type ThreadStandingAccent, + type ThreadStandingAvatarId, +} from "@t3tools/contracts"; +import { useEffect, useId, useState } from "react"; +import { create } from "zustand"; + +import { cn } from "~/lib/utils"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { BotAvatar, BOT_ACCENT_CLASSES } from "./BotAvatar"; + +type Request = { + readonly initial: ThreadStanding; + readonly isNew: boolean; + readonly nonce: number; + readonly resolve: (persona: ThreadStanding | null) => void; +}; +let nextNonce = 0; +const useRequest = create<{ request: Request | null }>(() => ({ request: null })); + +/** Asks for a bot persona; resolves null when the user cancels. */ +export function requestBotPersona(input: { + readonly initial: ThreadStanding; + readonly isNew: boolean; +}): Promise { + useRequest.getState().request?.resolve(null); + return new Promise((resolve) => + useRequest.setState({ request: { ...input, nonce: nextNonce++, resolve } }), + ); +} + +function finish(persona: ThreadStanding | null) { + const request = useRequest.getState().request; + useRequest.setState({ request: null }); + request?.resolve(persona); +} + +/** A starting persona for a thread becoming a bot: its title, and a look picked from its id. */ +export function defaultBotPersona(thread: { readonly id: string; readonly title: string }) { + let hash = 0; + for (const char of thread.id) hash = (hash * 31 + char.charCodeAt(0)) >>> 0; + return { + name: thread.title.trim().replace(/\s+/g, " ").slice(0, 40) || "Bot", + role: null, + avatarId: THREAD_STANDING_AVATAR_IDS[hash % THREAD_STANDING_AVATAR_IDS.length]!, + accent: THREAD_STANDING_ACCENTS[(hash >>> 4) % THREAD_STANDING_ACCENTS.length]!, + } satisfies ThreadStanding; +} + +export function BotPersonaDialogHost() { + const request = useRequest((state) => state.request); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resolves any pending persona request promise with null when the dialog host unmounts + useEffect(() => () => finish(null), []); + return request ? : null; +} + +function BotPersonaDialog(props: { readonly request: Request }) { + const id = useId(); + const { initial, isNew } = props.request; + const [name, setName] = useState(initial.name); + const [role, setRole] = useState(initial.role ?? ""); + const [avatarId, setAvatarId] = useState(initial.avatarId); + const [accent, setAccent] = useState(initial.accent); + const trimmedName = name.trim().replace(/\s+/g, " "); + const trimmedRole = role.trim().replace(/\s+/g, " "); + return ( + { + if (!open) finish(null); + }} + > + +
{ + event.preventDefault(); + if (trimmedName.length === 0) return; + finish({ + name: trimmedName, + role: trimmedRole.length === 0 ? null : trimmedRole, + avatarId, + accent, + }); + }} + > + + {isNew ? "Make standing bot" : "Edit bot persona"} + + A standing bot is a long-lived lane. It lists under Bots, apart from pinned threads. + + + +
+
+ +
+
{trimmedName || "Bot"}
+
+ {trimmedRole || "No role line"} +
+
+
+
+ + setName(event.currentTarget.value)} + /> +
+
+ + setRole(event.currentTarget.value)} + /> +
+
+ Avatar +
+ {THREAD_STANDING_AVATAR_IDS.map((candidate) => ( + + ))} +
+
+
+ Accent +
+ {THREAD_STANDING_ACCENTS.map((candidate) => ( +
+
+
+
+ + + + +
+
+
+ ); +} diff --git a/apps/web/src/components/bots/botMenuActions.ts b/apps/web/src/components/bots/botMenuActions.ts new file mode 100644 index 0000000000000..27574e5ce492a --- /dev/null +++ b/apps/web/src/components/bots/botMenuActions.ts @@ -0,0 +1,34 @@ +import type { ScopedThreadRef, ThreadStanding } from "@t3tools/contracts"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; + +import { defaultBotPersona, requestBotPersona } from "./BotPersonaDialog"; + +/** Runs a bot menu action; returns false for any other action. */ +export async function runBotMenuAction(input: { + readonly action: string; + readonly threadRef: ScopedThreadRef; + readonly thread: Pick; + readonly setThreadStanding: ( + target: ScopedThreadRef, + standing: ThreadStanding | null, + ) => Promise; + readonly report: (title: string, run: () => Promise) => Promise; +}): Promise { + const { action, threadRef, thread } = input; + if (action === "make-ordinary") { + await input.report("Failed to make an ordinary thread", () => + input.setThreadStanding(threadRef, null), + ); + return true; + } + if (action !== "make-bot" && action !== "edit-bot") return false; + const persona = await requestBotPersona({ + initial: thread.standing ?? defaultBotPersona(thread), + isNew: thread.standing === null, + }); + if (persona === null) return true; + await input.report("Failed to save the bot persona", () => + input.setThreadStanding(threadRef, persona), + ); + return true; +} diff --git a/apps/web/src/components/bots/botPresence.test.ts b/apps/web/src/components/bots/botPresence.test.ts new file mode 100644 index 0000000000000..1db96abf47281 --- /dev/null +++ b/apps/web/src/components/bots/botPresence.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveBotPresence, sortBotThreads, splitStandingThreads } from "./botPresence"; + +describe("resolveBotPresence", () => { + it.each(["Pending Approval", "Awaiting Input", "Guest Request", "Plan Ready"] as const)( + "rings the avatar and badges the row when %s", + (label) => { + expect(resolveBotPresence({ label }, "Ops lane")).toEqual({ + avatarState: "needs-you", + line: label, + badge: "needs-you", + }); + }, + ); + + it("blinks while working and shows failure on its own ring", () => { + expect(resolveBotPresence({ label: "Working" }, null).avatarState).toBe("running"); + expect(resolveBotPresence({ label: "Connecting" }, null).avatarState).toBe("running"); + expect(resolveBotPresence({ label: "Failed" }, "Ops")).toEqual({ + avatarState: "failed", + line: "Failed", + badge: null, + }); + }); + + it("falls back to the role line when idle", () => { + expect(resolveBotPresence(null, "Daily digest")).toEqual({ + avatarState: "idle", + line: "Daily digest", + badge: null, + }); + expect(resolveBotPresence(null, null).line).toBeNull(); + expect(resolveBotPresence({ label: "Completed" }, null)).toEqual({ + avatarState: "idle", + line: "New reply", + badge: "unread", + }); + }); +}); + +describe("sortBotThreads", () => { + it("orders by persona name, case-insensitively, then id", () => { + const threads = [ + { id: "c", standing: { name: "zed" } }, + { id: "b", standing: { name: "Alpha" } }, + { id: "a", standing: { name: "alpha" } }, + ]; + expect(sortBotThreads(threads).map((thread) => thread.id)).toEqual(["a", "b", "c"]); + }); +}); + +describe("splitStandingThreads", () => { + it("sends bots to their own group whatever their pin, settle or snooze state", () => { + const persona = { name: "Ops" }; + const threads = [ + { id: "a", standing: null, pinnedAt: "2026-11-19T00:00:00Z" }, + { id: "b", standing: persona, pinnedAt: "2026-11-19T00:00:00Z" }, + { id: "c", standing: persona, settledOverride: "settled" }, + { id: "d", standing: persona, snoozedAt: "2026-11-19T00:00:00Z" }, + { id: "e", standing: null }, + ]; + const { bots, rest } = splitStandingThreads(threads); + expect(bots.map((thread) => thread.id)).toEqual(["b", "c", "d"]); + expect(rest.map((thread) => thread.id)).toEqual(["a", "e"]); + }); +}); diff --git a/apps/web/src/components/bots/botPresence.ts b/apps/web/src/components/bots/botPresence.ts new file mode 100644 index 0000000000000..fb640fba83378 --- /dev/null +++ b/apps/web/src/components/bots/botPresence.ts @@ -0,0 +1,54 @@ +import type { ThreadStatusPill } from "../Sidebar.logic"; +import type { BotAvatarState } from "./BotAvatar"; + +export interface BotPresence { + readonly avatarState: BotAvatarState; + /** Second line: what the bot is doing, or its role when there is nothing newer. */ + readonly line: string | null; + /** The trailing badge: a count-free dot for needs-you or unread. */ + readonly badge: "needs-you" | "unread" | null; +} + +const NEEDS_YOU = new Set(["Pending Approval", "Awaiting Input", "Guest Request", "Plan Ready"]); + +/** Maps the thread's status pill onto a bot's quieter vocabulary. */ +export function resolveBotPresence( + pill: Pick | null, + role: string | null | undefined, +): BotPresence { + const label = pill?.label ?? null; + if (label !== null && NEEDS_YOU.has(label)) + return { avatarState: "needs-you", line: label, badge: "needs-you" }; + if (label === "Working" || label === "Connecting") + return { avatarState: "running", line: label, badge: null }; + if (label === "Failed") return { avatarState: "failed", line: "Failed", badge: null }; + if (label === "Completed") + return { avatarState: "idle", line: role ?? "New reply", badge: "unread" }; + if (label === "Waiting") return { avatarState: "idle", line: "Waiting", badge: null }; + return { avatarState: "idle", line: role ?? null, badge: null }; +} + +/** Bots list alphabetically by persona name, so their places never move. */ +export function sortBotThreads< + T extends { readonly standing: { readonly name: string } | null; readonly id: string }, +>(threads: readonly T[]): T[] { + return threads.toSorted( + (left, right) => + (left.standing?.name ?? "").localeCompare(right.standing?.name ?? "", undefined, { + sensitivity: "base", + }) || left.id.localeCompare(right.id), + ); +} + +/** + * Splits standing bots out of the sidebar's thread list. Bots go to their own group whatever + * their pin, settle or snooze state; everything else continues to the ordinary sections. + */ +export function splitStandingThreads( + threads: readonly T[], +): { readonly bots: T[]; readonly rest: T[] } { + const bots: T[] = []; + const rest: T[] = []; + for (const thread of threads) (thread.standing != null ? bots : rest).push(thread); + return { bots, rest }; +} diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 22e02b228a24d..a92dd8d998aae 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -3,6 +3,7 @@ import { type EnvironmentId, type ScopedThreadRef, type ThreadId, + type ThreadStanding, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; @@ -43,6 +44,7 @@ import { cn } from "~/lib/utils"; import { textDirection } from "~/textDirection"; import { useClientSettings } from "../../hooks/useSettings"; import { GuestShareIndicator } from "./GuestShareControls"; +import { BotAvatar } from "../bots/BotAvatar"; interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; @@ -57,6 +59,8 @@ interface ChatHeaderProps { onNewThreadInProject: () => void; onOpenProjectSettings?: (() => void) | undefined; onFindInThread?: ((threadRef: ScopedThreadRef) => void) | undefined; + /** A standing bot shows who it is instead of the project/thread breadcrumb. */ + standing?: ThreadStanding | null | undefined; } function resolveRenameCommit(input: { @@ -82,6 +86,7 @@ export const ChatHeader = memo(function ChatHeader({ onNewThreadInProject, onOpenProjectSettings, onFindInThread, + standing, }: ChatHeaderProps) { const activeProjectName = activeProject?.isScratch ? "No project" : activeProject?.title; const activeProjectCwd = activeProject?.workspaceRoot ?? null; @@ -156,6 +161,8 @@ export const ChatHeader = memo(function ChatHeader({ parentThreadLink, interfaceFont, isRenamingTitle, + // A bot header has no breadcrumb list; reverting to an ordinary thread mounts it again. + standing != null, ]); const renameCommittedRef = useRef(false); const startRename = () => { @@ -246,6 +253,39 @@ export const ChatHeader = memo(function ChatHeader({ setRenaming(null); } }; + if (standing && renamingTitle === null) { + return ( +
+ + + {standing.role ? ( + + {standing.role} + + ) : null} + + {isServerThread ? : null} +
+ ); + } return (
void; + readonly onThreadActivate: (threadRef: ScopedThreadRef) => void; + readonly onContextMenu: ( + threadRef: ScopedThreadRef, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => void; +} + +/** + * Standing bots sit above Pinned as one-line rows: who the bot is and what it + * is doing. Branch, worktree, PR, model and time belong to work threads and + * stay off these rows; they live in the thread's details instead. + */ +export function SidebarBotsGroup( + props: BotRowHandlers & { + readonly threads: readonly EnvironmentThreadShell[]; + readonly activeThreadKey: string | null; + }, +) { + if (props.threads.length === 0) return null; + return ( +
+
+ Bots + +
+
    + {props.threads.map((thread) => { + const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + return ( + + ); + })} +
+
+ ); +} + +const SidebarBotRow = memo(function SidebarBotRow( + props: BotRowHandlers & { + readonly thread: EnvironmentThreadShell; + readonly threadKey: string; + readonly isActive: boolean; + }, +) { + const { thread, threadKey } = props; + const standing = thread.standing!; + const threadRef = scopeThreadRef(thread.environmentId, thread.id); + const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); + const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); + const presence = resolveBotPresence( + resolveThreadStatusPill({ thread: { ...thread, lastVisitedAt } }), + standing.role, + ); + const accent = BOT_ACCENT_CLASSES[standing.accent]; + const handleKeyDown = (event: KeyboardEvent) => { + if (event.target !== event.currentTarget) return; + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + props.onThreadActivate(threadRef); + }; + return ( +
  • +
    props.onThreadClick(event, threadRef)} + onKeyDown={handleKeyDown} + onContextMenu={(event) => { + event.preventDefault(); + props.onContextMenu( + threadRef, + { x: event.clientX, y: event.clientY }, + contextMenuSourceOf(event), + ); + }} + > + + + {standing.name} + + {presence.line ? ( + + {presence.line} + + ) : ( + + )} + {presence.badge ? ( + + ) : null} +
    +
  • + ); +}); diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index 12234c2d70a28..bbb7808ecbf35 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -105,3 +105,27 @@ it("offers inbox routing only on capable environments and retains ordinary opera expect(threadRoutingUpdateFromMenuAction("attention:FYI")).toEqual({ attentionKind: "FYI" }); expect(threadRoutingUpdateFromMenuAction("rename")).toBeNull(); }); + +describe("standing bot menu items", () => { + const ids = (state: ThreadActionMenuState) => + buildThreadActionMenuItems(state).map((item) => item.id); + + it("offers Make standing bot only when the environment supports it", () => { + expect(ids(baseState)).not.toContain("make-bot"); + const supported = { ...baseState, supports: { ...baseState.supports, standing: true } }; + expect(ids(supported)).toContain("make-bot"); + expect(ids(supported)).not.toContain("make-ordinary"); + }); + + it("offers editing and reverting on a bot, independent of pinning", () => { + const bot = { + ...baseState, + isPinned: true, + isStanding: true, + supports: { ...baseState.supports, standing: true }, + }; + const items = ids(bot); + expect(items).toEqual(expect.arrayContaining(["unpin", "edit-bot", "make-ordinary"])); + expect(items).not.toContain("make-bot"); + }); +}); diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 328c99930d0bb..141e117f89b01 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -15,6 +15,9 @@ export type ThreadActionMenuId = | "project-settings" | "pin" | "unpin" + | "make-bot" + | "edit-bot" + | "make-ordinary" | "settle" | "unsettle" | "auto-settle" @@ -82,6 +85,8 @@ export interface ThreadActionMenuState { readonly isActive: boolean; } | null; readonly isPinned: boolean; + /** A standing bot thread; independent of pinning. */ + readonly isStanding?: boolean; readonly isSettled: boolean; readonly autoSettleEnabled: boolean; readonly isSnoozed: boolean; @@ -95,6 +100,7 @@ export interface ThreadActionMenuState { readonly autoSettleOptOut: boolean; readonly snooze: boolean; readonly pinning: boolean; + readonly standing?: boolean; readonly titleRegeneration: boolean; }; readonly snoozePresets: ReadonlyArray; @@ -166,6 +172,14 @@ export function buildThreadActionMenuItems( : { id: "pin" as const, label: "Pin thread", icon: "pin" }, ] : []), + ...(state.supports.standing + ? state.isStanding + ? [ + { id: "edit-bot" as const, label: "Edit bot persona…", icon: "bot" }, + { id: "make-ordinary" as const, label: "Make ordinary thread", icon: "message-square" }, + ] + : [{ id: "make-bot" as const, label: "Make standing bot…", icon: "bot" }] + : []), ...(state.supports.settlement ? [ state.isSettled diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 22c0c575b4c84..ac964da10c6e6 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -9,6 +9,14 @@ const ICON_PATHS: Record()( + "ThreadStandingUnsupportedError", + { + environmentId: EnvironmentId, + threadId: ThreadId, + }, +) { + override get message(): string { + return "This environment's server does not support standing bot threads yet. Update the server to use it."; + } +} + export class ThreadPinningUnsupportedError extends Schema.TaggedError()( "ThreadPinningUnsupportedError", { @@ -300,6 +314,9 @@ export function useThreadActions() { const setThreadAutoSettleMutation = useOrchestrationCommand(threadEnvironment.setAutoSettle, { reportFailure: false, }); + const setThreadStandingMutation = useOrchestrationCommand(threadEnvironment.setStanding, { + reportFailure: false, + }); const reorderPinnedThreadMutation = useOrchestrationCommand(threadEnvironment.reorderPin, { reportFailure: false, }); @@ -746,6 +763,23 @@ export function useThreadActions() { }); }; + const setThreadStanding = async (target: ScopedThreadRef, standing: ThreadStanding | null) => { + if (!readEnvironmentSupportsThreadStanding(target.environmentId)) { + return AsyncResult.failure( + Cause.fail( + new ThreadStandingUnsupportedError({ + environmentId: target.environmentId, + threadId: target.threadId, + }), + ), + ); + } + return setThreadStandingMutation({ + environmentId: target.environmentId, + input: { threadId: target.threadId, standing }, + }); + }; + const sendPin = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { if (!readEnvironmentServerConfigLoaded(target.environmentId)) { return AsyncResult.failure( @@ -1029,6 +1063,7 @@ export function useThreadActions() { reorderActiveThread, markThreadUnread, setThreadAutoSettle, + setThreadStanding, turnThreadIntoProject: (target: ScopedThreadRef) => createProjectFromThread({ environmentId: target.environmentId, diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 771c714b1ff8a..152216f5c5b52 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -225,6 +225,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil compositor updates discrete frames instead of every vsync. */ --animate-status-pulse: status-pulse 2s infinite; --animate-status-ping: status-ping 2s infinite; + /* A running bot blinks once every 4s: two discrete frames, nothing in between. */ + --animate-bot-blink: bot-blink 4s step-end infinite; /* Stash pulses hold a highlight for 1.2s; the row then eases back over 200ms, the count snaps. The row alternates two identical keyframes so each stash restarts it without a remount. */ --animate-stash-pulse-row: stash-pulse-row 1400ms; @@ -329,6 +331,16 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil color: var(--color-primary); } } + @keyframes bot-blink { + 0%, + 94% { + transform: scaleY(1); + } + 95%, + 98% { + transform: scaleY(0.15); + } + } @keyframes status-pulse { 0%, 40% { diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index da499d623f6ee..5b8f3044d6ab0 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -17,6 +17,7 @@ import { APP_DISPLAY_NAME, APP_VERSION } from "../branding"; import { AppSidebarLayout } from "../components/AppSidebarLayout"; import { CommandPalette } from "../components/CommandPalette"; import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog"; +import { BotPersonaDialogHost } from "../components/bots/BotPersonaDialog"; import { GuestShareDialogHost } from "../components/chat/GuestShareControls"; import { UseInAnotherAppDialogHost } from "../components/mcp/UseInAnotherAppDialog"; import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog"; @@ -193,6 +194,7 @@ function RootRouteBranch() { + diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 27168e1ce7893..68e2a668bd5ac 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -375,6 +375,13 @@ export function readEnvironmentSupportsAutoSettleOptOut(environmentId: Environme ); } +export function readEnvironmentSupportsThreadStanding(environmentId: EnvironmentId): boolean { + return ( + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities + .threadStanding === true + ); +} + export function readEnvironmentThreadRefs( environmentId: EnvironmentId, ): ReadonlyArray { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 7030e105577ad..82a05f75011d3 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -585,6 +585,21 @@ export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* ( }); }); +export interface SetThreadStandingInput extends ThreadCommandInput { + /** The bot persona, or null to make the thread ordinary again. */ + readonly standing: import("@t3tools/contracts").ThreadStanding | null; +} +export const setThreadStanding = Effect.fn("EnvironmentCommands.setThreadStanding")(function* ( + input: SetThreadStandingInput, +) { + return yield* dispatch({ + type: "thread.standing.set", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + standing: input.standing, + }); +}); + export interface SetThreadAutoSettleInput extends ThreadCommandInput { readonly enabled: boolean; } diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 6bc914b8572fd..09e793c702f00 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -16,6 +16,7 @@ import type { RunId, ThreadId, } from "@t3tools/contracts"; +import { resolveThreadStanding } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; @@ -186,6 +187,8 @@ export interface EnvironmentThreadShell { readonly snoozedAt: string | null; readonly limitRecovery?: import("@t3tools/contracts").OrchestrationV2LimitRecovery | null; readonly pinnedAt: string | null; + /** Persona when this thread is a standing bot; independent of pinning. */ + readonly standing: import("@t3tools/contracts").ThreadStanding | null; readonly autoSettleDisabledAt?: string | null; readonly pinOrderKey: string | null; readonly activeOrderKey: string | null; @@ -341,6 +344,7 @@ export function presentThreadShell( snoozedAt: nullableIso(thread.snoozedAt ?? null), limitRecovery: thread.limitRecovery ?? null, pinnedAt: nullableIso(thread.pinnedAt ?? null), + standing: resolveThreadStanding(thread.standing), autoSettleDisabledAt: nullableIso(thread.autoSettleDisabledAt ?? null), pinOrderKey: thread.pinOrderKey ?? null, activeOrderKey: thread.activeOrderKey ?? null, diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 37da408a1c35b..b513380341a10 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -323,6 +323,7 @@ export function applyOrchestrationV2ProjectionEvent( // Visited tracking and tags are not activity: skip the updatedAt bump. case "thread.visited": case "thread.tags-updated": + case "thread.standing-updated": case "thread.marked-unread": return { ...projection, thread: event.payload }; case "thread.visit-recorded": diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index e28d8aa90899a..36cd01353a2bc 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -52,6 +52,7 @@ import { reorderPinnedThread, reorderActiveThread, setThreadAutoSettle, + setThreadStanding, settleThread, snoozeThread, startThreadTurn, @@ -251,6 +252,12 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency, }), + setStanding: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:set-standing", + execute: setThreadStanding, + scheduler, + concurrency, + }), reorderActive: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:reorder-active", execute: reorderActiveThread, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 9bdabab1d9ce0..a04719df3d151 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -132,6 +132,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ usagePriceOverrides: Schema.optionalKey(Schema.Boolean), usageModelAliases: Schema.optionalKey(Schema.Boolean), threadPinning: Schema.optionalKey(Schema.Boolean), + /** Server understands thread.standing.set and exposes `standing` on threads. Clients hide + the bot actions on servers without it. */ + threadStanding: Schema.optionalKey(Schema.Boolean), threadPinReorder: Schema.optionalKey(Schema.Boolean), threadActiveReorder: Schema.optionalKey(Schema.Boolean), threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7087bc252e443..392b256b6e4b2 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -48,6 +48,7 @@ export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; export * from "./threadSearch.ts"; export * from "./threadTags.ts"; +export * from "./threadStanding.ts"; export * from "./threadTitle.ts"; export * from "./t3ProjectFile.ts"; export * from "./editor.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 3a8e79449e387..bdb6690021df9 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -53,6 +53,7 @@ import { AuthMcpClientAccess } from "./auth.ts"; import { ChatAttachment } from "./chatAttachment.ts"; import { ThreadGuestShare } from "./guestShare.ts"; import { StoredThreadTags, ThreadTag } from "./threadTags.ts"; +import { StoredThreadStanding, ThreadStanding } from "./threadStanding.ts"; import { ThreadTitleRegenerationOutcome } from "./threadTitle.ts"; import { OrchestrationSearchThreadsInput, @@ -523,6 +524,8 @@ export const OrchestrationV2AppThread = Schema.Struct({ activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), /** Absent on threads written before tags existed; read as empty. */ tags: Schema.optional(StoredThreadTags), + /** Bot persona for a standing thread; absent or null is an ordinary thread. Independent of pinning. */ + standing: Schema.optional(StoredThreadStanding), lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), @@ -2025,6 +2028,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([ "thread.pin-reordered", "thread.active-reordered", "thread.tags-updated", + "thread.standing-updated", "thread.visited", "thread.marked-unread", "thread.metadata-updated", @@ -2294,6 +2298,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), /** Absent on threads written before tags existed; read as empty. */ tags: Schema.optional(StoredThreadTags), + /** Bot persona for a standing thread; absent or null is an ordinary thread. Independent of pinning. */ + standing: Schema.optional(StoredThreadStanding), lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), opens: Schema.optional(LenientThreadOpens), titleRegeneration: Schema.optional( @@ -2341,11 +2347,15 @@ export function isLiveSubagentShell( * count every such thread, so the server and clients share this one rule. */ export function isOlderSettledThreadShell( - thread: Pick, + thread: Pick & { + readonly standing?: unknown; + }, beforeMs: number, ): boolean { return ( isListedThreadLineage(thread.lineage) && + // Standing bots always stream, so the Bots group never loses one to the Settled shelf. + thread.standing == null && thread.settledOverride === "settled" && thread.settledAt !== null && DateTime.toEpochMillis(thread.settledAt) < beforeMs @@ -2993,6 +3003,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ "thread.pin-reordered", "thread.active-reordered", "thread.tags-updated", + "thread.standing-updated", "thread.visited", "thread.marked-unread", "thread.pull-request-synced", @@ -3260,6 +3271,13 @@ export const OrchestrationV2Command = Schema.Union([ commandId: CommandId, threadId: ThreadId, }), + Schema.Struct({ + type: Schema.Literal("thread.standing.set"), + commandId: CommandId, + threadId: ThreadId, + /** The persona to show, or null to make it an ordinary thread again. */ + standing: Schema.NullOr(ThreadStanding), + }), Schema.Struct({ type: Schema.Literal("thread.tag.set"), commandId: CommandId, diff --git a/packages/contracts/src/threadMetadataMcp.ts b/packages/contracts/src/threadMetadataMcp.ts index 7057a3fdd9c83..95aca7489db33 100644 --- a/packages/contracts/src/threadMetadataMcp.ts +++ b/packages/contracts/src/threadMetadataMcp.ts @@ -9,6 +9,7 @@ import { } from "./baseSchemas.ts"; import { ThreadDecisionAsk, ThreadInbox, ThreadInboxRoutingPatch } from "./threadInbox.ts"; import { ThreadLinkedPullRequest } from "./threadPullRequest.ts"; +import { StoredThreadStanding, ThreadStanding } from "./threadStanding.ts"; import { ThreadTitleRegeneration } from "./threadTitle.ts"; export function hasOnlyPairedSurrogates(value: string): boolean { @@ -47,6 +48,7 @@ export const ThreadMetadataMcpAction = Schema.Literals([ "route", "request_decision", "resolve_decision", + "set_standing", ]); export type ThreadMetadataMcpAction = typeof ThreadMetadataMcpAction.Type; @@ -56,14 +58,21 @@ export const ThreadMetadataMcpUpdateInput = Schema.Struct({ title: Schema.optional(ThreadMetadataTitle), inboxRouting: Schema.optional(ThreadInboxRoutingPatch), decision: Schema.optional(ThreadDecisionAsk), + standing: Schema.optional( + Schema.NullOr(ThreadStanding).annotate({ + description: + "Required only when action is set_standing: a bot persona ({name, role?, avatarId, accent}) makes this a standing bot thread; null makes it an ordinary thread. Independent of pinning.", + }), + ), clientRequestId: Schema.optional(ThreadMetadataClientRequestId), }).check( Schema.makeFilter((input) => (input.action === "rename") === (input.title !== undefined) && (input.action === "route") === (input.inboxRouting !== undefined) && - (input.action === "request_decision") === (input.decision !== undefined) + (input.action === "request_decision") === (input.decision !== undefined) && + (input.action === "set_standing") === (input.standing !== undefined) ? true - : "rename requires title; route requires inboxRouting; request_decision requires decision; other actions reject those fields.", + : "rename requires title; route requires inboxRouting; request_decision requires decision; set_standing requires standing; other actions reject those fields.", ), ); export type ThreadMetadataMcpUpdateInput = typeof ThreadMetadataMcpUpdateInput.Type; @@ -77,6 +86,7 @@ export const ThreadMetadataMcpUpdateResult = Schema.Struct({ titleRegeneration: Schema.NullOr(ThreadTitleRegeneration), linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest), inbox: Schema.optionalKey(ThreadInbox), + standing: Schema.optionalKey(StoredThreadStanding), updatedAt: IsoDateTime, }); export type ThreadMetadataMcpUpdateResult = typeof ThreadMetadataMcpUpdateResult.Type; diff --git a/packages/contracts/src/threadStanding.test.ts b/packages/contracts/src/threadStanding.test.ts new file mode 100644 index 0000000000000..b650f03d0f5a3 --- /dev/null +++ b/packages/contracts/src/threadStanding.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vite-plus/test"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; + +import { isOlderSettledThreadShell } from "./orchestrationV2.ts"; + +import { resolveThreadStanding, StoredThreadStanding } from "./threadStanding.ts"; + +describe("thread standing", () => { + const decodeStored = Schema.decodeUnknownSync(StoredThreadStanding); + + it("keeps a newer peer's unknown avatar and accent, then resolves them to built-ins", () => { + const stored = decodeStored({ name: "Synthetic", avatarId: "future", accent: "chartreuse" }); + expect(stored).toEqual({ name: "Synthetic", avatarId: "future", accent: "chartreuse" }); + expect(resolveThreadStanding(stored)).toEqual({ + name: "Synthetic", + role: null, + avatarId: "bolt", + accent: "sky", + }); + }); + + it("reads a malformed value as an ordinary thread", () => { + expect(decodeStored({ name: 3 })).toBeNull(); + expect(resolveThreadStanding(undefined)).toBeNull(); + expect(resolveThreadStanding({ name: " ", avatarId: "bolt", accent: "sky" })).toBeNull(); + }); +}); + +describe("isOlderSettledThreadShell", () => { + it("never treats a standing bot as an older settled shell", () => { + const settled = { + lineage: { relationshipToParent: null, sideChat: false } as never, + settledOverride: "settled" as const, + settledAt: DateTime.makeUnsafe("2026-01-01T00:00:00Z"), + }; + const later = Date.parse("2026-02-01T00:00:00Z"); + expect(isOlderSettledThreadShell(settled, later)).toBe(true); + expect( + isOlderSettledThreadShell( + { ...settled, standing: { name: "Ops", avatarId: "bolt", accent: "sky" } }, + later, + ), + ).toBe(false); + }); +}); diff --git a/packages/contracts/src/threadStanding.ts b/packages/contracts/src/threadStanding.ts new file mode 100644 index 0000000000000..042c7b08e1ecd --- /dev/null +++ b/packages/contracts/src/threadStanding.ts @@ -0,0 +1,99 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** + * A standing thread is a long-lived bot lane (Lead, a designer, a CTO) rather + * than a unit of work. It is independent of pinning: pinning is the user's + * watch list, standing is what the thread is. + */ + +/** Built-in avatars clients ship. Unknown ids from a newer peer fall back to the first one. */ +export const THREAD_STANDING_AVATAR_IDS = [ + "bolt", + "dish", + "visor", + "cyclops", + "periscope", + "twin", + "sprout", + "halo", + "grill", + "monocle", +] as const; +export type ThreadStandingAvatarId = (typeof THREAD_STANDING_AVATAR_IDS)[number]; + +/** Named accents; clients map each to theme-tuned colors for light and dark. */ +export const THREAD_STANDING_ACCENTS = [ + "sky", + "violet", + "emerald", + "amber", + "rose", + "teal", + "indigo", + "orange", +] as const; +export type ThreadStandingAccent = (typeof THREAD_STANDING_ACCENTS)[number]; + +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, + ), + ); + +/** What a client or tool may write. */ +export const ThreadStanding = Schema.Struct({ + name: singleLine(40), + /** One-line description shown under the name when the bot has nothing newer to say. */ + role: Schema.optional(Schema.NullOr(singleLine(80))), + avatarId: Schema.Literals(THREAD_STANDING_AVATAR_IDS), + accent: Schema.Literals(THREAD_STANDING_ACCENTS), +}); +export type ThreadStanding = typeof ThreadStanding.Type; + +/** + * Standing read back from storage or a peer. Avatar and accent stay plain + * strings so a newer peer's ids never fail a whole thread; a value that does + * not decode at all reads as an ordinary thread. + */ +export const StoredThreadStanding = Schema.NullOr( + Schema.Struct({ + name: Schema.String, + role: Schema.optional(Schema.NullOr(Schema.String)), + avatarId: Schema.String, + accent: Schema.String, + }), +).pipe(Schema.catchDecoding(() => Effect.succeedSome(null))); +export type StoredThreadStanding = typeof StoredThreadStanding.Type; + +export function resolveThreadStandingAvatarId(avatarId: string): ThreadStandingAvatarId { + return (THREAD_STANDING_AVATAR_IDS as readonly string[]).includes(avatarId) + ? (avatarId as ThreadStandingAvatarId) + : THREAD_STANDING_AVATAR_IDS[0]; +} + +export function resolveThreadStandingAccent(accent: string): ThreadStandingAccent { + return (THREAD_STANDING_ACCENTS as readonly string[]).includes(accent) + ? (accent as ThreadStandingAccent) + : THREAD_STANDING_ACCENTS[0]; +} + +/** A stored standing value with unknown avatar and accent ids mapped to built-ins. */ +export function resolveThreadStanding( + stored: StoredThreadStanding | undefined, +): ThreadStanding | null { + if (stored == null) return null; + const name = stored.name.trim(); + if (name.length === 0) return null; + const role = stored.role?.trim() ?? ""; + return { + name, + role: role.length === 0 ? null : role, + avatarId: resolveThreadStandingAvatarId(stored.avatarId), + accent: resolveThreadStandingAccent(stored.accent), + }; +} diff --git a/third-party-licenses.config.json b/third-party-licenses.config.json index 66eed772bebbf..374cf26ee53bb 100644 --- a/third-party-licenses.config.json +++ b/third-party-licenses.config.json @@ -1,5 +1,20 @@ { "customNotices": [ + { + "bundles": ["desktop", "web"], + "license": "MIT", + "name": "Standing bot avatars", + "sourceUrl": "https://github.com/nullStack65/t3code/blob/main/apps/web/src/components/bots/BotAvatar.tsx", + "generatedNotices": [ + { + "licenseId": "MIT", + "copyrights": ["Copyright (c) 2026 T3 Tools Inc."], + "preamble": [ + "The standing bot avatars in apps/web/src/components/bots/BotAvatar.tsx are original line drawings made for this project. They copy no third-party avatar set, icon pack or character art, and ship under this repository's MIT license." + ] + } + ] + }, { "name": "opencode Office viewers", "bundles": ["web"],