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
14 changes: 14 additions & 0 deletions apps/server/src/orchestration-v2/ShellStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,20 @@ describe("subagent shell events", () => {
expect([tool("running"), tool("completed"), tool("failed")]).toEqual([false, true, true]);
});

it("publishes a subagent's secret or link card so its parent hears it waits on you", () => {
const subagents = new Set(["child"]);
const card = (type: string, status: string) =>
shouldPublishShellApplicationEvent(
stored("child", "turn-item.updated", { type, status }),
subagents,
);
expect([
card("secret_request", "waiting"),
card("secret_request", "completed"),
card("link_request", "waiting"),
]).toEqual([true, true, true]);
});

it("tracks subagents created after the subscription starts", () => {
const subagents = new Set<string>();
const created = {
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/orchestration-v2/ShellStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,14 @@ export function shouldPublishShellApplicationEvent(

const LATEST_ACTION_TYPES: ReadonlySet<string> = new Set(LATEST_ACTION_ITEM_TYPES);

/** A finished tool moves the child's latest action; streaming tool output does not. */
/**
* A secret or link card is the child's only record of waiting on you, so its parent must hear it.
* A finished tool moves the child's latest action; streaming tool output does not.
*/
const changesChildShell = (item: { readonly type: string; readonly status: string }) =>
LATEST_ACTION_TYPES.has(item.type) && item.status !== "running" && item.status !== "pending";
item.type === "secret_request" ||
item.type === "link_request" ||
(LATEST_ACTION_TYPES.has(item.type) && item.status !== "running" && item.status !== "pending");

/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ const state = vi.hoisted(() => ({ respond: vi.fn(), approvalsAtom: null as unkno

vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));
vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.respond }));
vi.mock("./SecretRequestCard", () => ({ SecretRequestCard: () => null }));
vi.mock("../../state/threads", () => ({
childThreadApprovalsAtom: () => state.approvalsAtom,
childThreadSecretRequestsAtom: () => Atom.make([]),
threadEnvironment: { respondToApproval: {} },
}));

Expand Down
18 changes: 16 additions & 2 deletions apps/web/src/components/chat/ChildThreadApprovals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import { useState } from "react";
import { useEnvironmentScope } from "../../state/session";
import { childThreadApprovalsAtom, threadEnvironment } from "../../state/threads";
import {
childThreadApprovalsAtom,
childThreadSecretRequestsAtom,
threadEnvironment,
} from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
import { SecretRequestCard } from "./SecretRequestCard";

function ChildApproval({ entry }: { entry: ChildThreadApproval }) {
const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope);
Expand Down Expand Up @@ -77,9 +82,18 @@ function ChildApproval({ entry }: { entry: ChildThreadApproval }) {

export function ChildThreadApprovals({ threadRef }: { threadRef: ScopedThreadRef | null }) {
const approvals = useAtomValue(childThreadApprovalsAtom(threadRef));
if (approvals.length === 0) return null;
const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef));
if (approvals.length === 0 && secrets.length === 0) return null;
return (
<div className="mb-2 flex max-h-80 flex-col gap-2 overflow-auto">
{secrets.map((entry) => (
<SecretRequestCard
key={JSON.stringify([entry.thread.environmentId, entry.item.id])}
environmentId={entry.thread.environmentId}
item={entry.item}
visibility="local"
/>
))}
{approvals.map((entry) => (
<ChildApproval
key={JSON.stringify([
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/state/threads.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests";
import {
createChildThreadApprovalsAtom,
createChildThreadSecretRequestsAtom,
} from "@t3tools/client-runtime/state/thread-requests";
import { useAtomValue } from "@effect/atom-react";
import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";
import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities";
Expand Down Expand Up @@ -46,6 +49,10 @@ export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,
});
export const childThreadSecretRequestsAtom = createChildThreadSecretRequestsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
visibleTurnItemsAtom: environmentThreadDetails.visibleTurnItemsAtom,
});

const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
Atom.withLabel("web-environment-thread:empty"),
Expand Down
51 changes: 51 additions & 0 deletions packages/client-runtime/src/state/threadRequests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixture
import {
createQuestionHistoryProjector,
createChildThreadApprovalsAtom,
createChildThreadSecretRequestsAtom,
type PendingThreadRequests,
derivePendingThreadRequests,
declinePendingApprovals,
Expand Down Expand Up @@ -633,6 +634,56 @@ it("loads only child approvals and retains their destination across environments
);
expect(registry.get(approvalsAtom(parent))).toEqual([]);
expect(readDetails).not.toHaveBeenCalled();

// The same children now wait on a secret: only their waiting cards reach the parent.
const card = (id: string, secretStatus: "pending" | "saved") => ({
position: 0,
visibility: "local" as const,
sourceThreadId: childId,
sourceItemId: TurnItemId.make(id),
item: {
id: TurnItemId.make(id),
threadId: childId,
runId: null,
nodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: secretStatus === "pending" ? ("waiting" as const) : ("completed" as const),
title: "GITHUB_CLIENT_SECRET",
startedAt: v2Now,
completedAt: null,
updatedAt: v2Now,
type: "secret_request" as const,
label: "GITHUB_CLIENT_SECRET",
reason: "To test the real OAuth flow",
secretStatus,
},
});
const items = Atom.family((key: string) =>
Atom.make<OrchestrationV2ThreadProjection["visibleTurnItems"]>(
key.startsWith(local) ? [card("saved", "saved"), card("asking", "pending")] : [],
),
);
const readItems = vi.fn((ref: ScopedThreadRef) => items(threadKey(ref)));
const secretsAtom = createChildThreadSecretRequestsAtom({
childThreadInputsAtom: () => children,
visibleTurnItemsAtom: readItems,
});
const unmountSecrets = registry.mount(secretsAtom(parent));
expect(
registry.get(secretsAtom(parent)).map((entry) => [entry.thread.environmentId, entry.item.id]),
).toEqual([[local, "asking"]]);
readItems.mockClear();
registry.set(
children,
registry.get(children).map((child) => ({ ...child, hasPendingUserInput: false })),
);
expect(registry.get(secretsAtom(parent))).toEqual([]);
expect(readItems).not.toHaveBeenCalled();
unmountSecrets();
unmount();
registry.dispose();
});
51 changes: 51 additions & 0 deletions packages/client-runtime/src/state/threadRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
ScopedThreadRef,
ThreadId,
OrchestrationV2ThreadProjection,
OrchestrationV2TurnItem,
OrchestrationV2RuntimeRequest,
OrchestrationV2UserInputQuestion,
ProviderApprovalFullAccessOverride,
Expand Down Expand Up @@ -393,3 +394,53 @@ export function createChildThreadApprovalsAtom(input: {
const empty = Atom.make<ReadonlyArray<ChildThreadApproval>>([]);
return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref)));
}

export interface ChildThreadSecretRequest {
readonly thread: ScopedThreadRef;
readonly title: string;
readonly item: Extract<OrchestrationV2TurnItem, { readonly type: "secret_request" }>;
}

/** Waiting secret cards of the child threads under `ref`, so the parent can answer them. */
export function createChildThreadSecretRequestsAtom(input: {
readonly childThreadInputsAtom: (
ref: ScopedThreadRef,
) => Atom.Atom<ReadonlyArray<EnvironmentThreadShell>>;
readonly visibleTurnItemsAtom: (
ref: ScopedThreadRef,
) => Atom.Atom<OrchestrationV2ThreadProjection["visibleTurnItems"]>;
}) {
const family = Atom.family((key: string) => {
let previous: ReadonlyArray<ChildThreadSecretRequest> = [];
return Atom.make((get) => {
const next = get(input.childThreadInputsAtom(parseThreadKey(key))).flatMap((child) => {
if (!child.hasPendingUserInput) return [];
const thread = { environmentId: child.environmentId, threadId: child.id };
// Only children waiting on input need a detail subscription.
return get(input.visibleTurnItemsAtom(thread)).flatMap(({ item, visibility }) =>
item.type === "secret_request" &&
item.secretStatus === "pending" &&
visibility === "local"
? [{ thread, title: child.title, item }]
: [],
);
});
if (
next.length === previous.length &&
next.every((entry, index) => {
const old = previous[index]!;
return (
old.item === entry.item &&
old.title === entry.title &&
threadKey(old.thread) === threadKey(entry.thread)
);
})
)
return previous;
previous = next;
return next;
});
});
const empty = Atom.make<ReadonlyArray<ChildThreadSecretRequest>>([]);
return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref)));
}