Files

784 lines
25 KiB
TypeScript

// An in-process environment for app render scenarios: a fetch stub for its HTTP API and a
// session that answers the shell, thread and config subscriptions from fixtures. Other RPCs
// stay pending so nothing retries on timers. Everything above the wire is the app's own.
import {
type AssetCreateUrlResult,
AuthStandardClientScopes,
EnvironmentId,
EventId,
ExecutionEnvironmentDescriptor,
MessageId,
NodeId,
OrchestrationV2DispatchCommandError,
ORCHESTRATION_PROTOCOL_VERSION,
ORCHESTRATION_V2_WS_METHODS,
ProjectId,
ProviderInstanceId,
RunId,
RuntimeRequestId,
ServerConfig,
ThreadId,
TurnItemId,
WS_METHODS,
WsRpcGroup,
type VcsStatusStreamEvent,
type ModelSelection,
type OrchestrationProjectShell,
type OrchestrationV2Command,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
type OrchestrationV2ShellStreamItem,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadShell,
type OrchestrationV2ThreadStreamItem,
type OrchestrationV2TurnItem,
type TerminalMetadataStreamEvent,
type ResolvedKeybindingsConfig,
} from "@hanzodev/contracts";
import type {
ConnectionAttemptError,
ConnectionCatalogEntry,
EnvironmentConnectionLease,
RouteCheck,
} from "@hanzodev/client-runtime/connection";
import type { WsRpcProtocolClient } from "@hanzodev/client-runtime/rpc";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@hanzodev/shared/keybindings";
import { APP_VERSION } from "~/branding";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import type * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { RpcSchema } from "effect/rpc";
export const ENVIRONMENT_ID = EnvironmentId.make("environment-render");
export const PROJECT_ID = ProjectId.make("project-render");
const CODEX = ProviderInstanceId.make("codex");
const MODEL = { instanceId: CODEX, model: "gpt-5.4" };
const AT = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z");
const descriptor = {
environmentId: ENVIRONMENT_ID,
label: "Render scenarios",
platform: { os: "linux", arch: "x64" },
// A matching version, since a mismatch adds an update banner a typical user never sees.
serverVersion: APP_VERSION,
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
capabilities: { repositoryIdentity: true, sideChats: true },
};
const auth = {
policy: "loopback-browser",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie"],
sessionCookieName: "hanzo_session",
};
const readyProvider = (
instanceId: string,
driver: string,
models: ReadonlyArray<{ readonly slug: string; readonly name: string }>,
) => ({
instanceId,
driver,
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-03-17T19:12:28.000Z",
models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })),
});
export const CODEX_PROVIDER = readyProvider(CODEX, "codex", [
{ slug: "gpt-5.4", name: "GPT-5.4" },
{ slug: "gpt-5.5", name: "GPT-5.5" },
]);
export const CLAUDE_PROVIDER = {
...readyProvider("claudeAgent", "claudeAgent", [
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
]),
slashCommands: [{ name: "compact" }],
};
const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig);
const makeServerConfig = (
providers: ReadonlyArray<unknown>,
supportsIssues = false,
): ServerConfig => ({
...decodeServerConfig({
environment: {
...descriptor,
capabilities: { ...descriptor.capabilities, issues: supportsIssues },
},
auth,
cwd: "/workspace/render",
keybindingsConfigPath: "/workspace/.hanzo-dev/keybindings.json",
keybindings: [],
issues: [],
providers,
availableEditors: [],
observability: {
logsDirectoryPath: "/workspace/.hanzo-dev/logs",
localTracingEnabled: false,
otlpTracesEnabled: false,
otlpMetricsEnabled: false,
},
settings: {},
threadSnapshotPagination: true,
threadResumeCompletionMarker: true,
shellResumeCompletionMarker: true,
}),
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
});
let baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
// A server only leaves threads out of the shell when it serves their families.
const serverConfig = (): ServerConfig =>
threads.some((thread) => thread.olderSettled)
? { ...baseServerConfig, shellThreadFamilies: true }
: baseServerConfig;
const project: OrchestrationProjectShell = {
id: PROJECT_ID,
title: "render",
workspaceRoot: "/workspace/render",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-03-17T19:12:28.000Z",
updatedAt: "2026-03-17T19:12:28.000Z",
};
const base = (threadId: ThreadId, runId: RunId, id: string, ordinal: number) => ({
id: TurnItemId.make(id),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal,
status: "completed" as const,
title: null,
startedAt: AT,
completedAt: AT,
updatedAt: AT,
});
function userItem(threadId: ThreadId, runId: RunId, id: string, ordinal: number, text: string) {
return {
...base(threadId, runId, id, ordinal),
type: "user_message",
messageId: MessageId.make(id),
text,
attachments: [],
inputIntent: "turn_start",
createdBy: "user",
creationSource: "web",
} satisfies OrchestrationV2TurnItem;
}
export function assistantItem(
threadId: ThreadId,
runId: RunId,
id: string,
ordinal: number,
text: string,
streaming = false,
) {
return {
...base(threadId, runId, id, ordinal),
type: "assistant_message",
messageId: MessageId.make(id),
text,
streaming,
...(streaming ? { status: "running" as const, completedAt: null } : {}),
} satisfies OrchestrationV2TurnItem;
}
function run(
threadId: ThreadId,
id: RunId,
ordinal: number,
userMessageId: string,
modelSelection: ModelSelection = MODEL,
) {
return {
id,
threadId,
ordinal,
providerInstanceId: modelSelection.instanceId,
modelSelection,
providerThreadId: null,
userMessageId: MessageId.make(userMessageId),
rootNodeId: null,
activeAttemptId: null,
status: "completed",
requestedAt: AT,
startedAt: AT,
completedAt: AT,
checkpointId: null,
contextHandoffId: null,
} satisfies OrchestrationV2Run;
}
export interface FakeThread {
/** Makes this a side chat of that thread. */
readonly sideChatOf?: ThreadId;
/** Makes this an older settled thread the shell leaves out; only its family read returns it. */
readonly olderSettled?: true;
readonly id: ThreadId;
readonly title: string;
/** Defaults to GPT-5.4 on Codex. */
readonly modelSelection?: ModelSelection;
/** The first is the thread's active provider thread. */
readonly providerThreads?: ReadonlyArray<OrchestrationV2ProviderThread>;
readonly issues?: OrchestrationV2ThreadShell["issues"];
readonly runs: ReadonlyArray<OrchestrationV2Run>;
readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
readonly runtimeRequests?: OrchestrationV2ThreadProjection["runtimeRequests"];
}
/** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */
export function threadWithHistory(
name: string,
turns: number,
modelSelection: ModelSelection = MODEL,
): FakeThread {
const id = ThreadId.make(name);
const runs: OrchestrationV2Run[] = [];
const items: OrchestrationV2TurnItem[] = [];
for (let turn = 0; turn < turns; turn++) {
const runId = RunId.make(`${name}-run-${turn}`);
runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`, modelSelection));
items.push(
userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`),
assistantItem(
id,
runId,
`${name}-assistant-${turn}`,
turn * 2 + 1,
`Answer ${turn} for ${name}.\n\n- checked \`Sidebar.tsx\`\n- ran the tests\n\n` +
"The width is now `clamp(next, MIN_WIDTH, MAX_WIDTH)`, so the layout no longer jumps.",
),
);
}
return { id, title: `Thread ${name}`, modelSelection, runs, items };
}
/** A one-turn thread whose agent waits on an answer to one question. */
export function threadWithQuestion(name: string, question: string): FakeThread {
const thread = threadWithHistory(name, 1);
const requestId = RuntimeRequestId.make(`${name}-request`);
return {
...thread,
items: [
...thread.items,
{
...base(thread.id, RunId.make(`${name}-run-0`), `${name}-question`, 2),
type: "user_input_request",
requestId,
responseMode: "message",
questions: [
{
id: "choice",
header: "Choice",
question,
required: true,
allowCustomAnswer: false,
options: [{ label: "Continue", value: "continue", description: "Resume work" }],
},
],
},
],
runtimeRequests: [
{
id: requestId,
nodeId: NodeId.make(`${name}-node`),
providerTurnId: null,
nativeRequestRef: null,
kind: "user_input",
status: "pending",
responseCapability: { type: "message" },
createdAt: AT,
resolvedAt: null,
},
],
};
}
function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {
const latest = thread.runs.at(-1);
const modelSelection = thread.modelSelection ?? MODEL;
return {
id: thread.id,
projectId: PROJECT_ID,
title: thread.title,
providerInstanceId: modelSelection.instanceId,
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null,
...(thread.issues === undefined ? {} : { issues: thread.issues }),
lineage: {
rootThreadId: thread.sideChatOf ?? thread.id,
parentThreadId: thread.sideChatOf ?? null,
relationshipToParent: null,
...(thread.sideChatOf ? { sideChat: true } : {}),
},
forkedFrom: null,
createdBy: "user",
creationSource: "web",
latestRunId: latest?.id ?? null,
activeRunId: null,
// Idle reads as waiting on the user, which shows a per-second duration in the sidebar.
status: latest ? "completed" : "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: AT,
hasActionableProposedPlan: false,
itemCount: thread.items.length,
visibleItemCount: thread.items.length,
createdAt: AT,
updatedAt: AT,
archivedAt: null,
settledOverride: thread.olderSettled ? "settled" : null,
settledAt: thread.olderSettled ? AT : null,
lastVisitedAt: AT,
deletedAt: null,
};
}
function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection {
const shell = shellOf(thread);
const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = thread.items.map(
(item, position) => ({
position,
visibility: "local",
sourceThreadId: thread.id,
sourceItemId: item.id,
item,
}),
);
return {
thread: {
id: shell.id,
projectId: shell.projectId,
title: shell.title,
providerInstanceId: shell.providerInstanceId,
modelSelection: shell.modelSelection,
runtimeMode: shell.runtimeMode,
interactionMode: shell.interactionMode,
branch: shell.branch,
worktreePath: shell.worktreePath,
activeProviderThreadId: shell.activeProviderThreadId,
lineage: shell.lineage,
forkedFrom: null,
createdBy: "user",
creationSource: "web",
createdAt: AT,
updatedAt: AT,
archivedAt: null,
settledOverride: shell.settledOverride,
settledAt: shell.settledAt,
lastVisitedAt: AT,
deletedAt: null,
},
runs: [...thread.runs],
attempts: [],
nodes: [],
subagents: [],
providerSessions: [],
providerThreads: [...(thread.providerThreads ?? [])],
providerTurns: [],
runtimeRequests: [...(thread.runtimeRequests ?? [])],
messages: [],
plans: [],
turnItems: [...thread.items],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
contextTransfers: [],
visibleTurnItems,
updatedAt: AT,
};
}
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
// Keyed by thread id: a live thread subscription's queue, for pushing events to it.
const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStreamItem>>();
let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;
let shellSubscriber: Queue.Queue<OrchestrationV2ShellStreamItem> | null = null;
let threads: ReadonlyArray<FakeThread> = [];
let dispatched: OrchestrationV2Command[] = [];
let acceptCommands = false;
let projects: ReadonlyArray<OrchestrationProjectShell> = [project];
let holdCommand: (command: OrchestrationV2Command) => boolean = () => false;
let pendingDispatches: Array<{
readonly command: OrchestrationV2Command;
readonly reply: Deferred.Deferred<never, OrchestrationV2DispatchCommandError>;
}> = [];
let pendingAssetUrls: Array<Deferred.Deferred<AssetCreateUrlResult>> = [];
let sequence = 1;
type ServerConfigStreamSnapshot = {
readonly version: 1;
readonly type: "snapshot";
readonly config: ServerConfig;
};
let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
let serverConfigSubscriber: Queue.Queue<ServerConfigStreamSnapshot> | null = null;
const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) =>
Stream.unwrap(
Effect.gen(function* () {
const queue = yield* Queue.unbounded<A>();
yield* Queue.offerAll(queue, first);
if (register) {
const unregister = register(queue);
yield* Effect.addFinalizer(() => Effect.sync(unregister));
}
return Stream.fromQueue(queue);
}),
);
const handlers: Record<string, (input: never) => unknown> = {
// Recorded, and accepted only when the scenario asks, since a pending command holds every
// later command on its thread. Accepted commands' events never arrive.
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
Effect.suspend(() => {
dispatched.push(command);
if (acceptCommands && !holdCommand(command)) {
if (command.type !== "thread.fork" || !command.sideChat || shellSubscriber === null)
return Effect.succeed({ sequence: sequence + 1 });
const fork: FakeThread = {
id: command.targetThreadId,
title: command.title ?? "Side chat",
sideChatOf: command.sourceThreadId,
runs: [],
items: [],
};
threads = [...threads, fork];
sequence += 1;
return Queue.offer(shellSubscriber, {
kind: "thread.updated",
sequence,
location: "active",
thread: shellOf(fork),
}).pipe(Effect.as({ sequence }));
}
const reply = Deferred.makeUnsafe<never, OrchestrationV2DispatchCommandError>();
pendingDispatches.push({ command, reply });
return Deferred.await(reply);
}),
// Held like any other unanswered call, until `answerAssetUrls`.
[WS_METHODS.assetsCreateUrl]: () =>
Effect.suspend(() => {
const reply = Deferred.makeUnsafe<AssetCreateUrlResult>();
pendingAssetUrls.push(reply);
return Deferred.await(reply);
}),
[WS_METHODS.subscribeTerminalMetadata]: () =>
subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
terminalMetadataSubscriber = queue;
return () => {
if (terminalMetadataSubscriber === queue) terminalMetadataSubscriber = null;
};
}),
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
subscribe<OrchestrationV2ShellStreamItem>(
[
{
kind: "snapshot",
snapshot: {
schemaVersion: 1,
snapshotSequence: sequence,
projects,
threads: threads.filter((thread) => !thread.olderSettled).map(shellOf),
archivedThreads: [],
},
},
{ kind: "synchronized" },
],
(queue) => {
shellSubscriber = queue;
return () => {
if (shellSubscriber === queue) shellSubscriber = null;
};
},
),
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: (input: { readonly threadId: ThreadId }) => {
const thread = threads.find((candidate) => candidate.id === input.threadId);
if (!thread) return Stream.never;
return subscribe<OrchestrationV2ThreadStreamItem>(
[
{ kind: "snapshot", snapshotSequence: sequence, projection: projectionOf(thread) },
{ kind: "synchronized" },
],
(queue) => {
threadSubscribers.set(thread.id, queue);
// A replaced subscription closes after its successor registers.
return () => {
if (threadSubscribers.get(thread.id) === queue) threadSubscribers.delete(thread.id);
};
},
);
},
[ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input: { readonly threadId: ThreadId }) => {
const rootOf = (thread: FakeThread) => thread.sideChatOf ?? thread.id;
const requested = threads.find((candidate) => candidate.id === input.threadId);
return Effect.succeed({
snapshotSequence: sequence,
threads: requested
? threads.filter((thread) => rootOf(thread) === rootOf(requested)).map(shellOf)
: [],
});
},
[WS_METHODS.subscribeVcsStatus]: () =>
subscribe<VcsStatusStreamEvent>([], (queue) => {
vcsStatusSubscriber = queue;
return () => {
if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null;
};
}),
};
const subscribeServerConfigStream = () =>
subscribe<ServerConfigStreamSnapshot>(
[{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }],
(queue) => {
serverConfigSubscriber = queue;
return () => {
if (serverConfigSubscriber === queue) serverConfigSubscriber = null;
};
},
);
handlers[WS_METHODS.subscribeServerConfig] = subscribeServerConfigStream;
// Unanswered calls stay pending, like a server that has not replied yet.
const client = new Proxy(handlers, {
get: (target, method: string) =>
target[method] ??
(() => {
const rpc = WsRpcGroup.requests.get(method);
return rpc && RpcSchema.isStreamSchema(rpc.successSchema) ? Stream.never : Effect.never;
}),
});
const session: EnvironmentConnectionLease["session"] = {
client: client as unknown as WsRpcProtocolClient,
initialConfig: Effect.sync(serverConfig),
subscribeServerConfig: subscribeServerConfigStream,
ready: Effect.void,
probe: Effect.void,
inboundFrames: Effect.succeed(0),
closed: Effect.never,
};
/** Stands in for client-runtime's ConnectionDriver: every connection opens the session above. */
export const fakeDriver = {
connect: (
entry: ConnectionCatalogEntry,
): Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope> =>
Effect.succeed({
prepared: {
environmentId: ENVIRONMENT_ID,
label: descriptor.label,
httpBaseUrl: window.location.origin,
socketUrl: window.location.origin.replace(/^http/, "ws"),
httpAuthorization: null,
target: entry.target,
},
session,
refusedRouteIds: [],
}),
preflight: () => Effect.succeed(true),
checkHost: () => Effect.succeed<RouteCheck>("unchecked"),
};
export type FakeDriver = typeof fakeDriver;
const realFetch = globalThis.fetch;
const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
Schema.decodeUnknownSync(ExecutionEnvironmentDescriptor)(descriptor),
);
/** Serves the environment's HTTP API and these threads until disposed. */
export function installFakeEnvironment(
fixtures: ReadonlyArray<FakeThread>,
options?: {
readonly acceptCommands?: boolean;
readonly keybindings?: ResolvedKeybindingsConfig;
readonly extraProjects?: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;
/** Commands left unanswered even when accepting, until `rejectPendingCommand`. */
readonly holdCommand?: (command: OrchestrationV2Command) => boolean;
readonly providers?: ReadonlyArray<unknown>;
},
): Disposable {
threads = fixtures;
baseServerConfig = {
...makeServerConfig(
options?.providers ?? [CODEX_PROVIDER],
fixtures.some((thread) => (thread.issues?.length ?? 0) > 0),
),
keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS,
};
if (serverConfigSubscriber !== null) {
Effect.runSync(
Queue.offer(serverConfigSubscriber, {
version: 1,
type: "snapshot",
config: serverConfig(),
}),
);
}
dispatched = [];
acceptCommands = options?.acceptCommands === true;
projects = [
project,
...(options?.extraProjects ?? []).map((extra) => ({
...project,
...extra,
workspaceRoot: `/workspace/${extra.title}`,
})),
];
holdCommand = options?.holdCommand ?? (() => false);
globalThis.fetch = async (input, init) => {
const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);
if (url.origin !== window.location.origin) return realFetch(input, init);
if (url.pathname === "/.well-known/hanzo/environment") return json(encodedDescriptor);
if (url.pathname === "/v1/auth/session") {
return json({
authenticated: true,
auth,
scopes: AuthStandardClientScopes,
sessionMethod: "browser-session-cookie",
expiresAt: "2099-01-01T00:00:00.000Z",
});
}
// Snapshot endpoints fall back to the socket, which serves the same fixtures.
if (/^\/(v1|api|oauth|\.well-known)\//.test(url.pathname)) return json({}, 404);
return realFetch(input, init);
};
return {
[Symbol.dispose]: () => {
globalThis.fetch = realFetch;
threads = [];
baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
if (serverConfigSubscriber !== null) {
Effect.runSync(
Queue.offer(serverConfigSubscriber, {
version: 1,
type: "snapshot",
config: serverConfig(),
}),
);
}
dispatched = [];
acceptCommands = false;
projects = [project];
holdCommand = () => false;
pendingDispatches = [];
pendingAssetUrls = [];
},
};
}
/** Answers the oldest unanswered command with the server's rejection. */
export async function rejectPendingCommand(message: string): Promise<void> {
const pending = pendingDispatches.shift();
if (!pending) throw new Error("No pending command");
await Effect.runPromise(
Deferred.fail(
pending.reply,
new OrchestrationV2DispatchCommandError({
commandId: pending.command.commandId,
commandType: pending.command.type,
message,
}),
),
);
}
export function hasPendingAssetUrl(): boolean {
return pendingAssetUrls.length > 0;
}
/** Answers every held asset URL request, as a server that still has the file. */
export async function answerAssetUrls(): Promise<void> {
const replies = pendingAssetUrls;
pendingAssetUrls = [];
for (const reply of replies) {
await Effect.runPromise(
Deferred.succeed(reply, { relativeUrl: "/v1/assets/fake", expiresAt: 4_102_444_800_000 }),
);
}
}
/** Commands the app dispatched to the environment, oldest first. */
export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
return dispatched;
}
type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>["event"];
/** Answers one RPC method with `handler` until disposed. */
export function answerRpc(method: string, handler: (input: never) => unknown): Disposable {
const previous = handlers[method];
handlers[method] = handler;
return {
[Symbol.dispose]: () => {
if (previous) handlers[method] = previous;
else delete handlers[method];
},
};
}
export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise<void> {
if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription");
await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event));
}
/** Whether the app holds a live subscription to the thread, so events reach it. */
export function isThreadSubscribed(threadId: ThreadId): boolean {
return threadSubscribers.has(threadId);
}
/** Delivers one domain event, such as a run or turn-item update, to the thread's subscription. */
export async function emitThreadEvent(
threadId: ThreadId,
event: Pick<ThreadEvent, "type" | "payload">,
): Promise<void> {
const queue = threadSubscribers.get(threadId);
if (!queue) throw new Error(`No live subscription for ${threadId}`);
sequence += 1;
await Effect.runPromise(
Queue.offer(queue, {
kind: "event",
sequence,
event: { ...event, id: EventId.make(`event-${sequence}`), threadId, occurredAt: AT },
} as OrchestrationV2ThreadStreamItem),
);
}
export function runningRun(threadId: ThreadId, id: string, ordinal: number, userMessageId: string) {
return {
...run(threadId, RunId.make(id), ordinal, userMessageId),
status: "running" as const,
completedAt: null,
};
}
export { userItem };
export async function emitVcsStatus(event: VcsStatusStreamEvent): Promise<void> {
if (vcsStatusSubscriber === null) throw new Error("No VCS status subscription");
await Effect.runPromise(Queue.offer(vcsStatusSubscriber, event));
}