feat(factory): finish workbench milestone pass

This commit is contained in:
Nathan Flurry 2026-03-09 16:34:27 -07:00
parent bf282199b5
commit 49cba9e6c2
137 changed files with 819 additions and 338 deletions

View file

@ -1,5 +1,5 @@
{
"name": "@openhandoff/backend",
"name": "@sandbox-agent/factory-backend",
"version": "0.1.0",
"private": true,
"type": "module",
@ -17,7 +17,7 @@
"@hono/node-server": "^1.19.7",
"@hono/node-ws": "^1.3.0",
"@iarna/toml": "^2.2.5",
"@openhandoff/shared": "workspace:*",
"@sandbox-agent/factory-shared": "workspace:*",
"@sandbox-agent/persist-rivet": "workspace:*",
"drizzle-orm": "^0.44.5",
"hono": "^4.11.9",

View file

@ -1,4 +1,4 @@
import type { AppConfig } from "@openhandoff/shared";
import type { AppConfig } from "@sandbox-agent/factory-shared";
import type { BackendDriver } from "../driver.js";
import type { NotificationService } from "../notifications/index.js";
import type { ProviderRegistry } from "../providers/index.js";

View file

@ -1,4 +1,4 @@
import type { HandoffStatus, ProviderId } from "@openhandoff/shared";
import type { HandoffStatus, ProviderId } from "@sandbox-agent/factory-shared";
export interface HandoffCreatedEvent {
workspaceId: string;

View file

@ -8,7 +8,7 @@ import {
sandboxInstanceKey,
workspaceKey
} from "./keys.js";
import type { ProviderId } from "@openhandoff/shared";
import type { ProviderId } from "@sandbox-agent/factory-shared";
export function actorClient(c: any) {
return c.client();

View file

@ -1,6 +1,6 @@
import { actor, queue } from "rivetkit";
import { workflow } from "rivetkit/workflow";
import type { ProviderId } from "@openhandoff/shared";
import type { ProviderId } from "@sandbox-agent/factory-shared";
import { getHandoff, getSandboxInstance, selfHandoffStatusSync } from "../handles.js";
import { logActorWarning, resolveErrorMessage, resolveErrorStack } from "../logging.js";
import { type PollingControlState, runWorkflowPollingLoop } from "../polling.js";

View file

@ -10,7 +10,7 @@ import type {
HandoffWorkbenchSendMessageInput,
HandoffWorkbenchUpdateDraftInput,
ProviderId
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { expectQueueResponse } from "../../services/queue.js";
import { selfHandoff } from "../handles.js";
import { handoffDb } from "./db/db.js";

View file

@ -1,6 +1,6 @@
// @ts-nocheck
import { eq } from "drizzle-orm";
import type { HandoffRecord, HandoffStatus } from "@openhandoff/shared";
import type { HandoffRecord, HandoffStatus } from "@sandbox-agent/factory-shared";
import { getOrCreateWorkspace } from "../../handles.js";
import { handoff as handoffTable, handoffRuntime, handoffSandboxes } from "../db/schema.js";
import { historyKey } from "../../keys.js";

View file

@ -46,6 +46,8 @@ import {
export { HANDOFF_QUEUE_NAMES, handoffWorkflowQueueName } from "./queue.js";
const INIT_ENSURE_NAME_TIMEOUT_MS = 5 * 60_000;
type HandoffQueueName = (typeof HANDOFF_QUEUE_NAMES)[number];
type WorkflowHandler = (loopCtx: any, msg: { name: HandoffQueueName; body: any; complete: (response: unknown) => Promise<void> }) => Promise<void>;
@ -75,7 +77,11 @@ const commandHandlers: Record<HandoffQueueName, WorkflowHandler> = {
const body = msg.body;
await loopCtx.removed("init-failed", "step");
try {
await loopCtx.step("init-ensure-name", async () => initEnsureNameActivity(loopCtx));
await loopCtx.step({
name: "init-ensure-name",
timeout: INIT_ENSURE_NAME_TIMEOUT_MS,
run: async () => initEnsureNameActivity(loopCtx),
});
await loopCtx.step("init-assert-name", async () => initAssertNameActivity(loopCtx));
const sandbox = await loopCtx.step({

View file

@ -2,7 +2,7 @@
import { and, desc, eq } from "drizzle-orm";
import { actor, queue } from "rivetkit";
import { Loop, workflow } from "rivetkit/workflow";
import type { HistoryEvent } from "@openhandoff/shared";
import type { HistoryEvent } from "@sandbox-agent/factory-shared";
import { selfHistory } from "../handles.js";
import { historyDb } from "./db/db.js";
import { events } from "./db/schema.js";

View file

@ -27,5 +27,5 @@ export function logActorWarning(
...(context ?? {})
};
// eslint-disable-next-line no-console
console.warn("[openhandoff][actor:warn]", payload);
console.warn("[factory][actor:warn]", payload);
}

View file

@ -10,7 +10,7 @@ import type {
RepoOverview,
RepoStackAction,
RepoStackActionResult
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { getActorRuntimeContext } from "../context.js";
import {
getHandoff,
@ -21,7 +21,7 @@ import {
selfProject
} from "../handles.js";
import { isActorNotFoundError, logActorWarning, resolveErrorMessage } from "../logging.js";
import { openhandoffRepoClonePath } from "../../services/openhandoff-paths.js";
import { factoryRepoClonePath } from "../../services/factory-paths.js";
import { expectQueueResponse } from "../../services/queue.js";
import { withRepoGitLock } from "../../services/repo-git-lock.js";
import { branches, handoffIndex, prCache, repoMeta } from "./db/schema.js";
@ -125,7 +125,7 @@ export function projectWorkflowQueueName(name: ProjectQueueName): ProjectQueueNa
async function ensureLocalClone(c: any, remoteUrl: string): Promise<string> {
const { config, driver } = getActorRuntimeContext();
const localPath = openhandoffRepoClonePath(config, c.state.workspaceId, c.state.repoId);
const localPath = factoryRepoClonePath(config, c.state.workspaceId, c.state.repoId);
await driver.git.ensureCloned(remoteUrl, localPath);
c.state.localPath = localPath;
return localPath;

View file

@ -2,7 +2,7 @@ import { setTimeout as delay } from "node:timers/promises";
import { eq } from "drizzle-orm";
import { actor, queue } from "rivetkit";
import { Loop, workflow } from "rivetkit/workflow";
import type { ProviderId } from "@openhandoff/shared";
import type { ProviderId } from "@sandbox-agent/factory-shared";
import type { SessionEvent, SessionRecord } from "sandbox-agent";
import { sandboxInstanceDb } from "./db/db.js";
import { sandboxInstance as sandboxInstanceTable } from "./db/schema.js";

View file

@ -27,7 +27,7 @@ import type {
RepoRecord,
SwitchResult,
WorkspaceUseInput
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { getActorRuntimeContext } from "../context.js";
import { getHandoff, getOrCreateHistory, getOrCreateProject, selfWorkspace } from "../handles.js";
import { logActorWarning, resolveErrorMessage } from "../logging.js";

View file

@ -2,9 +2,9 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { homedir } from "node:os";
import * as toml from "@iarna/toml";
import { ConfigSchema, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, type AppConfig } from "@sandbox-agent/factory-shared";
export const CONFIG_PATH = `${homedir()}/.config/openhandoff/config.toml`;
export const CONFIG_PATH = `${homedir()}/.config/sandbox-agent-factory/config.toml`;
export function loadConfig(path = CONFIG_PATH): AppConfig {
if (!existsSync(path)) {

View file

@ -1,4 +1,4 @@
import type { AppConfig } from "@openhandoff/shared";
import type { AppConfig } from "@sandbox-agent/factory-shared";
export function defaultWorkspace(config: AppConfig): string {
const ws = config.workspace.default.trim();

View file

@ -29,7 +29,7 @@ export interface ActorSqliteDbOptions<TSchema extends Record<string, unknown>> {
/**
* Override base directory for per-actor SQLite files.
*
* Default: `<cwd>/.openhandoff/backend/sqlite`
* Default: `<cwd>/.sandbox-agent-factory/backend/sqlite`
*/
baseDir?: string;
}
@ -53,7 +53,7 @@ export function actorSqliteDb<TSchema extends Record<string, unknown>>(
}) as unknown as DatabaseProvider<any & RawAccess>;
}
const baseDir = options.baseDir ?? join(process.cwd(), ".openhandoff", "backend", "sqlite");
const baseDir = options.baseDir ?? join(process.cwd(), ".sandbox-agent-factory", "backend", "sqlite");
const migrationsFolder = fileURLToPath(options.migrationsFolderUrl);
return {

View file

@ -28,7 +28,7 @@ function ensureAskpassScript(): string {
return cachedAskpassPath;
}
const dir = mkdtempSync(resolve(tmpdir(), "openhandoff-git-askpass-"));
const dir = mkdtempSync(resolve(tmpdir(), "factory-git-askpass-"));
const path = resolve(dir, "askpass.sh");
// Git invokes $GIT_ASKPASS with the prompt string as argv[1]. Provide both username and password.

View file

@ -1,4 +1,4 @@
import type { AgentType } from "@openhandoff/shared";
import type { AgentType } from "@sandbox-agent/factory-shared";
import type {
ListEventsRequest,
ListPage,
@ -144,7 +144,7 @@ export class SandboxAgentClient {
const modeId = modeIdForAgent(normalized.agent ?? this.agent);
// Codex defaults to a restrictive "read-only" preset in some environments.
// For OpenHandoff automation we need to allow edits + command execution + network
// For Sandbox Agent Factory automation we need to allow edits + command execution + network
// access (git push / PR creation). Use full-access where supported.
//
// If the agent doesn't support session modes, ignore.

View file

@ -205,11 +205,11 @@ export class DaytonaProvider implements SandboxProvider {
image: this.buildSnapshotImage(),
envVars: this.buildEnvVars(),
labels: {
"openhandoff.workspace": req.workspaceId,
"openhandoff.handoff": req.handoffId,
"openhandoff.repo_id": req.repoId,
"openhandoff.repo_remote": req.repoRemote,
"openhandoff.branch": req.branchName,
"factory.workspace": req.workspaceId,
"factory.handoff": req.handoffId,
"factory.repo_id": req.repoId,
"factory.repo_remote": req.repoRemote,
"factory.branch": req.branchName,
},
autoStopInterval: this.config.autoStopInterval,
})
@ -220,7 +220,7 @@ export class DaytonaProvider implements SandboxProvider {
state: sandbox.state ?? null
});
const repoDir = `/home/daytona/openhandoff/${req.workspaceId}/${req.repoId}/${req.handoffId}/repo`;
const repoDir = `/home/daytona/sandbox-agent-factory/${req.workspaceId}/${req.repoId}/${req.handoffId}/repo`;
// Prepare a working directory for the agent. This must succeed for the handoff to work.
const installStartedAt = Date.now();
@ -258,8 +258,8 @@ export class DaytonaProvider implements SandboxProvider {
`git fetch origin --prune`,
// The handoff branch may not exist remotely yet (agent push creates it). Base off current branch (default branch).
`if git show-ref --verify --quiet "refs/remotes/origin/${req.branchName}"; then git checkout -B "${req.branchName}" "origin/${req.branchName}"; else git checkout -B "${req.branchName}" "$(git branch --show-current 2>/dev/null || echo main)"; fi`,
`git config user.email "openhandoff@local" >/dev/null 2>&1 || true`,
`git config user.name "OpenHandoff" >/dev/null 2>&1 || true`,
`git config user.email "factory@local" >/dev/null 2>&1 || true`,
`git config user.name "Sandbox Agent Factory" >/dev/null 2>&1 || true`,
].join("; ")
)}`
].join(" "),
@ -294,12 +294,12 @@ export class DaytonaProvider implements SandboxProvider {
client.getSandbox(req.sandboxId)
);
const labels = info.labels ?? {};
const workspaceId = labels["openhandoff.workspace"] ?? req.workspaceId;
const repoId = labels["openhandoff.repo_id"] ?? "";
const handoffId = labels["openhandoff.handoff"] ?? "";
const workspaceId = labels["factory.workspace"] ?? req.workspaceId;
const repoId = labels["factory.repo_id"] ?? "";
const handoffId = labels["factory.handoff"] ?? "";
const cwd =
repoId && handoffId
? `/home/daytona/openhandoff/${workspaceId}/${repoId}/${handoffId}/repo`
? `/home/daytona/sandbox-agent-factory/${workspaceId}/${repoId}/${handoffId}/repo`
: null;
return {

View file

@ -1,5 +1,5 @@
import type { ProviderId } from "@openhandoff/shared";
import type { AppConfig } from "@openhandoff/shared";
import type { ProviderId } from "@sandbox-agent/factory-shared";
import type { AppConfig } from "@sandbox-agent/factory-shared";
import type { BackendDriver } from "../driver.js";
import { DaytonaProvider } from "./daytona/index.js";
import { LocalProvider } from "./local/index.js";

View file

@ -77,7 +77,7 @@ export class LocalProvider implements SandboxProvider {
private rootDir(): string {
return expandHome(
this.config.rootDir?.trim() || "~/.local/share/openhandoff/local-sandboxes",
this.config.rootDir?.trim() || "~/.local/share/sandbox-agent-factory/local-sandboxes",
);
}

View file

@ -1,4 +1,4 @@
import type { ProviderId } from "@openhandoff/shared";
import type { ProviderId } from "@sandbox-agent/factory-shared";
export interface ProviderCapabilities {
remote: boolean;

View file

@ -1,4 +1,4 @@
import type { AppConfig } from "@openhandoff/shared";
import type { AppConfig } from "@sandbox-agent/factory-shared";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
@ -9,17 +9,17 @@ function expandPath(input: string): string {
return input;
}
export function openhandoffDataDir(config: AppConfig): string {
export function factoryDataDir(config: AppConfig): string {
// Keep data collocated with the backend DB by default.
const dbPath = expandPath(config.backend.dbPath);
return resolve(dirname(dbPath));
}
export function openhandoffRepoClonePath(
export function factoryRepoClonePath(
config: AppConfig,
workspaceId: string,
repoId: string
): string {
return resolve(join(openhandoffDataDir(config), "repos", workspaceId, repoId));
return resolve(join(factoryDataDir(config), "repos", workspaceId, repoId));
}

View file

@ -12,7 +12,7 @@ class RecordingDaytonaClient implements DaytonaClientLike {
return {
id: "sandbox-1",
state: "started",
snapshot: "snapshot-openhandoff",
snapshot: "snapshot-factory",
labels: {},
};
}
@ -21,7 +21,7 @@ class RecordingDaytonaClient implements DaytonaClientLike {
return {
id: sandboxId,
state: "started",
snapshot: "snapshot-openhandoff",
snapshot: "snapshot-factory",
labels: {},
};
}
@ -92,9 +92,9 @@ describe("daytona provider snapshot image behavior", () => {
expect(commands).toContain("GIT_TERMINAL_PROMPT=0");
expect(commands).toContain("GIT_ASKPASS=/bin/echo");
expect(handle.metadata.snapshot).toBe("snapshot-openhandoff");
expect(handle.metadata.snapshot).toBe("snapshot-factory");
expect(handle.metadata.image).toBe("ubuntu:24.04");
expect(handle.metadata.cwd).toBe("/home/daytona/openhandoff/default/repo-1/handoff-1/repo");
expect(handle.metadata.cwd).toBe("/home/daytona/sandbox-agent-factory/default/repo-1/handoff-1/repo");
expect(client.executedCommands.length).toBeGreaterThan(0);
});

View file

@ -27,7 +27,7 @@ describe("validateRemote", () => {
mkdirSync(brokenRepoDir, { recursive: true });
writeFileSync(resolve(brokenRepoDir, ".git"), "gitdir: /definitely/missing/worktree\n", "utf8");
await execFileAsync("git", ["init", remoteRepoDir]);
await execFileAsync("git", ["-C", remoteRepoDir, "config", "user.name", "OpenHandoff Test"]);
await execFileAsync("git", ["-C", remoteRepoDir, "config", "user.name", "Factory Test"]);
await execFileAsync("git", ["-C", remoteRepoDir, "config", "user.email", "test@example.com"]);
writeFileSync(resolve(remoteRepoDir, "README.md"), "# test\n", "utf8");
await execFileAsync("git", ["-C", remoteRepoDir, "add", "README.md"]);

View file

@ -1,6 +1,6 @@
import { tmpdir } from "node:os";
import { join } from "node:path";
import { ConfigSchema, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, type AppConfig } from "@sandbox-agent/factory-shared";
import type { BackendDriver } from "../../src/driver.js";
import { initActorRuntimeContext } from "../../src/actors/context.js";
import { createProviderRegistry } from "../../src/providers/index.js";

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { ConfigSchema, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, type AppConfig } from "@sandbox-agent/factory-shared";
import { createProviderRegistry } from "../src/providers/index.js";
function makeConfig(): AppConfig {
@ -10,7 +10,7 @@ function makeConfig(): AppConfig {
backend: {
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,

View file

@ -3,41 +3,41 @@ import { normalizeRemoteUrl, repoIdFromRemote } from "../src/services/repo.js";
describe("normalizeRemoteUrl", () => {
test("accepts GitHub shorthand owner/repo", () => {
expect(normalizeRemoteUrl("rivet-dev/openhandoff")).toBe(
"https://github.com/rivet-dev/openhandoff.git"
expect(normalizeRemoteUrl("rivet-dev/sandbox-agent-factory")).toBe(
"https://github.com/rivet-dev/sandbox-agent-factory.git"
);
});
test("accepts github.com/owner/repo without scheme", () => {
expect(normalizeRemoteUrl("github.com/rivet-dev/openhandoff")).toBe(
"https://github.com/rivet-dev/openhandoff.git"
expect(normalizeRemoteUrl("github.com/rivet-dev/sandbox-agent-factory")).toBe(
"https://github.com/rivet-dev/sandbox-agent-factory.git"
);
});
test("canonicalizes GitHub repo URLs without .git", () => {
expect(normalizeRemoteUrl("https://github.com/rivet-dev/openhandoff")).toBe(
"https://github.com/rivet-dev/openhandoff.git"
expect(normalizeRemoteUrl("https://github.com/rivet-dev/sandbox-agent-factory")).toBe(
"https://github.com/rivet-dev/sandbox-agent-factory.git"
);
});
test("canonicalizes GitHub non-clone URLs (e.g. /tree/main)", () => {
expect(normalizeRemoteUrl("https://github.com/rivet-dev/openhandoff/tree/main")).toBe(
"https://github.com/rivet-dev/openhandoff.git"
expect(normalizeRemoteUrl("https://github.com/rivet-dev/sandbox-agent-factory/tree/main")).toBe(
"https://github.com/rivet-dev/sandbox-agent-factory.git"
);
});
test("does not rewrite scp-style ssh remotes", () => {
expect(normalizeRemoteUrl("git@github.com:rivet-dev/openhandoff.git")).toBe(
"git@github.com:rivet-dev/openhandoff.git"
expect(normalizeRemoteUrl("git@github.com:rivet-dev/sandbox-agent-factory.git")).toBe(
"git@github.com:rivet-dev/sandbox-agent-factory.git"
);
});
});
describe("repoIdFromRemote", () => {
test("repoId is stable across equivalent GitHub inputs", () => {
const a = repoIdFromRemote("rivet-dev/openhandoff");
const b = repoIdFromRemote("https://github.com/rivet-dev/openhandoff.git");
const c = repoIdFromRemote("https://github.com/rivet-dev/openhandoff/tree/main");
const a = repoIdFromRemote("rivet-dev/sandbox-agent-factory");
const b = repoIdFromRemote("https://github.com/rivet-dev/sandbox-agent-factory.git");
const c = repoIdFromRemote("https://github.com/rivet-dev/sandbox-agent-factory/tree/main");
expect(a).toBe(b);
expect(b).toBe(c);
});

View file

@ -17,7 +17,7 @@ function createRepo(): { repoPath: string } {
const repoPath = mkdtempSync(join(tmpdir(), "hf-isolation-repo-"));
execFileSync("git", ["init"], { cwd: repoPath });
execFileSync("git", ["config", "user.email", "test@example.com"], { cwd: repoPath });
execFileSync("git", ["config", "user.name", "OpenHandoff Test"], { cwd: repoPath });
execFileSync("git", ["config", "user.name", "Factory Test"], { cwd: repoPath });
writeFileSync(join(repoPath, "README.md"), "hello\n", "utf8");
execFileSync("git", ["add", "README.md"], { cwd: repoPath });
execFileSync("git", ["commit", "-m", "init"], { cwd: repoPath });

View file

@ -20,7 +20,7 @@ function locationToNames(entry, names) {
}
for (const t of targets) {
const db = new Database(`/root/.local/share/openhandoff/rivetkit/databases/${t.actorId}.db`, { readonly: true });
const db = new Database(`/root/.local/share/sandbox-agent-factory/rivetkit/databases/${t.actorId}.db`, { readonly: true });
const token = new TextDecoder().decode(db.query("SELECT value FROM kv WHERE hex(key)=?").get("03").value);
await new Promise((resolve, reject) => {

View file

@ -1,6 +1,6 @@
import { Database } from "bun:sqlite";
const db = new Database("/root/.local/share/openhandoff/rivetkit/databases/2e443238457137bf.db", { readonly: true });
const db = new Database("/root/.local/share/sandbox-agent-factory/rivetkit/databases/2e443238457137bf.db", { readonly: true });
const rows = db.query("SELECT hex(key) as k, value as v FROM kv WHERE hex(key) LIKE ? ORDER BY key").all("07%");
const out = rows.map((r) => {
const bytes = new Uint8Array(r.v);

View file

@ -9,7 +9,7 @@ import { decodeReadRangeWire } from "/rivet-handoff-fixes/rivetkit-typescript/pa
import { readRangeWireToOtlp } from "/rivet-handoff-fixes/rivetkit-typescript/packages/traces/src/read-range.ts";
const actorId = "2e443238457137bf";
const db = new Database(`/root/.local/share/openhandoff/rivetkit/databases/${actorId}.db`, { readonly: true });
const db = new Database(`/root/.local/share/sandbox-agent-factory/rivetkit/databases/${actorId}.db`, { readonly: true });
const row = db.query("SELECT value FROM kv WHERE hex(key)=?").get("03");
const token = new TextDecoder().decode(row.value);

View file

@ -14,7 +14,7 @@ function decodeAscii(u8) {
}
for (const actorId of actorIds) {
const dbPath = `/root/.local/share/openhandoff/rivetkit/databases/${actorId}.db`;
const dbPath = `/root/.local/share/sandbox-agent-factory/rivetkit/databases/${actorId}.db`;
const db = new Database(dbPath, { readonly: true });
const wfStateRow = db.query("SELECT value FROM kv WHERE hex(key)=?").get("0715041501");

View file

@ -3,7 +3,7 @@ import { TO_CLIENT_VERSIONED, decodeWorkflowHistoryTransport } from "rivetkit/in
import util from "node:util";
const actorId = "2e443238457137bf";
const db = new Database(`/root/.local/share/openhandoff/rivetkit/databases/${actorId}.db`, { readonly: true });
const db = new Database(`/root/.local/share/sandbox-agent-factory/rivetkit/databases/${actorId}.db`, { readonly: true });
const row = db.query("SELECT value FROM kv WHERE hex(key) = ?").get("03");
const token = new TextDecoder().decode(row.value);

View file

@ -1,5 +1,5 @@
{
"name": "@openhandoff/cli",
"name": "@sandbox-agent/factory-cli",
"version": "0.1.0",
"private": true,
"type": "module",
@ -16,8 +16,8 @@
"dependencies": {
"@iarna/toml": "^2.2.5",
"@opentui/core": "^0.1.77",
"@openhandoff/client": "workspace:*",
"@openhandoff/shared": "workspace:*",
"@sandbox-agent/factory-client": "workspace:*",
"@sandbox-agent/factory-shared": "workspace:*",
"zod": "^4.1.5"
},
"devDependencies": {

View file

@ -11,8 +11,8 @@ import {
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { checkBackendHealth } from "@openhandoff/client";
import type { AppConfig } from "@openhandoff/shared";
import { checkBackendHealth } from "@sandbox-agent/factory-client";
import type { AppConfig } from "@sandbox-agent/factory-shared";
import { CLI_BUILD_ID } from "../build-id.js";
const HEALTH_TIMEOUT_MS = 1_500;
@ -39,10 +39,10 @@ function backendStateDir(): string {
const xdgDataHome = process.env.XDG_DATA_HOME?.trim();
if (xdgDataHome) {
return join(xdgDataHome, "openhandoff", "backend");
return join(xdgDataHome, "sandbox-agent-factory", "backend");
}
return join(homedir(), ".local", "share", "openhandoff", "backend");
return join(homedir(), ".local", "share", "sandbox-agent-factory", "backend");
}
function backendPidPath(host: string, port: number): string {
@ -214,7 +214,7 @@ function resolveLaunchSpec(host: string, port: number): LaunchSpec {
command: "pnpm",
args: [
"--filter",
"@openhandoff/backend",
"@sandbox-agent/factory-backend",
"exec",
"bun",
"src/index.ts",

View file

@ -2,14 +2,14 @@
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { AgentTypeSchema, CreateHandoffInputSchema, type HandoffRecord } from "@openhandoff/shared";
import { AgentTypeSchema, CreateHandoffInputSchema, type HandoffRecord } from "@sandbox-agent/factory-shared";
import {
readBackendMetadata,
createBackendClientFromConfig,
formatRelativeAge,
groupHandoffStatus,
summarizeHandoffs
} from "@openhandoff/client";
} from "@sandbox-agent/factory-client";
import {
ensureBackendRunning,
getBackendStatus,

View file

@ -3,7 +3,7 @@ import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { cwd } from "node:process";
import * as toml from "@iarna/toml";
import type { AppConfig } from "@openhandoff/shared";
import type { AppConfig } from "@sandbox-agent/factory-shared";
import opencodeThemePackJson from "./themes/opencode-pack.json" with { type: "json" };
export type ThemeMode = "dark" | "light";
@ -101,7 +101,7 @@ export function resolveTuiTheme(config: AppConfig, baseDir = cwd()): TuiThemeRes
return {
theme: candidate.theme,
name: candidate.name,
source: "openhandoff config",
source: "factory config",
mode
};
}

View file

@ -1,11 +1,11 @@
import type { AppConfig, HandoffRecord } from "@openhandoff/shared";
import type { AppConfig, HandoffRecord } from "@sandbox-agent/factory-shared";
import { spawnSync } from "node:child_process";
import {
createBackendClientFromConfig,
filterHandoffs,
formatRelativeAge,
groupHandoffStatus
} from "@openhandoff/client";
} from "@sandbox-agent/factory-client";
import { CLI_BUILD_ID } from "./build-id.js";
import { resolveTuiTheme, type TuiTheme } from "./theme.js";
@ -338,7 +338,7 @@ export async function runTui(config: AppConfig, workspaceId: string): Promise<vo
const client = createBackendClientFromConfig(config);
const renderer = await createCliRenderer({ exitOnCtrlC: false });
const text = new TextRenderable(renderer, {
id: "openhandoff-switch",
id: "factory-switch",
content: "Loading..."
});
text.fg = themeResolution.theme.text;

View file

@ -2,9 +2,9 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { homedir } from "node:os";
import * as toml from "@iarna/toml";
import { ConfigSchema, resolveWorkspaceId, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, resolveWorkspaceId, type AppConfig } from "@sandbox-agent/factory-shared";
export const CONFIG_PATH = `${homedir()}/.config/openhandoff/config.toml`;
export const CONFIG_PATH = `${homedir()}/.config/sandbox-agent-factory/config.toml`;
export function loadConfig(path = CONFIG_PATH): AppConfig {
if (!existsSync(path)) {

View file

@ -20,7 +20,7 @@ vi.mock("node:child_process", async () => {
});
import { ensureBackendRunning, parseBackendPort } from "../src/backend/manager.js";
import { ConfigSchema, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, type AppConfig } from "@sandbox-agent/factory-shared";
function backendStateFile(baseDir: string, host: string, port: number, suffix: string): string {
const sanitized = host
@ -62,7 +62,7 @@ describe("backend manager", () => {
backend: {
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,

View file

@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { ConfigSchema, type AppConfig } from "@openhandoff/shared";
import { ConfigSchema, type AppConfig } from "@sandbox-agent/factory-shared";
import { resolveTuiTheme } from "../src/theme.js";
function withEnv(key: string, value: string | undefined): void {
@ -25,7 +25,7 @@ describe("resolveTuiTheme", () => {
backend: {
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,
@ -98,7 +98,7 @@ describe("resolveTuiTheme", () => {
expect(resolution.theme.background).toBe("#0a0a0a");
});
it("prefers explicit openhandoff theme override from config", () => {
it("prefers explicit factory theme override from config", () => {
tempDir = mkdtempSync(join(tmpdir(), "hf-theme-test-"));
withEnv("XDG_STATE_HOME", join(tempDir, "state"));
withEnv("XDG_CONFIG_HOME", join(tempDir, "config"));
@ -107,6 +107,6 @@ describe("resolveTuiTheme", () => {
const resolution = resolveTuiTheme(config, tempDir);
expect(resolution.name).toBe("opencode-default");
expect(resolution.source).toBe("openhandoff config");
expect(resolution.source).toBe("factory config");
});
});

View file

@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { HandoffRecord } from "@openhandoff/shared";
import { filterHandoffs, fuzzyMatch } from "@openhandoff/client";
import type { HandoffRecord } from "@sandbox-agent/factory-shared";
import { filterHandoffs, fuzzyMatch } from "@sandbox-agent/factory-client";
import { formatRows } from "../src/tui.js";
const sample: HandoffRecord = {

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { ConfigSchema } from "@openhandoff/shared";
import { ConfigSchema } from "@sandbox-agent/factory-shared";
import { resolveWorkspace } from "../src/workspace/config.js";
describe("cli workspace resolution", () => {
@ -11,7 +11,7 @@ describe("cli workspace resolution", () => {
backend: {
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,

View file

@ -1,12 +1,43 @@
{
"name": "@openhandoff/client",
"name": "@sandbox-agent/factory-client",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./backend": {
"types": "./dist/backend.d.ts",
"import": "./dist/backend.js"
},
"./workbench": {
"types": "./dist/workbench.d.ts",
"import": "./dist/workbench.js"
},
"./view-model": {
"types": "./dist/view-model.d.ts",
"import": "./dist/view-model.js"
}
},
"typesVersions": {
"*": {
"backend": [
"dist/backend.d.ts"
],
"view-model": [
"dist/view-model.d.ts"
],
"workbench": [
"dist/workbench.d.ts"
]
}
},
"scripts": {
"build": "tsup src/index.ts --format esm --dts",
"build": "tsup src/index.ts src/backend.ts src/workbench.ts src/view-model.ts --format esm --dts",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:e2e:full": "HF_ENABLE_DAEMON_FULL_E2E=1 vitest run test/e2e/full-integration-e2e.test.ts",
@ -14,7 +45,7 @@
"test:e2e:workbench-load": "HF_ENABLE_DAEMON_WORKBENCH_LOAD_E2E=1 vitest run test/e2e/workbench-load-e2e.test.ts"
},
"dependencies": {
"@openhandoff/shared": "workspace:*",
"@sandbox-agent/factory-shared": "workspace:*",
"rivetkit": "link:../../../../../handoff/rivet-checkout/rivetkit-typescript/packages/rivetkit"
},
"devDependencies": {

View file

@ -26,7 +26,7 @@ import type {
RepoStackActionResult,
RepoRecord,
SwitchResult
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { sandboxInstanceKey, workspaceKey } from "./keys.js";
export type HandoffAction = "push" | "sync" | "merge" | "archive" | "kill";

View file

@ -0,0 +1 @@
export * from "./backend-client.js";

View file

@ -26,7 +26,7 @@ import type {
WorkbenchAgentTab as AgentTab,
WorkbenchHandoff as Handoff,
WorkbenchTranscriptEvent as TranscriptEvent,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import type { HandoffWorkbenchClient } from "../workbench-client.js";
function buildTranscriptEvent(params: {
@ -48,10 +48,14 @@ function buildTranscriptEvent(params: {
}
class MockWorkbenchStore implements HandoffWorkbenchClient {
private snapshot = buildInitialMockLayoutViewModel();
private snapshot: HandoffWorkbenchSnapshot;
private listeners = new Set<() => void>();
private pendingTimers = new Map<string, ReturnType<typeof setTimeout>>();
constructor(workspaceId: string) {
this.snapshot = buildInitialMockLayoutViewModel(workspaceId);
}
getSnapshot(): HandoffWorkbenchSnapshot {
return this.snapshot;
}
@ -103,6 +107,17 @@ class MockWorkbenchStore implements HandoffWorkbenchClient {
...current,
handoffs: [nextHandoff, ...current.handoffs],
}));
const task = input.task.trim();
if (task) {
await this.sendMessage({
handoffId: id,
tabId,
text: task,
attachments: [],
});
}
return { handoffId: id, tabId };
}
@ -149,6 +164,13 @@ class MockWorkbenchStore implements HandoffWorkbenchClient {
}));
}
async pushHandoff(input: HandoffWorkbenchSelectInput): Promise<void> {
this.updateHandoff(input.handoffId, (handoff) => ({
...handoff,
updatedAtMs: nowMs(),
}));
}
async revertFile(input: HandoffWorkbenchDiffInput): Promise<void> {
this.updateHandoff(input.handoffId, (handoff) => {
const file = handoff.fileChanges.find((entry) => entry.path === input.path);
@ -195,8 +217,11 @@ class MockWorkbenchStore implements HandoffWorkbenchClient {
this.updateHandoff(input.handoffId, (currentHandoff) => {
const isFirstOnHandoff = currentHandoff.status === "new";
const newTitle = isFirstOnHandoff ? (text.length > 50 ? `${text.slice(0, 47)}...` : text) : currentHandoff.title;
const newBranch = isFirstOnHandoff ? `feat/${slugify(newTitle)}` : currentHandoff.branch;
const synthesizedTitle = text.length > 50 ? `${text.slice(0, 47)}...` : text;
const newTitle =
isFirstOnHandoff && currentHandoff.title === "New Handoff" ? synthesizedTitle : currentHandoff.title;
const newBranch =
isFirstOnHandoff && !currentHandoff.branch ? `feat/${slugify(synthesizedTitle)}` : currentHandoff.branch;
const userMessageLines = [text, ...input.attachments.map((attachment) => `@ ${attachment.filePath}:${attachment.lineNumber}`)];
const userEvent = buildTranscriptEvent({
sessionId: input.tabId,
@ -435,11 +460,13 @@ function candidateEventIndex(handoff: Handoff, tabId: string): number {
return (tab?.transcript.length ?? 0) + 1;
}
let sharedMockWorkbenchClient: HandoffWorkbenchClient | null = null;
const mockWorkbenchClients = new Map<string, HandoffWorkbenchClient>();
export function getSharedMockWorkbenchClient(): HandoffWorkbenchClient {
if (!sharedMockWorkbenchClient) {
sharedMockWorkbenchClient = new MockWorkbenchStore();
export function getMockWorkbenchClient(workspaceId = "default"): HandoffWorkbenchClient {
let client = mockWorkbenchClients.get(workspaceId);
if (!client) {
client = new MockWorkbenchStore(workspaceId);
mockWorkbenchClients.set(workspaceId, client);
}
return sharedMockWorkbenchClient;
return client;
}

View file

@ -12,7 +12,7 @@ import type {
HandoffWorkbenchSnapshot,
HandoffWorkbenchTabInput,
HandoffWorkbenchUpdateDraftInput,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import type { BackendClient } from "../backend-client.js";
import { groupWorkbenchProjects } from "../workbench-model.js";
import type { HandoffWorkbenchClient } from "../workbench-client.js";
@ -93,6 +93,11 @@ class RemoteWorkbenchStore implements HandoffWorkbenchClient {
await this.refresh();
}
async pushHandoff(input: HandoffWorkbenchSelectInput): Promise<void> {
await this.backend.runAction(this.workspaceId, input.handoffId, "push");
await this.refresh();
}
async revertFile(input: HandoffWorkbenchDiffInput): Promise<void> {
await this.backend.revertWorkbenchFile(this.workspaceId, input);
await this.refresh();

View file

@ -1,4 +1,4 @@
import type { HandoffRecord, HandoffStatus } from "@openhandoff/shared";
import type { HandoffRecord, HandoffStatus } from "@sandbox-agent/factory-shared";
export const HANDOFF_STATUS_GROUPS = [
"queued",

View file

@ -12,9 +12,9 @@ import type {
HandoffWorkbenchSnapshot,
HandoffWorkbenchTabInput,
HandoffWorkbenchUpdateDraftInput,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import type { BackendClient } from "./backend-client.js";
import { getSharedMockWorkbenchClient } from "./mock/workbench-client.js";
import { getMockWorkbenchClient } from "./mock/workbench-client.js";
import { createRemoteWorkbenchClient } from "./remote/workbench-client.js";
export type HandoffWorkbenchClientMode = "mock" | "remote";
@ -34,6 +34,7 @@ export interface HandoffWorkbenchClient {
renameBranch(input: HandoffWorkbenchRenameInput): Promise<void>;
archiveHandoff(input: HandoffWorkbenchSelectInput): Promise<void>;
publishPr(input: HandoffWorkbenchSelectInput): Promise<void>;
pushHandoff(input: HandoffWorkbenchSelectInput): Promise<void>;
revertFile(input: HandoffWorkbenchDiffInput): Promise<void>;
updateDraft(input: HandoffWorkbenchUpdateDraftInput): Promise<void>;
sendMessage(input: HandoffWorkbenchSendMessageInput): Promise<void>;
@ -49,7 +50,7 @@ export function createHandoffWorkbenchClient(
options: CreateHandoffWorkbenchClientOptions,
): HandoffWorkbenchClient {
if (options.mode === "mock") {
return getSharedMockWorkbenchClient();
return getMockWorkbenchClient(options.workspaceId);
}
if (!options.backend) {

View file

@ -12,7 +12,7 @@ import type {
WorkbenchProjectSection,
WorkbenchRepo,
WorkbenchTranscriptEvent as TranscriptEvent,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
export const MODEL_GROUPS: ModelGroup[] = [
{
@ -913,7 +913,7 @@ export function buildInitialHandoffs(): Handoff[] {
];
}
export function buildInitialMockLayoutViewModel(): HandoffWorkbenchSnapshot {
export function buildInitialMockLayoutViewModel(workspaceId = "default"): HandoffWorkbenchSnapshot {
const repos: WorkbenchRepo[] = [
{ id: "acme-backend", label: "acme/backend" },
{ id: "acme-frontend", label: "acme/frontend" },
@ -921,7 +921,7 @@ export function buildInitialMockLayoutViewModel(): HandoffWorkbenchSnapshot {
];
const handoffs = buildInitialHandoffs();
return {
workspaceId: "default",
workspaceId,
repos,
projects: groupWorkbenchProjects(repos, handoffs),
handoffs,
@ -960,6 +960,5 @@ export function groupWorkbenchProjects(repos: WorkbenchRepo[], handoffs: Handoff
updatedAtMs:
project.handoffs.length > 0 ? Math.max(...project.handoffs.map((handoff) => handoff.updatedAtMs)) : project.updatedAtMs,
}))
.filter((project) => project.handoffs.length > 0)
.sort((a, b) => b.updatedAtMs - a.updatedAtMs);
}

View file

@ -0,0 +1 @@
export * from "./workbench-client.js";

View file

@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { describe, expect, it } from "vitest";
import type { HistoryEvent, RepoOverview } from "@openhandoff/shared";
import type { HistoryEvent, RepoOverview } from "@sandbox-agent/factory-shared";
import { createBackendClient } from "../../src/backend-client.js";
const RUN_FULL_E2E = process.env.HF_ENABLE_DAEMON_FULL_E2E === "1";

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { HandoffRecord, HistoryEvent } from "@openhandoff/shared";
import type { HandoffRecord, HistoryEvent } from "@sandbox-agent/factory-shared";
import { createBackendClient } from "../../src/backend-client.js";
const RUN_E2E = process.env.HF_ENABLE_DAEMON_E2E === "1";

View file

@ -1,13 +1,15 @@
import { execFile } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import type {
HandoffRecord,
HandoffWorkbenchSnapshot,
WorkbenchAgentTab,
WorkbenchHandoff,
WorkbenchModelId,
WorkbenchTranscriptEvent,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { createBackendClient } from "../../src/backend-client.js";
const RUN_WORKBENCH_E2E = process.env.HF_ENABLE_DAEMON_WORKBENCH_E2E === "1";
@ -21,6 +23,10 @@ function requiredEnv(name: string): string {
return value;
}
function requiredRepoRemote(): string {
return process.env.HF_E2E_REPO_REMOTE?.trim() || requiredEnv("HF_E2E_GITHUB_REPO");
}
function workbenchModelEnv(name: string, fallback: WorkbenchModelId): WorkbenchModelId {
const value = process.env[name]?.trim();
switch (value) {
@ -38,14 +44,66 @@ async function sleep(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}
async function seedSandboxFile(workspaceId: string, handoffId: string, filePath: string, content: string): Promise<void> {
const repoPath = `/root/.local/share/openhandoff/local-sandboxes/${workspaceId}/${handoffId}/repo`;
function backendPortFromEndpoint(endpoint: string): string {
const url = new URL(endpoint);
if (url.port) {
return url.port;
}
return url.protocol === "https:" ? "443" : "80";
}
async function resolveBackendContainerName(endpoint: string): Promise<string | null> {
const explicit = process.env.HF_E2E_BACKEND_CONTAINER?.trim();
if (explicit) {
if (explicit.toLowerCase() === "host") {
return null;
}
return explicit;
}
const { stdout } = await execFileAsync("docker", [
"ps",
"--filter",
`publish=${backendPortFromEndpoint(endpoint)}`,
"--format",
"{{.Names}}",
]);
const containerName = stdout
.split("\n")
.map((line) => line.trim())
.find(Boolean);
return containerName ?? null;
}
function sandboxRepoPath(record: HandoffRecord): string {
const activeSandbox =
record.sandboxes.find((sandbox) => sandbox.sandboxId === record.activeSandboxId) ??
record.sandboxes.find((sandbox) => typeof sandbox.cwd === "string" && sandbox.cwd.length > 0);
const cwd = activeSandbox?.cwd?.trim();
if (!cwd) {
throw new Error(`No sandbox cwd is available for handoff ${record.handoffId}`);
}
return cwd;
}
async function seedSandboxFile(endpoint: string, record: HandoffRecord, filePath: string, content: string): Promise<void> {
const repoPath = sandboxRepoPath(record);
const containerName = await resolveBackendContainerName(endpoint);
if (!containerName) {
const directory =
filePath.includes("/") ? `${repoPath}/${filePath.slice(0, filePath.lastIndexOf("/"))}` : repoPath;
await mkdir(directory, { recursive: true });
await writeFile(`${repoPath}/${filePath}`, `${content}\n`, "utf8");
return;
}
const script = [
`cd ${JSON.stringify(repoPath)}`,
`mkdir -p ${JSON.stringify(filePath.includes("/") ? filePath.slice(0, filePath.lastIndexOf("/")) : ".")}`,
`printf '%s\\n' ${JSON.stringify(content)} > ${JSON.stringify(filePath)}`,
].join(" && ");
await execFileAsync("docker", ["exec", "openhandoff-backend-1", "bash", "-lc", script]);
await execFileAsync("docker", ["exec", containerName, "bash", "-lc", script]);
}
async function poll<T>(
@ -166,7 +224,7 @@ describe("e2e(client): workbench flows", () => {
const endpoint =
process.env.HF_E2E_BACKEND_ENDPOINT?.trim() || "http://127.0.0.1:7741/api/rivet";
const workspaceId = process.env.HF_E2E_WORKSPACE?.trim() || "default";
const repoRemote = requiredEnv("HF_E2E_GITHUB_REPO");
const repoRemote = requiredRepoRemote();
const model = workbenchModelEnv("HF_E2E_MODEL", "gpt-4o");
const runId = `wb-${Date.now().toString(36)}`;
const expectedFile = `${runId}.txt`;
@ -215,7 +273,8 @@ describe("e2e(client): workbench flows", () => {
expect(findTab(initialCompleted, primaryTab.id).sessionId).toBeTruthy();
expect(transcriptIncludesAgentText(findTab(initialCompleted, primaryTab.id).transcript, expectedInitialReply)).toBe(true);
await seedSandboxFile(workspaceId, created.handoffId, expectedFile, runId);
const detail = await client.getHandoff(workspaceId, created.handoffId);
await seedSandboxFile(endpoint, detail, expectedFile, runId);
const fileSeeded = await poll(
"seeded sandbox file reflected in workbench",

View file

@ -5,7 +5,7 @@ import type {
WorkbenchHandoff,
WorkbenchModelId,
WorkbenchTranscriptEvent,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { createBackendClient } from "../../src/backend-client.js";
const RUN_WORKBENCH_LOAD_E2E = process.env.HF_ENABLE_DAEMON_WORKBENCH_LOAD_E2E === "1";
@ -18,6 +18,10 @@ function requiredEnv(name: string): string {
return value;
}
function requiredRepoRemote(): string {
return process.env.HF_E2E_REPO_REMOTE?.trim() || requiredEnv("HF_E2E_GITHUB_REPO");
}
function workbenchModelEnv(name: string, fallback: WorkbenchModelId): WorkbenchModelId {
const value = process.env[name]?.trim();
switch (value) {
@ -196,7 +200,7 @@ describe("e2e(client): workbench load", () => {
async () => {
const endpoint = process.env.HF_E2E_BACKEND_ENDPOINT?.trim() || "http://127.0.0.1:7741/api/rivet";
const workspaceId = process.env.HF_E2E_WORKSPACE?.trim() || "default";
const repoRemote = requiredEnv("HF_E2E_GITHUB_REPO");
const repoRemote = requiredRepoRemote();
const model = workbenchModelEnv("HF_E2E_MODEL", "gpt-4o");
const handoffCount = intEnv("HF_LOAD_HANDOFF_COUNT", 3);
const extraSessionCount = intEnv("HF_LOAD_EXTRA_SESSION_COUNT", 2);

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { HandoffRecord } from "@openhandoff/shared";
import type { HandoffRecord } from "@sandbox-agent/factory-shared";
import {
filterHandoffs,
formatRelativeAge,

View file

@ -0,0 +1,128 @@
import { describe, expect, it } from "vitest";
import type { BackendClient } from "../src/backend-client.js";
import { createHandoffWorkbenchClient } from "../src/workbench-client.js";
async function sleep(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}
describe("createHandoffWorkbenchClient", () => {
it("scopes mock clients by workspace", async () => {
const alpha = createHandoffWorkbenchClient({
mode: "mock",
workspaceId: "mock-alpha",
});
const beta = createHandoffWorkbenchClient({
mode: "mock",
workspaceId: "mock-beta",
});
const alphaInitial = alpha.getSnapshot();
const betaInitial = beta.getSnapshot();
expect(alphaInitial.workspaceId).toBe("mock-alpha");
expect(betaInitial.workspaceId).toBe("mock-beta");
await alpha.createHandoff({
repoId: alphaInitial.repos[0]!.id,
task: "Ship alpha-only change",
title: "Alpha only",
});
expect(alpha.getSnapshot().handoffs).toHaveLength(alphaInitial.handoffs.length + 1);
expect(beta.getSnapshot().handoffs).toHaveLength(betaInitial.handoffs.length);
});
it("uses the initial task to bootstrap a new mock handoff session", async () => {
const client = createHandoffWorkbenchClient({
mode: "mock",
workspaceId: "mock-onboarding",
});
const snapshot = client.getSnapshot();
const created = await client.createHandoff({
repoId: snapshot.repos[0]!.id,
task: "Reply with exactly: MOCK_WORKBENCH_READY",
title: "Mock onboarding",
branch: "feat/mock-onboarding",
model: "gpt-4o",
});
const runningHandoff = client.getSnapshot().handoffs.find((handoff) => handoff.id === created.handoffId);
expect(runningHandoff).toEqual(
expect.objectContaining({
title: "Mock onboarding",
branch: "feat/mock-onboarding",
status: "running",
}),
);
expect(runningHandoff?.tabs[0]).toEqual(
expect.objectContaining({
id: created.tabId,
created: true,
status: "running",
}),
);
expect(runningHandoff?.tabs[0]?.transcript).toEqual([
expect.objectContaining({
sender: "client",
payload: expect.objectContaining({
method: "session/prompt",
}),
}),
]);
await sleep(2_700);
const completedHandoff = client.getSnapshot().handoffs.find((handoff) => handoff.id === created.handoffId);
expect(completedHandoff?.status).toBe("idle");
expect(completedHandoff?.tabs[0]).toEqual(
expect.objectContaining({
status: "idle",
unread: true,
}),
);
expect(completedHandoff?.tabs[0]?.transcript).toEqual([
expect.objectContaining({ sender: "client" }),
expect.objectContaining({ sender: "agent" }),
]);
});
it("routes remote push actions through the backend boundary", async () => {
const actions: Array<{ workspaceId: string; handoffId: string; action: string }> = [];
let snapshotReads = 0;
const backend = {
async runAction(workspaceId: string, handoffId: string, action: string): Promise<void> {
actions.push({ workspaceId, handoffId, action });
},
async getWorkbench(workspaceId: string) {
snapshotReads += 1;
return {
workspaceId,
repos: [],
projects: [],
handoffs: [],
};
},
subscribeWorkbench(): () => void {
return () => {};
},
} as unknown as BackendClient;
const client = createHandoffWorkbenchClient({
mode: "remote",
backend,
workspaceId: "remote-ws",
});
await client.pushHandoff({ handoffId: "handoff-123" });
expect(actions).toEqual([
{
workspaceId: "remote-ws",
handoffId: "handoff-123",
action: "push",
},
]);
expect(snapshotReads).toBe(1);
});
});

View file

@ -1,5 +1,5 @@
{
"name": "@openhandoff/frontend-errors",
"name": "@sandbox-agent/factory-frontend-errors",
"version": "0.1.0",
"private": true,
"type": "module",

View file

@ -6,8 +6,8 @@ interface FrontendErrorCollectorGlobal {
declare global {
interface Window {
__OPENHANDOFF_FRONTEND_ERROR_COLLECTOR__?: FrontendErrorCollectorGlobal;
__OPENHANDOFF_FRONTEND_ERROR_CONTEXT__?: FrontendErrorContext;
__FACTORY_FRONTEND_ERROR_COLLECTOR__?: FrontendErrorCollectorGlobal;
__FACTORY_FRONTEND_ERROR_CONTEXT__?: FrontendErrorContext;
}
}
@ -17,11 +17,11 @@ export function setFrontendErrorContext(context: FrontendErrorContext): void {
}
const nextContext = sanitizeContext(context);
window.__OPENHANDOFF_FRONTEND_ERROR_CONTEXT__ = {
...(window.__OPENHANDOFF_FRONTEND_ERROR_CONTEXT__ ?? {}),
window.__FACTORY_FRONTEND_ERROR_CONTEXT__ = {
...(window.__FACTORY_FRONTEND_ERROR_CONTEXT__ ?? {}),
...nextContext,
};
window.__OPENHANDOFF_FRONTEND_ERROR_COLLECTOR__?.setContext(nextContext);
window.__FACTORY_FRONTEND_ERROR_COLLECTOR__?.setContext(nextContext);
}
function sanitizeContext(input: FrontendErrorContext): FrontendErrorContext {

View file

@ -4,8 +4,8 @@ import { dirname, join, resolve } from "node:path";
import { Hono } from "hono";
import type { FrontendErrorContext, FrontendErrorKind, FrontendErrorLogEvent } from "./types.js";
const DEFAULT_RELATIVE_LOG_PATH = ".openhandoff/logs/frontend-errors.ndjson";
const DEFAULT_REPORTER = "openhandoff-frontend";
const DEFAULT_RELATIVE_LOG_PATH = ".sandbox-agent-factory/logs/frontend-errors.ndjson";
const DEFAULT_REPORTER = "sandbox-agent-factory";
const MAX_FIELD_LENGTH = 12_000;
export interface FrontendErrorCollectorRouterOptions {

View file

@ -1,6 +1,6 @@
import type { FrontendErrorCollectorScriptOptions } from "./types.js";
const DEFAULT_REPORTER = "openhandoff-frontend";
const DEFAULT_REPORTER = "sandbox-agent-factory";
export function createFrontendErrorCollectorScript(
options: FrontendErrorCollectorScriptOptions
@ -17,13 +17,13 @@ export function createFrontendErrorCollectorScript(
return;
}
if (window.__OPENHANDOFF_FRONTEND_ERROR_COLLECTOR__) {
if (window.__FACTORY_FRONTEND_ERROR_COLLECTOR__) {
return;
}
var config = ${JSON.stringify(config)};
var sharedContext = window.__OPENHANDOFF_FRONTEND_ERROR_CONTEXT__ || {};
window.__OPENHANDOFF_FRONTEND_ERROR_CONTEXT__ = sharedContext;
var sharedContext = window.__FACTORY_FRONTEND_ERROR_CONTEXT__ || {};
window.__FACTORY_FRONTEND_ERROR_CONTEXT__ = sharedContext;
function now() {
return Date.now();
@ -124,7 +124,7 @@ export function createFrontendErrorCollectorScript(
});
}
window.__OPENHANDOFF_FRONTEND_ERROR_COLLECTOR__ = {
window.__FACTORY_FRONTEND_ERROR_COLLECTOR__ = {
setContext: function (nextContext) {
if (!nextContext || typeof nextContext !== "object") {
return;

View file

@ -4,7 +4,7 @@ import type { Plugin } from "vite";
import { createFrontendErrorCollectorRouter, defaultFrontendErrorLogPath } from "./router.js";
import { createFrontendErrorCollectorScript } from "./script.js";
const DEFAULT_MOUNT_PATH = "/__openhandoff/frontend-errors";
const DEFAULT_MOUNT_PATH = "/__factory/frontend-errors";
const DEFAULT_EVENT_PATH = "/events";
export interface FrontendErrorCollectorVitePluginOptions {
@ -20,7 +20,7 @@ export function frontendErrorCollectorVitePlugin(
): Plugin {
const mountPath = normalizePath(options.mountPath ?? DEFAULT_MOUNT_PATH);
const logFilePath = options.logFilePath ?? defaultFrontendErrorLogPath(process.cwd());
const reporter = options.reporter ?? "openhandoff-vite";
const reporter = options.reporter ?? "factory-vite";
const endpoint = `${mountPath}${DEFAULT_EVENT_PATH}`;
const router = createFrontendErrorCollectorRouter({
@ -31,7 +31,7 @@ export function frontendErrorCollectorVitePlugin(
const listener = getRequestListener(mountApp.fetch);
return {
name: "openhandoff:frontend-error-collector",
name: "factory:frontend-error-collector",
apply: "serve",
transformIndexHtml(html) {
return {

View file

@ -47,9 +47,9 @@ describe("frontend error collector router", () => {
describe("frontend error collector script", () => {
test("embeds configured endpoint", () => {
const script = createFrontendErrorCollectorScript({
endpoint: "/__openhandoff/frontend-errors/events",
endpoint: "/__factory/frontend-errors/events",
});
expect(script).toContain("/__openhandoff/frontend-errors/events");
expect(script).toContain("/__factory/frontend-errors/events");
expect(script).toContain("window.addEventListener(\"error\"");
});
});

View file

@ -10,7 +10,7 @@
</script>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenHandoff</title>
<title>Sandbox Agent Factory</title>
</head>
<body>
<div id="root"></div>

View file

@ -1,5 +1,5 @@
{
"name": "@openhandoff/frontend",
"name": "@sandbox-agent/factory-frontend",
"version": "0.1.0",
"private": true,
"type": "module",
@ -10,9 +10,9 @@
"test": "vitest run"
},
"dependencies": {
"@openhandoff/client": "workspace:*",
"@openhandoff/frontend-errors": "workspace:*",
"@openhandoff/shared": "workspace:*",
"@sandbox-agent/factory-client": "workspace:*",
"@sandbox-agent/factory-frontend-errors": "workspace:*",
"@sandbox-agent/factory-shared": "workspace:*",
"@tanstack/react-query": "^5.85.5",
"@tanstack/react-router": "^1.132.23",
"baseui": "^16.1.1",

View file

@ -1,5 +1,5 @@
import { useEffect } from "react";
import { setFrontendErrorContext } from "@openhandoff/frontend-errors/client";
import { useEffect, useSyncExternalStore } from "react";
import { setFrontendErrorContext } from "@sandbox-agent/factory-frontend-errors/client";
import {
Navigate,
Outlet,
@ -10,7 +10,7 @@ import {
} from "@tanstack/react-router";
import { MockLayout } from "../components/mock-layout";
import { defaultWorkspaceId } from "../lib/env";
import { handoffWorkbenchClient } from "../lib/workbench";
import { getHandoffWorkbenchClient, resolveRepoRouteHandoffId } from "../lib/workbench";
const rootRoute = createRootRoute({
component: RootLayout,
@ -74,18 +74,27 @@ function WorkspaceLayoutRoute() {
function WorkspaceRoute() {
const { workspaceId } = workspaceRoute.useParams();
const client = getHandoffWorkbenchClient(workspaceId);
useEffect(() => {
setFrontendErrorContext({
workspaceId,
handoffId: undefined,
});
}, [workspaceId]);
return <MockLayout workspaceId={workspaceId} selectedHandoffId={null} selectedSessionId={null} />;
return (
<MockLayout
client={client}
workspaceId={workspaceId}
selectedHandoffId={null}
selectedSessionId={null}
/>
);
}
function HandoffRoute() {
const { workspaceId, handoffId } = handoffRoute.useParams();
const { sessionId } = handoffRoute.useSearch();
const client = getHandoffWorkbenchClient(workspaceId);
useEffect(() => {
setFrontendErrorContext({
workspaceId,
@ -93,11 +102,24 @@ function HandoffRoute() {
repoId: undefined,
});
}, [handoffId, workspaceId]);
return <MockLayout workspaceId={workspaceId} selectedHandoffId={handoffId} selectedSessionId={sessionId ?? null} />;
return (
<MockLayout
client={client}
workspaceId={workspaceId}
selectedHandoffId={handoffId}
selectedSessionId={sessionId ?? null}
/>
);
}
function RepoRoute() {
const { workspaceId, repoId } = repoRoute.useParams();
const client = getHandoffWorkbenchClient(workspaceId);
const snapshot = useSyncExternalStore(
client.subscribe.bind(client),
client.getSnapshot.bind(client),
client.getSnapshot.bind(client),
);
useEffect(() => {
setFrontendErrorContext({
workspaceId,
@ -105,9 +127,7 @@ function RepoRoute() {
repoId,
});
}, [repoId, workspaceId]);
const activeHandoffId = handoffWorkbenchClient.getSnapshot().handoffs.find(
(handoff) => handoff.repoId === repoId,
)?.id;
const activeHandoffId = resolveRepoRouteHandoffId(snapshot, repoId);
if (!activeHandoffId) {
return (
<Navigate

View file

@ -1,4 +1,5 @@
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { HandoffWorkbenchClient } from "@sandbox-agent/factory-client";
import { useNavigate } from "@tanstack/react-router";
import { DiffContent } from "./mock-layout/diff-content";
@ -22,7 +23,6 @@ import {
type Message,
type ModelId,
} from "./mock-layout/view-model";
import { handoffWorkbenchClient } from "../lib/workbench";
function firstAgentTabId(handoff: Handoff): string | null {
return handoff.tabs[0]?.id ?? null;
@ -63,6 +63,7 @@ function sanitizeActiveTabId(
}
const TranscriptPanel = memo(function TranscriptPanel({
client,
handoff,
activeTabId,
lastAgentTabId,
@ -72,6 +73,7 @@ const TranscriptPanel = memo(function TranscriptPanel({
onSetLastAgentTabId,
onSetOpenDiffs,
}: {
client: HandoffWorkbenchClient;
handoff: Handoff;
activeTabId: string | null;
lastAgentTabId: string | null;
@ -172,12 +174,12 @@ const TranscriptPanel = memo(function TranscriptPanel({
return;
}
void handoffWorkbenchClient.setSessionUnread({
void client.setSessionUnread({
handoffId: handoff.id,
tabId: activeAgentTab.id,
unread: false,
});
}, [activeAgentTab?.id, activeAgentTab?.unread, handoff.id]);
}, [activeAgentTab?.id, activeAgentTab?.unread, client, handoff.id]);
const startEditingField = useCallback((field: "title" | "branch", value: string) => {
setEditingField(field);
@ -197,13 +199,13 @@ const TranscriptPanel = memo(function TranscriptPanel({
}
if (field === "title") {
void handoffWorkbenchClient.renameHandoff({ handoffId: handoff.id, value });
void client.renameHandoff({ handoffId: handoff.id, value });
} else {
void handoffWorkbenchClient.renameBranch({ handoffId: handoff.id, value });
void client.renameBranch({ handoffId: handoff.id, value });
}
setEditingField(null);
},
[editValue, handoff.id],
[client, editValue, handoff.id],
);
const updateDraft = useCallback(
@ -212,14 +214,14 @@ const TranscriptPanel = memo(function TranscriptPanel({
return;
}
void handoffWorkbenchClient.updateDraft({
void client.updateDraft({
handoffId: handoff.id,
tabId: promptTab.id,
text: nextText,
attachments: nextAttachments,
});
},
[handoff.id, promptTab],
[client, handoff.id, promptTab],
);
const sendMessage = useCallback(() => {
@ -230,24 +232,24 @@ const TranscriptPanel = memo(function TranscriptPanel({
onSetActiveTabId(promptTab.id);
onSetLastAgentTabId(promptTab.id);
void handoffWorkbenchClient.sendMessage({
void client.sendMessage({
handoffId: handoff.id,
tabId: promptTab.id,
text,
attachments,
});
}, [attachments, draft, handoff.id, onSetActiveTabId, onSetLastAgentTabId, promptTab]);
}, [attachments, client, draft, handoff.id, onSetActiveTabId, onSetLastAgentTabId, promptTab]);
const stopAgent = useCallback(() => {
if (!promptTab) {
return;
}
void handoffWorkbenchClient.stopAgent({
void client.stopAgent({
handoffId: handoff.id,
tabId: promptTab.id,
});
}, [handoff.id, promptTab]);
}, [client, handoff.id, promptTab]);
const switchTab = useCallback(
(tabId: string) => {
@ -257,7 +259,7 @@ const TranscriptPanel = memo(function TranscriptPanel({
onSetLastAgentTabId(tabId);
const tab = handoff.tabs.find((candidate) => candidate.id === tabId);
if (tab?.unread) {
void handoffWorkbenchClient.setSessionUnread({
void client.setSessionUnread({
handoffId: handoff.id,
tabId,
unread: false,
@ -266,14 +268,14 @@ const TranscriptPanel = memo(function TranscriptPanel({
onSyncRouteSession(handoff.id, tabId);
}
},
[handoff.id, handoff.tabs, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession],
[client, handoff.id, handoff.tabs, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession],
);
const setTabUnread = useCallback(
(tabId: string, unread: boolean) => {
void handoffWorkbenchClient.setSessionUnread({ handoffId: handoff.id, tabId, unread });
void client.setSessionUnread({ handoffId: handoff.id, tabId, unread });
},
[handoff.id],
[client, handoff.id],
);
const startRenamingTab = useCallback(
@ -305,13 +307,13 @@ const TranscriptPanel = memo(function TranscriptPanel({
return;
}
void handoffWorkbenchClient.renameSession({
void client.renameSession({
handoffId: handoff.id,
tabId: editingSessionTabId,
title: trimmedName,
});
cancelTabRename();
}, [cancelTabRename, editingSessionName, editingSessionTabId, handoff.id]);
}, [cancelTabRename, client, editingSessionName, editingSessionTabId, handoff.id]);
const closeTab = useCallback(
(tabId: string) => {
@ -326,9 +328,9 @@ const TranscriptPanel = memo(function TranscriptPanel({
}
onSyncRouteSession(handoff.id, nextTabId);
void handoffWorkbenchClient.closeTab({ handoffId: handoff.id, tabId });
void client.closeTab({ handoffId: handoff.id, tabId });
},
[activeTabId, handoff.id, handoff.tabs, lastAgentTabId, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession],
[activeTabId, client, handoff.id, handoff.tabs, lastAgentTabId, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession],
);
const closeDiffTab = useCallback(
@ -346,12 +348,12 @@ const TranscriptPanel = memo(function TranscriptPanel({
const addTab = useCallback(() => {
void (async () => {
const { tabId } = await handoffWorkbenchClient.addTab({ handoffId: handoff.id });
const { tabId } = await client.addTab({ handoffId: handoff.id });
onSetLastAgentTabId(tabId);
onSetActiveTabId(tabId);
onSyncRouteSession(handoff.id, tabId);
})();
}, [handoff.id, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession]);
}, [client, handoff.id, onSetActiveTabId, onSetLastAgentTabId, onSyncRouteSession]);
const changeModel = useCallback(
(model: ModelId) => {
@ -359,13 +361,13 @@ const TranscriptPanel = memo(function TranscriptPanel({
throw new Error(`Unable to change model for handoff ${handoff.id} without an active prompt tab`);
}
void handoffWorkbenchClient.changeModel({
void client.changeModel({
handoffId: handoff.id,
tabId: promptTab.id,
model,
});
},
[handoff.id, promptTab],
[client, handoff.id, promptTab],
);
const addAttachment = useCallback(
@ -551,17 +553,18 @@ const TranscriptPanel = memo(function TranscriptPanel({
});
interface MockLayoutProps {
client: HandoffWorkbenchClient;
workspaceId: string;
selectedHandoffId?: string | null;
selectedSessionId?: string | null;
}
export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }: MockLayoutProps) {
export function MockLayout({ client, workspaceId, selectedHandoffId, selectedSessionId }: MockLayoutProps) {
const navigate = useNavigate();
const viewModel = useSyncExternalStore(
handoffWorkbenchClient.subscribe.bind(handoffWorkbenchClient),
handoffWorkbenchClient.getSnapshot.bind(handoffWorkbenchClient),
handoffWorkbenchClient.getSnapshot.bind(handoffWorkbenchClient),
client.subscribe.bind(client),
client.getSnapshot.bind(client),
client.getSnapshot.bind(client),
);
const handoffs = viewModel.handoffs ?? [];
const projects = viewModel.projects ?? [];
@ -668,7 +671,7 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
const title = window.prompt("Optional handoff title", "")?.trim() || undefined;
const branch = window.prompt("Optional branch name", "")?.trim() || undefined;
const { handoffId, tabId } = await handoffWorkbenchClient.createHandoff({
const { handoffId, tabId } = await client.createHandoff({
repoId,
task,
model: "gpt-4o",
@ -684,7 +687,7 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
search: { sessionId: tabId ?? undefined },
});
})();
}, [activeHandoff?.repoId, navigate, viewModel.repos, workspaceId]);
}, [activeHandoff?.repoId, client, navigate, viewModel.repos, workspaceId]);
const openDiffTab = useCallback(
(path: string) => {
@ -726,8 +729,8 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
);
const markHandoffUnread = useCallback((id: string) => {
void handoffWorkbenchClient.markHandoffUnread({ handoffId: id });
}, []);
void client.markHandoffUnread({ handoffId: id });
}, [client]);
const renameHandoff = useCallback(
(id: string) => {
@ -746,9 +749,9 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
return;
}
void handoffWorkbenchClient.renameHandoff({ handoffId: id, value: trimmedTitle });
void client.renameHandoff({ handoffId: id, value: trimmedTitle });
},
[handoffs],
[client, handoffs],
);
const renameBranch = useCallback(
@ -768,24 +771,31 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
return;
}
void handoffWorkbenchClient.renameBranch({ handoffId: id, value: trimmedBranch });
void client.renameBranch({ handoffId: id, value: trimmedBranch });
},
[handoffs],
[client, handoffs],
);
const archiveHandoff = useCallback(() => {
if (!activeHandoff) {
throw new Error("Cannot archive without an active handoff");
}
void handoffWorkbenchClient.archiveHandoff({ handoffId: activeHandoff.id });
}, [activeHandoff]);
void client.archiveHandoff({ handoffId: activeHandoff.id });
}, [activeHandoff, client]);
const publishPr = useCallback(() => {
if (!activeHandoff) {
throw new Error("Cannot publish PR without an active handoff");
}
void handoffWorkbenchClient.publishPr({ handoffId: activeHandoff.id });
}, [activeHandoff]);
void client.publishPr({ handoffId: activeHandoff.id });
}, [activeHandoff, client]);
const pushHandoff = useCallback(() => {
if (!activeHandoff) {
throw new Error("Cannot push without an active handoff");
}
void client.pushHandoff({ handoffId: activeHandoff.id });
}, [activeHandoff, client]);
const revertFile = useCallback(
(path: string) => {
@ -804,18 +814,20 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
: current[activeHandoff.id] ?? null,
}));
void handoffWorkbenchClient.revertFile({
void client.revertFile({
handoffId: activeHandoff.id,
path,
});
},
[activeHandoff, lastAgentTabIdByHandoff],
[activeHandoff, client, lastAgentTabIdByHandoff],
);
if (!activeHandoff) {
return (
<Shell>
<Sidebar
workspaceId={workspaceId}
repoCount={viewModel.repos.length}
projects={projects}
activeId=""
onSelect={selectHandoff}
@ -879,6 +891,8 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
return (
<Shell>
<Sidebar
workspaceId={workspaceId}
repoCount={viewModel.repos.length}
projects={projects}
activeId={activeHandoff.id}
onSelect={selectHandoff}
@ -888,6 +902,7 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
onRenameBranch={renameBranch}
/>
<TranscriptPanel
client={client}
handoff={activeHandoff}
activeTabId={activeTabId}
lastAgentTabId={lastAgentTabId}
@ -908,6 +923,7 @@ export function MockLayout({ workspaceId, selectedHandoffId, selectedSessionId }
activeTabId={activeTabId}
onOpenDiff={openDiffTab}
onArchive={archiveHandoff}
onPush={pushHandoff}
onRevertFile={revertFile}
onPublishPr={publishPr}
/>

View file

@ -15,6 +15,49 @@ import {
import { type ContextMenuItem, ContextMenuOverlay, PanelHeaderBar, SPanel, ScrollBody, useContextMenu } from "./ui";
import { type FileTreeNode, type Handoff, diffTabId } from "./view-model";
const StatusCard = memo(function StatusCard({
label,
value,
mono = false,
}: {
label: string;
value: string;
mono?: boolean;
}) {
const [css, theme] = useStyletron();
return (
<div
className={css({
padding: "10px 12px",
borderRadius: "8px",
backgroundColor: theme.colors.backgroundSecondary,
border: `1px solid ${theme.colors.borderOpaque}`,
display: "flex",
flexDirection: "column",
gap: "4px",
})}
>
<LabelSmall color={theme.colors.contentTertiary} $style={{ fontSize: "10px", fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase" }}>
{label}
</LabelSmall>
<div
className={css({
color: theme.colors.contentPrimary,
fontSize: "12px",
fontWeight: 600,
fontFamily: mono ? '"IBM Plex Mono", monospace' : undefined,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
})}
>
{value}
</div>
</div>
);
});
const FileTree = memo(function FileTree({
nodes,
depth,
@ -106,6 +149,7 @@ export const RightSidebar = memo(function RightSidebar({
activeTabId,
onOpenDiff,
onArchive,
onPush,
onRevertFile,
onPublishPr,
}: {
@ -113,6 +157,7 @@ export const RightSidebar = memo(function RightSidebar({
activeTabId: string | null;
onOpenDiff: (path: string) => void;
onArchive: () => void;
onPush: () => void;
onRevertFile: (path: string) => void;
onPublishPr: () => void;
}) {
@ -121,7 +166,12 @@ export const RightSidebar = memo(function RightSidebar({
const contextMenu = useContextMenu();
const changedPaths = useMemo(() => new Set(handoff.fileChanges.map((file) => file.path)), [handoff.fileChanges]);
const isTerminal = handoff.status === "archived";
const canPush = !isTerminal && Boolean(handoff.branch);
const pullRequestUrl = handoff.pullRequest != null ? `https://github.com/${handoff.repoName}/pull/${handoff.pullRequest.number}` : null;
const pullRequestStatus =
handoff.pullRequest == null
? "Not published"
: `#${handoff.pullRequest.number} ${handoff.pullRequest.status === "draft" ? "Draft" : "Ready"}`;
const copyFilePath = useCallback(async (path: string) => {
try {
@ -183,6 +233,7 @@ export const RightSidebar = memo(function RightSidebar({
{pullRequestUrl ? "Open PR" : "Publish PR"}
</button>
<button
onClick={canPush ? onPush : undefined}
className={css({
all: "unset",
display: "flex",
@ -192,8 +243,9 @@ export const RightSidebar = memo(function RightSidebar({
borderRadius: "8px",
fontSize: "12px",
fontWeight: 500,
color: "#e4e4e7",
cursor: "pointer",
color: canPush ? "#e4e4e7" : theme.colors.contentTertiary,
cursor: canPush ? "pointer" : "not-allowed",
opacity: canPush ? 1 : 0.5,
transition: "all 200ms ease",
":hover": { backgroundColor: "rgba(255, 255, 255, 0.06)", color: "#ffffff" },
})}
@ -303,6 +355,10 @@ export const RightSidebar = memo(function RightSidebar({
</div>
<ScrollBody>
<div className={css({ padding: "12px 14px 0", display: "grid", gap: "8px" })}>
<StatusCard label="Branch" value={handoff.branch ?? "Not created"} mono />
<StatusCard label="Pull Request" value={pullRequestStatus} />
</div>
{rightTab === "changes" ? (
<div className={css({ padding: "10px 14px", display: "flex", flexDirection: "column", gap: "2px" })}>
{handoff.fileChanges.length === 0 ? (

View file

@ -14,6 +14,8 @@ import {
} from "./ui";
export const Sidebar = memo(function Sidebar({
workspaceId,
repoCount,
projects,
activeId,
onSelect,
@ -22,6 +24,8 @@ export const Sidebar = memo(function Sidebar({
onRenameHandoff,
onRenameBranch,
}: {
workspaceId: string;
repoCount: number;
projects: ProjectSection[];
activeId: string;
onSelect: (id: string) => void;
@ -37,11 +41,17 @@ export const Sidebar = memo(function Sidebar({
return (
<SPanel>
<PanelHeaderBar>
<LabelSmall color={theme.colors.contentPrimary} $style={{ fontWeight: 600, flex: 1, fontSize: "13px" }}>
Handoffs
</LabelSmall>
<div className={css({ flex: 1, minWidth: 0 })}>
<LabelSmall color={theme.colors.contentPrimary} $style={{ fontWeight: 600, fontSize: "13px" }}>
{workspaceId}
</LabelSmall>
<LabelXSmall color={theme.colors.contentTertiary}>
{repoCount} {repoCount === 1 ? "repo" : "repos"}
</LabelXSmall>
</div>
<button
onClick={onCreate}
aria-label="Create handoff"
className={css({
all: "unset",
width: "24px",
@ -92,10 +102,22 @@ export const Sidebar = memo(function Sidebar({
{project.label}
</LabelSmall>
<LabelXSmall color={theme.colors.contentTertiary}>
{formatRelativeAge(project.updatedAtMs)}
{project.updatedAtMs > 0 ? formatRelativeAge(project.updatedAtMs) : "No handoffs"}
</LabelXSmall>
</div>
{project.handoffs.length === 0 ? (
<div
className={css({
padding: "0 12px 10px 34px",
color: theme.colors.contentTertiary,
fontSize: "12px",
})}
>
No handoffs yet
</div>
) : null}
{project.handoffs.slice(0, visibleCount).map((handoff) => {
const isActive = handoff.id === activeId;
const isDim = handoff.status === "archived";

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { WorkbenchAgentTab } from "@openhandoff/shared";
import type { WorkbenchAgentTab } from "@sandbox-agent/factory-shared";
import { buildDisplayMessages } from "./view-model";
function makeTab(transcript: WorkbenchAgentTab["transcript"]): WorkbenchAgentTab {

View file

@ -12,7 +12,7 @@ import type {
WorkbenchParsedDiffLine as ParsedDiffLine,
WorkbenchProjectSection as ProjectSection,
WorkbenchTranscriptEvent as TranscriptEvent,
} from "@openhandoff/shared";
} from "@sandbox-agent/factory-shared";
import { extractEventText } from "../../features/sessions/model";
export type { ProjectSection };

View file

@ -1,6 +1,7 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import type { AgentType, HandoffRecord, HandoffSummary, RepoBranchRecord, RepoOverview, RepoStackAction } from "@openhandoff/shared";
import { groupHandoffStatus, type SandboxSessionEventRecord } from "@openhandoff/client";
import type { AgentType, HandoffRecord, HandoffSummary, RepoBranchRecord, RepoOverview, RepoStackAction } from "@sandbox-agent/factory-shared";
import type { SandboxSessionEventRecord } from "@sandbox-agent/factory-client";
import { groupHandoffStatus } from "@sandbox-agent/factory-client/view-model";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Link, useNavigate } from "@tanstack/react-router";
import { Button } from "baseui/button";

View file

@ -0,0 +1,7 @@
declare module "@sandbox-agent/factory-client/view-model" {
export {
HANDOFF_STATUS_GROUPS,
groupHandoffStatus,
} from "@sandbox-agent/factory-client";
export type { HandoffStatusGroup } from "@sandbox-agent/factory-client";
}

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { HandoffRecord } from "@openhandoff/shared";
import type { HandoffRecord } from "@sandbox-agent/factory-shared";
import { formatDiffStat, groupHandoffsByRepo } from "./model";
const base: HandoffRecord = {

View file

@ -1,4 +1,4 @@
import type { HandoffRecord } from "@openhandoff/shared";
import type { HandoffRecord } from "@sandbox-agent/factory-shared";
export interface RepoGroup {
repoId: string;

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { SandboxSessionRecord } from "@openhandoff/client";
import type { SandboxSessionRecord } from "@sandbox-agent/factory-client";
import { buildTranscript, extractEventText, resolveSessionSelection } from "./model";
describe("extractEventText", () => {

View file

@ -1,5 +1,5 @@
import type { SandboxSessionEventRecord } from "@openhandoff/client";
import type { SandboxSessionRecord } from "@openhandoff/client";
import type { SandboxSessionEventRecord } from "@sandbox-agent/factory-client";
import type { SandboxSessionRecord } from "@sandbox-agent/factory-client";
function fromPromptArray(value: unknown): string | null {
if (!Array.isArray(value)) {

View file

@ -1,4 +1,4 @@
import { createBackendClient } from "@openhandoff/client";
import { createBackendClient } from "@sandbox-agent/factory-client/backend";
import { backendEndpoint, defaultWorkspaceId } from "./env";
export const backendClient = createBackendClient({

View file

@ -6,7 +6,7 @@ function resolveDefaultBackendEndpoint(): string {
}
type FrontendImportMetaEnv = ImportMetaEnv & {
OPENHANDOFF_FRONTEND_CLIENT_MODE?: string;
FACTORY_FRONTEND_CLIENT_MODE?: string;
};
const frontendEnv = import.meta.env as FrontendImportMetaEnv;
@ -17,7 +17,7 @@ export const backendEndpoint =
export const defaultWorkspaceId = import.meta.env.VITE_HF_WORKSPACE?.trim() || "default";
function resolveFrontendClientMode(): "mock" | "remote" {
const raw = frontendEnv.OPENHANDOFF_FRONTEND_CLIENT_MODE?.trim().toLowerCase();
const raw = frontendEnv.FACTORY_FRONTEND_CLIENT_MODE?.trim().toLowerCase();
if (raw === "mock") {
return "mock";
}
@ -25,7 +25,7 @@ function resolveFrontendClientMode(): "mock" | "remote" {
return "remote";
}
throw new Error(
`Unsupported OPENHANDOFF_FRONTEND_CLIENT_MODE value "${frontendEnv.OPENHANDOFF_FRONTEND_CLIENT_MODE}". Expected "mock" or "remote".`,
`Unsupported FACTORY_FRONTEND_CLIENT_MODE value "${frontendEnv.FACTORY_FRONTEND_CLIENT_MODE}". Expected "mock" or "remote".`,
);
}

View file

@ -0,0 +1,8 @@
import type { HandoffWorkbenchSnapshot } from "@sandbox-agent/factory-shared";
export function resolveRepoRouteHandoffId(
snapshot: HandoffWorkbenchSnapshot,
repoId: string,
): string | null {
return snapshot.handoffs.find((handoff) => handoff.repoId === repoId)?.id ?? null;
}

View file

@ -0,0 +1,11 @@
import {
createHandoffWorkbenchClient,
type HandoffWorkbenchClient,
} from "@sandbox-agent/factory-client/workbench";
export function createWorkbenchRuntimeClient(workspaceId: string): HandoffWorkbenchClient {
return createHandoffWorkbenchClient({
mode: "mock",
workspaceId,
});
}

View file

@ -0,0 +1,13 @@
import {
createHandoffWorkbenchClient,
type HandoffWorkbenchClient,
} from "@sandbox-agent/factory-client/workbench";
import { backendClient } from "./backend";
export function createWorkbenchRuntimeClient(workspaceId: string): HandoffWorkbenchClient {
return createHandoffWorkbenchClient({
mode: "remote",
backend: backendClient,
workspaceId,
});
}

View file

@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import type { HandoffWorkbenchSnapshot } from "@sandbox-agent/factory-shared";
import { resolveRepoRouteHandoffId } from "./workbench-routing";
const snapshot: HandoffWorkbenchSnapshot = {
workspaceId: "default",
repos: [
{ id: "repo-a", label: "acme/repo-a" },
{ id: "repo-b", label: "acme/repo-b" },
],
projects: [],
handoffs: [
{
id: "handoff-a",
repoId: "repo-a",
title: "Alpha",
status: "idle",
repoName: "acme/repo-a",
updatedAtMs: 20,
branch: "feature/alpha",
pullRequest: null,
tabs: [],
fileChanges: [],
diffs: {},
fileTree: [],
},
],
};
describe("resolveRepoRouteHandoffId", () => {
it("finds the active handoff for a repo route", () => {
expect(resolveRepoRouteHandoffId(snapshot, "repo-a")).toBe("handoff-a");
});
it("returns null when a repo has no handoff yet", () => {
expect(resolveRepoRouteHandoffId(snapshot, "repo-b")).toBeNull();
});
});

View file

@ -1,9 +1,18 @@
import { createHandoffWorkbenchClient } from "@openhandoff/client";
import { backendClient } from "./backend";
import { defaultWorkspaceId, frontendClientMode } from "./env";
import type { HandoffWorkbenchClient } from "@sandbox-agent/factory-client/workbench";
import { createWorkbenchRuntimeClient } from "@workbench-runtime";
import { frontendClientMode } from "./env";
export { resolveRepoRouteHandoffId } from "./workbench-routing";
export const handoffWorkbenchClient = createHandoffWorkbenchClient({
mode: frontendClientMode,
backend: backendClient,
workspaceId: defaultWorkspaceId,
});
const workbenchClientCache = new Map<string, HandoffWorkbenchClient>();
export function getHandoffWorkbenchClient(workspaceId: string): HandoffWorkbenchClient {
const cacheKey = `${frontendClientMode}:${workspaceId}`;
const existing = workbenchClientCache.get(cacheKey);
if (existing) {
return existing;
}
const client = createWorkbenchRuntimeClient(workspaceId);
workbenchClientCache.set(cacheKey, client);
return client;
}

View file

@ -6,7 +6,11 @@
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"declaration": false,
"types": ["vite/client", "vitest/globals"]
"types": ["vite/client", "vitest/globals"],
"baseUrl": ".",
"paths": {
"@workbench-runtime": ["./src/lib/workbench-runtime.remote.ts"]
}
},
"include": ["src", "vite.config.ts", "vitest.config.ts"]
}

View file

@ -1,17 +1,31 @@
import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { frontendErrorCollectorVitePlugin } from "@openhandoff/frontend-errors/vite";
import { frontendErrorCollectorVitePlugin } from "@sandbox-agent/factory-frontend-errors/vite";
const backendProxyTarget = process.env.HF_BACKEND_HTTP?.trim() || "http://127.0.0.1:7741";
const cacheDir = process.env.HF_VITE_CACHE_DIR?.trim() || undefined;
const frontendClientMode = process.env.FACTORY_FRONTEND_CLIENT_MODE?.trim() || "remote";
export default defineConfig({
define: {
"import.meta.env.OPENHANDOFF_FRONTEND_CLIENT_MODE": JSON.stringify(
process.env.OPENHANDOFF_FRONTEND_CLIENT_MODE?.trim() || "remote",
"import.meta.env.FACTORY_FRONTEND_CLIENT_MODE": JSON.stringify(
frontendClientMode,
),
},
plugins: [react(), frontendErrorCollectorVitePlugin()],
cacheDir,
resolve: {
alias: {
"@workbench-runtime": fileURLToPath(
new URL(
frontendClientMode === "mock"
? "./src/lib/workbench-runtime.mock.ts"
: "./src/lib/workbench-runtime.remote.ts",
import.meta.url,
),
),
},
},
server: {
port: 4173,
proxy: {

View file

@ -1,5 +1,5 @@
{
"name": "@openhandoff/shared",
"name": "@sandbox-agent/factory-shared",
"version": "0.1.0",
"private": true,
"type": "module",

View file

@ -24,7 +24,7 @@ export const ConfigSchema = z.object({
backend: z.object({
host: z.string().default("127.0.0.1"),
port: z.number().int().min(1).max(65535).default(7741),
dbPath: z.string().default("~/.local/share/openhandoff/handoff.db"),
dbPath: z.string().default("~/.local/share/sandbox-agent-factory/handoff.db"),
opencode_poll_interval: z.number().default(2),
github_poll_interval: z.number().default(30),
backup_interval_secs: z.number().default(3600),
@ -32,7 +32,7 @@ export const ConfigSchema = z.object({
}).default({
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,

View file

@ -8,7 +8,7 @@ const cfg: AppConfig = ConfigSchema.parse({
backend: {
host: "127.0.0.1",
port: 7741,
dbPath: "~/.local/share/openhandoff/handoff.db",
dbPath: "~/.local/share/sandbox-agent-factory/handoff.db",
opencode_poll_interval: 2,
github_poll_interval: 30,
backup_interval_secs: 3600,