Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(scheduler): let interactive work swap out any lower-priority run

LeoXing0d8d82652409
diff --git a/apps/node-services/src/agent/runner-gateway/model-queue.ts b/apps/node-services/src/agent/runner-gateway/model-queue.ts
index b6fd1ed7..4eec2417 100644
--- a/apps/node-services/src/agent/runner-gateway/model-queue.ts
+++ b/apps/node-services/src/agent/runner-gateway/model-queue.ts
@@ -70,9 +70,9 @@ interface EndpointState {
/**
* Admits model work per endpoint. A Run Operation, a model attempt and a
* compaction each occupy one place. Smaller priority numbers start first,
- * in arrival order within a priority. When the
- * limit exceeds one, chat, voice asks and standalone approvals may fill the
- * last place.
+ * in arrival order within a priority. When the limit exceeds one, work up to
+ * chat priority may fill the last place. When it cannot start, it asks a
+ * lower-priority Run holding a place to yield.
* The limit adapts to what finished requests report. Admission only; it
* never picks, orders or retries a Run.
*/
@@ -85,7 +85,10 @@ export class ModelQueue {
constructor(
private readonly concurrency: (endpoint: ModelEndpoint) => ConcurrencyRange,
private readonly now: () => number = Date.now,
- private readonly onInteractiveWait?: (endpoint: ModelEndpoint) => void,
+ private readonly onInteractiveWait?: (
+ endpoint: ModelEndpoint,
+ priority: number,
+ ) => void,
) {}
/** A model request on endpoint finished, whoever holds its place. */
@@ -166,17 +169,19 @@ export class ModelQueue {
return this.#lease(state, work, queuedAt);
}
- /** A newly resumable Task can yield to chat already waiting on this endpoint. */
+ /** Interactive work first in line and out of places asks for a yield, also
+ * when a Run on this endpoint has just become able to yield. */
recheckInteractiveWait(endpoint: ModelEndpoint): void {
const state = this.#endpoints.get(endpointKey(endpoint));
+ const next = state?.waiting[0];
if (
state &&
- state.active === 1 &&
- state.waiting.length &&
- this.#limit(state.key, endpoint).value === 1 &&
- state.waiting[0]!.priority <= runPriorities.chat
+ next &&
+ next.priority <= runPriorities.chat &&
+ state.active >=
+ admissionLimit(this.#limit(state.key, endpoint).value, next.priority)
)
- this.onInteractiveWait?.(endpoint);
+ this.onInteractiveWait?.(endpoint, next.priority);
}
/** The Computer is gone; work waiting for it fails with error. */
diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
index 139a2ef0..c8bea5cd 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
@@ -180,7 +180,7 @@ export class RunnerGateway
this.runtimeModels(endpoint.computerId, endpoint.runtimeType),
),
Date.now,
- (endpoint) => this.#operations.yieldTaskForChat(endpoint),
+ (endpoint, priority) => this.#operations.yieldFor(endpoint, priority),
);
this.#computerTools = new RunnerComputerTools(context, owners);
this.#localModels = new RunnerLocalModels(context, owners);
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
index ff43cf8d..e0a1b13b 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
@@ -1,4 +1,8 @@
-import type { RunKind, CapacityPriority } from "../../model-tasks.js";
+import {
+ runPriorities,
+ type RunKind,
+ type CapacityPriority,
+} from "../../model-tasks.js";
import { EventEmitter, once } from "node:events";
import { isDeepStrictEqual } from "node:util";
@@ -250,6 +254,7 @@ export class RunnerOperationState {
#terminal = false;
#cancelCommand?: OperationCancel;
readonly #delegatedTask: boolean;
+ readonly #priority: number;
#yieldSessionId?: string;
#yieldRequested = false;
#observedNativeWork = false;
@@ -303,6 +308,7 @@ export class RunnerOperationState {
}) {
this.#epoch = options.target.executionEpoch;
this.#delegatedTask = options.target.runKind === "task";
+ this.#priority = runPriorities[options.target.runKind ?? "chat"];
this.#createId = options.createId;
this.#send = options.send;
this.#cancelTimeoutMs = options.cancelTimeoutMs;
@@ -598,24 +604,35 @@ export class RunnerOperationState {
}
}
- get resumableTask(): boolean {
- // Codex announces its thread before the first task input is durably in its history.
+ /** The queue priority of the Run's kind; smaller goes first. */
+ get priority(): number {
+ return this.#priority;
+ }
+
+ get resumable(): boolean {
+ // Codex announces its thread before the first input is durably in its history.
return (
Boolean(this.#yieldSessionId) &&
(this.start.runtime_type !== "codex" || this.#observedNativeWork)
);
}
- /** Only a native terminal can hand a running Task's slot to another caller. */
- requestYield(): void {
+ /** A yield was asked and the Computer has not reported its terminal. */
+ get yielding(): boolean {
+ return this.#yieldRequested && !this.#terminal;
+ }
+
+ /** Only a native terminal can hand a running Run's place to another
+ * caller. Answers whether this call asked the Run to yield. */
+ requestYield(): boolean {
if (
- !this.resumableTask ||
+ !this.resumable ||
this.#terminal ||
this.#cancelCommand ||
this.#interactions.size ||
[...this.#pendingInputs.values()].some((input) => !input.settled)
)
- return;
+ return false;
this.#yieldRequested = true;
this.#cancelCommand = createCancel(
this.start,
@@ -624,6 +641,7 @@ export class RunnerOperationState {
);
// Reconciliation resends this exact command if the Computer disconnected.
void this.#send(this.#cancelCommand).catch(() => undefined);
+ return true;
}
retainCancellation(reason: string): void {
@@ -861,7 +879,6 @@ export class RunnerOperationState {
this.#turnId = envelope.event.turn_id;
const threadId = envelope.event.session?.threadId;
if (
- this.#delegatedTask &&
envelope.event.session?.canYield === true &&
typeof threadId === "string" &&
threadId.trim()
@@ -869,16 +886,12 @@ export class RunnerOperationState {
this.#yieldSessionId = threadId;
}
if (
- this.#delegatedTask &&
- (envelope.event.type === "tool.called" ||
- envelope.event.type === "tool.returned" ||
- envelope.event.type === "model.responded")
+ envelope.event.type === "tool.called" ||
+ envelope.event.type === "tool.returned" ||
+ envelope.event.type === "model.responded"
)
this.#observedNativeWork = true;
- if (
- this.#delegatedTask &&
- envelope.event.type === "human_interaction.requested"
- ) {
+ if (envelope.event.type === "human_interaction.requested") {
// A prompt in transit belongs to the retiring Operation and cannot be answered on its successor.
if (this.#yieldRequested) break;
if (typeof envelope.event.request.request_id === "string")
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
index 40ff074e..66430699 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
@@ -212,13 +212,11 @@ export class RunnerOperations {
};
}
if (
- hard === 1 &&
first === waiter &&
waiter.rank !== undefined &&
- rank <= runPriorities.chat &&
- active.length === 1
+ rank <= runPriorities.chat
)
- active[0]!.requestYield();
+ yieldLowerRun(active, rank);
await waitForCapacityChange(changed, signal);
}
} finally {
@@ -286,12 +284,14 @@ export class RunnerOperations {
}
}
- /** A chat waiting on the model may already hold its Computer permit. */
- yieldTaskForChat(endpoint: ModelEndpoint): void {
- for (const operation of this.activeOperations(endpoint.computerId)) {
- if (operation.start.runtime_type === endpoint.runtimeType)
- operation.requestYield();
- }
+ /** Interactive work waiting on the endpoint swaps out a lower Run there. */
+ yieldFor(endpoint: ModelEndpoint, priority: number): void {
+ yieldLowerRun(
+ this.activeOperations(endpoint.computerId).filter(
+ (operation) => operation.start.runtime_type === endpoint.runtimeType,
+ ),
+ priority,
+ );
}
/** Pins the reviewed Operation's place until its approval has settled. */
@@ -674,7 +674,7 @@ export class RunnerOperations {
);
return;
}
- const wasResumable = operation.resumableTask;
+ const wasResumable = operation.resumable;
const acknowledgement = await operation.receive(envelope);
if (
envelope.type === "operation.event" &&
@@ -692,7 +692,7 @@ export class RunnerOperations {
this.#recordRunOperation(operation);
if (
!operation.terminal &&
- operation.resumableTask &&
+ operation.resumable &&
(!wasResumable || envelope.type === "operation.input_result")
) {
this.owners.queue().recheckInteractiveWait(operationEndpoint(operation));
@@ -824,3 +824,18 @@ function operationEndpoint(operation: RunnerOperationState): ModelEndpoint {
runtimeType: operation.start.runtime_type,
};
}
+
+/**
+ * Asks the lowest-priority Run below priority that can yield to do so. One
+ * yield at a time: the place it frees goes to the waiter that asked.
+ */
+function yieldLowerRun(
+ operations: readonly RunnerOperationState[],
+ priority: number,
+): void {
+ if (operations.some((operation) => operation.yielding)) return;
+ const lower = operations
+ .filter((operation) => operation.priority > priority)
+ .sort((a, b) => b.priority - a.priority);
+ for (const operation of lower) if (operation.requestYield()) return;
+}
diff --git a/apps/node-services/src/model-tasks.ts b/apps/node-services/src/model-tasks.ts
index cb2b0c71..81abe161 100644
--- a/apps/node-services/src/model-tasks.ts
+++ b/apps/node-services/src/model-tasks.ts
@@ -27,7 +27,8 @@ export type RunKind =
| "follow_up"
| "document";
-/** Smaller priorities go first; chat and its dependencies may use the last place. */
+/** Smaller priorities go first. Work up to chat may use the last place and
+ * swaps out a running Run of a lower priority when it cannot start. */
export const runPriorities: Readonly<Record<RunKind, number>> = {
chat: 10,
task: 12,
@@ -60,6 +61,9 @@ export type CapacityPriority =
resolve(): Promise<number>;
};
+/** A question or the notes of a recording go before chat. */
+export const RECORDING_PRIORITY = 5;
+
export const COMPACTION_PRIORITY = 20;
export function softLimit(hard: number): number {
@@ -79,7 +83,8 @@ export interface ModelCallPolicy {
/** Runtime attempts of one call, a lone call or a chain's, corrections
* included. Callers do not retry a call themselves. */
readonly attempts: number;
- /** One Runtime attempt when the request names none. */
+ /** One Runtime attempt when the request names none. The Runtime counts it
+ * from the attempt's start, so waiting for a place never counts. */
readonly timeoutMs: number;
}
@@ -93,13 +98,13 @@ export const modelCallPolicies: Readonly<
timeoutMs: 15_000,
},
voice_ask: {
- priority: runPriorities.chat,
+ priority: RECORDING_PRIORITY,
interactive: true,
attempts: 1,
timeoutMs: 45_000,
},
meeting_notes: {
- priority: runPriorities.task,
+ priority: RECORDING_PRIORITY,
interactive: true,
attempts: 1,
timeoutMs: 20_000,
diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.ts
index 1264c109..a0f5a77c 100644
--- a/apps/node-services/src/runtime-model-call.ts
+++ b/apps/node-services/src/runtime-model-call.ts
@@ -727,12 +727,8 @@ async function invokeAttempt(
| undefined;
let lease: ModelLease | undefined;
const timeoutMs = call.timeoutMs ?? policy.timeoutMs;
- const deadline = policy.interactive
- ? AbortSignal.timeout(timeoutMs)
- : undefined;
- const attemptSignal = deadline ? AbortSignal.any([signal, deadline]) : signal;
try {
- if (entry.chain) lease = await entry.chain.acquire(call.key, attemptSignal);
+ if (entry.chain) lease = await entry.chain.acquire(call.key, signal);
if (call.startBefore !== undefined && Date.now() >= call.startBefore)
throw new ModelCallStartDeadlineError(
"The model step missed its start deadline",
@@ -766,7 +762,7 @@ async function invokeAttempt(
: {}),
},
...(lease ? { callLease: lease } : {}),
- signal: attemptSignal,
+ signal,
});
} catch (error) {
callLog?.finished({
@@ -778,11 +774,6 @@ async function invokeAttempt(
error: error instanceof Error ? error.message : String(error),
});
if (signal.aborted) throw signal.reason;
- if (deadline?.aborted)
- throw new ModelCallError(
- "timed_out",
- "The model call did not finish in time",
- );
if (error instanceof ModelCallStartDeadlineError) throw error;
if (error instanceof ModelCallError) {
if (error.kind === "computer_offline" && key !== undefined)
diff --git a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts b/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
index f1746242..6710ae0f 100644
--- a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts
@@ -182,7 +182,13 @@ describe("ModelQueue limit", () => {
signal,
);
const chat = await queue.acquire(codex, run(), signal);
- const notes = track(queue.acquire(codex, call("meeting_notes"), signal));
+ const task = track(
+ queue.acquire(
+ codex,
+ { kind: "task", priority: runPriorities.task, key: "t" },
+ signal,
+ ),
+ );
const doc = track(
queue.acquire(
codex,
@@ -193,7 +199,7 @@ describe("ModelQueue limit", () => {
const ask = await queue.acquire(codex, call("voice_ask"), signal);
const next = track(queue.acquire(codex, run(), signal));
await flush();
- expect([notes.value, doc.value, next.value]).toEqual([
+ expect([task.value, doc.value, next.value]).toEqual([
undefined,
undefined,
undefined,
@@ -203,13 +209,43 @@ describe("ModelQueue limit", () => {
expect(next.value).toBeDefined();
chat.release(done);
await flush();
- expect(notes.value).toBeUndefined();
+ expect(task.value).toBeUndefined();
routine.release(done);
await flush();
- expect(notes.value).toBeDefined();
+ expect(task.value).toBeDefined();
expect(doc.value).toBeUndefined();
});
+ it("asks a lower Run to yield whenever interactive work first in line cannot start", async () => {
+ const asked = vi.fn();
+ const queue = new ModelQueue(() => fixed(2), Date.now, asked);
+ const task = await queue.acquire(
+ codex,
+ { kind: "task", priority: runPriorities.task, key: "t" },
+ signal,
+ );
+ const chat = await queue.acquire(codex, run(), signal);
+ const wiki = track(queue.acquire(codex, call("wiki"), signal));
+ await flush();
+ expect(asked).not.toHaveBeenCalled();
+ const notes = track(queue.acquire(codex, call("meeting_notes"), signal));
+ await flush();
+ expect(asked).toHaveBeenLastCalledWith(
+ codex,
+ modelCallPolicies.meeting_notes.priority,
+ );
+ task.release(done);
+ await flush();
+ expect(notes.value).toBeDefined();
+ expect(wiki.value).toBeUndefined();
+ asked.mockClear();
+ notes.value!.release(done);
+ chat.release(done);
+ await flush();
+ expect(wiki.value).toBeDefined();
+ expect(asked).not.toHaveBeenCalled();
+ });
+
it("tries one more unit while work waits and requests stay as fast", async () => {
const queue = new ModelQueue(() => ({ initial: 1, max: 3 }));
await queue.acquire(codex, run("a"), signal);
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
index 633fb153..3ec7b77a 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts
@@ -215,7 +215,7 @@ describe("RunnerGateway model invocation", () => {
}
});
- it("keeps voice queued at hard one while a background call owns the endpoint", async () => {
+ it("keeps recording work queued at hard one while a background call owns the endpoint", async () => {
const { gateway, peer, connection } = await connect();
try {
const memory = gateway.invokeModel(
@@ -234,10 +234,10 @@ describe("RunnerGateway model invocation", () => {
expect(sentInvocations(peer)).toHaveLength(1);
await invoked(connection, sentInvocations(peer)[0]!);
await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));
- expect(sentInvocations(peer)[1]!.input).toBe("voice");
+ expect(sentInvocations(peer)[1]!.input).toBe("notes");
await invoked(connection, sentInvocations(peer)[1]!);
await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(3));
- expect(sentInvocations(peer)[2]!.input).toBe("notes");
+ expect(sentInvocations(peer)[2]!.input).toBe("voice");
await invoked(connection, sentInvocations(peer)[2]!);
await Promise.all([memory, notes, ask]);
} finally {
@@ -245,6 +245,87 @@ describe("RunnerGateway model invocation", () => {
}
});
+ it("swaps out a chat Run holding the only place so recording notes complete", async () => {
+ const { gateway, peer, connection } = await connect();
+ try {
+ const chat = await gateway.startOperation({
+ ...sessionTarget(),
+ runKind: "chat",
+ });
+ const start = peer.sent.find(
+ (envelope): envelope is OperationStart =>
+ envelope.type === "operation.start",
+ )!;
+ await connection.receive(
+ event(start, 1, {
+ type: "operation.accepted",
+ command_id: start.command_id,
+ runner_pid: 100,
+ }),
+ );
+ await connection.receive(
+ event(start, 2, {
+ type: "operation.event",
+ event: {
+ type: "run.started",
+ turn_id: "turn-chat",
+ session: { threadId: "chat-session", canYield: true },
+ },
+ }),
+ );
+ await connection.receive(
+ event(start, 3, {
+ type: "operation.event",
+ event: {
+ type: "tool.called",
+ call_id: "read",
+ tool_name: "read",
+ input: {},
+ },
+ }),
+ );
+ const notes = gateway.invokeModel(
+ "runner-local",
+ request({
+ input: "notes",
+ timeoutMs: 20_000,
+ queue: queued("meeting_notes"),
+ }),
+ );
+ await vi.waitFor(() =>
+ expect(
+ peer.sent.filter((command) => command.type === "cancel"),
+ ).toHaveLength(1),
+ );
+ expect(
+ peer.sent.find((command) => command.type === "cancel"),
+ ).toMatchObject({
+ operation_id: start.operation_id,
+ reason: "scheduler_yield",
+ });
+ expect(sentInvocations(peer)).toHaveLength(0);
+ const yielded = expect(chat.result).rejects.toMatchObject({
+ session: { threadId: "chat-session" },
+ });
+ await connection.receive(
+ event(start, 4, {
+ type: "operation.cancelled",
+ reason: "scheduler_yield",
+ }),
+ );
+ await yielded;
+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));
+ expect(sentInvocations(peer)[0]).toMatchObject({
+ input: "notes",
+ timeout_ms: 20_000,
+ });
+ await invoked(connection, sentInvocations(peer)[0]!);
+ await expect(notes).resolves.toMatchObject({ outcome: "completed" });
+ } finally {
+ connection.disconnect();
+ }
+ });
+
it.each(["next step", "schema correction"] as const)(
"at one place a chat runs before the Wiki chain's %s",
async (next) => {
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
index 9660f4a9..646f1c32 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
@@ -96,9 +96,13 @@ describe("RunnerGateway", () => {
await expect(operation.result).resolves.toMatchObject({ type: "run" });
});
- it.each([1, null])(
- "waits for confirmed Task cleanup before starting chat (Computer capacity %s)",
- async (capacity) => {
+ it.each([
+ ["task", 1],
+ ["task", null],
+ ["routine", 1],
+ ] as const)(
+ "waits for confirmed %s cleanup before starting chat (Computer capacity %s)",
+ async (runKind, capacity) => {
const gateway = createTestRunnerGateway({
createId: sequenceIds(),
operationCancelTimeoutMs: 10,
@@ -111,7 +115,7 @@ describe("RunnerGateway", () => {
try {
const task = await gateway.startOperation({
...runTarget(),
- runKind: "task",
+ runKind,
});
const start = peer.sent.find(
(command) => command.type === "operation.start",
diff --git a/apps/node-services/tests/runtime-model-call.test.ts b/apps/node-services/tests/runtime-model-call.test.ts
index ec470320..ca095220 100644
--- a/apps/node-services/tests/runtime-model-call.test.ts
+++ b/apps/node-services/tests/runtime-model-call.test.ts
@@ -161,7 +161,7 @@ describe("Runtime model call", () => {
},
}),
);
- // Voice uses the interactive reserve.
+ // A recording question goes before chat.
await modelCall.text({
kind: "voice_ask",
key: "ask",
@@ -171,22 +171,33 @@ describe("Runtime model call", () => {
expect(invokeModel.mock.lastCall![1].queue).toEqual({
kind: "voice_ask",
key: "ask",
- priority: 10,
+ priority: 5,
});
});
- it("expires interactive work while waiting for model admission", async () => {
- const { modelCall, invokeModel } = setup({ invoke: hanging });
- await expect(
- modelCall.text({
- kind: "meeting_notes",
- key: "recording",
- owner: { tenantId: "tenant_1", ownerActorId: "alice" },
- input: "Notes",
- timeoutMs: 25,
- }),
- ).rejects.toMatchObject({ kind: "timed_out" });
- expect(invokeModel.mock.lastCall![1].signal.aborted).toBe(true);
+ it("does not spend an interactive call's timeout while it waits for a place", async () => {
+ let admit!: () => void;
+ const admitted = new Promise<void>((resolve) => (admit = resolve));
+ const { modelCall, invokeModel } = setup({
+ invoke: async () => {
+ await admitted;
+ return completed("Notes");
+ },
+ });
+ const notes = modelCall.text({
+ kind: "meeting_notes",
+ key: "recording",
+ owner: { tenantId: "tenant_1", ownerActorId: "alice" },
+ input: "Notes",
+ timeoutMs: 25,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ admit();
+ await expect(notes).resolves.toMatchObject({ output: "Notes" });
+ expect(invokeModel.mock.lastCall![1]).toMatchObject({
+ timeoutMs: 25,
+ queue: { priority: 5, kind: "meeting_notes" },
+ });
});
it("runs a workspace call on a named Another Me and returns its files", async () => {
diff --git a/apps/teamhub/internal/roomagent/model_call.go b/apps/teamhub/internal/roomagent/model_call.go
index a667598e..81aa8d4c 100644
--- a/apps/teamhub/internal/roomagent/model_call.go
+++ b/apps/teamhub/internal/roomagent/model_call.go
@@ -28,6 +28,11 @@ const (
transportGrace = 5 * time.Second
)
+// ModelCallWait is the longest one model call keeps its caller waiting,
+// queueing included. A foreground call fails past it; a background call
+// answers ErrModelCallPending.
+const ModelCallWait = modelCallMaxWait + transportGrace
+
var (
// ErrModelCallUnconfigured means TeamHub has no Agent Service URL or token.
ErrModelCallUnconfigured = errors.New("Agent Service model calls are not configured")
diff --git a/apps/teamhub/internal/voice/capture_quick_notes.go b/apps/teamhub/internal/voice/capture_quick_notes.go
index debc3e01..94c2c980 100644
--- a/apps/teamhub/internal/voice/capture_quick_notes.go
+++ b/apps/teamhub/internal/voice/capture_quick_notes.go
@@ -55,7 +55,7 @@ type captureQuickNotesWorker struct {
}
func (w *captureQuickNotesWorker) Timeout(*river.Job[CaptureQuickNotesArgs]) time.Duration {
- return voicequicknotes.Timeout + 10*time.Second
+ return roomagent.ModelCallWait + 30*time.Second
}
func (w *captureQuickNotesWorker) Work(ctx context.Context, job *river.Job[CaptureQuickNotesArgs]) error {
@@ -98,8 +98,6 @@ func (s *Service) composeCaptureQuickNotes(ctx context.Context, session store.Ca
if err != nil {
return voicequicknotes.Notes{}, err
}
- ctx, cancel := context.WithTimeout(ctx, voicequicknotes.Timeout+5*time.Second)
- defer cancel()
return s.quickNotes.Write(ctx, roomagent.ModelCallOwner{TenantID: session.TenantID, OwnerActorID: session.CreatedByActorID}, session.ID, transcript)
}
diff --git a/apps/teamhub/internal/voice/voice_capture_questions.go b/apps/teamhub/internal/voice/voice_capture_questions.go
index a8b4655f..75a16d80 100644
--- a/apps/teamhub/internal/voice/voice_capture_questions.go
+++ b/apps/teamhub/internal/voice/voice_capture_questions.go
@@ -19,9 +19,10 @@ import (
const (
// VoiceCaptureQuestionMaxRunes bounds a recording question.
VoiceCaptureQuestionMaxRunes = 1000
- // VoiceCaptureQuestionTimeout bounds an answer. It runs on the recorder's
- // Agent Runtime, which takes ten to fifteen seconds; the Web shows a
- // thinking state meanwhile.
+ // VoiceCaptureQuestionTimeout bounds an answer once the recorder's Agent
+ // Runtime starts it, which takes ten to fifteen seconds; the Web shows a
+ // thinking state meanwhile. Waiting for a place goes before chat and is
+ // bounded by roomagent.ModelCallWait.
VoiceCaptureQuestionTimeout = 45 * time.Second
)
@@ -94,11 +95,9 @@ func (s *Service) AskCaptureQuestion(ctx context.Context, accountID, captureID,
for index, row := range rows {
segments[index] = voicecaptureqa.Segment{StartOffsetMS: row.StartOffsetMs, EndOffsetMS: row.EndOffsetMs, Text: row.Text, Speaker: row.SpeakerID.String}
}
- answerCtx, cancel := context.WithTimeout(ctx, VoiceCaptureQuestionTimeout)
- defer cancel()
// The recorder's Agent Runtime answers.
owner := roomagent.ModelCallOwner{TenantID: capture.TenantID, OwnerActorID: capture.CreatedByActorID}
- answer, err := s.answerer.Answer(answerCtx, owner, question, segments)
+ answer, err := s.answerer.Answer(ctx, owner, question, segments)
if ctx.Err() != nil {
return httpapi.VoiceCaptureQuestion{}, ctx.Err()
}
diff --git a/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go b/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go
index f44f8bc5..e5323508 100644
--- a/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go
+++ b/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go
@@ -178,7 +178,7 @@ type modelAnswerer struct {
}
// NewAnswerer answers through a foreground Agent Service model call on the
-// owner's Agent Runtime. The timeout covers queueing and the model attempt.
+// owner's Agent Runtime. The timeout bounds the model attempt once it starts.
func NewAnswerer(models *roomagent.ModelCallClient, timeout time.Duration) Answerer {
return &modelAnswerer{models: models, timeout: timeout}
}
diff --git a/apps/teamhub/internal/voicequicknotes/voicequicknotes.go b/apps/teamhub/internal/voicequicknotes/voicequicknotes.go
index 3a75850c..2ac089c7 100644
--- a/apps/teamhub/internal/voicequicknotes/voicequicknotes.go
+++ b/apps/teamhub/internal/voicequicknotes/voicequicknotes.go
@@ -15,8 +15,9 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
)
-// Timeout bounds one model call; the recording and transcript are already
-// posted, and without notes they stay as they are.
+// Timeout bounds the model attempt once the Runtime starts it; waiting for a
+// place goes before chat. The recording and transcript are already posted,
+// and without notes they stay as they are.
const Timeout = 20 * time.Second
const (
@@ -51,7 +52,7 @@ type Writer interface {
type modelWriter struct{ models *roomagent.ModelCallClient }
-// NewWriter writes on the owner's Agent Runtime at task priority.
+// NewWriter writes on the owner's Agent Runtime ahead of chat.
func NewWriter(models *roomagent.ModelCallClient) Writer { return modelWriter{models: models} }
func (w modelWriter) Write(ctx context.Context, owner roomagent.ModelCallOwner, captureID, transcript string) (Notes, error) {
diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
index 57cc494b..a0215c1f 100644
--- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go
+++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
@@ -2043,7 +2043,7 @@ type MemoryRebuildStatusPhase string
// ModelCallEffort Reasoning effort for the Runtime's default model; omitted, low.
type ModelCallEffort string
-// ModelCallKind An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.
+// ModelCallKind An approval borrows its Run's place on the same endpoint or queues first. Recording questions and notes go before chat, can use the reserved place and swap out a running Run of lower priority. All three calls stop waiting when their caller leaves and never answer pending.
type ModelCallKind string
// ModelCallRequest defines model for ModelCallRequest.
@@ -2060,7 +2060,7 @@ type ModelCallRequest struct {
// Key Names the work, for example profile:<generation_id>. A request with the same key and the same content joins the running execution or receives its cached result; the same key with other content is a new request.
Key string `json:"key"`
- // Kind An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.
+ // Kind An approval borrows its Run's place on the same endpoint or queues first. Recording questions and notes go before chat, can use the reserved place and swap out a running Run of lower priority. All three calls stop waiting when their caller leaves and never answer pending.
Kind ModelCallKind `json:"kind"`
// Output Asks for one JSON object; omitted, the answer is text.
@@ -2086,7 +2086,7 @@ type ModelCallRequest struct {
// SessionKey Names the session a structured call belongs to. Codex answers one session's calls in one resident thread that keeps the instructions and earlier calls, so only the new input is uncached; a schema correction and a Claude call run on their own.
SessionKey *string `json:"sessionKey,omitempty"`
- // TimeoutMs The budget of one Runtime attempt, each correction getting its own; omitted, the kind's default.
+ // TimeoutMs The budget of one Runtime attempt from its start, each correction getting its own; waiting for a place does not count. Omitted, the kind's default.
TimeoutMs *int `json:"timeoutMs,omitempty"`
}
diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
index 70b620b1..fb56291b 100644
--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
@@ -672,7 +672,7 @@ export interface components {
*/
ModelCallEffort: "low" | "medium" | "high";
/**
- * @description An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.
+ * @description An approval borrows its Run's place on the same endpoint or queues first. Recording questions and notes go before chat, can use the reserved place and swap out a running Run of lower priority. All three calls stop waiting when their caller leaves and never answer pending.
* @enum {string}
*/
ModelCallKind:
@@ -719,7 +719,7 @@ export interface components {
[key: string]: unknown;
};
};
- /** @description The budget of one Runtime attempt, each correction getting its own; omitted, the kind's default. */
+ /** @description The budget of one Runtime attempt from its start, each correction getting its own; waiting for a place does not count. Omitted, the kind's default. */
timeoutMs?: number;
/** @description Names the session a structured call belongs to. Codex answers one session's calls in one resident thread that keeps the instructions and earlier calls, so only the new input is uncached; a schema correction and a Claude call run on their own. */
sessionKey?: string;
diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml
index 6e9466e4..0693498d 100644
--- a/contracts/openapi/node-services-internal/openapi.yaml
+++ b/contracts/openapi/node-services-internal/openapi.yaml
@@ -1424,9 +1424,9 @@ components:
- ModelCallKindInsight
description: >-
An approval borrows its Run's place on the same endpoint or queues first.
- Voice questions share chat priority and can use the reserved place.
- Meeting notes share task priority. All three calls stop waiting when
- their caller leaves and return a result or an error within their deadline.
+ Recording questions and notes go before chat, can use the reserved
+ place and swap out a running Run of lower priority. All three calls
+ stop waiting when their caller leaves and never answer pending.
ModelCallErrorCode:
type: string
description: Stable error codes of POST /v1/model-calls.
@@ -1505,8 +1505,9 @@ components:
minimum: 1000
maximum: 600000
description:
- The budget of one Runtime attempt, each correction getting its
- own; omitted, the kind's default.
+ The budget of one Runtime attempt from its start, each correction
+ getting its own; waiting for a place does not count. Omitted, the
+ kind's default.
sessionKey:
type: string
minLength: 1
diff --git a/docs/model-scheduling.md b/docs/model-scheduling.md
index 7f102724..aa65a0af 100644
--- a/docs/model-scheduling.md
+++ b/docs/model-scheduling.md
@@ -23,32 +23,36 @@ hour. What it learns lasts until the service restarts or the runtime's models
change.
The current adaptive limit is the hard limit. Ordinary work can start while
-the total running count is below the soft limit, `max(1, hard - 1)`. Chat,
-recording questions and standalone approvals can use the last place. When
-the limit drops, new work respects the lower limit.
+the total running count is below the soft limit, `max(1, hard - 1)`.
+Recording questions and notes, chat and standalone approvals can use the last
+place. When the limit drops, new work respects the lower limit.
A Computer with an explicit Operation capacity also reserves its last place
for an interactive Run when that capacity exceeds one.
-| Work in priority order | Unit |
-| ---------------------------- | --------------------------------------------------------------------------------------------------- |
-| Tool approval | The review borrows the reviewed Run's place on the same endpoint. A standalone review queues first. |
-| Chat and recording questions | A chat Run or a question in a recording's Ask tab. |
-| Tasks and documents | Tasks, task callbacks, agent messages, document Runs and recording notes share one priority. |
-| Scheduled and proactive work | Routines, proactive Runs and automatic follow-ups share one priority. |
-| Compaction | An idle conversation's session compaction. New work for that conversation cancels it. |
-| Background | Agent memory, user memory, profile, insights and wiki refresh, in descending priority. |
+| Work in priority order | Unit |
+| ----------------------------- | --------------------------------------------------------------------------------------------------- |
+| Tool approval | The review borrows the reviewed Run's place on the same endpoint. A standalone review queues first. |
+| Recording questions and notes | A question in a recording's Ask tab, and the quick notes written when a recording ends. |
+| Chat | A chat Run. |
+| Tasks and documents | Tasks, task callbacks, agent messages and document Runs share one priority. |
+| Scheduled and proactive work | Routines, proactive Runs and automatic follow-ups share one priority. |
+| Compaction | An idle conversation's session compaction. New work for that conversation cancels it. |
+| Background | Agent memory, user memory, profile, insights and wiki refresh, in descending priority. |
-When a delegated Task occupies the only place on its endpoint or Computer,
-a waiting interactive request can ask it to yield once the Runtime has a
-resumable native session. On Codex, the Task must also have reached its first
-model response or tool event so that the original brief is in its history.
-Chat starts after the Computer confirms cleanup.
-The Task keeps its ID, running status and claim while it waits, and continues
-in the same session when admitted again. A user stop still ends the Task.
-A pending tool approval or human interaction is answered before yielding.
-If a yielded Task's cleanup cannot be confirmed, the Computer refuses further
+When work at chat priority or above is first in line and cannot start, it asks
+the lowest-priority running Run below it on that endpoint or Computer to yield,
+one Run at a time and at any limit. A recording question can swap out a chat,
+and a chat can swap out a Task or a routine. A Run can yield once the Runtime
+has a resumable native session. On Codex, the Run must also have reached its
+first model response or tool event so that its original input is in its
+history. A pending tool approval or human interaction is answered before
+yielding. The waiting work starts after the Computer confirms cleanup.
+The yielded Run keeps its ID, running status and claim while it waits, and
+continues in the same session when admitted again. A user stop still ends it.
+If a yielded Run's cleanup cannot be confirmed, the Computer refuses further
work on that Runtime until it restarts. Other stops only report the unknown
-cleanup.
+cleanup. A model attempt already sent and a compaction are never interrupted,
+so waiting work may still wait for one of them.
Each running Operation holds one place across its tool calls. Inputs merged
into a queued Run take the highest priority among them. Eligible work at the same priority
@@ -59,6 +63,11 @@ attempt releases its place when the Runtime answers. A waiting chat can start
before the next step, retry or correction, even at a hard limit of one. The
chain then continues with the results of its completed steps.
+Time limits count running time. A model call's timeout starts when the
+Runtime starts the attempt, so waiting for a place, also while other work was
+swapped in, does not count. A recording question or its notes may therefore
+wait for a place up to the five minutes TeamHub keeps any model call open.
+
Every model call is retried and corrected in one place. A timeout, a reply past
its length cap or a runtime failure is tried again after a pause, and an answer
that does not fit its schema or its caller's checks is sent back with the