Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
355a1c5985 | ||
|
|
6b73b3defe | ||
|
|
7aad7911f6 | ||
|
|
6da92244cc | ||
|
|
c471145e96 | ||
|
|
64a991ad45 | ||
|
|
0ec4fbc4a3 | ||
|
|
ea50b695a7 | ||
|
|
331c6dce7f | ||
|
|
4f5834ba72 | ||
|
|
aa16c180e5 | ||
|
|
470d4eb993 | ||
|
|
99d91ddaa4 | ||
|
|
ab3b55e29a | ||
|
|
e4abc31f1e | ||
|
|
b7d1981b57 | ||
|
|
64a3cd6d7d | ||
|
|
48e2c27f2f | ||
|
|
8b2ea5721a | ||
|
|
df2f1273e9 | ||
|
|
f9e8236899 | ||
|
|
8f341f20c9 | ||
|
|
808d685355 | ||
|
|
80720ad592 | ||
|
|
a483337a02 | ||
|
|
1ffba7093a | ||
|
|
3da315e7b5 | ||
|
|
a2ca89aa10 | ||
|
|
990bb0b689 |
No files matched your search
@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ export interface PendingApprovalCardProps {
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
|
||||
// behind this card, so a translucent surface bleeds messages through it.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
Approval needed
|
||||
</Text>
|
||||
|
||||
@@ -24,8 +24,11 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface ThreadDetailScreenProps {
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
@@ -371,6 +373,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
|
||||
@@ -164,6 +164,11 @@ export interface ThreadFeedProps {
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
readonly loading: boolean;
|
||||
readonly onLoadEarlier: () => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -1893,7 +1898,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.loadEarlier != null ? (
|
||||
<Pressable
|
||||
onPress={props.loadEarlier.onLoadEarlier}
|
||||
disabled={props.loadEarlier.loading}
|
||||
className="items-center py-2"
|
||||
>
|
||||
<Text className="text-xs text-foreground-secondary">
|
||||
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
requestOlderThreadTurns,
|
||||
threadHasOlderTurns,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -190,6 +194,20 @@ function ThreadRouteContent(
|
||||
useThreadSelection();
|
||||
const selectedThreadDetailState = props.selectedThreadDetailState;
|
||||
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
|
||||
// "Load earlier turns" header state for windowed (paginated) thread loads.
|
||||
const loadEarlierTurns = useMemo(() => {
|
||||
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
loading:
|
||||
selectedThreadDetailState.page._tag === "Some" &&
|
||||
selectedThreadDetailState.page.value.loadingOlder,
|
||||
onLoadEarlier: () => {
|
||||
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
|
||||
},
|
||||
};
|
||||
}, [selectedThread, selectedThreadDetailState]);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
@@ -766,6 +784,7 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
|
||||
@@ -532,3 +532,39 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("quiet timeline: nested agents", () => {
|
||||
it("keeps a nested agent's terminal row but hides its background work", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-nested"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Nested agents",
|
||||
activities: [
|
||||
// A subagent's own shell: internal, covered by the owner's liveness.
|
||||
makeActivity({
|
||||
id: EventId.make("shell-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
|
||||
}),
|
||||
// A nested AGENT's completion: mobile has no Agents sheet, so this
|
||||
// terminal row is the only signal it ever finished.
|
||||
makeActivity({
|
||||
id: EventId.make("nested-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const ids = feed.flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
|
||||
);
|
||||
expect(ids).toContain("nested-done");
|
||||
expect(ids).not.toContain("shell-done");
|
||||
});
|
||||
});
|
||||
@@ -80,6 +80,8 @@ interface WorkLogEntry {
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
activityKind: OrchestrationThreadActivity["kind"];
|
||||
collapseKey?: string;
|
||||
/** Grouping key for subagent lifecycle rows (one row per agent). */
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
type RawThreadFeedEntry =
|
||||
@@ -235,6 +237,63 @@ function resolvePendingUserInputAnswer(
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
* task.completed — these rows are mobile's only terminal signal for them. */
|
||||
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
|
||||
"idle",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
]);
|
||||
|
||||
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
|
||||
if (activity.kind !== "task.updated") {
|
||||
return false;
|
||||
}
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
return (
|
||||
payload?.timelineBypass === true &&
|
||||
typeof payload.status === "string" &&
|
||||
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
|
||||
* activity lives in the Agents sheet, not the work log. Terminal rows are
|
||||
* kept — with no Agents surface on mobile they are the terminal signal
|
||||
* (a surface that hides rows must keep its own terminal signal). That means
|
||||
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
|
||||
* children never emit task.completed — review finding).
|
||||
*/
|
||||
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
if (!payload) {
|
||||
return false;
|
||||
}
|
||||
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
|
||||
if (payload.timelineBypass === true && !isTerminalTaskRow) {
|
||||
return true;
|
||||
}
|
||||
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
|
||||
// the only signal mobile gets (no Agents sheet), so it stays. Only an
|
||||
// agent's own background work (stamped "background") is internal — same
|
||||
// rule as web (review finding: hiding on agentId alone dropped nested
|
||||
// completions with no replacement UI).
|
||||
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
|
||||
if (!ownedByAgent) {
|
||||
return false;
|
||||
}
|
||||
return !(isTerminalTaskRow && payload.agentKind === "agent");
|
||||
}
|
||||
|
||||
function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
@@ -243,9 +302,13 @@ function deriveWorkLogEntries(
|
||||
for (const activity of ordered) {
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started") continue;
|
||||
// Terminal bypassed updates pass: Codex children's only terminal signal.
|
||||
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
|
||||
if (activity.kind === "tool.progress") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
if (activity.summary === "Checkpoint captured") continue;
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
if (isAgentInternalActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries);
|
||||
@@ -271,7 +334,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
|
||||
// task.updated included: terminal bypassed updates (Codex children's only
|
||||
// terminal signal) must carry task identity so they collapse per child
|
||||
// instead of stacking anonymous "Task idle" rows.
|
||||
const isTaskActivity =
|
||||
activity.kind === "task.progress" ||
|
||||
activity.kind === "task.completed" ||
|
||||
activity.kind === "task.updated";
|
||||
const taskSummary =
|
||||
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
|
||||
? payload.summary
|
||||
@@ -284,10 +353,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
? payload.detail
|
||||
: null;
|
||||
const taskLabel = taskSummary || taskDetailAsLabel;
|
||||
const taskId =
|
||||
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
|
||||
? payload.taskId
|
||||
: undefined;
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
...(taskId ? { taskId } : {}),
|
||||
label: taskLabel || activity.summary,
|
||||
tone:
|
||||
activity.kind === "task.progress"
|
||||
@@ -352,7 +426,25 @@ function collapseDerivedWorkLogEntries(
|
||||
entries: ReadonlyArray<DerivedWorkLogEntry>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
const collapsed: DerivedWorkLogEntry[] = [];
|
||||
// Subagent rows collapse by identity, not adjacency (quiet-timeline
|
||||
// guarantee; mirrors web's session-logic).
|
||||
const taskRowIndex = new Map<string, number>();
|
||||
for (const entry of entries) {
|
||||
const isTaskRow =
|
||||
entry.taskId !== undefined &&
|
||||
(entry.activityKind === "task.progress" ||
|
||||
entry.activityKind === "task.completed" ||
|
||||
entry.activityKind === "task.updated");
|
||||
if (isTaskRow && entry.taskId !== undefined) {
|
||||
const existingIndex = taskRowIndex.get(entry.taskId);
|
||||
if (existingIndex !== undefined) {
|
||||
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
|
||||
continue;
|
||||
}
|
||||
taskRowIndex.set(entry.taskId, collapsed.length);
|
||||
collapsed.push(entry);
|
||||
continue;
|
||||
}
|
||||
const previous = collapsed.at(-1);
|
||||
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
|
||||
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
|
||||
|
||||
@@ -50,6 +50,7 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityRe
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
@@ -305,7 +306,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusTest,
|
||||
);
|
||||
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
|
||||
@@ -22,6 +22,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
||||
*/
|
||||
export const RPC_REQUIRED_SCOPES = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -31,7 +31,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
|
||||
});
|
||||
|
||||
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
|
||||
expect(unit).toContain("KillMode=control-group");
|
||||
expect(unit).toContain("KillMode=mixed");
|
||||
expect(unit).not.toContain("versions/1.2.3");
|
||||
});
|
||||
|
||||
|
||||
@@ -64,7 +64,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
|
||||
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
|
||||
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
|
||||
"KillMode=control-group",
|
||||
// Let the launcher mark an explicit stop before it signals the server.
|
||||
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
|
||||
"KillMode=mixed",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import {
|
||||
@@ -15,6 +18,14 @@ import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfigModule from "../config.ts";
|
||||
import { writeServiceState } from "../serviceLauncher.ts";
|
||||
import {
|
||||
SERVICE_LAUNCHER_PROTOCOL,
|
||||
SERVICE_STATE_FILE,
|
||||
SERVICE_STOP_MARKER_FILE,
|
||||
type ServiceUpdateRecord,
|
||||
} from "./serviceProtocol.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
@@ -24,6 +35,7 @@ import {
|
||||
consumeCloudReplayGuards,
|
||||
isSupportedLinkProviderKind,
|
||||
linkProofScopes,
|
||||
pendingServiceUpdateExists,
|
||||
reconcileDesiredCloudLink,
|
||||
releaseManagedTunnelOnShutdown,
|
||||
} from "./http.ts";
|
||||
@@ -256,6 +268,23 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
readonly respond?: () => Response;
|
||||
}
|
||||
|
||||
// Writes the launcher's durable state file into this test's baseDir with
|
||||
// the launcher's own writer; the release reads it to detect an in-flight
|
||||
// update handoff.
|
||||
const writeLauncherState = (update: ServiceUpdateRecord) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfigModule.ServerConfig;
|
||||
const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
|
||||
yield* Effect.promise(() =>
|
||||
writeServiceState(statePath, {
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
activeVersion: "0.0.30",
|
||||
update,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const provideReleaseHarness =
|
||||
(harness: ReleaseHarness) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
@@ -306,6 +335,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
}),
|
||||
),
|
||||
),
|
||||
// The release consults the launcher state file under the configured
|
||||
// baseDir, so every harness run gets a scoped temp baseDir.
|
||||
Effect.provide(
|
||||
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
// The persisted state of a CLI-managed link whose tunnel is releasable.
|
||||
@@ -390,6 +427,84 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending",
|
||||
});
|
||||
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
// The launcher restarts a server immediately, so the tunnel is not
|
||||
// orphaned; keeping it avoids the hostname route re-propagation that
|
||||
// dominates update downtime. The stored config must survive so the
|
||||
// next boot respawns the connector against the same tunnel.
|
||||
expect(released).toBe(false);
|
||||
expect(applyConfigCalls).toEqual([]);
|
||||
expect(requests).toEqual([]);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("still releases a pending update when the launcher is stopping", () => {
|
||||
// `t3 service uninstall` or `systemctl stop` during the pending window:
|
||||
// the launcher writes its stop marker before signalling the child, so no
|
||||
// replacement server is coming and the tunnel must not be kept.
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending",
|
||||
});
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfigModule.ServerConfig;
|
||||
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
|
||||
|
||||
expect(yield* pendingServiceUpdateExists).toBe(true);
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
expect(released).toBe(true);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("still releases when the recorded update already settled", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
status: "committed",
|
||||
});
|
||||
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
expect(released).toBe(true);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
|
||||
@@ -46,7 +46,9 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -56,8 +58,14 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { requireEnvironmentScope } from "../auth/http.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import {
|
||||
SERVICE_STATE_FILE,
|
||||
SERVICE_STOP_MARKER_FILE,
|
||||
serviceStateHasPendingUpdate,
|
||||
} from "./serviceProtocol.ts";
|
||||
import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
@@ -627,6 +635,37 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
},
|
||||
);
|
||||
|
||||
// The launcher owns this durable state, so read it directly both when a trial
|
||||
// decides whether it owns pre-activation cleanup and while a server tears down.
|
||||
export const pendingServiceUpdateExists = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runtimeDir = path.join(config.baseDir, "runtime");
|
||||
const stateText = yield* fs
|
||||
.readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
|
||||
.pipe(Effect.option);
|
||||
return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
|
||||
});
|
||||
|
||||
// A pending update alone is not proof a replacement server is coming: an
|
||||
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
|
||||
// the pending window also tears this server down. The launcher marks that case
|
||||
// just before it signals the child, so pending + no marker is the handoff.
|
||||
const pendingUpdateHandoffExists = Effect.gen(function* () {
|
||||
if (!(yield* pendingServiceUpdateExists)) {
|
||||
return false;
|
||||
}
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runtimeDir = path.join(config.baseDir, "runtime");
|
||||
const stopping = yield* fs
|
||||
.exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
return !stopping;
|
||||
});
|
||||
|
||||
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
|
||||
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
|
||||
// relay keeps the link and its hostname reservation, and the next startup's
|
||||
@@ -649,6 +688,19 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
|
||||
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
|
||||
return false;
|
||||
}
|
||||
// A shutdown that hands off to a pending remote update is not the
|
||||
// environment going offline: the launcher immediately brings a server back
|
||||
// (the new version, or the old one after a rollback). Deleting the tunnel
|
||||
// here forces that server to provision a replacement UUID, and the public
|
||||
// hostname's route to the new tunnel takes 1-2 minutes to propagate — the
|
||||
// dominant cost of an update restart. Keep the tunnel instead: the next
|
||||
// boot respawns the connector from the stored config and is reachable as
|
||||
// soon as it connects, and the reconcile confirms the still-live tunnel
|
||||
// without replacing it.
|
||||
if (yield* pendingUpdateHandoffExists) {
|
||||
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
|
||||
return false;
|
||||
}
|
||||
const token = yield* dependencies.cliTokenManager.getExisting;
|
||||
if (Option.isNone(token)) {
|
||||
return false;
|
||||
|
||||
@@ -5,6 +5,10 @@ export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
|
||||
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
|
||||
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
|
||||
export const SERVICE_STATE_FILE = "service-state.json";
|
||||
/** Written by the launcher just before an explicit stop kills its child, so
|
||||
the child can tell "the service is going away" from "the launcher is about
|
||||
to start my replacement" while a pending update is recorded. */
|
||||
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
|
||||
|
||||
export interface PendingServiceUpdate {
|
||||
readonly id: string;
|
||||
|
||||
@@ -69,6 +69,10 @@ export class GitWorkflowService extends Context.Service<
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<void, GitCommandError>;
|
||||
readonly remoteExists: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<boolean, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (input: {
|
||||
readonly cwd: string;
|
||||
readonly refName: string;
|
||||
@@ -303,6 +307,10 @@ export const make = Effect.gen(function* () {
|
||||
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
|
||||
Effect.andThen(git.fetchRemote(input)),
|
||||
),
|
||||
remoteExists: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
|
||||
Effect.andThen(git.remoteExists(input)),
|
||||
),
|
||||
resolveRemoteTrackingCommit: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
|
||||
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
|
||||
|
||||
function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: "activity-1",
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool",
|
||||
payload,
|
||||
turnId: null,
|
||||
createdAt: "2026-08-01T10:00:00.000Z",
|
||||
} as unknown as OrchestrationThreadActivity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire-survival regression: the slimming pass rewrites payload.data but must
|
||||
* never strip the top-level per-agent fields the subagent fold depends on.
|
||||
* If slimming ever moves to an allowlist over the whole payload, these
|
||||
* assertions are the tripwire.
|
||||
*/
|
||||
describe("projectActivityPayload agent-field survival", () => {
|
||||
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "command_execution",
|
||||
agentId: "task-123",
|
||||
parentToolUseId: "toolu_abc",
|
||||
data: {
|
||||
toolName: "Bash",
|
||||
input: { command: "ls" },
|
||||
command: "ls",
|
||||
rawOutput: { content: "x".repeat(10) },
|
||||
somethingClientNeverReads: { big: "blob" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
const payload = projected.payload as Record<string, unknown>;
|
||||
expect(payload.agentId).toBe("task-123");
|
||||
expect(payload.parentToolUseId).toBe("toolu_abc");
|
||||
// Slimming itself still applies to data.
|
||||
const data = payload.data as Record<string, unknown>;
|
||||
expect(data.somethingClientNeverReads).toBeUndefined();
|
||||
});
|
||||
|
||||
it("slims Codex-shaped mcp_tool_call items to rendered fields plus a result summary", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "mcp_tool_call",
|
||||
data: {
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "item-1",
|
||||
tool: "fetch_pr",
|
||||
server: "github",
|
||||
status: "completed",
|
||||
arguments: { pr: 42 },
|
||||
durationMs: 1200,
|
||||
result: {
|
||||
content: [{ type: "text", text: `PR body line one\n${"x".repeat(5000)}` }],
|
||||
structuredContent: { huge: "y".repeat(5000) },
|
||||
},
|
||||
_meta: { internal: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
|
||||
const item = data.item as Record<string, unknown>;
|
||||
expect(item.tool).toBe("fetch_pr");
|
||||
expect(item.server).toBe("github");
|
||||
expect(item.arguments).toEqual({ pr: 42 });
|
||||
expect(item._meta).toBeUndefined();
|
||||
expect(item.result).toEqual({ content: "PR body line one" });
|
||||
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it("slims Claude-shaped mcp_tool_call data (toolName/input/result block)", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "mcp_tool_call",
|
||||
data: {
|
||||
toolName: "mcp__github__fetch_pr",
|
||||
input: { pr: 42 },
|
||||
result: {
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_1",
|
||||
content: [{ type: "text", text: `first line of output\n${"z".repeat(5000)}` }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
|
||||
expect(data.toolName).toBe("mcp__github__fetch_pr");
|
||||
expect(data.input).toEqual({ pr: 42 });
|
||||
expect(data.result).toEqual({ content: "first line of output" });
|
||||
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it("passes task lifecycle payloads (no data field) through untouched", () => {
|
||||
const source = activity({
|
||||
taskId: "task-9",
|
||||
title: "Audit auth",
|
||||
role: "explorer",
|
||||
model: "opus",
|
||||
effort: "high",
|
||||
workflowName: "audit-flow",
|
||||
phases: [{ index: 0, title: "Audit" }],
|
||||
typedUsage: { totalTokens: 1200 },
|
||||
runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },
|
||||
timelineBypass: true,
|
||||
});
|
||||
const projected = projectActivityPayload(source);
|
||||
expect(projected.payload).toEqual(source.payload);
|
||||
});
|
||||
});
|
||||
@@ -123,6 +123,114 @@ function summarizeToolTextOutput(value: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fields of an MCP tool-call item both clients render in the expanded
|
||||
* work-log row. Everything else — notably `result`, which carries the full
|
||||
* tool output and dominates wire size on MCP-heavy threads — is summarized
|
||||
* or dropped. Full payloads remain in persistence.
|
||||
*/
|
||||
const MCP_ITEM_KEPT_FIELDS = [
|
||||
"type",
|
||||
"id",
|
||||
"tool",
|
||||
"server",
|
||||
"status",
|
||||
"arguments",
|
||||
"appContext",
|
||||
"error",
|
||||
"durationMs",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Pulls renderable text out of an MCP tool result: either a Codex-style
|
||||
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
|
||||
* `tool_result` block whose `content` is a string or block array.
|
||||
*/
|
||||
function extractMcpResultText(result: unknown): string | null {
|
||||
const record = asRecord(result);
|
||||
if (!record) {
|
||||
return typeof result === "string" ? result : null;
|
||||
}
|
||||
if (typeof record.content === "string") {
|
||||
return record.content;
|
||||
}
|
||||
if (Array.isArray(record.content)) {
|
||||
const texts: string[] = [];
|
||||
for (const entry of record.content) {
|
||||
const text = asRecord(entry)?.text;
|
||||
if (typeof text === "string" && text.trim().length > 0) {
|
||||
texts.push(text);
|
||||
}
|
||||
}
|
||||
if (texts.length > 0) {
|
||||
return texts.join("\n");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
|
||||
if (result === undefined || result === null) {
|
||||
return undefined;
|
||||
}
|
||||
const text = extractMcpResultText(result);
|
||||
const summary = text ? summarizeToolTextOutput(text) : null;
|
||||
return summary ? { content: summary } : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP tool calls carry full tool results (`data.item.result` on Codex,
|
||||
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
|
||||
* keep the expanded-row UI working. Keep the fields the UI actually renders
|
||||
* and summarize the result like regular tool output.
|
||||
*/
|
||||
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
|
||||
const item = asRecord(data.item);
|
||||
if (item) {
|
||||
const projectedItem: Record<string, unknown> = {};
|
||||
for (const key of MCP_ITEM_KEPT_FIELDS) {
|
||||
if (key in item) {
|
||||
projectedItem[key] = item[key];
|
||||
}
|
||||
}
|
||||
const result = summarizeMcpResult(item.result);
|
||||
if (result) {
|
||||
projectedItem.result = result;
|
||||
}
|
||||
projectedData.item = projectedItem;
|
||||
}
|
||||
|
||||
if ("toolName" in data) {
|
||||
projectedData.toolName = data.toolName;
|
||||
}
|
||||
if ("input" in data) {
|
||||
projectedData.input = data.input;
|
||||
}
|
||||
if (!item) {
|
||||
const result = summarizeMcpResult(data.result);
|
||||
if (result) {
|
||||
projectedData.result = result;
|
||||
}
|
||||
}
|
||||
|
||||
if ("toolCallId" in data) {
|
||||
projectedData.toolCallId = data.toolCallId;
|
||||
}
|
||||
if ("kind" in data) {
|
||||
projectedData.kind = data.kind;
|
||||
}
|
||||
|
||||
const changedFiles: string[] = [];
|
||||
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
|
||||
if (changedFiles.length > 0) {
|
||||
projectedData.files = changedFiles.map((path) => ({ path }));
|
||||
}
|
||||
|
||||
return projectedData;
|
||||
}
|
||||
|
||||
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
|
||||
const rawOutput = asRecord(value);
|
||||
if (!rawOutput) {
|
||||
@@ -160,10 +268,20 @@ export function projectActivityPayload(
|
||||
): OrchestrationThreadActivity {
|
||||
const payload = asRecord(activity.payload);
|
||||
const data = asRecord(payload?.data);
|
||||
if (!payload || !data || payload.itemType === "mcp_tool_call") {
|
||||
if (!payload || !data) {
|
||||
return activity;
|
||||
}
|
||||
|
||||
if (payload.itemType === "mcp_tool_call") {
|
||||
return {
|
||||
...activity,
|
||||
payload: {
|
||||
...payload,
|
||||
data: projectMcpToolCallData(data),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
const item = projectCommandData(data);
|
||||
if (item) {
|
||||
@@ -247,6 +365,107 @@ function dropStaleContextWindowActivities(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity both clients use to fold a tool lifecycle row into the call it
|
||||
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
|
||||
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
|
||||
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
|
||||
* with no identity at all — those never collapse on the client either, so they
|
||||
* must not be dropped here.
|
||||
*/
|
||||
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
|
||||
const payload = asRecord(activity.payload);
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
|
||||
if (toolCallId) {
|
||||
return `id:${toolCallId}`;
|
||||
}
|
||||
|
||||
const itemType = asTrimmedString(payload.itemType) ?? "";
|
||||
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
|
||||
// gain a trailing "complete"/"completed" the in-flight updates lack.
|
||||
const label = (asTrimmedString(payload.title) ?? activity.summary)
|
||||
.replace(/\s+(?:complete|completed)\s*$/iu, "")
|
||||
.trim();
|
||||
const detail = asTrimmedString(payload.detail) ?? "";
|
||||
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return [itemType, label, detail].join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
|
||||
* update is the in-flight snapshot of a call; once the call completes, the
|
||||
* completion carries the final state and the clients fold every matching
|
||||
* update into it, so shipping the updates buys nothing — 47k such rows exist
|
||||
* in one real database, and a single thread carries 2,291 of them totalling
|
||||
* ~1MB post-slimming.
|
||||
*
|
||||
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
|
||||
* retains per turn: a live `thread.reverted` makes the client discard whole
|
||||
* turns, so a completion in a different turn could vanish and leave the
|
||||
* dropped update unrepresented. The completion must also come *after* the
|
||||
* update within the turn — a later update belongs to a subsequent call that
|
||||
* reuses the same identity and is still in flight. Rows without a lifecycle
|
||||
* identity pass through, matching the clients, which never collapse them.
|
||||
* Live `thread.activity-appended` events are untouched: updates still stream
|
||||
* in real time and the completion supersedes them on the client as before.
|
||||
*
|
||||
* Deliberate divergence from client collapse: clients fold only *adjacent*
|
||||
* lifecycle rows, so a superseded update separated from its completion by an
|
||||
* interleaved parallel call renders as its own row today, and this drop
|
||||
* removes it. Measured against a real database, that affects 1.5% of dropped
|
||||
* rows (553 of 36,581), all pure in-flight state whose final result the
|
||||
* retained completion still shows. Dropping them is intentional; matching
|
||||
* adjacency server-side would forfeit most of the win for parallel-heavy
|
||||
* threads, which are exactly the heavy ones. Superseding completions always
|
||||
* carry a payload superset of their updates (verified across all 49,515
|
||||
* update rows: zero dropped rows held a client-merged field — detail, title,
|
||||
* command, item, kind, files — their completion lacked), so no expanded-row
|
||||
* content is lost.
|
||||
*/
|
||||
function dropSupersededToolUpdatedActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
const completionIndicesByKey = new Map<string, number[]>();
|
||||
for (let index = 0; index < activities.length; index += 1) {
|
||||
const activity = activities[index]!;
|
||||
if (activity.kind !== "tool.completed") {
|
||||
continue;
|
||||
}
|
||||
const identity = toolLifecycleIdentity(activity);
|
||||
if (!identity) {
|
||||
continue;
|
||||
}
|
||||
const key = `${activity.turnId ?? ""} | ||||