Files
t3code/packages/client-runtime/src/state/threadSnapshotHttp.ts
T
Julius MarmingeandClaude Fable 5 807072b7c1 fix: port main fixes stranded by the v2 rewrite (round 2)
Native subagent observability (#5219), wired per its spec's v2 merge plan:
- getWorkflowScript RPC re-homed onto the v2 WS surface (contracts, rpc
  group, ws handler, auth scope, client atom).
- AgentsPanel fed by the spec's mapper swap: projectedSubagentsToRuntime
  maps orchestration-v2 subagent entities into the panel model;
  deriveAgentPanelModel's v2Projection leg is now live and the v1 fold
  never runs. Agents surface wired into ChatView + RightPanelTabs.
Other ports and reconciliations:
- Shell reconnect-loop fix (#5561) ported into the v2 shell sync
  (same-session resubscribes resume from the in-memory cursor), with the
  cursor-resume regression test adapted to v2 fixtures.
- Mobile end-follow latch (#5566) ported onto the v2 ThreadFeed.
- Claude ede_diagnostic interrupt classification (#5557) ported into
  ClaudeAdapterV2 (aborted_tools/aborted_streaming => interrupted; CLI
  telemetry never becomes the failure banner). #5559 needs no v2 port
  (unknown system subtypes are already ignored).
- Plan sidebar removed from the v2 ChatView/ChatComposer per main's
  plans-fold-into-chat rework (#5558); rightPanelStore stays at main's
  surface set.
- SettingsPanels rebuilt as main's refactored version plus the branch's
  composer-context setting; sidebar snooze respects the time format
  (#4438 follow-through).
- v1-only leftovers deleted: zombie v1 adapters/ingestion/tests the v2
  rewrite removes, the v1-bound transfer-budget CI harness (#5350, needs
  a v2 rebuild), and main's v1 client pagination machinery (#5493 client
  side; the 037 keyset migration is kept — server-side v2 windowing is a
  follow-up).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:27 +02:00

121 lines
4.8 KiB
TypeScript

import type { OrchestrationV2ThreadDetailSnapshot, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { HttpClient } from "effect/unstable/http";
import type { PreparedConnection } from "../connection/model.ts";
import { environmentEndpointUrl } from "../environment/endpoint.ts";
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
import {
executeEnvironmentHttpRequest,
makeEnvironmentHttpApiClient,
type RemoteEnvironmentRequestError,
} from "../rpc/http.ts";
import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
// Bounded so a pathologically slow endpoint cannot block the (cheaper) socket
// fallback for long. The cached thread renders while this runs, so the wait only
// delays the transition to live data on the first open, not the initial paint.
const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000;
/**
* Load a thread's detail snapshot over HTTP instead of embedding it in the
* WebSocket subscription's first frame. The response is gzip-compressible by
* the transport and keeps the (potentially multi-KB) snapshot off the socket.
*/
export const fetchEnvironmentThreadSnapshot = Effect.fn(
"clientRuntime.state.fetchEnvironmentThreadSnapshot",
)(function* (input: {
readonly prepared: PreparedConnection;
readonly threadId: ThreadId;
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
readonly timeoutMs?: number;
}) {
const requestUrl = environmentEndpointUrl(
input.prepared.httpBaseUrl,
`/api/orchestration/threads/${input.threadId}`,
);
const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
const headers = yield* buildEnvironmentAuthHeaders(
input.prepared.httpAuthorization,
"GET",
requestUrl,
input.signer,
);
return yield* executeEnvironmentHttpRequest(
requestUrl,
input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,
withEnvironmentCredentials(
input.prepared.httpAuthorization,
client.orchestration.threadSnapshot({
params: { threadId: input.threadId },
headers,
}),
),
);
});
export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;
/**
* Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it
* cannot be loaded (so the caller falls back to the socket-embedded snapshot).
* Decouples the thread state machine from the underlying HTTP + DPoP details and
* keeps them out of test contexts.
*/
export class ThreadSnapshotLoader extends Context.Service<
ThreadSnapshotLoader,
{
readonly load: (
prepared: PreparedConnection,
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationV2ThreadDetailSnapshot>>;
}
>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
export const threadSnapshotLoaderLayer: Layer.Layer<
ThreadSnapshotLoader,
never,
HttpClient.HttpClient
> = Layer.effect(
ThreadSnapshotLoader,
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
// Resolve the DPoP signer optionally: it is only needed for relay/DPoP
// connections, so the loader must not hard-require it (bearer/primary
// connections work without one).
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
return ThreadSnapshotLoader.of({
load: (prepared: PreparedConnection, threadId: ThreadId) =>
fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe(
Effect.map(Option.some<OrchestrationV2ThreadDetailSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
// A genuinely missing thread (404) is expected — the socket
// subscription is the source of truth for thread existence and will
// surface the deletion — so don't treat it as an error worth warning
// about; just defer to the socket path.
Effect.catchTags({
EnvironmentResourceNotFoundError: () =>
Effect.logDebug(
"Thread snapshot not found over HTTP; deferring to the socket subscription.",
).pipe(
Effect.annotateLogs({ threadId }),
Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
),
}),
Effect.catchCause((cause) =>
Effect.logWarning(
"Could not load the thread snapshot over HTTP; using the socket snapshot instead.",
).pipe(
Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }),
Effect.as(Option.none<OrchestrationV2ThreadDetailSnapshot>()),
),
),
),
});
}),
);