Files
fusion/packages/dashboard/app/__tests__/api-git.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

1163 lines
39 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,
revertTask,
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";
describe("Git Management API", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
describe("fetchGitStatus", () => {
it("returns git status", async () => {
const status = { branch: "main", commit: "abc1234", isDirty: false, ahead: 0, behind: 0 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, status));
const result = await fetchGitStatus();
expect(result).toEqual(status);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/status", {
headers: API_JSON_HEADERS,
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Not a git repository" }, 400));
await expect(fetchGitStatus()).rejects.toThrow("Not a git repository");
});
});
describe("fetchGitCommits", () => {
it("returns commits without limit", async () => {
const commits = [
{ hash: "abc123", shortHash: "abc", message: "Test commit", author: "User", date: "2026-01-01", parents: [] },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchGitCommits();
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits", {
headers: API_JSON_HEADERS,
});
});
it("includes limit in query string", async () => {
const commits = [{ hash: "abc123", shortHash: "abc", message: "Test", author: "User", date: "2026-01-01", parents: [] }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchGitCommits(50);
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits?limit=50", {
headers: API_JSON_HEADERS,
});
});
});
describe("fetchCommitDiff", () => {
it("returns diff for a commit", async () => {
const diff = { stat: "1 file changed", patch: "diff content" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, diff));
const result = await fetchCommitDiff("abc123");
expect(result).toEqual(diff);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits/abc123/diff", {
headers: API_JSON_HEADERS,
});
});
it("throws on 404", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Commit not found" }, 404));
await expect(fetchCommitDiff("invalid")).rejects.toThrow("Commit not found");
});
});
describe("fetchAheadCommits", () => {
it("returns commits ahead of upstream", async () => {
const commits = [
{ hash: "abc123", shortHash: "abc", message: "Fix bug", author: "User", date: "2026-01-01", parents: [] },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchAheadCommits();
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/commits/ahead", {
headers: API_JSON_HEADERS,
});
});
it("returns empty array when no upstream", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, []));
const result = await fetchAheadCommits();
expect(result).toEqual([]);
});
});
describe("fetchRemoteCommits", () => {
it("fetches commits for a remote with default params", async () => {
const commits = [
{ hash: "def456", shortHash: "def", message: "Remote commit", author: "User", date: "2026-01-01", parents: [] },
];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, commits));
const result = await fetchRemoteCommits("origin");
expect(result).toEqual(commits);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/remotes/origin/commits", {
headers: API_JSON_HEADERS,
});
});
it("includes ref and limit in query", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, []));
await fetchRemoteCommits("origin", "main", 5);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/remotes/origin/commits?ref=main&limit=5", {
headers: API_JSON_HEADERS,
});
});
it("encodes remote name in URL", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, []));
await fetchRemoteCommits("my-remote");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/remotes/my-remote/commits", {
headers: API_JSON_HEADERS,
});
});
});
describe("fetchGitBranches", () => {
it("returns branches array", async () => {
const branches = [{ name: "main", isCurrent: true, remote: "origin/main" }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, branches));
const result = await fetchGitBranches();
expect(result).toEqual(branches);
});
});
describe("fetchGitWorktrees", () => {
it("returns worktrees array", async () => {
const worktrees = [{ path: "/path/to/repo", branch: "main", isMain: true, isBare: false }];
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, worktrees));
const result = await fetchGitWorktrees();
expect(result).toEqual(worktrees);
});
});
describe("createBranch", () => {
it("sends POST to create branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { created: true }, 201));
await createBranch("feature-branch");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ name: "feature-branch", base: undefined }),
});
});
it("sends base when provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { created: true }, 201));
await createBranch("feature-branch", "main");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ name: "feature-branch", base: "main" }),
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Invalid branch name" }, 400));
await expect(createBranch("invalid")).rejects.toThrow("Invalid branch name");
});
});
describe("checkoutBranch", () => {
it("sends POST to checkout branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { checkedOut: "main" }));
await checkoutBranch("main");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/main/checkout", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("encodes branch name", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, {}));
await checkoutBranch("feature/test");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature%2Ftest/checkout", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
});
describe("deleteBranch", () => {
it("sends DELETE to remove branch", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { deleted: "feature" }));
await deleteBranch("feature");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
it("includes force query param when true", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { deleted: "feature" }));
await deleteBranch("feature", true);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/branches/feature?force=true", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
});
describe("fetchRemote", () => {
it("sends POST to fetch origin by default", async () => {
const result = { fetched: true, message: "Fetched" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await fetchRemote();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/fetch", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ remote: undefined }),
});
});
it("sends custom remote when provided", async () => {
const result = { fetched: true, message: "Fetched from upstream" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
await fetchRemote("upstream");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/fetch", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ remote: "upstream" }),
});
});
});
describe("pullBranch", () => {
it("sends POST to pull with default rebase false", async () => {
const result = { success: true, message: "Pulled 2 commits" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await pullBranch();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/pull", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ rebase: false }),
});
});
it("sends rebase true when requested", async () => {
const result = { success: true, message: "Rebased and pulled" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
await pullBranch({ rebase: true });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/pull", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ rebase: true }),
});
});
it("returns conflict info when there are conflicts", async () => {
const result = { success: false, message: "Merge conflict", conflict: true };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result, 409));
const response = await pullBranch();
expect(response.conflict).toBe(true);
});
});
describe("pushBranch", () => {
it("sends POST to push", async () => {
const result = { success: true, message: "Pushed to origin" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, result));
const response = await pushBranch();
expect(response).toEqual(result);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/git/push", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on rejection", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Push rejected" }, 409));
await expect(pushBranch()).rejects.toThrow("Push rejected");
});
});
describe("archiveTask", () => {
it("sends POST to archive endpoint", async () => {
const archivedTask: Task = { ...FAKE_DETAIL, column: "archived" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, archivedTask));
const response = await archiveTask("FN-001");
expect(response.column).toBe("archived");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/archive", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("sends removeLineageReferences=true when archive lineage unlink is requested", async () => {
const archivedTask: Task = { ...FAKE_DETAIL, column: "archived" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, archivedTask));
await archiveTask("FN-001", undefined, { removeLineageReferences: true });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/archive?removeLineageReferences=true", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not in done" }, 400));
await expect(archiveTask("FN-001")).rejects.toThrow("Task not in done");
});
});
describe("unarchiveTask", () => {
it("sends POST to unarchive endpoint", async () => {
const unarchivedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, unarchivedTask));
const response = await unarchiveTask("FN-001");
expect(response.column).toBe("done");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/unarchive", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not in archived" }, 400));
await expect(unarchiveTask("FN-001")).rejects.toThrow("Task not in archived");
});
});
/*
FNXC:TaskRevert 2026-07-05-00:00 (FN-7525):
Client-shape coverage for `revertTask` — the `POST /tasks/:id/revert` route
(FN-7523/FN-7524) contract. Asserts the JSON body is forwarded verbatim and
the parsed discriminated-union result (git or ai path) is returned as-is,
plus standard error propagation on a non-2xx response.
*/
describe("revertTask", () => {
it("sends POST with the JSON mode body and returns the parsed git-path result", async () => {
const gitResult = { mode: "git", clean: true, revertCommitSha: "deadbeef1234" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, gitResult));
const response = await revertTask("FN-001", undefined, { mode: "auto" });
expect(response).toEqual(gitResult);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/revert", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ mode: "auto" }),
});
});
it("returns the parsed ai-path result", async () => {
const aiResult = { mode: "ai", createdTaskId: "FN-999" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, aiResult));
const response = await revertTask("FN-001", undefined, { mode: "ai" });
expect(response).toEqual(aiResult);
});
it("defaults to an empty JSON body when no options are provided", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { mode: "git", clean: true }));
await revertTask("FN-001");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/revert", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({}),
});
});
it("throws on error propagation", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task is in column \"todo\"" }, 409));
await expect(revertTask("FN-001")).rejects.toThrow('Task is in column "todo"');
});
});
describe("deleteTask", () => {
it("sends DELETE to task endpoint", async () => {
const deletedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, deletedTask));
const response = await deleteTask("FN-001");
expect(response).toEqual(deletedTask);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
it("sends removeDependencyReferences=true when dependency rewrite is requested", async () => {
const deletedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, deletedTask));
await deleteTask("FN-001", undefined, { removeDependencyReferences: true });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001?removeDependencyReferences=true", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
it("sends githubIssueAction when requested", async () => {
const deletedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, deletedTask));
await deleteTask("FN-001", undefined, { githubIssueAction: "delete" });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001?githubIssueAction=delete", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
it("sends removeLineageReferences=true when lineage unlink is requested", async () => {
const deletedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, deletedTask));
await deleteTask("FN-001", undefined, { removeLineageReferences: true });
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001?removeLineageReferences=true", {
headers: API_JSON_HEADERS,
method: "DELETE",
});
});
it("throws ApiRequestError on error and preserves details payload", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(
false,
{
error: "Cannot delete task FN-001: still referenced as a dependency by FN-002.",
details: {
code: "TASK_HAS_DEPENDENTS",
dependentIds: ["FN-002"],
},
},
409,
),
);
await expect(deleteTask("FN-001")).rejects.toBeInstanceOf(ApiRequestError);
await expect(deleteTask("FN-001")).rejects.toMatchObject({
message: "Cannot delete task FN-001: still referenced as a dependency by FN-002.",
status: 409,
details: {
code: "TASK_HAS_DEPENDENTS",
dependentIds: ["FN-002"],
},
});
});
});
describe("moveTask", () => {
it("sends POST to move endpoint with column body", async () => {
const movedTask: Task = { ...FAKE_DETAIL, column: "todo" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, movedTask));
const response = await moveTask("FN-001", "todo");
expect(response.column).toBe("todo");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/move", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ column: "todo" }),
});
});
it("sends POST with done column", async () => {
const movedTask: Task = { ...FAKE_DETAIL, column: "done" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, movedTask));
const response = await moveTask("FN-001", "done");
expect(response.column).toBe("done");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/move", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ column: "done" }),
});
});
it("forwards projectId as query param", async () => {
const movedTask: Task = { ...FAKE_DETAIL, column: "todo" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, movedTask));
await moveTask("FN-001", "todo", "proj_123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/move?projectId=proj_123", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ column: "todo" }),
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Cannot move to same column" }, 400));
await expect(moveTask("FN-001", "todo")).rejects.toThrow("Cannot move to same column");
});
});
describe("mergeTask", () => {
it("sends POST to merge endpoint and returns MergeResult", async () => {
const mergeResult = {
task: { id: "FN-001", description: "", column: "done", dependencies: [], steps: [], currentStep: 0, log: [], createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z" },
branch: "fn/FN-001",
merged: true,
worktreeRemoved: true,
branchDeleted: true,
} as unknown as MergeResult;
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, mergeResult));
const response = await mergeTask("FN-001");
expect(response).toEqual(mergeResult);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/merge", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Cannot merge with itself" }, 400));
await expect(mergeTask("FN-001")).rejects.toThrow("Cannot merge with itself");
});
});
describe("retryTask", () => {
it("sends POST to retry endpoint", async () => {
const retriedTask: Task = { ...FAKE_DETAIL, column: "todo" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, retriedTask));
const response = await retryTask("FN-001");
expect(response).toEqual(retriedTask);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/retry", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not in error state" }, 400));
await expect(retryTask("FN-001")).rejects.toThrow("Task not in error state");
});
});
describe("duplicateTask", () => {
it("sends POST to duplicate endpoint", async () => {
const duplicatedTask: Task = { ...FAKE_DETAIL, id: "FN-002" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, duplicatedTask));
const response = await duplicateTask("FN-001");
expect(response.id).toBe("FN-002");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/duplicate", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Duplicate failed" }, 500));
await expect(duplicateTask("FN-001")).rejects.toThrow("Duplicate failed");
});
});
describe("pauseTask", () => {
it("sends POST to pause endpoint", async () => {
const pausedTask: Task = { ...FAKE_DETAIL, column: "in-progress" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, pausedTask));
const response = await pauseTask("FN-001");
expect(response).toEqual(pausedTask);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/pause", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Cannot pause completed task" }, 400));
await expect(pauseTask("FN-001")).rejects.toThrow("Cannot pause completed task");
});
});
describe("unpauseTask", () => {
it("sends POST to unpause endpoint", async () => {
const unpausedTask: Task = { ...FAKE_DETAIL, column: "in-progress" };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, unpausedTask));
const response = await unpauseTask("FN-001");
expect(response).toEqual(unpausedTask);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/tasks/FN-001/unpause", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("throws on error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not paused" }, 400));
await expect(unpauseTask("FN-001")).rejects.toThrow("Task not paused");
});
});
describe("workspace file APIs", () => {
it("fetchWorkspaces requests the workspace list", async () => {
const payload = {
project: "/repo",
tasks: [{ id: "FN-001", title: "Task", worktree: "/repo/.worktrees/kb-001" }],
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaces();
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/workspaces", {
headers: API_JSON_HEADERS,
});
});
it("fetchWorkspaceFileList sends workspace and path query params", async () => {
const payload = { path: "src", entries: [] };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaceFileList("FN-001", "src");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files?workspace=FN-001&path=src", {
headers: API_JSON_HEADERS,
});
});
it("fetchWorkspaceFileContent sends the workspace query param", async () => {
const payload = { content: "hello", mtime: "2026-01-01T00:00:00.000Z", size: 5 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await fetchWorkspaceFileContent("project", "src/index.ts");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/src%2Findex.ts?workspace=project", {
headers: API_JSON_HEADERS,
});
});
it("saveWorkspaceFileContent posts content to the workspace route", async () => {
const payload = { success: true, mtime: "2026-01-01T00:00:00.000Z", size: 5 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await saveWorkspaceFileContent("FN-001", "src/index.ts", "hello");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/src%2Findex.ts?workspace=FN-001", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ content: "hello" }),
});
});
it("deleteFile sends POST to the delete route with encoded URL and workspace query", async () => {
// FN-1492 regression: ensure folder delete (e.g., "somefolder/") doesn't hit the
// generic write route POST /files/{*filepath} and get rejected for missing `content`.
const payload = { success: true, mtime: null, size: 0 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
const response = await deleteFile("FN-001", "src/old");
expect(response).toEqual(payload);
// Verify the delete operation goes to /files/{encoded-path}/delete (not the write route)
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/src%2Fold/delete?workspace=FN-001", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("deleteFile URL-encodes nested paths correctly", async () => {
const payload = { success: true, mtime: null, size: 0 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
await deleteFile("FN-001", "a/b/c");
// Forward slashes in path segments must be encoded so Express matches
// POST /files/{*filepath}/delete rather than POST /files/{*filepath}
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/a%2Fb%2Fc/delete?workspace=FN-001", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("deleteFile handles folder paths (FN-1492 regression)", async () => {
const payload = { success: true, mtime: null, size: 0 };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, payload));
// Deleting a folder should work without hitting write-route validation
const response = await deleteFile("FN-001", "old-folder");
expect(response).toEqual(payload);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/files/old-folder/delete?workspace=FN-001", {
headers: API_JSON_HEADERS,
method: "POST",
});
});
it("propagates workspace API errors", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(false, { error: "Task not found" }, 404));
await expect(fetchWorkspaceFileList("FN-404")).rejects.toThrow("Task not found");
});
});
});
describe("Planning Mode API", () => {
const originalFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = originalFetch;
});
const FAKE_QUESTION: PlanningQuestion = {
id: "q-scope",
type: "single_select",
question: "What is the scope of this plan?",
description: "This helps estimate the size and complexity.",
options: [
{ id: "small", label: "Small", description: "Quick implementation" },
{ id: "large", label: "Large", description: "Complex feature" },
],
};
const FAKE_SUMMARY: PlanningSummary = {
title: "Build user authentication",
description: "Implement login/logout with JWT tokens",
suggestedSize: "M",
suggestedDependencies: [],
keyDeliverables: ["Login form", "JWT middleware", "Logout endpoint"],
};
describe("startPlanning", () => {
it("sends POST with initial plan and returns session", async () => {
const response = { sessionId: "plan-123", currentQuestion: FAKE_QUESTION, summary: null };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response, 201));
const result = await startPlanning("Build a user auth system");
expect(result.sessionId).toBe("plan-123");
expect(result.currentQuestion).toEqual(FAKE_QUESTION);
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/start", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ initialPlan: "Build a user auth system" }),
});
});
it("throws on rate limit error", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Rate limit exceeded. Maximum 1000 planning sessions per hour." }, 429)
);
await expect(startPlanning("Build something")).rejects.toThrow("Rate limit exceeded");
});
it("accepts long initialPlan values (no character limit)", async () => {
// Test that long initialPlan values are accepted by the server (removed 500-char limit)
const response = { sessionId: "plan-456", currentQuestion: FAKE_QUESTION, summary: null };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response, 201));
const result = await startPlanning("a".repeat(2000));
expect(result.sessionId).toBe("plan-456");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/start", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ initialPlan: "a".repeat(2000) }),
});
});
});
describe("respondToPlanning", () => {
it("sends POST with responses and returns next question", async () => {
const response = { sessionId: "plan-123", currentQuestion: FAKE_QUESTION, summary: null };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await respondToPlanning("plan-123", { scope: "small" });
expect(result.sessionId).toBe("plan-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/respond", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ sessionId: "plan-123", responses: { scope: "small" } }),
});
});
it("returns summary when planning is complete", async () => {
const response = { sessionId: "plan-123", currentQuestion: null, summary: FAKE_SUMMARY };
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, response));
const result = await respondToPlanning("plan-123", { final: "yes" });
expect(result.summary).toEqual(FAKE_SUMMARY);
expect(result.currentQuestion).toBeNull();
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session plan-123 not found or expired" }, 404)
);
await expect(respondToPlanning("plan-123", {})).rejects.toThrow("not found");
});
});
describe("cancelPlanning", () => {
it("sends POST to cancel endpoint", async () => {
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, { success: true }));
await cancelPlanning("plan-123");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/cancel", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ sessionId: "plan-123" }),
});
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session not found" }, 404)
);
await expect(cancelPlanning("plan-123")).rejects.toThrow("not found");
});
});
describe("createTaskFromPlanning", () => {
it("sends POST to create-task endpoint and returns task", async () => {
const createdTask: Task = {
id: "FN-042",
title: "Build user authentication",
description: "Implement login/logout with JWT tokens",
column: "triage",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
/*
FNXC:PlanningMode 2026-07-23-23:35:
FN-8442 (36b318096) changed POST /planning/create-task to respond with a
{ task, alreadyCreated } envelope (idempotent replay detection); the client
unwraps response.task. Mock the real server envelope, not a bare Task.
*/
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(true, { task: createdTask, alreadyCreated: false }, 201)
);
const result = await createTaskFromPlanning("plan-123");
expect(result.id).toBe("FN-042");
expect(result.column).toBe("triage");
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/create-task", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({ sessionId: "plan-123" }),
});
});
it("throws when session is not complete", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session is not complete" }, 400)
);
await expect(createTaskFromPlanning("plan-123")).rejects.toThrow("not complete");
});
it("throws on session not found", async () => {
globalThis.fetch = vi.fn().mockReturnValue(
mockFetchResponse(false, { error: "Planning session not found" }, 404)
);
await expect(createTaskFromPlanning("plan-123")).rejects.toThrow("not found");
});
it("includes branchSelection options in create-task request body", async () => {
const createdTask: Task = {
id: "FN-043",
title: "Branch aware plan",
description: "Create task with branch config",
column: "triage",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
globalThis.fetch = vi.fn().mockReturnValue(mockFetchResponse(true, createdTask, 201));
await createTaskFromPlanning("plan-123", undefined, undefined, {
branchSelection: {
mode: "custom-new",
branchName: "feature/planning-ui",
baseBranch: "develop",
},
});
expect(globalThis.fetch).toHaveBeenCalledWith("/api/planning/create-task", {
headers: API_JSON_HEADERS,
method: "POST",
body: JSON.stringify({
sessionId: "plan-123",
branchSelection: {
mode: "custom-new",
branchName: "feature/planning-ui",
baseBranch: "develop",
},
}),
});
});
});
});
/** Mock helper for HTML error responses (e.g., 404 page) */