Skip to content
Closed
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
37 changes: 16 additions & 21 deletions apps/host-daemon/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,9 @@ function createFakeRuntime(): AgentRuntime {
listRunningProviders() {
return [];
},
getSessionPhase() {
return "idle";
},
getActiveTurnId() {
return null;
},
Expand Down Expand Up @@ -697,17 +700,13 @@ describe("createHostDaemonApp", () => {
},
});
expect(resolveRuntimeShellEnv).toHaveBeenCalledTimes(1);
expect(runtimeOptions.current).toEqual(
expect.objectContaining({
env: {
PATH: "/shell/bin:/usr/bin",
},
shellEnv: {
PATH: "/shell/bin:/usr/bin",
BB_SERVER_URL: "http://127.0.0.1:3334",
},
}),
);
expect(runtimeOptions.current?.getProcessEnv?.()).toEqual({
PATH: "/shell/bin:/usr/bin",
});
expect(runtimeOptions.current?.getShellEnv?.()).toEqual({
PATH: "/shell/bin:/usr/bin",
BB_SERVER_URL: "http://127.0.0.1:3334",
});
expect(listModels).toHaveBeenCalledWith({
providerId: "cursor",
cwd: "/tmp/worktree",
Expand Down Expand Up @@ -803,13 +802,9 @@ describe("createHostDaemonApp", () => {
});

expect(resolveRuntimeShellEnv).not.toHaveBeenCalled();
expect(runtimeOptions.current).toEqual(
expect.objectContaining({
env: {
PATH: "/startup/bin:/usr/bin",
},
}),
);
expect(runtimeOptions.current?.getProcessEnv?.()).toEqual({
PATH: "/startup/bin:/usr/bin",
});
} finally {
await app.daemon.shutdown("test", 0);
}
Expand Down Expand Up @@ -982,13 +977,13 @@ describe("createHostDaemonApp", () => {
freshShellEnv.resolve({ PATH: "/fresh/bin:/usr/bin" });
await response;
expect(calls).toEqual([method]);
expect(runtimeOptions.current?.env).toEqual({
expect(runtimeOptions.current?.getProcessEnv?.()).toEqual({
PATH: "/fresh/bin:/usr/bin",
});
} else {
await expect(response).resolves.toMatchObject({ ok: true });
expect(calls).toEqual([method]);
expect(runtimeOptions.current?.env).toEqual({
expect(runtimeOptions.current?.getProcessEnv?.()).toEqual({
PATH: "/last-resolved/bin:/usr/bin",
});
freshShellEnv.resolve({ PATH: "/fresh/bin:/usr/bin" });
Expand Down Expand Up @@ -1029,7 +1024,7 @@ describe("createHostDaemonApp", () => {
freshShellEnv.resolve({ PATH: "/fresh/bin:/usr/bin" });
await expect(response).resolves.toMatchObject({ ok: true });
expect(calls).toEqual(["listCommands"]);
expect(runtimeOptions.current?.env).toEqual({
expect(runtimeOptions.current?.getProcessEnv?.()).toEqual({
PATH: "/fresh/bin:/usr/bin",
});
} finally {
Expand Down
8 changes: 3 additions & 5 deletions apps/host-daemon/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import {
} from "./runtime-shell-env-cache.js";
import type {
AgentRuntime,
AgentRuntimeOptions,
AgentRuntimeShellEnvironment,
RuntimeOpenBackgroundWork,
} from "@bb/agent-runtime";
import { createProtocolSelfUpdater } from "./protocol-self-update.js";
Expand Down Expand Up @@ -157,11 +157,9 @@ interface CreateHostDaemonAppOptions {
releaseLock: () => Promise<void>;
localApiConfig: HostDaemonLocalApiConfig | null;
createRuntime?: RuntimeManagerOptions["createRuntime"];
runtimeShellEnv?: AgentRuntimeOptions["shellEnv"];
runtimeShellEnv?: AgentRuntimeShellEnvironment;
runtimeShellEnvResolvedAtMs?: number;
resolveRuntimeShellEnv?: () => Promise<
NonNullable<AgentRuntimeOptions["shellEnv"]>
>;
resolveRuntimeShellEnv?: () => Promise<AgentRuntimeShellEnvironment>;
nowMs?: () => number;
hostWatcher?: HostWatcher;
fetchFn?: FetchFn;
Expand Down
19 changes: 0 additions & 19 deletions apps/host-daemon/src/command-dispatch-support.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { CompetingTurnError } from "@bb/agent-runtime";
import { COMPETING_TURN_ERROR_CODE } from "@bb/host-daemon-contract";
import { BRIDGE_JSON_RPC_ERRORS } from "@bb/provider-bridge-protocol";
import { JsonRpcResponseError } from "@bb/provider-bridge-protocol/bridge-kit";
import { describe, expect, it } from "vitest";
Expand All @@ -10,23 +8,6 @@ import {
} from "./command-dispatch-support.js";

describe("command dispatch support", () => {
it("reports a runtime competing-turn refusal with the contract error code", () => {
expect(getErrorCode(new CompetingTurnError("thread-1"))).toBe(
COMPETING_TURN_ERROR_CODE,
);
expect(
getErrorCode(
new CommandDispatchError(
COMPETING_TURN_ERROR_CODE,
"Refusing to start a competing turn while thread-1 is still starting",
),
),
).toBe("competing_turn");
expect(getErrorCode(new Error("Refusing to start a competing turn"))).toBe(
"command_failed",
);
});

it("classifies a bridge missing-executable rejection without sniffing its message", () => {
expect(
getErrorCode(
Expand Down
18 changes: 1 addition & 17 deletions apps/host-daemon/src/command-dispatch-support.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import type { DesktopBrowserBroker } from "./desktop-browser-broker.js";
import {
CompetingTurnError,
type AgentRuntimeBridgeLaunch,
} from "@bb/agent-runtime";
import { type AgentRuntimeBridgeLaunch } from "@bb/agent-runtime";
import type { AvailableModel } from "@bb/domain";
import type { EventSink } from "./event-sink.js";
import {
COMPETING_TURN_ERROR_CODE,
type EnvironmentHookProgressMessage,
type HostDaemonCommand,
type HostDaemonContributedEnvEntry,
type ProviderHealthResult,
type ProviderUsageResult,
type HostDaemonBridgeLaunch,
type HostDaemonInjectedSkillSource,
type HostDaemonOnlineRpcCommand,
type HostDaemonConnectTunnelIdentity,
type WorkspaceContext,
Expand Down Expand Up @@ -200,9 +195,6 @@ export function getErrorCode(error: unknown): string {
if (error instanceof CommandDispatchError) {
return error.code;
}
if (error instanceof CompetingTurnError) {
return COMPETING_TURN_ERROR_CODE;
}
if (isBridgeMissingExecutableError(error)) {
return "missing_executable";
}
Expand Down Expand Up @@ -258,8 +250,6 @@ function isMessageOnlySpawnMissingExecutableError(error: unknown): boolean {
export async function requireWorkspaceEnvironment(
args: {
environmentId: string;
injectedSkillSources?: readonly HostDaemonInjectedSkillSource[];
targetThreadId?: string;
workspaceContext: WorkspaceContext;
},
runtimeManager: RuntimeManager,
Expand All @@ -277,12 +267,6 @@ export async function requireWorkspaceEnvironment(

return runtimeManager.ensureEnvironment({
environmentId: args.environmentId,
...(args.injectedSkillSources !== undefined
? { injectedSkillSources: args.injectedSkillSources }
: {}),
...(args.targetThreadId !== undefined
? { targetThreadId: args.targetThreadId }
: {}),
workspacePath: args.workspaceContext.workspacePath,
});
}
85 changes: 71 additions & 14 deletions apps/host-daemon/src/command-dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ interface BusySkillCatalogFixture {
createRuntimeSpy: Mock<() => AgentRuntime>;
dataDir: string;
manager: RuntimeManager;
originalCatalogHash: string | null;
runtime: FakeDispatchRuntime;
source: HostDaemonInjectedSkillSource;
}
Expand Down Expand Up @@ -85,9 +84,14 @@ async function setupBusySkillCatalogEnvironment(args: {
createRuntime: createRuntimeSpy,
provisionWorkspace: async () => createWorkspace(),
});
const entry = await manager.ensureEnvironment({
await manager.ensureEnvironment({
environmentId: "env-1",
workspacePath: WORKSPACE_PATH,
});
await manager.stageThreadSkillRoots({
environmentId: "env-1",
injectedSkillSources: [source],
threadId: args.activeThreadId,
workspacePath: WORKSPACE_PATH,
});
runtime.setActiveTurn(args.activeThreadId, "turn-busy-1");
Expand All @@ -96,7 +100,6 @@ async function setupBusySkillCatalogEnvironment(args: {
createRuntimeSpy,
dataDir,
manager,
originalCatalogHash: entry.skillCatalogHash,
runtime,
source,
};
Expand Down Expand Up @@ -171,6 +174,8 @@ function createRuntime(): FakeDispatchRuntime {
listRunningProviders: vi.fn(() => ["fake"]),
getActiveTurnId: (threadId) => activeTurnsByThreadId.get(threadId) ?? null,
getActiveTurnRequestIds: () => [],
getSessionPhase: (threadId) =>
activeTurnsByThreadId.has(threadId) ? "turnRunning" : "idle",
waitForActiveTurn: vi.fn(
async (threadId: string) => activeTurnsByThreadId.get(threadId) ?? null,
),
Expand Down Expand Up @@ -476,6 +481,7 @@ describe("dispatchCommand", () => {
throw new Error("Unexpected project attachment fetch");
},
...unexpectedProviderMaintenance,
fetchPluginHostArtifact: fetchDispatchTestArtifact,
runtimeManager: manager,
threadStorageRootPath: "/tmp/bb-thread-storage",
},
Expand All @@ -490,6 +496,8 @@ describe("dispatchCommand", () => {
clientRequestId: "creq_turn_submit",
expectedTurnId: "turn-starting",
threadId: "thread-1",
contributedEnv: [],
instructions: "Be concise.",
}),
);
expect(runtime.runTurn).not.toHaveBeenCalled();
Expand Down Expand Up @@ -520,6 +528,7 @@ describe("dispatchCommand", () => {
throw new Error("Unexpected project attachment fetch");
},
...unexpectedProviderMaintenance,
fetchPluginHostArtifact: fetchDispatchTestArtifact,
runtimeManager: manager,
threadStorageRootPath: "/tmp/bb-thread-storage",
},
Expand Down Expand Up @@ -554,6 +563,7 @@ describe("dispatchCommand", () => {
throw new Error("Unexpected project attachment fetch");
},
...unexpectedProviderMaintenance,
fetchPluginHostArtifact: fetchDispatchTestArtifact,
runtimeManager: manager,
threadStorageRootPath: "/tmp/bb-thread-storage",
},
Expand Down Expand Up @@ -589,17 +599,71 @@ describe("dispatchCommand", () => {
throw new Error("Unexpected project attachment fetch");
},
...unexpectedProviderMaintenance,
fetchPluginHostArtifact: fetchDispatchTestArtifact,
runtimeManager: manager,
threadStorageRootPath: "/tmp/bb-thread-storage",
},
),
).rejects.toThrow(
"Refusing to start a competing turn while thread-1 is still starting",
);
).rejects.toMatchObject({
code: "thread_busy",
message: "Thread thread-1 is still starting a turn",
});
expect(runtime.runTurn).not.toHaveBeenCalled();
expect(runtime.steerTurn).not.toHaveBeenCalled();
});

it.each([
["start", "busy", "thread_busy"],
["start", "rejected", "turn_rejected"],
["steer", "busy", "thread_busy"],
["steer", "rejected", "turn_rejected"],
] as const)(
"reports a runtime %s refusal of status %s with the %s error code",
async (path, status, code) => {
const runtime = createRuntime();
const manager = new RuntimeManager({
createRuntime: () => runtime,
provisionWorkspace: async () => createWorkspace(),
});
await manager.ensureEnvironment({
environmentId: "env-1",
workspacePath: WORKSPACE_PATH,
});
const refusal = { status, message: `The agent refused (${status}).` };
if (path === "start") {
runtime.setIdle("thread-1");
vi.mocked(runtime.runTurn).mockResolvedValueOnce(refusal);
} else {
runtime.setActiveTurn("thread-1", "turn-1");
vi.mocked(runtime.steerTurn).mockResolvedValueOnce(refusal);
}

await expect(
dispatchCommand(
createTurnSubmitCommand({
mode: "auto",
expectedTurnId: path === "start" ? null : "turn-1",
}),
{
dataDir: "/tmp/bb-data",
logger: silentLogger,
eventSink: { emit: vi.fn(), flush: vi.fn(async () => undefined) },
fetchProjectAttachment: async () => {
throw new Error("Unexpected project attachment fetch");
},
...unexpectedProviderMaintenance,
fetchPluginHostArtifact: fetchDispatchTestArtifact,
runtimeManager: manager,
threadStorageRootPath: "/tmp/bb-thread-storage",
},
),
).rejects.toMatchObject({ code, message: refusal.message });
expect(
path === "start" ? runtime.runTurn : runtime.steerTurn,
).toHaveBeenCalledOnce();
},
);

it("flushes buffered events before reporting thread.stop success", async () => {
const runtime = createRuntime();
const manager = new RuntimeManager({
Expand Down Expand Up @@ -1755,7 +1819,7 @@ describe("dispatchCommand", () => {
const createdRuntimeShellPaths: (string | undefined)[] = [];
const manager = new RuntimeManager({
createRuntime: (runtimeOptions) => {
createdRuntimeShellPaths.push(runtimeOptions.shellEnv?.PATH);
createdRuntimeShellPaths.push(runtimeOptions.getShellEnv?.().PATH);
return runtime;
},
provisionWorkspace: async () => createWorkspace(),
Expand Down Expand Up @@ -2346,7 +2410,6 @@ describe("dispatchCommand", () => {
dataDir: fixture.dataDir,
injectedSkillSources: [fixture.source],
});
expect(currentCatalog.catalogHash).not.toBe(fixture.originalCatalogHash);
await expect(
fs.readFile(
path.join(
Expand All @@ -2362,9 +2425,6 @@ describe("dispatchCommand", () => {
);
expect(fixture.createRuntimeSpy).toHaveBeenCalledTimes(1);
expect(fixture.runtime.shutdown).not.toHaveBeenCalled();
expect(fixture.manager.get("env-1")?.skillCatalogHash).toBe(
fixture.originalCatalogHash,
);
});

it("reuses a busy runtime when turn.submit carries a changed skill catalog", async () => {
Expand Down Expand Up @@ -2427,9 +2487,6 @@ describe("dispatchCommand", () => {
expect(fixture.runtime.resumeThread).not.toHaveBeenCalled();
expect(fixture.createRuntimeSpy).toHaveBeenCalledTimes(1);
expect(fixture.runtime.shutdown).not.toHaveBeenCalled();
expect(fixture.manager.get("env-1")?.skillCatalogHash).toBe(
fixture.originalCatalogHash,
);
});

it("routes provider health and usage to the targeted bridge runtime", async () => {
Expand Down
6 changes: 3 additions & 3 deletions apps/host-daemon/src/command-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,8 +449,8 @@ const commandHandlers: CommandHandlerMap = {
),
"turn.submit": (command, options) =>
withRetainedThreadEnvironment(command, options, async () => {
const entry = await ensureThreadRuntime(command, options);
return submitTurn(command, entry, options);
const target = await ensureThreadRuntime(command, options);
return submitTurn(command, target, options);
}),
"thread.stop": stopThreadRuntime,
"thread.storage.delete": async (command, options) => {
Expand All @@ -459,7 +459,7 @@ const commandHandlers: CommandHandlerMap = {
return result;
},
"thread.goal.clear": async (command, options) => {
const entry = await ensureThreadRuntime(command, options);
const { entry } = await ensureThreadRuntime(command, options);
const result = await entry.runtime.clearThreadGoal({
threadId: command.threadId,
});
Expand Down
Loading