Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ export const make = Effect.gen(function* () {
usagePriceOverrides: true,
usageModelAliases: true,
threadPinning: true,
threadStanding: true,
threadPinReorder: true,
threadActiveReorder: true,
threadAutoSettleOptOut: true,
Expand Down
22 changes: 18 additions & 4 deletions apps/server/src/mcp/ThreadMetadataMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,18 @@ function metadataCommand(input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly update: ThreadMetadataMcpUpdateInput;
}): Extract<OrchestrationV2Command, { readonly type: "thread.metadata.update" }> {
}): 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",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/mcp/toolkits/project/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
clampedPositiveInt,
InboxChoiceParameter,
ThreadInboxRoutingPatch,
ThreadStanding,
NonNegativeInt,
ModelSelection,
TrimmedNonEmptyString,
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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":
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 7 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ export type ProjectionSettlementCandidate = Pick<
| "settledOverride"
| "pinnedAt"
| "autoSettleDisabledAt"
| "standing"
| "snoozedUntil"
| "snoozedAt"
| "latestRunId"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -2398,6 +2402,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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":
Expand Down Expand Up @@ -3218,6 +3223,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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" &&
Expand Down Expand Up @@ -7841,6 +7847,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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.
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/orchestration-v2/ThreadSettlementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
29 changes: 29 additions & 0 deletions apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
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":
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/relay/AgentAwarenessRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ function shouldPublishAgentAwarenessEvent(
case "thread.pin-reordered":
case "thread.active-reordered":
case "thread.tags-updated":
case "thread.standing-updated":
case "thread.visited":
case "thread.visit-recorded":
case "thread.marked-unread":
Expand Down
34 changes: 33 additions & 1 deletion apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ import {
shouldRefocusComposerOnWindowFocus,
hasCompactableConversation,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
import { useComposerHandleContext } from "../composerHandleContext";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { appAtomRegistry } from "../rpc/atomRegistry";
Expand Down Expand Up @@ -441,6 +441,20 @@ const DismissedFallbackWindowSchema = Schema.NullOr(Schema.String);

const ignoreComposerFocus = () => {};

/** 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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -3385,6 +3416,7 @@ export default function ChatView(props: ChatViewProps) {
? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }
: {})}
{...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}
standing={activeStanding}
/>
</header>
)}
Expand Down
Loading
Loading