Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): show and control bot delegations (#78)

Leoeddf7d59baf4
diff --git a/apps/mobile/src/features/archive/archivedThreadList.test.ts b/apps/mobile/src/features/archive/archivedThreadList.test.ts
index 5ebedfb34..4de076634 100644
--- a/apps/mobile/src/features/archive/archivedThreadList.test.ts
+++ b/apps/mobile/src/features/archive/archivedThreadList.test.ts
@@ -59,6 +59,7 @@ function makeSnapshot(
threads,
bots: [],
groups: [],
+ delegations: [],
updatedAt: "2026-06-04T00:00:00.000Z",
},
};
diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
index 3b96ac418..a061fc326 100644
--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
@@ -190,6 +190,7 @@ describe("OrchestrationEngine", () => {
snapshotSequence: projectionSnapshot.snapshotSequence,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: projectionSnapshot.updatedAt,
@@ -199,6 +200,7 @@ describe("OrchestrationEngine", () => {
snapshotSequence: projectionSnapshot.snapshotSequence,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: projectionSnapshot.updatedAt,
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
index 00ffef97a..4a54d12a1 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts
@@ -1,4 +1,5 @@
import {
+ AkeruDelegationRecord,
CheckpointRef,
EventId,
MessageId,
@@ -11,6 +12,7 @@ import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -27,6 +29,10 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
+const decodeDelegationRecord = Schema.decodeUnknownEffect(AkeruDelegationRecord);
+const encodeDelegationRecordJson = Schema.encodeEffect(
+ Schema.fromJsonString(AkeruDelegationRecord),
+);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
@@ -39,6 +45,65 @@ const projectionSnapshotLayer = it.layer(
);
projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
+ it.effect("includes delegation records in the shell snapshot", () =>
+ Effect.gen(function* () {
+ const snapshotQuery = yield* ProjectionSnapshotQuery;
+ const sql = yield* SqlClient.SqlClient;
+ const record = {
+ delegationId: "delegation-shell",
+ parentDelegationId: null,
+ parentBotId: "bot-parent",
+ childBotId: "bot-child",
+ parentThreadId: "thread-parent",
+ childThreadId: null,
+ parentTurnId: "turn-parent",
+ childTurnId: null,
+ ancestorBotIds: ["bot-parent"],
+ depth: 1,
+ task: "Compare the release options.",
+ expectedResult: "A short comparison.",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: ["project"],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "none",
+ },
+ state: "queued",
+ billedBotId: "bot-child",
+ result: null,
+ failure: null,
+ keep: false,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ startedAt: null,
+ completedAt: null,
+ };
+ const recordJson = yield* decodeDelegationRecord(record).pipe(
+ Effect.flatMap(encodeDelegationRecordJson),
+ );
+
+ yield* sql`DELETE FROM projection_delegations`;
+ yield* sql`
+ INSERT INTO projection_delegations (delegation_id, record_json)
+ VALUES (
+ ${record.delegationId},
+ ${recordJson}
+ )
+ `;
+
+ const snapshot = yield* snapshotQuery.getShellSnapshot();
+ assert.equal(snapshot.delegations.length, 1);
+ assert.equal(snapshot.delegations[0]?.delegationId, "delegation-shell");
+ assert.equal(snapshot.delegations[0]?.task, "Compare the release options.");
+ yield* sql`DELETE FROM projection_delegations`;
+ }),
+ );
+
it.effect("hydrates read model from projection tables and computes snapshot sequence", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index 16ef07867..4713de75e 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -2208,6 +2208,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
+ listDelegationRows(undefined).pipe(
+ Effect.mapError(
+ toPersistenceSqlOrDecodeError(
+ "ProjectionSnapshotQuery.getShellSnapshot:listDelegations:query",
+ "ProjectionSnapshotQuery.getShellSnapshot:listDelegations:decodeRows",
+ ),
+ ),
+ ),
projectionMcpServerRepository.listAll(),
listActiveThreadRows(undefined).pipe(
Effect.mapError(
@@ -2249,6 +2257,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
projectRows,
botRows,
groupRows,
+ delegationRows,
mcpServers,
threadRows,
sessionRows,
@@ -2266,6 +2275,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
for (const row of groupRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
+ for (const row of delegationRows) {
+ updatedAt = maxIso(updatedAt, row.delegation.updatedAt);
+ }
for (const mcpServer of mcpServers) {
updatedAt = maxIso(updatedAt, mcpServer.updatedAt);
}
@@ -2308,6 +2320,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
bots: botRows.map(mapBotRow),
groups: groupRows.map(mapGroupRow),
+ delegations: delegationRows.map((row) => row.delegation),
mcpServers,
threads: Arr.filterMap(threadRows, (row) =>
row.deletedAt === null
diff --git a/apps/server/src/provider/AkeruDelegationRuntime.test.ts b/apps/server/src/provider/AkeruDelegationRuntime.test.ts
index e1f60190f..b0a7edb99 100644
--- a/apps/server/src/provider/AkeruDelegationRuntime.test.ts
+++ b/apps/server/src/provider/AkeruDelegationRuntime.test.ts
@@ -607,4 +607,31 @@ describe("AkeruDelegationRuntime", () => {
).runtime.send(parent(), request() as never),
).rejects.toThrow("current group");
});
+
+ it("requires authoritative group membership for an associated bot", async () => {
+ const groupId = GroupId.make("group-1");
+ const group = {
+ id: groupId,
+ name: "Research",
+ bossBotId: PARENT_BOT_ID,
+ members: [{ botId: PARENT_BOT_ID, role: "boss" as const }],
+ createdAt: NOW,
+ updatedAt: NOW,
+ };
+
+ await expect(
+ harness(
+ snapshot({
+ bots: [bot(PARENT_BOT_ID, { groupId }), bot(CHILD_BOT_ID, { groupId })],
+ groups: [group],
+ threads: [
+ thread(PARENT_THREAD_ID, null, {
+ groupId,
+ respondingBotId: PARENT_BOT_ID,
+ }),
+ ],
+ }),
+ ).runtime.send(parent(), request() as never),
+ ).rejects.toThrow("The target bot is not available in the current group.");
+ });
});
diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts
index 20892adcd..80ab7941c 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts
@@ -492,6 +492,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
projects: [project],
bots: [],
groups: [],
+ delegations: [],
threads: [thread],
updatedAt: now,
} satisfies OrchestrationShellSnapshot),
@@ -685,6 +686,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
projects: [project],
bots: [],
groups: [],
+ delegations: [],
threads: [thread],
updatedAt: now,
} satisfies OrchestrationShellSnapshot),
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 1049e51a6..2fec245a2 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -5,12 +5,14 @@ import * as NodeCrypto from "node:crypto";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
+ type AkeruDelegationRecord,
AuthAccessTokenType,
AuthEnvironmentBootstrapTokenType,
AuthTokenExchangeGrantType,
BotId,
CommandId,
DEFAULT_SERVER_SETTINGS,
+ DelegationId,
EnvironmentId,
EventId,
GitCommandError,
@@ -30,6 +32,7 @@ import {
ProviderInstanceId,
ResolvedKeybindingRule,
ThreadId,
+ TurnId,
WS_METHODS,
WsRpcGroup,
EditorId,
@@ -840,6 +843,7 @@ const buildAppUnderTest = (options?: {
snapshotSequence: 0,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
@@ -849,6 +853,7 @@ const buildAppUnderTest = (options?: {
snapshotSequence: 0,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
@@ -6414,6 +6419,103 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("maps delegation lifecycle events into shell upserts", () =>
+ Effect.gen(function* () {
+ const now = "2026-08-31T00:00:00.000Z";
+ const record = (delegationId: DelegationId): AkeruDelegationRecord => ({
+ delegationId,
+ parentDelegationId: null,
+ parentBotId: BotId.make("bot-parent"),
+ childBotId: BotId.make("bot-child"),
+ parentThreadId: ThreadId.make("thread-parent"),
+ childThreadId: null,
+ parentTurnId: TurnId.make("turn-parent"),
+ childTurnId: null,
+ ancestorBotIds: [BotId.make("bot-parent")],
+ depth: 1,
+ task: "Compare the release options.",
+ expectedResult: "A short comparison.",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: [],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "none",
+ },
+ state: "queued",
+ billedBotId: BotId.make("bot-child"),
+ result: null,
+ failure: null,
+ keep: false,
+ createdAt: now,
+ updatedAt: now,
+ startedAt: null,
+ completedAt: null,
+ });
+ const created = record(DelegationId.make("delegation-created"));
+ const updated = {
+ ...record(DelegationId.make("delegation-updated")),
+ state: "running",
+ } as const;
+ const events = [
+ {
+ sequence: 1,
+ eventId: EventId.make("event-delegation-created"),
+ aggregateKind: "delegation",
+ aggregateId: created.delegationId,
+ occurredAt: now,
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "delegation.created",
+ payload: { delegation: created },
+ } satisfies Extract<OrchestrationEvent, { type: "delegation.created" }>,
+ {
+ sequence: 2,
+ eventId: EventId.make("event-delegation-updated"),
+ aggregateKind: "delegation",
+ aggregateId: updated.delegationId,
+ occurredAt: now,
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "delegation.updated",
+ payload: { delegation: updated },
+ } satisfies Extract<OrchestrationEvent, { type: "delegation.updated" }>,
+ ];
+
+ yield* buildAppUnderTest({
+ layers: {
+ orchestrationEngine: {
+ latestSequence: Effect.succeed(2),
+ readEvents: () => Stream.fromIterable(events),
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const items = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) =>
+ client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe(
+ Stream.take(2),
+ Stream.runCollect,
+ ),
+ ),
+ );
+
+ assert.deepEqual(Array.from(items), [
+ { kind: "delegation-upserted", sequence: 1, delegation: created },
+ { kind: "delegation-upserted", sequence: 2, delegation: updated },
+ ]);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
it.effect("marks a socket thread snapshot as synchronized when requested", () =>
Effect.gen(function* () {
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
@@ -6474,6 +6576,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
snapshotSequence: 1,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [makeDefaultOrchestrationThreadShell()],
updatedAt: "2026-01-01T00:00:00.000Z",
@@ -6734,6 +6837,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
snapshotSequence: 100_000,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [makeDefaultOrchestrationThreadShell({ id: snapshotThreadId })],
updatedAt: now,
@@ -6783,6 +6887,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
snapshotSequence: 5,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 13ba3c575..a1bdbdbd1 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -872,6 +872,15 @@ const makeWsRpcLayer = (
mcpServerId: event.payload.mcpServerId,
}),
);
+ case "delegation.created":
+ case "delegation.updated":
+ return Effect.succeed(
+ Option.some({
+ kind: "delegation-upserted" as const,
+ sequence: event.sequence,
+ delegation: event.payload.delegation,
+ }),
+ );
case "thread.deleted":
case "thread.archived":
return Effect.succeed(
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index 41a425ddd..c977d1a92 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
-import { BotId, type BotEngine } from "@t3tools/contracts";
+import { BotId, type BotEngine, type EnvironmentId } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
@@ -17,6 +17,7 @@ import {
import { botEnvironment } from "../../state/bots";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
+import { environmentSnapshotAtom } from "../../state/shell";
import { useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
import { openSettings } from "../../settingsDialogStore";
@@ -29,6 +30,7 @@ import { BotApprovalPrompt } from "./BotApprovalPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
+import { DelegationCard } from "./DelegationCard";
import { visibleBotChatMessages } from "./botConversationPresentation";
import { resolveStickyBotEngine } from "./botEngineSelection";
import { BotPromptComposer } from "./BotPromptComposer";
@@ -39,13 +41,16 @@ import { useRosterStore } from "./rosterStore";
import { useBotThreadRuntime } from "./useBotThreadRuntime";
import { useRosterPendingApproval } from "./useRosterPendingApproval";
+const NO_ENVIRONMENT = "" as EnvironmentId;
+
export function BotThreadLanding({ botId }: { readonly botId: string }) {
const navigate = useNavigate();
const environmentId = usePrimaryEnvironmentId();
const settings = usePrimarySettings();
const providers = useAtomValue(primaryServerProvidersAtom);
const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });
- const bot = useRosterStore((state) => state.bots.find((candidate) => candidate.id === botId));
+ const bots = useRosterStore((state) => state.bots);
+ const bot = bots.find((candidate) => candidate.id === botId);
const [pendingEngine, setPendingEngine] = useState<BotEngine | null>(null);
const [modelUpdatePending, setModelUpdatePending] = useState(false);
const configuredEngine = pendingEngine ?? bot?.engine ?? null;
@@ -90,6 +95,7 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
? null
: serverEnvironment.subscriptionAuth({ environmentId, input: {} }),
);
+ const snapshot = useAtomValue(environmentSnapshotAtom(environmentId ?? NO_ENVIRONMENT));
useEffect(() => {
if (
@@ -114,6 +120,11 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
const messages = visibleBotChatMessages(runtime.messages);
const pendingApproval = approvalState.pendingApproval;
const inboxItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? [], new Set([bot.id]));
+ const delegations = runtime.linkedThreadRef
+ ? (snapshot?.delegations.filter(
+ (delegation) => delegation.parentThreadId === runtime.linkedThreadRef?.threadId,
+ ) ?? [])
+ : [];
return (
<SidebarInset
@@ -194,6 +205,18 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
onRespond={(decision) => approvalState.respond(pendingApproval.requestId, decision)}
/>
) : null}
+ {delegations.map((delegation) => (
+ <DelegationCard
+ key={delegation.delegationId}
+ delegation={delegation}
+ childBot={
+ bots.find(
+ (candidate) =>
+ candidate.id === delegation.childBotId && candidate.archivedAt === null,
+ ) ?? null
+ }
+ />
+ ))}
{working ? <BotActivityStatus avatar={bot.avatar} name={bot.name} /> : null}
</BotConversationScrollArea>
<BotInboxAlertStack
diff --git a/apps/web/src/components/roster/DelegationCard.test.tsx b/apps/web/src/components/roster/DelegationCard.test.tsx
new file mode 100644
index 000000000..21caa78ec
--- /dev/null
+++ b/apps/web/src/components/roster/DelegationCard.test.tsx
@@ -0,0 +1,279 @@
+import type { ReactElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ AkeruDelegationRecord,
+ BotId,
+ EnvironmentId,
+ EventId,
+ ProjectId,
+ ProviderInstanceId,
+ ThreadId,
+ TurnId,
+ type AkeruDelegationState,
+ type OrchestrationThreadActivity,
+ type OrchestrationThreadShell,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+const mocks = vi.hoisted(() => ({
+ activities: [] as OrchestrationThreadActivity[],
+ cancel: vi.fn(),
+ navigate: vi.fn(),
+ recordChatPath: vi.fn(),
+ thread: null as OrchestrationThreadShell | null,
+}));
+
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>();
+ return { ...actual, useMemo: <T,>(factory: () => T) => factory() };
+});
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => mocks.navigate }));
+vi.mock("../../state/environments", () => ({
+ usePrimaryEnvironmentId: () => EnvironmentId.make("environment-1"),
+}));
+vi.mock("../../state/entities", () => ({
+ useThreadActivities: () => mocks.activities,
+ useThreadShell: () => mocks.thread,
+}));
+vi.mock("../../state/orchestration", () => ({
+ orchestrationEnvironment: { cancelDelegation: Symbol("cancelDelegation") },
+}));
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => mocks.cancel }));
+vi.mock("./rosterStore", () => ({
+ useRosterStore: { getState: () => ({ recordChatPath: mocks.recordChatPath }) },
+}));
+
+import { DelegationCard, delegationUsageTokens } from "./DelegationCard";
+import { visitElements } from "../../test/reactElementTree";
+import type { Bot } from "./types";
+
+const decodeDelegationRecord = Schema.decodeUnknownSync(AkeruDelegationRecord);
+
+const childBot: Bot = {
+ id: "bot-child",
+ name: "Mori",
+ title: "Researcher",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither", seed: "mori" },
+ engine: null,
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ usageCap: null,
+ voiceEnabled: false,
+ groupId: null,
+ pinned: false,
+ archivedAt: null,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+};
+
+const childThread = {
+ id: ThreadId.make("thread-child"),
+ projectId: ProjectId.make("project-1"),
+ botId: BotId.make("bot-child"),
+ groupId: null,
+ respondingBotId: BotId.make("bot-child"),
+ title: "Delegated research",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ latestTurn: null,
+ createdAt: "2026-08-31T00:00:10.000Z",
+ updatedAt: "2026-08-31T00:01:00.000Z",
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ session: null,
+ latestUserMessageAt: null,
+ hasPendingApprovals: false,
+ hasPendingUserInput: false,
+ hasActionableProposedPlan: false,
+} satisfies OrchestrationThreadShell;
+
+function delegation(state: AkeruDelegationState) {
+ return decodeDelegationRecord({
+ delegationId: `delegation-${state}`,
+ parentDelegationId: null,
+ parentBotId: "bot-parent",
+ childBotId: "bot-child",
+ parentThreadId: "thread-parent",
+ childThreadId: state === "queued" ? null : "thread-child",
+ parentTurnId: "turn-parent",
+ childTurnId: state === "queued" ? null : "turn-child",
+ ancestorBotIds: ["bot-parent"],
+ depth: 1,
+ task: "Compare the release options.",
+ expectedResult: "A short comparison.",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: ["project"],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "none",
+ },
+ state,
+ billedBotId: "bot-child",
+ result:
+ state === "completed"
+ ? {
+ summary: "Release comparison complete.",
+ childThreadId: "thread-child",
+ childTurnId: "turn-child",
+ }
+ : null,
+ failure:
+ state === "failed" ? { failureCode: "child_failed", message: "The provider stopped." } : null,
+ keep: false,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:01:00.000Z",
+ startedAt: state === "queued" ? null : "2026-08-31T00:00:10.000Z",
+ completedAt: ["failed", "canceled", "completed"].includes(state)
+ ? "2026-08-31T00:01:00.000Z"
+ : null,
+ });
+}
+
+function usage(turnId: string, totalProcessedTokens: number): OrchestrationThreadActivity {
+ return {
+ id: EventId.make(`usage-${turnId}`),
+ tone: "info",
+ kind: "context-window.updated",
+ summary: "Context window updated",
+ payload: { usedTokens: totalProcessedTokens, totalProcessedTokens },
+ turnId: TurnId.make(turnId),
+ createdAt: "2026-08-31T00:00:40.000Z",
+ };
+}
+
+function renderCard(state: AkeruDelegationState, bot: Bot | null = childBot) {
+ return renderToStaticMarkup(<DelegationCard delegation={delegation(state)} childBot={bot} />);
+}
+
+function cardElement(state: AkeruDelegationState, bot: Bot | null = childBot) {
+ return DelegationCard({ delegation: delegation(state), childBot: bot }) as ReactElement<
+ Record<string, unknown>
+ >;
+}
+
+describe("DelegationCard", () => {
+ beforeEach(() => {
+ mocks.activities = [usage("other-turn", 99_999), usage("turn-child", 1_234)];
+ mocks.thread = childThread;
+ mocks.cancel.mockReset().mockResolvedValue({ _tag: "Success", value: { sequence: 1 } });
+ mocks.navigate.mockReset().mockResolvedValue(undefined);
+ mocks.recordChatPath.mockReset();
+ });
+
+ it.each(["queued", "running", "blocked", "failed", "canceled", "completed"] as const)(
+ "shows the exact %s state",
+ (state) => {
+ const markup = renderCard(state);
+ expect(markup).toContain(`aria-live="polite">${state}</span>`);
+ },
+ );
+
+ it("shows result and failure text without mixing them", () => {
+ const complete = renderCard("completed");
+ expect(complete).toContain("Release comparison complete.");
+ expect(complete).not.toContain("The provider stopped.");
+
+ const failed = renderCard("failed");
+ expect(failed).toContain("The provider stopped.");
+ expect(failed).not.toContain("Release comparison complete.");
+ });
+
+ it("shows fallback text when terminal details are missing", () => {
+ const completed = delegation("completed");
+ const failed = delegation("failed");
+ expect(
+ renderToStaticMarkup(
+ <DelegationCard delegation={{ ...completed, result: null }} childBot={childBot} />,
+ ),
+ ).toContain("Result unavailable");
+ expect(
+ renderToStaticMarkup(
+ <DelegationCard delegation={{ ...failed, failure: null }} childBot={childBot} />,
+ ),
+ ).toContain("Failure details unavailable");
+ });
+
+ it("shows elapsed time and the access grant", () => {
+ const markup = renderCard("completed");
+ expect(markup).toContain(">50s</span>");
+ expect(markup).toContain("approval required · local sandbox · tools: Read");
+ expect(markup).toContain("memory: project · MCP servers: 0 · no user computer · no approvals");
+ });
+
+ it("uses only the delegated child turn usage", () => {
+ expect(delegationUsageTokens(delegation("completed"), mocks.activities)).toBe(1_234);
+ expect(delegationUsageTokens(delegation("queued"), mocks.activities)).toBeNull();
+ const markup = renderCard("completed");
+ expect(markup).toContain('aria-label="1,234 tokens billed to Mori"');
+ expect(markup).not.toContain("100K");
+ });
+
+ it("cancels through the delegation command with keep disabled", async () => {
+ const cancel = visitElements(
+ cardElement("running"),
+ (element) => element.props["aria-label"] === "Cancel delegation to Mori",
+ );
+ (cancel?.props.onClick as (() => void) | undefined)?.();
+ await Promise.resolve();
+ expect(mocks.cancel).toHaveBeenCalledWith({
+ environmentId: EnvironmentId.make("environment-1"),
+ input: { delegationId: delegation("running").delegationId, keep: false },
+ });
+ });
+
+ it.each(["failed", "canceled", "completed"] as const)(
+ "hides cancel for the terminal %s state",
+ (state) => {
+ expect(renderCard(state)).not.toContain(`aria-label="Cancel delegation to Mori"`);
+ },
+ );
+
+ it("opens the child through roster thread navigation", () => {
+ const open = visitElements(
+ cardElement("running"),
+ (element) => element.props["aria-label"] === "Open Mori thread",
+ );
+ (open?.props.onClick as (() => void) | undefined)?.();
+ expect(mocks.recordChatPath).toHaveBeenCalledWith("bot-child", "/environment-1/thread-child");
+ expect(mocks.navigate).toHaveBeenCalledWith({
+ to: "/bots/$botId",
+ params: { botId: "bot-child" },
+ });
+ });
+
+ it("handles a missing child without enabling a false route", () => {
+ mocks.thread = null;
+ const markup = renderCard("running", null);
+ expect(markup).toContain("Unknown bot");
+ expect(markup).toContain("Usage unavailable");
+ expect(markup).toContain('aria-label="Open Unknown bot thread" disabled=""');
+ });
+
+ it("treats an archived child as unavailable", () => {
+ const markup = renderCard("running", {
+ ...childBot,
+ archivedAt: "2026-08-31T00:02:00.000Z",
+ });
+ expect(markup).toContain("Unknown bot");
+ expect(markup).toContain('aria-label="Open Unknown bot thread" disabled=""');
+ });
+
+ it("names both actions for assistive technology", () => {
+ const markup = renderCard("running");
+ expect(markup).toContain('aria-label="Cancel delegation to Mori"');
+ expect(markup).toContain('aria-label="Open Mori thread"');
+ });
+});
diff --git a/apps/web/src/components/roster/DelegationCard.tsx b/apps/web/src/components/roster/DelegationCard.tsx
new file mode 100644
index 000000000..6a2010fd6
--- /dev/null
+++ b/apps/web/src/components/roster/DelegationCard.tsx
@@ -0,0 +1,214 @@
+import type {
+ AkeruDelegationAccessGrant,
+ AkeruDelegationRecord,
+ AkeruDelegationState,
+ OrchestrationThreadActivity,
+} from "@t3tools/contracts";
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
+import { formatDuration } from "@t3tools/shared/orchestrationTiming";
+import { formatTokens } from "@t3tools/shared/usageFormat";
+import { useNavigate } from "@tanstack/react-router";
+import { useEffect, useMemo, useRef } from "react";
+
+import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
+import { usePrimaryEnvironmentId } from "../../state/environments";
+import { useThreadActivities, useThreadShell } from "../../state/entities";
+import { orchestrationEnvironment } from "../../state/orchestration";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { Button } from "../ui/button";
+import { toastManager } from "../ui/toast";
+import { BotAvatarView } from "./BotAvatarView";
+import { useRosterStore } from "./rosterStore";
+import type { Bot } from "./types";
+
+const TERMINAL_STATES = new Set<AkeruDelegationState>(["failed", "canceled", "completed"]);
+
+const STATE_DOT: Record<AkeruDelegationState, string> = {
+ queued: "bg-muted-foreground/50",
+ running: "bg-info",
+ blocked: "bg-warning",
+ failed: "bg-destructive",
+ canceled: "bg-muted-foreground/60",
+ completed: "bg-success",
+};
+
+const RUNTIME_MODE_LABEL: Record<AkeruDelegationAccessGrant["runtimeMode"], string> = {
+ "approval-required": "approval required",
+ "auto-accept-edits": "auto-accept edits",
+ auto: "automatic approvals",
+ "full-access": "full access",
+};
+
+function formatDelegationAccess(access: AkeruDelegationAccessGrant): string {
+ return [
+ RUNTIME_MODE_LABEL[access.runtimeMode],
+ access.sandbox === null ? "no sandbox" : `${access.sandbox} sandbox`,
+ `tools: ${access.allowedToolIds.join(", ") || "none"}`,
+ `memory: ${access.memoryScopes.join(", ") || "none"}`,
+ `MCP servers: ${access.enabledMcpServerIds.length}`,
+ access.hasUserComputer ? "user computer" : "no user computer",
+ access.approvalCeiling === "none"
+ ? "no approvals"
+ : `approval ceiling: ${access.approvalCeiling}`,
+ ].join(" · ");
+}
+
+export function delegationUsageTokens(
+ delegation: AkeruDelegationRecord,
+ childActivities: ReadonlyArray<OrchestrationThreadActivity>,
+): number | null {
+ if (!delegation.childTurnId) return null;
+ const activities = childActivities.filter(
+ (activity) => activity.turnId === delegation.childTurnId,
+ );
+ const usage = deriveLatestContextWindowSnapshot(activities);
+ return usage?.totalProcessedTokens ?? usage?.usedTokens ?? null;
+}
+
+function delegationElapsed(delegation: AkeruDelegationRecord, now = Date.now()): string | null {
+ const startedAt = Date.parse(delegation.startedAt ?? delegation.createdAt);
+ const endedAt = delegation.completedAt ? Date.parse(delegation.completedAt) : now;
+ if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) return null;
+ return formatDuration(endedAt - startedAt);
+}
+
+function DelegationElapsed({ delegation }: { readonly delegation: AkeruDelegationRecord }) {
+ const textRef = useRef<HTMLSpanElement>(null);
+ const live = !TERMINAL_STATES.has(delegation.state);
+
+ useEffect(() => {
+ if (!live) return;
+ const update = () => {
+ if (textRef.current) textRef.current.textContent = delegationElapsed(delegation) ?? "";
+ };
+ update();
+ const id = window.setInterval(update, 1_000);
+ return () => window.clearInterval(id);
+ }, [delegation, live]);
+
+ const elapsed = delegationElapsed(delegation);
+ return elapsed ? (
+ <span ref={textRef} className="tabular-nums">
+ {elapsed}
+ </span>
+ ) : null;
+}
+
+export function DelegationCard({
+ delegation,
+ childBot,
+}: {
+ readonly delegation: AkeruDelegationRecord;
+ readonly childBot: Bot | null;
+}) {
+ const navigate = useNavigate();
+ const environmentId = usePrimaryEnvironmentId();
+ const cancelDelegation = useAtomCommand(orchestrationEnvironment.cancelDelegation, {
+ reportFailure: false,
+ });
+ const childThreadRef = useMemo(
+ () =>
+ environmentId && delegation.childThreadId
+ ? scopeThreadRef(environmentId, delegation.childThreadId)
+ : null,
+ [delegation.childThreadId, environmentId],
+ );
+ const childThread = useThreadShell(childThreadRef);
+ const childActivities = useThreadActivities(childThreadRef);
+ const activeChildBot = childBot?.archivedAt === null ? childBot : null;
+ const childName = activeChildBot?.name ?? "Unknown bot";
+ const usageTokens = childThread ? delegationUsageTokens(delegation, childActivities) : null;
+ const canCancel = !TERMINAL_STATES.has(delegation.state) && environmentId !== null;
+ const canOpen = activeChildBot !== null && childThread !== null && environmentId !== null;
+ const outcome =
+ delegation.failure?.message ??
+ delegation.result?.summary ??
+ (delegation.state === "failed"
+ ? "Failure details unavailable"
+ : delegation.state === "completed"
+ ? "Result unavailable"
+ : null);
+
+ return (
+ <article
+ aria-label={`Delegation to ${childName}`}
+ className="ml-10 max-w-[min(42rem,calc(100%-2.5rem))] border-l-2 border-border py-1.5 pl-3"
+ data-testid="delegation-card"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <BotAvatarView
+ avatar={activeChildBot?.avatar ?? { kind: "dither", seed: delegation.childBotId }}
+ name={childName}
+ className="size-7 shrink-0"
+ />
+ <span className="min-w-0 truncate text-sm font-medium">{childName}</span>
+ <span className="ml-auto inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
+ <span aria-hidden className={`size-1.5 rounded-full ${STATE_DOT[delegation.state]}`} />
+ <span aria-live="polite">{delegation.state}</span>
+ </span>
+ </div>
+ <p className="mt-1 line-clamp-2 text-sm leading-5">{delegation.task}</p>
+ <p className="mt-1 break-words text-xs text-muted-foreground">
+ {formatDelegationAccess(delegation.access)}
+ </p>
+ <div className="mt-1 flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground">
+ <DelegationElapsed delegation={delegation} />
+ <span
+ className="tabular-nums"
+ aria-label={
+ usageTokens === null
+ ? `Usage unavailable for ${childName}`
+ : `${usageTokens.toLocaleString()} tokens billed to ${childName}`
+ }
+ >
+ {usageTokens === null ? "Usage unavailable" : `${formatTokens(usageTokens)} tokens`}
+ </span>
+ </div>
+ {outcome ? (
+ <p
+ className={`mt-1 text-sm leading-5 ${delegation.failure ? "text-destructive-foreground" : "text-muted-foreground"}`}
+ >
+ {outcome}
+ </p>
+ ) : null}
+ <div className="mt-1.5 flex items-center gap-1">
+ {canCancel ? (
+ <Button
+ size="sm"
+ variant="ghost-muted"
+ className="min-h-11"
+ aria-label={`Cancel delegation to ${childName}`}
+ onClick={() => {
+ void cancelDelegation({
+ environmentId,
+ input: { delegationId: delegation.delegationId, keep: false },
+ }).then((result) => {
+ if (result._tag === "Failure") {
+ toastManager.add({ type: "error", title: "Could not cancel delegation" });
+ }
+ });
+ }}
+ >
+ Cancel
+ </Button>
+ ) : null}
+ <Button
+ size="sm"
+ variant="ghost-muted"
+ className="min-h-11"
+ aria-label={`Open ${childName} thread`}
+ disabled={!canOpen}
+ onClick={() => {
+ if (!canOpen) return;
+ useRosterStore
+ .getState()
+ .recordChatPath(activeChildBot.id, `/${environmentId}/${childThread.id}`);
+ void navigate({ to: "/bots/$botId", params: { botId: activeChildBot.id } });
+ }}
+ >
+ Open thread
+ </Button>
+ </div>
+ </article>
+ );
+}
diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsx
index 3abe50da8..2ef708bdb 100644
--- a/apps/web/src/components/roster/GroupThreadLanding.tsx
+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx
@@ -1,3 +1,5 @@
+import { useAtomValue } from "@effect/atom-react";
+import type { EnvironmentId } from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import { useEffect } from "react";
@@ -6,6 +8,7 @@ import { openSettings } from "../../settingsDialogStore";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
+import { environmentSnapshotAtom } from "../../state/shell";
import { SidebarInset } from "../ui/sidebar";
import ChatMarkdown from "../ChatMarkdown";
import { WorkspacePageHeader } from "../WorkspacePageHeader";
@@ -15,6 +18,7 @@ import { BotApprovalPrompt } from "./BotApprovalPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
+import { DelegationCard } from "./DelegationCard";
import { visibleBotChatMessages } from "./botConversationPresentation";
import { BotPromptComposer } from "./BotPromptComposer";
import { useGroupPresence } from "./botPresence";
@@ -22,6 +26,8 @@ import { useRosterStore } from "./rosterStore";
import { useGroupThreadRuntime } from "./useGroupThreadRuntime";
import { useRosterPendingApproval } from "./useRosterPendingApproval";
+const NO_ENVIRONMENT = "" as EnvironmentId;
+
export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
const navigate = useNavigate();
const environmentId = usePrimaryEnvironmentId();
@@ -37,6 +43,7 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
? null
: serverEnvironment.subscriptionAuth({ environmentId, input: {} }),
);
+ const snapshot = useAtomValue(environmentSnapshotAtom(environmentId ?? NO_ENVIRONMENT));
useEffect(() => {
if (!group) void navigate({ to: "/", replace: true });
@@ -54,6 +61,11 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
inboxQuery.data?.inbox ?? [],
new Set(members.map((bot) => bot.id)),
);
+ const delegations = runtime.linkedThreadRef
+ ? (snapshot?.delegations.filter(
+ (delegation) => delegation.parentThreadId === runtime.linkedThreadRef?.threadId,
+ ) ?? [])
+ : [];
return (
<SidebarInset
@@ -138,6 +150,18 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
onRespond={(decision) => approvalState.respond(pendingApproval.requestId, decision)}
/>
) : null}
+ {delegations.map((delegation) => (
+ <DelegationCard
+ key={delegation.delegationId}
+ delegation={delegation}
+ childBot={
+ bots.find(
+ (candidate) =>
+ candidate.id === delegation.childBotId && candidate.archivedAt === null,
+ ) ?? null
+ }
+ />
+ ))}
{working ? <BotActivityStatus avatar={activeBot.avatar} name={activeBot.name} /> : null}
</BotConversationScrollArea>
<BotInboxAlertStack
diff --git a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
new file mode 100644
index 000000000..d679f7754
--- /dev/null
+++ b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
@@ -0,0 +1,216 @@
+import type { ReactElement } from "react";
+import {
+ AkeruDelegationRecord,
+ EnvironmentId,
+ ThreadId,
+ type OrchestrationShellSnapshot,
+} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { reactHookHarness as hooks } from "../../test/reactHookHarness";
+import { visitElements } from "../../test/reactElementTree";
+import type { Bot, Group } from "./types";
+
+const mocks = vi.hoisted(() => ({
+ providersAtom: Symbol("providers"),
+ snapshotAtom: Symbol("snapshot"),
+ snapshot: null as OrchestrationShellSnapshot | null,
+ bots: [] as Bot[],
+ groups: [] as Group[],
+}));
+
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>();
+ const { reactHookHarness } = await import("../../test/reactHookHarness");
+ return {
+ ...actual,
+ useCallback: reactHookHarness.useCallback,
+ useEffect: () => undefined,
+ useMemo: reactHookHarness.useMemo,
+ useRef: reactHookHarness.useRef,
+ useState: reactHookHarness.useState,
+ };
+});
+vi.mock("react/compiler-runtime", async () => {
+ const { reactHookHarness } = await import("../../test/reactHookHarness");
+ return { c: reactHookHarness.useMemoCache };
+});
+vi.mock("@effect/atom-react", () => ({
+ useAtomValue: (atom: unknown) => (atom === mocks.snapshotAtom ? mocks.snapshot : []),
+}));
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
+vi.mock("../../hooks/useSettings", () => ({ usePrimarySettings: () => ({}) }));
+vi.mock("../../modelSelection", () => ({
+ getCustomModelOptionsByInstance: () => new Map(),
+ resolveAppModelSelectionState: () => null,
+}));
+vi.mock("../../providerInstances", () => ({
+ applyProviderInstanceSettings: () => [],
+ deriveProviderInstanceEntries: () => [],
+ sortProviderInstanceEntries: () => [],
+}));
+vi.mock("../../state/bots", () => ({ botEnvironment: { update: Symbol("update") } }));
+vi.mock("../../state/environments", () => ({
+ usePrimaryEnvironmentId: () => EnvironmentId.make("environment-1"),
+}));
+vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: { inbox: [] } }) }));
+vi.mock("../../state/server", () => ({
+ primaryServerProvidersAtom: mocks.providersAtom,
+ serverEnvironment: { subscriptionAuth: () => null },
+}));
+vi.mock("../../state/shell", () => ({ environmentSnapshotAtom: () => mocks.snapshotAtom }));
+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
+vi.mock("../../settingsDialogStore", () => ({ openSettings: vi.fn() }));
+vi.mock("../voice/VoiceCall", () => ({
+ BotVoiceCallButton: () => null,
+ useVoiceCall: () => ({ activeCall: null, startingBotId: null }),
+}));
+vi.mock("./botEngineSelection", () => ({ resolveStickyBotEngine: () => null }));
+vi.mock("./botPresence", () => ({
+ useBotPresence: () => "idle",
+ useGroupPresence: () => "idle",
+}));
+vi.mock("./rosterStore", () => {
+ const useRosterStore = (selector: (state: unknown) => unknown) =>
+ selector({ bots: mocks.bots, groups: mocks.groups });
+ useRosterStore.getState = () => ({ selectBot: vi.fn() });
+ return { useRosterStore };
+});
+vi.mock("./useBotThreadRuntime", () => ({
+ useBotThreadRuntime: () => ({
+ sending: false,
+ messages: [],
+ error: null,
+ latestTurn: null,
+ defaultProject: null,
+ botReady: true,
+ bootstrapped: true,
+ linkedThreadRef: {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-parent"),
+ },
+ send: vi.fn(),
+ }),
+}));
+vi.mock("./useGroupThreadRuntime", () => ({
+ useGroupThreadRuntime: () => ({
+ sending: false,
+ messages: [],
+ error: null,
+ defaultProject: null,
+ groupReady: true,
+ bootstrapped: true,
+ respondingBotId: "bot-parent",
+ linkedThreadRef: {
+ environmentId: EnvironmentId.make("environment-1"),
+ threadId: ThreadId.make("thread-parent"),
+ },
+ send: vi.fn(),
+ }),
+}));
+
+import { BotThreadLanding } from "./BotThreadLanding";
+import { DelegationCard } from "./DelegationCard";
+import { GroupThreadLanding } from "./GroupThreadLanding";
+
+const decodeDelegation = Schema.decodeUnknownSync(AkeruDelegationRecord);
+const parentBot: Bot = {
+ id: "bot-parent",
+ name: "Akeru",
+ title: "Boss",
+ label: null,
+ description: null,
+ disabledMcpServerIds: [],
+ avatar: { kind: "dither", seed: "parent" },
+ engine: null,
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ usageCap: null,
+ voiceEnabled: false,
+ groupId: "group-1",
+ pinned: false,
+ archivedAt: null,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+};
+const childBot: Bot = { ...parentBot, id: "bot-child", name: "Mori", title: "Researcher" };
+const group: Group = {
+ id: "group-1",
+ name: "Research",
+ bossBotId: parentBot.id,
+ members: [
+ { botId: parentBot.id, role: "boss" },
+ { botId: childBot.id, role: "specialist" },
+ ],
+ createdAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+};
+
+function delegation(id: string, parentThreadId: string) {
+ return decodeDelegation({
+ delegationId: id,
+ parentDelegationId: null,
+ parentBotId: parentBot.id,
+ childBotId: childBot.id,
+ parentThreadId,
+ childThreadId: null,
+ parentTurnId: "turn-parent",
+ childTurnId: null,
+ ancestorBotIds: [parentBot.id],
+ depth: 1,
+ task: "Compare the release options.",
+ expectedResult: "A short comparison.",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: ["project"],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "none",
+ },
+ state: "queued",
+ billedBotId: childBot.id,
+ result: null,
+ failure: null,
+ keep: false,
+ createdAt: "2026-08-31T00:00:00.000Z",
+ updatedAt: "2026-08-31T00:00:00.000Z",
+ startedAt: null,
+ completedAt: null,
+ });
+}
+
+describe("thread landing delegations", () => {
+ beforeEach(() => {
+ hooks.reset();
+ mocks.bots = [parentBot, childBot];
+ mocks.groups = [group];
+ mocks.snapshot = {
+ snapshotSequence: 1,
+ bots: [],
+ groups: [],
+ delegations: [delegation("matching", "thread-parent"), delegation("other", "thread-other")],
+ projects: [],
+ threads: [],
+ updatedAt: "2026-08-31T00:00:00.000Z",
+ };
+ });
+
+ it.each([
+ ["bot", () => BotThreadLanding({ botId: parentBot.id })],
+ ["group", () => GroupThreadLanding({ groupId: group.id })],
+ ])("renders the shared card for the matching %s thread delegation", (_kind, render) => {
+ hooks.beginRender();
+ const card = visitElements(
+ render(),
+ (element) => element.type === DelegationCard,
+ ) as ReactElement<Parameters<typeof DelegationCard>[0]> | null;
+
+ expect(card?.props.delegation.delegationId).toBe("matching");
+ expect(card?.props.childBot).toBe(childBot);
+ });
+});
diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts
index c8e2612f1..eb4edfad5 100644
--- a/packages/client-runtime/src/connection/registry.test.ts
+++ b/packages/client-runtime/src/connection/registry.test.ts
@@ -116,6 +116,7 @@ const CACHED_SNAPSHOT: OrchestrationShellSnapshot = {
snapshotSequence: 1,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "2026-06-06T00:00:00.000Z",
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index 866f25e22..e69e65f66 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -1,6 +1,7 @@
import {
BotId,
CommandId,
+ DelegationId,
EnvironmentId,
GroupId,
McpServerId,
@@ -27,6 +28,7 @@ import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import {
archiveThread,
assignGroupMember,
+ cancelDelegation,
createMcpServer,
createProject,
settleThread,
@@ -208,6 +210,30 @@ describe("environment commands", () => {
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
+ it.effect("dispatches delegation cancellation with the keep choice", () =>
+ Effect.gen(function* () {
+ const dispatched: ClientOrchestrationCommand[] = [];
+ const supervisor = yield* makeSupervisor(dispatched);
+
+ yield* cancelDelegation({
+ commandId: CommandId.make("cancel-delegation"),
+ delegationId: DelegationId.make("delegation-1"),
+ keep: false,
+ createdAt: "2026-08-31T00:01:00.000Z",
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
+
+ expect(dispatched).toEqual([
+ {
+ type: "delegation.cancel",
+ commandId: "cancel-delegation",
+ delegationId: "delegation-1",
+ keep: false,
+ createdAt: "2026-08-31T00:01:00.000Z",
+ },
+ ]);
+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
+ );
+
it.effect("does not add timestamps to commands without createdAt", () =>
Effect.gen(function* () {
const dispatched: ClientOrchestrationCommand[] = [];
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index 2935fc41c..e3999f934 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -67,6 +67,7 @@ export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond
export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">;
export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">;
export type StopThreadSessionInput = CommandInput<"thread.session.stop">;
+export type CancelDelegationInput = CommandInput<"delegation.cancel">;
type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand;
type CommandEffect = Effect.Effect<
@@ -530,3 +531,15 @@ export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect
createdAt: metadata.createdAt,
});
});
+
+export const cancelDelegation: (input: CancelDelegationInput) => CommandEffect = Effect.fn(
+ "EnvironmentCommands.cancelDelegation",
+)(function* (input) {
+ const metadata = yield* timestampedCommandMetadata(input);
+ return yield* dispatch({
+ ...input,
+ type: "delegation.cancel",
+ commandId: metadata.commandId,
+ createdAt: metadata.createdAt,
+ });
+});
diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts
index 31558d882..b0e46fad5 100644
--- a/packages/client-runtime/src/state/entities.test.ts
+++ b/packages/client-runtime/src/state/entities.test.ts
@@ -110,6 +110,7 @@ const SNAPSHOT: OrchestrationShellSnapshot = {
updatedAt: "2026-06-01T00:00:00.000Z",
bots: [],
groups: [],
+ delegations: [],
projects: [
{
id: PROJECT_ID,
diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts
index ba80275bf..a20615e76 100644
--- a/packages/client-runtime/src/state/orchestration.ts
+++ b/packages/client-runtime/src/state/orchestration.ts
@@ -1,13 +1,30 @@
import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
+import * as Crypto from "effect/Crypto";
import { Atom } from "effect/unstable/reactivity";
-import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
+import { cancelDelegation, type CancelDelegationInput } from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
+import {
+ createAtomCommandScheduler,
+ createEnvironmentCommand,
+ createEnvironmentRpcQueryAtomFamily,
+} from "./runtime.ts";
export function createOrchestrationEnvironmentAtoms<R, E>(
- runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
+ runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,
) {
+ const scheduler = createAtomCommandScheduler();
return {
+ cancelDelegation: createEnvironmentCommand(runtime, {
+ label: "environment-data:commands:delegation:cancel",
+ execute: (input: CancelDelegationInput) => cancelDelegation(input),
+ scheduler,
+ concurrency: {
+ mode: "serial",
+ key: ({ environmentId, input }) =>
+ JSON.stringify([environmentId, "delegation", input.delegationId]),
+ },
+ }),
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:turn-diff",
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts
index b5612df5b..8eb6034bd 100644
--- a/packages/client-runtime/src/state/shell-sync.test.ts
+++ b/packages/client-runtime/src/state/shell-sync.test.ts
@@ -44,6 +44,7 @@ const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
snapshotSequence: 1,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "2026-06-06T00:00:00.000Z",
@@ -158,6 +159,7 @@ describe("environment shell synchronization", () => {
snapshotSequence: 5,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [{ id: "cached-thread" } as never],
updatedAt: "2026-06-06T00:00:00.000Z",
diff --git a/packages/client-runtime/src/state/shell.test.ts b/packages/client-runtime/src/state/shell.test.ts
index 4e4ca82e1..063a3d8dd 100644
--- a/packages/client-runtime/src/state/shell.test.ts
+++ b/packages/client-runtime/src/state/shell.test.ts
@@ -39,6 +39,7 @@ function shellState(input: {
projects: [],
bots: [],
groups: [],
+ delegations: [],
threads: [],
}),
status: input.status,
diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts
index 8e985ec16..51b429aab 100644
--- a/packages/client-runtime/src/state/shellReducer.test.ts
+++ b/packages/client-runtime/src/state/shellReducer.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
+ AkeruDelegationRecord,
BotId,
GroupId,
McpServerId,
@@ -8,6 +9,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
import { applyShellStreamEvent } from "./shellReducer.ts";
@@ -16,11 +18,47 @@ const baseSnapshot: OrchestrationShellSnapshot = {
snapshotSequence: 0,
bots: [],
groups: [],
+ delegations: [],
projects: [],
threads: [],
updatedAt: "2026-04-01T00:00:00.000Z",
};
+const stubDelegation = Schema.decodeUnknownSync(AkeruDelegationRecord)({
+ delegationId: "delegation-1",
+ parentDelegationId: null,
+ parentBotId: "bot-parent",
+ childBotId: "bot-child",
+ parentThreadId: "thread-parent",
+ childThreadId: null,
+ parentTurnId: "turn-parent",
+ childTurnId: null,
+ ancestorBotIds: ["bot-parent"],
+ depth: 1,
+ task: "Compare the release options.",
+ expectedResult: "A short comparison.",
+ deadline: null,
+ access: {
+ allowedToolIds: ["Read"],
+ memoryScopes: ["project"],
+ sandbox: "local",
+ runtimeMode: "approval-required",
+ hasUserComputer: false,
+ enabledMcpServerIds: [],
+ disabledMcpServerIds: [],
+ approvalCeiling: "none",
+ },
+ state: "queued",
+ billedBotId: "bot-child",
+ result: null,
+ failure: null,
+ keep: false,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ startedAt: null,
+ completedAt: null,
+});
+
const stubProject = {
id: ProjectId.make("project-1"),
title: "Test Project",
@@ -260,6 +298,25 @@ describe("applyShellStreamEvent", () => {
});
});
+ describe("delegation-upserted", () => {
+ it("adds and updates a delegation by id", () => {
+ const added = applyShellStreamEvent(baseSnapshot, {
+ kind: "delegation-upserted",
+ sequence: 9,
+ delegation: stubDelegation,
+ });
+ const updated = applyShellStreamEvent(added, {
+ kind: "delegation-upserted",
+ sequence: 10,
+ delegation: { ...stubDelegation, state: "running", startedAt: stubDelegation.createdAt },
+ });
+
+ expect(updated.delegations).toHaveLength(1);
+ expect(updated.delegations[0]?.state).toBe("running");
+ expect(updated.snapshotSequence).toBe(10);
+ });
+ });
+
describe("thread-upserted", () => {
it("adds a new thread", () => {
const event: OrchestrationShellStreamEvent = {
diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts
index fa2bd75cc..5dfa1ad8d 100644
--- a/packages/client-runtime/src/state/shellReducer.ts
+++ b/packages/client-runtime/src/state/shellReducer.ts
@@ -64,6 +64,18 @@ export function applyShellStreamEvent(
),
snapshotSequence: event.sequence,
};
+ case "delegation-upserted": {
+ const delegations = snapshot.delegations.some(
+ (delegation) => delegation.delegationId === event.delegation.delegationId,
+ )
+ ? Arr.map(snapshot.delegations, (delegation) =>
+ delegation.delegationId === event.delegation.delegationId
+ ? event.delegation
+ : delegation,
+ )
+ : Arr.append(snapshot.delegations, event.delegation);
+ return { ...snapshot, delegations, snapshotSequence: event.sequence };
+ }
case "thread-upserted": {
const threads = snapshot.threads.some((t) => t.id === event.thread.id)
? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))
diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts
index 76a7eed0b..449fb2e42 100644
--- a/packages/contracts/src/orchestration.test.ts
+++ b/packages/contracts/src/orchestration.test.ts
@@ -17,6 +17,7 @@ import {
OrchestrationGetTurnDiffInput,
OrchestrationLatestTurn,
OrchestrationReadModel,
+ OrchestrationShellSnapshot,
ProjectCreatedPayload,
ProjectMetaUpdatedPayload,
OrchestrationProposedPlan,
@@ -47,6 +48,7 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
);
const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn);
const decodeOrchestrationReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
+const decodeOrchestrationShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
const decodeOrchestrationThread = Schema.decodeUnknownEffect(OrchestrationThread);
@@ -612,6 +614,19 @@ it.effect("defaults delegations when decoding historical read models", () =>
}),
);
+it.effect("defaults delegations when decoding historical shell snapshots", () =>
+ Effect.gen(function* () {
+ const snapshot = yield* decodeOrchestrationShellSnapshot({
+ snapshotSequence: 1,
+ projects: [],
+ threads: [],
+ updatedAt: "2026-08-31T00:00:00.000Z",
+ });
+
+ assert.deepEqual(snapshot.delegations, []);
+ }),
+);
+
it.effect("decodes thread archived and unarchived events", () =>
Effect.gen(function* () {
const archived = yield* decodeOrchestrationEvent({
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 4e347a6df..815d1777e 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -647,6 +647,9 @@ export const OrchestrationShellSnapshot = Schema.Struct({
projects: Schema.Array(OrchestrationProjectShell),
bots: Schema.Array(OrchestrationBot).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
groups: Schema.Array(OrchestrationGroup).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
+ delegations: Schema.Array(Schema.suspend(() => AkeruDelegationRecord)).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
mcpServers: Schema.optional(Schema.Array(McpServer)),
threads: Schema.Array(OrchestrationThreadShell),
updatedAt: IsoDateTime,
@@ -689,6 +692,11 @@ export const OrchestrationShellStreamEvent = Schema.Union([
sequence: NonNegativeInt,
mcpServerId: McpServerId,
}),
+ Schema.Struct({
+ kind: Schema.Literal("delegation-upserted"),
+ sequence: NonNegativeInt,
+ delegation: Schema.suspend(() => AkeruDelegationRecord),
+ }),
Schema.Struct({
kind: Schema.Literal("thread-upserted"),
sequence: NonNegativeInt,