Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: budget a large local prompt's prefill instead of letting the run look wedged (#6117)
Adam Eivy6337558bd128
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 53df823882..014f1fd1a0 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -18,6 +18,7 @@ import {MessageSquare,ExternalLink,Terminal,+ Hourglass,Send,GitBranch,GitPullRequest,@@ -385,6 +386,23 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,? 'No shell: a public-review stage always runs headless, even when you configure it onto a TUI provider — the screened PR content stays inside the sandboxed child. Watch the live output below to see what it is doing.': null;+ // Why this run can be silent for minutes and still be perfectly healthy: its+ // prompt is large and its model server is on this machine, so the whole+ // prefill happens before the child emits its first line (#6117). Only shown+ // when the server actually stamped a long-prefill budget — an absent stamp is+ // "no estimate" (a cloud run, or a pre-upgrade record), never "instant".+ const prefillBudget = agent.metadata?.localPromptBudget?.longPrefill+ && Number.isFinite(agent.metadata.localPromptBudget.prefillMs)+ ? agent.metadata.localPromptBudget+ : null;+ const prefillLabel = prefillBudget ? formatDurationMs(prefillBudget.prefillMs) : null;+ const prefillReason = prefillBudget+ ? `Large prompt (~${(prefillBudget.promptTokens ?? 0).toLocaleString()} tokens) on a local model server — expect roughly ${prefillLabel} of silent prefill before the first line of output. The run is working, not wedged.${+ prefillBudget.expectedDurationMs+ ? ` Its duration estimate was raised to ~${formatDurationMs(prefillBudget.expectedDurationMs)} to cover it.`+ : ''}`+ : null;+// Extract recent tool activity (last few tool lines) for live displayconst recentActivity = useMemo(() => {if (inactive || output.length === 0) return [];@@ -681,6 +699,15 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,<span>No shell</span></span>)}+ {!inactive && prefillReason && (+ <span+ className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-warning/20 text-port-warning whitespace-nowrap"+ title={prefillReason}+ >+ <Hourglass size={10} aria-hidden="true" className="shrink-0" />+ <span>Long prefill ~{prefillLabel}</span>+ </span>+ )}{!remote && (<buttononClick={openPromptModal}diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex f10443cd21..e01404afe2 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { render, screen, waitFor } from '@testing-library/react';+import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';import { typeSettled } from '../../../test/settledInput';@@ -415,6 +415,41 @@ describe('AgentCard missing shell explanation', () => {expect(screen.getByText('Open Shell')).toBeInTheDocument();expect(screen.queryByText('No shell')).not.toBeInTheDocument();});++ // #6117: a ~100K-token public-review envelope aimed at a model server on this+ // box spends minutes in prefill before the child emits its first line. The+ // card showed a running agent with no output and no reason for it.+ it('explains a long silent prefill and names the raised run estimate', () => {+ renderCard(running({+ executionMode: 'direct',+ localPromptBudget: {+ endpoint: 'localhost:18020',+ promptTokens: 100_000,+ prefillMs: 9 * 60_000,+ baseDurationMs: 13 * 60_000,+ expectedDurationMs: 22 * 60_000,+ longPrefill: true,+ },+ }));++ expect(screen.getByText(/Long prefill/)).toBeInTheDocument();+ expect(screen.getByTitle(/100,000 tokens/)).toBeInTheDocument();+ expect(screen.getByTitle(/duration estimate was raised/)).toBeInTheDocument();+ });++ it('stays silent when the prefill is short or the run is not on a local endpoint', () => {+ // An absent budget is "no estimate" (a cloud run, or a record written before+ // the stamp existed) — never "instant". Neither may render the chip.+ renderCard(running({+ executionMode: 'direct',+ localPromptBudget: { endpoint: 'localhost:11434', promptTokens: 2_000, prefillMs: 16_667, longPrefill: false },+ }));+ expect(screen.queryByText(/Long prefill/)).not.toBeInTheDocument();++ cleanup();+ renderCard(running({ executionMode: 'direct' }));+ expect(screen.queryByText(/Long prefill/)).not.toBeInTheDocument();+ });});// #5994: the goal-fidelity verdict — whether the run built what the task askeddiff --git a/server/lib/README.md b/server/lib/README.mdindex 14db2bdee9..7d178c5585 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -211,6 +211,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `codexAssistantExtract.js` | Strip Codex CLI banner + echoed metadata from session transcript. || `codexCliOutput.js` | Network/system error patterns for `agentErrorAnalysis.js`. || `contextBudget.js` | Context-window budgeter for editorial passes. `estimateTokens`/`estimateTokensFromChars` (chars/4), `usableInputTokens`, `manuscriptContentBudgetChars` (single-block content cap floored at a manuscript minimum so a standalone stage trims to fit a small window instead of overflowing a fixed 48–60K floor, #1488), `planManuscriptPass({ contextWindow, sections })` → `{ mode: 'whole' \| 'chunked', chunks }`. Also `fitContextToManuscriptFloor`/`capContextOverhead`/`trimContextToBudget` — trim a re-sent context block (scene map, character arcs, …) so a large reverse outline on a small window can't starve the manuscript chunk below a budget floor (#1459). Decides whole-manuscript vs chunked given a model's window. |+| `localPromptBudget.js` | What a large prompt costs to PREFILL on a model server running on this machine (#6117). `planLocalPromptBudget({ prompt, endpoint, baseDurationMs })` → `{ promptTokens, prefillMs, expectedDurationMs, longPrefill, … }`, or `null` for a cloud endpoint / no prompt to measure — a sentinel a caller must read as "no estimate", never as a small one. `estimateLocalPrefillMs` and `describeLocalPromptBudget` are the token→ms and plan→sentence halves; `LOCAL_PREFILL_TOKENS_PER_SECOND` is a deliberately pessimistic constant, since over-estimating only widens the window a healthy run gets. Never refuses a dispatch: it raises the run's duration estimate so a ~100K-token public-review envelope reads as a long silent prefill instead of a wedged run. Pure. || `ansiStrip.js` | Streaming ANSI / control-byte stripper. || `hfErrors.js` | Parse huggingface_hub gated-access errors: `isGatedRepoError(text)` classifies a failure as gated (403/restricted), `extractGatedRepo(text)` → `owner/name` (or null) for the UI's license deep-link. Shared by the image runner and MIDI transcription (LoRA trainer keeps its own regex to also match bare 401). Pure. || `hfCache.js` | HuggingFace Hub cache inspection (`inspectModelCache(repoId,{revision?})` → `{cached,sizeBytes,snapshotPath}`, `isModelCached`, `getHfCacheRoot`). Drives the inline "Available / Download" badge on the image + video gen forms. Also `verifyModelCache(repoId,{deep,revision?})` (structural safetensors-header + optional sha256 integrity check) and `repairModelCache(repoId,{deep,revision?})` (delete corrupt weight files so the download path re-fetches them) — power the "Repair model" banner. `findCachedRepoSnapshot(repoId,revision)` resolves an immutable local snapshot; `findCachedRepoFile(repoId,filename,{revision?})` resolves ONE known file without walking it, and `findCachedRepoFiles(repoId,filenames,{revision?})` is its all-or-nothing plural form (paths in request order, or `null` if ANY is missing — a caller needing several pinned files, e.g. the shards of one checkpoint, can do nothing useful with a partial set); `isSafeHfRepoRelativePath` rejects traversal/absolute dependency filenames; `verifyCachedRepoFiles` / `repairCachedRepoFiles` apply that revision-aware exact-file contract to pinned adapter pairs; and `repairCachedFile(path,{snapshotPath?})` is the containment-checked matching single-file repair. `verifySafetensorsStructure(path,size)` is the reusable header/size structural check. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 927740707a..c5327bbc11 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -359,6 +359,7 @@ export * from './localLlmDisk.js';export * from './specDecodePresets.js';export * from './llamaCppInstall.js';export * from './localModelHeuristics.js';+export * from './localPromptBudget.js';export * from './localModelAssessment.js';export * from './localModelTuning.js';export * from './modelCapabilityTests.js';diff --git a/server/lib/localPromptBudget.js b/server/lib/localPromptBudget.jsnew file mode 100644index 0000000000..0bbf8098e2--- /dev/null+++ b/server/lib/localPromptBudget.js@@ -0,0 +1,127 @@+/**+ * What a large prompt costs on a LOCAL inference endpoint (#6117).+ *+ * A public-review Stage 3 dispatch inlines the whole screened+ * `<cleared-public-review-input>` envelope, which routinely runs to ~100K+ * tokens. A hosted provider prefills that in seconds; a model server on this+ * box does not — the observed run sat silent for ~9 minutes before the child+ * emitted its first line, against a run the queue expected to take ~13 minutes+ * end to end. Nothing compared the assembled prompt against the throughput of+ * the endpoint it was about to be dispatched to, so the run either finished+ * with no margin or looked wedged the whole time it was healthy.+ *+ * This module answers that one question, and only for an endpoint on this+ * machine: how long is this prompt's prefill, and what does the run's duration+ * estimate become once that is added to it. It deliberately does NOT refuse a+ * dispatch — the user chose the local provider, and refusing would make a+ * legitimately-configured endpoint unusable for the stage. Refusal stays the+ * answer only when the prompt exceeds the model's advertised context window,+ * which is a separate, already-fatal condition the provider itself reports.+ *+ * Trimming the envelope is explicitly not an option here: the reviewer must see+ * the complete screened material, and a truncated one produces a review of a+ * partial patch.+ *+ * Pure / side-effect-free — unit-tested in localPromptBudget.test.js.+ */++import { estimateTokens } from './contextBudget.js';++/**+ * Prefill throughput assumed for a model server on this machine, in tokens per+ * second. Deliberately BELOW what the observed run measured (~100K tokens in+ * ~9 minutes ≈ 185 tok/s on a 27B local model): the number exists to keep an+ * estimate from undershooting, and an over-estimate merely widens the window a+ * healthy run is allowed, while an under-estimate re-creates the bug.+ *+ * It is a single conservative constant on purpose. A per-model measured rate+ * would be more accurate and is not needed to answer "is this prompt going to+ * cost minutes?" — the question this budget exists for.+ */+export const LOCAL_PREFILL_TOKENS_PER_SECOND = 120;++/**+ * Prefill at or above which a run is expected to be SILENT for long enough that+ * a viewer would otherwise read it as wedged. One minute: below that the card's+ * ordinary "initializing" state already covers the gap.+ */+export const LONG_PREFILL_MS = 60_000;++const positiveNumber = (value) => (Number.isFinite(value) && value > 0 ? value : null);++/**+ * Milliseconds of prefill `promptTokens` costs at `tokensPerSecond`.+ *+ * `null` — not `0` — for a non-positive/garbled token count, so "no estimate"+ * can never be mistaken for "estimated to be instant".+ */+export function estimateLocalPrefillMs(promptTokens, tokensPerSecond = LOCAL_PREFILL_TOKENS_PER_SECOND) {+ const tokens = positiveNumber(Number(promptTokens));+ const rate = positiveNumber(Number(tokensPerSecond)) ?? LOCAL_PREFILL_TOKENS_PER_SECOND;+ if (tokens === null) return null;+ return Math.ceil((tokens / rate) * 1000);+}++/**+ * What a run's duration estimate should be, given the prompt it is about to be+ * dispatched with and the endpoint that prompt lands on.+ *+ * @param {object} args+ * @param {string} args.prompt - the FULLY assembled prompt (the envelope included).+ * @param {string|null} args.endpoint - the local endpoint this run's inference+ * occupies (`localEndpointOfProvider`), or null/'' for a cloud provider.+ * @param {number|null} [args.baseDurationMs] - the run's duration estimate+ * before prefill (the learned per-task-type average). `null` = nothing+ * learned yet, which is NOT the same as "estimated at zero".+ * @param {number} [args.tokensPerSecond]+ * @returns {null | {+ * endpoint: string, promptChars: number, promptTokens: number,+ * tokensPerSecond: number, prefillMs: number,+ * baseDurationMs: number|null, expectedDurationMs: number|null,+ * longPrefill: boolean+ * }}+ * `null` when the question does not apply — a cloud endpoint, or no prompt to+ * measure. A caller must treat that as "no estimate", never as a small one.+ */+export function planLocalPromptBudget({+ prompt,+ endpoint,+ baseDurationMs = null,+ tokensPerSecond = LOCAL_PREFILL_TOKENS_PER_SECOND,+} = {}) {+ const target = typeof endpoint === 'string' ? endpoint.trim() : '';+ if (!target) return null;+ const text = typeof prompt === 'string' ? prompt : '';+ if (!text) return null;++ const rate = positiveNumber(Number(tokensPerSecond)) ?? LOCAL_PREFILL_TOKENS_PER_SECOND;+ const promptTokens = estimateTokens(text);+ const prefillMs = estimateLocalPrefillMs(promptTokens, rate);+ if (prefillMs === null) return null;++ const base = positiveNumber(Number(baseDurationMs));+ return {+ endpoint: target,+ promptChars: text.length,+ promptTokens,+ tokensPerSecond: rate,+ prefillMs,+ baseDurationMs: base === null ? null : Math.round(base),+ // The RAISED estimate: whatever the run was expected to take, plus the+ // prefill this prompt costs before the model can emit its first token.+ // Stays `null` when nothing was learned — reporting the bare prefill as the+ // whole run's estimate would understate it just as badly as the bug did.+ expectedDurationMs: base === null ? null : Math.round(base) + prefillMs,+ longPrefill: prefillMs >= LONG_PREFILL_MS,+ };+}++/** One-line, human-readable summary of a plan for a log line or a UI title. */+export function describeLocalPromptBudget(plan) {+ if (!plan) return null;+ const minutes = (ms) => `${(ms / 60000).toFixed(1)}m`;+ const expected = plan.expectedDurationMs === null+ ? 'no learned run estimate to raise'+ : `run estimate raised to ~${minutes(plan.expectedDurationMs)}`;+ return `~${plan.promptTokens} prompt tokens at ${plan.endpoint} — expect ~${minutes(plan.prefillMs)} of silent prefill before the first line (${expected})`;+}diff --git a/server/lib/localPromptBudget.test.js b/server/lib/localPromptBudget.test.jsnew file mode 100644index 0000000000..5a03d1000b--- /dev/null+++ b/server/lib/localPromptBudget.test.js@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest';+import {+ LOCAL_PREFILL_TOKENS_PER_SECOND,+ describeLocalPromptBudget,+ estimateLocalPrefillMs,+ planLocalPromptBudget,+} from './localPromptBudget.js';++// chars/4 (contextBudget's estimator), so 400K chars ≈ 100K tokens — the size+// the observed Stage 3 envelope actually reached.+const HUGE_PROMPT = 'x'.repeat(400_000);++describe('planLocalPromptBudget', () => {+ it('raises the run duration estimate by the prefill a ~100K-token prompt costs locally', () => {+ // The regression: a 412 KB envelope was dispatched to a local 27B model+ // against a ~13-minute run estimate, and spent ~9 of those minutes in a+ // silent prefill nothing had budgeted for.+ const plan = planLocalPromptBudget({+ prompt: HUGE_PROMPT,+ endpoint: 'localhost:18020',+ baseDurationMs: 13 * 60_000,+ });+ expect(plan.promptTokens).toBe(100_000);+ // Conservative by construction: at least the ~9 minutes the real run took.+ expect(plan.prefillMs).toBeGreaterThanOrEqual(9 * 60_000);+ expect(plan.longPrefill).toBe(true);+ expect(plan.expectedDurationMs).toBe(13 * 60_000 + plan.prefillMs);+ });++ it('keeps an unlearned run estimate absent instead of collapsing it to the bare prefill', () => {+ // Sentinel contract: `baseDurationMs: null` means "nothing learned yet".+ // Reporting the prefill alone as the whole run's estimate would understate+ // the run exactly as badly as having no prefill in it at all.+ const plan = planLocalPromptBudget({ prompt: HUGE_PROMPT, endpoint: 'localhost:18020' });+ expect(plan.prefillMs).toBeGreaterThan(0);+ expect(plan.baseDurationMs).toBeNull();+ expect(plan.expectedDurationMs).toBeNull();+ });++ it('answers null for a cloud endpoint and for a prompt there is nothing to measure', () => {+ // A null plan is what the card reads as "no estimate". A cloud dispatch and+ // a pre-assembly call must both land there rather than on a zero-cost plan.+ expect(planLocalPromptBudget({ prompt: HUGE_PROMPT, endpoint: null })).toBeNull();+ expect(planLocalPromptBudget({ prompt: HUGE_PROMPT, endpoint: ' ' })).toBeNull();+ expect(planLocalPromptBudget({ prompt: '', endpoint: 'localhost:18020' })).toBeNull();+ expect(planLocalPromptBudget()).toBeNull();+ });++ it('does not flag an ordinary agent prompt as a long prefill', () => {+ const plan = planLocalPromptBudget({ prompt: 'y'.repeat(8_000), endpoint: 'localhost:11434' });+ expect(plan.promptTokens).toBe(2_000);+ expect(plan.longPrefill).toBe(false);+ });+});++describe('estimateLocalPrefillMs', () => {+ it('reports no estimate — not an instant one — for a missing token count', () => {+ expect(estimateLocalPrefillMs(null)).toBeNull();+ expect(estimateLocalPrefillMs(0)).toBeNull();+ expect(estimateLocalPrefillMs(Number.NaN)).toBeNull();+ expect(estimateLocalPrefillMs(60_000)).toBe(Math.ceil((60_000 / LOCAL_PREFILL_TOKENS_PER_SECOND) * 1000));+ });++ it('falls back to the conservative default rather than dividing by a garbled rate', () => {+ expect(estimateLocalPrefillMs(1_200, 0)).toBe(estimateLocalPrefillMs(1_200));+ expect(estimateLocalPrefillMs(1_200, -5)).toBe(estimateLocalPrefillMs(1_200));+ });+});++describe('describeLocalPromptBudget', () => {+ it('names the endpoint, the prefill, and the raised estimate', () => {+ const line = describeLocalPromptBudget(planLocalPromptBudget({+ prompt: HUGE_PROMPT,+ endpoint: 'localhost:18020',+ baseDurationMs: 13 * 60_000,+ }));+ expect(line).toContain('localhost:18020');+ expect(line).toContain('100000 prompt tokens');+ expect(line).toContain('run estimate raised to');+ expect(describeLocalPromptBudget(null)).toBeNull();+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex ff5172edf7..bef6821ba7 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -81,7 +81,8 @@ import { v4 as uuidv4 } from '../lib/uuid.js';// Imported for use here only; the pass-through re-exports that used to sit// below them were retired with the `subAgentSpawner.js` barrel (#3450).import { resolveAgentProviderAndModel } from './agentProviderResolution.js';-import { cloudSwarmThreadCapacity, providerBaseUrl } from './cosLocalEndpointSlots.js';+import { cloudSwarmThreadCapacity, localEndpointOfProvider, providerBaseUrl } from './cosLocalEndpointSlots.js';+import { describeLocalPromptBudget, planLocalPromptBudget } from '../lib/localPromptBudget.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';// `releaseRetryHold` is imported STATICALLY here (the TUI/direct-CLI spawners// reach for it via `await import()` only because they sit BELOW this module and@@ -649,6 +650,44 @@ async function runAgentSpawn(task) {: basePrompt;const systemPrompt = typeof promptResult === 'string' ? null : promptResult.systemPrompt;+ // What this prompt costs to PREFILL on a model server running on this box+ // (#6117). A public-review stage inlines the whole screened envelope — ~100K+ // tokens is ordinary — and a local endpoint spends minutes on that before it+ // can emit a single line. Nothing else in the dispatch path compares the+ // assembled prompt against the throughput of the endpoint it is aimed at, so+ // the run's duration estimate was the review's estimate with none of the+ // prefill in it, and the card was indistinguishable from a wedged run.+ //+ // The dispatch is NEVER refused here: the user chose this provider, and the+ // window the prompt has to fit is the model's own context window — a+ // separate condition the provider reports for itself. All we do is raise the+ // estimate and say so.+ //+ // Cloud runs take no async hop at all: `localEndpointOfProvider` answers null+ // for anything not on this machine, and `planLocalPromptBudget` is skipped.+ const localEndpoint = localEndpointOfProvider(provider);+ const localPromptBudget = localEndpoint+ ? planLocalPromptBudget({+ prompt,+ endpoint: localEndpoint,+ // The learned per-task-type average — the estimate being raised. A+ // dynamic import for the same reason the workspace snapshot above uses+ // one: it keeps the task-learning graph out of this hot module's load+ // path, and a failed read means "nothing learned", not "zero".+ baseDurationMs: await import('./taskLearning.js')+ .then((tl) => tl.getTaskDurationEstimate(task.description))+ .then((estimate) => estimate?.estimatedDurationMs ?? null)+ .catch(() => null),+ })+ : null;+ if (localPromptBudget?.longPrefill) {+ emitLog('info', `🐢 Agent ${agentId} ${describeLocalPromptBudget(localPromptBudget)}`, {+ agentId,+ taskId: task.id,+ promptTokens: localPromptBudget.promptTokens,+ });+ }+// Create agent directoryconst agentDir = join(AGENTS_DIR, agentId);if (!existsSync(agentDir)) {@@ -729,6 +768,11 @@ async function runAgentSpawn(task) {// slot key: a slot key is null for a cloud provider, and stamping null// would re-open the mid-run-edit hole this exists to close.providerEndpoint: providerBaseUrl(provider),+ // What this run's prompt costs to prefill on a LOCAL endpoint, and the+ // duration estimate raised by it (#6117). `null` for a cloud provider and+ // for a run with nothing assembled to measure — the card must read that as+ // "no estimate", never as a small one, so it stays absent rather than 0.+ localPromptBudget,leanMode,// Whether THIS run's prompt told the agent to push, open, review, and merge// its own PR. Persisted rather than re-derived at cleanup time: the twodiff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 4343002f1e..fd25ce503b 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -868,3 +868,37 @@ describe('runAgentSpawn source — taskType normalization + claim-miss guard (isexpect(body).toContain('updateResult.error');});});++// #6117: a public-review Stage 3 dispatch inlines the whole screened envelope —+// ~100K tokens — and a model server on this box spends minutes prefilling it+// before the child emits a line. Nothing compared the assembled prompt against+// the endpoint it was aimed at, so the run's duration estimate carried none of+// that cost and the card was indistinguishable from a wedged run. The budget has+// no behavioral seam inside runAgentSpawn, so pin the two orderings that make it+// correct.+describe('runAgentSpawn source — local prompt/prefill budget (#6117)', () => {+ it('measures the FULLY assembled prompt, after the public-review envelope is appended', () => {+ // Measuring `basePrompt` would miss the envelope, which IS the ~100K tokens.+ const promptIdx = RUN_SPAWN_BODY.indexOf('formatPublicReviewInputPrompt(publicReviewPromptData)');+ const planIdx = RUN_SPAWN_BODY.indexOf('planLocalPromptBudget({');+ expect(promptIdx, 'the public-review envelope must still be appended to the prompt').toBeGreaterThan(-1);+ expect(planIdx, '`planLocalPromptBudget({` must exist inside runAgentSpawn').toBeGreaterThan(-1);+ expect(promptIdx, 'the budget must be planned AFTER the envelope is appended').toBeLessThan(planIdx);+ });++ it('only asks the question for an endpoint on this machine, and never refuses the dispatch', () => {+ // A cloud provider prefills in seconds and must take no async hop; and the+ // decision on this issue was explicitly to RAISE the estimate rather than+ // block a provider the user deliberately configured.+ expect(RUN_SPAWN_BODY).toMatch(/const\s+localEndpoint\s*=\s*localEndpointOfProvider\(provider\)\s*;/);+ expect(RUN_SPAWN_BODY).toMatch(/localEndpoint\s*\r?\n?\s*\?\s*planLocalPromptBudget\(\{/);+ expect(RUN_SPAWN_BODY, 'the budget must never turn into a blocked task')+ .not.toMatch(/localPromptBudget[\s\S]{0,200}blockedReason/);+ });++ it('stamps the budget onto the agent record so the card can explain the silence', () => {+ const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');+ const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, AGENT_LIFECYCLE_SRC.indexOf('\n });', registerIdx));+ expect(metaSlice).toMatch(/\blocalPromptBudget,/);+ });+});