Files
fusion/packages/dashboard/app/__tests__/api-settings.test.ts
gsxdsm e9e63d8e0f consolidate/capacity: --strict was red on main (my #2621), 14 stale baselines, routines seeding a deleted column, worktrees-off audit (#2652)
Capacity unit consolidation. Three coherent themes, small commits
inside.

## Census before/after (`node scripts/lifecycle-column-census.mjs`)

| | before | after |
|---|---:|---:|
| triage column guards (the bar) | 10 | **10** |
| `--strict` on main | ❌ **RED** | ✅ green |
| baseline staleness | 14 files stale | **0** |

This branch does **not** move the triage bar — its remaining 10 are
moves.ts (dies with the flag), the dashboard cluster, and one deliberate
site. It fixes the instrument that measures the bar, plus a live defect
the comparison count cannot see.

---

## 1. `--strict` was RED on clean `origin/main`, and it was my fault

```
packages/dashboard/src/routes/register-task-workflow-routes.ts: 22 -> 23
```

My merged #2621 added a v1-IR pre-WIP fallback answering a greptile P1
and shipped no marker or baseline update, so the program's measuring
instrument has been failing on main since it landed.

Fixed **at the site** with a `DELIBERATE-LITERAL` marker, not by bumping
the baseline. That branch runs only when the IR declares no columns and
no nodes, so there is no role to resolve — `resolveLifecycleColumns`
returns nothing and the legacy pre-implementation ids are the only
pre-WIP signal that exists there. It is *unconvertible*, not unfinished;
the sibling `else` two lines down is the trait path for every IR that
can answer. A rise that is genuinely correct belongs where a reader will
see it.

## 2. The baseline was stale for 14 files — a hole, not cosmetics

A stale allowance lets converted guards return while the check stays
green. Measured gaps:

```
self-healing.ts          allows 126, tree has 111
executor.ts              allows 112, tree has 104
moves.ts                 allows  44, tree has  39
default-workflow-hooks   allows  25, tree has   7
mission-feature-sync     allows   5, tree has   0
MissionControlPanel      allows   4, tree has   0        (+8 more)
```

**Only two of the fourteen are mine.** The other twelve are
already-merged conversions by other workers where nobody re-recorded.
Re-recorded all fourteen here rather than waiting for twelve PRs,
because until it happens the ratchet is not holding the 779 it exists to
hold. Flagging it plainly: those drops are other people's work being
locked in, not mine being claimed.

## 3. Routines created tasks into the column U11 deleted

The routine editor's "Target Column" defaulted to `triage`. That value
is submitted as the create step's `taskColumn`, and an **explicit**
column bypasses the workflow entry-column resolution added for
column-less creates (#2589) — so every routine saved with the untouched
default seeded its tasks into a column the board does not declare.

Defaulting to `todo` would be the same mistake one column over: a custom
workflow declaring no `todo` is seeded into an undeclared column just as
surely, because an explicit column overrides entry resolution whatever
its value. So the default sends **nothing** and each workflow's own
intake resolution decides.

The `triage` **option** is removed too, not merely un-defaulted — fixing
the initializer alone left the operator able to pick the deleted column
one click away, and it was the option labelled "Planning", the name the
merged `todo` column now displays. Removing it retires that label
inversion as well.

Found by scanning **membership** forms rather than comparisons: the
comparison census cannot see a `?? "triage"` default, so no count showed
this and nobody was looking. Revert-proof — restoring the default fails
with *"the default must not name a column at all"*.

## 4. "Worktrees off is INERT" had one unaudited reader

The constraint was that `maxWorktrees` become genuinely inert, "not set
very high and not skipped by convention". `resolveWorktreeCapacityLimit`
returns `null` for that, and its unit tests can only prove the
**resolver** is right — they cannot see a second reader, which is the
only way the constraint breaks.

Audited every `maxWorktrees` read that bounds anything. **Exactly two:**
`scheduler.ts` (the admission gate, via the resolver, single call site,
optional gate snapshot) and `self-healing.ts`'s `enforceWorktreeCap` —
`(settings.maxWorktrees ?? 4) * 2`, a **raw** read.

The second is **not a bug** and is left alone: it bounds worktree
*directories on disk* and only removes *idle* ones. Worktrees still
exist in OFF mode, so that bound must keep applying or idle directories
accumulate unbounded. Recorded consequence: in OFF mode the number still
governs disk retention while gating no admission — an edge you scoped
out. The note says explicitly **not** to unify the two readers: routing
hygiene through the resolver returns `null` in OFF mode and silently
removes the disk bound, which is a leak dressed as a simplification.

New ratchet requires every file bounding on `maxWorktrees` to be named
with a reason, and rejects a **stale** allowlist entry. Proven by
injecting `active >= (settings.maxWorktrees ?? 4)` into
`hybrid-executor.ts`.

---

## Deliberately NOT included

- **My own census script.** #2633 landed the canonical one, and it is
better than mine — an AST classifier *plus* an independent text
classifier with `--compare`, and a baseline that fails on unrecorded
**drops** as well as rises. Mine only caught rises. I deleted mine
rather than ship a second measuring instrument; three copies of "strip
comments" is the drift shape this program keeps paying for, so the
worktree ratchet now imports #2633's `stripComments`.
- **My TaskContextMenu fix.** Superseded, and by a better answer: main's
`isPureIntakeColumn` (intake *without* hold) keeps the merged Planning
column shown and suppresses only a bare Ideas capture, which resolves
the exact hold-lane objection coderabbit raised against my version. I
briefly clobbered that merged work by checking my old file out
wholesale, caught it in the diff, and reverted.

## Verification

`pnpm lint` clean · core + dashboard `tsc` clean · census suite 23/23 ·
worktree ratchet 8/8 · RoutineEditor 49/49 ·
`routes-task-retry-planning-column` 16/16 · `lifecycle-column-census
--strict` exits 0.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---

## Added after review (all four greptile threads were real, and two of
them mattered)

**The routine fix was half a fix.** `routine-runner.ts:515` *and*
`cron-runner.ts:982` both did `column: (step.taskColumn as Column) ||
"triage"` **after** the step is read, so every routine — including ones
saved through the fixed editor — still created tasks into the deleted
column. Both now omit it.

**The advanced steps editor MANUFACTURED the defect.**
`ScheduleStepsEditor.tsx` had three `triage` defaults: the new-step
template (`:64`), the per-step initializer (`:95`), and the select still
offering it (`:344`). So the path I had *not* fixed produced the bug by
default, on fresh data. Template names no column; initializer coerces a
persisted `triage`; `triage` removed from the options; empty submits
`undefined`.

**Four pre-existing tests pinned the defect** and are rewritten to the
corrected invariant rather than appeased:

| test | asserted |
|---|---|
| `cron-runner`: "defaults column to triage when taskColumn is not set"
| `column: "triage"` |
| `ScheduleStepsEditor`: "adds a create-task step..." | `taskColumn`
toBe `"triage"` |
| `ScheduleStepsEditor`: "allows saving create-task step..." | the
legacy column is **resubmitted** |
| plus the explicit-column case added beside each, so the fix cannot
swallow a deliberate choice |

**The allowlist hole was the worst finding.** `AUDITED_BOUNDS` was keyed
by FILE, so every bounding expression in an allowlisted file was exempt
— a second raw bound in `scheduler.ts` stayed green, the one case that
ratchet exists for. Per-expression now, and making it so **immediately
surfaced a real second bound the file-level version was hiding**
(`maxWorktreesGate.used >= maxWorktreesGate.limit`, safe by construction
since the snapshot is `undefined` in OFF mode). Proven by injection.

## Found while re-reading my own deletion, not reported

A **rendered tooltip** still named a deleted cap. The "Queued to plan"
badge read *"planning starts when a concurrency slot frees up
(maxConcurrent / globalMaxConcurrent)"*. The cross-project cap is gone —
capacity is two numbers per project — so it told operators their
planning waited on a limiter they can no longer find a setting for.
Names the surviving dimension only now.

## Coding (Ideas): enforcing #2651 rather than repeating it

I took the unowned coding-ideas IR merge, concluded it must not be done,
then found **#2651 had already implemented, reverted and documented
exactly that** — with better grounding than my own argument. It added no
test, so nothing stops the next person reaching the same dead end.

So this ships their reasoning as a ratchet, not a second opinion: triage
discovery keys on the column's `autoTriage`, so a merged column is
either never scanned (cards sit on a bootstrap stub until the **capacity
hold** releases them, sending **unplanned** work into in-progress —
worse than stalling) or scanning wins and the manual gate is gone. Their
scope caveat is kept: `autoTriage` is a general trait field, so only
*this preset's* collapse is dead, not manual intake as a concept. The
registry does not reject the merged shape, which is why prose was not
enough.

## Verification (re-run)

`pnpm lint` clean · core + engine + dashboard-app `tsc` clean ·
`lifecycle-column-census --strict` exits 0 ("every file matches its
baseline exactly") · routine-runner 24/24 · cron-runner 156/156 ·
ScheduleStepsEditor 41/41 · RoutineEditor 49/49 · worktree +
coding-ideas 12/12. TaskCard has 2 failures **pre-existing on main** —
confirmed identical with my changes stashed.

---

## Bears directly on the closing bar: this PR already removes the
67-guard ratchet slack

Measured on current `origin/main` with the census itself:

```
tree total: 787   baseline total: 854   SLACK: 67

FILES ABOVE BASELINE (1):
   +1  packages/dashboard/src/routes/register-task-workflow-routes.ts  (22 -> 23)

FILES BELOW BASELINE: 13, totalling 68 unrecorded conversions
   -18  core/default-workflow-hooks.ts (25->7)   -15  engine/self-healing.ts (126->111)
    -8  engine/executor.ts (112->104)             -5  core/task-store/moves.ts (44->39)
    -5  engine/mission-feature-sync.ts (5->0)     -4  core/live-agent-count.ts (10->6)
```

**The slack is not regression — it is 13 files of merged conversions
nobody re-recorded**, against exactly **one** rise. This PR re-records
the baseline **854 → 782 across 140 files**, which closes it.

**And the "+3 that slipped in" is +1, and it is mine.**
`register-task-workflow-routes.ts 22 → 23` is the v1-IR pre-WIP fallback
my #2621 added; it is justified (that branch runs only when the IR
declares no columns or nodes, so there is no role to resolve) but it
shipped with no marker and no baseline update — which is why `--strict`
has been **red on main since it merged**. Fixed here at the site with a
`DELIBERATE-LITERAL` marker rather than by bumping the baseline, because
a rise that is genuinely correct belongs where a reader will see it.

Sequencing note for the auto-lowering change: if this lands first, that
work is purely the mechanism (auto-lower, or fail with tighten
instructions) rather than a cleanup, and the two re-records will not
collide in the same file.

Also worth carrying into that mechanism, from building the same guard
here: **`--update` must refuse to RAISE.** An earlier version of mine
wrote current counts verbatim, so a developer who added a literal and
ran the documented update command locked the regression in as the new
ceiling — the mirror of the high-water problem. Lowering can be
unattended; raising should be a hand edit with the reason recorded.

## Third piece of residue from my own deletion

`updateGlobalConcurrency` in the dashboard API client PUT to
`/api/global-concurrency`, a route removed when the machine-wide cap
went. Zero callers; the only reference was the `legacy.ts` barrel
re-export. Deleted both. `fetchGlobalConcurrency` **survives on
purpose** — the GET route remains and serves live utilization telemetry
to the footer and Command Center; nothing gates on it.

That is the third: after the second raw `maxWorktrees` reader and the
"Queued to plan" tooltip. A deletion is not finished when the
enforcement goes — the client, the label and the tooltip outlive it.

---

## Re-greened the dashboard API tests: 117 failures on main, ONE root
cause

These would have polluted the closing verification pass, and nobody
owned them.

`api()` builds headers via `new Headers(...)` and returns
`Object.fromEntries(headers.entries())` — and `Headers.entries()`
**lowercases every key**, so the object reaching `fetch` is
`content-type`, not `Content-Type`. `ab87d0d80` then added
`x-fusion-client: dashboard-ui` for run-audit attribution. Both changes
are correct; neither is visible at a call site, so **114 assertions
across 7 files** kept asserting the old shape and went red together.

Fixed by naming the shape **once** in `app/test/apiRequestHeaders.ts`
rather than patching 114 literals — restating a shared fact 114 times is
what made a two-line client change look like 117 failures. Deliberately
not a loose `objectContaining`: these tests are the only thing pinning
that the attribution header is sent *at all*.

**117 → 4.** The remaining 4 are unrelated pre-existing CSS failures
(`task-detail-modal-tablet-width` ×3, `space-token-defined` ×1) —
confirmed identical on clean main with my changes stashed.

### A gap this surfaced, recorded not papered over

Three routes failed in the *opposite* direction — they send the old
shape because they call `fetch()` **directly**, bypassing `api()`, so
they never get the attribution header. `client.ts` claims the opposite:

> "Applied once here rather than per-call so no future mutation route
has to remember it."

That does not hold for a route that bypasses the helper it is applied
in. **Measured in `app/api/`: 8 files make direct `fetch()` calls and 7
include mutations (POST/DELETE)** — among them `ai-sessions.ts`'s
DELETE, which is the same class as the four-delete incident the header
was added for. So the attribution fix has a hole in exactly its
motivating case.

Not fixed here: routing those onto `api()` is a behaviour change across
the API layer and belongs to its owner, not to a test re-green. Those
assertions use a separate `API_JSON_HEADERS_NO_ATTRIBUTION` constant so
the gap stays **visible** — if a route is later moved onto `api()`, its
test fails and points at the note explaining why.

---

## This branch takes the triage bar 10 → 5, and makes `--strict` green

`node scripts/lifecycle-column-census.mjs` on this branch reports
**triage 5**, against **10** on `origin/main`. The five removed are the
ScheduleStepsEditor template/initializer/option and the RoutineEditor
default/option — the automation paths that were creating tasks into the
deleted column.

**`--strict` was also RED on clean main, twice over, and both causes
were the same mistake:** a thorough written rationale the tool cannot
read, because the marker was not where the census looks. The census
reads a comparison node's **leading comments**; a `DELIBERATE-LITERAL`
in the JSDoc above the enclosing function or declaration does not reach
the comparison inside it.

| site | why it is legitimate | why the tool could not see it |
|---|---|---|
| `columnRoles.ts:80` `isHoldColumnRole` | degrades to `columnId ===
"todo"` only when a column has **no resolved traits** — identical in
kind to `LEGACY_PRE_IMPLEMENTATION_COLUMN_IDS` directly above, which
escapes counting only because a Set is a membership form | rationale
written, **no marker token** |
| `MissionControlPanel.tsx` ×3 | the SDLC funnel **alias table** — maps
`to-do`/`ready`/`review`/`shipped` onto one display stage with an
explicit `other` bucket, and nothing branches on it | marker in the
JSDoc; the comparisons are arrow bodies **inside the array literal**,
which it does not reach |

The second only surfaced because converting the `triage` stage to a Set
removed its count and exposed the siblings — red gate, justification
sitting three lines above, unreachable.

Both are markers, no behaviour change. Neither is a conversion
candidate: resolving the funnel table to traits would **drop the
non-column aliases it exists to accept**.

**For the auto-lowering work:** the marker-placement rule is now the
recurring trap — three instances, three different authors, including me.
A marker that does not register is indistinguishable from no marker, and
the failure mode is a red gate with a written explanation nobody can act
on. If the census accepted a marker anywhere in the enclosing
declaration's comments, none of the three would have happened.

Baseline re-recorded per the tool's own instruction ("Re-record the
baseline in the SAME PR that lowered the count").


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Task “Actions” menus no longer appear on bare cards in the Planning
column.
- Routines, scheduled tasks, and create-task steps now respect each
board’s configured workflow intake column instead of using a retired
default.
- Legacy tasks saved with the retired intake column are migrated to
automatic workflow resolution.
- Target-column selection now offers only “Automatic (workflow intake)”
and “Planning,” removing the obsolete option.
- Capacity/planning messaging and related UI tooltip text were
clarified; concurrency cap updates are managed per project.

- **Tests**
- Added/updated coverage for workflow intake resolution, create-task
target column behavior (including legacy coercion), capacity safeguards,
and API request consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 03:10:35 -07:00

1169 lines
40 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { API_JSON_HEADERS } from "../test/apiRequestHeaders";
import {
fetchTaskDetail,
uploadAttachment,
fetchAgentLogsWithMeta,
fetchAiSessions,
fetchAiSession,
deleteAiSession,
updateTask,
createTask,
connectPlanningStream,
connectSubtaskStream,
connectMissionInterviewStream,
assignTask,
fetchAgentTasks,
archiveTask,
unarchiveTask,
deleteTask,
ApiRequestError,
moveTask,
mergeTask,
retryTask,
duplicateTask,
pauseTask,
unpauseTask,
fetchAuthStatus,
loginProvider,
logoutProvider,
fetchModels,
addSteeringComment,
addTaskComment,
updateTaskComment,
deleteTaskComment,
fetchTaskComments,
fetchGitRemotes,
refineTask,
fetchBatchStatus,
fetchWorkspaces,
fetchWorkspaceFileList,
fetchWorkspaceFileContent,
saveWorkspaceFileContent,
deleteFile,
startPlanningStreaming,
startAgentOnboardingStreaming,
respondToAgentOnboarding,
retryAgentOnboardingSession,
stopAgentOnboardingGeneration,
cancelAgentOnboarding,
fetchTasks,
summarizeTitle,
fetchProjects,
registerProject,
unregisterProject,
fetchProjectHealth,
fetchActivityFeed,
pauseProject,
resumeProject,
fetchFirstRunStatus,
fetchGlobalConcurrency,
updateGlobalConcurrency,
fetchPiSettings,
updatePiSettings,
installPiPackage,
reinstallFusionPiPackage,
fetchPiExtensions,
updatePiExtensions,
fetchProjectTasks,
fetchProjectConfig,
fetchExecutorStats,
fetchAgentRunAudit,
fetchAgentRunTimeline,
streamChatResponse,
fetchMemoryBackendStatus,
type ProjectInfo,
type ProjectHealth,
type ActivityFeedEntry,
type FirstRunStatus,
type GlobalConcurrencyState,
type ExecutorStats,
type ExecutorState,
} from "../api";
import type { Task, TaskDetail, BatchStatusResponse, MergeResult } from "@fusion/core";
import { clearAuthToken } from "../auth";
const TASK_TOKEN_USAGE_FIXTURE = {
inputTokens: 1000,
outputTokens: 300,
cachedTokens: 125,
totalTokens: 1425,
firstUsedAt: "2026-04-24T08:00:00.000Z",
lastUsedAt: "2026-04-24T09:30:00.000Z",
};
const FAKE_DETAIL: TaskDetail = {
id: "FN-001",
description: "Test",
column: "in-progress",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
tokenUsage: TASK_TOKEN_USAGE_FIXTURE,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
prompt: "# FN-001",
};
function mockFetchResponse(
ok: boolean,
body: unknown,
status = ok ? 200 : 500,
contentType = "application/json"
) {
const bodyText = JSON.stringify(body);
return Promise.resolve({
ok,
status,
statusText: ok ? "OK" : "Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? contentType : null,
},
json: () => Promise.resolve(body),
text: () => Promise.resolve(bodyText),
} as unknown as Response);
}
beforeEach(() => {
clearAuthToken();
localStorage.removeItem("fn.authToken");
});
afterEach(() => {
clearAuthToken();
localStorage.removeItem("fn.authToken");
});
import {
fetchGitRemotesDetailed,
addGitRemote,
removeGitRemote,
renameGitRemote,
updateGitRemoteUrl,
} from "../api";
import { approvePlan, rejectPlan } from "../api";
import {
startAgentRun,
createAgent,
updateAgent,
fetchGitStatus,
fetchGitCommits,
fetchCommitDiff,
fetchAheadCommits,
fetchRemoteCommits,
fetchGitBranches,
fetchGitWorktrees,
createBranch,
checkoutBranch,
deleteBranch,
fetchRemote,
pullBranch,
pushBranch,
} from "../api";
import { startPlanning, respondToPlanning, cancelPlanning, createTaskFromPlanning } from "../api";
import type { PlanningQuestion, PlanningSummary } from "@fusion/core";
import { refineText, getRefineErrorMessage, REFINE_ERROR_MESSAGES, type RefinementType } from "../api";
function mockHtmlErrorResponse(status: number, htmlBody: string) {
return Promise.resolve({
ok: false,
status,
statusText: "Not Found",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "text/html" : null,
},
json: () => Promise.reject(new Error("JSON parse error")),
text: () => Promise.resolve(htmlBody),
} as unknown as Response);
}
const FAKE_PROJECT: ProjectInfo = {
id: "proj_abc123",
name: "Test Project",
path: "/path/to/project",
status: "active",
isolationMode: "in-process",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
lastActivityAt: "2026-01-01T00:00:00.000Z",
};
const FAKE_PROJECT_HEALTH: ProjectHealth = {
projectId: "proj_abc123",
status: "active",
activeTaskCount: 5,
inFlightAgentCount: 2,
lastActivityAt: "2026-01-01T00:00:00.000Z",
totalTasksCompleted: 100,
totalTasksFailed: 5,
averageTaskDurationMs: 600000,
updatedAt: "2026-01-01T00:00:00.000Z",
};
const FAKE_ACTIVITY_ENTRY: ActivityFeedEntry = {
id: "act_123",
timestamp: "2026-01-01T00:00:00.000Z",
type: "task:created",
projectId: "proj_abc123",
projectName: "Test Project",
taskId: "KB-001",
taskTitle: "Test Task",
details: "Task created",
};
function mockSchedulingFetchResponse(
ok: boolean,
body: unknown,
status = ok ? 200 : 500,
contentType = "application/json"
) {
const bodyText = JSON.stringify(body);
return Promise.resolve({
ok,
status,
statusText: ok ? "OK" : "Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? contentType : null,
},
json: () => Promise.resolve(body),
text: () => Promise.resolve(bodyText),
} as unknown as Response);
}
/**
* Settings API wrapper tests for FN-1712 (scope-split settings UX).
* These tests verify the API contract for:
* - fetchSettingsByScope: Returns { global, project } scoped settings
* - updateGlobalSettings: PUT /api/settings/global
* - updateSettings: PUT /api/settings (project scope)
* - fetchGlobalSettings: GET /api/settings/global
*/
describe("Settings API wrappers", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("fetchSettingsByScope", () => {
it("calls /api/settings/scopes with no query string when projectId is omitted", async () => {
const { fetchSettingsByScope } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ global: { themeMode: "dark" }, project: {} }),
text: () => Promise.resolve(JSON.stringify({ global: { themeMode: "dark" }, project: {} })),
} as unknown as Response);
await fetchSettingsByScope();
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/scopes", expect.objectContaining({
headers: API_JSON_HEADERS,
}));
// GET is the default method, so method should not be specified
const call = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(call[1].method).toBeUndefined();
});
it("calls /api/settings/scopes?projectId=proj_123 when projectId is provided", async () => {
const { fetchSettingsByScope } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ global: { themeMode: "dark" }, project: {} }),
text: () => Promise.resolve(JSON.stringify({ global: { themeMode: "dark" }, project: {} })),
} as unknown as Response);
await fetchSettingsByScope("proj_123");
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/scopes?projectId=proj_123", expect.objectContaining({
headers: API_JSON_HEADERS,
}));
// GET is the default method
const call = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(call[1].method).toBeUndefined();
});
it("returns the { global, project } shape", async () => {
const { fetchSettingsByScope } = await import("../api");
const mockResponse = {
global: { themeMode: "dark", defaultProvider: "anthropic", defaultModelId: "claude-sonnet-4-5" },
project: { planningProvider: "openai", planningModelId: "gpt-4o" },
};
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve(mockResponse),
text: () => Promise.resolve(JSON.stringify(mockResponse)),
} as unknown as Response);
const result = await fetchSettingsByScope();
expect(result).toHaveProperty("global");
expect(result).toHaveProperty("project");
expect(result.global.themeMode).toBe("dark");
expect(result.global.defaultProvider).toBe("anthropic");
expect(result.project.planningProvider).toBe("openai");
});
it("throws with server error message on failure", async () => {
const { fetchSettingsByScope } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
statusText: "Internal Server Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ error: "Database connection failed" }),
text: () => Promise.resolve(JSON.stringify({ error: "Database connection failed" })),
} as unknown as Response);
await expect(fetchSettingsByScope()).rejects.toThrow("Database connection failed");
});
});
describe("updateGlobalSettings", () => {
it("sends PUT to /api/settings/global with the provided payload", async () => {
const { updateGlobalSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ themeMode: "light" }),
text: () => Promise.resolve(JSON.stringify({ themeMode: "light" })),
} as unknown as Response);
await updateGlobalSettings({ themeMode: "light" });
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
const [url, options] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe("/api/settings/global");
expect(options.method).toBe("PUT");
expect(JSON.parse(options.body as string)).toEqual({ themeMode: "light" });
});
it("returns the settings object on success", async () => {
const { updateGlobalSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ themeMode: "light", defaultProvider: "anthropic" }),
text: () => Promise.resolve(JSON.stringify({ themeMode: "light", defaultProvider: "anthropic" })),
} as unknown as Response);
const result = await updateGlobalSettings({ defaultProvider: "anthropic" });
expect(result.themeMode).toBe("light");
expect(result.defaultProvider).toBe("anthropic");
});
it("throws with server error message on failure", async () => {
const { updateGlobalSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: "Bad Request",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ error: "Invalid settings format" }),
text: () => Promise.resolve(JSON.stringify({ error: "Invalid settings format" })),
} as unknown as Response);
await expect(updateGlobalSettings({})).rejects.toThrow("Invalid settings format");
});
});
describe("updateSettings scope rejection", () => {
it("forwards payload to PUT /api/settings and surfaces resulting 400 error", async () => {
const { updateSettings } = await import("../api");
// The backend rejects global keys on PUT /api/settings
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: "Bad Request",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ error: "Global settings keys not allowed in project scope" }),
text: () => Promise.resolve(JSON.stringify({ error: "Global settings keys not allowed in project scope" })),
} as unknown as Response);
// This documents the client/server contract: sending global keys to project endpoint fails
await expect(updateSettings({ themeMode: "light" })).rejects.toThrow(
"Global settings keys not allowed in project scope"
);
const [url, options] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe("/api/settings");
expect(options.method).toBe("PUT");
});
it("sends PUT to /api/settings with project-scoped payload on success", async () => {
const { updateSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ planningProvider: "openai" }),
text: () => Promise.resolve(JSON.stringify({ planningProvider: "openai" })),
} as unknown as Response);
const result = await updateSettings({ planningProvider: "openai", planningModelId: "gpt-4o" });
expect(result.planningProvider).toBe("openai");
const [url, options] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe("/api/settings");
expect(options.method).toBe("PUT");
expect(JSON.parse(options.body as string)).toEqual({
planningProvider: "openai",
planningModelId: "gpt-4o",
});
});
});
describe("fetchGlobalSettings", () => {
it("calls GET /api/settings/global with no query string", async () => {
const { fetchGlobalSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ themeMode: "dark" }),
text: () => Promise.resolve(JSON.stringify({ themeMode: "dark" })),
} as unknown as Response);
await fetchGlobalSettings();
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/global", expect.objectContaining({
headers: API_JSON_HEADERS,
}));
// GET is the default method
const call = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(call[1].method).toBeUndefined();
});
it("returns GlobalSettings with known keys like themeMode", async () => {
const { fetchGlobalSettings } = await import("../api");
const mockSettings = {
themeMode: "light",
defaultProvider: "anthropic",
defaultModelId: "claude-sonnet-4-5",
};
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve(mockSettings),
text: () => Promise.resolve(JSON.stringify(mockSettings)),
} as unknown as Response);
const result = await fetchGlobalSettings();
expect(result.themeMode).toBe("light");
expect(result.defaultProvider).toBe("anthropic");
});
it("throws with server error message on failure", async () => {
const { fetchGlobalSettings } = await import("../api");
globalThis.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
statusText: "Internal Server Error",
headers: {
get: (name: string) =>
name.toLowerCase() === "content-type" ? "application/json" : null,
},
json: () => Promise.resolve({ error: "Settings file corrupted" }),
text: () => Promise.resolve(JSON.stringify({ error: "Settings file corrupted" })),
} as unknown as Response);
await expect(fetchGlobalSettings()).rejects.toThrow("Settings file corrupted");
});
});
});
describe("Automation API scope forwarding", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("fetchAutomations sends GET to /automations without scope by default", async () => {
const { fetchAutomations } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchAutomations();
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe("/api/automations");
});
it("fetchAutomations includes scope=global when specified", async () => {
const { fetchAutomations } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchAutomations({ scope: "global" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations?scope=global");
});
it("fetchAutomations includes scope=project and projectId when project-scoped", async () => {
const { fetchAutomations } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchAutomations({ scope: "project", projectId: "proj-123" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations");
expect(url).toContain("scope=project");
expect(url).toContain("projectId=proj-123");
});
it("createAutomation forwards scope context in query params", async () => {
const { createAutomation } = await import("../api");
const fakeSchedule = {
id: "sched-001",
name: "Test",
scheduleType: "daily",
cronExpression: "0 0 * * *",
command: "echo test",
enabled: true,
scope: "project",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
globalThis.fetch = vi.fn().mockReturnValue({
ok: true,
status: 201,
statusText: "Created",
headers: { get: () => "application/json" },
json: () => Promise.resolve(fakeSchedule),
text: () => Promise.resolve(JSON.stringify(fakeSchedule)),
} as unknown as Response);
await createAutomation(
{ name: "Test", scheduleType: "daily", command: "echo test", enabled: true, scope: "project" },
{ scope: "project", projectId: "proj-123" }
);
const [url, opts] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations?scope=project&projectId=proj-123");
const body = JSON.parse(opts.body);
expect(body.name).toBe("Test");
expect(body.scope).toBe("project");
});
it("createAutomation forwards scope context without projectId for global scope", async () => {
const { createAutomation } = await import("../api");
const fakeSchedule = {
id: "sched-001",
name: "Test",
scheduleType: "daily",
cronExpression: "0 0 * * *",
command: "echo test",
enabled: true,
scope: "global",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
globalThis.fetch = vi.fn().mockReturnValue({
ok: true,
status: 201,
statusText: "Created",
headers: { get: () => "application/json" },
json: () => Promise.resolve(fakeSchedule),
text: () => Promise.resolve(JSON.stringify(fakeSchedule)),
} as unknown as Response);
await createAutomation(
{ name: "Test", scheduleType: "daily", command: "echo test", enabled: true },
{ scope: "global" }
);
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations?scope=global");
expect(url).not.toContain("projectId");
});
it("runAutomation forwards scope context", async () => {
const { runAutomation } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, { schedule: {}, result: { success: true } }));
await runAutomation("sched-001", { scope: "project", projectId: "proj-123" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations/sched-001/run?scope=project&projectId=proj-123");
});
it("toggleAutomation forwards scope context", async () => {
const { toggleAutomation } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, { id: "sched-001", enabled: false }));
await toggleAutomation("sched-001", { scope: "global" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/automations/sched-001/toggle?scope=global");
});
});
describe("Routine API scope forwarding", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("fetchRoutines sends GET to /routines without scope by default", async () => {
const { fetchRoutines } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchRoutines();
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toBe("/api/routines");
});
it("fetchRoutines includes scope=global when specified", async () => {
const { fetchRoutines } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchRoutines({ scope: "global" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines?scope=global");
});
it("fetchRoutines includes scope=project and projectId when project-scoped", async () => {
const { fetchRoutines } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, []));
await fetchRoutines({ scope: "project", projectId: "proj-456" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines");
expect(url).toContain("scope=project");
expect(url).toContain("projectId=proj-456");
});
it("createRoutine forwards scope context in query params", async () => {
const { createRoutine } = await import("../api");
const fakeRoutine = {
id: "routine-001",
name: "Test Routine",
enabled: true,
trigger: { type: "manual" },
scope: "project",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
globalThis.fetch = vi.fn().mockReturnValue({
ok: true,
status: 201,
statusText: "Created",
headers: { get: () => "application/json" },
json: () => Promise.resolve(fakeRoutine),
text: () => Promise.resolve(JSON.stringify(fakeRoutine)),
} as unknown as Response);
await createRoutine(
{ name: "Test Routine", agentId: "", trigger: { type: "manual" as const }, enabled: true },
{ scope: "project", projectId: "proj-456" }
);
const [url, opts] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines?scope=project&projectId=proj-456");
const body = JSON.parse(opts.body);
expect(body.name).toBe("Test Routine");
expect(body.scope).toBeUndefined(); // scope is in query, not body (body comes from RoutineCreateInput)
});
it("updateRoutine forwards scope context", async () => {
const { updateRoutine } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, { id: "routine-001", name: "Updated" }));
await updateRoutine("routine-001", { name: "Updated" }, { scope: "project", projectId: "proj-456" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines/routine-001?scope=project&projectId=proj-456");
});
it("deleteRoutine forwards scope context", async () => {
const { deleteRoutine } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue({
ok: true,
status: 204,
statusText: "No Content",
headers: { get: () => "application/json" },
json: () => Promise.resolve(null),
text: () => Promise.resolve(""),
} as unknown as Response);
await deleteRoutine("routine-001", { scope: "global" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines/routine-001?scope=global");
});
it("runRoutine forwards scope context", async () => {
const { runRoutine } = await import("../api");
globalThis.fetch = vi.fn().mockReturnValue(mockSchedulingFetchResponse(true, { routine: {}, result: { success: true } }));
await runRoutine("routine-001", { scope: "project", projectId: "proj-789" });
const [url] = (globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(url).toContain("/api/routines/routine-001/trigger?scope=project&projectId=proj-789");
});
});
describe("fetchPiSettings", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("fetches pi settings from /api/pi-settings", async () => {
const mockSettings = {
packages: ["npm:pi-example"],
extensions: ["/path/to/extension"],
skills: ["/path/to/skill"],
prompts: ["/path/to/prompts"],
themes: ["/path/to/themes"],
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, mockSettings));
const result = await fetchPiSettings();
expect(result).toEqual(mockSettings);
/*
Exact headers, not a nested objectContaining (coderabbit #2652). `fetchPiSettings` goes through
`api()`, so it carries the `x-fusion-client` attribution header — and a loose matcher would pass
with that header silently dropped, which is precisely what these assertions are the only guard
against. My own note in test/apiRequestHeaders.ts says so; this site was inconsistent with it.
*/
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings", expect.objectContaining({
headers: API_JSON_HEADERS,
}));
});
it("throws with server error message on failure", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Failed to read settings" })
);
await expect(fetchPiSettings()).rejects.toThrow("Failed to read settings");
});
});
describe("updatePiSettings", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends PUT to /api/pi-settings with settings body", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
const result = await updatePiSettings({ packages: ["npm:new-package"] });
expect(result.success).toBe(true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings", expect.objectContaining({
method: "PUT",
body: JSON.stringify({ packages: ["npm:new-package"] }),
}));
});
it("sends all fields when updating multiple settings", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
const result = await updatePiSettings({
packages: ["npm:pi-example"],
extensions: ["/custom/extension"],
skills: ["/custom/skill"],
prompts: ["/custom/prompts"],
themes: ["/custom/themes"],
});
expect(result.success).toBe(true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings", expect.objectContaining({
method: "PUT",
body: JSON.stringify({
packages: ["npm:pi-example"],
extensions: ["/custom/extension"],
skills: ["/custom/skill"],
prompts: ["/custom/prompts"],
themes: ["/custom/themes"],
}),
}));
});
});
describe("installPiPackage", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends POST to /api/pi-settings/packages with source", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
const result = await installPiPackage("npm:pi-example");
expect(result.success).toBe(true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings/packages", expect.objectContaining({
method: "POST",
body: JSON.stringify({ source: "npm:pi-example" }),
}));
});
it("handles git source URLs", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
const result = await installPiPackage("git:https://github.com/example/pi-extension.git");
expect(result.success).toBe(true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings/packages", expect.objectContaining({
method: "POST",
body: JSON.stringify({ source: "git:https://github.com/example/pi-extension.git" }),
}));
});
});
describe("reinstallFusionPiPackage", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends POST to /api/pi-settings/reinstall-fusion", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(true, { success: true, source: "npm:@runfusion/fusion" })
);
const result = await reinstallFusionPiPackage();
expect(result).toEqual({ success: true, source: "npm:@runfusion/fusion" });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings/reinstall-fusion", expect.objectContaining({
method: "POST",
}));
});
it("forwards projectId query parameter when provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(true, { success: true, source: "npm:@runfusion/fusion" })
);
await reinstallFusionPiPackage("proj-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/pi-settings/reinstall-fusion?projectId=proj-123", expect.objectContaining({
method: "POST",
}));
});
it("throws API error message on failure", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Reinstall failed" }, 500));
await expect(reinstallFusionPiPackage()).rejects.toThrow("Reinstall failed");
});
});
describe("fetchPiExtensions", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends GET to /api/settings/pi-extensions", async () => {
const mockSettings = {
extensions: [
{ id: "ext-1", name: "Example", source: "fusion-global", path: "/path/to/ext", enabled: true },
],
disabledIds: [],
settingsPath: "/path/to/settings",
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, mockSettings));
const result = await fetchPiExtensions();
expect(result.extensions).toEqual(mockSettings.extensions);
expect(result.disabledIds).toEqual(mockSettings.disabledIds);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/pi-extensions", expect.any(Object));
});
it("includes projectId query param when provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { extensions: [], disabledIds: [], settingsPath: "" }));
await fetchPiExtensions("proj-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/pi-extensions?projectId=proj-123", expect.any(Object));
});
it("returns empty extensions when no extensions", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { extensions: [], disabledIds: [], settingsPath: "" }));
const result = await fetchPiExtensions();
expect(result.extensions).toEqual([]);
});
it("handles all source types", async () => {
const mockSettings = {
extensions: [
{ id: "ext-1", name: "Fusion Global", source: "fusion-global", path: "/path", enabled: true },
{ id: "ext-2", name: "Pi Global", source: "pi-global", path: "/path", enabled: true },
{ id: "ext-3", name: "Fusion Project", source: "fusion-project", path: "/path", enabled: false },
{ id: "ext-4", name: "Pi Project", source: "pi-project", path: "/path", enabled: true },
],
disabledIds: ["ext-3"],
settingsPath: "/path/to/settings",
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, mockSettings));
const result = await fetchPiExtensions();
expect(result.extensions).toHaveLength(4);
expect(result.extensions[0].source).toBe("fusion-global");
});
it("throws error on API failure", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Server error" }, 500));
await expect(fetchPiExtensions()).rejects.toThrow();
});
});
describe("updatePiExtensions", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("sends PUT to /api/settings/pi-extensions with disabledIds", async () => {
const mockSettings = { extensions: [], disabledIds: ["ext-1", "ext-2"], settingsPath: "" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, mockSettings));
const result = await updatePiExtensions(["ext-1", "ext-2"]);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/pi-extensions", expect.objectContaining({
method: "PUT",
body: JSON.stringify({ disabledIds: ["ext-1", "ext-2"] }),
}));
expect(result.disabledIds).toEqual(["ext-1", "ext-2"]);
});
it("includes projectId query param when provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { extensions: [], disabledIds: [], settingsPath: "" }));
await updatePiExtensions([], "proj-456");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/pi-extensions?projectId=proj-456", expect.any(Object));
});
it("sends empty disabledIds array", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { extensions: [], disabledIds: [], settingsPath: "" }));
await updatePiExtensions([]);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/settings/pi-extensions", expect.objectContaining({
method: "PUT",
body: JSON.stringify({ disabledIds: [] }),
}));
});
it("throws error on API failure", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Server error" }, 500));
await expect(updatePiExtensions(["ext-1"])).rejects.toThrow();
});
});
describe("agent onboarding API wrappers", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
it("starts onboarding streaming session with create context payload", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { sessionId: "onb-1" }, 201));
const result = await startAgentOnboardingStreaming(
"Need a docs reviewer",
{
existingAgents: [{ id: "agent-1", name: "Reviewer", role: "reviewer" }],
templates: [{ id: "preset-1", label: "Reviewer preset" }],
mode: "create",
},
"proj-123",
{ planningModelProvider: "openai", planningModelId: "gpt-4o" },
);
expect(result.sessionId).toBe("onb-1");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/agents/onboarding/start-streaming?projectId=proj-123", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({
intent: "Need a docs reviewer",
context: {
existingAgents: [{ id: "agent-1", name: "Reviewer", role: "reviewer" }],
templates: [{ id: "preset-1", label: "Reviewer preset" }],
mode: "create",
},
mode: "create",
planningModelProvider: "openai",
planningModelId: "gpt-4o",
}),
});
});
it("starts onboarding streaming session with edit context payload", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { sessionId: "onb-edit" }, 201));
const result = await startAgentOnboardingStreaming(
"Tighten this agent's review quality",
{
existingAgents: [{ id: "agent-1", name: "Reviewer", role: "reviewer" }],
templates: [{ id: "preset-1", label: "Reviewer preset" }],
mode: "edit",
existingAgentConfig: {
name: "Reviewer",
role: "reviewer",
instructionsText: "Current instructions",
runtimeHint: "openclaw",
heartbeatIntervalMs: 30000,
},
},
"proj-123",
);
expect(result.sessionId).toBe("onb-edit");
expect(globalThis.fetch).toHaveBeenCalledWith(
"/api/agents/onboarding/start-streaming?projectId=proj-123",
expect.objectContaining({
method: "POST",
body: JSON.stringify({
intent: "Tighten this agent's review quality",
context: {
existingAgents: [{ id: "agent-1", name: "Reviewer", role: "reviewer" }],
templates: [{ id: "preset-1", label: "Reviewer preset" }],
mode: "edit",
existingAgentConfig: {
name: "Reviewer",
role: "reviewer",
instructionsText: "Current instructions",
runtimeHint: "openclaw",
heartbeatIntervalMs: 30000,
},
},
mode: "edit",
existingAgentConfig: {
name: "Reviewer",
role: "reviewer",
instructionsText: "Current instructions",
runtimeHint: "openclaw",
heartbeatIntervalMs: 30000,
},
}),
}),
);
});
it("posts onboarding response/retry/stop/cancel endpoints", async () => {
globalThis.fetch = vi.fn()
.mockReturnValueOnce(mockFetchResponse(true, { type: "question", data: { id: "q1", type: "text", question: "?" } }))
.mockReturnValueOnce(mockFetchResponse(true, { success: true, sessionId: "onb-1" }))
.mockReturnValueOnce(mockFetchResponse(true, { success: true }))
.mockReturnValueOnce(mockFetchResponse(true, {}));
await respondToAgentOnboarding("onb-1", { q1: "answer" }, "proj-123");
await retryAgentOnboardingSession("onb-1", "proj-123");
await stopAgentOnboardingGeneration("onb-1", "proj-123");
await cancelAgentOnboarding("onb-1", "proj-123");
expect(globalThis.fetch).toHaveBeenNthCalledWith(1, "/api/agents/onboarding/respond?projectId=proj-123", expect.objectContaining({ method: "POST" }));
expect(globalThis.fetch).toHaveBeenNthCalledWith(2, "/api/agents/onboarding/onb-1/retry?projectId=proj-123", expect.objectContaining({ method: "POST" }));
expect(globalThis.fetch).toHaveBeenNthCalledWith(3, "/api/agents/onboarding/onb-1/stop?projectId=proj-123", expect.objectContaining({ method: "POST" }));
expect(globalThis.fetch).toHaveBeenNthCalledWith(4, "/api/agents/onboarding/cancel?projectId=proj-123", expect.objectContaining({ method: "POST" }));
});
});