Skip to content
34 changes: 34 additions & 0 deletions apps/api/src/services/vm-prompt-delivery-startup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Env } from '../env';

/**
* Before TaskRunner commits in_progress, placement may not have created or linked a
* workspace. Submission writers bind tasks.chat_session_id before starting the runner
* (persistVmTaskSession, reserved submissions, dispatch_task and ProjectOrchestrator).
* A follow-up in this window has nothing to wake and must wait in the existing inbox.
*
* Recovery also queues tasks: retained sleeping_at, the same history required by
* loadRecoveryContext, leaves those conversations with ensureSessionRecovery. A mere
* checkpoint row is not sleep history. Do not use execution_step or started_at here:
* startup and retry writers do not maintain those as a first-placement discriminator.
*/
export async function isVmPromptTargetStarting(
env: Env,
projectId: string,
chatSessionId: string
): Promise<boolean> {
const starting = await env.DATABASE.prepare(
`SELECT task.id
FROM tasks task
WHERE task.project_id = ? AND task.chat_session_id = ?
AND task.status IN ('draft', 'ready', 'queued', 'delegated')
AND NOT EXISTS (
SELECT 1 FROM session_snapshots snapshot
WHERE snapshot.chat_session_id = task.chat_session_id
AND snapshot.sleeping_at IS NOT NULL
)
LIMIT 1`
)
.bind(projectId, chatSessionId)
.first();
return starting !== null;
}
5 changes: 5 additions & 0 deletions apps/api/src/services/vm-prompt-delivery-target.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { classifySessionRecoveryRefusal } from './session-recovery-refusals';
import { sessionSleepClaimLeaseMs } from './session-snapshot-sleep-claim';
import { signalSessionWakeReadyBestEffort } from './session-wake-ready';
import { isSessionWakeReadyCurrent } from './session-wake-ready-authority';
import { isVmPromptTargetStarting } from './vm-prompt-delivery-startup';

/** ProjectData owns the delivery contract these describe; re-exported for worker callers. */
export type { VmPromptDeliverySourceTaskGuard, VmPromptDeliveryTarget };
Expand Down Expand Up @@ -330,6 +331,10 @@ export async function resolveVmPromptDeliveryTarget(
runSideEffectGuard
);
}
if (await isVmPromptTargetStarting(env, projectId, chatSessionId)) {
// Readiness retries preserve the attempt budget; the delivery TTL bounds this wait.
return { kind: 'retry', reason: 'Task is still starting; no workspace yet' };
}
const guarded = await runSideEffectGuard();
if (guarded) return { kind: 'guarded', result: guarded };
const recovery = await ensureSessionRecovery(env, projectId, chatSessionId, sourceTaskGuard, {
Expand Down
33 changes: 1 addition & 32 deletions apps/api/tests/workers/eviction-restored-session-prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@
* instead drive snapshot completion, node selection, provisioning/readiness and TaskRunner linking.
*/
import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config';
import {
claimDuePromptDeliveries,
type PromptDeliveryResult,
} from '@simple-agent-manager/project-data/internal/do/prompt-delivery';
import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner';
import { buildVmPromptDeliveryCapabilitiesPath } from '@simple-agent-manager/shared';
import { env, runInDurableObject, SELF } from 'cloudflare:test';
import { eq } from 'drizzle-orm';
Expand All @@ -26,7 +21,6 @@ import * as schema from '../../src/db/schema';
import type { TaskRunner, TaskRunnerState } from '../../src/durable-objects/task-runner';
import { ensureSessionLinked } from '../../src/durable-objects/task-runner/session-linking';
import type { TaskRunnerContext } from '../../src/durable-objects/task-runner/types';
import type { Env } from '../../src/env';
import {
CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS,
capacityPlacementSnapshotSqlValues,
Expand All @@ -42,7 +36,6 @@ import {
SESSION_RECOVERY_INITIAL_PROMPT,
} from '../../src/services/session-sleep-fallback-messages';
import { buildSessionSnapshotR2Key } from '../../src/services/session-snapshots';
import { DefaultVmPromptDeliveryAdapter } from '../../src/services/vm-prompt-delivery-adapter';
import { ensurePoolsWithStarterMachines } from '../helpers/capacity-pool-picks';
import {
acceptedPromptResponse,
Expand All @@ -59,6 +52,7 @@ import {
seedUser,
seedWorkspace,
} from './helpers/seed-d1';
import { runDueDelivery } from './helpers/vm-prompt-delivery';

const config = resolveDurableExecutionConfig({});
/** Captured before any test replaces it, so a second VM double cannot call into the first. */
Expand Down Expand Up @@ -222,31 +216,6 @@ async function evict(f: Fixture, interruptedWork?: boolean): Promise<void> {
expect(response.status, await response.text()).toBe(204);
}

/** One pass of the production delivery claim runner for whatever is due at `now`. */
async function runDueDelivery(f: Fixture, now = Date.now()): Promise<PromptDeliveryResult | null> {
return runInDurableObject(f.stub, async (instance, state) => {
const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now);
if (!claim) return null;
// Bindings must come from the object's own context, as in its production alarm.
const objectEnv = (instance as unknown as { env: Env }).env;
return runPromptDeliveryClaim(
state.storage.sql,
objectEnv,
config,
claim,
new DefaultVmPromptDeliveryAdapter(objectEnv),
{
projectId: f.projectId,
recalculateAlarm: async () => undefined,
broadcastEvent: () => undefined,
armIdleCleanup: () => undefined,
nudgeDeliveries: () => 0,
scheduleSummarySync: () => undefined,
}
);
});
}

/**
* Write what node selection through workspace_ready leave behind for this wake: a running
* replacement workspace on another node bound to the chat, the task delegated to it, the
Expand Down
38 changes: 2 additions & 36 deletions apps/api/tests/workers/helpers/provider-limit-restore.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
/** Real Workers restoration fixture; only external VM HTTP is doubled. */
import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config';
import {
claimDuePromptDeliveries,
type PromptDeliveryResult,
} from '@simple-agent-manager/project-data/internal/do/prompt-delivery';
import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner';
import { env, runInDurableObject, SELF } from 'cloudflare:test';
import { eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/d1';
import { expect, vi } from 'vitest';

import * as schema from '../../../src/db/schema';
import type { TaskRunner } from '../../../src/durable-objects/task-runner';
import type { Env } from '../../../src/env';
import { getSelectedAgentCredentialReference } from '../../../src/routes/credentials';
import {
CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS,
Expand All @@ -22,7 +15,6 @@ import { encrypt } from '../../../src/services/encryption';
import { signCallbackToken } from '../../../src/services/jwt';
import { resolveTaskStartPlacementCredentialAttribution } from '../../../src/services/placement-resolver';
import { resolveSessionRuntimeContract } from '../../../src/services/session-runtime-contract';
import { DefaultVmPromptDeliveryAdapter } from '../../../src/services/vm-prompt-delivery-adapter';
import { ensurePoolsWithStarterMachines } from '../../helpers/capacity-pool-picks';
import { projectStub, sqlRows, testEnv } from './agent-message-channels';
import { pauseAlarms, pauseNodeAlarms, type StateWriteHook } from './durable-alarm-control';
Expand All @@ -35,7 +27,6 @@ import {
seedUser,
seedWorkspace,
} from './seed-d1';
const config = resolveDurableExecutionConfig({});
export function taskRunner(taskId: string): DurableObjectStub<TaskRunner> {
return env.TASK_RUNNER.get(env.TASK_RUNNER.idFromName(taskId)) as DurableObjectStub<TaskRunner>;
}
Expand Down Expand Up @@ -208,33 +199,6 @@ export async function agentOnVm(taskMode: TaskMode, agentType = 'claude-code') {
};
}

/** Claim one due prompt delivery and run it through the real delivery runner. */
export async function runDueDelivery(
f: Fixture,
now = Date.now()
): Promise<PromptDeliveryResult | null> {
return runInDurableObject(f.stub, async (instance, state) => {
const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now);
if (!claim) return null;
// Bindings must come from the object's own context, as in its production alarm.
const objectEnv = (instance as unknown as { env: Env }).env;
return runPromptDeliveryClaim(
state.storage.sql,
objectEnv,
config,
claim,
new DefaultVmPromptDeliveryAdapter(objectEnv),
{
projectId: f.projectId,
recalculateAlarm: async () => undefined,
broadcastEvent: () => undefined,
armIdleCleanup: () => undefined,
nudgeDeliveries: () => 0,
scheduleSummarySync: () => undefined,
}
);
});
}
export async function taskRow(taskId: string) {
return env.DATABASE.prepare('SELECT status, execution_step FROM tasks WHERE id = ?')
.bind(taskId)
Expand Down Expand Up @@ -364,3 +328,5 @@ export async function deleteSleptWorkspace(nodeId: string, taskId: string): Prom
runtime_deletion_proof: 'vm_agent_confirmed',
});
}

export { runDueDelivery } from './vm-prompt-delivery';
38 changes: 38 additions & 0 deletions apps/api/tests/workers/helpers/vm-prompt-delivery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config';
import { claimDuePromptDeliveries } from '@simple-agent-manager/project-data/internal/do/prompt-delivery';
import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner';
import { runInDurableObject } from 'cloudflare:test';

import type { Env } from '../../../src/env';
import { DefaultVmPromptDeliveryAdapter } from '../../../src/services/vm-prompt-delivery-adapter';
import type { projectStub } from './agent-message-channels';

const config = resolveDurableExecutionConfig({});

/** Run one due claim with real object bindings and the production VM adapter. */
export async function runDueDelivery(

Check warning on line 13 in apps/api/tests/workers/helpers/vm-prompt-delivery.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Review this async function: it has no await expression.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHo9O6HvA3VFAao5XHT&open=AaHo9O6HvA3VFAao5XHT&pullRequest=2852
f: { stub: ReturnType<typeof projectStub>; projectId: string },
now = Date.now()
) {
return runInDurableObject(f.stub, async (instance, state) => {

Check warning on line 17 in apps/api/tests/workers/helpers/vm-prompt-delivery.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Review this async function: it has no await expression.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHo9O6HvA3VFAao5XHU&open=AaHo9O6HvA3VFAao5XHU&pullRequest=2852
const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now);
if (!claim) return null;
// Bindings must come from the object's own context, as in its production alarm.
const objectEnv = (instance as unknown as { env: Env }).env;
return runPromptDeliveryClaim(
state.storage.sql,
objectEnv,
config,
claim,
new DefaultVmPromptDeliveryAdapter(objectEnv),
{
projectId: f.projectId,
recalculateAlarm: async () => undefined,

Check warning on line 30 in apps/api/tests/workers/helpers/vm-prompt-delivery.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Review this async function: it has no await expression.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaHo9O6HvA3VFAao5XHV&open=AaHo9O6HvA3VFAao5XHV&pullRequest=2852
broadcastEvent: () => undefined,
armIdleCleanup: () => undefined,
nudgeDeliveries: () => 0,
scheduleSummarySync: () => undefined,
}
);
});
}
34 changes: 2 additions & 32 deletions apps/api/tests/workers/vm-prompt-delivery-sleep-claim-hold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,24 @@
* and the production delivery runner attempts it against a VM double that would accept it.
*/
import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config';
import {
claimDuePromptDeliveries,
type PromptDeliveryResult,
} from '@simple-agent-manager/project-data/internal/do/prompt-delivery';
import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner';
import { buildVmPromptDeliveryCapabilitiesPath } from '@simple-agent-manager/shared';
import { env, runInDurableObject } from 'cloudflare:test';
import { env } from 'cloudflare:test';
import { drizzle } from 'drizzle-orm/d1';
import { afterEach, describe, expect, it, vi } from 'vitest';

import * as schema from '../../src/db/schema';
import type { Env } from '../../src/env';
import { getNodeBackendBaseUrl } from '../../src/services/node-agent-readiness';
import * as projectData from '../../src/services/project-data';
import { ensureSessionSnapshotForSleep } from '../../src/services/session-snapshot-prepare';
import { claimSessionSnapshotSleep } from '../../src/services/session-snapshot-sleep-claim';
import { failSessionSnapshotSleepBeforeTeardown } from '../../src/services/session-snapshot-sleep-failure';
import { DefaultVmPromptDeliveryAdapter } from '../../src/services/vm-prompt-delivery-adapter';
import { resolveVmPromptDeliveryTarget } from '../../src/services/vm-prompt-delivery-target';
import {
acceptedPromptResponse,
versionedPromptCapabilities,
} from '../helpers/vm-prompt-delivery-fixtures';
import { inboxRows, sqlRows, testEnv, twoAgentProject } from './helpers/agent-message-channels';
import { runDueDelivery } from './helpers/vm-prompt-delivery';

const config = resolveDurableExecutionConfig({});
const RUNTIME_IDENTITY = 'sleep-claim-runtime';
Expand Down Expand Up @@ -118,30 +112,6 @@ function installVm(f: Fixture) {
return { prompts };
}

/** One pass of the production delivery claim runner for whatever is due at `now`. */
async function runDueDelivery(f: Fixture, now: number): Promise<PromptDeliveryResult | null> {
return runInDurableObject(f.stub, async (instance, state) => {
const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now);
if (!claim) return null;
const objectEnv = (instance as unknown as { env: Env }).env;
return runPromptDeliveryClaim(
state.storage.sql,
objectEnv,
config,
claim,
new DefaultVmPromptDeliveryAdapter(objectEnv),
{
projectId: f.projectId,
recalculateAlarm: async () => undefined,
broadcastEvent: () => undefined,
armIdleCleanup: () => undefined,
nudgeDeliveries: () => 0,
scheduleSummarySync: () => undefined,
}
);
});
}

async function deliveryState(f: Fixture) {
const [row] = await sqlRows<{ delivery_state: string; last_error: string | null }>(
f.stub,
Expand Down
Loading
Loading