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
36 changes: 3 additions & 33 deletions apps/mobile/src/features/threads/ChildThreadApprovals.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts";
import type {
ChildThreadApproval,
ChildThreadSecretRequest,
} from "@t3tools/client-runtime/state/thread-requests";
import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
Expand All @@ -13,15 +10,9 @@ import { useEnvironmentScope } from "../../state/session";
import { ScrollView, View } from "react-native";
import Animated, { useAnimatedStyle, type DerivedValue } from "react-native-reanimated";
import { AppText } from "../../components/ui/AppText";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import {
childThreadApprovalsAtom,
childThreadSecretRequestsAtom,
threadEnvironment,
} from "../../state/threads";
import { childThreadApprovalsAtom, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { SecretRequestCard } from "./SecretRequestCard";

function ChildApproval({ entry }: { entry: ChildThreadApproval }) {
const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope);
Expand Down Expand Up @@ -68,20 +59,6 @@ function ChildApproval({ entry }: { entry: ChildThreadApproval }) {
);
}

function ChildSecret({ entry }: { entry: ChildThreadSecretRequest }) {
const iconColor = useUniwindTheme()["--color-icon-subtle"];
return (
<View className="mx-3.5 my-2 gap-2">
<AppText className="font-t3-bold text-sm text-foreground">Secret from {entry.title}</AppText>
<SecretRequestCard
environmentId={entry.thread.environmentId}
projectedItem={{ item: entry.item, visibility: "local" }}
iconColor={iconColor}
/>
</View>
);
}

export function ChildThreadApprovals({
threadRef,
maxHeight,
Expand All @@ -90,18 +67,11 @@ export function ChildThreadApprovals({
maxHeight: DerivedValue<number>;
}) {
const approvals = useAtomValue(childThreadApprovalsAtom(threadRef));
const secrets = useAtomValue(childThreadSecretRequestsAtom(threadRef));
const heightStyle = useAnimatedStyle(() => ({ maxHeight: Math.min(320, maxHeight.value / 2) }));
if (approvals.length === 0 && secrets.length === 0) return null;
if (approvals.length === 0) return null;
return (
<Animated.View style={heightStyle} className="overflow-hidden">
<ScrollView keyboardShouldPersistTaps="handled" nestedScrollEnabled style={{ flexShrink: 1 }}>
{secrets.map((entry) => (
<ChildSecret
key={JSON.stringify([entry.thread.environmentId, entry.item.id])}
entry={entry}
/>
))}
{approvals.map((entry) => (
<ChildApproval
key={JSON.stringify([
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/src/features/threads/SecretRequestCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const PRIVATE_SYMBOL: AppSymbolName = { ios: "checkmark.shield", android: "lock"

export function SecretRequestCard(props: {
readonly environmentId: EnvironmentId;
readonly projectedItem: Pick<OrchestrationV2ProjectedTurnItem, "item" | "visibility">;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly iconColor: ColorValue;
}) {
const { item, visibility } = props.projectedItem;
Expand Down
9 changes: 1 addition & 8 deletions apps/mobile/src/state/threads.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
createChildThreadApprovalsAtom,
createChildThreadSecretRequestsAtom,
} from "@t3tools/client-runtime/state/thread-requests";
import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests";
import { useAtomValue } from "@effect/atom-react";
import { createSandboxStartQueueAtoms } from "@t3tools/client-runtime/state/sandbox-mirror";
import {
Expand Down Expand Up @@ -77,10 +74,6 @@ export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,
});
export const childThreadSecretRequestsAtom = createChildThreadSecretRequestsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
visibleTurnItemsAtom: environmentThreadDetails.visibleTurnItemsAtom,
});

// Long enough for the opened screen to subscribe; its subscription keeps the thread after this.
const OPENING_THREAD_HOLD_MS = 3_000;
Expand Down
1 change: 0 additions & 1 deletion apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2834,7 +2834,6 @@ const make = Effect.gen(function* () {
parentNodeId: parentRun.rootNodeId,
task: taskPrompt(input),
...(input.title === undefined ? {} : { title: input.title }),
...(input.group === undefined ? {} : { group: input.group }),
modelSelection: target.modelSelection,
runtimeMode,
interactionMode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,6 @@ describe("orchestrator MCP toolkit", () => {
providerInstanceId: codexInstanceId,
model: codexModel,
},
group: "Backend",
mode: "async",
clientRequestId: "delegate-codex-replay-1",
});
Expand Down Expand Up @@ -466,11 +465,6 @@ describe("orchestrator MCP toolkit", () => {
);
expect(followupTasks).toHaveLength(2);
expect(followupTasks.every((task) => task.result === null)).toBe(true);
const parentNow = yield* orchestrator.getThreadProjection(parentThreadId);
expect(parentNow.subagents.find((task) => task.id === delegated.taskId)).toMatchObject({
group: "Backend",
});
expect(followupTasks.map((task) => task.group)).toEqual(["Backend", "Backend"]);
expect(followupTasks.map((task) => task.id)).toEqual([
runningFollowup.taskId,
queuedFollowup.taskId,
Expand Down
2 changes: 0 additions & 2 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9515,7 +9515,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nativeTaskRef: null,
prompt: command.task,
title: command.title ?? null,
...(command.group === undefined ? {} : { group: command.group }),
model: command.modelSelection.model,
modelSelection: command.modelSelection,
...(command.completionWake === undefined ? {} : { completionWake: command.completionWake }),
Expand Down Expand Up @@ -9979,7 +9978,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nativeTaskRef: null,
prompt: command.task,
title: command.title ?? null,
...(command.group === undefined ? {} : { group: command.group }),
model: command.modelSelection.model,
modelSelection: command.modelSelection,
...(command.completionWake === undefined ? {} : { completionWake: command.completionWake }),
Expand Down
133 changes: 0 additions & 133 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9350,139 +9350,6 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
}),
);

it.effect("shells carry the latest tool action, from the list and from the projection", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const sql = yield* SqlClient.SqlClient;
const suffix = "shell-latest-action";
const threadId = yield* addRolledBackRecoveryCandidate(suffix);
const runId = RunId.make(`run:${suffix}:live`);
const nodeId = NodeId.make(`node:${suffix}:live`);
const now = yield* DateTime.now;
yield* projectionStore.apply({
id: EventId.make(`event:${suffix}:live-run`),
type: "run.created",
threadId,
runId,
nodeId,
driver,
providerInstanceId,
occurredAt: now,
payload: {
id: runId,
threadId,
ordinal: 2,
providerInstanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make(`message:${suffix}:live`),
rootNodeId: nodeId,
activeAttemptId: null,
status: "running",
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
},
});
const base = {
threadId,
runId,
nodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
status: "running" as const,
title: null,
completedAt: null,
};
const addItem = (
id: string,
ordinal: number,
item:
| { readonly type: "command_execution"; readonly input: string; readonly output?: string }
| { readonly type: "file_change"; readonly fileName: string; readonly diffStr?: string }
| { readonly type: "reasoning"; readonly text: string; readonly streaming: boolean },
) =>
projectionStore.apply({
id: EventId.make(`event:${suffix}:${id}`),
type: "turn-item.updated",
threadId,
runId,
nodeId,
driver,
occurredAt: now,
payload: {
...base,
...item,
id: TurnItemId.make(`item:${suffix}:${id}`),
ordinal,
startedAt: DateTime.add(now, { seconds: ordinal }),
updatedAt: DateTime.add(now, { seconds: ordinal + 30 }),
},
});
const latestActions = Effect.gen(function* () {
const listed = (yield* projectionStore.getShellSnapshot()).threads.find(
(thread) => thread.id === threadId,
);
const projected = ProjectionStore.threadShellFromProjection(
yield* projectionStore.getThreadProjection(threadId),
);
return [listed?.latestAction, projected.latestAction];
});

// Only the rolled-back run's command so far.
assert.deepEqual(yield* latestActions, [null, null]);

yield* addItem("command", 2, {
type: "command_execution",
input: "pnpm test",
output: "x".repeat(4096),
});
const ranCommand = {
summary: "Ran command",
detail: "pnpm test",
at: DateTime.add(now, { seconds: 2 }),
};
assert.deepEqual(yield* latestActions, [ranCommand, ranCommand]);

yield* addItem("edit", 3, {
type: "file_change",
fileName: "src/auth/session.ts",
diffStr: "+".repeat(4096),
});
const changedFile = {
summary: "Changed files",
detail: "src/auth/session.ts",
at: DateTime.add(now, { seconds: 3 }),
};
assert.deepEqual(yield* latestActions, [changedFile, changedFile]);

yield* addItem("thought", 4, { type: "reasoning", text: "Next, the tests", streaming: true });
assert.deepEqual(yield* latestActions, [changedFile, changedFile]);

const longCommand = `echo ${"a".repeat(300)}`;
yield* addItem("long", 5, { type: "command_execution", input: longCommand });
const [listed] = yield* latestActions;
assert.lengthOf(listed?.detail ?? "", 120);
assert.isTrue(listed?.detail?.endsWith("…"));

const { statements, tracer } = traceSqlStatements();
yield* projectionStore.getShellSnapshot().pipe(Effect.withTracer(tracer));
const statement = statements.find((query) => query.includes("AS latest_tool_payload_json"));
assert.isDefined(statement);
const plan = (yield* sql.unsafe<{ readonly detail: string }>(
`EXPLAIN QUERY PLAN ${statement}`,
)).map((row) => row.detail);
assert.isTrue(
plan.some((detail) => detail.includes("turn_items_latest_tool_idx (thread_id=?)")),
plan.join("\n"),
);
}),
);

it.effect("counts history inherited by fork shells, but not by side chats", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
Expand Down
46 changes: 0 additions & 46 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ import * as SqlClient from "effect/sql/SqlClient";
import type * as Statement from "effect/sql/Statement";

import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";
import { LATEST_ACTION_ITEM_TYPES, latestActionFromTurnItem } from "./latestAction.ts";
import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts";
import { readableSearchText } from "./messageSearchIndex.ts";
import {
Expand Down Expand Up @@ -1145,7 +1144,6 @@ type ShellThreadRow = {
readonly blocking_failure_payload_json: string | null;
readonly pending_request_payload_json: string | null;
readonly pending_secret_request_payload_json: string | null;
readonly latest_tool_payload_json: string | null;
readonly pending_link_request_payload_json: string | null;
readonly latest_user_message_at: string | null;
readonly latest_user_authored_message_at: string | null;
Expand Down Expand Up @@ -1711,27 +1709,6 @@ const linkCardStillAsks = (
latestUserAuthoredMessageAt === null ||
!DateTime.isGreaterThan(latestUserAuthoredMessageAt, item.startedAt ?? item.updatedAt);

function latestToolItem(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2TurnItem | null {
const rolledBack = new Set(
projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
);
const types: ReadonlyArray<string> = LATEST_ACTION_ITEM_TYPES;
let latest: OrchestrationV2TurnItem | null = null;
for (const item of projection.turnItems) {
if (!types.includes(item.type) || (item.runId !== null && rolledBack.has(item.runId))) continue;
if (
latest === null ||
item.ordinal > latest.ordinal ||
(item.ordinal === latest.ordinal && item.id > latest.id)
) {
latest = item;
}
}
return latest;
}

export function threadShellFromProjection(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadShell {
Expand Down Expand Up @@ -1867,7 +1844,6 @@ export function threadShellFromProjection(
// Thread detail owns message bodies. Keeping them out of shell rows makes
// initial hydration and streaming updates independent of transcript size.
latestVisibleMessage: null,
latestAction: latestActionFromTurnItem(latestToolItem(projection)),
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
latestUserAuthoredMessageAt,
hasActionableProposedPlan: projection.plans.some(
Expand Down Expand Up @@ -2006,7 +1982,6 @@ type ShellThreadState = {
readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"];
readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"];
readonly goal: OrchestrationV2ThreadShell["goal"];
readonly latestAction: OrchestrationV2ThreadShell["latestAction"];
readonly itemCount: number;
readonly runlessItemCount: number;
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
Expand Down Expand Up @@ -2174,7 +2149,6 @@ function shellFromState(input: {
pendingRuntimeRequest: input.state.pendingRuntimeRequest,
pendingGuestMessageCount: pendingGuestMessageCount(input.state.thread.guestShare),
latestVisibleMessage: null,
latestAction: input.state.latestAction,
latestUserMessageAt: input.state.latestUserMessageAt,
latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
Expand Down Expand Up @@ -8013,19 +7987,6 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ORDER BY link.updated_at DESC, link.turn_item_id DESC
LIMIT 1
) AS pending_link_request_payload_json,
(
-- Tool output and diffs can be megabytes; the label needs none of them.
SELECT json_remove(tool.payload_json,
'$.output', '$.diffStr', '$.oldStr', '$.newStr', '$.changes', '$.results')
FROM orchestration_v2_projection_turn_items tool
INDEXED BY orchestration_v2_projection_turn_items_latest_tool_idx
LEFT JOIN orchestration_v2_projection_runs tool_run ON tool_run.run_id = tool.run_id
WHERE tool.thread_id = t.thread_id
AND tool.type IN ('command_execution', 'file_change', 'file_search', 'web_search', 'dynamic_tool')
AND (tool.run_id IS NULL OR tool_run.status <> 'rolled_back')
ORDER BY tool.ordinal DESC, tool.turn_item_id DESC
LIMIT 1
) AS latest_tool_payload_json,
(
SELECT message.updated_at
FROM orchestration_v2_projection_messages message
Expand Down Expand Up @@ -8597,12 +8558,6 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
pendingRuntimeRequest = waitingCard;
}
}
const latestToolItem =
row.latest_tool_payload_json === null
? null
: yield* decodeTurnItemPayload(row.latest_tool_payload_json).pipe(
Effect.orElseSucceed(() => null),
);
let terminalFailureItem =
row.terminal_failure_payload_json === null
? null
Expand Down Expand Up @@ -8717,7 +8672,6 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
providerThreadsByThreadId.get(thread.id) ?? [],
thread.activeProviderThreadId,
),
latestAction: latestActionFromTurnItem(latestToolItem),
itemCount: shellItemCountsByThreadId.get(thread.id)?.itemCount ?? 0,
runlessItemCount: shellItemCountsByThreadId.get(thread.id)?.runlessItemCount ?? 0,
updatedAt: thread.updatedAt,
Expand Down
Loading