Skip to content
Draft
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
11 changes: 9 additions & 2 deletions apps/mobile/src/features/threads/thread-list-v2-items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
} from "@t3tools/client-runtime/state/models";
import {
AuthOrchestrationOperateScope,
isStandingThreadRoot,
type EnvironmentId,
type EnvironmentMachineKind,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -943,6 +944,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
!useEnvironmentScopeDenied(thread.environmentId, AuthOrchestrationOperateScope) &&
!canOperateThread;
const canShareWithGuest = useCanShareWithGuest(thread.environmentId);
const isStandingRoot = isStandingThreadRoot(thread);
const navigation = useNavigation();
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
Expand Down Expand Up @@ -1181,7 +1183,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
nested,
direct: [
...direct,
localized(CARD_MENU_ACTIONS[0]!),
{
...localized(CARD_MENU_ACTIONS[0]!),
attributes: { disabled: isStandingRoot },
},
...(swipeActions.secondary === "snooze"
? [
{
Expand All @@ -1208,6 +1213,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
autoSettleMenuItems,
canShareWithGuest,
canUnsettle,
isStandingRoot,
pinMenuItems,
props.settlementSupported,
reorderMenuItems,
Expand Down Expand Up @@ -1372,7 +1378,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[gt, handleMenuAction, snoozePresetActions, swipeActions.secondary, thread.title],
);
const canSwipe =
canOperateThread || (triageOnly && TRIAGE_MENU_ACTION_IDS.has(swipeActions.primary));
(canOperateThread || (triageOnly && TRIAGE_MENU_ACTION_IDS.has(swipeActions.primary))) &&
!(swipeActions.primary === "settle" && isStandingRoot);
const swipeAccessibilityHint = !canSwipe
? gt("Opens the thread")
: secondaryAction === null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2459,6 +2459,94 @@ it.effect("replays a thread.create receipt without changing the thread", () =>
}).pipe(Effect.provide(layerTest)),
);

it.effect.each(["thread.settle", "thread.auto-settle"] as const)(
"%s refuses a standing root without events, allows its persona child and permits retirement",
(type) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const projections = yield* ProjectionStore.ProjectionStoreV2;
const events = yield* EventSink.EventSinkV2;
const threadId = ThreadId.make("thread:standing-root");
yield* orchestrator.dispatch({
type: "thread.create",
commandId: CommandId.make("standing-root:create"),
threadId,
projectId: ProjectId.make("project:standing-settle"),
title: "Role thread",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdBy: "user",
creationSource: "web",
});
yield* orchestrator.dispatch({
type: "thread.standing.set",
commandId: CommandId.make("standing-root:persona"),
threadId,
standing: { name: "Role", avatarId: "bolt", accent: "sky" },
});
const before = yield* projections.getThread(threadId);
const beforeSequence = yield* orchestrator.getThreadEventSequence(threadId);
const commandId = CommandId.make("standing-root:settle");
const refused = yield* orchestrator
.dispatch({ type, commandId, threadId, snapshotAt: before.updatedAt })
.pipe(Effect.flip);
assert.equal(refused._tag, "OrchestratorDispatchError");
assert.include(
"cause" in refused ? String(refused.cause) : "",
"Clear its standing persona before settling",
);
assert.deepEqual(yield* projections.getThread(threadId), before);
assert.equal(yield* orchestrator.getThreadEventSequence(threadId), beforeSequence);
assert.deepEqual(yield* events.readByCommandId({ commandId }).pipe(Stream.runCollect), []);

const childId = ThreadId.make("thread:standing-child");
yield* projections.apply({
id: EventId.make("standing-child:create"),
type: "thread.created",
threadId: childId,
occurredAt: before.updatedAt,
payload: {
...before,
id: childId,
lineage: {
parentThreadId: threadId,
rootThreadId: threadId,
relationshipToParent: "fork",
},
},
});
yield* orchestrator.dispatch({
type,
commandId: CommandId.make("standing-child:settle"),
threadId: childId,
snapshotAt: before.updatedAt,
});
const child = yield* projections.getThread(childId);
assert.deepEqual(child.standing, before.standing);
assert.equal(child.settledOverride, "settled");

yield* orchestrator.dispatch({
type: "thread.standing.set",
commandId: CommandId.make("standing-root:retire"),
threadId,
standing: null,
});
const retired = yield* projections.getThread(threadId);
yield* orchestrator.dispatch({
type,
commandId: CommandId.make("standing-root:settle-retired"),
threadId,
snapshotAt: retired.updatedAt,
});
const settled = yield* projections.getThread(threadId);
assert.equal(settled.settledOverride, "settled");
assert.isNull(settled.deletedAt);
}).pipe(Effect.provide(layerTest)),
);

it.effect("explicit settle clears snooze atomically and stays idempotent after re-snoozing", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
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 @@ -9,6 +9,7 @@ import type {
} from "@t3tools/contracts";
import {
inboxAfterStandingSet,
isStandingThreadRoot,
makeThreadInbox,
nextFounderSeenMessage,
nextFounderVisits,
Expand Down Expand Up @@ -5613,6 +5614,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
}
if (command.type === "thread.settle") {
if (isStandingThreadRoot(thread)) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause:
"Standing role threads cannot be settled. Clear its standing persona before settling.",
});
}
const projection = yield* loadProjectionForCommand(
command,
["runs", "runtimeRequests", "providerThreads", "turnItems"],
Expand Down
8 changes: 6 additions & 2 deletions apps/server/src/orchestration-v2/ThreadManagementService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as SecureRandom from "effect/crypto/SecureRandom";
import { BACKGROUND_WAIT_STALE_MINUTES, ThreadRedirectError } from "@t3tools/contracts";
import {
BACKGROUND_WAIT_STALE_MINUTES,
isStandingThreadRoot,
ThreadRedirectError,
} from "@t3tools/contracts";
import { staleTimeoutMs } from "./waitStaleness.ts";
import type {
OrchestrationV2SearchThreadInput,
Expand Down Expand Up @@ -1561,7 +1565,7 @@ const make = Effect.gen(function* () {
"orchestrationV2.threadManagement.settleThread",
)(function* (input) {
const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null;
if (shell != null && shell.activeRunId !== null) {
if (shell != null && shell.activeRunId !== null && !isStandingThreadRoot(shell)) {
yield* settleAfterRun({
projectId: shell.projectId,
threadId: shell.id,
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,16 @@ describe("settlesFinishedAgentWork", () => {
}),
),
).toBe(false);
const child = finished("completed", {
standing: { name: "Ops", role: null, avatarId: "bolt", accent: "sky" },
lineage: {
parentThreadId: ThreadId.make("role-root"),
rootThreadId: ThreadId.make("role-root"),
relationshipToParent: "subagent",
},
});
expect(ThreadSettlementService.settlesFinishedAgentWork(child)).toBe(true);
expect(ThreadSettlementService.isAutoSettlementCandidate(child, NOW_MS)).toBe(true);
expect(ThreadSettlementService.settlesFinishedAgentWork(shell({ status: "completed" }))).toBe(
false,
);
Expand Down
8 changes: 4 additions & 4 deletions apps/server/src/orchestration-v2/ThreadSettlementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
import {
CommandId,
isDelegatedAppThread,
isStandingThreadRoot,
isOrchestrationV2WorkActive,
type ThreadId,
type OrchestrationV2DomainEvent,
Expand Down Expand Up @@ -191,10 +192,10 @@ function agentBackgroundWorkPending(
export function settlesFinishedAgentWork(
thread: Pick<
ProjectionStore.ProjectionSettlementCandidate,
"inbox" | "status" | "pendingBackgroundTasks" | "standing"
"inbox" | "status" | "pendingBackgroundTasks" | "standing" | "lineage"
>,
): boolean {
if (thread.standing != null || thread.inbox?.audience !== "agent-only") return false;
if (isStandingThreadRoot(thread) || thread.inbox?.audience !== "agent-only") return false;
// An unattributed conversation uses Agents for routing without becoming autonomous work.
if (thread.inbox.origin === null) return false;
if (!FINISHED_AGENT_RUN_STATUSES.has(thread.status)) return false;
Expand All @@ -213,8 +214,7 @@ export function isAutoSettlementCandidate(
return false;
}
if (thread.inbox?.audience === "agent-only" && thread.status === "failed") return false;
// A standing bot is a long-lived lane, never finished work.
if (thread.standing != null) return false;
if (isStandingThreadRoot(thread)) 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
2 changes: 2 additions & 0 deletions apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { m } from "../i18n/messages";
import { attachSidebarTree } from "../lib/sidebarTree";
import {
effectiveInboxFilter,
isStandingThreadRoot,
isHiddenFromFounder,
staysActiveWhileWorking,
type EnvironmentId,
Expand Down Expand Up @@ -2908,6 +2909,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
AuthOrchestrationOperateScope,
),
canTriage: threadTriagePermitted(threadRef.environmentId),
canSettle: !isStandingThreadRoot(thread),
branch: thread.branch ?? null,
// An archived project is not a filter choice.
projectFilter:
Expand Down
3 changes: 3 additions & 0 deletions apps/web/src/components/sidebar/SidebarThreadRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environ
import { toServerClock } from "@t3tools/client-runtime/clock";
import {
AuthOrchestrationOperateScope,
isStandingThreadRoot,
type ContextMenuSource,
type EnvironmentId,
type EnvironmentMachineKind,
Expand Down Expand Up @@ -1562,6 +1563,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
type="button"
aria-label={gt("Settle thread")}
onClick={handleSettleClick}
disabled={isStandingThreadRoot(thread)}
onPointerDown={handleActionPointerDown}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 -mr-2 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-any-hover/sidebar-row:pointer-events-auto group-any-hover/sidebar-row:opacity-100",
Expand Down Expand Up @@ -1772,6 +1774,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
type="button"
aria-label={gt("Settle thread")}
onClick={handleSettleClick}
disabled={isStandingThreadRoot(thread)}
onPointerDown={handleActionPointerDown}
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/components/threadActionMenu.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ const baseState: ThreadActionMenuState = {
};

describe("buildThreadActionMenuItems", () => {
it("disables settling when the thread is a standing root while keeping un-settle available", () => {
const items = buildThreadActionMenuItems({ ...baseState, canSettle: false });
expect(items.find((item) => item.id === "settle")?.disabled).toBe(true);
const settled = buildThreadActionMenuItems({
...baseState,
canSettle: false,
isSettled: true,
});
expect(settled.find((item) => item.id === "unsettle")?.disabled).not.toBe(true);
});

it.each([false, true])(
"disables both lifecycle directions without permission (reversed: %s)",
(reversed) => {
Expand Down
8 changes: 7 additions & 1 deletion apps/web/src/components/threadActionMenu.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export interface ThreadActionMenuState {
readonly canOperate: boolean;
/** Settle, snooze and their undo stay available until the host denies the operate scope. */
readonly canTriage?: boolean;
readonly canSettle?: boolean;
readonly canFind?: boolean;
/** False where no inline title editor is rendered, such as sidebar search results. */
readonly canRename?: boolean;
Expand Down Expand Up @@ -240,7 +241,12 @@ export function buildThreadActionMenuItems(
label: resolve(msg("Un-settle thread")),
icon: "circle-check",
}
: { id: "settle" as const, label: resolve(msg("Settle thread")), icon: "circle-check" },
: {
id: "settle" as const,
label: resolve(msg("Settle thread")),
icon: "circle-check",
disabled: state.canSettle === false,
},
]
: []),
...(state.supports.snooze
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/hooks/useThreadActionMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import {
AuthOrchestrationOperateScope,
isStandingThreadRoot,
type ScopedThreadRef,
type ThreadId,
type ContextMenuSource,
Expand Down Expand Up @@ -140,6 +141,7 @@ export function useThreadActionMenu(input: {
const items = buildThreadActionMenuItems({
canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
canTriage: threadTriagePermitted(threadRef.environmentId),
canSettle: !isStandingThreadRoot(thread),
canFind: onFind !== undefined,
canRename: onStartRename !== undefined,
branch: thread.branch ?? null,
Expand Down
7 changes: 7 additions & 0 deletions packages/contracts/src/threadStanding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ export const StoredThreadStanding = Schema.NullOr(
).pipe(Schema.catchDecoding(() => Effect.succeedSome(null)));
export type StoredThreadStanding = typeof StoredThreadStanding.Type;

export function isStandingThreadRoot(thread: {
readonly standing?: unknown;
readonly lineage: { readonly parentThreadId: string | null };
}): boolean {
return thread.standing != null && thread.lineage.parentThreadId === null;
}

export function resolveThreadStandingAvatarId(avatarId: string): ThreadStandingAvatarId {
return (THREAD_STANDING_AVATAR_IDS as readonly string[]).includes(avatarId)
? (avatarId as ThreadStandingAvatarId)
Expand Down
Loading