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>
910 lines
29 KiB
TypeScript
910 lines
29 KiB
TypeScript
/**
|
|
* FNXC:CodeOrganization 2026-07-19-12:00:
|
|
* Multi-project management client API peeled from legacy.ts.
|
|
*/
|
|
import type {
|
|
NodeConfig,
|
|
NodeStatus,
|
|
MeshClusterSnapshot,
|
|
SystemMetrics,
|
|
DiscoveryConfig,
|
|
DockerNodeConfig,
|
|
ManagedDockerNodeInput,
|
|
DockerHostConfig,
|
|
DockerResourceSizing,
|
|
DockerVolumeMount,
|
|
DockerExtraCli,
|
|
DockerNodeStatus,
|
|
ProjectNodePathMapping,
|
|
ActivityEventType,
|
|
Task,
|
|
} from "@fusion/core";
|
|
import { api, proxyApi } from "./client.js";
|
|
import { withProjectId } from "./health.js";
|
|
import { getAuthToken } from "../auth";
|
|
import { dedupe } from "./dedupe.js";
|
|
|
|
// ── Project Management API (Multi-Project Support) ───────────────────────
|
|
|
|
/** Project information returned by project endpoints */
|
|
export interface ProjectInfo {
|
|
id: string;
|
|
name: string;
|
|
path: string;
|
|
status: "active" | "paused" | "errored" | "initializing";
|
|
isolationMode: "in-process" | "child-process";
|
|
nodeId?: string;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
lastActivityAt?: string;
|
|
}
|
|
|
|
/** Project health metrics */
|
|
export interface CodebaseMetrics {
|
|
tokenEstimate: number;
|
|
sourceFileCount: number;
|
|
sourceByteCount: number;
|
|
diskBytes: number;
|
|
diskFileCount: number;
|
|
method: string;
|
|
truncated: boolean;
|
|
}
|
|
|
|
export interface ProjectHealth {
|
|
projectId: string;
|
|
status: "active" | "paused" | "errored" | "initializing";
|
|
activeTaskCount: number;
|
|
inFlightAgentCount: number;
|
|
lastActivityAt?: string;
|
|
lastErrorAt?: string;
|
|
lastErrorMessage?: string;
|
|
totalTasksCompleted: number;
|
|
totalTasksFailed: number;
|
|
averageTaskDurationMs?: number;
|
|
updatedAt: string;
|
|
}
|
|
|
|
/**
|
|
* Executor state values.
|
|
*
|
|
* FNXC:EngineControls 2026-06-22-00:00:
|
|
* A globally stopped AI engine (`globalPause`) is an operator action, not idleness; the footer must expose it as "Stopped" in error red with the stop-rectangle icon.
|
|
*/
|
|
export type ExecutorState = "idle" | "running" | "paused" | "stopped";
|
|
|
|
/** Aggregated executor statistics for the status bar.
|
|
*
|
|
* Counts (runningTaskCount, blockedTaskCount, queuedTaskCount, inReviewCount, stuckTaskCount)
|
|
* are derived client-side from the same tasks array shared with the board, ensuring
|
|
* the footer counts always match the active work states displayed on screen. Queued covers
|
|
* todo plus planning/triage work; Done is intentionally not exposed unless a footer Done
|
|
* segment is added.
|
|
* The API returns settings-based values (globalPause, enginePaused, maxConcurrent) and
|
|
* lastActivityAt from the activity log.
|
|
*
|
|
* The executorState is derived from:
|
|
* - "stopped": globalPause is true
|
|
* - "paused": enginePaused is true (regardless of runningTaskCount)
|
|
* - "running": globalPause is false AND enginePaused is false AND runningTaskCount > 0
|
|
* - "idle": nothing paused and nothing running
|
|
*
|
|
* FNXC:EngineControls 2026-07-24-18:35: pause state dominates run state so a paused
|
|
* engine never reads "Idle" once in-flight work drains. See deriveExecutorState in
|
|
* app/hooks/useExecutorStats.ts for the rationale.
|
|
*/
|
|
export interface ExecutorStats {
|
|
/** Number of tasks currently in "in-progress" column */
|
|
runningTaskCount: number;
|
|
/** Number of tasks with blockedBy field set (waiting on file overlap) */
|
|
blockedTaskCount: number;
|
|
/** Number of "in-progress" tasks with no activity for > 10 minutes */
|
|
stuckTaskCount: number;
|
|
/** Number of tasks in "todo" plus planning/triage work states */
|
|
queuedTaskCount: number;
|
|
/** Number of tasks in "in-review" column */
|
|
inReviewCount: number;
|
|
/** Derived executor state: "idle", "running", "paused", or "stopped" */
|
|
executorState: ExecutorState;
|
|
/** Maximum concurrent tasks allowed from settings */
|
|
maxConcurrent: number;
|
|
/** ISO timestamp of most recent task event from activity log */
|
|
lastActivityAt?: string;
|
|
}
|
|
|
|
/** Unified activity feed entry */
|
|
export interface ActivityFeedEntry {
|
|
id: string;
|
|
timestamp: string;
|
|
type: ActivityEventType;
|
|
projectId: string;
|
|
projectName: string;
|
|
taskId?: string;
|
|
taskTitle?: string;
|
|
details: string;
|
|
metadata?: Record<string, unknown>;
|
|
}
|
|
|
|
/** Input for creating a new project */
|
|
export interface ProjectCreateInput {
|
|
name: string;
|
|
path: string;
|
|
isolationMode?: "in-process" | "child-process";
|
|
nodeId?: string;
|
|
gitSetupMode?: "existing" | "init" | "clone";
|
|
cloneUrl?: string;
|
|
workspaceMode?: boolean;
|
|
taskPrefix?: string;
|
|
/** Confirmed "create anyway without a git repo" when git is missing on the host (never valid for clone mode). */
|
|
skipGitInit?: boolean;
|
|
}
|
|
|
|
export type DockerNodeConfigInfo = DockerNodeConfig;
|
|
export type { DockerNodeConfig };
|
|
|
|
/** Node information returned by node endpoints */
|
|
export interface NodeInfo {
|
|
id: NodeConfig["id"];
|
|
name: NodeConfig["name"];
|
|
type: NodeConfig["type"];
|
|
url?: NodeConfig["url"];
|
|
apiKey?: NodeConfig["apiKey"];
|
|
status: NodeStatus;
|
|
capabilities?: NodeConfig["capabilities"];
|
|
maxConcurrent: NodeConfig["maxConcurrent"];
|
|
createdAt: NodeConfig["createdAt"];
|
|
updatedAt: NodeConfig["updatedAt"];
|
|
dockerConfig?: DockerNodeConfigInfo;
|
|
}
|
|
|
|
/** Managed Docker node information returned by docker node endpoints */
|
|
export interface DockerNodeInfo {
|
|
id: string;
|
|
nodeId: string | null;
|
|
name: string;
|
|
nodeType: "docker-managed";
|
|
imageName: string;
|
|
imageTag: string;
|
|
containerId: string | null;
|
|
status: DockerNodeStatus;
|
|
hostConfig: DockerHostConfig;
|
|
envVars: Record<string, string>;
|
|
volumeMounts: DockerVolumeMount[];
|
|
resourceSizing: DockerResourceSizing;
|
|
extraClis: DockerExtraCli[];
|
|
persistentStorage: boolean;
|
|
reachableUrl: string | null;
|
|
apiKey: string | null;
|
|
errorMessage: string | null;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
export interface ManagedDockerNodeInfo {
|
|
id: string;
|
|
nodeId?: string;
|
|
name: string;
|
|
containerId?: string;
|
|
status: string;
|
|
hostConfig: {
|
|
type: "local" | "remote";
|
|
host?: string;
|
|
context?: string;
|
|
tlsOptions?: Record<string, unknown>;
|
|
};
|
|
envVars: Record<string, string>;
|
|
reachableUrl?: string;
|
|
imageName: string;
|
|
imageTag: string;
|
|
volumeMounts: Array<{ hostPath: string; containerPath: string; readOnly?: boolean }>;
|
|
persistentStorage: boolean;
|
|
resourceSizing?: { cpuLimit?: string; memoryLimit?: string };
|
|
errorMessage?: string;
|
|
linkedNode?: NodeInfo;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
export interface ContainerStatusInfo {
|
|
running: boolean;
|
|
status: string;
|
|
startedAt?: string;
|
|
finishedAt?: string;
|
|
exitCode?: number;
|
|
error?: string;
|
|
ports?: Record<string, string>;
|
|
}
|
|
|
|
/** Node discovered over local network mDNS/DNS-SD */
|
|
export interface DiscoveredNodeInfo {
|
|
name: string;
|
|
host: string;
|
|
port: number;
|
|
nodeType: "local" | "remote";
|
|
nodeId?: string;
|
|
discoveredAt: string;
|
|
lastSeenAt: string;
|
|
}
|
|
|
|
/** Input for creating a new node */
|
|
export interface NodeCreateInput {
|
|
name: string;
|
|
type: "local" | "remote";
|
|
url?: string;
|
|
apiKey?: string;
|
|
maxConcurrent?: number;
|
|
dockerConfig?: DockerNodeConfigInfo;
|
|
}
|
|
|
|
/** Input for assigning a project path for a specific node during onboarding. */
|
|
export interface NodeProjectMappingInput {
|
|
projectId: string;
|
|
path: string;
|
|
}
|
|
|
|
export interface RemoteNodeDiscoveredProject {
|
|
id: string;
|
|
name: string;
|
|
path: string;
|
|
status: "active" | "paused" | "errored" | "initializing";
|
|
isolationMode: "in-process" | "child-process";
|
|
}
|
|
|
|
export interface RemoteNodeProjectDiscoveryResult {
|
|
projects: RemoteNodeDiscoveredProject[];
|
|
}
|
|
|
|
/**
|
|
* Node onboarding payload used by dashboard UI.
|
|
*
|
|
* `projectMappings` is intentionally separate from `ProjectInfo.path` and `projects.nodeId`.
|
|
* It captures node-specific filesystem paths for selected existing projects.
|
|
*/
|
|
export interface NodeOnboardingInput extends NodeCreateInput {
|
|
projectMappings: NodeProjectMappingInput[];
|
|
}
|
|
|
|
/** Input for updating an existing node */
|
|
export type NodeUpdateInput = Partial<Pick<NodeCreateInput, "name" | "type" | "url" | "apiKey" | "maxConcurrent" | "dockerConfig">> & {
|
|
status?: NodeStatus;
|
|
capabilities?: string[];
|
|
};
|
|
|
|
/** Result from a node health check */
|
|
export interface NodeHealthCheckResult {
|
|
nodeId: string;
|
|
status: NodeStatus;
|
|
responseTimeMs?: number;
|
|
error?: string;
|
|
checkedAt: string;
|
|
}
|
|
|
|
/** Runtime metrics for a node */
|
|
export interface NodeMetrics {
|
|
nodeId: string;
|
|
activeTaskCount: number;
|
|
inFlightAgentCount: number;
|
|
uptimeMs: number;
|
|
lastActivityAt?: string;
|
|
}
|
|
|
|
/** Options for fetching activity feed */
|
|
export interface FeedOptions {
|
|
limit?: number;
|
|
since?: string;
|
|
projectId?: string;
|
|
type?: ActivityFeedEntry["type"];
|
|
}
|
|
|
|
/** Global concurrency state across all projects */
|
|
export interface GlobalConcurrencyState {
|
|
globalMaxConcurrent: number;
|
|
currentlyActive: number;
|
|
queuedCount: number;
|
|
projectsActive: Record<string, number>;
|
|
}
|
|
|
|
/** First run status response */
|
|
export interface FirstRunStatus {
|
|
hasProjects: boolean;
|
|
singleProjectPath: string | null;
|
|
}
|
|
|
|
/** Setup state for first-run wizard */
|
|
export interface SetupState {
|
|
/** The first-run state: fresh-install, setup-wizard, normal-operation */
|
|
state: "fresh-install" | "setup-wizard" | "normal-operation";
|
|
/** Projects detected on the filesystem (not yet registered) */
|
|
detectedProjects: Array<{
|
|
path: string;
|
|
name: string;
|
|
hasDb: boolean;
|
|
}>;
|
|
/** Whether the central database exists */
|
|
hasCentralDb: boolean;
|
|
/** Projects already registered in the central database */
|
|
registeredProjects: Array<{
|
|
id: string;
|
|
name: string;
|
|
path: string;
|
|
}>;
|
|
}
|
|
|
|
/** Input for completing setup */
|
|
export interface CompleteSetupInput {
|
|
projects: Array<{
|
|
path: string;
|
|
name: string;
|
|
isolationMode?: "in-process" | "child-process";
|
|
}>;
|
|
}
|
|
|
|
/** Result of completing setup */
|
|
export interface CompleteSetupResult {
|
|
success: boolean;
|
|
projectsRegistered: string[];
|
|
errors: string[];
|
|
}
|
|
|
|
/** Fetch all registered projects */
|
|
export function fetchProjects(): Promise<ProjectInfo[]> {
|
|
return api<ProjectInfo[]>("/projects");
|
|
}
|
|
|
|
/** Dashboard-facing mapping contract for project availability on nodes. */
|
|
export interface ProjectNodeAvailability {
|
|
nodeId: string;
|
|
nodeName?: string;
|
|
path: string;
|
|
available: boolean;
|
|
}
|
|
|
|
/** Project info with source node metadata (added by server for remote projects). */
|
|
export interface ProjectInfoWithSource extends ProjectInfo {
|
|
/** Name of the source node (added by server for remote projects). */
|
|
_sourceNodeName?: string;
|
|
/** Normalized per-node project mappings for dashboard UI. */
|
|
nodeMappings?: ProjectNodeAvailability[];
|
|
/** Compatibility fields accepted from in-flight server rollouts. */
|
|
projectNodeMappings?: ProjectNodeAvailability[];
|
|
pathMappings?: ProjectNodeAvailability[];
|
|
}
|
|
|
|
export function hasNodeMappingsSupport(project: ProjectInfoWithSource): boolean {
|
|
return Array.isArray(project.nodeMappings)
|
|
|| Array.isArray(project.projectNodeMappings)
|
|
|| Array.isArray(project.pathMappings);
|
|
}
|
|
|
|
/** Fetch all registered projects from all nodes (local + remote) */
|
|
export function fetchProjectsAcrossNodes(): Promise<ProjectInfoWithSource[]> {
|
|
return dedupe("/projects/across-nodes", () => api<ProjectInfoWithSource[]>("/projects/across-nodes"));
|
|
}
|
|
|
|
/** Fetch all registered nodes */
|
|
export function fetchNodes(): Promise<NodeInfo[]> {
|
|
return dedupe("/nodes", () => api<NodeInfo[]>("/nodes"));
|
|
}
|
|
|
|
/** Fetch discovery runtime status and active config. */
|
|
export function fetchDiscoveryStatus(): Promise<{ active: boolean; config: DiscoveryConfig | null }> {
|
|
return api<{ active: boolean; config: DiscoveryConfig | null }>("/discovery/status");
|
|
}
|
|
|
|
/** Fetch all managed Docker nodes */
|
|
export function listManagedDockerNodes(): Promise<DockerNodeInfo[]> {
|
|
return api<DockerNodeInfo[]>("/docker-nodes");
|
|
}
|
|
|
|
export function fetchManagedDockerNodes(): Promise<ManagedDockerNodeInfo[]> {
|
|
return api<ManagedDockerNodeInfo[]>("/docker/nodes");
|
|
}
|
|
|
|
export function fetchManagedDockerNode(id: string): Promise<ManagedDockerNodeInfo> {
|
|
return api<ManagedDockerNodeInfo>(`/docker/nodes/${encodeURIComponent(id)}`);
|
|
}
|
|
|
|
export function fetchManagedDockerNodeContainerStatus(id: string): Promise<ContainerStatusInfo> {
|
|
return api<ContainerStatusInfo>(`/docker/nodes/${encodeURIComponent(id)}/container-status`);
|
|
}
|
|
|
|
export function fetchDockerNodeLogs(id: string, options?: { tail?: number }): Promise<{ logs: string }> {
|
|
const params = new URLSearchParams();
|
|
if (typeof options?.tail === "number") {
|
|
params.set("tail", String(options.tail));
|
|
}
|
|
const suffix = params.size > 0 ? `?${params.toString()}` : "";
|
|
return api<{ logs: string }>(`/docker/nodes/${encodeURIComponent(id)}/logs${suffix}`);
|
|
}
|
|
|
|
/** Create a managed Docker node */
|
|
export function createManagedDockerNode(input: ManagedDockerNodeInput): Promise<DockerNodeInfo> {
|
|
return api<DockerNodeInfo>("/docker-nodes", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
|
|
/** Start local-network discovery service. */
|
|
export function startDiscovery(input?: {
|
|
broadcast?: boolean;
|
|
listen?: boolean;
|
|
port?: number;
|
|
}): Promise<{ success: boolean; config: DiscoveryConfig }> {
|
|
return api<{ success: boolean; config: DiscoveryConfig }>("/discovery/start", {
|
|
method: "POST",
|
|
body: JSON.stringify(input ?? {}),
|
|
});
|
|
}
|
|
|
|
/** Stop local-network discovery service. */
|
|
export function stopDiscovery(): Promise<{ success: boolean }> {
|
|
return api<{ success: boolean }>("/discovery/stop", {
|
|
method: "POST",
|
|
body: JSON.stringify({}),
|
|
});
|
|
}
|
|
|
|
/** Fetch currently discovered nodes from mDNS/DNS-SD. */
|
|
export function fetchDiscoveredNodes(): Promise<DiscoveredNodeInfo[]> {
|
|
return api<DiscoveredNodeInfo[]>("/discovery/nodes");
|
|
}
|
|
|
|
/** Register a discovered node into the central node registry. */
|
|
export function connectDiscoveredNode(input: {
|
|
name: string;
|
|
host: string;
|
|
port: number;
|
|
apiKey?: string;
|
|
}): Promise<NodeInfo> {
|
|
return api<NodeInfo>("/discovery/connect", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
|
|
/** Register a new node */
|
|
export function registerNode(input: NodeCreateInput): Promise<NodeInfo> {
|
|
return api<NodeInfo>("/nodes", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
|
|
/** Discover projects from a remote node before registering it. */
|
|
export function discoverRemoteNodeProjects(input: { url: string; apiKey?: string }): Promise<RemoteNodeProjectDiscoveryResult> {
|
|
return api<RemoteNodeProjectDiscoveryResult>("/nodes/discover-projects", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
|
|
/** Fetch a single node by ID */
|
|
export function fetchNode(id: string): Promise<NodeInfo> {
|
|
return api<NodeInfo>(`/nodes/${encodeURIComponent(id)}`);
|
|
}
|
|
|
|
/** Fetch all project path mappings for a node */
|
|
export function fetchNodePathMappings(nodeId: string): Promise<ProjectNodePathMapping[]> {
|
|
return api<ProjectNodePathMapping[]>(`/nodes/${encodeURIComponent(nodeId)}/path-mappings`);
|
|
}
|
|
|
|
/** Update an existing node */
|
|
export function updateNode(id: string, updates: NodeUpdateInput): Promise<NodeInfo> {
|
|
return api<NodeInfo>(`/nodes/${encodeURIComponent(id)}`, {
|
|
method: "PATCH",
|
|
body: JSON.stringify(updates),
|
|
});
|
|
}
|
|
|
|
/** Fetch sanitized docker config for a node */
|
|
export function fetchDockerNodeConfig(nodeId: string): Promise<DockerNodeConfigInfo | null> {
|
|
return api<DockerNodeConfigInfo | null>(`/nodes/${encodeURIComponent(nodeId)}/docker-config`);
|
|
}
|
|
|
|
/** Replace full docker config for a node */
|
|
export function replaceDockerNodeConfig(nodeId: string, config: DockerNodeConfig): Promise<DockerNodeConfigInfo> {
|
|
return api<DockerNodeConfigInfo>(`/nodes/${encodeURIComponent(nodeId)}/docker-config`, {
|
|
method: "PUT",
|
|
body: JSON.stringify(config),
|
|
});
|
|
}
|
|
|
|
/** Patch docker config for a node */
|
|
export function updateDockerNodeConfig(nodeId: string, config: Partial<DockerNodeConfig>): Promise<DockerNodeConfigInfo> {
|
|
return api<DockerNodeConfigInfo>(`/nodes/${encodeURIComponent(nodeId)}/docker-config`, {
|
|
method: "PATCH",
|
|
body: JSON.stringify(config),
|
|
});
|
|
}
|
|
|
|
/** Fetch docker config diff status for a node */
|
|
export function fetchDockerConfigDiff(nodeId: string): Promise<{
|
|
persistedVersion: number;
|
|
deployedVersion: number | null;
|
|
needsRecreate: boolean;
|
|
}> {
|
|
return api<{ persistedVersion: number; deployedVersion: number | null; needsRecreate: boolean }>(
|
|
`/nodes/${encodeURIComponent(nodeId)}/docker-config/diff`,
|
|
);
|
|
}
|
|
|
|
/** Unregister a node */
|
|
export function unregisterNode(id: string): Promise<void> {
|
|
return api<void>(`/nodes/${encodeURIComponent(id)}`, {
|
|
method: "DELETE",
|
|
});
|
|
}
|
|
|
|
/** Trigger a node health check */
|
|
export async function checkNodeHealth(id: string): Promise<NodeHealthCheckResult> {
|
|
const result = await api<Partial<NodeHealthCheckResult> & { status: NodeStatus }>(`/nodes/${encodeURIComponent(id)}/health-check`, {
|
|
method: "POST",
|
|
});
|
|
|
|
return {
|
|
nodeId: result.nodeId ?? id,
|
|
status: result.status,
|
|
responseTimeMs: result.responseTimeMs,
|
|
error: result.error,
|
|
checkedAt: result.checkedAt ?? new Date().toISOString(),
|
|
};
|
|
}
|
|
|
|
/** Fetch runtime metrics for a node */
|
|
export async function fetchNodeMetrics(id: string): Promise<SystemMetrics | null> {
|
|
return api<SystemMetrics | null>(`/nodes/${encodeURIComponent(id)}/metrics`);
|
|
}
|
|
|
|
/** Fetch full mesh topology state (all nodes with their metrics and known peers) */
|
|
export async function fetchMeshState(): Promise<MeshClusterSnapshot> {
|
|
return api<MeshClusterSnapshot>("/mesh/state");
|
|
}
|
|
|
|
/*
|
|
* FNXC:MeshSharedPg 2026-06-25-00:00:
|
|
* With the mesh on shared PostgreSQL, the dashboard needs to surface which
|
|
* engines are actively connected to the shared DB, their in-flight tasks, and
|
|
* heartbeat status. GET /api/mesh/engines joins the local engineManager with
|
|
* the central node registry and per-project health. The shape matches the
|
|
* MeshTopology `engines` prop (MeshEngineStatus) so the dashboard can render it
|
|
* without transformation.
|
|
*/
|
|
export interface MeshEnginesResponse {
|
|
collectedAt: string;
|
|
backend: string;
|
|
engines: MeshEngineStatusApi[];
|
|
}
|
|
|
|
/** Per-engine status entry returned by GET /api/mesh/engines. Mirrors MeshEngineStatus. */
|
|
export interface MeshEngineStatusApi {
|
|
projectId: string;
|
|
projectName?: string;
|
|
projectPath?: string;
|
|
workingDirectory?: string;
|
|
runtimeStatus: string;
|
|
inFlightTasks: number;
|
|
activeAgents: number;
|
|
lastActivityAt?: string;
|
|
memoryBytes?: number;
|
|
nodeId?: string;
|
|
}
|
|
|
|
/** Fetch active engine connections reading from shared PG (GET /api/mesh/engines). */
|
|
export async function fetchMeshEngines(): Promise<MeshEnginesResponse> {
|
|
return api<MeshEnginesResponse>("/mesh/engines");
|
|
}
|
|
|
|
/** Browse directory entries for the directory picker */
|
|
export interface BrowseDirectoryResult {
|
|
currentPath: string;
|
|
parentPath: string | null;
|
|
entries: Array<{ name: string; path: string; hasChildren: boolean }>;
|
|
}
|
|
|
|
export function browseDirectory(
|
|
path?: string,
|
|
showHidden?: boolean,
|
|
nodeId?: string,
|
|
localNodeId?: string,
|
|
): Promise<BrowseDirectoryResult> {
|
|
const effectiveNodeId = nodeId && nodeId !== localNodeId ? nodeId : undefined;
|
|
const params = new URLSearchParams();
|
|
if (path) params.set("path", path);
|
|
if (showHidden) params.set("showHidden", "true");
|
|
if (effectiveNodeId) params.set("nodeId", effectiveNodeId);
|
|
const token = getAuthToken();
|
|
if (token) {
|
|
params.set("fn_token", token);
|
|
}
|
|
const qs = params.toString();
|
|
const fullPath = `/browse-directory${qs ? `?${qs}` : ""}`;
|
|
return api<BrowseDirectoryResult>(fullPath);
|
|
}
|
|
|
|
/** Create a new directory */
|
|
export function createDirectory(path: string): Promise<{ success: true; path: string }> {
|
|
return api<{ success: true; path: string }>("/create-directory", {
|
|
method: "POST",
|
|
body: JSON.stringify({ path }),
|
|
});
|
|
}
|
|
|
|
/** Register a new project */
|
|
export function registerProject(input: ProjectCreateInput): Promise<ProjectInfo> {
|
|
return api<ProjectInfo>("/projects", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
/** Detect git sub-repos in a directory (workspace mode detection) */
|
|
export function detectWorkspace(path: string): Promise<{ repos: string[]; isWorkspace: boolean }> {
|
|
return api<{ repos: string[]; isWorkspace: boolean }>("/projects/detect-workspace", {
|
|
method: "POST",
|
|
body: JSON.stringify({ path }),
|
|
});
|
|
}
|
|
|
|
/** Unregister a project */
|
|
export function unregisterProject(id: string): Promise<void> {
|
|
return api<void>(`/projects/${encodeURIComponent(id)}`, {
|
|
method: "DELETE",
|
|
});
|
|
}
|
|
|
|
/** Fetch all per-node path mappings for a project */
|
|
export function fetchProjectPathMappings(projectId: string): Promise<ProjectNodePathMapping[]> {
|
|
return api<ProjectNodePathMapping[]>(`/projects/${encodeURIComponent(projectId)}/path-mappings`);
|
|
}
|
|
|
|
/** Fetch a single project-node path mapping */
|
|
export function fetchProjectPathMapping(projectId: string, nodeId: string): Promise<ProjectNodePathMapping> {
|
|
return api<ProjectNodePathMapping>(
|
|
`/projects/${encodeURIComponent(projectId)}/path-mappings/${encodeURIComponent(nodeId)}`,
|
|
);
|
|
}
|
|
|
|
/** Create or update a project-node path mapping */
|
|
export function upsertProjectPathMapping(
|
|
projectId: string,
|
|
nodeId: string,
|
|
path: string,
|
|
): Promise<ProjectNodePathMapping> {
|
|
return api<ProjectNodePathMapping>(
|
|
`/projects/${encodeURIComponent(projectId)}/path-mappings/${encodeURIComponent(nodeId)}`,
|
|
{
|
|
method: "PUT",
|
|
body: JSON.stringify({ path }),
|
|
},
|
|
);
|
|
}
|
|
|
|
/** Remove a project-node path mapping */
|
|
export function removeProjectPathMapping(projectId: string, nodeId: string): Promise<void> {
|
|
return api<void>(
|
|
`/projects/${encodeURIComponent(projectId)}/path-mappings/${encodeURIComponent(nodeId)}`,
|
|
{
|
|
method: "DELETE",
|
|
},
|
|
);
|
|
}
|
|
|
|
/** Fetch health metrics for a specific project */
|
|
export function fetchProjectHealth(id: string): Promise<ProjectHealth> {
|
|
return api<ProjectHealth>(`/projects/${encodeURIComponent(id)}/health`);
|
|
}
|
|
|
|
export function fetchCodebaseMetrics(id: string): Promise<CodebaseMetrics> {
|
|
return api<CodebaseMetrics>(`/projects/${encodeURIComponent(id)}/codebase-metrics`);
|
|
}
|
|
|
|
/** Fetch executor statistics for the status bar.
|
|
*
|
|
* Returns settings-based values and lastActivityAt.
|
|
* Counts are derived client-side from the tasks array.
|
|
*/
|
|
export function fetchExecutorStats(projectId?: string): Promise<{
|
|
globalPause: boolean;
|
|
enginePaused: boolean;
|
|
maxConcurrent: number;
|
|
lastActivityAt?: string;
|
|
}> {
|
|
const path = withProjectId("/executor/stats", projectId);
|
|
return dedupe(path, () => api<{
|
|
globalPause: boolean;
|
|
enginePaused: boolean;
|
|
maxConcurrent: number;
|
|
lastActivityAt?: string;
|
|
}>(path));
|
|
}
|
|
|
|
export interface SystemStatsSnapshot {
|
|
rss: number;
|
|
heapUsed: number;
|
|
heapTotal: number;
|
|
heapLimit: number;
|
|
external: number;
|
|
arrayBuffers: number;
|
|
// Null until at least two samples are available to compute process CPU delta.
|
|
cpuPercent: number | null;
|
|
loadAvg: [number, number, number];
|
|
cpuCount: number;
|
|
systemTotalMem: number;
|
|
systemFreeMem: number;
|
|
pid: number;
|
|
nodeVersion: string;
|
|
platform: string;
|
|
}
|
|
|
|
export interface TaskStatsSnapshot {
|
|
total: number;
|
|
byColumn: Record<string, number>;
|
|
active: number;
|
|
agents: {
|
|
idle: number;
|
|
active: number;
|
|
running: number;
|
|
error: number;
|
|
};
|
|
}
|
|
|
|
export interface SystemStatsResponse {
|
|
systemStats: SystemStatsSnapshot;
|
|
taskStats: TaskStatsSnapshot;
|
|
vitestProcessCount?: number;
|
|
vitestLastAutoKillAt?: string | null;
|
|
}
|
|
|
|
export interface KillVitestResponse {
|
|
killed: number;
|
|
pids: number[];
|
|
}
|
|
|
|
export interface GithubSourceIssueClosedAtBackfillResult {
|
|
scanned: number;
|
|
filled: number;
|
|
skipped: number;
|
|
errors: number;
|
|
hasMore: boolean;
|
|
}
|
|
|
|
/*
|
|
FNXC:CommandCenter 2026-06-21-00:00:
|
|
The Command Center System area keeps the direct local /system-stats client and uses the explicit /nodes/:id/system-stats route for selected remote nodes so authenticated node proxying stays server-side and local project scoping is not forwarded across nodes.
|
|
*/
|
|
export function fetchSystemStats(projectId?: string): Promise<SystemStatsResponse> {
|
|
return api<SystemStatsResponse>(withProjectId("/system-stats", projectId));
|
|
}
|
|
|
|
export function fetchNodeSystemStats(nodeId: string, projectId?: string): Promise<SystemStatsResponse> {
|
|
return api<SystemStatsResponse>(withProjectId(`/nodes/${encodeURIComponent(nodeId)}/system-stats`, projectId));
|
|
}
|
|
|
|
export function killVitestProcesses(projectId?: string, nodeId?: string, localNodeId?: string): Promise<KillVitestResponse> {
|
|
return proxyApi<KillVitestResponse>(withProjectId("/kill-vitest", projectId), {
|
|
method: "POST",
|
|
nodeId,
|
|
localNodeId,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* FNXC:GithubSourceIssueBackfill 2026-06-18-19:20:
|
|
* Thin client for the FN-6674 manual source-issue closed-at backfill endpoint. Callers own bounded pagination until `hasMore === false`; this helper keeps the GitHub lookup in the explicit operator action path and out of analytics/render-time data loading.
|
|
*/
|
|
export function apiBackfillGithubSourceIssueClosedAt(
|
|
options: { offset?: number; limit?: number } = {},
|
|
projectId?: string,
|
|
): Promise<GithubSourceIssueClosedAtBackfillResult> {
|
|
return api<GithubSourceIssueClosedAtBackfillResult>(
|
|
withProjectId("/git/github/backfill-source-issue-closed-at", projectId),
|
|
{
|
|
method: "POST",
|
|
body: JSON.stringify({ offset: options.offset, limit: options.limit }),
|
|
},
|
|
);
|
|
}
|
|
|
|
/** Fetch unified activity feed */
|
|
export function fetchActivityFeed(options?: FeedOptions): Promise<ActivityFeedEntry[]> {
|
|
const params = new URLSearchParams();
|
|
if (options?.limit !== undefined) params.set("limit", String(options.limit));
|
|
if (options?.since) params.set("since", options.since);
|
|
if (options?.projectId) params.set("projectId", options.projectId);
|
|
if (options?.type) params.set("type", options.type);
|
|
|
|
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
return api<ActivityFeedEntry[]>(`/activity-feed${query}`);
|
|
}
|
|
|
|
/** Pause a project */
|
|
export function pauseProject(id: string): Promise<ProjectInfo> {
|
|
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}/pause`, {
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
/** Resume a paused project */
|
|
export function resumeProject(id: string): Promise<ProjectInfo> {
|
|
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}/resume`, {
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
/** Fetch first run status to detect if user needs setup wizard */
|
|
export function fetchFirstRunStatus(): Promise<FirstRunStatus> {
|
|
return api<FirstRunStatus>("/first-run-status");
|
|
}
|
|
|
|
/** Fetch detailed setup state including detected projects */
|
|
export function fetchSetupState(): Promise<SetupState> {
|
|
return api<SetupState>("/setup-state");
|
|
}
|
|
|
|
/** Complete first-run setup by registering projects */
|
|
export function completeSetup(input: CompleteSetupInput): Promise<CompleteSetupResult> {
|
|
return api<CompleteSetupResult>("/complete-setup", {
|
|
method: "POST",
|
|
body: JSON.stringify(input),
|
|
});
|
|
}
|
|
|
|
/** Fetch global concurrency state */
|
|
export function fetchGlobalConcurrency(): Promise<GlobalConcurrencyState> {
|
|
return api<GlobalConcurrencyState>("/global-concurrency");
|
|
}
|
|
|
|
/*
|
|
FNXC:CapacityModel 2026-07-30-19:40 (finishing the cross-project cap deletion):
|
|
`updateGlobalConcurrency` is DELETED. It PUT to `/api/global-concurrency`, a route removed when the
|
|
machine-wide cap went (capacity is two numbers PER PROJECT), so the only thing this client could do was
|
|
call an endpoint that no longer exists. Measured: ZERO callers — the sole reference was the barrel
|
|
re-export in `legacy.ts`, which is gone with it.
|
|
|
|
`fetchGlobalConcurrency` above SURVIVES on purpose: the GET route remains and serves live utilization
|
|
TELEMETRY ("N running, all projects") for the footer and Command Center. Nothing gates on it; it is a
|
|
read, not a limiter.
|
|
*/
|
|
|
|
/** Fetch tasks for a specific project */
|
|
export function fetchProjectTasks(projectId: string, limit?: number, offset?: number): Promise<Task[]> {
|
|
const params = new URLSearchParams();
|
|
params.set("projectId", projectId);
|
|
if (limit !== undefined) params.set("limit", String(limit));
|
|
if (offset !== undefined) params.set("offset", String(offset));
|
|
return api<Task[]>(`/tasks?${params.toString()}`);
|
|
}
|
|
|
|
/** Fetch project-specific config */
|
|
export function fetchProjectConfig(projectId: string): Promise<{ maxConcurrent: number; rootDir: string }> {
|
|
return api<{ maxConcurrent: number; rootDir: string }>(`/projects/${encodeURIComponent(projectId)}/config`);
|
|
}
|
|
|
|
/** Detected project information */
|
|
export interface DetectedProject {
|
|
path: string;
|
|
suggestedName: string;
|
|
existing: boolean;
|
|
}
|
|
|
|
/** Detect projects in a base path */
|
|
export function detectProjects(basePath?: string): Promise<{ projects: DetectedProject[] }> {
|
|
return api<{ projects: DetectedProject[] }>("/projects/detect", {
|
|
method: "POST",
|
|
body: JSON.stringify({ basePath }),
|
|
});
|
|
}
|
|
|
|
/** Fetch a single project by ID */
|
|
export function fetchProject(id: string): Promise<ProjectInfo> {
|
|
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}`);
|
|
}
|
|
|
|
/** Update an existing project */
|
|
export function updateProject(id: string, updates: Partial<ProjectInfo>): Promise<ProjectInfo> {
|
|
return api<ProjectInfo>(`/projects/${encodeURIComponent(id)}`, {
|
|
method: "PATCH",
|
|
body: JSON.stringify(updates),
|
|
});
|
|
}
|
|
|