Arm the target button in the composer and the next prompt becomes a goal: the server keeps the session working toward it (idle tick -> small-model audit -> continuation) until the objective is verifiably complete, blocked, or out of budget — even with the UI closed. Server (packages/web/server/lib/session-goal): - event-driven loop on the global SSE hub; goal state lives in session.metadata.openchamber.goal (merge-safe patches, stale-write guard by goal id), so it survives restarts and syncs to every client for free - the small-model audit (objective + last assistant turn only, language pinned to the objective) is the sole termination authority; blocked needs 3 consecutive verdicts, audit outages tolerate one unaudited continuation then stop the goal as resumable-blocked - hard stops: optional token budget, auto-continuation cap (Resume grants a fresh allowance), turn errors; user abort pauses the goal instead of blocking it, and resuming over an aborted tail nudges immediately - token accounting as a snapshot of the latest turn (input + cache.read + output), goal-relative via a creation baseline and segmented across compactions; a compaction summary skips the audit and continues - continuations reuse the session's own provider/model/agent/variant UI: - three-mode target button (arm / disarm / manage dialog), informational goal strip with inline pause/resume and an Evaluating indicator, sidebar state glyph, objective length counter (2000-char server clamp), read-only completed goals - goal entry points: composer (sessions and drafts), start-new-session- from-answer dialog, plan implement dialog (plan content becomes the objective), scheduled tasks (Run as goal + budget) - Settings -> Chat -> Goal: feature toggle + default token budget with three-layer parity (web server, client persistence, VS Code bridge); VS Code renders goal state but hides the entry points (the loop runs in the web server only) Notifications: per-turn "ready" notifications are suppressed while a goal is active; settling sends one final notification (desktop, web-push, APNs generic titles with the session name as body) honoring the completion toggle. Error/question/permission notifications are untouched. Docs: user guide (session-goals) in all 9 locales + sidebar entry, scheduled-tasks cross-reference, server module DOCUMENTATION.md.
128 lines
4.0 KiB
TypeScript
128 lines
4.0 KiB
TypeScript
import { runtimeFetch } from './runtime-fetch';
|
|
|
|
export type ScheduledTaskStatus = 'idle' | 'running' | 'success' | 'error';
|
|
|
|
export type ScheduledTask = {
|
|
id: string;
|
|
name: string;
|
|
enabled: boolean;
|
|
schedule: {
|
|
kind: 'daily' | 'weekly' | 'once' | 'cron';
|
|
times?: string[];
|
|
time?: string;
|
|
date?: string;
|
|
weekdays?: number[];
|
|
cron?: string;
|
|
timezone?: string;
|
|
};
|
|
execution: {
|
|
prompt: string;
|
|
providerID: string;
|
|
modelID: string;
|
|
variant?: string;
|
|
agent?: string;
|
|
goalEnabled?: boolean;
|
|
goalTokenBudget?: number;
|
|
};
|
|
state: {
|
|
createdAt: number;
|
|
updatedAt: number;
|
|
lastRunAt?: number;
|
|
lastStatus?: ScheduledTaskStatus;
|
|
lastError?: string;
|
|
lastDurationMs?: number;
|
|
lastSessionId?: string;
|
|
nextRunAt?: number;
|
|
};
|
|
};
|
|
|
|
const parseErrorMessage = async (response: Response, fallback: string) => {
|
|
try {
|
|
const parsed = await response.json();
|
|
if (parsed && typeof parsed.error === 'string' && parsed.error.trim().length > 0) {
|
|
return parsed.error;
|
|
}
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
return fallback;
|
|
};
|
|
|
|
const ensureProjectID = (projectID: string): string => {
|
|
const trimmed = typeof projectID === 'string' ? projectID.trim() : '';
|
|
if (!trimmed) {
|
|
throw new Error('projectId is required');
|
|
}
|
|
return trimmed;
|
|
};
|
|
|
|
export const fetchScheduledTasks = async (projectID: string): Promise<ScheduledTask[]> => {
|
|
const safeProjectID = ensureProjectID(projectID);
|
|
const response = await runtimeFetch(`/api/projects/${encodeURIComponent(safeProjectID)}/scheduled-tasks`);
|
|
if (!response.ok) {
|
|
throw new Error(await parseErrorMessage(response, 'Failed to load scheduled tasks'));
|
|
}
|
|
const parsed = await response.json().catch(() => null);
|
|
if (!parsed || !Array.isArray(parsed.tasks)) {
|
|
return [];
|
|
}
|
|
return parsed.tasks as ScheduledTask[];
|
|
};
|
|
|
|
export const upsertScheduledTask = async (projectID: string, task: Partial<ScheduledTask>): Promise<ScheduledTask[]> => {
|
|
const safeProjectID = ensureProjectID(projectID);
|
|
const response = await runtimeFetch(`/api/projects/${encodeURIComponent(safeProjectID)}/scheduled-tasks`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
accept: 'application/json',
|
|
},
|
|
body: JSON.stringify({ task }),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(await parseErrorMessage(response, 'Failed to save scheduled task'));
|
|
}
|
|
const parsed = await response.json().catch(() => null);
|
|
if (!parsed || !Array.isArray(parsed.tasks)) {
|
|
return [];
|
|
}
|
|
return parsed.tasks as ScheduledTask[];
|
|
};
|
|
|
|
export const deleteScheduledTask = async (projectID: string, taskID: string): Promise<ScheduledTask[]> => {
|
|
const safeProjectID = ensureProjectID(projectID);
|
|
const safeTaskID = ensureProjectID(taskID);
|
|
const response = await runtimeFetch(`/api/projects/${encodeURIComponent(safeProjectID)}/scheduled-tasks/${encodeURIComponent(safeTaskID)}`, {
|
|
method: 'DELETE',
|
|
headers: {
|
|
accept: 'application/json',
|
|
},
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(await parseErrorMessage(response, 'Failed to delete scheduled task'));
|
|
}
|
|
const parsed = await response.json().catch(() => null);
|
|
if (!parsed || !Array.isArray(parsed.tasks)) {
|
|
return [];
|
|
}
|
|
return parsed.tasks as ScheduledTask[];
|
|
};
|
|
|
|
export const runScheduledTaskNow = async (projectID: string, taskID: string): Promise<{ sessionId?: string }> => {
|
|
const safeProjectID = ensureProjectID(projectID);
|
|
const safeTaskID = ensureProjectID(taskID);
|
|
const response = await runtimeFetch(`/api/projects/${encodeURIComponent(safeProjectID)}/scheduled-tasks/${encodeURIComponent(safeTaskID)}/run`, {
|
|
method: 'POST',
|
|
headers: {
|
|
accept: 'application/json',
|
|
},
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(await parseErrorMessage(response, 'Failed to run scheduled task'));
|
|
}
|
|
const parsed = await response.json().catch(() => null);
|
|
return {
|
|
sessionId: typeof parsed?.sessionId === 'string' && parsed.sessionId.length > 0 ? parsed.sessionId : undefined,
|
|
};
|
|
};
|