Add cron-based scheduling with prompt templates integration (#164)
No files matched your search
@@ -55,6 +55,7 @@ For local development setup, see the [Development Guide](https://chriswritescode
|
|||||||
- **Git** — Multi-repo support, SSH authentication, worktrees, unified diffs with line numbers, PR creation
|
- **Git** — Multi-repo support, SSH authentication, worktrees, unified diffs with line numbers, PR creation
|
||||||
- **Files** — Directory browser with tree view, syntax highlighting, create/rename/delete, ZIP download
|
- **Files** — Directory browser with tree view, syntax highlighting, create/rename/delete, ZIP download
|
||||||
- **Chat** — Real-time streaming (SSE), slash commands, `@file` mentions, Plan/Build modes, Mermaid diagrams
|
- **Chat** — Real-time streaming (SSE), slash commands, `@file` mentions, Plan/Build modes, Mermaid diagrams
|
||||||
|
- **Schedules** — Recurring repo jobs with reusable prompts, run history, linked sessions, and markdown-rendered output
|
||||||
- **Audio** — Text-to-speech (browser + OpenAI-compatible), speech-to-text (browser + OpenAI-compatible)
|
- **Audio** — Text-to-speech (browser + OpenAI-compatible), speech-to-text (browser + OpenAI-compatible)
|
||||||
- **AI** — Model selection, provider config, OAuth for Anthropic/GitHub Copilot, custom agents with system prompts
|
- **AI** — Model selection, provider config, OAuth for Anthropic/GitHub Copilot, custom agents with system prompts
|
||||||
- **MCP** — Local and remote MCP server support with pre-built templates
|
- **MCP** — Local and remote MCP server support with pre-built templates
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun --watch src/index.ts",
|
"dev": "bun --watch-path src --watch src/index.ts",
|
||||||
"start": "bun src/index.ts",
|
"start": "bun src/index.ts",
|
||||||
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
"build": "bun build src/index.ts --outdir=dist --target=bun",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
"@opencode-manager/shared": "workspace:*",
|
"@opencode-manager/shared": "workspace:*",
|
||||||
"archiver": "^7.0.1",
|
"archiver": "^7.0.1",
|
||||||
"better-auth": "^1.4.17",
|
"better-auth": "^1.4.17",
|
||||||
|
"croner": "^10.0.1",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"eventsource": "^4.1.0",
|
"eventsource": "^4.1.0",
|
||||||
"hono": "^4.11.7",
|
"hono": "^4.11.7",
|
||||||
@@ -34,6 +35,7 @@
|
|||||||
"@types/bun": "latest",
|
"@types/bun": "latest",
|
||||||
"@types/eventsource": "^3.0.0",
|
"@types/eventsource": "^3.0.0",
|
||||||
"@types/web-push": "^3.6.4",
|
"@types/web-push": "^3.6.4",
|
||||||
|
"@vitest/coverage-v8": "^3.2.4",
|
||||||
"@vitest/ui": "^3.2.4",
|
"@vitest/ui": "^3.2.4",
|
||||||
"eslint": "^9.39.1",
|
"eslint": "^9.39.1",
|
||||||
"typescript-eslint": "^8.45.0",
|
"typescript-eslint": "^8.45.0",
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import type { Migration } from '../migration-runner'
|
||||||
|
|
||||||
|
const migration: Migration = {
|
||||||
|
version: 7,
|
||||||
|
name: 'schedules',
|
||||||
|
|
||||||
|
up(db) {
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS schedule_jobs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
interval_minutes INTEGER,
|
||||||
|
agent_slug TEXT,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
model TEXT,
|
||||||
|
skill_metadata TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
last_run_at INTEGER,
|
||||||
|
next_run_at INTEGER
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS schedule_runs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||||
|
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||||
|
trigger_source TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
started_at INTEGER NOT NULL,
|
||||||
|
finished_at INTEGER,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
session_id TEXT,
|
||||||
|
session_title TEXT,
|
||||||
|
log_text TEXT,
|
||||||
|
response_text TEXT,
|
||||||
|
error_text TEXT
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||||
|
},
|
||||||
|
|
||||||
|
down(db) {
|
||||||
|
db.run('DROP TABLE IF EXISTS schedule_runs')
|
||||||
|
db.run('DROP TABLE IF EXISTS schedule_jobs')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default migration
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import type { Migration } from '../migration-runner'
|
||||||
|
|
||||||
|
interface ColumnInfo {
|
||||||
|
name: string
|
||||||
|
notnull: number
|
||||||
|
dflt_value: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
const migration: Migration = {
|
||||||
|
version: 8,
|
||||||
|
name: 'schedule-cron-support',
|
||||||
|
|
||||||
|
up(db) {
|
||||||
|
const tableInfo = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||||
|
const existingColumns = new Set(tableInfo.map((column) => column.name))
|
||||||
|
const intervalMinutesColumn = tableInfo.find((column) => column.name === 'interval_minutes')
|
||||||
|
const scheduleModeColumn = tableInfo.find((column) => column.name === 'schedule_mode')
|
||||||
|
const hasCronColumns = existingColumns.has('schedule_mode') && existingColumns.has('cron_expression') && existingColumns.has('timezone')
|
||||||
|
const scheduleModeDefault = scheduleModeColumn?.dflt_value?.replaceAll("'", '')
|
||||||
|
|
||||||
|
if (intervalMinutesColumn?.notnull === 0 && hasCronColumns && scheduleModeDefault === 'interval') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE schedule_jobs_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
interval_minutes INTEGER,
|
||||||
|
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||||
|
cron_expression TEXT,
|
||||||
|
timezone TEXT,
|
||||||
|
agent_slug TEXT,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
model TEXT,
|
||||||
|
skill_metadata TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
last_run_at INTEGER,
|
||||||
|
next_run_at INTEGER
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
INSERT INTO schedule_jobs_new (
|
||||||
|
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||||
|
agent_slug, prompt, model, skill_metadata, created_at, updated_at, last_run_at, next_run_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
repo_id,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
interval_minutes,
|
||||||
|
${existingColumns.has('schedule_mode') ? "COALESCE(schedule_mode, 'interval')" : "'interval'"},
|
||||||
|
${existingColumns.has('cron_expression') ? 'cron_expression' : 'NULL'},
|
||||||
|
${existingColumns.has('timezone') ? 'timezone' : 'NULL'},
|
||||||
|
agent_slug,
|
||||||
|
prompt,
|
||||||
|
model,
|
||||||
|
skill_metadata,
|
||||||
|
created_at,
|
||||||
|
updated_at,
|
||||||
|
last_run_at,
|
||||||
|
next_run_at
|
||||||
|
FROM schedule_jobs
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run('DROP TABLE schedule_jobs')
|
||||||
|
db.run('ALTER TABLE schedule_jobs_new RENAME TO schedule_jobs')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||||
|
},
|
||||||
|
|
||||||
|
down(db) {
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE schedule_jobs_old (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
interval_minutes INTEGER NOT NULL,
|
||||||
|
agent_slug TEXT,
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
model TEXT,
|
||||||
|
skill_metadata TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
last_run_at INTEGER,
|
||||||
|
next_run_at INTEGER
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run(`
|
||||||
|
INSERT INTO schedule_jobs_old (
|
||||||
|
id, repo_id, name, description, enabled, interval_minutes, agent_slug, prompt, model, skill_metadata,
|
||||||
|
created_at, updated_at, last_run_at, next_run_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
repo_id,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
COALESCE(interval_minutes, 60),
|
||||||
|
agent_slug,
|
||||||
|
prompt,
|
||||||
|
model,
|
||||||
|
skill_metadata,
|
||||||
|
created_at,
|
||||||
|
updated_at,
|
||||||
|
last_run_at,
|
||||||
|
next_run_at
|
||||||
|
FROM schedule_jobs
|
||||||
|
`)
|
||||||
|
|
||||||
|
db.run('DROP TABLE schedule_jobs')
|
||||||
|
db.run('ALTER TABLE schedule_jobs_old RENAME TO schedule_jobs')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||||
|
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default migration
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
import type { Migration } from '../migration-runner'
|
||||||
|
|
||||||
|
const migration: Migration = {
|
||||||
|
version: 10,
|
||||||
|
name: '010-prompt-templates',
|
||||||
|
|
||||||
|
up(db) {
|
||||||
|
db.run(`
|
||||||
|
CREATE TABLE prompt_templates (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
category TEXT NOT NULL,
|
||||||
|
cadence_hint TEXT NOT NULL,
|
||||||
|
suggested_name TEXT NOT NULL,
|
||||||
|
suggested_description TEXT NOT NULL DEFAULT '',
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
prompt TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
const insert = db.prepare(`
|
||||||
|
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Repo Health Report',
|
||||||
|
'Health',
|
||||||
|
'Weekly',
|
||||||
|
'Weekly repo health report',
|
||||||
|
'Summarize code health, risk areas, and the next highest-leverage follow-ups.',
|
||||||
|
'A broad weekly review of project health, risks, and recommended next actions.',
|
||||||
|
[
|
||||||
|
'Review this repository and prepare a concise weekly health report.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- overall code health and maintainability signals',
|
||||||
|
'- risky or stale areas in the codebase',
|
||||||
|
'- flaky, fragile, or untested workflows',
|
||||||
|
'- notable recent drift in tooling, scripts, or structure',
|
||||||
|
'',
|
||||||
|
'Do not modify files or create commits.',
|
||||||
|
'',
|
||||||
|
'Return the result in these sections:',
|
||||||
|
'1. Overall Status',
|
||||||
|
'2. Key Risks',
|
||||||
|
'3. What Changed or Drifted',
|
||||||
|
'4. Recommended Next Actions',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Dependency Watchlist',
|
||||||
|
'Maintenance',
|
||||||
|
'Weekly',
|
||||||
|
'Dependency watchlist',
|
||||||
|
'Review dependency health, upgrade pressure, and risky package drift.',
|
||||||
|
'Surfaces outdated, risky, or inconsistent dependencies and upgrade priorities.',
|
||||||
|
[
|
||||||
|
'Audit this repository for dependency risk and upgrade pressure.',
|
||||||
|
'',
|
||||||
|
'Inspect package manifests, lockfiles, build tooling, runtime dependencies, and obvious version drift.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- outdated or inconsistent package versions',
|
||||||
|
'- packages that look risky, abandoned, duplicated, or unnecessary',
|
||||||
|
'- tooling mismatches that could cause local vs CI drift',
|
||||||
|
'- high-priority upgrades to tackle next',
|
||||||
|
'',
|
||||||
|
'Do not change files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Highest Priority Upgrades',
|
||||||
|
'2. Risky or Inconsistent Dependencies',
|
||||||
|
'3. Tooling Drift',
|
||||||
|
'4. Suggested Upgrade Order',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Release Readiness Review',
|
||||||
|
'Release',
|
||||||
|
'Before release',
|
||||||
|
'Release readiness review',
|
||||||
|
'Check whether the repo looks ready to ship and what could block release confidence.',
|
||||||
|
'A pre-release checkpoint for blockers, missing validation, and confidence gaps.',
|
||||||
|
[
|
||||||
|
'Review this repository for release readiness.',
|
||||||
|
'',
|
||||||
|
'Focus on anything that would reduce confidence in shipping soon, including:',
|
||||||
|
'- missing validation, tests, or smoke coverage',
|
||||||
|
'- fragile configuration or deployment assumptions',
|
||||||
|
'- unfinished, ambiguous, or risky recent work',
|
||||||
|
'- docs or scripts that appear stale relative to the implementation',
|
||||||
|
'',
|
||||||
|
'Do not edit files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Release Confidence',
|
||||||
|
'2. Blockers',
|
||||||
|
'3. Follow-ups Before Shipping',
|
||||||
|
'4. Nice-to-have Cleanup After Release',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Test Stability Audit',
|
||||||
|
'Quality',
|
||||||
|
'Weekly',
|
||||||
|
'Test stability audit',
|
||||||
|
'Find flaky areas, missing coverage signals, and brittle testing patterns.',
|
||||||
|
'Looks at test quality, slow paths, brittle coverage, and likely flaky areas.',
|
||||||
|
[
|
||||||
|
'Inspect this repository for test stability and coverage risk.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- flaky or brittle test patterns',
|
||||||
|
'- important product areas with weak or missing coverage',
|
||||||
|
'- slow or overcomplicated test flows',
|
||||||
|
'- test setup/config problems that could cause false confidence',
|
||||||
|
'',
|
||||||
|
'Do not modify files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Confidence Gaps',
|
||||||
|
'2. Flaky or Fragile Areas',
|
||||||
|
'3. Coverage Priorities',
|
||||||
|
'4. Suggested Test Improvements',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Docs Drift Review',
|
||||||
|
'Docs',
|
||||||
|
'Biweekly',
|
||||||
|
'Docs drift review',
|
||||||
|
'Check whether README, setup steps, and docs still match the current repo.',
|
||||||
|
'Finds README/setup/documentation drift relative to the actual codebase.',
|
||||||
|
[
|
||||||
|
'Review this repository for documentation drift.',
|
||||||
|
'',
|
||||||
|
'Compare README files, setup instructions, scripts, and other repo docs against the actual implementation and project structure.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- stale setup or run instructions',
|
||||||
|
'- missing documentation for important workflows',
|
||||||
|
'- docs that no longer match the codebase structure or tooling',
|
||||||
|
'- confusing or duplicated documentation',
|
||||||
|
'',
|
||||||
|
'Do not edit files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Docs That Look Stale',
|
||||||
|
'2. Missing Documentation',
|
||||||
|
'3. Confusing or Conflicting Guidance',
|
||||||
|
'4. Suggested Documentation Updates',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Tech Debt Triage',
|
||||||
|
'Planning',
|
||||||
|
'Weekly',
|
||||||
|
'Tech debt triage',
|
||||||
|
'Identify the most expensive sources of drag and rank cleanup opportunities.',
|
||||||
|
'Ranks the most valuable cleanup and refactor opportunities in the repo.',
|
||||||
|
[
|
||||||
|
'Review this repository and identify the most important technical debt to address next.',
|
||||||
|
'',
|
||||||
|
'Focus on debt that creates drag for delivery, reliability, or maintainability, such as:',
|
||||||
|
'- duplicated logic or tangled ownership',
|
||||||
|
'- brittle architecture seams',
|
||||||
|
'- outdated patterns or confusing abstractions',
|
||||||
|
'- hotspots that are hard to safely change',
|
||||||
|
'',
|
||||||
|
'Do not make changes.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Top Technical Debt Items',
|
||||||
|
'2. Why Each Item Matters',
|
||||||
|
'3. Cost vs Impact',
|
||||||
|
'4. Recommended Cleanup Order',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Security and Config Review',
|
||||||
|
'Security',
|
||||||
|
'Weekly',
|
||||||
|
'Security and config review',
|
||||||
|
'Inspect obvious security, secrets, and environment/config handling risks.',
|
||||||
|
'Looks for obvious secrets, auth, and configuration handling issues.',
|
||||||
|
[
|
||||||
|
'Inspect this repository for obvious security and configuration handling risks.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- secrets or credentials handling problems',
|
||||||
|
'- risky defaults in environment or auth configuration',
|
||||||
|
'- places where permission checks or trust assumptions look weak',
|
||||||
|
'- config sprawl that could cause unsafe deployments',
|
||||||
|
'',
|
||||||
|
'Stay read-only. Do not modify files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. High-Risk Findings',
|
||||||
|
'2. Medium-Risk Findings',
|
||||||
|
'3. Configuration Concerns',
|
||||||
|
'4. Recommended Fixes',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'CI and Ops Review',
|
||||||
|
'Operations',
|
||||||
|
'Weekly',
|
||||||
|
'CI and ops review',
|
||||||
|
'Check CI, scripts, and operational workflows for fragility or drift.',
|
||||||
|
'Surfaces friction or fragility in CI, automation, and repo operations.',
|
||||||
|
[
|
||||||
|
'Review this repository for CI, automation, and operational workflow issues.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- brittle build or test assumptions',
|
||||||
|
'- scripts that look stale, redundant, or inconsistent',
|
||||||
|
'- automation that appears slow, noisy, or easy to break',
|
||||||
|
'- workflow gaps that could hurt developer reliability',
|
||||||
|
'',
|
||||||
|
'Do not edit files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Operational Risks',
|
||||||
|
'2. CI or Automation Drift',
|
||||||
|
'3. Reliability Improvements',
|
||||||
|
'4. Highest-Leverage Next Steps',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Onboarding Brief',
|
||||||
|
'Knowledge',
|
||||||
|
'Monthly',
|
||||||
|
'Onboarding brief refresh',
|
||||||
|
'Produce a concise orientation summary for someone new to the repo.',
|
||||||
|
'Creates a concise orientation guide for engineers who are new to the repo.',
|
||||||
|
[
|
||||||
|
'Prepare an onboarding brief for an engineer who is new to this repository.',
|
||||||
|
'',
|
||||||
|
'Focus on:',
|
||||||
|
'- the repo structure and major areas of responsibility',
|
||||||
|
'- the core development workflows and important commands',
|
||||||
|
'- risky or confusing areas worth knowing early',
|
||||||
|
'- where a new engineer should start reading or exploring',
|
||||||
|
'',
|
||||||
|
'Do not modify files.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. What This Repo Does',
|
||||||
|
'2. Important Areas to Know',
|
||||||
|
'3. Local Workflow Cheatsheet',
|
||||||
|
'4. Common Pitfalls and First Reading List',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
|
||||||
|
insert.run(
|
||||||
|
'Memory Candidate Review',
|
||||||
|
'Knowledge',
|
||||||
|
'Biweekly',
|
||||||
|
'Memory candidate review',
|
||||||
|
'Identify stable conventions, decisions, and context worth preserving as memory.',
|
||||||
|
'Great for repos using durable memory or team conventions that should be captured.',
|
||||||
|
[
|
||||||
|
'Review this repository and identify durable knowledge worth preserving as long-lived memory.',
|
||||||
|
'',
|
||||||
|
'Focus on conventions, architectural decisions, recurring workflows, and stable context that future sessions should know.',
|
||||||
|
'',
|
||||||
|
'Do not create or update memory directly. Just recommend candidates.',
|
||||||
|
'',
|
||||||
|
'Return:',
|
||||||
|
'1. Candidate Conventions',
|
||||||
|
'2. Candidate Decisions',
|
||||||
|
'3. Candidate Context',
|
||||||
|
'4. Why Each Item Should Be Preserved',
|
||||||
|
].join('\n'),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
|
||||||
|
down(db) {
|
||||||
|
db.run('DROP TABLE IF EXISTS prompt_templates')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default migration
|
||||||
@@ -5,7 +5,10 @@ import migration003 from './003-repos-add-columns'
|
|||||||
import migration004 from './004-repos-indexes'
|
import migration004 from './004-repos-indexes'
|
||||||
import migration005 from './005-repos-local-path-prefix'
|
import migration005 from './005-repos-local-path-prefix'
|
||||||
import migration006 from './006-git-token-to-credentials'
|
import migration006 from './006-git-token-to-credentials'
|
||||||
|
import migration007 from './007-schedules'
|
||||||
|
import migration008 from './008-schedule-cron-support'
|
||||||
import migration009 from './009-repo-source-path'
|
import migration009 from './009-repo-source-path'
|
||||||
|
import migration010 from './009-prompt-templates'
|
||||||
|
|
||||||
export const allMigrations: Migration[] = [
|
export const allMigrations: Migration[] = [
|
||||||
migration001,
|
migration001,
|
||||||
@@ -14,5 +17,8 @@ export const allMigrations: Migration[] = [
|
|||||||
migration004,
|
migration004,
|
||||||
migration005,
|
migration005,
|
||||||
migration006,
|
migration006,
|
||||||
|
migration007,
|
||||||
|
migration008,
|
||||||
migration009,
|
migration009,
|
||||||
|
migration010,
|
||||||
]
|
]
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
import {
|
||||||
|
PromptTemplateSchema,
|
||||||
|
type PromptTemplate,
|
||||||
|
type CreatePromptTemplateRequest,
|
||||||
|
type UpdatePromptTemplateRequest,
|
||||||
|
} from '@opencode-manager/shared/schemas'
|
||||||
|
|
||||||
|
interface PromptTemplateRow {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
category: string
|
||||||
|
cadence_hint: string
|
||||||
|
suggested_name: string
|
||||||
|
suggested_description: string
|
||||||
|
description: string
|
||||||
|
prompt: string
|
||||||
|
created_at: number
|
||||||
|
updated_at: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowToPromptTemplate(row: PromptTemplateRow): PromptTemplate {
|
||||||
|
return PromptTemplateSchema.parse({
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
category: row.category,
|
||||||
|
cadenceHint: row.cadence_hint,
|
||||||
|
suggestedName: row.suggested_name,
|
||||||
|
suggestedDescription: row.suggested_description,
|
||||||
|
description: row.description,
|
||||||
|
prompt: row.prompt,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
updatedAt: row.updated_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listPromptTemplates(db: Database): PromptTemplate[] {
|
||||||
|
const rows = db.prepare('SELECT * FROM prompt_templates ORDER BY id ASC').all() as PromptTemplateRow[]
|
||||||
|
return rows.map(rowToPromptTemplate)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPromptTemplateById(db: Database, id: number): PromptTemplate | null {
|
||||||
|
const row = db.prepare('SELECT * FROM prompt_templates WHERE id = ?').get(id) as PromptTemplateRow | null
|
||||||
|
return row ? rowToPromptTemplate(row) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPromptTemplate(db: Database, data: CreatePromptTemplateRequest): PromptTemplate {
|
||||||
|
const now = Date.now()
|
||||||
|
const result = db.prepare(`
|
||||||
|
INSERT INTO prompt_templates (title, category, cadence_hint, suggested_name, suggested_description, description, prompt, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`).run(data.title, data.category, data.cadenceHint, data.suggestedName, data.suggestedDescription, data.description, data.prompt, now, now)
|
||||||
|
return getPromptTemplateById(db, result.lastInsertRowid as number)!
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updatePromptTemplate(db: Database, id: number, data: UpdatePromptTemplateRequest): PromptTemplate | null {
|
||||||
|
const existing = getPromptTemplateById(db, id)
|
||||||
|
if (!existing) return null
|
||||||
|
const now = Date.now()
|
||||||
|
db.prepare(`
|
||||||
|
UPDATE prompt_templates SET
|
||||||
|
title = ?, category = ?, cadence_hint = ?, suggested_name = ?,
|
||||||
|
suggested_description = ?, description = ?, prompt = ?, updated_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
`).run(
|
||||||
|
data.title ?? existing.title,
|
||||||
|
data.category ?? existing.category,
|
||||||
|
data.cadenceHint ?? existing.cadenceHint,
|
||||||
|
data.suggestedName ?? existing.suggestedName,
|
||||||
|
data.suggestedDescription ?? existing.suggestedDescription,
|
||||||
|
data.description ?? existing.description,
|
||||||
|
data.prompt ?? existing.prompt,
|
||||||
|
now,
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
return getPromptTemplateById(db, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deletePromptTemplate(db: Database, id: number): boolean {
|
||||||
|
const result = db.prepare('DELETE FROM prompt_templates WHERE id = ?').run(id)
|
||||||
|
return result.changes > 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
import {
|
||||||
|
ScheduleJobSchema,
|
||||||
|
ScheduleRunSchema,
|
||||||
|
ScheduleSkillMetadataSchema,
|
||||||
|
type ScheduleJob,
|
||||||
|
type ScheduleMode,
|
||||||
|
type ScheduleRun,
|
||||||
|
type ScheduleRunStatus,
|
||||||
|
type ScheduleRunTriggerSource,
|
||||||
|
} from '@opencode-manager/shared/schemas'
|
||||||
|
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||||
|
|
||||||
|
interface ScheduleJobRow {
|
||||||
|
id: number
|
||||||
|
repo_id: number
|
||||||
|
name: string
|
||||||
|
description: string | null
|
||||||
|
enabled: number
|
||||||
|
schedule_mode: ScheduleMode | null
|
||||||
|
interval_minutes: number | null
|
||||||
|
cron_expression: string | null
|
||||||
|
timezone: string | null
|
||||||
|
agent_slug: string | null
|
||||||
|
prompt: string
|
||||||
|
model: string | null
|
||||||
|
skill_metadata: string | null
|
||||||
|
created_at: number
|
||||||
|
updated_at: number
|
||||||
|
last_run_at: number | null
|
||||||
|
next_run_at: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScheduleRunRow {
|
||||||
|
id: number
|
||||||
|
job_id: number
|
||||||
|
repo_id: number
|
||||||
|
trigger_source: string
|
||||||
|
status: string
|
||||||
|
started_at: number
|
||||||
|
finished_at: number | null
|
||||||
|
created_at: number
|
||||||
|
session_id: string | null
|
||||||
|
session_title: string | null
|
||||||
|
log_text: string | null
|
||||||
|
response_text: string | null
|
||||||
|
error_text: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSkillMetadata(raw: string | null) {
|
||||||
|
if (!raw) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw)
|
||||||
|
const result = ScheduleSkillMetadataSchema.safeParse(parsed)
|
||||||
|
return result.success ? result.data : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||||
|
return ScheduleJobSchema.parse({
|
||||||
|
id: row.id,
|
||||||
|
repoId: row.repo_id,
|
||||||
|
name: row.name,
|
||||||
|
description: row.description,
|
||||||
|
enabled: Boolean(row.enabled),
|
||||||
|
scheduleMode: row.schedule_mode ?? 'interval',
|
||||||
|
intervalMinutes: row.interval_minutes,
|
||||||
|
cronExpression: row.cron_expression,
|
||||||
|
timezone: row.timezone,
|
||||||
|
agentSlug: row.agent_slug,
|
||||||
|
prompt: row.prompt,
|
||||||
|
model: row.model,
|
||||||
|
skillMetadata: parseSkillMetadata(row.skill_metadata),
|
||||||
|
createdAt: row.created_at,
|
||||||
|
updatedAt: row.updated_at,
|
||||||
|
lastRunAt: row.last_run_at,
|
||||||
|
nextRunAt: row.next_run_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
|
||||||
|
return ScheduleRunSchema.parse({
|
||||||
|
id: row.id,
|
||||||
|
jobId: row.job_id,
|
||||||
|
repoId: row.repo_id,
|
||||||
|
triggerSource: row.trigger_source,
|
||||||
|
status: row.status,
|
||||||
|
startedAt: row.started_at,
|
||||||
|
finishedAt: row.finished_at,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
sessionId: row.session_id,
|
||||||
|
sessionTitle: row.session_title,
|
||||||
|
logText: row.log_text,
|
||||||
|
responseText: row.response_text,
|
||||||
|
errorText: row.error_text,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeSkillMetadata(skillMetadata: ScheduleJobPersistenceInput['skillMetadata']): string | null {
|
||||||
|
if (!skillMetadata) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.stringify(skillMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||||
|
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||||
|
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||||
|
return rows.map(rowToScheduleJob)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listDueScheduleJobs(db: Database, now: number, limit: number = 20): ScheduleJob[] {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
SELECT * FROM schedule_jobs
|
||||||
|
WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?
|
||||||
|
ORDER BY next_run_at ASC
|
||||||
|
LIMIT ?
|
||||||
|
`)
|
||||||
|
const rows = stmt.all(now, limit) as ScheduleJobRow[]
|
||||||
|
return rows.map(rowToScheduleJob)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
|
||||||
|
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||||
|
const rows = stmt.all() as ScheduleJobRow[]
|
||||||
|
return rows.map(rowToScheduleJob)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getScheduleJobById(db: Database, repoId: number, jobId: number): ScheduleJob | null {
|
||||||
|
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||||
|
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
|
||||||
|
return row ? rowToScheduleJob(row) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createScheduleJob(db: Database, repoId: number, input: ScheduleJobPersistenceInput): ScheduleJob {
|
||||||
|
const now = Date.now()
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
INSERT INTO schedule_jobs (
|
||||||
|
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||||
|
created_at, updated_at, last_run_at, next_run_at
|
||||||
|
)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
`)
|
||||||
|
|
||||||
|
const result = stmt.run(
|
||||||
|
repoId,
|
||||||
|
input.name,
|
||||||
|
input.description ?? null,
|
||||||
|
input.enabled ? 1 : 0,
|
||||||
|
input.scheduleMode,
|
||||||
|
input.intervalMinutes,
|
||||||
|
input.cronExpression,
|
||||||
|
input.timezone,
|
||||||
|
input.agentSlug ?? null,
|
||||||
|
input.prompt,
|
||||||
|
input.model ?? null,
|
||||||
|
serializeSkillMetadata(input.skillMetadata),
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
null,
|
||||||
|
input.nextRunAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
const job = getScheduleJobById(db, repoId, Number(result.lastInsertRowid))
|
||||||
|
if (!job) {
|
||||||
|
throw new Error('Failed to load created schedule job')
|
||||||
|
}
|
||||||
|
return job
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateScheduleJob(db: Database, repoId: number, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||||
|
const existing = getScheduleJobById(db, repoId, jobId)
|
||||||
|
if (!existing) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
UPDATE schedule_jobs
|
||||||
|
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?, agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, updated_at = ?, next_run_at = ?
|
||||||
|
WHERE repo_id = ? AND id = ?
|
||||||
|
`)
|
||||||
|
|
||||||
|
stmt.run(
|
||||||
|
input.name,
|
||||||
|
input.description,
|
||||||
|
input.enabled ? 1 : 0,
|
||||||
|
input.scheduleMode,
|
||||||
|
input.intervalMinutes,
|
||||||
|
input.cronExpression,
|
||||||
|
input.timezone,
|
||||||
|
input.agentSlug,
|
||||||
|
input.prompt,
|
||||||
|
input.model,
|
||||||
|
serializeSkillMetadata(input.skillMetadata),
|
||||||
|
now,
|
||||||
|
input.nextRunAt,
|
||||||
|
repoId,
|
||||||
|
jobId,
|
||||||
|
)
|
||||||
|
|
||||||
|
return getScheduleJobById(db, repoId, jobId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
|
||||||
|
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||||
|
const result = stmt.run(repoId, jobId)
|
||||||
|
return result.changes > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reserveScheduleJobNextRun(db: Database, repoId: number, jobId: number, nextRunAt: number): void {
|
||||||
|
const stmt = db.prepare('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||||
|
stmt.run(nextRunAt, Date.now(), repoId, jobId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||||
|
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||||
|
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createScheduleRun(
|
||||||
|
db: Database,
|
||||||
|
input: {
|
||||||
|
jobId: number
|
||||||
|
repoId: number
|
||||||
|
triggerSource: ScheduleRunTriggerSource
|
||||||
|
status: ScheduleRunStatus
|
||||||
|
startedAt: number
|
||||||
|
createdAt: number
|
||||||
|
},
|
||||||
|
): ScheduleRun {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)
|
||||||
|
`)
|
||||||
|
|
||||||
|
const result = stmt.run(
|
||||||
|
input.jobId,
|
||||||
|
input.repoId,
|
||||||
|
input.triggerSource,
|
||||||
|
input.status,
|
||||||
|
input.startedAt,
|
||||||
|
input.createdAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
const run = getScheduleRunById(db, input.repoId, input.jobId, Number(result.lastInsertRowid))
|
||||||
|
if (!run) {
|
||||||
|
throw new Error('Failed to load created schedule run')
|
||||||
|
}
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateScheduleRun(
|
||||||
|
db: Database,
|
||||||
|
repoId: number,
|
||||||
|
jobId: number,
|
||||||
|
runId: number,
|
||||||
|
input: {
|
||||||
|
status: ScheduleRunStatus
|
||||||
|
finishedAt: number
|
||||||
|
sessionId?: string | null
|
||||||
|
sessionTitle?: string | null
|
||||||
|
logText?: string | null
|
||||||
|
responseText?: string | null
|
||||||
|
errorText?: string | null
|
||||||
|
},
|
||||||
|
): ScheduleRun | null {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
UPDATE schedule_runs
|
||||||
|
SET status = ?, finished_at = ?, session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||||
|
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||||
|
`)
|
||||||
|
|
||||||
|
stmt.run(
|
||||||
|
input.status,
|
||||||
|
input.finishedAt,
|
||||||
|
input.sessionId ?? null,
|
||||||
|
input.sessionTitle ?? null,
|
||||||
|
input.logText ?? null,
|
||||||
|
input.responseText ?? null,
|
||||||
|
input.errorText ?? null,
|
||||||
|
repoId,
|
||||||
|
jobId,
|
||||||
|
runId,
|
||||||
|
)
|
||||||
|
|
||||||
|
return getScheduleRunById(db, repoId, jobId, runId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateScheduleRunMetadata(
|
||||||
|
db: Database,
|
||||||
|
repoId: number,
|
||||||
|
jobId: number,
|
||||||
|
runId: number,
|
||||||
|
input: {
|
||||||
|
sessionId?: string | null
|
||||||
|
sessionTitle?: string | null
|
||||||
|
logText?: string | null
|
||||||
|
responseText?: string | null
|
||||||
|
errorText?: string | null
|
||||||
|
},
|
||||||
|
): ScheduleRun | null {
|
||||||
|
const existing = getScheduleRunById(db, repoId, jobId, runId)
|
||||||
|
if (!existing) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
UPDATE schedule_runs
|
||||||
|
SET session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||||
|
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||||
|
`)
|
||||||
|
|
||||||
|
stmt.run(
|
||||||
|
input.sessionId === undefined ? existing.sessionId : input.sessionId,
|
||||||
|
input.sessionTitle === undefined ? existing.sessionTitle : input.sessionTitle,
|
||||||
|
input.logText === undefined ? existing.logText : input.logText,
|
||||||
|
input.responseText === undefined ? existing.responseText : input.responseText,
|
||||||
|
input.errorText === undefined ? existing.errorText : input.errorText,
|
||||||
|
repoId,
|
||||||
|
jobId,
|
||||||
|
runId,
|
||||||
|
)
|
||||||
|
|
||||||
|
return getScheduleRunById(db, repoId, jobId, runId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): ScheduleRun | null {
|
||||||
|
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||||
|
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
|
||||||
|
return row ? rowToScheduleRun(row) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
SELECT * FROM schedule_runs
|
||||||
|
WHERE repo_id = ? AND job_id = ? AND status = 'running'
|
||||||
|
ORDER BY started_at DESC
|
||||||
|
LIMIT 1
|
||||||
|
`)
|
||||||
|
const row = stmt.get(repoId, jobId) as ScheduleRunRow | undefined
|
||||||
|
return row ? rowToScheduleRun(row) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRunningScheduleRuns(db: Database, limit: number = 100): ScheduleRun[] {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
SELECT * FROM schedule_runs
|
||||||
|
WHERE status = 'running'
|
||||||
|
ORDER BY started_at ASC
|
||||||
|
LIMIT ?
|
||||||
|
`)
|
||||||
|
const rows = stmt.all(limit) as ScheduleRunRow[]
|
||||||
|
return rows.map(rowToScheduleRun)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listScheduleRunsByJob(db: Database, repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||||
|
const stmt = db.prepare(`
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
job_id,
|
||||||
|
repo_id,
|
||||||
|
trigger_source,
|
||||||
|
status,
|
||||||
|
started_at,
|
||||||
|
finished_at,
|
||||||
|
created_at,
|
||||||
|
session_id,
|
||||||
|
session_title,
|
||||||
|
NULL AS log_text,
|
||||||
|
NULL AS response_text,
|
||||||
|
error_text
|
||||||
|
FROM schedule_runs
|
||||||
|
WHERE repo_id = ? AND job_id = ?
|
||||||
|
ORDER BY started_at DESC
|
||||||
|
LIMIT ?
|
||||||
|
`)
|
||||||
|
const rows = stmt.all(repoId, jobId, limit) as ScheduleRunRow[]
|
||||||
|
return rows.map(rowToScheduleRun)
|
||||||
|
}
|
||||||
@@ -37,12 +37,14 @@ import { createMcpOauthProxyRoutes } from './routes/mcp-oauth-proxy'
|
|||||||
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
|
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
|
||||||
import { createAuth } from './auth'
|
import { createAuth } from './auth'
|
||||||
import { createAuthMiddleware } from './auth/middleware'
|
import { createAuthMiddleware } from './auth/middleware'
|
||||||
|
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||||
import { sseAggregator } from './services/sse-aggregator'
|
import { sseAggregator } from './services/sse-aggregator'
|
||||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||||
import { SettingsService } from './services/settings'
|
import { SettingsService } from './services/settings'
|
||||||
import { opencodeServerManager } from './services/opencode-single-server'
|
import { opencodeServerManager } from './services/opencode-single-server'
|
||||||
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
|
import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './services/proxy'
|
||||||
import { NotificationService } from './services/notification'
|
import { NotificationService } from './services/notification'
|
||||||
|
import { ScheduleRunner, ScheduleService } from './services/schedules'
|
||||||
|
|
||||||
import { logger } from './utils/logger'
|
import { logger } from './utils/logger'
|
||||||
import {
|
import {
|
||||||
@@ -81,6 +83,7 @@ const requireAuth = createAuthMiddleware(auth)
|
|||||||
import { DEFAULT_AGENTS_MD } from './constants'
|
import { DEFAULT_AGENTS_MD } from './constants'
|
||||||
|
|
||||||
let ipcServer: IPCServer | undefined
|
let ipcServer: IPCServer | undefined
|
||||||
|
let scheduleRunnerInstance: ScheduleRunner | undefined
|
||||||
const gitAuthService = new GitAuthService()
|
const gitAuthService = new GitAuthService()
|
||||||
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
|
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
|
||||||
|
|
||||||
@@ -312,6 +315,10 @@ try {
|
|||||||
await opencodeServerManager.start()
|
await opencodeServerManager.start()
|
||||||
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
|
logger.info(`OpenCode server running on port ${opencodeServerManager.getPort()}`)
|
||||||
|
|
||||||
|
const scheduleService = new ScheduleService(db)
|
||||||
|
scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||||
|
await scheduleRunnerInstance.start()
|
||||||
|
|
||||||
await syncAdminFromEnv(auth, db)
|
await syncAdminFromEnv(auth, db)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Failed to initialize workspace:', error)
|
logger.error('Failed to initialize workspace:', error)
|
||||||
@@ -340,13 +347,13 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
|||||||
|
|
||||||
app.route('/api/auth', createAuthRoutes(auth))
|
app.route('/api/auth', createAuthRoutes(auth))
|
||||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||||
|
app.route('/api/health', createHealthRoutes(db))
|
||||||
|
|
||||||
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
|
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(requireAuth))
|
||||||
|
|
||||||
const protectedApi = new Hono()
|
const protectedApi = new Hono()
|
||||||
protectedApi.use('/*', requireAuth)
|
protectedApi.use('/*', requireAuth)
|
||||||
|
|
||||||
protectedApi.route('/health', createHealthRoutes(db))
|
|
||||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService))
|
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService))
|
||||||
protectedApi.route('/settings', createSettingsRoutes(db))
|
protectedApi.route('/settings', createSettingsRoutes(db))
|
||||||
protectedApi.route('/files', createFileRoutes())
|
protectedApi.route('/files', createFileRoutes())
|
||||||
@@ -359,6 +366,7 @@ protectedApi.route('/sse', createSSERoutes())
|
|||||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||||
protectedApi.route('/memory', createMemoryRoutes(db))
|
protectedApi.route('/memory', createMemoryRoutes(db))
|
||||||
|
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||||
|
|
||||||
app.route('/api', protectedApi)
|
app.route('/api', protectedApi)
|
||||||
|
|
||||||
@@ -461,6 +469,8 @@ const shutdown = async (signal: string) => {
|
|||||||
await ipcServer.dispose()
|
await ipcServer.dispose()
|
||||||
logger.info('Git IPC server stopped')
|
logger.info('Git IPC server stopped')
|
||||||
}
|
}
|
||||||
|
scheduleRunnerInstance?.stop()
|
||||||
|
logger.info('Schedule runner stopped')
|
||||||
await opencodeServerManager.stop()
|
await opencodeServerManager.stop()
|
||||||
logger.info('OpenCode server stopped')
|
logger.info('OpenCode server stopped')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { Hono, type Context } from 'hono'
|
||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
import {
|
||||||
|
CreatePromptTemplateRequestSchema,
|
||||||
|
UpdatePromptTemplateRequestSchema,
|
||||||
|
} from '@opencode-manager/shared/schemas'
|
||||||
|
import { PromptTemplateService, PromptTemplateServiceError } from '../services/prompt-templates'
|
||||||
|
import { getErrorMessage } from '../utils/error-utils'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
function parseId(value: string | undefined): number {
|
||||||
|
const parsed = Number.parseInt(value ?? '', 10)
|
||||||
|
if (Number.isNaN(parsed)) throw new PromptTemplateServiceError('Invalid id', 400)
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTemplateError(c: Context, error: unknown, fallback: string) {
|
||||||
|
if (error instanceof PromptTemplateServiceError) {
|
||||||
|
return c.json({ error: error.message }, error.statusCode as 400 | 404 | 500)
|
||||||
|
}
|
||||||
|
logger.error(fallback, error)
|
||||||
|
return c.json({ error: getErrorMessage(error) }, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPromptTemplateRoutes(database: Database) {
|
||||||
|
const app = new Hono()
|
||||||
|
const service = new PromptTemplateService(database)
|
||||||
|
|
||||||
|
app.get('/', (c) => {
|
||||||
|
try {
|
||||||
|
return c.json({ templates: service.list() })
|
||||||
|
} catch (error) {
|
||||||
|
return handleTemplateError(c, error, 'Failed to list templates')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/', async (c) => {
|
||||||
|
try {
|
||||||
|
const body = await c.req.json()
|
||||||
|
const input = CreatePromptTemplateRequestSchema.parse(body)
|
||||||
|
const template = service.create(input)
|
||||||
|
return c.json({ template }, 201)
|
||||||
|
} catch (error) {
|
||||||
|
return handleTemplateError(c, error, 'Failed to create template')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/:id', (c) => {
|
||||||
|
try {
|
||||||
|
const id = parseId(c.req.param('id'))
|
||||||
|
return c.json({ template: service.getById(id) })
|
||||||
|
} catch (error) {
|
||||||
|
return handleTemplateError(c, error, 'Failed to get template')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.patch('/:id', async (c) => {
|
||||||
|
try {
|
||||||
|
const id = parseId(c.req.param('id'))
|
||||||
|
const body = await c.req.json()
|
||||||
|
const input = UpdatePromptTemplateRequestSchema.parse(body)
|
||||||
|
const template = service.update(id, input)
|
||||||
|
return c.json({ template })
|
||||||
|
} catch (error) {
|
||||||
|
return handleTemplateError(c, error, 'Failed to update template')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.delete('/:id', (c) => {
|
||||||
|
try {
|
||||||
|
const id = parseId(c.req.param('id'))
|
||||||
|
service.delete(id)
|
||||||
|
return c.body(null, 204)
|
||||||
|
} catch (error) {
|
||||||
|
return handleTemplateError(c, error, 'Failed to delete template')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import { logger } from '../utils/logger'
|
|||||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||||
import { createRepoGitRoutes } from './repo-git'
|
import { createRepoGitRoutes } from './repo-git'
|
||||||
|
import { createScheduleRoutes } from './schedules'
|
||||||
import type { GitAuthService } from '../services/git-auth'
|
import type { GitAuthService } from '../services/git-auth'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
|
|
||||||
@@ -20,6 +21,7 @@ export function createRepoRoutes(database: Database, gitAuthService: GitAuthServ
|
|||||||
const app = new Hono()
|
const app = new Hono()
|
||||||
|
|
||||||
app.route('/', createRepoGitRoutes(database, gitAuthService))
|
app.route('/', createRepoGitRoutes(database, gitAuthService))
|
||||||
|
app.route('/:id/schedules', createScheduleRoutes(database))
|
||||||
|
|
||||||
app.post('/', async (c) => {
|
app.post('/', async (c) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { Hono, type Context } from 'hono'
|
||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
import {
|
||||||
|
CreateScheduleJobRequestSchema,
|
||||||
|
UpdateScheduleJobRequestSchema,
|
||||||
|
} from '@opencode-manager/shared/schemas'
|
||||||
|
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||||
|
import { getErrorMessage } from '../utils/error-utils'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
|
function parseId(value: string | undefined, label: string): number {
|
||||||
|
if (!value) {
|
||||||
|
throw new ScheduleServiceError(`Missing ${label}`, 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = Number.parseInt(value, 10)
|
||||||
|
if (Number.isNaN(parsed)) {
|
||||||
|
throw new ScheduleServiceError(`Invalid ${label}`, 400)
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRunListLimit(value: string | undefined): number {
|
||||||
|
if (value === undefined) {
|
||||||
|
return 20
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseId(value, 'limit')
|
||||||
|
if (parsed < 1) {
|
||||||
|
throw new ScheduleServiceError('Limit must be greater than 0', 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.min(parsed, 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createScheduleRoutes(database: Database) {
|
||||||
|
const app = new Hono()
|
||||||
|
const scheduleService = new ScheduleService(database)
|
||||||
|
|
||||||
|
app.get('/', (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
return c.json({ jobs: scheduleService.listJobs(repoId) })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to list schedules')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/', async (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const body = await c.req.json()
|
||||||
|
const input = CreateScheduleJobRequestSchema.parse(body)
|
||||||
|
const job = scheduleService.createJob(repoId, input)
|
||||||
|
return c.json({ job }, 201)
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to create schedule')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/:jobId', (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const job = scheduleService.getJob(repoId, jobId)
|
||||||
|
if (!job) {
|
||||||
|
return c.json({ error: 'Schedule not found' }, 404)
|
||||||
|
}
|
||||||
|
return c.json({ job })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to get schedule')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.patch('/:jobId', async (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const body = await c.req.json()
|
||||||
|
const input = UpdateScheduleJobRequestSchema.parse(body)
|
||||||
|
const job = scheduleService.updateJob(repoId, jobId, input)
|
||||||
|
return c.json({ job })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to update schedule')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.delete('/:jobId', (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
scheduleService.deleteJob(repoId, jobId)
|
||||||
|
return c.json({ success: true })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to delete schedule')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/:jobId/run', async (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const run = await scheduleService.runJob(repoId, jobId, 'manual')
|
||||||
|
return c.json({ run })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to run schedule')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/:jobId/runs', (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const limit = parseRunListLimit(c.req.query('limit'))
|
||||||
|
return c.json({ runs: scheduleService.listRuns(repoId, jobId, limit) })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to list schedule runs')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/:jobId/runs/:runId', (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const runId = parseId(c.req.param('runId'), 'run id')
|
||||||
|
return c.json({ run: scheduleService.getRun(repoId, jobId, runId) })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to get schedule run')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/:jobId/runs/:runId/cancel', async (c) => {
|
||||||
|
try {
|
||||||
|
const repoId = parseId(c.req.param('id'), 'repo id')
|
||||||
|
const jobId = parseId(c.req.param('jobId'), 'schedule id')
|
||||||
|
const runId = parseId(c.req.param('runId'), 'run id')
|
||||||
|
const run = await scheduleService.cancelRun(repoId, jobId, runId)
|
||||||
|
return c.json({ run })
|
||||||
|
} catch (error) {
|
||||||
|
return handleScheduleError(c, error, 'Failed to cancel schedule run')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleScheduleError(c: Context, error: unknown, fallbackMessage: string) {
|
||||||
|
if (error instanceof ScheduleServiceError) {
|
||||||
|
return c.json({ error: error.message }, error.status as 400 | 404 | 409 | 500 | 502)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.error(fallbackMessage + ':', error)
|
||||||
|
return c.json({ error: getErrorMessage(error) }, 500)
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { logger } from '../utils/logger'
|
import { logger } from '../utils/logger'
|
||||||
import { ENV } from '@opencode-manager/shared/config/env'
|
import { ENV } from '@opencode-manager/shared/config/env'
|
||||||
|
import { resolveOpenCodeModel } from '../services/opencode-models'
|
||||||
|
|
||||||
const TitleRequestSchema = z.object({
|
const TitleRequestSchema = z.object({
|
||||||
text: z.string().min(1).max(5000),
|
text: z.string().min(1).max(5000),
|
||||||
@@ -9,12 +10,101 @@ const TitleRequestSchema = z.object({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
|
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
|
||||||
|
const TITLE_POLL_INTERVAL_MS = 1_000
|
||||||
|
const TITLE_POLL_TIMEOUT_MS = 30_000
|
||||||
|
|
||||||
|
interface PromptResponse {
|
||||||
|
parts?: Array<{ type?: string; text?: string }>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SessionMessage {
|
||||||
|
info?: {
|
||||||
|
role?: string
|
||||||
|
time?: {
|
||||||
|
completed?: number
|
||||||
|
}
|
||||||
|
error?: {
|
||||||
|
name?: string
|
||||||
|
data?: {
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parts?: Array<{ type?: string; text?: string }>
|
||||||
|
}
|
||||||
|
|
||||||
function buildUrl(path: string, directory?: string): string {
|
function buildUrl(path: string, directory?: string): string {
|
||||||
const url = `${OPENCODE_SERVER_URL}${path}`
|
const url = `${OPENCODE_SERVER_URL}${path}`
|
||||||
return directory ? `${url}${url.includes('?') ? '&' : '?'}directory=${encodeURIComponent(directory)}` : url
|
return directory ? `${url}${url.includes('?') ? '&' : '?'}directory=${encodeURIComponent(directory)}` : url
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parsePromptResponse(responseText: string): PromptResponse | null {
|
||||||
|
if (!responseText.trim()) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return JSON.parse(responseText) as PromptResponse
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractText(parts: Array<{ type?: string; text?: string }> | undefined): string {
|
||||||
|
return (parts ?? [])
|
||||||
|
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
||||||
|
.map((part) => part.text?.replace(/<think>[\s\S]*?<\/think>\s*/g, '').trim() ?? '')
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractTitle(result: PromptResponse | SessionMessage): string {
|
||||||
|
const text = extractText(result.parts)
|
||||||
|
const title = text
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.find((line) => line.length > 0) || ''
|
||||||
|
|
||||||
|
if (title.length > 100) {
|
||||||
|
return title.substring(0, 97) + '...'
|
||||||
|
}
|
||||||
|
|
||||||
|
return title
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForTitleResponse(sessionID: string, directory: string): Promise<SessionMessage> {
|
||||||
|
const startedAt = Date.now()
|
||||||
|
|
||||||
|
while (Date.now() - startedAt < TITLE_POLL_TIMEOUT_MS) {
|
||||||
|
const messagesResponse = await fetch(buildUrl(`/session/${sessionID}/message`, directory))
|
||||||
|
|
||||||
|
if (!messagesResponse.ok) {
|
||||||
|
const errorText = await messagesResponse.text()
|
||||||
|
throw new Error(errorText || 'Failed to fetch title generation messages')
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = await messagesResponse.json() as SessionMessage[]
|
||||||
|
const assistantMessage = [...messages]
|
||||||
|
.reverse()
|
||||||
|
.find((message) => message.info?.role === 'assistant')
|
||||||
|
|
||||||
|
if (assistantMessage) {
|
||||||
|
const errorText = assistantMessage.info?.error?.data?.message ?? assistantMessage.info?.error?.name
|
||||||
|
if (errorText) {
|
||||||
|
throw new Error(errorText)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (assistantMessage.info?.time?.completed) {
|
||||||
|
return assistantMessage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Bun.sleep(TITLE_POLL_INTERVAL_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Timed out waiting for title generation')
|
||||||
|
}
|
||||||
|
|
||||||
const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else.
|
const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else.
|
||||||
|
|
||||||
<task>
|
<task>
|
||||||
@@ -63,15 +153,9 @@ export function createTitleRoutes() {
|
|||||||
|
|
||||||
logger.info('Generating session title via LLM', { sessionID, textLength: text.length })
|
logger.info('Generating session title via LLM', { sessionID, textLength: text.length })
|
||||||
|
|
||||||
const configResponse = await fetch(buildUrl('/config', directory))
|
const model = await resolveOpenCodeModel(directory || undefined, {
|
||||||
if (!configResponse.ok) {
|
preferSmallModel: true,
|
||||||
logger.error('Failed to fetch OpenCode config')
|
})
|
||||||
return c.json({ error: 'Failed to fetch config' }, 500)
|
|
||||||
}
|
|
||||||
const config = await configResponse.json() as { model?: string; small_model?: string }
|
|
||||||
|
|
||||||
const modelStr = config.small_model || (config.model ?? "")
|
|
||||||
const [providerID, modelID] = modelStr.split('/')
|
|
||||||
|
|
||||||
const titleSessionResponse = await fetch(buildUrl('/session', directory), {
|
const titleSessionResponse = await fetch(buildUrl('/session', directory), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -98,7 +182,10 @@ export function createTitleRoutes() {
|
|||||||
text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n<user_message>\n${text.substring(0, 2000)}\n</user_message>`
|
text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n<user_message>\n${text.substring(0, 2000)}\n</user_message>`
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
model: { providerID, modelID }
|
model: {
|
||||||
|
providerID: model.providerID,
|
||||||
|
modelID: model.modelID,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -108,23 +195,9 @@ export function createTitleRoutes() {
|
|||||||
return c.json({ error: 'LLM request failed' }, 500)
|
return c.json({ error: 'LLM request failed' }, 500)
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await promptResponse.json() as { parts?: Array<{ type: string; text?: string }> }
|
const promptBody = await promptResponse.text()
|
||||||
|
const promptResult = parsePromptResponse(promptBody)
|
||||||
let title = ''
|
const title = extractTitle(promptResult ?? await waitForTitleResponse(titleSessionID, directory))
|
||||||
if (result.parts) {
|
|
||||||
const textPart = result.parts.find((p: { type: string }) => p.type === 'text')
|
|
||||||
if (textPart && 'text' in textPart) {
|
|
||||||
title = (textPart.text as string)
|
|
||||||
.replace(/<think>[\s\S]*?<\/think>\s*/g, '')
|
|
||||||
.split('\n')
|
|
||||||
.map((line: string) => line.trim())
|
|
||||||
.find((line: string) => line.length > 0) || ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (title && title.length > 100) {
|
|
||||||
title = title.substring(0, 97) + '...'
|
|
||||||
}
|
|
||||||
|
|
||||||
if (title) {
|
if (title) {
|
||||||
const updateResponse = await fetch(buildUrl(`/session/${sessionID}`, directory), {
|
const updateResponse = await fetch(buildUrl(`/session/${sessionID}`, directory), {
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { proxyToOpenCodeWithDirectory } from './proxy'
|
||||||
|
|
||||||
|
interface OpenCodeConfigResponse {
|
||||||
|
model?: string
|
||||||
|
small_model?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OpenCodeProviderResponse {
|
||||||
|
providers?: Array<{
|
||||||
|
id: string
|
||||||
|
models?: Record<string, unknown>
|
||||||
|
}>
|
||||||
|
default?: Record<string, string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedOpenCodeModel {
|
||||||
|
providerID: string
|
||||||
|
modelID: string
|
||||||
|
model: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeModelCandidate(model: string | null | undefined): string | null {
|
||||||
|
if (!model) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = model.trim()
|
||||||
|
return normalized ? normalized : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseModel(model: string): ResolvedOpenCodeModel | null {
|
||||||
|
const [providerID, ...modelParts] = model.split('/')
|
||||||
|
const modelID = modelParts.join('/')
|
||||||
|
|
||||||
|
if (!providerID || !modelID) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
providerID,
|
||||||
|
modelID,
|
||||||
|
model: `${providerID}/${modelID}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAvailableModels(response: OpenCodeProviderResponse): Set<string> {
|
||||||
|
const availableModels = new Set<string>()
|
||||||
|
|
||||||
|
for (const provider of response.providers ?? []) {
|
||||||
|
for (const modelID of Object.keys(provider.models ?? {})) {
|
||||||
|
availableModels.add(`${provider.id}/${modelID}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return availableModels
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqueCandidates(candidates: Array<string | null | undefined>): string[] {
|
||||||
|
const normalizedCandidates = candidates
|
||||||
|
.map(normalizeModelCandidate)
|
||||||
|
.filter((candidate): candidate is string => candidate !== null)
|
||||||
|
|
||||||
|
return [...new Set(normalizedCandidates)]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchOpenCodeConfig(directory?: string): Promise<OpenCodeConfigResponse> {
|
||||||
|
const response = await proxyToOpenCodeWithDirectory('/config', 'GET', directory)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text()
|
||||||
|
throw new Error(errorText || 'Failed to fetch OpenCode config')
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json() as OpenCodeConfigResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchOpenCodeProviders(directory?: string): Promise<OpenCodeProviderResponse> {
|
||||||
|
const response = await proxyToOpenCodeWithDirectory('/config/providers', 'GET', directory)
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text()
|
||||||
|
throw new Error(errorText || 'Failed to fetch OpenCode providers')
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json() as OpenCodeProviderResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveOpenCodeModel(
|
||||||
|
directory: string | undefined,
|
||||||
|
options?: {
|
||||||
|
preferredModel?: string | null
|
||||||
|
preferSmallModel?: boolean
|
||||||
|
},
|
||||||
|
): Promise<ResolvedOpenCodeModel> {
|
||||||
|
const [config, providersResponse] = await Promise.all([
|
||||||
|
fetchOpenCodeConfig(directory),
|
||||||
|
fetchOpenCodeProviders(directory),
|
||||||
|
])
|
||||||
|
|
||||||
|
const availableModels = buildAvailableModels(providersResponse)
|
||||||
|
const defaultModels = providersResponse.default ?? {}
|
||||||
|
const configCandidates = options?.preferSmallModel
|
||||||
|
? [config.small_model, config.model]
|
||||||
|
: [config.model, config.small_model]
|
||||||
|
const candidates = uniqueCandidates([options?.preferredModel, ...configCandidates])
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (availableModels.has(candidate)) {
|
||||||
|
const parsedCandidate = parseModel(candidate)
|
||||||
|
if (parsedCandidate) {
|
||||||
|
return parsedCandidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedCandidate = parseModel(candidate)
|
||||||
|
if (!parsedCandidate) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const providerDefaultModel = defaultModels[parsedCandidate.providerID]
|
||||||
|
if (!providerDefaultModel) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const providerDefault = `${parsedCandidate.providerID}/${providerDefaultModel}`
|
||||||
|
if (availableModels.has(providerDefault)) {
|
||||||
|
return {
|
||||||
|
providerID: parsedCandidate.providerID,
|
||||||
|
modelID: providerDefaultModel,
|
||||||
|
model: providerDefault,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [providerID, modelID] of Object.entries(defaultModels)) {
|
||||||
|
const model = `${providerID}/${modelID}`
|
||||||
|
if (availableModels.has(model)) {
|
||||||
|
return {
|
||||||
|
providerID,
|
||||||
|
modelID,
|
||||||
|
model,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const provider of providersResponse.providers ?? []) {
|
||||||
|
const firstModelID = Object.keys(provider.models ?? {})[0]
|
||||||
|
if (firstModelID) {
|
||||||
|
return {
|
||||||
|
providerID: provider.id,
|
||||||
|
modelID: firstModelID,
|
||||||
|
model: `${provider.id}/${firstModelID}`,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('No configured OpenCode models are available')
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import type { Database } from 'bun:sqlite'
|
||||||
|
import type { CreatePromptTemplateRequest, UpdatePromptTemplateRequest } from '@opencode-manager/shared/schemas'
|
||||||
|
import {
|
||||||
|
listPromptTemplates,
|
||||||
|
getPromptTemplateById,
|
||||||
|
createPromptTemplate,
|
||||||
|
updatePromptTemplate,
|
||||||
|
deletePromptTemplate,
|
||||||
|
} from '../db/prompt-templates'
|
||||||
|
|
||||||
|
export class PromptTemplateServiceError extends Error {
|
||||||
|
constructor(message: string, public statusCode: number = 500) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'PromptTemplateServiceError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PromptTemplateService {
|
||||||
|
constructor(private db: Database) {}
|
||||||
|
|
||||||
|
list() {
|
||||||
|
return listPromptTemplates(this.db)
|
||||||
|
}
|
||||||
|
|
||||||
|
getById(id: number) {
|
||||||
|
const template = getPromptTemplateById(this.db, id)
|
||||||
|
if (!template) throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
return template
|
||||||
|
}
|
||||||
|
|
||||||
|
create(data: CreatePromptTemplateRequest) {
|
||||||
|
return createPromptTemplate(this.db, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id: number, data: UpdatePromptTemplateRequest) {
|
||||||
|
const template = updatePromptTemplate(this.db, id, data)
|
||||||
|
if (!template) throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
return template
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(id: number) {
|
||||||
|
const deleted = deletePromptTemplate(this.db, id)
|
||||||
|
if (!deleted) throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { Cron } from 'croner'
|
||||||
|
import type {
|
||||||
|
CreateScheduleJobRequest,
|
||||||
|
ScheduleJob,
|
||||||
|
ScheduleMode,
|
||||||
|
ScheduleSkillMetadata,
|
||||||
|
UpdateScheduleJobRequest,
|
||||||
|
} from '@opencode-manager/shared/types'
|
||||||
|
|
||||||
|
const DEFAULT_CRON_TIMEZONE = 'UTC'
|
||||||
|
|
||||||
|
export interface ScheduleJobPersistenceInput {
|
||||||
|
name: string
|
||||||
|
description: string | null
|
||||||
|
enabled: boolean
|
||||||
|
scheduleMode: ScheduleMode
|
||||||
|
intervalMinutes: number | null
|
||||||
|
cronExpression: string | null
|
||||||
|
timezone: string | null
|
||||||
|
agentSlug: string | null
|
||||||
|
prompt: string
|
||||||
|
model: string | null
|
||||||
|
skillMetadata: ScheduleSkillMetadata | null | undefined
|
||||||
|
nextRunAt: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateTimeZone(timezone: string): string {
|
||||||
|
try {
|
||||||
|
new Intl.DateTimeFormat('en-US', { timeZone: timezone })
|
||||||
|
return timezone
|
||||||
|
} catch {
|
||||||
|
throw new Error(`Invalid timezone: ${timezone}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCronNextRunAt(cronExpression: string, timezone: string, currentDate: number): number {
|
||||||
|
const cron = new Cron(cronExpression, { timezone })
|
||||||
|
const next = cron.nextRun(new Date(currentDate))
|
||||||
|
if (!next) {
|
||||||
|
throw new Error(`Cron expression "${cronExpression}" has no upcoming run`)
|
||||||
|
}
|
||||||
|
return next.getTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCronConfig(cronExpression: string, timezone: string | null | undefined, currentDate: number) {
|
||||||
|
const normalizedTimezone = validateTimeZone(timezone?.trim() || DEFAULT_CRON_TIMEZONE)
|
||||||
|
const normalizedCronExpression = cronExpression.trim()
|
||||||
|
const nextRunAt = getCronNextRunAt(normalizedCronExpression, normalizedTimezone, currentDate)
|
||||||
|
|
||||||
|
return {
|
||||||
|
scheduleMode: 'cron' as const,
|
||||||
|
intervalMinutes: null,
|
||||||
|
cronExpression: normalizedCronExpression,
|
||||||
|
timezone: normalizedTimezone,
|
||||||
|
nextRunAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeIntervalConfig(intervalMinutes: number, currentDate: number) {
|
||||||
|
return {
|
||||||
|
scheduleMode: 'interval' as const,
|
||||||
|
intervalMinutes,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
nextRunAt: currentDate + intervalMinutes * 60_000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computeNextRunAtForJob(job: ScheduleJob, currentDate: number): number | null {
|
||||||
|
if (!job.enabled) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
if (job.scheduleMode === 'cron') {
|
||||||
|
if (!job.cronExpression) {
|
||||||
|
throw new Error('Cron expression is required for cron schedules')
|
||||||
|
}
|
||||||
|
|
||||||
|
return getCronNextRunAt(job.cronExpression, job.timezone || DEFAULT_CRON_TIMEZONE, currentDate)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!job.intervalMinutes) {
|
||||||
|
throw new Error('Interval minutes are required for interval schedules')
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentDate + job.intervalMinutes * 60_000
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequest, currentDate: number = Date.now()): ScheduleJobPersistenceInput {
|
||||||
|
const base = {
|
||||||
|
name: input.name.trim(),
|
||||||
|
description: input.description?.trim() || null,
|
||||||
|
enabled: input.enabled !== false,
|
||||||
|
agentSlug: input.agentSlug?.trim() || null,
|
||||||
|
prompt: input.prompt.trim(),
|
||||||
|
model: input.model?.trim() || null,
|
||||||
|
skillMetadata: input.skillMetadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
const scheduleConfig = input.scheduleMode === 'cron'
|
||||||
|
? normalizeCronConfig(input.cronExpression, input.timezone, currentDate)
|
||||||
|
: normalizeIntervalConfig(input.intervalMinutes, currentDate)
|
||||||
|
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
...scheduleConfig,
|
||||||
|
nextRunAt: base.enabled ? scheduleConfig.nextRunAt : null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUpdatedSchedulePersistenceInput(
|
||||||
|
existing: ScheduleJob,
|
||||||
|
input: UpdateScheduleJobRequest,
|
||||||
|
currentDate: number = Date.now(),
|
||||||
|
): ScheduleJobPersistenceInput {
|
||||||
|
const enabled = input.enabled ?? existing.enabled
|
||||||
|
const scheduleMode = input.scheduleMode ?? existing.scheduleMode
|
||||||
|
|
||||||
|
const scheduleConfig = scheduleMode === 'cron'
|
||||||
|
? normalizeCronConfig(
|
||||||
|
input.cronExpression ?? existing.cronExpression ?? '',
|
||||||
|
input.timezone ?? existing.timezone ?? DEFAULT_CRON_TIMEZONE,
|
||||||
|
currentDate,
|
||||||
|
)
|
||||||
|
: normalizeIntervalConfig(
|
||||||
|
input.intervalMinutes ?? existing.intervalMinutes ?? 60,
|
||||||
|
currentDate,
|
||||||
|
)
|
||||||
|
|
||||||
|
const scheduleChanged =
|
||||||
|
input.scheduleMode !== undefined ||
|
||||||
|
input.intervalMinutes !== undefined ||
|
||||||
|
input.cronExpression !== undefined ||
|
||||||
|
input.timezone !== undefined
|
||||||
|
|
||||||
|
const nextRunAt = enabled
|
||||||
|
? scheduleChanged || input.enabled !== undefined || existing.nextRunAt === null
|
||||||
|
? scheduleConfig.nextRunAt
|
||||||
|
: existing.nextRunAt
|
||||||
|
: null
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: input.name?.trim() || existing.name,
|
||||||
|
description: input.description === undefined ? existing.description : (input.description?.trim() || null),
|
||||||
|
enabled,
|
||||||
|
scheduleMode: scheduleConfig.scheduleMode,
|
||||||
|
intervalMinutes: scheduleConfig.intervalMinutes,
|
||||||
|
cronExpression: scheduleConfig.cronExpression,
|
||||||
|
timezone: scheduleConfig.timezone,
|
||||||
|
agentSlug: input.agentSlug === undefined ? existing.agentSlug : (input.agentSlug?.trim() || null),
|
||||||
|
prompt: input.prompt?.trim() || existing.prompt,
|
||||||
|
model: input.model === undefined ? existing.model : (input.model?.trim() || null),
|
||||||
|
skillMetadata: input.skillMetadata === undefined ? existing.skillMetadata : input.skillMetadata,
|
||||||
|
nextRunAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
import migration007 from '../../src/db/migrations/007-schedules'
|
||||||
|
import migration008 from '../../src/db/migrations/008-schedule-cron-support'
|
||||||
|
|
||||||
|
describe('schedule migrations', () => {
|
||||||
|
it('creates schedule jobs with nullable interval minutes in v7', () => {
|
||||||
|
const db = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
|
||||||
|
migration007.up(db as never)
|
||||||
|
|
||||||
|
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('interval_minutes INTEGER,'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rebuilds schedule jobs for cron support in v8', () => {
|
||||||
|
const db = {
|
||||||
|
prepare: vi.fn().mockReturnValue({
|
||||||
|
all: vi.fn().mockReturnValue([
|
||||||
|
{ name: 'id', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'repo_id', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'name', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'description', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'enabled', notnull: 1, dflt_value: 'TRUE' },
|
||||||
|
{ name: 'interval_minutes', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'agent_slug', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'prompt', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'model', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'skill_metadata', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'created_at', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'updated_at', notnull: 1, dflt_value: null },
|
||||||
|
{ name: 'last_run_at', notnull: 0, dflt_value: null },
|
||||||
|
{ name: 'next_run_at', notnull: 0, dflt_value: null },
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
|
||||||
|
migration008.up(db as never)
|
||||||
|
|
||||||
|
expect(db.prepare).toHaveBeenCalledWith('PRAGMA table_info(schedule_jobs)')
|
||||||
|
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('CREATE TABLE schedule_jobs_new'))
|
||||||
|
expect(db.run).toHaveBeenCalledWith(expect.stringContaining('interval_minutes INTEGER,'))
|
||||||
|
expect(db.run).toHaveBeenCalledWith(expect.stringContaining("schedule_mode TEXT NOT NULL DEFAULT 'interval'"))
|
||||||
|
expect(db.run).toHaveBeenCalledWith(expect.stringContaining("'interval'"))
|
||||||
|
expect(db.run).toHaveBeenCalledWith('DROP TABLE schedule_jobs')
|
||||||
|
expect(db.run).toHaveBeenCalledWith('ALTER TABLE schedule_jobs_new RENAME TO schedule_jobs')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import * as schedulesDb from '../../src/db/schedules'
|
||||||
|
|
||||||
|
const mockDb = {
|
||||||
|
prepare: vi.fn(),
|
||||||
|
} as any
|
||||||
|
|
||||||
|
function makeJobRow(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
id: 7,
|
||||||
|
repo_id: 42,
|
||||||
|
name: 'Weekly engineering summary',
|
||||||
|
description: 'Summarize repo health and recent changes.',
|
||||||
|
enabled: 1,
|
||||||
|
schedule_mode: 'cron',
|
||||||
|
interval_minutes: null,
|
||||||
|
cron_expression: '0 9 * * 1',
|
||||||
|
timezone: 'UTC',
|
||||||
|
agent_slug: 'planner',
|
||||||
|
prompt: 'Generate a weekly summary.',
|
||||||
|
model: 'openai/gpt-5-mini',
|
||||||
|
skill_metadata: JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||||
|
created_at: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updated_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
last_run_at: Date.UTC(2026, 2, 9, 11, 0, 0),
|
||||||
|
next_run_at: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeRunRow(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
id: 5,
|
||||||
|
job_id: 7,
|
||||||
|
repo_id: 42,
|
||||||
|
trigger_source: 'manual',
|
||||||
|
status: 'running',
|
||||||
|
started_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
finished_at: null,
|
||||||
|
created_at: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
session_id: 'ses-1',
|
||||||
|
session_title: 'Scheduled: Weekly engineering summary',
|
||||||
|
log_text: 'Run started. Waiting for assistant response...',
|
||||||
|
response_text: null,
|
||||||
|
error_text: null,
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('schedule database queries', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists schedule jobs and parses persisted metadata', () => {
|
||||||
|
const stmt = {
|
||||||
|
all: vi.fn().mockReturnValue([makeJobRow()]),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const jobs = schedulesDb.listScheduleJobsByRepo(mockDb, 42)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||||
|
expect(jobs[0]).toMatchObject({
|
||||||
|
id: 7,
|
||||||
|
repoId: 42,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
skillMetadata: {
|
||||||
|
skillSlugs: ['planning'],
|
||||||
|
notes: 'Optional notes',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates a schedule job and reloads the inserted row', () => {
|
||||||
|
const insertStmt = {
|
||||||
|
run: vi.fn().mockReturnValue({ lastInsertRowid: 7 }),
|
||||||
|
}
|
||||||
|
const selectStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeJobRow()),
|
||||||
|
}
|
||||||
|
|
||||||
|
mockDb.prepare.mockReturnValueOnce(insertStmt).mockReturnValueOnce(selectStmt)
|
||||||
|
|
||||||
|
const job = schedulesDb.createScheduleJob(mockDb, 42, {
|
||||||
|
name: 'Weekly engineering summary',
|
||||||
|
description: 'Summarize repo health and recent changes.',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
intervalMinutes: null,
|
||||||
|
cronExpression: '0 9 * * 1',
|
||||||
|
timezone: 'UTC',
|
||||||
|
agentSlug: 'planner',
|
||||||
|
prompt: 'Generate a weekly summary.',
|
||||||
|
model: 'openai/gpt-5-mini',
|
||||||
|
skillMetadata: { skillSlugs: ['planning'], notes: 'Optional notes' },
|
||||||
|
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(insertStmt.run).toHaveBeenCalledWith(
|
||||||
|
42,
|
||||||
|
'Weekly engineering summary',
|
||||||
|
'Summarize repo health and recent changes.',
|
||||||
|
1,
|
||||||
|
'cron',
|
||||||
|
null,
|
||||||
|
'0 9 * * 1',
|
||||||
|
'UTC',
|
||||||
|
'planner',
|
||||||
|
'Generate a weekly summary.',
|
||||||
|
'openai/gpt-5-mini',
|
||||||
|
JSON.stringify({ skillSlugs: ['planning'], notes: 'Optional notes' }),
|
||||||
|
expect.any(Number),
|
||||||
|
expect.any(Number),
|
||||||
|
null,
|
||||||
|
Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
)
|
||||||
|
expect(job.id).toBe(7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates a schedule job when it exists', () => {
|
||||||
|
const existingStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeJobRow({ name: 'Existing summary' })),
|
||||||
|
}
|
||||||
|
const updateStmt = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
const reloadStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeJobRow({ name: 'Updated summary', enabled: 0, skill_metadata: null })),
|
||||||
|
}
|
||||||
|
|
||||||
|
mockDb.prepare
|
||||||
|
.mockReturnValueOnce(existingStmt)
|
||||||
|
.mockReturnValueOnce(updateStmt)
|
||||||
|
.mockReturnValueOnce(reloadStmt)
|
||||||
|
|
||||||
|
const job = schedulesDb.updateScheduleJob(mockDb, 42, 7, {
|
||||||
|
name: 'Updated summary',
|
||||||
|
description: null,
|
||||||
|
enabled: false,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 90,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Run a new summary.',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||||
|
'Updated summary',
|
||||||
|
null,
|
||||||
|
0,
|
||||||
|
'interval',
|
||||||
|
90,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
'Run a new summary.',
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
expect.any(Number),
|
||||||
|
null,
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
)
|
||||||
|
expect(job).toMatchObject({
|
||||||
|
name: 'Updated summary',
|
||||||
|
enabled: false,
|
||||||
|
skillMetadata: null,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null when updating metadata for a missing run', () => {
|
||||||
|
const selectStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(undefined),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(selectStmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.updateScheduleRunMetadata(mockDb, 42, 7, 5, {
|
||||||
|
sessionTitle: 'Updated title',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(run).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates schedule run metadata while preserving omitted fields', () => {
|
||||||
|
const existingRun = makeRunRow({ response_text: 'Existing response', error_text: 'Existing error' })
|
||||||
|
const existingStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(existingRun),
|
||||||
|
}
|
||||||
|
const updateStmt = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
const reloadStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeRunRow({ session_title: 'Updated title', response_text: 'Existing response', error_text: 'Existing error' })),
|
||||||
|
}
|
||||||
|
|
||||||
|
mockDb.prepare
|
||||||
|
.mockReturnValueOnce(existingStmt)
|
||||||
|
.mockReturnValueOnce(updateStmt)
|
||||||
|
.mockReturnValueOnce(reloadStmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.updateScheduleRunMetadata(mockDb, 42, 7, 5, {
|
||||||
|
sessionTitle: 'Updated title',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||||
|
'ses-1',
|
||||||
|
'Updated title',
|
||||||
|
'Run started. Waiting for assistant response...',
|
||||||
|
'Existing response',
|
||||||
|
'Existing error',
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
)
|
||||||
|
expect(run?.sessionTitle).toBe('Updated title')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates and reloads a schedule run', () => {
|
||||||
|
const insertStmt = {
|
||||||
|
run: vi.fn().mockReturnValue({ lastInsertRowid: 5 }),
|
||||||
|
}
|
||||||
|
const selectStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeRunRow()),
|
||||||
|
}
|
||||||
|
|
||||||
|
mockDb.prepare.mockReturnValueOnce(insertStmt).mockReturnValueOnce(selectStmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.createScheduleRun(mockDb, {
|
||||||
|
jobId: 7,
|
||||||
|
repoId: 42,
|
||||||
|
triggerSource: 'manual',
|
||||||
|
status: 'running',
|
||||||
|
startedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
createdAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(insertStmt.run).toHaveBeenCalledWith(7, 42, 'manual', 'running', expect.any(Number), expect.any(Number))
|
||||||
|
expect(run.id).toBe(5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists active runs and maps persisted fields', () => {
|
||||||
|
const stmt = {
|
||||||
|
all: vi.fn().mockReturnValue([
|
||||||
|
makeRunRow({ id: 5 }),
|
||||||
|
makeRunRow({ id: 6, status: 'failed', error_text: 'Model unavailable' }),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const runs = schedulesDb.listRunningScheduleRuns(mockDb, 10)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('WHERE status = \'running\''))
|
||||||
|
expect(runs).toHaveLength(2)
|
||||||
|
expect(runs[1]).toMatchObject({ id: 6, status: 'failed', errorText: 'Model unavailable' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists run summaries without loading large log or response blobs', () => {
|
||||||
|
const stmt = {
|
||||||
|
all: vi.fn().mockReturnValue([
|
||||||
|
makeRunRow({ log_text: null, response_text: null, error_text: 'Run failed' }),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const runs = schedulesDb.listScheduleRunsByJob(mockDb, 42, 7, 5)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS log_text'))
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('NULL AS response_text'))
|
||||||
|
expect(runs[0]).toMatchObject({
|
||||||
|
id: 5,
|
||||||
|
logText: null,
|
||||||
|
responseText: null,
|
||||||
|
errorText: 'Run failed',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the running run for a job when present', () => {
|
||||||
|
const stmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeRunRow({ id: 8 })),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.getRunningScheduleRunByJob(mockDb, 42, 7)
|
||||||
|
|
||||||
|
expect(run).toMatchObject({ id: 8, sessionId: 'ses-1' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists due schedule jobs ordered by next run time', () => {
|
||||||
|
const now = Date.now()
|
||||||
|
const limit = 10
|
||||||
|
const jobRow = makeJobRow()
|
||||||
|
const stmt = {
|
||||||
|
all: vi.fn().mockReturnValue([jobRow]),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const jobs = schedulesDb.listDueScheduleJobs(mockDb, now, limit)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith(expect.stringContaining('WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ?'))
|
||||||
|
expect(stmt.all).toHaveBeenCalledWith(now, limit)
|
||||||
|
expect(jobs).toHaveLength(1)
|
||||||
|
expect(jobs.at(0)?.id).toBe(7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists enabled schedule jobs ordered by id', () => {
|
||||||
|
const jobRow = makeJobRow()
|
||||||
|
const stmt = {
|
||||||
|
all: vi.fn().mockReturnValue([jobRow]),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const jobs = schedulesDb.listEnabledScheduleJobs(mockDb)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE enabled = 1 ORDER BY id ASC')
|
||||||
|
expect(stmt.all).toHaveBeenCalledWith()
|
||||||
|
expect(jobs).toHaveLength(1)
|
||||||
|
expect(jobs.at(0)?.enabled).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gets a schedule job by id when found', () => {
|
||||||
|
const jobRow = makeJobRow()
|
||||||
|
const stmt = {
|
||||||
|
get: vi.fn().mockReturnValue(jobRow),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const job = schedulesDb.getScheduleJobById(mockDb, 42, 7)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||||
|
expect(stmt.get).toHaveBeenCalledWith(42, 7)
|
||||||
|
expect(job).toMatchObject({ id: 7, repoId: 42, name: 'Weekly engineering summary' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null when schedule job is not found', () => {
|
||||||
|
const stmt = {
|
||||||
|
get: vi.fn().mockReturnValue(undefined),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const job = schedulesDb.getScheduleJobById(mockDb, 42, 7)
|
||||||
|
|
||||||
|
expect(job).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deletes a schedule job successfully', () => {
|
||||||
|
const stmt = {
|
||||||
|
run: vi.fn().mockReturnValue({ changes: 1 }),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const result = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||||
|
expect(stmt.run).toHaveBeenCalledWith(42, 7)
|
||||||
|
expect(result).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns false when deleting a non-existent schedule job', () => {
|
||||||
|
const stmt = {
|
||||||
|
run: vi.fn().mockReturnValue({ changes: 0 }),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const result = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||||
|
|
||||||
|
expect(result).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reserves the next run time for a schedule job', () => {
|
||||||
|
const nextRunAt = Date.now() + 3600000
|
||||||
|
const stmt = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
schedulesDb.reserveScheduleJobNextRun(mockDb, 42, 7, nextRunAt)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||||
|
expect(stmt.run).toHaveBeenCalledWith(nextRunAt, expect.any(Number), 42, 7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates the run state of a schedule job', () => {
|
||||||
|
const lastRunAt = Date.now()
|
||||||
|
const nextRunAt = Date.now() + 3600000
|
||||||
|
const stmt = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
schedulesDb.updateScheduleJobRunState(mockDb, 42, 7, { lastRunAt, nextRunAt })
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||||
|
expect(stmt.run).toHaveBeenCalledWith(lastRunAt, nextRunAt, expect.any(Number), 42, 7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates a schedule run and reloads the result', () => {
|
||||||
|
const updateStmt = {
|
||||||
|
run: vi.fn(),
|
||||||
|
}
|
||||||
|
const selectStmt = {
|
||||||
|
get: vi.fn().mockReturnValue(makeRunRow({ status: 'completed', response_text: 'Completed' })),
|
||||||
|
}
|
||||||
|
|
||||||
|
mockDb.prepare.mockReturnValueOnce(updateStmt).mockReturnValueOnce(selectStmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.updateScheduleRun(mockDb, 42, 7, 5, {
|
||||||
|
status: 'completed',
|
||||||
|
finishedAt: Date.now(),
|
||||||
|
sessionId: 'ses-1',
|
||||||
|
sessionTitle: 'Updated title',
|
||||||
|
logText: 'Log output',
|
||||||
|
responseText: 'Completed',
|
||||||
|
errorText: null,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updateStmt.run).toHaveBeenCalledWith(
|
||||||
|
'completed',
|
||||||
|
expect.any(Number),
|
||||||
|
'ses-1',
|
||||||
|
'Updated title',
|
||||||
|
'Log output',
|
||||||
|
'Completed',
|
||||||
|
null,
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
)
|
||||||
|
expect(run).toMatchObject({ status: 'completed', responseText: 'Completed' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gets a schedule run by id when found', () => {
|
||||||
|
const runRow = makeRunRow()
|
||||||
|
const stmt = {
|
||||||
|
get: vi.fn().mockReturnValue(runRow),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.getScheduleRunById(mockDb, 42, 7, 5)
|
||||||
|
|
||||||
|
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||||
|
expect(stmt.get).toHaveBeenCalledWith(42, 7, 5)
|
||||||
|
expect(run).toMatchObject({ id: 5, jobId: 7, repoId: 42, status: 'running' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null when schedule run is not found', () => {
|
||||||
|
const stmt = {
|
||||||
|
get: vi.fn().mockReturnValue(undefined),
|
||||||
|
}
|
||||||
|
mockDb.prepare.mockReturnValue(stmt)
|
||||||
|
|
||||||
|
const run = schedulesDb.getScheduleRunById(mockDb, 42, 7, 5)
|
||||||
|
|
||||||
|
expect(run).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
promptService: {
|
||||||
|
list: vi.fn(),
|
||||||
|
getById: vi.fn(),
|
||||||
|
create: vi.fn(),
|
||||||
|
update: vi.fn(),
|
||||||
|
delete: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/prompt-templates', () => ({
|
||||||
|
PromptTemplateService: vi.fn().mockImplementation(() => mocks.promptService),
|
||||||
|
PromptTemplateServiceError: class PromptTemplateServiceError extends Error {
|
||||||
|
constructor(message: string, public statusCode: number = 500) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'PromptTemplateServiceError'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/utils/logger', () => ({
|
||||||
|
logger: {
|
||||||
|
info: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
warn: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { createPromptTemplateRoutes } from '../../src/routes/prompt-templates'
|
||||||
|
import { PromptTemplateServiceError } from '../../src/services/prompt-templates'
|
||||||
|
|
||||||
|
describe('prompt template routes', () => {
|
||||||
|
let app: ReturnType<typeof createPromptTemplateRoutes>
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mocks.promptService.list.mockReset()
|
||||||
|
mocks.promptService.getById.mockReset()
|
||||||
|
mocks.promptService.create.mockReset()
|
||||||
|
mocks.promptService.update.mockReset()
|
||||||
|
mocks.promptService.delete.mockReset()
|
||||||
|
|
||||||
|
app = createPromptTemplateRoutes({} as never)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists all templates including seeded ones from migration', async () => {
|
||||||
|
const mockTemplates = [
|
||||||
|
{ id: 1, title: 'Repo Health Report', category: 'Health', cadence_hint: 'Daily', suggested_name: 'repo-health', suggested_description: 'Report', description: 'Report', prompt: 'Check health' },
|
||||||
|
{ id: 2, title: 'Dependency Watchlist', category: 'Dependencies', cadence_hint: 'Weekly', suggested_name: 'dep-watch', suggested_description: 'Watch deps', description: 'Watch', prompt: 'Watch deps' },
|
||||||
|
]
|
||||||
|
mocks.promptService.list.mockReturnValue(mockTemplates)
|
||||||
|
|
||||||
|
const response = await app.request('/')
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
|
||||||
|
const body = await response.json() as { templates: Array<{ id: number; title: string }> }
|
||||||
|
expect(body.templates.length).toBe(2)
|
||||||
|
expect(body.templates[0]?.title).toBe('Repo Health Report')
|
||||||
|
expect(body.templates[1]?.title).toBe('Dependency Watchlist')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates a template and returns 201', async () => {
|
||||||
|
const newTemplate = {
|
||||||
|
title: 'Test Template',
|
||||||
|
category: 'Test',
|
||||||
|
cadenceHint: 'Daily',
|
||||||
|
suggestedName: 'Test job name',
|
||||||
|
suggestedDescription: 'Test description',
|
||||||
|
description: 'Test description',
|
||||||
|
prompt: 'Test prompt content',
|
||||||
|
}
|
||||||
|
|
||||||
|
const createdTemplate = { id: 1, ...newTemplate }
|
||||||
|
mocks.promptService.create.mockReturnValue(createdTemplate)
|
||||||
|
|
||||||
|
const response = await app.request('/', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(newTemplate),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(response.status).toBe(201)
|
||||||
|
const body = await response.json() as { template: { id: number; title: string } }
|
||||||
|
expect(body.template.title).toBe('Test Template')
|
||||||
|
expect(body.template.id).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gets a template by id', async () => {
|
||||||
|
const mockTemplate = { id: 1, title: 'Get Test', category: 'Test', cadence_hint: 'Daily', suggested_name: 'get-test', suggested_description: '', description: '', prompt: 'Test prompt' }
|
||||||
|
mocks.promptService.getById.mockReturnValue(mockTemplate)
|
||||||
|
|
||||||
|
const getResponse = await app.request('/1')
|
||||||
|
expect(getResponse.status).toBe(200)
|
||||||
|
|
||||||
|
const body = await getResponse.json() as { template: { id: number; title: string } }
|
||||||
|
expect(body.template.id).toBe(1)
|
||||||
|
expect(body.template.title).toBe('Get Test')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 for missing template', async () => {
|
||||||
|
mocks.promptService.getById.mockImplementation(() => {
|
||||||
|
throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await app.request('/99999')
|
||||||
|
expect(response.status).toBe(404)
|
||||||
|
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
expect(body.error).toBe('Template not found')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates a template', async () => {
|
||||||
|
const updatedTemplate = { id: 1, title: 'Updated Title', category: 'Test', cadence_hint: 'Daily', suggested_name: 'updated', suggested_description: '', description: '', prompt: 'Test prompt' }
|
||||||
|
mocks.promptService.update.mockReturnValue(updatedTemplate)
|
||||||
|
|
||||||
|
const updateResponse = await app.request('/1', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ title: 'Updated Title' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(updateResponse.status).toBe(200)
|
||||||
|
const body = await updateResponse.json() as { template: { title: string } }
|
||||||
|
expect(body.template.title).toBe('Updated Title')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 when updating missing template', async () => {
|
||||||
|
mocks.promptService.update.mockImplementation(() => {
|
||||||
|
throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await app.request('/99999', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ title: 'Nope' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(response.status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deletes a template and returns 204', async () => {
|
||||||
|
mocks.promptService.delete.mockReturnValue(undefined)
|
||||||
|
|
||||||
|
const deleteResponse = await app.request('/1', {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(deleteResponse.status).toBe(204)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 when deleting missing template', async () => {
|
||||||
|
mocks.promptService.delete.mockImplementation(() => {
|
||||||
|
throw new PromptTemplateServiceError('Template not found', 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await app.request('/99999', {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(response.status).toBe(404)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => {
|
||||||
|
class MockScheduleServiceError extends Error {
|
||||||
|
status: number
|
||||||
|
|
||||||
|
constructor(message: string, status: number) {
|
||||||
|
super(message)
|
||||||
|
this.status = status
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
MockScheduleServiceError,
|
||||||
|
scheduleService: {
|
||||||
|
listJobs: vi.fn(),
|
||||||
|
createJob: vi.fn(),
|
||||||
|
getJob: vi.fn(),
|
||||||
|
updateJob: vi.fn(),
|
||||||
|
deleteJob: vi.fn(),
|
||||||
|
runJob: vi.fn(),
|
||||||
|
listRuns: vi.fn(),
|
||||||
|
getRun: vi.fn(),
|
||||||
|
cancelRun: vi.fn(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
vi.mock('../../src/services/schedules', () => ({
|
||||||
|
ScheduleService: vi.fn().mockImplementation(() => mocks.scheduleService),
|
||||||
|
ScheduleServiceError: mocks.MockScheduleServiceError,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/utils/logger', () => ({
|
||||||
|
logger: {
|
||||||
|
error: vi.fn(),
|
||||||
|
info: vi.fn(),
|
||||||
|
warn: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { createScheduleRoutes } from '../../src/routes/schedules'
|
||||||
|
|
||||||
|
describe('Schedule Routes', () => {
|
||||||
|
let app: Hono
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
app = new Hono()
|
||||||
|
app.route('/repos/:id/schedules', createScheduleRoutes({} as never))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists jobs for a repo', async () => {
|
||||||
|
mocks.scheduleService.listJobs.mockReturnValue([{ id: 7, name: 'Weekly engineering summary' }])
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules')
|
||||||
|
const body = await response.json() as { jobs: Array<{ id: number }> }
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(body.jobs).toHaveLength(1)
|
||||||
|
expect(mocks.scheduleService.listJobs).toHaveBeenCalledWith(42)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates a schedule from a valid request body', async () => {
|
||||||
|
mocks.scheduleService.createJob.mockReturnValue({ id: 7, name: 'Daily release summary' })
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: 'Daily release summary',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
prompt: 'Summarize release readiness.',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await response.json() as { job: { id: number } }
|
||||||
|
|
||||||
|
expect(response.status).toBe(201)
|
||||||
|
expect(body.job.id).toBe(7)
|
||||||
|
expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({ name: 'Daily release summary' }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('runs a schedule manually', async () => {
|
||||||
|
mocks.scheduleService.runJob.mockResolvedValue({ id: 5, status: 'running' })
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules/7/run', {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
const body = await response.json() as { run: { id: number; status: string } }
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(body.run).toEqual({ id: 5, status: 'running' })
|
||||||
|
expect(mocks.scheduleService.runJob).toHaveBeenCalledWith(42, 7, 'manual')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels a running schedule run', async () => {
|
||||||
|
mocks.scheduleService.cancelRun.mockResolvedValue({ id: 5, status: 'cancelled' })
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules/7/runs/5/cancel', {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
const body = await response.json() as { run: { status: string } }
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(body.run.status).toBe('cancelled')
|
||||||
|
expect(mocks.scheduleService.cancelRun).toHaveBeenCalledWith(42, 7, 5)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('maps service conflicts to HTTP 409 responses', async () => {
|
||||||
|
mocks.scheduleService.runJob.mockRejectedValue(new mocks.MockScheduleServiceError('Schedule is already running', 409))
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules/7/run', {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(409)
|
||||||
|
expect(body.error).toBe('Schedule is already running')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 400 for invalid route ids before reaching the service', async () => {
|
||||||
|
const response = await app.request('/repos/not-a-number/schedules')
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(400)
|
||||||
|
expect(body.error).toBe('Invalid repo id')
|
||||||
|
expect(mocks.scheduleService.listJobs).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('loads and updates a single schedule job', async () => {
|
||||||
|
mocks.scheduleService.getJob.mockReturnValue({ id: 7, name: 'Weekly engineering summary' })
|
||||||
|
mocks.scheduleService.updateJob.mockReturnValue({ id: 7, name: 'Updated engineering summary' })
|
||||||
|
|
||||||
|
const getResponse = await app.request('/repos/42/schedules/7')
|
||||||
|
const getBody = await getResponse.json() as { job: { name: string } }
|
||||||
|
|
||||||
|
const patchResponse = await app.request('/repos/42/schedules/7', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ name: 'Updated engineering summary' }),
|
||||||
|
})
|
||||||
|
const patchBody = await patchResponse.json() as { job: { name: string } }
|
||||||
|
|
||||||
|
expect(getResponse.status).toBe(200)
|
||||||
|
expect(getBody.job.name).toBe('Weekly engineering summary')
|
||||||
|
expect(patchResponse.status).toBe(200)
|
||||||
|
expect(patchBody.job.name).toBe('Updated engineering summary')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists runs, loads a single run, and deletes a schedule', async () => {
|
||||||
|
mocks.scheduleService.listRuns.mockReturnValue([{ id: 5, status: 'completed' }])
|
||||||
|
mocks.scheduleService.getRun.mockReturnValue({ id: 5, status: 'completed' })
|
||||||
|
mocks.scheduleService.deleteJob.mockReturnValue(undefined)
|
||||||
|
|
||||||
|
const runsResponse = await app.request('/repos/42/schedules/7/runs?limit=5')
|
||||||
|
const runsBody = await runsResponse.json() as { runs: Array<{ id: number }> }
|
||||||
|
|
||||||
|
const runResponse = await app.request('/repos/42/schedules/7/runs/5')
|
||||||
|
const runBody = await runResponse.json() as { run: { id: number } }
|
||||||
|
|
||||||
|
const deleteResponse = await app.request('/repos/42/schedules/7', {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
const deleteBody = await deleteResponse.json() as { success: boolean }
|
||||||
|
|
||||||
|
expect(runsResponse.status).toBe(200)
|
||||||
|
expect(runsBody.runs[0]?.id).toBe(5)
|
||||||
|
expect(runResponse.status).toBe(200)
|
||||||
|
expect(runBody.run.id).toBe(5)
|
||||||
|
expect(deleteResponse.status).toBe(200)
|
||||||
|
expect(deleteBody.success).toBe(true)
|
||||||
|
expect(mocks.scheduleService.deleteJob).toHaveBeenCalledWith(42, 7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects non-positive run list limits', async () => {
|
||||||
|
const response = await app.request('/repos/42/schedules/7/runs?limit=0')
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(400)
|
||||||
|
expect(body.error).toBe('Limit must be greater than 0')
|
||||||
|
expect(mocks.scheduleService.listRuns).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clamps large run list limits', async () => {
|
||||||
|
mocks.scheduleService.listRuns.mockReturnValue([])
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules/7/runs?limit=500')
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(mocks.scheduleService.listRuns).toHaveBeenCalledWith(42, 7, 100)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 404 when schedule job is not found', async () => {
|
||||||
|
mocks.scheduleService.getJob.mockReturnValue(null)
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules/7')
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(404)
|
||||||
|
expect(body.error).toBe('Schedule not found')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates a cron schedule from a valid request body', async () => {
|
||||||
|
mocks.scheduleService.createJob.mockReturnValue({ id: 8, name: 'Morning report' })
|
||||||
|
|
||||||
|
const response = await app.request('/repos/42/schedules', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: 'Morning report',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: '0 9 * * *',
|
||||||
|
timezone: 'America/New_York',
|
||||||
|
prompt: 'Generate the daily report.',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await response.json() as { job: { id: number } }
|
||||||
|
|
||||||
|
expect(response.status).toBe(201)
|
||||||
|
expect(body.job.id).toBe(8)
|
||||||
|
expect(mocks.scheduleService.createJob).toHaveBeenCalledWith(42, expect.objectContaining({
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: '0 9 * * *',
|
||||||
|
timezone: 'America/New_York',
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
resolveOpenCodeModel: vi.fn(),
|
||||||
|
fetch: vi.fn(),
|
||||||
|
sleep: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/opencode-models', () => ({
|
||||||
|
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/utils/logger', () => ({
|
||||||
|
logger: {
|
||||||
|
info: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
warn: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||||
|
ENV: {
|
||||||
|
OPENCODE: { PORT: 5551 },
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { createTitleRoutes } from '../../src/routes/title'
|
||||||
|
|
||||||
|
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function textResponse(body: string, status: number = 200): Response {
|
||||||
|
return new Response(body, { status })
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Title Routes', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||||
|
vi.stubGlobal('fetch', mocks.fetch)
|
||||||
|
vi.stubGlobal('Bun', { sleep: mocks.sleep })
|
||||||
|
mocks.sleep.mockResolvedValue(undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates the session title from an immediate JSON prompt response', async () => {
|
||||||
|
const app = createTitleRoutes()
|
||||||
|
|
||||||
|
mocks.fetch
|
||||||
|
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-1' }))
|
||||||
|
.mockResolvedValueOnce(textResponse(JSON.stringify({
|
||||||
|
parts: [{ type: 'text', text: 'Refactoring background jobs' }],
|
||||||
|
})))
|
||||||
|
.mockResolvedValueOnce(textResponse('', 200))
|
||||||
|
.mockResolvedValueOnce(textResponse('', 200))
|
||||||
|
|
||||||
|
const response = await app.request('http://localhost/', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
directory: '/workspace/repos/sample-project',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
text: 'Refactor recurring background jobs and improve observability.',
|
||||||
|
sessionID: 'session-main-1',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await response.json() as { title: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(body.title).toBe('Refactoring background jobs')
|
||||||
|
expect(mocks.fetch).toHaveBeenCalledWith(
|
||||||
|
'http://127.0.0.1:5551/session/session-main-1?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||||
|
expect.objectContaining({ method: 'PATCH' }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('polls session messages when the prompt endpoint returns an empty body', async () => {
|
||||||
|
const app = createTitleRoutes()
|
||||||
|
|
||||||
|
mocks.fetch
|
||||||
|
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-2' }))
|
||||||
|
.mockResolvedValueOnce(textResponse(''))
|
||||||
|
.mockResolvedValueOnce(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||||
|
parts: [{ type: 'text', text: 'Analyzing recurring job setup' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
.mockResolvedValueOnce(textResponse('', 200))
|
||||||
|
.mockResolvedValueOnce(textResponse('', 200))
|
||||||
|
|
||||||
|
const response = await app.request('http://localhost/', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
directory: '/workspace/repos/sample-project',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
text: 'Why do recurring jobs stop after a restart?',
|
||||||
|
sessionID: 'session-main-2',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await response.json() as { title: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(body.title).toBe('Analyzing recurring job setup')
|
||||||
|
expect(mocks.fetch).toHaveBeenNthCalledWith(
|
||||||
|
3,
|
||||||
|
'http://127.0.0.1:5551/session/title-session-2/message?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns a 500 when the polled assistant message reports an error', async () => {
|
||||||
|
const app = createTitleRoutes()
|
||||||
|
|
||||||
|
mocks.fetch
|
||||||
|
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-3' }))
|
||||||
|
.mockResolvedValueOnce(textResponse(''))
|
||||||
|
.mockResolvedValueOnce(jsonResponse([
|
||||||
|
{
|
||||||
|
info: {
|
||||||
|
role: 'assistant',
|
||||||
|
error: { data: { message: 'Model unavailable' } },
|
||||||
|
},
|
||||||
|
parts: [],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
.mockResolvedValueOnce(textResponse('', 200))
|
||||||
|
|
||||||
|
const response = await app.request('http://localhost/', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
directory: '/workspace/repos/sample-project',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
text: 'Generate a title for this broken run.',
|
||||||
|
sessionID: 'session-main-3',
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await response.json() as { error: string }
|
||||||
|
|
||||||
|
expect(response.status).toBe(500)
|
||||||
|
expect(body.error).toBe('Model unavailable')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const { proxyToOpenCodeWithDirectory } = vi.hoisted(() => ({
|
||||||
|
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/proxy', () => ({
|
||||||
|
proxyToOpenCodeWithDirectory,
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { resolveOpenCodeModel } from '../../src/services/opencode-models'
|
||||||
|
|
||||||
|
function jsonResponse(body: unknown): Response {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('resolveOpenCodeModel', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the preferred model when it is available', async () => {
|
||||||
|
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||||
|
if (path === '/config') {
|
||||||
|
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
providers: [
|
||||||
|
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||||
|
],
|
||||||
|
default: { openai: 'gpt-5-mini' },
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||||
|
preferredModel: 'openai/gpt-5',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
providerID: 'openai',
|
||||||
|
modelID: 'gpt-5',
|
||||||
|
model: 'openai/gpt-5',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to the provider default when the preferred model is unavailable', async () => {
|
||||||
|
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||||
|
if (path === '/config') {
|
||||||
|
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5.4' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
providers: [
|
||||||
|
{ id: 'openai', models: { 'gpt-5.3-codex-spark': {}, 'gpt-5-mini': {} } },
|
||||||
|
],
|
||||||
|
default: { openai: 'gpt-5.3-codex-spark' },
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||||
|
preferredModel: 'openai/gpt-5.4',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
providerID: 'openai',
|
||||||
|
modelID: 'gpt-5.3-codex-spark',
|
||||||
|
model: 'openai/gpt-5.3-codex-spark',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('prefers the configured small model when requested', async () => {
|
||||||
|
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||||
|
if (path === '/config') {
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
model: 'openai/gpt-5',
|
||||||
|
small_model: 'openai/gpt-5-mini',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
providers: [
|
||||||
|
{ id: 'openai', models: { 'gpt-5': {}, 'gpt-5-mini': {} } },
|
||||||
|
],
|
||||||
|
default: { openai: 'gpt-5' },
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await resolveOpenCodeModel('/workspace/repos/sample-project', {
|
||||||
|
preferSmallModel: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
providerID: 'openai',
|
||||||
|
modelID: 'gpt-5-mini',
|
||||||
|
model: 'openai/gpt-5-mini',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back to the first available model when defaults are missing', async () => {
|
||||||
|
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||||
|
if (path === '/config') {
|
||||||
|
return Promise.resolve(jsonResponse({}))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
providers: [
|
||||||
|
{ id: 'anthropic', models: { 'claude-sonnet-4': {}, 'claude-haiku-4': {} } },
|
||||||
|
],
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await resolveOpenCodeModel('/workspace/repos/sample-project')
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
providerID: 'anthropic',
|
||||||
|
modelID: 'claude-sonnet-4',
|
||||||
|
model: 'anthropic/claude-sonnet-4',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws when no configured models are available', async () => {
|
||||||
|
proxyToOpenCodeWithDirectory.mockImplementation((path: string) => {
|
||||||
|
if (path === '/config') {
|
||||||
|
return Promise.resolve(jsonResponse({ model: 'openai/gpt-5' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse({ providers: [], default: {} }))
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(resolveOpenCodeModel('/workspace/repos/sample-project')).rejects.toThrow(
|
||||||
|
'No configured OpenCode models are available',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||||
|
import {
|
||||||
|
buildCreateSchedulePersistenceInput,
|
||||||
|
buildUpdatedSchedulePersistenceInput,
|
||||||
|
computeNextRunAtForJob,
|
||||||
|
} from '../../src/services/schedule-config'
|
||||||
|
|
||||||
|
describe('schedule-config', () => {
|
||||||
|
it('builds interval schedule persistence input with trimmed fields', () => {
|
||||||
|
const currentDate = Date.UTC(2026, 2, 9, 12, 0, 0)
|
||||||
|
|
||||||
|
const result = buildCreateSchedulePersistenceInput({
|
||||||
|
name: ' Daily health check ',
|
||||||
|
description: ' Summarize repo health ',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
prompt: ' Review the repository and summarize risks. ',
|
||||||
|
agentSlug: ' code ',
|
||||||
|
model: ' openai/gpt-5 ',
|
||||||
|
}, currentDate)
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
name: 'Daily health check',
|
||||||
|
description: 'Summarize repo health',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: 'code',
|
||||||
|
prompt: 'Review the repository and summarize risks.',
|
||||||
|
model: 'openai/gpt-5',
|
||||||
|
skillMetadata: undefined,
|
||||||
|
nextRunAt: currentDate + 60 * 60_000,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('defaults cron schedules to UTC and computes the next run', () => {
|
||||||
|
const currentDate = Date.UTC(2026, 2, 9, 8, 15, 0)
|
||||||
|
|
||||||
|
const result = buildCreateSchedulePersistenceInput({
|
||||||
|
name: 'Morning report',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: ' 0 9 * * * ',
|
||||||
|
timezone: ' ',
|
||||||
|
prompt: 'Generate the daily report.',
|
||||||
|
}, currentDate)
|
||||||
|
|
||||||
|
expect(result.scheduleMode).toBe('cron')
|
||||||
|
expect(result.cronExpression).toBe('0 9 * * *')
|
||||||
|
expect(result.timezone).toBe('UTC')
|
||||||
|
expect(result.nextRunAt).toBe(Date.UTC(2026, 2, 9, 9, 0, 0))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('preserves the existing next run when only prompt text changes', () => {
|
||||||
|
const existing: ScheduleJob = {
|
||||||
|
id: 7,
|
||||||
|
repoId: 42,
|
||||||
|
name: 'Weekly engineering summary',
|
||||||
|
description: 'Summarize health',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Old prompt',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||||
|
prompt: ' New prompt body ',
|
||||||
|
}, Date.UTC(2026, 2, 9, 12, 30, 0))
|
||||||
|
|
||||||
|
expect(result.prompt).toBe('New prompt body')
|
||||||
|
expect(result.nextRunAt).toBe(existing.nextRunAt)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('normalizes optional text fields when updating a schedule', () => {
|
||||||
|
const existing: ScheduleJob = {
|
||||||
|
id: 10,
|
||||||
|
repoId: 42,
|
||||||
|
name: 'Weekly engineering summary',
|
||||||
|
description: 'Existing description',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: 'planner',
|
||||||
|
prompt: 'Old prompt',
|
||||||
|
model: 'openai/gpt-5-mini',
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||||
|
description: ' ',
|
||||||
|
agentSlug: ' reviewer ',
|
||||||
|
model: ' ',
|
||||||
|
}, Date.UTC(2026, 2, 9, 12, 30, 0))
|
||||||
|
|
||||||
|
expect(result.description).toBeNull()
|
||||||
|
expect(result.agentSlug).toBe('reviewer')
|
||||||
|
expect(result.model).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('recomputes the next run when a disabled schedule is re-enabled', () => {
|
||||||
|
const existing: ScheduleJob = {
|
||||||
|
id: 8,
|
||||||
|
repoId: 42,
|
||||||
|
name: 'Paused summary',
|
||||||
|
description: null,
|
||||||
|
enabled: false,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 30,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Run a report',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: null,
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentDate = Date.UTC(2026, 2, 9, 14, 0, 0)
|
||||||
|
const result = buildUpdatedSchedulePersistenceInput(existing, {
|
||||||
|
enabled: true,
|
||||||
|
}, currentDate)
|
||||||
|
|
||||||
|
expect(result.enabled).toBe(true)
|
||||||
|
expect(result.nextRunAt).toBe(currentDate + 30 * 60_000)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws for invalid cron timezones', () => {
|
||||||
|
expect(() => buildCreateSchedulePersistenceInput({
|
||||||
|
name: 'Invalid timezone',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: '0 9 * * *',
|
||||||
|
timezone: 'Mars/Phobos',
|
||||||
|
prompt: 'Test prompt',
|
||||||
|
}, Date.UTC(2026, 2, 9, 8, 0, 0))).toThrow('Invalid timezone: Mars/Phobos')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null for disabled jobs when computing the next run', () => {
|
||||||
|
const job: ScheduleJob = {
|
||||||
|
id: 9,
|
||||||
|
repoId: 42,
|
||||||
|
name: 'Disabled summary',
|
||||||
|
description: null,
|
||||||
|
enabled: false,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 15,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Prompt',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: null,
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(computeNextRunAtForJob(job, Date.UTC(2026, 2, 9, 12, 0, 0))).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,884 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
getRepoById: vi.fn(),
|
||||||
|
createScheduleJob: vi.fn(),
|
||||||
|
createScheduleRun: vi.fn(),
|
||||||
|
deleteScheduleJob: vi.fn(),
|
||||||
|
getScheduleJobById: vi.fn(),
|
||||||
|
getRunningScheduleRunByJob: vi.fn(),
|
||||||
|
getScheduleRunById: vi.fn(),
|
||||||
|
listDueScheduleJobs: vi.fn(),
|
||||||
|
listEnabledScheduleJobs: vi.fn(),
|
||||||
|
listRunningScheduleRuns: vi.fn(),
|
||||||
|
listScheduleJobsByRepo: vi.fn(),
|
||||||
|
listScheduleRunsByJob: vi.fn(),
|
||||||
|
updateScheduleJob: vi.fn(),
|
||||||
|
updateScheduleJobRunState: vi.fn(),
|
||||||
|
updateScheduleRun: vi.fn(),
|
||||||
|
updateScheduleRunMetadata: vi.fn(),
|
||||||
|
buildCreateSchedulePersistenceInput: vi.fn(),
|
||||||
|
buildUpdatedSchedulePersistenceInput: vi.fn(),
|
||||||
|
computeNextRunAtForJob: vi.fn(),
|
||||||
|
|
||||||
|
resolveOpenCodeModel: vi.fn(),
|
||||||
|
proxyToOpenCodeWithDirectory: vi.fn(),
|
||||||
|
addClient: vi.fn(),
|
||||||
|
onEvent: vi.fn(),
|
||||||
|
loggerError: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/db/queries', () => ({
|
||||||
|
getRepoById: mocks.getRepoById,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/db/schedules', () => ({
|
||||||
|
createScheduleJob: mocks.createScheduleJob,
|
||||||
|
createScheduleRun: mocks.createScheduleRun,
|
||||||
|
deleteScheduleJob: mocks.deleteScheduleJob,
|
||||||
|
getScheduleJobById: mocks.getScheduleJobById,
|
||||||
|
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
|
||||||
|
getScheduleRunById: mocks.getScheduleRunById,
|
||||||
|
listDueScheduleJobs: mocks.listDueScheduleJobs,
|
||||||
|
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
|
||||||
|
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
|
||||||
|
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
|
||||||
|
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
|
||||||
|
updateScheduleJob: mocks.updateScheduleJob,
|
||||||
|
updateScheduleJobRunState: mocks.updateScheduleJobRunState,
|
||||||
|
updateScheduleRun: mocks.updateScheduleRun,
|
||||||
|
updateScheduleRunMetadata: mocks.updateScheduleRunMetadata,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/schedule-config', () => ({
|
||||||
|
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
|
||||||
|
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
|
||||||
|
computeNextRunAtForJob: mocks.computeNextRunAtForJob,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/opencode-models', () => ({
|
||||||
|
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/proxy', () => ({
|
||||||
|
proxyToOpenCodeWithDirectory: mocks.proxyToOpenCodeWithDirectory,
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||||
|
sseAggregator: {
|
||||||
|
addClient: mocks.addClient,
|
||||||
|
onEvent: mocks.onEvent,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('../../src/utils/logger', () => ({
|
||||||
|
logger: {
|
||||||
|
error: mocks.loggerError,
|
||||||
|
info: vi.fn(),
|
||||||
|
warn: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mockCronStop = vi.fn()
|
||||||
|
const mockCronInstances: Array<{ callback: () => void; options: Record<string, unknown>; pattern: string; stop: typeof mockCronStop }> = []
|
||||||
|
|
||||||
|
vi.mock('croner', () => ({
|
||||||
|
Cron: vi.fn().mockImplementation((pattern: string, options: Record<string, unknown>, callback: () => void) => {
|
||||||
|
const instance = { pattern, options, callback, stop: mockCronStop }
|
||||||
|
mockCronInstances.push(instance)
|
||||||
|
return instance
|
||||||
|
}),
|
||||||
|
}))
|
||||||
|
|
||||||
|
import { ScheduleRunner, ScheduleService } from '../../src/services/schedules'
|
||||||
|
|
||||||
|
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function textResponse(body: string, status: number = 200): Response {
|
||||||
|
return new Response(body, { status })
|
||||||
|
}
|
||||||
|
|
||||||
|
const repo = {
|
||||||
|
id: 42,
|
||||||
|
fullPath: '/workspace/repos/sample-project',
|
||||||
|
localPath: 'sample-project',
|
||||||
|
repoUrl: 'https://github.com/example/sample-project',
|
||||||
|
}
|
||||||
|
|
||||||
|
const job: ScheduleJob = {
|
||||||
|
id: 7,
|
||||||
|
repoId: 42,
|
||||||
|
name: 'Weekly engineering summary',
|
||||||
|
description: 'Summarize repo health and recent changes.',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Review the repository and summarize the current state.',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||||
|
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||||
|
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseRun: ScheduleRun = {
|
||||||
|
id: 5,
|
||||||
|
jobId: 7,
|
||||||
|
repoId: 42,
|
||||||
|
triggerSource: 'manual',
|
||||||
|
status: 'running',
|
||||||
|
startedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||||
|
finishedAt: null,
|
||||||
|
createdAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||||
|
sessionId: null,
|
||||||
|
sessionTitle: null,
|
||||||
|
logText: null,
|
||||||
|
responseText: null,
|
||||||
|
errorText: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ScheduleService', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
Reflect.get(ScheduleService, 'activeRuns').clear()
|
||||||
|
|
||||||
|
mocks.getRepoById.mockReturnValue(repo)
|
||||||
|
mocks.getScheduleJobById.mockReturnValue(job)
|
||||||
|
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||||
|
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||||
|
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||||
|
mocks.addClient.mockReturnValue(vi.fn())
|
||||||
|
mocks.onEvent.mockReturnValue(vi.fn())
|
||||||
|
mocks.getScheduleRunById.mockReturnValue({
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-1',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
logText: 'Run started. Waiting for assistant response...',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('starts a run immediately and completes it after polling session messages', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runWithSession: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-1',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
logText: 'Run started. Waiting for assistant response...',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session' && method === 'POST') {
|
||||||
|
return Promise.resolve(jsonResponse({ id: 'ses-run-1' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-1/message' && method === 'POST') {
|
||||||
|
return Promise.resolve(textResponse(''))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-1/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||||
|
parts: [{ type: 'text', text: 'System health is stable.' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await service.runJob(42, 7, 'manual')
|
||||||
|
|
||||||
|
expect(result).toEqual(runWithSession)
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'completed',
|
||||||
|
responseText: 'System health is stable.',
|
||||||
|
sessionId: 'ses-run-1',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mocks.updateScheduleJobRunState).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
expect.objectContaining({ nextRunAt: job.nextRunAt }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('completes a run immediately when the prompt endpoint returns JSON', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runWithSession: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-2',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
logText: 'Run started. Waiting for assistant response...',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session' && method === 'POST') {
|
||||||
|
return Promise.resolve(jsonResponse({ id: 'ses-run-2' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-2/message' && method === 'POST') {
|
||||||
|
return Promise.resolve(textResponse(JSON.stringify({
|
||||||
|
parts: [{ type: 'text', text: 'Immediate status summary.' }],
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
await service.runJob(42, 7, 'manual')
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'completed',
|
||||||
|
responseText: 'Immediate status summary.',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects a new run when the job already has a running entry', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
|
||||||
|
mocks.getRunningScheduleRunByJob.mockReturnValue({
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-existing',
|
||||||
|
sessionTitle: 'Scheduled: Existing run',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({
|
||||||
|
message: 'Schedule is already running',
|
||||||
|
status: 409,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('surfaces setup failures when the model cannot be resolved', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
|
||||||
|
mocks.resolveOpenCodeModel.mockRejectedValueOnce(new Error('No configured models are available.'))
|
||||||
|
mocks.updateScheduleRun.mockReturnValue({
|
||||||
|
...baseRun,
|
||||||
|
status: 'failed',
|
||||||
|
finishedAt: Date.UTC(2026, 2, 9, 12, 6, 0),
|
||||||
|
errorText: 'No configured models are available.',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({
|
||||||
|
message: 'No configured models are available.',
|
||||||
|
status: 500,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'failed',
|
||||||
|
errorText: 'No configured models are available.',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks the run failed when prompt submission is rejected after session creation', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runWithSession: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-6',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
logText: 'Run started. Waiting for assistant response...',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(runWithSession)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session' && method === 'POST') {
|
||||||
|
return Promise.resolve(jsonResponse({ id: 'ses-run-6' }))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-6/message' && method === 'POST') {
|
||||||
|
return Promise.resolve(textResponse('Provider unavailable', 500))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await service.runJob(42, 7, 'manual')
|
||||||
|
|
||||||
|
expect(result).toEqual(runWithSession)
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'failed',
|
||||||
|
errorText: 'Provider unavailable',
|
||||||
|
sessionId: 'ses-run-6',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels an in-progress run by aborting the linked session', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runningRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-3',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
logText: 'Run started. Waiting for assistant response...',
|
||||||
|
}
|
||||||
|
const cancelledRun: ScheduleRun = {
|
||||||
|
...runningRun,
|
||||||
|
status: 'cancelled',
|
||||||
|
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||||
|
errorText: 'Run cancelled by user.',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||||
|
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-3/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-3/abort' && method === 'POST') {
|
||||||
|
return Promise.resolve(textResponse(''))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await service.cancelRun(42, 7, 5)
|
||||||
|
|
||||||
|
expect(result).toEqual(cancelledRun)
|
||||||
|
expect(mocks.proxyToOpenCodeWithDirectory).toHaveBeenCalledWith(
|
||||||
|
'/session/ses-run-3/abort',
|
||||||
|
'POST',
|
||||||
|
repo.fullPath,
|
||||||
|
)
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({ status: 'cancelled', errorText: 'Run cancelled by user.' }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects cancellation for runs that already finished', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
|
||||||
|
mocks.getScheduleRunById.mockReturnValue({
|
||||||
|
...baseRun,
|
||||||
|
status: 'completed',
|
||||||
|
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||||
|
responseText: 'Already done',
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(service.cancelRun(42, 7, 5)).rejects.toMatchObject({
|
||||||
|
message: 'Only running schedule runs can be cancelled',
|
||||||
|
status: 409,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels a running entry without a linked session', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runningRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: null,
|
||||||
|
sessionTitle: null,
|
||||||
|
}
|
||||||
|
const cancelledRun: ScheduleRun = {
|
||||||
|
...runningRun,
|
||||||
|
status: 'cancelled',
|
||||||
|
finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0),
|
||||||
|
errorText: 'Run cancelled by user.',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||||
|
mocks.updateScheduleRun.mockReturnValue(cancelledRun)
|
||||||
|
|
||||||
|
const result = await service.cancelRun(42, 7, 5)
|
||||||
|
|
||||||
|
expect(result).toEqual(cancelledRun)
|
||||||
|
expect(mocks.proxyToOpenCodeWithDirectory).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('surfaces abort failures when cancellation cannot reach OpenCode', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runningRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-7',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(runningRun)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-7/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/ses-run-7/abort' && method === 'POST') {
|
||||||
|
return Promise.resolve(textResponse('Abort refused', 500))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(service.cancelRun(42, 7, 5)).rejects.toMatchObject({
|
||||||
|
message: 'Abort refused',
|
||||||
|
status: 502,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks orphaned idle runs as failed during recovery', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const orphanedRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
triggerSource: 'schedule',
|
||||||
|
sessionId: 'ses-run-4',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
responseText: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([orphanedRun])
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-4/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant' },
|
||||||
|
parts: [{ type: 'text', text: 'Partial summary' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/status' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
'ses-run-4': { type: 'idle' },
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
await service.recoverRunningRuns()
|
||||||
|
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'failed',
|
||||||
|
responseText: 'Partial summary',
|
||||||
|
errorText: expect.stringContaining('interrupted before completion'),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finalizes interrupted runs without a linked session during recovery', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([
|
||||||
|
{
|
||||||
|
...baseRun,
|
||||||
|
sessionId: null,
|
||||||
|
sessionTitle: null,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
await service.recoverRunningRuns()
|
||||||
|
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'failed',
|
||||||
|
errorText: expect.stringContaining('no linked session to recover'),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('completes recoverable runs when the assistant already finished', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const completedRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
triggerSource: 'schedule',
|
||||||
|
sessionId: 'ses-run-8',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([completedRun])
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-8/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||||
|
parts: [{ type: 'text', text: 'Recovered summary' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
await service.recoverRunningRuns()
|
||||||
|
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'completed',
|
||||||
|
responseText: 'Recovered summary',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resumes recoverable runs when the session is still active', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const resumedRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
triggerSource: 'schedule',
|
||||||
|
sessionId: 'ses-run-9',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
}
|
||||||
|
let messageRequests = 0
|
||||||
|
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([resumedRun])
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(resumedRun)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-9/message' && method === 'GET') {
|
||||||
|
messageRequests += 1
|
||||||
|
|
||||||
|
if (messageRequests === 1) {
|
||||||
|
return Promise.resolve(jsonResponse([]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.resolve(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||||
|
parts: [{ type: 'text', text: 'Recovered after reconnect' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path === '/session/status' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse({
|
||||||
|
'ses-run-9': { type: 'busy' },
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
await service.recoverRunningRuns()
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({
|
||||||
|
status: 'completed',
|
||||||
|
responseText: 'Recovered after reconnect',
|
||||||
|
sessionId: 'ses-run-9',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('lists jobs and runs through the persistence layer', () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const listedRun = { ...baseRun, status: 'completed', finishedAt: Date.UTC(2026, 2, 9, 12, 10, 0) }
|
||||||
|
|
||||||
|
mocks.listScheduleJobsByRepo.mockReturnValue([job])
|
||||||
|
mocks.listScheduleRunsByJob.mockReturnValue([listedRun])
|
||||||
|
|
||||||
|
expect(service.listJobs(42)).toEqual([job])
|
||||||
|
expect(service.listRuns(42, 7, 10)).toEqual([listedRun])
|
||||||
|
expect(mocks.listScheduleJobsByRepo).toHaveBeenCalledWith(expect.anything(), 42)
|
||||||
|
expect(mocks.listScheduleRunsByJob).toHaveBeenCalledWith(expect.anything(), 42, 7, 10)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('creates and updates jobs using normalized persistence input', () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const createdJob = { ...job, id: 8, name: 'Daily release summary' }
|
||||||
|
const updatedJob = { ...job, name: 'Updated release summary' }
|
||||||
|
|
||||||
|
mocks.buildCreateSchedulePersistenceInput.mockReturnValue({ name: 'Daily release summary' })
|
||||||
|
mocks.createScheduleJob.mockReturnValue(createdJob)
|
||||||
|
mocks.buildUpdatedSchedulePersistenceInput.mockReturnValue({ name: 'Updated release summary' })
|
||||||
|
mocks.updateScheduleJob.mockReturnValue(updatedJob)
|
||||||
|
|
||||||
|
const createResult = service.createJob(42, {
|
||||||
|
name: 'Daily release summary',
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
prompt: 'Summarize release readiness.',
|
||||||
|
})
|
||||||
|
const updateResult = service.updateJob(42, 7, { name: 'Updated release summary' })
|
||||||
|
|
||||||
|
expect(createResult).toEqual(createdJob)
|
||||||
|
expect(updateResult).toEqual(updatedJob)
|
||||||
|
expect(mocks.buildCreateSchedulePersistenceInput).toHaveBeenCalled()
|
||||||
|
expect(mocks.buildUpdatedSchedulePersistenceInput).toHaveBeenCalledWith(job, { name: 'Updated release summary' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('throws when deleting or loading missing records', () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
|
||||||
|
mocks.deleteScheduleJob.mockReturnValue(false)
|
||||||
|
mocks.getScheduleRunById.mockReturnValue(null)
|
||||||
|
|
||||||
|
expect(() => service.deleteJob(42, 7)).toThrow('Schedule not found')
|
||||||
|
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('cancels by finalizing the run when the assistant already completed', async () => {
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runningRun: ScheduleRun = {
|
||||||
|
...baseRun,
|
||||||
|
sessionId: 'ses-run-5',
|
||||||
|
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||||
|
}
|
||||||
|
const completedRun: ScheduleRun = {
|
||||||
|
...runningRun,
|
||||||
|
status: 'completed',
|
||||||
|
finishedAt: Date.UTC(2026, 2, 9, 12, 20, 0),
|
||||||
|
responseText: 'Completed summary',
|
||||||
|
}
|
||||||
|
|
||||||
|
mocks.getScheduleRunById.mockReturnValueOnce(runningRun).mockReturnValueOnce(completedRun)
|
||||||
|
mocks.proxyToOpenCodeWithDirectory.mockImplementation((path: string, method: string) => {
|
||||||
|
if (path === '/session/ses-run-5/message' && method === 'GET') {
|
||||||
|
return Promise.resolve(jsonResponse([
|
||||||
|
{
|
||||||
|
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||||
|
parts: [{ type: 'text', text: 'Completed summary' }],
|
||||||
|
},
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected proxy request: ${method} ${path}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await service.cancelRun(42, 7, 5)
|
||||||
|
|
||||||
|
expect(result).toEqual(completedRun)
|
||||||
|
expect(mocks.updateScheduleRun).toHaveBeenCalledWith(
|
||||||
|
expect.anything(),
|
||||||
|
42,
|
||||||
|
7,
|
||||||
|
5,
|
||||||
|
expect.objectContaining({ status: 'completed', responseText: 'Completed summary' }),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('ScheduleRunner', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockCronInstances.length = 0
|
||||||
|
mockCronStop.mockClear()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('recovers running runs and registers all enabled jobs on start', async () => {
|
||||||
|
const mockJob: ScheduleJob = {
|
||||||
|
id: 1,
|
||||||
|
repoId: 10,
|
||||||
|
name: 'Test Job',
|
||||||
|
description: null,
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Test',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.now(),
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
}
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||||
|
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||||
|
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runner = new ScheduleRunner(service)
|
||||||
|
await runner.start()
|
||||||
|
|
||||||
|
expect(mocks.listRunningScheduleRuns).toHaveBeenCalled()
|
||||||
|
expect(mocks.listEnabledScheduleJobs).toHaveBeenCalled()
|
||||||
|
expect(mockCronInstances).toHaveLength(1)
|
||||||
|
expect(mockCronInstances[0]?.pattern).toBe('*/60 * * * *')
|
||||||
|
expect(mockCronInstances[0]?.options).toEqual(expect.objectContaining({ protect: true }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('registers a cron job with timezone', async () => {
|
||||||
|
const mockJob: ScheduleJob = {
|
||||||
|
id: 2,
|
||||||
|
repoId: 10,
|
||||||
|
name: 'Test Cron',
|
||||||
|
description: null,
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: '0 9 * * *',
|
||||||
|
timezone: 'America/New_York',
|
||||||
|
intervalMinutes: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Test',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.now(),
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
}
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||||
|
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||||
|
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runner = new ScheduleRunner(service)
|
||||||
|
await runner.start()
|
||||||
|
|
||||||
|
expect(mockCronInstances).toHaveLength(1)
|
||||||
|
expect(mockCronInstances[0]?.pattern).toBe('0 9 * * *')
|
||||||
|
expect(mockCronInstances[0]?.options).toEqual(expect.objectContaining({ timezone: 'America/New_York', protect: true }))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('skips disabled jobs', async () => {
|
||||||
|
const mockJob: ScheduleJob = {
|
||||||
|
id: 3,
|
||||||
|
repoId: 10,
|
||||||
|
name: 'Disabled Job',
|
||||||
|
description: null,
|
||||||
|
enabled: false,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Test',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.now(),
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
}
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||||
|
mocks.listEnabledScheduleJobs.mockReturnValue([])
|
||||||
|
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runner = new ScheduleRunner(service)
|
||||||
|
await runner.start()
|
||||||
|
|
||||||
|
runner.registerJob(mockJob)
|
||||||
|
expect(mockCronInstances).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stops all cron instances on stop', async () => {
|
||||||
|
const mockJob: ScheduleJob = {
|
||||||
|
id: 4,
|
||||||
|
repoId: 10,
|
||||||
|
name: 'Stop Test',
|
||||||
|
description: null,
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 30,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Test',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.now(),
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
}
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||||
|
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||||
|
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runner = new ScheduleRunner(service)
|
||||||
|
await runner.start()
|
||||||
|
|
||||||
|
runner.stop()
|
||||||
|
expect(mockCronStop).toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unregisters and re-registers a job on update via onJobChange', async () => {
|
||||||
|
const mockJob: ScheduleJob = {
|
||||||
|
id: 5,
|
||||||
|
repoId: 10,
|
||||||
|
name: 'Update Test',
|
||||||
|
description: null,
|
||||||
|
enabled: true,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: 60,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
agentSlug: null,
|
||||||
|
prompt: 'Test',
|
||||||
|
model: null,
|
||||||
|
skillMetadata: null,
|
||||||
|
nextRunAt: Date.now(),
|
||||||
|
lastRunAt: null,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
}
|
||||||
|
mocks.listRunningScheduleRuns.mockReturnValue([])
|
||||||
|
mocks.listEnabledScheduleJobs.mockReturnValue([mockJob])
|
||||||
|
|
||||||
|
const service = new ScheduleService({} as never)
|
||||||
|
const runner = new ScheduleRunner(service)
|
||||||
|
await runner.start()
|
||||||
|
|
||||||
|
expect(mockCronInstances).toHaveLength(1)
|
||||||
|
|
||||||
|
const updatedJob = { ...mockJob, intervalMinutes: 30 }
|
||||||
|
runner.registerJob(updatedJob)
|
||||||
|
|
||||||
|
expect(mockCronStop).toHaveBeenCalled()
|
||||||
|
expect(mockCronInstances).toHaveLength(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -5,12 +5,16 @@ export default defineConfig({
|
|||||||
globals: true,
|
globals: true,
|
||||||
environment: 'node',
|
environment: 'node',
|
||||||
setupFiles: ['./test/setup.ts'],
|
setupFiles: ['./test/setup.ts'],
|
||||||
|
coverage: {
|
||||||
|
provider: 'v8',
|
||||||
|
reporter: ['text', 'html'],
|
||||||
|
},
|
||||||
env: {
|
env: {
|
||||||
NODE_ENV: 'test',
|
NODE_ENV: 'test',
|
||||||
PORT: '3001',
|
PORT: '3001',
|
||||||
DATABASE_PATH: ':memory:',
|
DATABASE_PATH: ':memory:',
|
||||||
AUTH_SECRET: 'test-secret-for-encryption',
|
AUTH_SECRET: 'test-secret-for-encryption',
|
||||||
WORKSPACE_PATH: '/test/workspace',
|
WORKSPACE_PATH: '/tmp/test-workspace',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -33,6 +33,16 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
|
|||||||
|
|
||||||
[Learn more →](chat.md)
|
[Learn more →](chat.md)
|
||||||
|
|
||||||
|
### Schedules & Recurring Jobs
|
||||||
|
|
||||||
|
- **Recurring Repo Jobs** - Run reusable prompts against a repository on an interval or cron schedule
|
||||||
|
- **Prompt Templates** - Start with built-in reviews for repo health, dependencies, release readiness, docs drift, and more
|
||||||
|
- **Run History** - Inspect statuses, logs, errors, and assistant output from past runs
|
||||||
|
- **Session Handoff** - Open the linked OpenCode session for any run and continue from there
|
||||||
|
- **Manual Runs** - Trigger the same job on demand when you want a fresh report immediately
|
||||||
|
|
||||||
|
[Learn more →](schedules.md)
|
||||||
|
|
||||||
### AI Configuration
|
### AI Configuration
|
||||||
|
|
||||||
- **Model Selection** - Browse and filter available AI models
|
- **Model Selection** - Browse and filter available AI models
|
||||||
@@ -95,4 +105,3 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
|
|||||||
- **Customizable** - Control which events trigger notifications
|
- **Customizable** - Control which events trigger notifications
|
||||||
|
|
||||||
[Learn more →](notifications.md)
|
[Learn more →](notifications.md)
|
||||||
|
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# Schedules & Recurring Jobs
|
||||||
|
|
||||||
|
Create recurring repo jobs that run reusable prompts against a repository, store run history, and link every run back to a normal OpenCode session.
|
||||||
|
|
||||||
|
## What Schedules Are Good For
|
||||||
|
|
||||||
|
Schedules make OpenCode Manager proactive instead of purely session-driven. Good examples include:
|
||||||
|
|
||||||
|
- **Repo health reports** for a quick morning review
|
||||||
|
- **Dependency watchlists** to catch upgrade pressure early
|
||||||
|
- **Release readiness checks** before a ship window
|
||||||
|
- **Docs drift reviews** to spot stale setup instructions
|
||||||
|
- **Tech debt triage** for recurring cleanup planning
|
||||||
|
|
||||||
|
Each run is stored with status, timestamps, logs, assistant output, and a linked session you can open and continue.
|
||||||
|
|
||||||
|
## Creating a Schedule
|
||||||
|
|
||||||
|
1. Open a repository
|
||||||
|
2. Click **Schedules**
|
||||||
|
3. Click **New Schedule**
|
||||||
|
4. Configure the job name, prompt, timing, and optional overrides
|
||||||
|
5. Save the schedule
|
||||||
|
|
||||||
|
The schedule is scoped to the current repository.
|
||||||
|
|
||||||
|
## Timing Options
|
||||||
|
|
||||||
|
The schedule builder supports both simple presets and advanced cron:
|
||||||
|
|
||||||
|
- **Interval** - Repeat every N minutes
|
||||||
|
- **Hourly** - Run once each hour at a chosen minute
|
||||||
|
- **Daily** - Run once per day at a chosen time
|
||||||
|
- **Weekdays** - Run Monday through Friday
|
||||||
|
- **Weekly** - Pick one or more weekdays and a time
|
||||||
|
- **Monthly** - Run on a day of the month
|
||||||
|
- **Advanced** - Enter a cron expression directly
|
||||||
|
|
||||||
|
Cron-based schedules also store a timezone so runs happen when expected.
|
||||||
|
|
||||||
|
## Prompt Templates
|
||||||
|
|
||||||
|
Built-in prompt templates help you start quickly with recurring jobs like:
|
||||||
|
|
||||||
|
- Repo health report
|
||||||
|
- Dependency watchlist
|
||||||
|
- Release readiness review
|
||||||
|
- Test stability audit
|
||||||
|
- Docs drift review
|
||||||
|
- Tech debt triage
|
||||||
|
- Security and config review
|
||||||
|
- CI and ops review
|
||||||
|
|
||||||
|
Applying a template fills the schedule name, description, and prompt so you can customize from a strong default instead of starting from scratch.
|
||||||
|
|
||||||
|
## Agent and Model Overrides
|
||||||
|
|
||||||
|
Schedules can run with:
|
||||||
|
|
||||||
|
- the default workspace agent and model
|
||||||
|
- a custom agent slug
|
||||||
|
- a specific model override when needed
|
||||||
|
|
||||||
|
If a requested model is no longer available, OpenCode Manager falls back to a valid configured model for that provider so the run can still start when possible.
|
||||||
|
|
||||||
|
## Run History
|
||||||
|
|
||||||
|
Each schedule stores a run history panel with:
|
||||||
|
|
||||||
|
- **Status** - Running, completed, or failed
|
||||||
|
- **Trigger source** - Manual or scheduled
|
||||||
|
- **Log output** - Execution metadata and captured results
|
||||||
|
- **Assistant output** - Rendered markdown preview and raw markdown
|
||||||
|
- **Errors** - Failure details when a run does not complete
|
||||||
|
|
||||||
|
This makes recurring jobs easy to review without digging through raw session data first.
|
||||||
|
|
||||||
|
## Linked Sessions
|
||||||
|
|
||||||
|
Every run creates or attaches to a normal OpenCode session.
|
||||||
|
|
||||||
|
Use **Open session** when you want to:
|
||||||
|
|
||||||
|
- inspect the original conversation
|
||||||
|
- continue from the generated report
|
||||||
|
- answer follow-up questions from the agent
|
||||||
|
- debug provider, permission, or tool issues
|
||||||
|
|
||||||
|
This keeps automation connected to the rest of the OpenCode Manager workflow instead of creating a separate silo.
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
- Keep prompts focused on one recurring outcome
|
||||||
|
- Prefer a few high-value schedules per repo over many overlapping jobs
|
||||||
|
- Use manual runs to validate a prompt before relying on the schedule
|
||||||
|
- Review failed runs quickly so broken provider or permission setups do not go unnoticed
|
||||||
|
- Treat schedules as reusable repo routines, not long-running background workers
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Run Failed
|
||||||
|
|
||||||
|
1. Open the run from **Run History**
|
||||||
|
2. Check the **Error** tab for the failure message
|
||||||
|
3. Use **Open session** to inspect the underlying session
|
||||||
|
4. Verify provider credentials, model availability, and any pending agent questions or permissions
|
||||||
|
|
||||||
|
### No Assistant Output
|
||||||
|
|
||||||
|
If a run starts but does not produce assistant output:
|
||||||
|
|
||||||
|
1. Open the linked session
|
||||||
|
2. Check for a provider error
|
||||||
|
3. Check whether the agent asked a question or needed permission
|
||||||
|
4. Re-run the schedule manually after fixing the issue
|
||||||
|
|
||||||
|
### Prompt Needs Iteration
|
||||||
|
|
||||||
|
Use **Run now** to test prompt changes immediately before waiting for the next scheduled run.
|
||||||
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 106 KiB |
@@ -21,6 +21,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
|
|||||||
|
|
||||||
- **Manage repositories** - Clone repos or discover existing local repos from a parent folder
|
- **Manage repositories** - Clone repos or discover existing local repos from a parent folder
|
||||||
- **Chat with AI** - Real-time streaming chat with file mentions and slash commands
|
- **Chat with AI** - Real-time streaming chat with file mentions and slash commands
|
||||||
|
- **Run recurring jobs** - Schedule repo reviews, health checks, and other reusable prompts
|
||||||
- **View diffs** - See code changes with syntax highlighting
|
- **View diffs** - See code changes with syntax highlighting
|
||||||
- **Control from anywhere** - Mobile-first PWA with push notifications
|
- **Control from anywhere** - Mobile-first PWA with push notifications
|
||||||
- **Configure AI** - Manage models, providers, and MCP servers
|
- **Configure AI** - Manage models, providers, and MCP servers
|
||||||
@@ -30,6 +31,7 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
|
|||||||
- **Multi-Repository Support** - Clone repos, discover local repo folders, and reconnect existing OpenCode chats
|
- **Multi-Repository Support** - Clone repos, discover local repo folders, and reconnect existing OpenCode chats
|
||||||
- **Git Integration** - View diffs, manage branches, create PRs directly from the UI
|
- **Git Integration** - View diffs, manage branches, create PRs directly from the UI
|
||||||
- **Real-time Chat** - Stream responses with file mentions and custom slash commands
|
- **Real-time Chat** - Stream responses with file mentions and custom slash commands
|
||||||
|
- **Scheduled Repo Jobs** - Run recurring prompts with linked sessions, logs, and reviewable output
|
||||||
- **Mobile-First PWA** - Install as an app on any device with push notifications
|
- **Mobile-First PWA** - Install as an app on any device with push notifications
|
||||||
- **Push Notifications** - Get background alerts for agent events when app is closed
|
- **Push Notifications** - Get background alerts for agent events when app is closed
|
||||||
- **AI Configuration** - Configure models, providers, OAuth, and custom agents
|
- **AI Configuration** - Configure models, providers, OAuth, and custom agents
|
||||||
@@ -46,5 +48,6 @@ OpenCode Manager provides a web-based interface for OpenCode AI agents, allowing
|
|||||||
- [Installation Guide](getting-started/installation.md) - Detailed setup instructions
|
- [Installation Guide](getting-started/installation.md) - Detailed setup instructions
|
||||||
- [Quick Start](getting-started/quickstart.md) - Get up and running fast
|
- [Quick Start](getting-started/quickstart.md) - Get up and running fast
|
||||||
- [Features Overview](features/overview.md) - Explore all features
|
- [Features Overview](features/overview.md) - Explore all features
|
||||||
|
- [Schedules & Recurring Jobs](features/schedules.md) - Automate recurring repo reviews and follow-ups
|
||||||
- [Memory Plugin](features/memory.md) - Persistent project knowledge with semantic search
|
- [Memory Plugin](features/memory.md) - Persistent project knowledge with semantic search
|
||||||
- [Configuration](configuration/environment.md) - Environment variables and setup
|
- [Configuration](configuration/environment.md) - Environment variables and setup
|
||||||
@@ -33,6 +33,7 @@
|
|||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.1.1",
|
"cmdk": "^1.1.1",
|
||||||
|
"cronstrue": "^3.13.0",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"diff": "^8.0.2",
|
"diff": "^8.0.2",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Repos } from './pages/Repos'
|
|||||||
import { RepoDetail } from './pages/RepoDetail'
|
import { RepoDetail } from './pages/RepoDetail'
|
||||||
import { SessionDetail } from './pages/SessionDetail'
|
import { SessionDetail } from './pages/SessionDetail'
|
||||||
import { Memories } from './pages/Memories'
|
import { Memories } from './pages/Memories'
|
||||||
|
import { Schedules } from './pages/Schedules'
|
||||||
import { Login } from './pages/Login'
|
import { Login } from './pages/Login'
|
||||||
import { Register } from './pages/Register'
|
import { Register } from './pages/Register'
|
||||||
import { Setup } from './pages/Setup'
|
import { Setup } from './pages/Setup'
|
||||||
@@ -136,6 +137,11 @@ const router = createBrowserRouter([
|
|||||||
element: <Memories />,
|
element: <Memories />,
|
||||||
loader: protectedLoader,
|
loader: protectedLoader,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/repos/:id/schedules',
|
||||||
|
element: <Schedules />,
|
||||||
|
loader: protectedLoader,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { paths } from './opencode-types'
|
import type { paths } from './opencode-types'
|
||||||
import { fetchWrapper } from './fetchWrapper'
|
import { fetchWrapper } from './fetchWrapper'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||||
|
|
||||||
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
|
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
|
||||||
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
|
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
|
||||||
@@ -248,3 +250,14 @@ export class OpenCodeClient {
|
|||||||
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
|
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
|
||||||
return new OpenCodeClient(baseURL, directory)
|
return new OpenCodeClient(baseURL, directory)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const useAgents = () => {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['opencode-agents'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
|
||||||
|
return await client.listAgents()
|
||||||
|
},
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||||
|
import { API_BASE_URL } from '@/config'
|
||||||
|
import type {
|
||||||
|
PromptTemplate,
|
||||||
|
CreatePromptTemplateRequest,
|
||||||
|
UpdatePromptTemplateRequest,
|
||||||
|
} from '@opencode-manager/shared/types'
|
||||||
|
|
||||||
|
export async function listPromptTemplates(): Promise<{ templates: PromptTemplate[] }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPromptTemplate(data: CreatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updatePromptTemplate(id: number, data: UpdatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates/${id}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePromptTemplate(id: number): Promise<void> {
|
||||||
|
return fetchWrapperVoid(`${API_BASE_URL}/api/prompt-templates/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||||
|
import { API_BASE_URL } from '@/config'
|
||||||
|
import type {
|
||||||
|
CreateScheduleJobRequest,
|
||||||
|
ScheduleJob,
|
||||||
|
ScheduleRun,
|
||||||
|
UpdateScheduleJobRequest,
|
||||||
|
} from '@opencode-manager/shared/types'
|
||||||
|
|
||||||
|
export async function listRepoSchedules(repoId: number): Promise<{ jobs: ScheduleJob[] }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRepoSchedule(repoId: number, jobId: number): Promise<{ job: ScheduleJob }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createRepoSchedule(repoId: number, data: CreateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateRepoSchedule(repoId: number, jobId: number, data: UpdateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteRepoSchedule(repoId: number, jobId: number): Promise<void> {
|
||||||
|
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runRepoSchedule(repoId: number, jobId: number): Promise<{ run: ScheduleRun }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/run`, {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listRepoScheduleRuns(repoId: number, jobId: number, limit: number = 20): Promise<{ runs: ScheduleRun[] }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs?limit=${limit}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function cancelRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||||
|
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}/cancel`, {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
formatScheduleSummary,
|
||||||
|
formatTimestamp,
|
||||||
|
getJobStatusTone,
|
||||||
|
hasSkillMetadata,
|
||||||
|
} from '@/components/schedules/schedule-utils'
|
||||||
|
import { Bot, CalendarClock, Clock3, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
|
||||||
|
|
||||||
|
interface JobDetailTabProps {
|
||||||
|
selectedJob: ScheduleJob | undefined
|
||||||
|
onEdit: (job: ScheduleJob) => void
|
||||||
|
onDelete: (jobId: number) => void
|
||||||
|
onToggleEnabled: () => void
|
||||||
|
onRunNow: () => void
|
||||||
|
updatePending: boolean
|
||||||
|
runPending: boolean
|
||||||
|
runningRun: boolean
|
||||||
|
isJobFetching: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JobDetailTab({
|
||||||
|
selectedJob,
|
||||||
|
onEdit,
|
||||||
|
onDelete,
|
||||||
|
onToggleEnabled,
|
||||||
|
onRunNow,
|
||||||
|
updatePending,
|
||||||
|
runPending,
|
||||||
|
runningRun,
|
||||||
|
isJobFetching,
|
||||||
|
}: JobDetailTabProps) {
|
||||||
|
if (!selectedJob) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full items-center justify-center">
|
||||||
|
<div className="text-center">
|
||||||
|
<CalendarClock className="mx-auto mb-4 h-10 w-10 text-muted-foreground" />
|
||||||
|
<p className="text-lg font-medium">No job selected</p>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">Select a job from the Jobs tab to view details</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-full overflow-y-auto">
|
||||||
|
<section className="overflow-hidden rounded-xl bg-card/40">
|
||||||
|
<div className="border-b border-border/60 bg-card px-3 py-4 sm:px-6 sm:py-5">
|
||||||
|
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h3 className="text-xl font-semibold tracking-tight">{selectedJob.name}</h3>
|
||||||
|
<Badge className={getJobStatusTone(selectedJob)}>{selectedJob.enabled ? 'Enabled' : 'Paused'}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">{selectedJob.description || 'No description provided.'}</p>
|
||||||
|
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
|
||||||
|
<span className="inline-flex items-center gap-1"><Clock3 className="h-3.5 w-3.5" /> {formatTimestamp(selectedJob.nextRunAt)}</span>
|
||||||
|
<span className="inline-flex items-center gap-1"><History className="h-3.5 w-3.5" /> Last run {formatTimestamp(selectedJob.lastRunAt)}</span>
|
||||||
|
<span className="inline-flex items-center gap-1"><CalendarClock className="h-3.5 w-3.5" /> {formatScheduleSummary(selectedJob)}</span>
|
||||||
|
<span className="inline-flex items-center gap-1"><Bot className="h-3.5 w-3.5" /> {selectedJob.agentSlug ?? 'default agent'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button variant="outline" size="sm" onClick={onToggleEnabled} disabled={updatePending}>
|
||||||
|
{selectedJob.enabled ? 'Pause' : 'Enable'}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => onEdit(selectedJob)} title="Edit">
|
||||||
|
<Pencil className="h-4 w-4 sm:mr-2" />
|
||||||
|
<span className="hidden sm:inline">Edit</span>
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" size="sm" onClick={onRunNow} disabled={runPending || runningRun || isJobFetching} title={runningRun ? 'Run in progress' : isJobFetching ? 'Refreshing...' : 'Run now'}>
|
||||||
|
{runPending || isJobFetching ? <Loader2 className="h-4 w-4 sm:mr-2 animate-spin" /> : <Play className="h-4 w-4 sm:mr-2" />}
|
||||||
|
<span className="hidden sm:inline">{runningRun ? 'Run in progress' : isJobFetching ? 'Refreshing...' : 'Run now'}</span>
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" size="sm" onClick={() => onDelete(selectedJob.id)} title="Delete">
|
||||||
|
<Trash2 className="h-4 w-4 sm:mr-2" />
|
||||||
|
<span className="hidden sm:inline">Delete</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3 sm:p-6">
|
||||||
|
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_280px]">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<section className="rounded-lg border border-border/60 bg-background/40 p-3 sm:p-4">
|
||||||
|
<div className="mb-3">
|
||||||
|
<h3 className="text-base font-medium">Execution Prompt</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">Sent to OpenCode as the first message in the generated session.</p>
|
||||||
|
</div>
|
||||||
|
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{selectedJob.prompt}</pre>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{hasSkillMetadata(selectedJob) && (
|
||||||
|
<section className="rounded-lg border border-border/60 bg-background/40 p-3 sm:p-4">
|
||||||
|
<div className="mb-3">
|
||||||
|
<h3 className="text-base font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Advanced metadata</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">Stored for future scheduler integrations. The current MVP does not execute against these fields yet.</p>
|
||||||
|
</div>
|
||||||
|
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{JSON.stringify(selectedJob.skillMetadata, null, 2)}</pre>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card className="border-border/60 bg-background/60 shadow-none">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Execution Settings</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">Schedule</p>
|
||||||
|
<p className="font-medium break-words">{formatScheduleSummary(selectedJob)}</p>
|
||||||
|
{selectedJob.scheduleMode === 'cron' && selectedJob.cronExpression && (
|
||||||
|
<p className="mt-1 break-all font-mono text-xs text-muted-foreground">{selectedJob.cronExpression}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">Agent</p>
|
||||||
|
<p className="font-medium">{selectedJob.agentSlug ?? 'Default agent'}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">Model</p>
|
||||||
|
<p className="font-medium break-all">{selectedJob.model ?? 'Workspace default'}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">Created</p>
|
||||||
|
<p className="font-medium">{formatTimestamp(selectedJob.createdAt)}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground">Updated</p>
|
||||||
|
<p className="font-medium">{formatTimestamp(selectedJob.updatedAt)}</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { formatScheduleShortLabel, getJobStatusTone } from '@/components/schedules/schedule-utils'
|
||||||
|
import { Bot, Clock3 } from 'lucide-react'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
interface JobsTabProps {
|
||||||
|
jobs: ScheduleJob[]
|
||||||
|
selectedJobId: number | null
|
||||||
|
onSelectJob: (id: number) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JobsTab({ jobs, selectedJobId, onSelectJob }: JobsTabProps) {
|
||||||
|
return (
|
||||||
|
<div className="h-full overflow-y-auto space-y-2 py-2">
|
||||||
|
{jobs.map((job) => (
|
||||||
|
<button
|
||||||
|
key={job.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSelectJob(job.id)}
|
||||||
|
className={cn(
|
||||||
|
'w-full rounded-xl border-2 px-4 py-3 text-left transition-all',
|
||||||
|
selectedJobId === job.id
|
||||||
|
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||||
|
: 'border-border/70 bg-background/60 hover:bg-accent/40'
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="font-medium truncate">{job.name}</p>
|
||||||
|
<p className="mt-1 truncate text-xs text-muted-foreground">{job.description || 'No description yet'}</p>
|
||||||
|
</div>
|
||||||
|
<Badge className={getJobStatusTone(job)}>{job.enabled ? 'Enabled' : 'Paused'}</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground">
|
||||||
|
<span className="inline-flex items-center gap-1"><Clock3 className="h-3.5 w-3.5" /> {formatScheduleShortLabel(job)}</span>
|
||||||
|
<span className="inline-flex items-center gap-1"><Bot className="h-3.5 w-3.5" /> {job.agentSlug ?? 'default agent'}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import type { PromptTemplate, CreatePromptTemplateRequest } from '@opencode-manager/shared/types'
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Loader2 } from 'lucide-react'
|
||||||
|
import { useCreatePromptTemplate, useUpdatePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||||
|
|
||||||
|
interface PromptTemplateDialogProps {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
template?: PromptTemplate
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PromptTemplateDialog({ open, onOpenChange, template }: PromptTemplateDialogProps) {
|
||||||
|
const [title, setTitle] = useState('')
|
||||||
|
const [category, setCategory] = useState('')
|
||||||
|
const [cadenceHint, setCadenceHint] = useState('')
|
||||||
|
const [suggestedName, setSuggestedName] = useState('')
|
||||||
|
const [suggestedDescription, setSuggestedDescription] = useState('')
|
||||||
|
const [description, setDescription] = useState('')
|
||||||
|
const [prompt, setPrompt] = useState('')
|
||||||
|
|
||||||
|
const createMutation = useCreatePromptTemplate()
|
||||||
|
const updateMutation = useUpdatePromptTemplate()
|
||||||
|
const isSaving = createMutation.isPending || updateMutation.isPending
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) {
|
||||||
|
setTitle(template?.title ?? '')
|
||||||
|
setCategory(template?.category ?? '')
|
||||||
|
setCadenceHint(template?.cadenceHint ?? '')
|
||||||
|
setSuggestedName(template?.suggestedName ?? '')
|
||||||
|
setSuggestedDescription(template?.suggestedDescription ?? '')
|
||||||
|
setDescription(template?.description ?? '')
|
||||||
|
setPrompt(template?.prompt ?? '')
|
||||||
|
} else {
|
||||||
|
setTitle('')
|
||||||
|
setCategory('')
|
||||||
|
setCadenceHint('')
|
||||||
|
setSuggestedName('')
|
||||||
|
setSuggestedDescription('')
|
||||||
|
setDescription('')
|
||||||
|
setPrompt('')
|
||||||
|
}
|
||||||
|
}, [template, open])
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
const data: CreatePromptTemplateRequest = {
|
||||||
|
title: title.trim(),
|
||||||
|
category: category.trim(),
|
||||||
|
cadenceHint: cadenceHint.trim(),
|
||||||
|
suggestedName: suggestedName.trim(),
|
||||||
|
suggestedDescription: suggestedDescription.trim(),
|
||||||
|
description: description.trim(),
|
||||||
|
prompt: prompt.trim(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if (template) {
|
||||||
|
updateMutation.mutate({ id: template.id, data }, { onSuccess: () => onOpenChange(false) })
|
||||||
|
} else {
|
||||||
|
createMutation.mutate(data, { onSuccess: () => onOpenChange(false) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = title.trim() && category.trim() && cadenceHint.trim() && suggestedName.trim() && prompt.trim()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className=" flex h-[calc(100dvh-1rem)] max-h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] max-w-2xl flex-col overflow-hidden sm:h-auto sm:max-h-[90vh]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{template ? 'Edit template' : 'New template'}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="flex-1 overflow-y-auto space-y-4 py-2">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-title">Title</Label>
|
||||||
|
<Input id="template-title" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Repo Health Report" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-category">Category</Label>
|
||||||
|
<Input id="template-category" value={category} onChange={(e) => setCategory(e.target.value)} placeholder="Health" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-cadence">Cadence hint</Label>
|
||||||
|
<Input id="template-cadence" value={cadenceHint} onChange={(e) => setCadenceHint(e.target.value)} placeholder="Weekly" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-suggested-name">Suggested job name</Label>
|
||||||
|
<Input id="template-suggested-name" value={suggestedName} onChange={(e) => setSuggestedName(e.target.value)} placeholder="Weekly repo health report" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-description">Description</Label>
|
||||||
|
<Input id="template-description" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Short summary shown on the template card" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-suggested-description">Suggested job description</Label>
|
||||||
|
<Input id="template-suggested-description" value={suggestedDescription} onChange={(e) => setSuggestedDescription(e.target.value)} placeholder="Pre-fills the schedule job description field" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="template-prompt">Prompt</Label>
|
||||||
|
<Textarea id="template-prompt" value={prompt} onChange={(e) => setPrompt(e.target.value)} className="min-h-[200px]" placeholder="The full prompt sent to the agent when the schedule runs." />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-row gap-2 pt-2 border-t border-border sm:justify-end">
|
||||||
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
|
||||||
|
<Button onClick={handleSubmit} disabled={isSaving || !isValid} className="flex-1 sm:flex-none">
|
||||||
|
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||||
|
{isSaving ? 'Saving...' : template ? 'Save changes' : 'Create template'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
|
||||||
|
import { getRunTone } from '@/components/schedules/schedule-utils'
|
||||||
|
import { Ban, CheckCircle2, ChevronDown, History, Loader2, XCircle } from 'lucide-react'
|
||||||
|
|
||||||
|
interface RunHistoryTabProps {
|
||||||
|
repoId: number
|
||||||
|
selectedJob: ScheduleJob | undefined
|
||||||
|
runs: ScheduleRun[] | undefined
|
||||||
|
runsLoading: boolean
|
||||||
|
selectedRunId: number | null
|
||||||
|
onSelectRun: (id: number) => void
|
||||||
|
activeRun: ScheduleRun | null
|
||||||
|
selectedRunLoading: boolean
|
||||||
|
onCancelRun: () => void
|
||||||
|
cancelRunPending: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RunDetailPanelProps {
|
||||||
|
repoId: number
|
||||||
|
activeRun: ScheduleRun | null
|
||||||
|
selectedRunLoading: boolean
|
||||||
|
onCancelRun: () => void
|
||||||
|
cancelRunPending: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
if (selectedRunLoading && !activeRun) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full items-center justify-center">
|
||||||
|
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!activeRun) {
|
||||||
|
return <div className="flex h-full items-center justify-center text-sm text-muted-foreground">Select a run to inspect logs and output.</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||||
|
<div className="flex items-center justify-center gap-2 px-2 py-1.5">
|
||||||
|
<TabsList className="h-auto gap-0 rounded-none border-0 bg-transparent p-0">
|
||||||
|
<TabsTrigger value="log" className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Log</TabsTrigger>
|
||||||
|
<TabsTrigger value="response" disabled={!activeRun.responseText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Assistant Output</TabsTrigger>
|
||||||
|
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
</div>
|
||||||
|
{(activeRun.status === 'running' || activeRun.sessionId || activeRun.responseText) && (
|
||||||
|
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{activeRun.sessionId && (
|
||||||
|
<Button variant="outline" size="sm" onClick={() => navigate(`/repos/${repoId}/sessions/${activeRun.sessionId}`)}>
|
||||||
|
Open session
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending || activeRun.status !== 'running'}>
|
||||||
|
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||||
|
Cancel run
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||||
|
{selectedRunLoading && !activeRun ? (
|
||||||
|
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||||
|
) : (
|
||||||
|
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">{activeRun.logText ?? 'No log text captured.'}</pre>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="response" className="mt-0 min-h-0 flex-1 flex flex-col overflow-hidden">
|
||||||
|
{selectedRunLoading && !activeRun ? (
|
||||||
|
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||||
|
) : activeRun.responseText ? (
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto px-0 py-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||||
|
<ScheduleRunMarkdown content={activeRun.responseText} />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="p-3"><pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">No assistant output captured.</pre></div>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent value="error" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||||
|
{selectedRunLoading && !activeRun ? (
|
||||||
|
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||||
|
) : (
|
||||||
|
<pre className={`whitespace-pre-wrap break-words text-sm font-mono leading-6 ${activeRun.status === 'cancelled' ? 'text-muted-foreground' : 'text-red-300'}`}>{activeRun.errorText ?? 'No error recorded.'}</pre>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RunHistoryTab({
|
||||||
|
repoId,
|
||||||
|
selectedJob,
|
||||||
|
runs,
|
||||||
|
runsLoading,
|
||||||
|
selectedRunId,
|
||||||
|
onSelectRun,
|
||||||
|
activeRun,
|
||||||
|
selectedRunLoading,
|
||||||
|
onCancelRun,
|
||||||
|
cancelRunPending,
|
||||||
|
}: RunHistoryTabProps) {
|
||||||
|
const [expandedRunId, setExpandedRunId] = useState<number | null>(selectedRunId)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setExpandedRunId(selectedRunId)
|
||||||
|
}, [selectedRunId])
|
||||||
|
|
||||||
|
function getRunStatusIcon(status: ScheduleRun['status']) {
|
||||||
|
if (status === 'completed') return <CheckCircle2 className="h-3.5 w-3.5 text-green-400" />
|
||||||
|
if (status === 'failed') return <XCircle className="h-3.5 w-3.5 text-red-400" />
|
||||||
|
if (status === 'running') return <Loader2 className="h-3.5 w-3.5 animate-spin text-blue-400" />
|
||||||
|
return <Ban className="h-3.5 w-3.5 text-muted-foreground" />
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCardClick(runId: number) {
|
||||||
|
if (expandedRunId === runId) {
|
||||||
|
setExpandedRunId(null)
|
||||||
|
} else {
|
||||||
|
setExpandedRunId(runId)
|
||||||
|
onSelectRun(runId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!selectedJob) {
|
||||||
|
if (selectedRunLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-0 flex-1 h-full items-center justify-center">
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-0 flex-1 h-full items-start">
|
||||||
|
<Card className="max-w-3xl border-dashed border-border/70 w-full">
|
||||||
|
<CardContent className="flex flex-col items-center p-8 sm:p-10 text-center">
|
||||||
|
<History className="h-10 w-10 text-muted-foreground mb-4" />
|
||||||
|
<p className="text-lg font-medium">No job selected</p>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">Select a job from the Jobs tab to view its run history</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||||
|
<div className="min-h-0 flex-1 overflow-hidden pt-2 xl:gap-4 xl:grid xl:grid-cols-[320px_minmax(0,1fr)] xl:grid-rows-1">
|
||||||
|
|
||||||
|
{/* Mobile: collapsible list (hidden on xl+) */}
|
||||||
|
<div className="xl:hidden flex flex-col min-h-0 flex-1 h-full">
|
||||||
|
<div className="min-h-0 flex-1 overflow-y-auto pt-4 pb-6 px-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||||
|
{runsLoading ? (
|
||||||
|
<div className="flex items-center justify-center p-6"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||||
|
) : runs?.length ? runs.map((run, index) => (
|
||||||
|
<div
|
||||||
|
key={run.id}
|
||||||
|
className={`rounded-xl border overflow-hidden transition-all bg-card ${
|
||||||
|
expandedRunId === run.id
|
||||||
|
? 'border-border/70'
|
||||||
|
: 'border-border/70'
|
||||||
|
} ${index === 0 ? 'mt-0' : 'mt-2'}`}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleCardClick(run.id)}
|
||||||
|
className="w-full px-3 py-2 text-left flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
{getRunStatusIcon(run.status)}
|
||||||
|
<Badge className={getRunTone(run)}>{run.status}</Badge>
|
||||||
|
</div>
|
||||||
|
<span className="text-xs text-muted-foreground">{run.triggerSource}</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 truncate text-sm font-medium leading-tight">
|
||||||
|
{run.sessionTitle ?? 'No session recorded'}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-xs text-muted-foreground">{new Date(run.startedAt).toLocaleString()}</p>
|
||||||
|
{run.errorText && (
|
||||||
|
<p className="mt-0.5 truncate text-xs text-red-400/80">{run.errorText}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ChevronDown className={`h-4 w-4 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${expandedRunId === run.id ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
{expandedRunId === run.id && (
|
||||||
|
<div className="border-t border-border/60 flex flex-col" style={{ maxHeight: 'calc(100vh - 200px)' }}>
|
||||||
|
<div className="flex flex-col min-h-0 flex-1 overflow-hidden">
|
||||||
|
<RunDetailPanel
|
||||||
|
repoId={repoId}
|
||||||
|
activeRun={activeRun}
|
||||||
|
selectedRunLoading={selectedRunLoading}
|
||||||
|
onCancelRun={onCancelRun}
|
||||||
|
cancelRunPending={cancelRunPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)) : (
|
||||||
|
<Alert>
|
||||||
|
<History className="h-4 w-4" />
|
||||||
|
<AlertTitle>No runs yet</AlertTitle>
|
||||||
|
<AlertDescription>Use Run now to generate the first execution record and log bundle.</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Desktop: original two-column layout (hidden below xl) */}
|
||||||
|
<div className="hidden xl:block min-h-0 space-y-2 overflow-y-auto pr-1">
|
||||||
|
{runsLoading ? (
|
||||||
|
<div className="flex items-center justify-center p-6"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||||
|
) : runs?.length ? runs.map((run) => (
|
||||||
|
<button
|
||||||
|
key={run.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onSelectRun(run.id)}
|
||||||
|
className={`w-full rounded-xl border px-4 py-3 text-left transition-all ${
|
||||||
|
selectedRunId === run.id
|
||||||
|
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||||
|
: 'border-border/70 bg-background/60 hover:bg-accent/40'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
{getRunStatusIcon(run.status)}
|
||||||
|
<Badge className={getRunTone(run)}>{run.status}</Badge>
|
||||||
|
</div>
|
||||||
|
<span className="text-xs text-muted-foreground">{run.triggerSource}</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 truncate text-sm font-medium leading-tight">
|
||||||
|
{run.sessionTitle ?? 'No session recorded'}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-xs text-muted-foreground">{new Date(run.startedAt).toLocaleString()}</p>
|
||||||
|
{run.errorText && (
|
||||||
|
<p className="mt-0.5 truncate text-xs text-red-400/80">{run.errorText}</p>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)) : (
|
||||||
|
<Alert>
|
||||||
|
<History className="h-4 w-4" />
|
||||||
|
<AlertTitle>No runs yet</AlertTitle>
|
||||||
|
<AlertDescription>Use Run now to generate the first execution record and log bundle.</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Desktop: detail panel (hidden below xl) */}
|
||||||
|
<div className="hidden xl:flex min-h-0 flex-col overflow-hidden rounded-xl border border-border/60 bg-background/60 p-4">
|
||||||
|
<RunDetailPanel
|
||||||
|
repoId={repoId}
|
||||||
|
activeRun={activeRun}
|
||||||
|
selectedRunLoading={selectedRunLoading}
|
||||||
|
onCancelRun={onCancelRun}
|
||||||
|
cancelRunPending={cancelRunPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,632 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob } from '@opencode-manager/shared/types'
|
||||||
|
import { getProvidersWithModels } from '@/api/providers'
|
||||||
|
import { createOpenCodeClient } from '@/api/opencode'
|
||||||
|
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Switch } from '@/components/ui/switch'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import {
|
||||||
|
buildCronExpressionFromPreset,
|
||||||
|
cronPresetOptions,
|
||||||
|
detectSchedulePreset,
|
||||||
|
formatDraftScheduleSummary,
|
||||||
|
getLocalTimeZone,
|
||||||
|
intervalOptions,
|
||||||
|
schedulePresetOptions,
|
||||||
|
type SchedulePreset,
|
||||||
|
weekdayOptions,
|
||||||
|
} from '@/components/schedules/schedule-utils'
|
||||||
|
import { Check, Info, Loader2, Pencil, Plus, Sparkles, Trash2 } from 'lucide-react'
|
||||||
|
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
|
||||||
|
import { PromptTemplateDialog } from './PromptTemplateDialog'
|
||||||
|
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||||
|
|
||||||
|
type ScheduleJobDialogProps = {
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
|
job?: ScheduleJob
|
||||||
|
isSaving: boolean
|
||||||
|
onSubmit: (data: CreateScheduleJobRequest) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function InfoHint({ text }: { text: string }) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
title={text}
|
||||||
|
aria-label={text}
|
||||||
|
className="inline-flex h-4 w-4 items-center justify-center text-muted-foreground"
|
||||||
|
>
|
||||||
|
<Info className="h-3.5 w-3.5" />
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit }: ScheduleJobDialogProps) {
|
||||||
|
const [schedulePreset, setSchedulePreset] = useState<SchedulePreset>('interval')
|
||||||
|
const [name, setName] = useState('')
|
||||||
|
const [description, setDescription] = useState('')
|
||||||
|
const [enabled, setEnabled] = useState(true)
|
||||||
|
const [intervalMinutes, setIntervalMinutes] = useState('60')
|
||||||
|
const [timeOfDay, setTimeOfDay] = useState('09:00')
|
||||||
|
const [hourlyMinute, setHourlyMinute] = useState('0')
|
||||||
|
const [weeklyDays, setWeeklyDays] = useState<string[]>(['1'])
|
||||||
|
const [monthlyDay, setMonthlyDay] = useState('1')
|
||||||
|
const [cronExpression, setCronExpression] = useState('0 9 * * 1-5')
|
||||||
|
const [timezone, setTimezone] = useState(getLocalTimeZone())
|
||||||
|
const [agentSlug, setAgentSlug] = useState('')
|
||||||
|
const [model, setModel] = useState('')
|
||||||
|
const [prompt, setPrompt] = useState('')
|
||||||
|
const [selectedPromptTemplateId, setSelectedPromptTemplateId] = useState<number | null>(null)
|
||||||
|
const [skillSlugs, setSkillSlugs] = useState('')
|
||||||
|
const [skillNotes, setSkillNotes] = useState('')
|
||||||
|
const [templateDialogOpen, setTemplateDialogOpen] = useState(false)
|
||||||
|
const [editingTemplate, setEditingTemplate] = useState<PromptTemplate | undefined>(undefined)
|
||||||
|
const [deletingTemplateId, setDeletingTemplateId] = useState<number | null>(null)
|
||||||
|
|
||||||
|
const { data: templates = [] } = usePromptTemplates()
|
||||||
|
const deleteTemplateMutation = useDeletePromptTemplate()
|
||||||
|
|
||||||
|
const { data: providerModels = [] } = useQuery({
|
||||||
|
queryKey: ['providers-with-models', 'schedule-dialog'],
|
||||||
|
queryFn: () => getProvidersWithModels(),
|
||||||
|
enabled: open,
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: agents = [] } = useQuery({
|
||||||
|
queryKey: ['opencode-agents', 'schedule-dialog'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
|
||||||
|
return await client.listAgents()
|
||||||
|
},
|
||||||
|
enabled: open,
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: openCodeConfig } = useQuery({
|
||||||
|
queryKey: ['opencode-config', 'schedule-dialog'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const client = createOpenCodeClient(OPENCODE_API_ENDPOINT)
|
||||||
|
return await client.getConfig()
|
||||||
|
},
|
||||||
|
enabled: open,
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const modelOptions = useMemo<ComboboxOption[]>(() => {
|
||||||
|
const configuredModels: ComboboxOption[] = []
|
||||||
|
const configuredValues = new Set<string>()
|
||||||
|
|
||||||
|
for (const configModel of [openCodeConfig?.model, openCodeConfig?.small_model]) {
|
||||||
|
if (!configModel || configuredValues.has(configModel)) continue
|
||||||
|
configuredValues.add(configModel)
|
||||||
|
const [providerId, ...modelParts] = configModel.split('/')
|
||||||
|
const modelId = modelParts.join('/')
|
||||||
|
const provider = providerModels.find((p) => p.id === providerId)
|
||||||
|
const providerModel = provider?.models.find((m) => m.id === modelId)
|
||||||
|
configuredModels.push({
|
||||||
|
value: configModel,
|
||||||
|
label: providerModel?.name || modelId,
|
||||||
|
description: configModel,
|
||||||
|
group: 'Configured',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const allModels = providerModels.flatMap((provider) =>
|
||||||
|
provider.models
|
||||||
|
.filter((providerModel) => !configuredValues.has(`${provider.id}/${providerModel.id}`))
|
||||||
|
.map((providerModel) => ({
|
||||||
|
value: `${provider.id}/${providerModel.id}`,
|
||||||
|
label: providerModel.name || providerModel.id,
|
||||||
|
description: `${provider.id}/${providerModel.id}`,
|
||||||
|
group: provider.name,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
|
||||||
|
return [...configuredModels, ...allModels]
|
||||||
|
}, [providerModels, openCodeConfig])
|
||||||
|
|
||||||
|
const agentOptions = useMemo<ComboboxOption[]>(() => {
|
||||||
|
return agents.map((agent) => ({
|
||||||
|
value: agent.name,
|
||||||
|
label: agent.name,
|
||||||
|
description: agent.description,
|
||||||
|
}))
|
||||||
|
}, [agents])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setName(job?.name ?? '')
|
||||||
|
setDescription(job?.description ?? '')
|
||||||
|
setEnabled(job?.enabled ?? true)
|
||||||
|
const scheduleDefaults = detectSchedulePreset(job)
|
||||||
|
setSchedulePreset(scheduleDefaults.preset)
|
||||||
|
setIntervalMinutes(scheduleDefaults.intervalMinutes)
|
||||||
|
setTimeOfDay(scheduleDefaults.timeOfDay)
|
||||||
|
setHourlyMinute(scheduleDefaults.hourlyMinute)
|
||||||
|
setWeeklyDays(scheduleDefaults.weeklyDays)
|
||||||
|
setMonthlyDay(scheduleDefaults.monthlyDay)
|
||||||
|
setCronExpression(scheduleDefaults.cronExpression)
|
||||||
|
setTimezone(scheduleDefaults.timezone)
|
||||||
|
setAgentSlug(job?.agentSlug ?? '')
|
||||||
|
setModel(job?.model ?? '')
|
||||||
|
setPrompt(job?.prompt ?? '')
|
||||||
|
const matchingTemplate = templates.find((template) => template.prompt === (job?.prompt ?? ''))
|
||||||
|
setSelectedPromptTemplateId(matchingTemplate ? matchingTemplate.id : null)
|
||||||
|
setSkillSlugs(job?.skillMetadata?.skillSlugs.join(', ') ?? '')
|
||||||
|
setSkillNotes(job?.skillMetadata?.notes ?? '')
|
||||||
|
}, [job, open, templates])
|
||||||
|
|
||||||
|
const applyPromptTemplate = (template: PromptTemplate) => {
|
||||||
|
setSelectedPromptTemplateId(template.id)
|
||||||
|
setName(template.suggestedName)
|
||||||
|
setDescription(template.suggestedDescription)
|
||||||
|
setPrompt(template.prompt)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = () => {
|
||||||
|
const parsedInterval = Number.parseInt(intervalMinutes, 10)
|
||||||
|
const resolvedCronExpression = buildCronExpressionFromPreset({
|
||||||
|
preset: schedulePreset,
|
||||||
|
intervalMinutes,
|
||||||
|
timeOfDay,
|
||||||
|
hourlyMinute,
|
||||||
|
weeklyDays,
|
||||||
|
monthlyDay,
|
||||||
|
cronExpression,
|
||||||
|
})
|
||||||
|
const baseFields = {
|
||||||
|
name: name.trim(),
|
||||||
|
description: description.trim() || undefined,
|
||||||
|
enabled,
|
||||||
|
agentSlug: agentSlug.trim() || undefined,
|
||||||
|
model: model.trim() || undefined,
|
||||||
|
prompt: prompt.trim(),
|
||||||
|
skillMetadata: skillSlugs.trim() || skillNotes.trim()
|
||||||
|
? {
|
||||||
|
skillSlugs: skillSlugs.split(',').map((value) => value.trim()).filter(Boolean),
|
||||||
|
notes: skillNotes.trim() || undefined,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (schedulePreset !== 'interval') {
|
||||||
|
onSubmit({
|
||||||
|
...baseFields,
|
||||||
|
scheduleMode: 'cron',
|
||||||
|
cronExpression: resolvedCronExpression,
|
||||||
|
timezone: timezone.trim() || 'UTC',
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit({
|
||||||
|
...baseFields,
|
||||||
|
scheduleMode: 'interval',
|
||||||
|
intervalMinutes: Number.isNaN(parsedInterval) ? 60 : parsedInterval,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const isScheduleConfigInvalid =
|
||||||
|
(schedulePreset === 'advanced' && (!cronExpression.trim() || !timezone.trim())) ||
|
||||||
|
((schedulePreset === 'daily' || schedulePreset === 'weekdays' || schedulePreset === 'weekly' || schedulePreset === 'monthly') && !timezone.trim()) ||
|
||||||
|
(schedulePreset === 'weekly' && weeklyDays.length === 0)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent
|
||||||
|
overlayClassName="bg-black/80"
|
||||||
|
className="flex h-dvh max-h-dvh w-full max-w-4xl flex-col gap-0 overflow-hidden border-border bg-background p-0 shadow-lg sm:h-[min(85vh,760px)] sm:max-h-[85vh] sm:w-[calc(100vw-1rem)]"
|
||||||
|
>
|
||||||
|
<DialogHeader className="shrink-0 space-y-1 px-3 sm:px-6 pt-6 pb-3 pr-14">
|
||||||
|
<DialogTitle>{job ? 'Edit schedule' : 'New schedule'}</DialogTitle>
|
||||||
|
<DialogDescription className="mt-0">
|
||||||
|
Create a reusable repo job with a visual schedule builder, manual runs, and optional advanced metadata.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<Tabs defaultValue="basics" className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||||
|
<div className="border-b border-border px-3 sm:px-6 pb-3">
|
||||||
|
<TabsList className="grid h-9 w-full grid-cols-4 bg-card p-0.5">
|
||||||
|
<TabsTrigger value="basics" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">General</TabsTrigger>
|
||||||
|
<TabsTrigger value="timing" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Timing</TabsTrigger>
|
||||||
|
<TabsTrigger value="prompt" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Prompt</TabsTrigger>
|
||||||
|
<TabsTrigger value="skills" className="h-8 px-2 text-xs sm:text-sm data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm">Skills</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TabsContent value="basics" className="mt-0 min-h-0 flex-1 overflow-y-auto pt-4 pb-5">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-name">Name</Label>
|
||||||
|
<Input id="schedule-name" value={name} onChange={(event) => setName(event.target.value)} placeholder="Nightly repo health check" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-description">Description</Label>
|
||||||
|
<Input id="schedule-description" value={description} onChange={(event) => setDescription(event.target.value)} placeholder="What this job checks or produces" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_220px] sm:items-end">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-agent">Agent slug</Label>
|
||||||
|
<Combobox
|
||||||
|
value={agentSlug}
|
||||||
|
onChange={setAgentSlug}
|
||||||
|
options={agentOptions}
|
||||||
|
placeholder="Select an agent"
|
||||||
|
allowCustomValue
|
||||||
|
showClear
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Label htmlFor="schedule-model">Model override</Label>
|
||||||
|
<InfoHint text="Pick from detected OpenCode models or type a custom provider/model value." />
|
||||||
|
</div>
|
||||||
|
<Combobox
|
||||||
|
value={model}
|
||||||
|
onChange={setModel}
|
||||||
|
options={modelOptions}
|
||||||
|
placeholder="Workspace default"
|
||||||
|
allowCustomValue
|
||||||
|
showClear
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="flex items-center justify-between gap-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="text-sm font-medium">Enabled</p>
|
||||||
|
<InfoHint text="Auto-run this job on its schedule while still allowing manual runs from the dashboard." />
|
||||||
|
</div>
|
||||||
|
<Switch checked={enabled} onCheckedChange={setEnabled} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="timing" className="px-3 mt-0 min-h-0 flex-1 overflow-y-auto sm:px-6 pt-4 pb-5">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-3 rounded-lg border border-border bg-card p-4">
|
||||||
|
<div>
|
||||||
|
<Label>Repeat</Label>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">Use a simple scheduler builder by default. Advanced cron is still available if you need it.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{schedulePresetOptions.map((option) => (
|
||||||
|
<Button
|
||||||
|
key={option.value}
|
||||||
|
type="button"
|
||||||
|
variant={schedulePreset === option.value ? 'default' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setSchedulePreset(option.value)}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{schedulePreset === 'interval' ? (
|
||||||
|
<div className="space-y-3 rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<Label htmlFor="schedule-interval">Run every</Label>
|
||||||
|
<Input
|
||||||
|
id="schedule-interval"
|
||||||
|
type="number"
|
||||||
|
min={5}
|
||||||
|
max={10080}
|
||||||
|
value={intervalMinutes}
|
||||||
|
onChange={(event) => setIntervalMinutes(event.target.value)}
|
||||||
|
className="w-28"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{intervalOptions.map((option) => (
|
||||||
|
<Button key={option.value} type="button" variant={intervalMinutes === String(option.value) ? 'default' : 'outline'} size="sm" onClick={() => setIntervalMinutes(String(option.value))}>
|
||||||
|
{option.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : schedulePreset === 'hourly' ? (
|
||||||
|
<div className="grid gap-4 rounded-lg border border-border bg-card p-4 sm:grid-cols-[120px_minmax(0,1fr)] sm:items-end">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-hourly-minute">Minute</Label>
|
||||||
|
<Input
|
||||||
|
id="schedule-hourly-minute"
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={59}
|
||||||
|
value={hourlyMinute}
|
||||||
|
onChange={(event) => setHourlyMinute(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">Run every hour at the selected minute mark.</p>
|
||||||
|
</div>
|
||||||
|
) : schedulePreset === 'daily' || schedulePreset === 'weekdays' ? (
|
||||||
|
<div className="grid gap-4 rounded-lg border border-border bg-card p-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-time">Time</Label>
|
||||||
|
<Input id="schedule-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-timezone">Timezone</Label>
|
||||||
|
<Input id="schedule-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : schedulePreset === 'weekly' ? (
|
||||||
|
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Days</Label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{weekdayOptions.map((option) => {
|
||||||
|
const selected = weeklyDays.includes(option.value)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
key={option.value}
|
||||||
|
type="button"
|
||||||
|
variant={selected ? 'default' : 'outline'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setWeeklyDays((current) => selected ? current.filter((value) => value !== option.value) : [...current, option.value])}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-weekly-time">Time</Label>
|
||||||
|
<Input id="schedule-weekly-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-weekly-timezone">Timezone</Label>
|
||||||
|
<Input id="schedule-weekly-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : schedulePreset === 'monthly' ? (
|
||||||
|
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-3">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-monthly-day">Day</Label>
|
||||||
|
<Input
|
||||||
|
id="schedule-monthly-day"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={31}
|
||||||
|
value={monthlyDay}
|
||||||
|
onChange={(event) => setMonthlyDay(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-monthly-time">Time</Label>
|
||||||
|
<Input id="schedule-monthly-time" type="time" value={timeOfDay} onChange={(event) => setTimeOfDay(event.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-monthly-timezone">Timezone</Label>
|
||||||
|
<Input id="schedule-monthly-timezone" value={timezone} onChange={(event) => setTimezone(event.target.value)} placeholder="Detected from browser" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4 rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-cron">Cron expression</Label>
|
||||||
|
<Input
|
||||||
|
id="schedule-cron"
|
||||||
|
value={cronExpression}
|
||||||
|
onChange={(event) => setCronExpression(event.target.value)}
|
||||||
|
placeholder="0 9 * * 1-5"
|
||||||
|
className="font-mono"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">Examples: `0 9 * * 1-5` weekdays at 9 AM, `30 6 1 * *` monthly on the 1st at 6:30 AM.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-timezone">Timezone</Label>
|
||||||
|
<Input
|
||||||
|
id="schedule-timezone"
|
||||||
|
value={timezone}
|
||||||
|
onChange={(event) => setTimezone(event.target.value)}
|
||||||
|
placeholder="Detected from browser"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{cronPresetOptions.map((option) => (
|
||||||
|
<Button key={option.value} type="button" variant="outline" size="sm" onClick={() => setCronExpression(option.value)}>
|
||||||
|
{option.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="rounded-lg border border-border bg-muted/40 p-4">
|
||||||
|
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Schedule Preview</p>
|
||||||
|
<p className="mt-2 text-sm font-medium break-words">{formatDraftScheduleSummary({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression, timezone })}</p>
|
||||||
|
{schedulePreset !== 'interval' && (
|
||||||
|
<p className="mt-2 text-xs text-muted-foreground font-mono break-all">
|
||||||
|
{buildCronExpressionFromPreset({ preset: schedulePreset, intervalMinutes, timeOfDay, hourlyMinute, weeklyDays, monthlyDay, cronExpression })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="prompt" className="mt-0 min-h-0 flex-1 overflow-y-auto px-3 pt-4 pb-5 sm:px-4">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<Label>Prompt templates</Label>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-7 gap-1 text-xs"
|
||||||
|
onClick={() => { setEditingTemplate(undefined); setTemplateDialogOpen(true) }}
|
||||||
|
>
|
||||||
|
<Plus className="h-3 w-3" />
|
||||||
|
New
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 lg:grid-cols-2">
|
||||||
|
{templates.map((template) => {
|
||||||
|
const isSelected = selectedPromptTemplateId === template.id
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={template.id} className="relative group">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => applyPromptTemplate(template)}
|
||||||
|
className={`w-full rounded-xl border-2 p-4 text-left transition-all ${
|
||||||
|
isSelected
|
||||||
|
? 'border-primary bg-primary/10 ring-2 ring-primary/30'
|
||||||
|
: 'border-border bg-card hover:bg-accent/40'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-orange-500 text-white">
|
||||||
|
{template.category}
|
||||||
|
</Badge>
|
||||||
|
<Badge className="text-[10px] uppercase tracking-wide border-transparent bg-slate-600 text-white">
|
||||||
|
{template.cadenceHint}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="mt-3">
|
||||||
|
<p className="text-sm font-semibold">{template.title}</p>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">{template.description}</p>
|
||||||
|
</div>
|
||||||
|
<p className="mt-3 text-xs text-muted-foreground line-clamp-3">{template.suggestedDescription}</p>
|
||||||
|
{isSelected && (
|
||||||
|
<div className="absolute top-2 right-2 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||||
|
<Check className="h-3 w-3 text-primary-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<div className={`absolute top-2 right-10 flex gap-1 transition-opacity ${isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-6 w-6"
|
||||||
|
onClick={(e) => { e.stopPropagation(); setEditingTemplate(template); setTemplateDialogOpen(true) }}
|
||||||
|
>
|
||||||
|
<Pencil className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-6 w-6 text-destructive hover:text-destructive"
|
||||||
|
onClick={(e) => { e.stopPropagation(); setDeletingTemplateId(template.id) }}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-prompt">Prompt</Label>
|
||||||
|
<Textarea
|
||||||
|
id="schedule-prompt"
|
||||||
|
value={prompt}
|
||||||
|
onChange={(event) => {
|
||||||
|
setPrompt(event.target.value)
|
||||||
|
setSelectedPromptTemplateId(null)
|
||||||
|
}}
|
||||||
|
className="min-h-[320px]"
|
||||||
|
placeholder="Review the repo, summarize notable risks, and open a session I can inspect later."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
This prompt becomes the first message sent to the agent when the schedule runs.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="skills" className="mt-0 min-h-0 flex-1 overflow-y-auto px-6 pt-4 pb-5">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<section className="rounded-lg border border-border bg-card p-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<h3 className="text-base font-medium flex items-center gap-2"><Sparkles className="h-4 w-4" /> Optional future integrations</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">You can ignore this for now. These fields are stored for future skill-aware scheduling, but the current MVP does not use them during execution.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<details className="group rounded-lg border border-dashed border-border bg-card/50 p-4">
|
||||||
|
<summary className="cursor-pointer list-none text-sm font-medium">Edit optional skill metadata</summary>
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-skills">Skill tags</Label>
|
||||||
|
<Input id="schedule-skills" value={skillSlugs} onChange={(event) => setSkillSlugs(event.target.value)} placeholder="nextjs, database-tuning" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="schedule-skill-notes">Notes</Label>
|
||||||
|
<Textarea id="schedule-skill-notes" value={skillNotes} onChange={(event) => setSkillNotes(event.target.value)} placeholder="Optional notes for a future skill-aware scheduler." />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
|
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row gap-2 sm:justify-end">
|
||||||
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
|
||||||
|
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid} className="flex-1 sm:flex-none">
|
||||||
|
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||||
|
{isSaving ? 'Saving...' : job ? 'Save changes' : 'Create schedule'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
<PromptTemplateDialog
|
||||||
|
open={templateDialogOpen}
|
||||||
|
onOpenChange={setTemplateDialogOpen}
|
||||||
|
template={editingTemplate}
|
||||||
|
/>
|
||||||
|
<DeleteDialog
|
||||||
|
open={deletingTemplateId !== null}
|
||||||
|
onOpenChange={(open) => { if (!open && !deleteTemplateMutation.isPending) setDeletingTemplateId(null) }}
|
||||||
|
onConfirm={() => {
|
||||||
|
if (deletingTemplateId !== null) {
|
||||||
|
deleteTemplateMutation.mutate(deletingTemplateId, {
|
||||||
|
onSuccess: () => setDeletingTemplateId(null),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onCancel={() => { if (!deleteTemplateMutation.isPending) setDeletingTemplateId(null) }}
|
||||||
|
title="Delete template"
|
||||||
|
description="Are you sure you want to delete this template?"
|
||||||
|
isDeleting={deleteTemplateMutation.isPending}
|
||||||
|
/>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import ReactMarkdown from 'react-markdown'
|
||||||
|
import rehypeHighlight from 'rehype-highlight'
|
||||||
|
import rehypeRaw from 'rehype-raw'
|
||||||
|
import remarkGfm from 'remark-gfm'
|
||||||
|
import { markdownComponents } from '@/components/file-browser/MarkdownComponents'
|
||||||
|
|
||||||
|
type ScheduleRunMarkdownProps = {
|
||||||
|
content: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ScheduleRunMarkdown({ content }: ScheduleRunMarkdownProps) {
|
||||||
|
return (
|
||||||
|
<div className="overflow-hidden">
|
||||||
|
<div className="prose prose-invert prose-enhanced max-w-none break-words text-foreground leading-snug">
|
||||||
|
<ReactMarkdown
|
||||||
|
remarkPlugins={[remarkGfm]}
|
||||||
|
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||||
|
components={markdownComponents}
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export { JobsTab } from './JobsTab'
|
||||||
|
export { JobDetailTab } from './JobDetailTab'
|
||||||
|
export { RunHistoryTab } from './RunHistoryTab'
|
||||||
|
export { ScheduleJobDialog } from './ScheduleJobDialog'
|
||||||
|
export { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
import cronstrue from 'cronstrue'
|
||||||
|
import { formatDistanceToNow } from 'date-fns'
|
||||||
|
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||||
|
|
||||||
|
export const intervalOptions = [
|
||||||
|
{ label: '15m', value: 15 },
|
||||||
|
{ label: '30m', value: 30 },
|
||||||
|
{ label: '1h', value: 60 },
|
||||||
|
{ label: '4h', value: 240 },
|
||||||
|
{ label: '1d', value: 1440 },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const cronPresetOptions = [
|
||||||
|
{ label: 'Weekdays 9 AM', value: '0 9 * * 1-5' },
|
||||||
|
{ label: 'Daily 9 AM', value: '0 9 * * *' },
|
||||||
|
{ label: 'Twice daily', value: '0 9,17 * * *' },
|
||||||
|
{ label: 'Mondays 8 AM', value: '0 8 * * 1' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export const schedulePresetOptions = [
|
||||||
|
{ label: 'Interval', value: 'interval' },
|
||||||
|
{ label: 'Hourly', value: 'hourly' },
|
||||||
|
{ label: 'Daily', value: 'daily' },
|
||||||
|
{ label: 'Weekdays', value: 'weekdays' },
|
||||||
|
{ label: 'Weekly', value: 'weekly' },
|
||||||
|
{ label: 'Monthly', value: 'monthly' },
|
||||||
|
{ label: 'Advanced', value: 'advanced' },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const weekdayOptions = [
|
||||||
|
{ label: 'Mon', value: '1' },
|
||||||
|
{ label: 'Tue', value: '2' },
|
||||||
|
{ label: 'Wed', value: '3' },
|
||||||
|
{ label: 'Thu', value: '4' },
|
||||||
|
{ label: 'Fri', value: '5' },
|
||||||
|
{ label: 'Sat', value: '6' },
|
||||||
|
{ label: 'Sun', value: '0' },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type SchedulePreset = typeof schedulePresetOptions[number]['value']
|
||||||
|
|
||||||
|
export function getLocalTimeZone(): string {
|
||||||
|
try {
|
||||||
|
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
|
||||||
|
} catch {
|
||||||
|
return 'UTC'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNumericToken(value: string): boolean {
|
||||||
|
return /^\d+$/.test(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTimeValue(value: string): { hour: number; minute: number } {
|
||||||
|
const [hourValue = '9', minuteValue = '0'] = value.split(':')
|
||||||
|
const hour = Number.parseInt(hourValue, 10)
|
||||||
|
const minute = Number.parseInt(minuteValue, 10)
|
||||||
|
|
||||||
|
return {
|
||||||
|
hour: Number.isNaN(hour) ? 9 : Math.min(Math.max(hour, 0), 23),
|
||||||
|
minute: Number.isNaN(minute) ? 0 : Math.min(Math.max(minute, 0), 59),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toTimeValue(hour: number, minute: number): string {
|
||||||
|
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function expandDayOfWeekExpression(expression: string): string[] | null {
|
||||||
|
const days = new Set<string>()
|
||||||
|
|
||||||
|
for (const token of expression.split(',')) {
|
||||||
|
const trimmedToken = token.trim()
|
||||||
|
|
||||||
|
if (!trimmedToken) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNumericToken(trimmedToken)) {
|
||||||
|
const normalized = trimmedToken === '7' ? '0' : trimmedToken
|
||||||
|
if (!weekdayOptions.some((option) => option.value === normalized)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
days.add(normalized)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const rangeMatch = trimmedToken.match(/^(\d)-(\d)$/)
|
||||||
|
if (rangeMatch) {
|
||||||
|
const start = rangeMatch[1] === '7' ? 0 : Number.parseInt(rangeMatch[1], 10)
|
||||||
|
const end = rangeMatch[2] === '7' ? 0 : Number.parseInt(rangeMatch[2], 10)
|
||||||
|
|
||||||
|
if (start > end) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let value = start; value <= end; value += 1) {
|
||||||
|
days.add(String(value))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return weekdayOptions.filter((option) => days.has(option.value)).map((option) => option.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortWeekdayValues(values: string[]): string[] {
|
||||||
|
const order = new Map<string, number>(weekdayOptions.map((option, index) => [option.value, index]))
|
||||||
|
return [...new Set(values)].sort((left, right) => (order.get(left) ?? 99) - (order.get(right) ?? 99))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectSchedulePreset(job?: ScheduleJob): {
|
||||||
|
preset: SchedulePreset
|
||||||
|
intervalMinutes: string
|
||||||
|
timeOfDay: string
|
||||||
|
hourlyMinute: string
|
||||||
|
weeklyDays: string[]
|
||||||
|
monthlyDay: string
|
||||||
|
cronExpression: string
|
||||||
|
timezone: string
|
||||||
|
} {
|
||||||
|
const defaultTimezone = job?.timezone ?? getLocalTimeZone()
|
||||||
|
const defaults = {
|
||||||
|
preset: 'interval' as SchedulePreset,
|
||||||
|
intervalMinutes: String(job?.intervalMinutes ?? 60),
|
||||||
|
timeOfDay: '09:00',
|
||||||
|
hourlyMinute: '0',
|
||||||
|
weeklyDays: ['1'],
|
||||||
|
monthlyDay: '1',
|
||||||
|
cronExpression: job?.cronExpression ?? '0 9 * * 1-5',
|
||||||
|
timezone: defaultTimezone,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!job || job.scheduleMode === 'interval') {
|
||||||
|
return defaults
|
||||||
|
}
|
||||||
|
|
||||||
|
const expression = job.cronExpression?.trim() ?? ''
|
||||||
|
const fields = expression.split(/\s+/)
|
||||||
|
if (fields.length !== 5) {
|
||||||
|
return { ...defaults, preset: 'advanced', cronExpression: expression || defaults.cronExpression }
|
||||||
|
}
|
||||||
|
|
||||||
|
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields
|
||||||
|
if (!isNumericToken(minute)) {
|
||||||
|
return { ...defaults, preset: 'advanced', cronExpression: expression }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (month === '*' && hour === '*' && dayOfMonth === '*' && dayOfWeek === '*') {
|
||||||
|
return {
|
||||||
|
...defaults,
|
||||||
|
preset: 'hourly',
|
||||||
|
hourlyMinute: minute,
|
||||||
|
cronExpression: expression,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isNumericToken(hour)) {
|
||||||
|
return { ...defaults, preset: 'advanced', cronExpression: expression }
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeOfDay = toTimeValue(Number.parseInt(hour, 10), Number.parseInt(minute, 10))
|
||||||
|
|
||||||
|
if (month === '*' && dayOfMonth === '*' && dayOfWeek === '*') {
|
||||||
|
return { ...defaults, preset: 'daily', timeOfDay, cronExpression: expression }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (month === '*' && dayOfMonth === '*' && dayOfWeek === '1-5') {
|
||||||
|
return { ...defaults, preset: 'weekdays', timeOfDay, cronExpression: expression, weeklyDays: ['1', '2', '3', '4', '5'] }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (month === '*' && dayOfMonth === '*') {
|
||||||
|
const weeklyDays = expandDayOfWeekExpression(dayOfWeek)
|
||||||
|
if (weeklyDays && weeklyDays.length > 0) {
|
||||||
|
return { ...defaults, preset: 'weekly', timeOfDay, weeklyDays, cronExpression: expression }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (month === '*' && dayOfWeek === '*' && isNumericToken(dayOfMonth)) {
|
||||||
|
return {
|
||||||
|
...defaults,
|
||||||
|
preset: 'monthly',
|
||||||
|
timeOfDay,
|
||||||
|
monthlyDay: dayOfMonth,
|
||||||
|
cronExpression: expression,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...defaults, preset: 'advanced', timeOfDay, cronExpression: expression }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCronExpressionFromPreset(input: {
|
||||||
|
preset: SchedulePreset
|
||||||
|
intervalMinutes?: string
|
||||||
|
timeOfDay: string
|
||||||
|
hourlyMinute: string
|
||||||
|
weeklyDays: string[]
|
||||||
|
monthlyDay: string
|
||||||
|
cronExpression: string
|
||||||
|
}): string {
|
||||||
|
const { hour, minute } = parseTimeValue(input.timeOfDay)
|
||||||
|
|
||||||
|
switch (input.preset) {
|
||||||
|
case 'hourly':
|
||||||
|
return `${Math.min(Math.max(Number.parseInt(input.hourlyMinute, 10) || 0, 0), 59)} * * * *`
|
||||||
|
case 'daily':
|
||||||
|
return `${minute} ${hour} * * *`
|
||||||
|
case 'weekdays':
|
||||||
|
return `${minute} ${hour} * * 1-5`
|
||||||
|
case 'weekly':
|
||||||
|
return `${minute} ${hour} * * ${sortWeekdayValues(input.weeklyDays).join(',') || '1'}`
|
||||||
|
case 'monthly':
|
||||||
|
return `${minute} ${hour} ${Math.min(Math.max(Number.parseInt(input.monthlyDay, 10) || 1, 1), 31)} * *`
|
||||||
|
case 'advanced':
|
||||||
|
return input.cronExpression.trim()
|
||||||
|
default:
|
||||||
|
return input.cronExpression.trim()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatIntervalLabel(intervalMinutes: number | null): string {
|
||||||
|
if (!intervalMinutes) {
|
||||||
|
return 'Custom interval'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intervalMinutes % 1440 === 0) {
|
||||||
|
const days = intervalMinutes / 1440
|
||||||
|
return `Every ${days} day${days === 1 ? '' : 's'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intervalMinutes % 60 === 0) {
|
||||||
|
const hours = intervalMinutes / 60
|
||||||
|
return `Every ${hours} hour${hours === 1 ? '' : 's'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return `Every ${intervalMinutes} minute${intervalMinutes === 1 ? '' : 's'}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCronHumanText(cronExpression: string | null): string | null {
|
||||||
|
if (!cronExpression) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return cronstrue.toString(cronExpression, {
|
||||||
|
throwExceptionOnParseError: true,
|
||||||
|
use24HourTimeFormat: false,
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatScheduleSummary(job: ScheduleJob): string {
|
||||||
|
if (job.scheduleMode === 'cron') {
|
||||||
|
return `${formatCronHumanText(job.cronExpression) ?? (job.cronExpression ?? 'Custom cron')}${job.timezone ? ` - ${job.timezone}` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatIntervalLabel(job.intervalMinutes)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatScheduleShortLabel(job: ScheduleJob): string {
|
||||||
|
if (job.scheduleMode === 'cron') {
|
||||||
|
return 'Cron schedule'
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatIntervalLabel(job.intervalMinutes)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDraftScheduleSummary(input: {
|
||||||
|
preset: SchedulePreset
|
||||||
|
intervalMinutes: string
|
||||||
|
timeOfDay: string
|
||||||
|
hourlyMinute: string
|
||||||
|
weeklyDays: string[]
|
||||||
|
monthlyDay: string
|
||||||
|
cronExpression: string
|
||||||
|
timezone: string
|
||||||
|
}): string {
|
||||||
|
if (input.preset === 'interval') {
|
||||||
|
const parsedInterval = Number.parseInt(input.intervalMinutes, 10)
|
||||||
|
return formatIntervalLabel(Number.isNaN(parsedInterval) ? null : parsedInterval)
|
||||||
|
}
|
||||||
|
|
||||||
|
const builtCronExpression = buildCronExpressionFromPreset(input)
|
||||||
|
const humanText = formatCronHumanText(builtCronExpression)
|
||||||
|
|
||||||
|
return builtCronExpression
|
||||||
|
? `${humanText ?? builtCronExpression} - ${input.timezone.trim() || 'UTC'}`
|
||||||
|
: 'Choose a schedule'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toUpdateScheduleRequest(data: CreateScheduleJobRequest): UpdateScheduleJobRequest {
|
||||||
|
if (data.scheduleMode === 'cron') {
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
description: data.description ?? null,
|
||||||
|
agentSlug: data.agentSlug ?? null,
|
||||||
|
model: data.model ?? null,
|
||||||
|
intervalMinutes: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
description: data.description ?? null,
|
||||||
|
agentSlug: data.agentSlug ?? null,
|
||||||
|
model: data.model ?? null,
|
||||||
|
cronExpression: null,
|
||||||
|
timezone: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatTimestamp(value: number | null): string {
|
||||||
|
if (!value) {
|
||||||
|
return 'Never'
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${new Date(value).toLocaleString()} (${formatDistanceToNow(value, { addSuffix: true })})`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRunTone(run: ScheduleRun): string {
|
||||||
|
if (run.status === 'completed') {
|
||||||
|
return 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (run.status === 'failed') {
|
||||||
|
return 'bg-red-500/15 text-red-300 border-red-500/30'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (run.status === 'cancelled') {
|
||||||
|
return 'bg-slate-500/15 text-slate-300 border-slate-500/30'
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'bg-amber-500/15 text-amber-300 border-amber-500/30'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getJobStatusTone(job: ScheduleJob): string {
|
||||||
|
return job.enabled
|
||||||
|
? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20'
|
||||||
|
: 'bg-muted text-muted-foreground border-border'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasSkillMetadata(job?: ScheduleJob | null): boolean {
|
||||||
|
if (!job?.skillMetadata) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return job.skillMetadata.skillSlugs.length > 0 || Boolean(job.skillMetadata.notes?.trim())
|
||||||
|
}
|
||||||
@@ -216,7 +216,7 @@ function HeaderMobileDropdown({ children, className }: { children: ReactNode; cl
|
|||||||
{totalPending > 0 && children && <DropdownMenuSeparator />}
|
{totalPending > 0 && children && <DropdownMenuSeparator />}
|
||||||
{children}
|
{children}
|
||||||
{children && <DropdownMenuSeparator />}
|
{children && <DropdownMenuSeparator />}
|
||||||
<DropdownMenuItem onClick={open} className="gap-2">
|
<DropdownMenuItem onClick={open} className="gap-2 bg-muted">
|
||||||
<Settings className="w-4 h-4" />
|
<Settings className="w-4 h-4" />
|
||||||
<span>Settings</span>
|
<span>Settings</span>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ const TabsContent = React.forwardRef<
|
|||||||
<TabsPrimitive.Content
|
<TabsPrimitive.Content
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
"px-2 mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type { CreatePromptTemplateRequest, UpdatePromptTemplateRequest } from '@opencode-manager/shared/types'
|
||||||
|
import {
|
||||||
|
listPromptTemplates,
|
||||||
|
createPromptTemplate,
|
||||||
|
updatePromptTemplate,
|
||||||
|
deletePromptTemplate,
|
||||||
|
} from '@/api/prompt-templates'
|
||||||
|
import { showToast } from '@/lib/toast'
|
||||||
|
|
||||||
|
export function usePromptTemplates() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['prompt-templates'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await listPromptTemplates()
|
||||||
|
return response.templates
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreatePromptTemplate() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (data: CreatePromptTemplateRequest) => createPromptTemplate(data).then(r => r.template),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
|
||||||
|
showToast.success('Template created')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to create template: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdatePromptTemplate() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: ({ id, data }: { id: number; data: UpdatePromptTemplateRequest }) =>
|
||||||
|
updatePromptTemplate(id, data).then(r => r.template),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
|
||||||
|
showToast.success('Template updated')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to update template: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeletePromptTemplate() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (id: number) => deletePromptTemplate(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['prompt-templates'] })
|
||||||
|
showToast.success('Template deleted')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to delete template: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type { CreateScheduleJobRequest, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||||
|
import {
|
||||||
|
cancelRepoScheduleRun,
|
||||||
|
createRepoSchedule,
|
||||||
|
deleteRepoSchedule,
|
||||||
|
getRepoSchedule,
|
||||||
|
getRepoScheduleRun,
|
||||||
|
listRepoScheduleRuns,
|
||||||
|
listRepoSchedules,
|
||||||
|
runRepoSchedule,
|
||||||
|
updateRepoSchedule,
|
||||||
|
} from '@/api/schedules'
|
||||||
|
import { showToast } from '@/lib/toast'
|
||||||
|
|
||||||
|
export function useRepoSchedules(repoId: number | undefined) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repo-schedules', repoId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await listRepoSchedules(repoId!)
|
||||||
|
return response.jobs
|
||||||
|
},
|
||||||
|
enabled: repoId !== undefined,
|
||||||
|
refetchInterval: 5000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRepoSchedule(repoId: number | undefined, jobId: number | null) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repo-schedule', repoId, jobId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await getRepoSchedule(repoId!, jobId!)
|
||||||
|
return response.job
|
||||||
|
},
|
||||||
|
enabled: repoId !== undefined && jobId !== null,
|
||||||
|
refetchInterval: jobId !== null ? 5000 : false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRepoScheduleRuns(repoId: number | undefined, jobId: number | null, limit: number = 20) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repo-schedule-runs', repoId, jobId, limit],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await listRepoScheduleRuns(repoId!, jobId!, limit)
|
||||||
|
return response.runs
|
||||||
|
},
|
||||||
|
enabled: repoId !== undefined && jobId !== null,
|
||||||
|
refetchInterval: jobId !== null ? 5000 : false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRepoScheduleRun(repoId: number | undefined, jobId: number | null, runId: number | null) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ['repo-schedule-run', repoId, jobId, runId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await getRepoScheduleRun(repoId!, jobId!, runId!)
|
||||||
|
return response.run
|
||||||
|
},
|
||||||
|
enabled: repoId !== undefined && jobId !== null && runId !== null,
|
||||||
|
refetchInterval: runId !== null ? 5000 : false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateRepoSchedule(repoId: number | undefined) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (data: CreateScheduleJobRequest) => {
|
||||||
|
const response = await createRepoSchedule(repoId!, data)
|
||||||
|
return response.job
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
|
||||||
|
showToast.success('Schedule created')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to create schedule: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateRepoSchedule(repoId: number | undefined) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({ jobId, data }: { jobId: number; data: UpdateScheduleJobRequest }) => {
|
||||||
|
const response = await updateRepoSchedule(repoId!, jobId, data)
|
||||||
|
return response.job
|
||||||
|
},
|
||||||
|
onSuccess: (_, variables) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, variables.jobId] })
|
||||||
|
showToast.success('Schedule updated')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to update schedule: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteRepoSchedule(repoId: number | undefined) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (jobId: number) => deleteRepoSchedule(repoId!, jobId),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
|
||||||
|
showToast.success('Schedule deleted')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to delete schedule: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRunRepoSchedule(repoId: number | undefined) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (jobId: number) => {
|
||||||
|
const response = await runRepoSchedule(repoId!, jobId)
|
||||||
|
return response.run
|
||||||
|
},
|
||||||
|
onSuccess: (run) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', repoId, run.jobId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, run.jobId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule-run', repoId, run.jobId, run.id] })
|
||||||
|
showToast.success(run.status === 'running' ? 'Schedule started' : 'Schedule run completed')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to run schedule: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCancelRepoScheduleRun(repoId: number | undefined) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({ jobId, runId }: { jobId: number; runId: number }) => {
|
||||||
|
const response = await cancelRepoScheduleRun(repoId!, jobId, runId)
|
||||||
|
return response.run
|
||||||
|
},
|
||||||
|
onSuccess: (run) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedules', repoId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', repoId, run.jobId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule', repoId, run.jobId] })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repo-schedule-run', repoId, run.jobId, run.id] })
|
||||||
|
showToast.success('Schedule run cancelled')
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
showToast.error(`Failed to cancel schedule run: ${error instanceof Error ? error.message : String(error)}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ import { useSwipeBack } from "@/hooks/useMobile";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||||
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2 } from "lucide-react";
|
import { Plug, FolderOpen, Plus, GitBranch, GitCommitHorizontal, ShieldOff, Brain, Loader2, CalendarClock } from "lucide-react";
|
||||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||||
import { invalidateConfigCaches } from "@/lib/queryInvalidation";
|
import { invalidateConfigCaches } from "@/lib/queryInvalidation";
|
||||||
@@ -184,24 +184,36 @@ export function RepoDetail() {
|
|||||||
<span className="hidden sm:inline">Memory</span>
|
<span className="hidden sm:inline">Memory</span>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => navigate(`/repos/${repoId}/schedules`)}
|
||||||
|
size="sm"
|
||||||
|
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||||
|
>
|
||||||
|
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||||
|
<span className="hidden sm:inline">Schedules</span>
|
||||||
|
</Button>
|
||||||
<Header.MobileDropdown>
|
<Header.MobileDropdown>
|
||||||
|
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
||||||
|
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
||||||
|
</DropdownMenuItem>
|
||||||
{memoryPluginStatus?.memoryPluginEnabled && (
|
{memoryPluginStatus?.memoryPluginEnabled && (
|
||||||
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
||||||
<Brain className="w-4 h-4 mr-2" /> Memory
|
<Brain className="w-4 h-4 mr-2" /> Memory
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
|
||||||
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
||||||
<Plug className="w-4 h-4 mr-2" /> MCP
|
<Plug className="w-4 h-4 mr-2" /> MCP
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
|
||||||
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
||||||
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/schedules`)}>
|
||||||
|
<CalendarClock className="w-4 h-4 mr-2" /> Schedules
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
||||||
|
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
||||||
|
</DropdownMenuItem>
|
||||||
</Header.MobileDropdown>
|
</Header.MobileDropdown>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => handleCreateSession()}
|
onClick={() => handleCreateSession()}
|
||||||
|
|||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useParams } from 'react-router-dom'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
|
||||||
|
import { getRepo } from '@/api/repos'
|
||||||
|
import {
|
||||||
|
useCancelRepoScheduleRun,
|
||||||
|
useCreateRepoSchedule,
|
||||||
|
useDeleteRepoSchedule,
|
||||||
|
useRepoSchedule,
|
||||||
|
useRepoScheduleRun,
|
||||||
|
useRepoScheduleRuns,
|
||||||
|
useRepoSchedules,
|
||||||
|
useRunRepoSchedule,
|
||||||
|
useUpdateRepoSchedule,
|
||||||
|
} from '@/hooks/useSchedules'
|
||||||
|
import { ScheduleJobDialog } from '@/components/schedules/ScheduleJobDialog'
|
||||||
|
import { JobsTab, JobDetailTab, RunHistoryTab } from '@/components/schedules'
|
||||||
|
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
|
||||||
|
import { Header } from '@/components/ui/header'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||||
|
import { getRepoDisplayName, cn } from '@/lib/utils'
|
||||||
|
import { CalendarClock, History, Info, Loader2, Plus } from 'lucide-react'
|
||||||
|
|
||||||
|
export function Schedules() {
|
||||||
|
const { id } = useParams<{ id: string }>()
|
||||||
|
const repoId = id ? Number(id) : undefined
|
||||||
|
const [selectedJobId, setSelectedJobId] = useState<number | null>(null)
|
||||||
|
const [selectedRunId, setSelectedRunId] = useState<number | null>(null)
|
||||||
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
|
const [editingJob, setEditingJob] = useState<ScheduleJob | undefined>()
|
||||||
|
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
|
||||||
|
const [activeTab, setActiveTab] = useState<'jobs' | 'detail' | 'runs'>('jobs')
|
||||||
|
|
||||||
|
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||||
|
queryKey: ['repo', repoId],
|
||||||
|
queryFn: () => getRepo(repoId!),
|
||||||
|
enabled: repoId !== undefined,
|
||||||
|
})
|
||||||
|
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
|
||||||
|
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, selectedJobId)
|
||||||
|
const { data: runs, isLoading: runsLoading } = useRepoScheduleRuns(repoId, selectedJobId, 30)
|
||||||
|
const { data: selectedRunDetails, isLoading: selectedRunLoading } = useRepoScheduleRun(repoId, selectedJobId, selectedRunId)
|
||||||
|
|
||||||
|
const createMutation = useCreateRepoSchedule(repoId)
|
||||||
|
const updateMutation = useUpdateRepoSchedule(repoId)
|
||||||
|
const deleteMutation = useDeleteRepoSchedule(repoId)
|
||||||
|
const runMutation = useRunRepoSchedule(repoId)
|
||||||
|
const cancelRunMutation = useCancelRepoScheduleRun(repoId)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!jobs?.length) {
|
||||||
|
setSelectedJobId(null)
|
||||||
|
setActiveTab('jobs')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const stillExists = selectedJobId !== null && jobs.some((job) => job.id === selectedJobId)
|
||||||
|
if (!stillExists) {
|
||||||
|
setSelectedJobId(jobs[0]?.id ?? null)
|
||||||
|
setActiveTab('jobs')
|
||||||
|
}
|
||||||
|
}, [jobs, selectedJobId])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!runs?.length) {
|
||||||
|
setSelectedRunId(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const stillExists = selectedRunId !== null && runs.some((run) => run.id === selectedRunId)
|
||||||
|
if (!stillExists) {
|
||||||
|
setSelectedRunId(runs[0]?.id ?? null)
|
||||||
|
}
|
||||||
|
}, [runs, selectedRunId])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const activeRunSummary = useMemo(() => runs?.find((run) => run.id === selectedRunId) ?? null, [runs, selectedRunId])
|
||||||
|
const activeRun = selectedRunDetails ?? activeRunSummary
|
||||||
|
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
|
||||||
|
|
||||||
|
if (repoLoading || jobsLoading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||||
|
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!repo || repoId === undefined) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||||
|
<p className="text-muted-foreground">Repository not found</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath)
|
||||||
|
const enabledCount = jobs?.filter((job) => job.enabled).length ?? 0
|
||||||
|
const hasJobs = (jobs?.length ?? 0) > 0
|
||||||
|
|
||||||
|
const handleCreate = (data: CreateScheduleJobRequest) => {
|
||||||
|
createMutation.mutate(data, {
|
||||||
|
onSuccess: (job) => {
|
||||||
|
setSelectedJobId(job.id)
|
||||||
|
setDialogOpen(false)
|
||||||
|
setEditingJob(undefined)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleUpdate = (data: CreateScheduleJobRequest) => {
|
||||||
|
if (!editingJob) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updateMutation.mutate({
|
||||||
|
jobId: editingJob.id,
|
||||||
|
data: toUpdateScheduleRequest(data),
|
||||||
|
}, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setDialogOpen(false)
|
||||||
|
setEditingJob(undefined)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = () => {
|
||||||
|
if (deleteJobId === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteMutation.mutate(deleteJobId, {
|
||||||
|
onSuccess: () => {
|
||||||
|
if (selectedJobId === deleteJobId) {
|
||||||
|
setSelectedJobId(null)
|
||||||
|
}
|
||||||
|
setDeleteJobId(null)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleEnabled = () => {
|
||||||
|
if (!selectedJob) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updateMutation.mutate({
|
||||||
|
jobId: selectedJob.id,
|
||||||
|
data: { enabled: !selectedJob.enabled },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRunNow = () => {
|
||||||
|
if (!selectedJob) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
runMutation.mutate(selectedJob.id, {
|
||||||
|
onSuccess: (run) => {
|
||||||
|
setSelectedRunId(run.id)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCancelRun = () => {
|
||||||
|
if (!activeRun || activeRun.status !== 'running') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelRunMutation.mutate({
|
||||||
|
jobId: activeRun.jobId,
|
||||||
|
runId: activeRun.id,
|
||||||
|
}, {
|
||||||
|
onSuccess: (run) => {
|
||||||
|
setSelectedRunId(run.id)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSelectJob = (jobId: number) => {
|
||||||
|
setSelectedJobId(jobId)
|
||||||
|
setActiveTab('detail')
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col">
|
||||||
|
<Header>
|
||||||
|
<Header.BackButton to={`/repos/${repoId}`} />
|
||||||
|
<div className="min-w-0 flex-1 px-3">
|
||||||
|
<Header.Title className="truncate">Schedules</Header.Title>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{repoName}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
|
||||||
|
<Badge variant="outline" className={cn('h-6 rounded-full px-2 text-xs', getJobStatusTone({ enabled: true } as ScheduleJob))}>{enabledCount} enabled</Badge>
|
||||||
|
<Header.Actions>
|
||||||
|
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="hidden sm:flex">
|
||||||
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
|
New Schedule
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }} size="sm" className="sm:hidden">
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</Header.Actions>
|
||||||
|
</div>
|
||||||
|
</Header>
|
||||||
|
|
||||||
|
<div className="flex flex-1 min-h-0 flex-col overflow-hidden px-2 md:px-6">
|
||||||
|
{!hasJobs ? (
|
||||||
|
<div className="flex min-h-0 flex-1 h-full items-start">
|
||||||
|
<Card className="max-w-3xl border-dashed border-border/70">
|
||||||
|
<CardContent className="flex flex-col items-start gap-4 p-8 sm:p-10">
|
||||||
|
<div className="rounded-full border border-border bg-muted/40 p-3">
|
||||||
|
<CalendarClock className="h-6 w-6 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<p className="text-xl font-semibold tracking-tight">No schedules yet</p>
|
||||||
|
<p className="text-sm text-muted-foreground">Create a schedule for this repo to automate recurring agent work, then inspect runs, logs, and sessions here.</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => { setEditingJob(undefined); setDialogOpen(true) }}>
|
||||||
|
<Plus className="w-4 h-4 mr-2" />
|
||||||
|
Create First Schedule
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{activeTab === 'jobs' && (
|
||||||
|
<JobsTab
|
||||||
|
jobs={jobs ?? []}
|
||||||
|
selectedJobId={selectedJobId}
|
||||||
|
onSelectJob={handleSelectJob}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeTab === 'detail' && (
|
||||||
|
<JobDetailTab
|
||||||
|
selectedJob={selectedJob}
|
||||||
|
onEdit={(job) => { setEditingJob(job); setDialogOpen(true) }}
|
||||||
|
onDelete={setDeleteJobId}
|
||||||
|
onToggleEnabled={handleToggleEnabled}
|
||||||
|
onRunNow={handleRunNow}
|
||||||
|
updatePending={updateMutation.isPending}
|
||||||
|
runPending={runMutation.isPending}
|
||||||
|
runningRun={Boolean(runningRun)}
|
||||||
|
isJobFetching={isJobFetching}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeTab === 'runs' && (
|
||||||
|
<RunHistoryTab
|
||||||
|
repoId={repoId}
|
||||||
|
selectedJob={selectedJob}
|
||||||
|
runs={runs}
|
||||||
|
runsLoading={runsLoading}
|
||||||
|
selectedRunId={selectedRunId}
|
||||||
|
onSelectRun={setSelectedRunId}
|
||||||
|
activeRun={activeRun}
|
||||||
|
selectedRunLoading={selectedRunLoading}
|
||||||
|
onCancelRun={handleCancelRun}
|
||||||
|
cancelRunPending={cancelRunMutation.isPending}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasJobs && (
|
||||||
|
<div className="flex border-t border-border bg-card/80 backdrop-blur-sm pb-[env(safe-area-inset-bottom)]">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
|
||||||
|
activeTab === 'jobs'
|
||||||
|
? 'bg-primary/10 text-primary'
|
||||||
|
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||||
|
)}
|
||||||
|
onClick={() => setActiveTab('jobs')}
|
||||||
|
>
|
||||||
|
<CalendarClock className="h-5 w-5" />
|
||||||
|
<span>Jobs</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
|
||||||
|
activeTab === 'detail'
|
||||||
|
? 'bg-primary/10 text-primary'
|
||||||
|
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||||
|
)}
|
||||||
|
onClick={() => setActiveTab('detail')}
|
||||||
|
>
|
||||||
|
<Info className="h-5 w-5" />
|
||||||
|
<span>Detail</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'flex-1 flex flex-col items-center gap-1 py-2 text-xs font-medium transition-colors',
|
||||||
|
activeTab === 'runs'
|
||||||
|
? 'bg-primary/10 text-primary'
|
||||||
|
: 'bg-transparent text-muted-foreground hover:text-foreground hover:bg-muted/50'
|
||||||
|
)}
|
||||||
|
onClick={() => setActiveTab('runs')}
|
||||||
|
>
|
||||||
|
<History className="h-5 w-5" />
|
||||||
|
<span>Run History</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ScheduleJobDialog
|
||||||
|
open={dialogOpen}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
setDialogOpen(open)
|
||||||
|
if (!open) {
|
||||||
|
setEditingJob(undefined)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
job={editingJob}
|
||||||
|
isSaving={createMutation.isPending || updateMutation.isPending}
|
||||||
|
onSubmit={editingJob ? handleUpdate : handleCreate}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DeleteDialog
|
||||||
|
open={deleteJobId !== null}
|
||||||
|
onOpenChange={(open) => !open && setDeleteJobId(null)}
|
||||||
|
onConfirm={handleDelete}
|
||||||
|
onCancel={() => setDeleteJobId(null)}
|
||||||
|
title="Delete Schedule"
|
||||||
|
description="This removes the job definition and all recorded run history for it."
|
||||||
|
isDeleting={deleteMutation.isPending}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -57,6 +57,7 @@ export function SessionDetail() {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const repoId = Number(id) || 0;
|
const repoId = Number(id) || 0;
|
||||||
const { preferences, updateSettings } = useSettings();
|
const { preferences, updateSettings } = useSettings();
|
||||||
|
const { open: openSettings } = useSettingsDialog();
|
||||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const pageRef = useRef<HTMLDivElement>(null);
|
const pageRef = useRef<HTMLDivElement>(null);
|
||||||
const promptInputRef = useRef<PromptInputHandle>(null);
|
const promptInputRef = useRef<PromptInputHandle>(null);
|
||||||
@@ -128,7 +129,6 @@ export function SessionDetail() {
|
|||||||
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
|
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
|
||||||
const createSession = useCreateSession(opcodeUrl, repoDirectory);
|
const createSession = useCreateSession(opcodeUrl, repoDirectory);
|
||||||
const isTitleGenerating = useTitleGenerating(sessionId);
|
const isTitleGenerating = useTitleGenerating(sessionId);
|
||||||
const { open: openSettings } = useSettingsDialog();
|
|
||||||
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
|
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
|
||||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||||
const { isEnabled: ttsEnabled } = useTTS();
|
const { isEnabled: ttsEnabled } = useTTS();
|
||||||
@@ -432,24 +432,24 @@ export function SessionDetail() {
|
|||||||
<span className="hidden sm:inline">Settings</span>
|
<span className="hidden sm:inline">Settings</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Header.MobileDropdown>
|
<Header.MobileDropdown>
|
||||||
|
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
||||||
|
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
||||||
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
<DropdownMenuItem onClick={() => navigate(`/repos/${repoId}/memories`)}>
|
||||||
<Brain className="w-4 h-4 mr-2" /> Memory
|
<Brain className="w-4 h-4 mr-2" /> Memory
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
|
||||||
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
<DropdownMenuItem onClick={() => setMcpDialogOpen(true)}>
|
||||||
<Plug className="w-4 h-4 mr-2" /> MCP
|
<Plug className="w-4 h-4 mr-2" /> MCP
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setLspDialogOpen(true)}>
|
<DropdownMenuItem onClick={() => setLspDialogOpen(true)}>
|
||||||
<Code className="w-4 h-4 mr-2" /> LSP
|
<Code className="w-4 h-4 mr-2" /> LSP
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setFileBrowserOpen(true)}>
|
|
||||||
<FolderOpen className="w-4 h-4 mr-2" /> Files
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
<DropdownMenuItem onClick={() => setResetPermissionsOpen(true)}>
|
||||||
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
<ShieldOff className="w-4 h-4 mr-2" /> Reset Permissions
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem onClick={() => setSourceControlOpen(true)}>
|
||||||
|
<GitCommitHorizontal className="w-4 h-4 mr-2" /> Source Control
|
||||||
|
</DropdownMenuItem>
|
||||||
</Header.MobileDropdown>
|
</Header.MobileDropdown>
|
||||||
</Header.Actions>
|
</Header.Actions>
|
||||||
</Header>
|
</Header>
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ nav:
|
|||||||
- Repository & Git: features/git.md
|
- Repository & Git: features/git.md
|
||||||
- File Browser: features/files.md
|
- File Browser: features/files.md
|
||||||
- Chat & Sessions: features/chat.md
|
- Chat & Sessions: features/chat.md
|
||||||
|
- Schedules & Recurring Jobs: features/schedules.md
|
||||||
- AI Configuration: features/ai-config.md
|
- AI Configuration: features/ai-config.md
|
||||||
- Memory Plugin: features/memory.md
|
- Memory Plugin: features/memory.md
|
||||||
- MCP Servers: features/mcp.md
|
- MCP Servers: features/mcp.md
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
"memory": "pnpm --filter @opencode-manager/memory cli",
|
"memory": "pnpm --filter @opencode-manager/memory cli",
|
||||||
"predev": "bash scripts/setup-dev.sh",
|
"predev": "bash scripts/setup-dev.sh",
|
||||||
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
|
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
|
||||||
"dev:backend": "bun --watch backend/src/index.ts",
|
"dev:backend": "bun --watch-path backend/src --watch backend/src/index.ts",
|
||||||
"dev:frontend": "pnpm --filter frontend dev",
|
"dev:frontend": "pnpm --filter frontend dev",
|
||||||
"build": "pnpm run build:memory && pnpm run build:backend && pnpm run build:frontend",
|
"build": "pnpm run build:memory && pnpm run build:backend && pnpm run build:frontend",
|
||||||
"build:memory": "pnpm --filter @opencode-manager/memory build",
|
"build:memory": "pnpm --filter @opencode-manager/memory build",
|
||||||
|
|||||||
@@ -36,6 +36,9 @@ importers:
|
|||||||
better-auth:
|
better-auth:
|
||||||
specifier: ^1.4.17
|
specifier: ^1.4.17
|
||||||
version: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4)
|
version: 1.4.17(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(vitest@3.2.4)
|
||||||
|
croner:
|
||||||
|
specifier: ^10.0.1
|
||||||
|
version: 10.0.1
|
||||||
dotenv:
|
dotenv:
|
||||||
specifier: ^17.2.3
|
specifier: ^17.2.3
|
||||||
version: 17.2.3
|
version: 17.2.3
|
||||||
@@ -69,13 +72,16 @@ importers:
|
|||||||
version: 7.6.13
|
version: 7.6.13
|
||||||
'@types/bun':
|
'@types/bun':
|
||||||
specifier: latest
|
specifier: latest
|
||||||
version: 1.3.6
|
version: 1.3.10
|
||||||
'@types/eventsource':
|
'@types/eventsource':
|
||||||
specifier: ^3.0.0
|
specifier: ^3.0.0
|
||||||
version: 3.0.0
|
version: 3.0.0
|
||||||
'@types/web-push':
|
'@types/web-push':
|
||||||
specifier: ^3.6.4
|
specifier: ^3.6.4
|
||||||
version: 3.6.4
|
version: 3.6.4
|
||||||
|
'@vitest/coverage-v8':
|
||||||
|
specifier: ^3.2.4
|
||||||
|
version: 3.2.4(vitest@3.2.4)
|
||||||
'@vitest/ui':
|
'@vitest/ui':
|
||||||
specifier: ^3.2.4
|
specifier: ^3.2.4
|
||||||
version: 3.2.4(vitest@3.2.4)
|
version: 3.2.4(vitest@3.2.4)
|
||||||
@@ -157,6 +163,9 @@ importers:
|
|||||||
cmdk:
|
cmdk:
|
||||||
specifier: ^1.1.1
|
specifier: ^1.1.1
|
||||||
version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
version: 1.1.1(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||||
|
cronstrue:
|
||||||
|
specifier: ^3.13.0
|
||||||
|
version: 3.13.0
|
||||||
date-fns:
|
date-fns:
|
||||||
specifier: ^4.1.0
|
specifier: ^4.1.0
|
||||||
version: 4.1.0
|
version: 4.1.0
|
||||||
@@ -296,7 +305,7 @@ importers:
|
|||||||
devDependencies:
|
devDependencies:
|
||||||
bun-types:
|
bun-types:
|
||||||
specifier: latest
|
specifier: latest
|
||||||
version: 1.3.9
|
version: 1.3.10
|
||||||
typescript:
|
typescript:
|
||||||
specifier: ^5.7.3
|
specifier: ^5.7.3
|
||||||
version: 5.9.3
|
version: 5.9.3
|
||||||
@@ -342,6 +351,10 @@ packages:
|
|||||||
'@adobe/css-tools@4.4.4':
|
'@adobe/css-tools@4.4.4':
|
||||||
resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
|
resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
|
||||||
|
|
||||||
|
'@ampproject/remapping@2.3.0':
|
||||||
|
resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
|
||||||
|
engines: {node: '>=6.0.0'}
|
||||||
|
|
||||||
'@antfu/install-pkg@1.1.0':
|
'@antfu/install-pkg@1.1.0':
|
||||||
resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
|
resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
|
||||||
|
|
||||||
@@ -445,6 +458,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
|
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
|
||||||
engines: {node: '>=6.9.0'}
|
engines: {node: '>=6.9.0'}
|
||||||
|
|
||||||
|
'@bcoe/v8-coverage@1.0.2':
|
||||||
|
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
'@better-auth/core@1.4.17':
|
'@better-auth/core@1.4.17':
|
||||||
resolution: {integrity: sha512-WSaEQDdUO6B1CzAmissN6j0lx9fM9lcslEYzlApB5UzFaBeAOHNUONTdglSyUs6/idiZBoRvt0t/qMXCgIU8ug==}
|
resolution: {integrity: sha512-WSaEQDdUO6B1CzAmissN6j0lx9fM9lcslEYzlApB5UzFaBeAOHNUONTdglSyUs6/idiZBoRvt0t/qMXCgIU8ug==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -957,6 +974,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
|
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
|
||||||
engines: {node: '>=18.0.0'}
|
engines: {node: '>=18.0.0'}
|
||||||
|
|
||||||
|
'@istanbuljs/schema@0.1.3':
|
||||||
|
resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
'@jridgewell/gen-mapping@0.3.13':
|
'@jridgewell/gen-mapping@0.3.13':
|
||||||
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
||||||
|
|
||||||
@@ -1771,8 +1792,8 @@ packages:
|
|||||||
'@types/better-sqlite3@7.6.13':
|
'@types/better-sqlite3@7.6.13':
|
||||||
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
|
resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}
|
||||||
|
|
||||||
'@types/bun@1.3.6':
|
'@types/bun@1.3.10':
|
||||||
resolution: {integrity: sha512-uWCv6FO/8LcpREhenN1d1b6fcspAB+cefwD7uti8C8VffIv0Um08TKMn98FynpTiU38+y2dUO55T11NgDt8VAA==}
|
resolution: {integrity: sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ==}
|
||||||
|
|
||||||
'@types/chai@5.2.3':
|
'@types/chai@5.2.3':
|
||||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||||
@@ -1995,6 +2016,15 @@ packages:
|
|||||||
peerDependencies:
|
peerDependencies:
|
||||||
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
|
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
|
||||||
|
|
||||||
|
'@vitest/coverage-v8@3.2.4':
|
||||||
|
resolution: {integrity: sha512-EyF9SXU6kS5Ku/U82E259WSnvg6c8KTjppUncuNdm5QHpe17mwREHnjDzozC8x9MZ0xfBUFSaLkRv4TMA75ALQ==}
|
||||||
|
peerDependencies:
|
||||||
|
'@vitest/browser': 3.2.4
|
||||||
|
vitest: 3.2.4
|
||||||
|
peerDependenciesMeta:
|
||||||
|
'@vitest/browser':
|
||||||
|
optional: true
|
||||||
|
|
||||||
'@vitest/expect@3.2.4':
|
'@vitest/expect@3.2.4':
|
||||||
resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}
|
resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}
|
||||||
|
|
||||||
@@ -2107,6 +2137,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
|
|
||||||
|
ast-v8-to-istanbul@0.3.12:
|
||||||
|
resolution: {integrity: sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g==}
|
||||||
|
|
||||||
async@3.2.6:
|
async@3.2.6:
|
||||||
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
|
resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}
|
||||||
|
|
||||||
@@ -2131,6 +2164,10 @@ packages:
|
|||||||
balanced-match@1.0.2:
|
balanced-match@1.0.2:
|
||||||
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
|
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
|
||||||
|
|
||||||
|
balanced-match@4.0.4:
|
||||||
|
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
|
||||||
|
engines: {node: 18 || 20 || >=22}
|
||||||
|
|
||||||
bare-events@2.8.2:
|
bare-events@2.8.2:
|
||||||
resolution: {integrity: sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==}
|
resolution: {integrity: sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
@@ -2232,6 +2269,10 @@ packages:
|
|||||||
brace-expansion@2.0.2:
|
brace-expansion@2.0.2:
|
||||||
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
|
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
|
||||||
|
|
||||||
|
brace-expansion@5.0.4:
|
||||||
|
resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==}
|
||||||
|
engines: {node: 18 || 20 || >=22}
|
||||||
|
|
||||||
browserslist@4.28.1:
|
browserslist@4.28.1:
|
||||||
resolution: {integrity: sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==}
|
resolution: {integrity: sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==}
|
||||||
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
|
||||||
@@ -2250,11 +2291,8 @@ packages:
|
|||||||
buffer@6.0.3:
|
buffer@6.0.3:
|
||||||
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
|
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
|
||||||
|
|
||||||
bun-types@1.3.6:
|
bun-types@1.3.10:
|
||||||
resolution: {integrity: sha512-OlFwHcnNV99r//9v5IIOgQ9Uk37gZqrNMCcqEaExdkVq3Avwqok1bJFmvGMCkCE0FqzdY8VMOZpfpR3lwI+CsQ==}
|
resolution: {integrity: sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg==}
|
||||||
|
|
||||||
bun-types@1.3.9:
|
|
||||||
resolution: {integrity: sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg==}
|
|
||||||
|
|
||||||
cac@6.7.14:
|
cac@6.7.14:
|
||||||
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
|
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
|
||||||
@@ -2390,6 +2428,14 @@ packages:
|
|||||||
resolution: {integrity: sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==}
|
resolution: {integrity: sha512-piICUB6ei4IlTv1+653yq5+KoqfBYmj9bw6LqXoOneTMDXk5nM1qt12mFW1caG3LlJXEKW1Bp0WggEmIfQB34g==}
|
||||||
engines: {node: '>= 14'}
|
engines: {node: '>= 14'}
|
||||||
|
|
||||||
|
croner@10.0.1:
|
||||||
|
resolution: {integrity: sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g==}
|
||||||
|
engines: {node: '>=18.0'}
|
||||||
|
|
||||||
|
cronstrue@3.13.0:
|
||||||
|
resolution: {integrity: sha512-M06cKwRIN46AyuM8BOmF1HUkBTkd3/h7uYImnrH1T3wtRKBGOibVo3jZ42VheEvx8LtgZbG/4GI35vfIxYxMug==}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
cross-spawn@7.0.6:
|
cross-spawn@7.0.6:
|
||||||
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
|
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
|
||||||
engines: {node: '>= 8'}
|
engines: {node: '>= 8'}
|
||||||
@@ -2938,6 +2984,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
|
resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
|
||||||
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
|
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
|
||||||
|
|
||||||
|
html-escaper@2.0.2:
|
||||||
|
resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
|
||||||
|
|
||||||
html-url-attributes@3.0.1:
|
html-url-attributes@3.0.1:
|
||||||
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
|
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
|
||||||
|
|
||||||
@@ -3041,6 +3090,22 @@ packages:
|
|||||||
isexe@2.0.0:
|
isexe@2.0.0:
|
||||||
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
|
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
|
||||||
|
|
||||||
|
istanbul-lib-coverage@3.2.2:
|
||||||
|
resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
|
istanbul-lib-report@3.0.1:
|
||||||
|
resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
|
istanbul-lib-source-maps@5.0.6:
|
||||||
|
resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
|
istanbul-reports@3.2.0:
|
||||||
|
resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
|
||||||
|
engines: {node: '>=8'}
|
||||||
|
|
||||||
jackspeak@3.4.3:
|
jackspeak@3.4.3:
|
||||||
resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
|
resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
|
||||||
|
|
||||||
@@ -3055,6 +3120,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==}
|
resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==}
|
||||||
engines: {node: '>=0.10.0'}
|
engines: {node: '>=0.10.0'}
|
||||||
|
|
||||||
|
js-tokens@10.0.0:
|
||||||
|
resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
|
||||||
|
|
||||||
js-tokens@4.0.0:
|
js-tokens@4.0.0:
|
||||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||||
|
|
||||||
@@ -3260,6 +3328,13 @@ packages:
|
|||||||
magic-string@0.30.21:
|
magic-string@0.30.21:
|
||||||
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
|
||||||
|
|
||||||
|
magicast@0.3.5:
|
||||||
|
resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
|
||||||
|
|
||||||
|
make-dir@4.0.0:
|
||||||
|
resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
|
||||||
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
markdown-table@3.0.4:
|
markdown-table@3.0.4:
|
||||||
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
|
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
|
||||||
|
|
||||||
@@ -3419,6 +3494,10 @@ packages:
|
|||||||
minimalistic-assert@1.0.1:
|
minimalistic-assert@1.0.1:
|
||||||
resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==}
|
resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==}
|
||||||
|
|
||||||
|
minimatch@10.2.4:
|
||||||
|
resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}
|
||||||
|
engines: {node: 18 || 20 || >=22}
|
||||||
|
|
||||||
minimatch@3.1.2:
|
minimatch@3.1.2:
|
||||||
resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
|
resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
|
||||||
|
|
||||||
@@ -3969,6 +4048,10 @@ packages:
|
|||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
test-exclude@7.0.2:
|
||||||
|
resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==}
|
||||||
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
text-decoder@1.2.3:
|
text-decoder@1.2.3:
|
||||||
resolution: {integrity: sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==}
|
resolution: {integrity: sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==}
|
||||||
|
|
||||||
@@ -4367,6 +4450,11 @@ snapshots:
|
|||||||
|
|
||||||
'@adobe/css-tools@4.4.4': {}
|
'@adobe/css-tools@4.4.4': {}
|
||||||
|
|
||||||
|
'@ampproject/remapping@2.3.0':
|
||||||
|
dependencies:
|
||||||
|
'@jridgewell/gen-mapping': 0.3.13
|
||||||
|
'@jridgewell/trace-mapping': 0.3.31
|
||||||
|
|
||||||
'@antfu/install-pkg@1.1.0':
|
'@antfu/install-pkg@1.1.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
package-manager-detector: 1.6.0
|
package-manager-detector: 1.6.0
|
||||||
@@ -4510,6 +4598,8 @@ snapshots:
|
|||||||
'@babel/helper-string-parser': 7.27.1
|
'@babel/helper-string-parser': 7.27.1
|
||||||
'@babel/helper-validator-identifier': 7.28.5
|
'@babel/helper-validator-identifier': 7.28.5
|
||||||
|
|
||||||
|
'@bcoe/v8-coverage@1.0.2': {}
|
||||||
|
|
||||||
'@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)':
|
'@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@better-auth/utils': 0.3.0
|
'@better-auth/utils': 0.3.0
|
||||||
@@ -4905,6 +4995,8 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
minipass: 7.1.2
|
minipass: 7.1.2
|
||||||
|
|
||||||
|
'@istanbuljs/schema@0.1.3': {}
|
||||||
|
|
||||||
'@jridgewell/gen-mapping@0.3.13':
|
'@jridgewell/gen-mapping@0.3.13':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@jridgewell/sourcemap-codec': 1.5.5
|
'@jridgewell/sourcemap-codec': 1.5.5
|
||||||
@@ -5731,9 +5823,9 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 24.10.4
|
'@types/node': 24.10.4
|
||||||
|
|
||||||
'@types/bun@1.3.6':
|
'@types/bun@1.3.10':
|
||||||
dependencies:
|
dependencies:
|
||||||
bun-types: 1.3.6
|
bun-types: 1.3.10
|
||||||
|
|
||||||
'@types/chai@5.2.3':
|
'@types/chai@5.2.3':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -6019,6 +6111,25 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
|
'@vitest/coverage-v8@3.2.4(vitest@3.2.4)':
|
||||||
|
dependencies:
|
||||||
|
'@ampproject/remapping': 2.3.0
|
||||||
|
'@bcoe/v8-coverage': 1.0.2
|
||||||
|
ast-v8-to-istanbul: 0.3.12
|
||||||
|
debug: 4.4.3(supports-color@10.2.2)
|
||||||
|
istanbul-lib-coverage: 3.2.2
|
||||||
|
istanbul-lib-report: 3.0.1
|
||||||
|
istanbul-lib-source-maps: 5.0.6
|
||||||
|
istanbul-reports: 3.2.0
|
||||||
|
magic-string: 0.30.21
|
||||||
|
magicast: 0.3.5
|
||||||
|
std-env: 3.10.0
|
||||||
|
test-exclude: 7.0.2
|
||||||
|
tinyrainbow: 2.0.0
|
||||||
|
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
'@vitest/expect@3.2.4':
|
'@vitest/expect@3.2.4':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/chai': 5.2.3
|
'@types/chai': 5.2.3
|
||||||
@@ -6155,6 +6266,12 @@ snapshots:
|
|||||||
|
|
||||||
assertion-error@2.0.1: {}
|
assertion-error@2.0.1: {}
|
||||||
|
|
||||||
|
ast-v8-to-istanbul@0.3.12:
|
||||||
|
dependencies:
|
||||||
|
'@jridgewell/trace-mapping': 0.3.31
|
||||||
|
estree-walker: 3.0.3
|
||||||
|
js-tokens: 10.0.0
|
||||||
|
|
||||||
async@3.2.6: {}
|
async@3.2.6: {}
|
||||||
|
|
||||||
autoprefixer@10.4.23(postcss@8.5.6):
|
autoprefixer@10.4.23(postcss@8.5.6):
|
||||||
@@ -6172,6 +6289,8 @@ snapshots:
|
|||||||
|
|
||||||
balanced-match@1.0.2: {}
|
balanced-match@1.0.2: {}
|
||||||
|
|
||||||
|
balanced-match@4.0.4: {}
|
||||||
|
|
||||||
bare-events@2.8.2: {}
|
bare-events@2.8.2: {}
|
||||||
|
|
||||||
base64-js@1.5.1: {}
|
base64-js@1.5.1: {}
|
||||||
@@ -6232,6 +6351,10 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
balanced-match: 1.0.2
|
balanced-match: 1.0.2
|
||||||
|
|
||||||
|
brace-expansion@5.0.4:
|
||||||
|
dependencies:
|
||||||
|
balanced-match: 4.0.4
|
||||||
|
|
||||||
browserslist@4.28.1:
|
browserslist@4.28.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
baseline-browser-mapping: 2.9.11
|
baseline-browser-mapping: 2.9.11
|
||||||
@@ -6252,11 +6375,7 @@ snapshots:
|
|||||||
base64-js: 1.5.1
|
base64-js: 1.5.1
|
||||||
ieee754: 1.2.1
|
ieee754: 1.2.1
|
||||||
|
|
||||||
bun-types@1.3.6:
|
bun-types@1.3.10:
|
||||||
dependencies:
|
|
||||||
'@types/node': 24.10.4
|
|
||||||
|
|
||||||
bun-types@1.3.9:
|
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/node': 24.10.4
|
'@types/node': 24.10.4
|
||||||
|
|
||||||
@@ -6392,6 +6511,10 @@ snapshots:
|
|||||||
crc-32: 1.2.2
|
crc-32: 1.2.2
|
||||||
readable-stream: 4.7.0
|
readable-stream: 4.7.0
|
||||||
|
|
||||||
|
croner@10.0.1: {}
|
||||||
|
|
||||||
|
cronstrue@3.13.0: {}
|
||||||
|
|
||||||
cross-spawn@7.0.6:
|
cross-spawn@7.0.6:
|
||||||
dependencies:
|
dependencies:
|
||||||
path-key: 3.1.1
|
path-key: 3.1.1
|
||||||
@@ -7022,6 +7145,8 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- '@exodus/crypto'
|
- '@exodus/crypto'
|
||||||
|
|
||||||
|
html-escaper@2.0.2: {}
|
||||||
|
|
||||||
html-url-attributes@3.0.1: {}
|
html-url-attributes@3.0.1: {}
|
||||||
|
|
||||||
html-void-elements@3.0.0: {}
|
html-void-elements@3.0.0: {}
|
||||||
@@ -7100,6 +7225,27 @@ snapshots:
|
|||||||
|
|
||||||
isexe@2.0.0: {}
|
isexe@2.0.0: {}
|
||||||
|
|
||||||
|
istanbul-lib-coverage@3.2.2: {}
|
||||||
|
|
||||||
|
istanbul-lib-report@3.0.1:
|
||||||
|
dependencies:
|
||||||
|
istanbul-lib-coverage: 3.2.2
|
||||||
|
make-dir: 4.0.0
|
||||||
|
supports-color: 7.2.0
|
||||||
|
|
||||||
|
istanbul-lib-source-maps@5.0.6:
|
||||||
|
dependencies:
|
||||||
|
'@jridgewell/trace-mapping': 0.3.31
|
||||||
|
debug: 4.4.3(supports-color@10.2.2)
|
||||||
|
istanbul-lib-coverage: 3.2.2
|
||||||
|
transitivePeerDependencies:
|
||||||
|
- supports-color
|
||||||
|
|
||||||
|
istanbul-reports@3.2.0:
|
||||||
|
dependencies:
|
||||||
|
html-escaper: 2.0.2
|
||||||
|
istanbul-lib-report: 3.0.1
|
||||||
|
|
||||||
jackspeak@3.4.3:
|
jackspeak@3.4.3:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@isaacs/cliui': 8.0.2
|
'@isaacs/cliui': 8.0.2
|
||||||
@@ -7112,6 +7258,8 @@ snapshots:
|
|||||||
|
|
||||||
js-levenshtein@1.1.6: {}
|
js-levenshtein@1.1.6: {}
|
||||||
|
|
||||||
|
js-tokens@10.0.0: {}
|
||||||
|
|
||||||
js-tokens@4.0.0: {}
|
js-tokens@4.0.0: {}
|
||||||
|
|
||||||
js-tokens@9.0.1: {}
|
js-tokens@9.0.1: {}
|
||||||
@@ -7299,6 +7447,16 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
'@jridgewell/sourcemap-codec': 1.5.5
|
'@jridgewell/sourcemap-codec': 1.5.5
|
||||||
|
|
||||||
|
magicast@0.3.5:
|
||||||
|
dependencies:
|
||||||
|
'@babel/parser': 7.28.5
|
||||||
|
'@babel/types': 7.28.5
|
||||||
|
source-map-js: 1.2.1
|
||||||
|
|
||||||
|
make-dir@4.0.0:
|
||||||
|
dependencies:
|
||||||
|
semver: 7.7.3
|
||||||
|
|
||||||
markdown-table@3.0.4: {}
|
markdown-table@3.0.4: {}
|
||||||
|
|
||||||
marked@14.0.0: {}
|
marked@14.0.0: {}
|
||||||
@@ -7682,6 +7840,10 @@ snapshots:
|
|||||||
|
|
||||||
minimalistic-assert@1.0.1: {}
|
minimalistic-assert@1.0.1: {}
|
||||||
|
|
||||||
|
minimatch@10.2.4:
|
||||||
|
dependencies:
|
||||||
|
brace-expansion: 5.0.4
|
||||||
|
|
||||||
minimatch@3.1.2:
|
minimatch@3.1.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
brace-expansion: 1.1.12
|
brace-expansion: 1.1.12
|
||||||
@@ -8327,6 +8489,12 @@ snapshots:
|
|||||||
source-map-support: 0.5.21
|
source-map-support: 0.5.21
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
test-exclude@7.0.2:
|
||||||
|
dependencies:
|
||||||
|
'@istanbuljs/schema': 0.1.3
|
||||||
|
glob: 10.5.0
|
||||||
|
minimatch: 10.2.4
|
||||||
|
|
||||||
text-decoder@1.2.3:
|
text-decoder@1.2.3:
|
||||||
dependencies:
|
dependencies:
|
||||||
b4a: 1.7.3
|
b4a: 1.7.3
|
||||||
|
|||||||
@@ -7,3 +7,4 @@ export * from './sse'
|
|||||||
export * from './notifications'
|
export * from './notifications'
|
||||||
export * from './ssh'
|
export * from './ssh'
|
||||||
export * from './memory'
|
export * from './memory'
|
||||||
|
export * from './schedule'
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
export const ScheduleRunTriggerSourceSchema = z.enum(['manual', 'schedule'])
|
||||||
|
export type ScheduleRunTriggerSource = z.infer<typeof ScheduleRunTriggerSourceSchema>
|
||||||
|
|
||||||
|
export const ScheduleRunStatusSchema = z.enum(['running', 'completed', 'failed', 'cancelled'])
|
||||||
|
export type ScheduleRunStatus = z.infer<typeof ScheduleRunStatusSchema>
|
||||||
|
|
||||||
|
export const ScheduleModeSchema = z.enum(['interval', 'cron'])
|
||||||
|
export type ScheduleMode = z.infer<typeof ScheduleModeSchema>
|
||||||
|
|
||||||
|
export const ScheduleSkillMetadataSchema = z.object({
|
||||||
|
skillSlugs: z.array(z.string().min(1).max(100)).default([]),
|
||||||
|
notes: z.string().max(2000).optional(),
|
||||||
|
})
|
||||||
|
export type ScheduleSkillMetadata = z.infer<typeof ScheduleSkillMetadataSchema>
|
||||||
|
|
||||||
|
export const ScheduleJobSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
repoId: z.number(),
|
||||||
|
name: z.string(),
|
||||||
|
description: z.string().nullable(),
|
||||||
|
enabled: z.boolean(),
|
||||||
|
scheduleMode: ScheduleModeSchema,
|
||||||
|
intervalMinutes: z.number().int().min(5).max(10080).nullable(),
|
||||||
|
cronExpression: z.string().nullable(),
|
||||||
|
timezone: z.string().nullable(),
|
||||||
|
agentSlug: z.string().nullable(),
|
||||||
|
prompt: z.string(),
|
||||||
|
model: z.string().nullable(),
|
||||||
|
skillMetadata: ScheduleSkillMetadataSchema.nullable(),
|
||||||
|
createdAt: z.number(),
|
||||||
|
updatedAt: z.number(),
|
||||||
|
lastRunAt: z.number().nullable(),
|
||||||
|
nextRunAt: z.number().nullable(),
|
||||||
|
})
|
||||||
|
export type ScheduleJob = z.infer<typeof ScheduleJobSchema>
|
||||||
|
|
||||||
|
export const ScheduleRunSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
jobId: z.number(),
|
||||||
|
repoId: z.number(),
|
||||||
|
triggerSource: ScheduleRunTriggerSourceSchema,
|
||||||
|
status: ScheduleRunStatusSchema,
|
||||||
|
startedAt: z.number(),
|
||||||
|
finishedAt: z.number().nullable(),
|
||||||
|
createdAt: z.number(),
|
||||||
|
sessionId: z.string().nullable(),
|
||||||
|
sessionTitle: z.string().nullable(),
|
||||||
|
logText: z.string().nullable(),
|
||||||
|
responseText: z.string().nullable(),
|
||||||
|
errorText: z.string().nullable(),
|
||||||
|
})
|
||||||
|
export type ScheduleRun = z.infer<typeof ScheduleRunSchema>
|
||||||
|
|
||||||
|
const ScheduleJobBaseRequestSchema = z.object({
|
||||||
|
name: z.string().min(1).max(120),
|
||||||
|
description: z.string().max(500).optional(),
|
||||||
|
enabled: z.boolean().default(true),
|
||||||
|
agentSlug: z.string().min(1).max(100).optional(),
|
||||||
|
prompt: z.string().min(1).max(20000),
|
||||||
|
model: z.string().min(1).max(200).optional(),
|
||||||
|
skillMetadata: ScheduleSkillMetadataSchema.optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const CreateScheduleJobRequestSchema = z.discriminatedUnion('scheduleMode', [
|
||||||
|
ScheduleJobBaseRequestSchema.extend({
|
||||||
|
scheduleMode: z.literal('interval'),
|
||||||
|
intervalMinutes: z.number().int().min(5).max(10080),
|
||||||
|
}),
|
||||||
|
ScheduleJobBaseRequestSchema.extend({
|
||||||
|
scheduleMode: z.literal('cron'),
|
||||||
|
cronExpression: z.string().min(1).max(200),
|
||||||
|
timezone: z.string().min(1).max(120),
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
export type CreateScheduleJobRequest = z.infer<typeof CreateScheduleJobRequestSchema>
|
||||||
|
|
||||||
|
export const UpdateScheduleJobRequestSchema = z.object({
|
||||||
|
name: z.string().min(1).max(120).optional(),
|
||||||
|
description: z.string().max(500).nullable().optional(),
|
||||||
|
enabled: z.boolean().optional(),
|
||||||
|
scheduleMode: ScheduleModeSchema.optional(),
|
||||||
|
intervalMinutes: z.number().int().min(5).max(10080).nullable().optional(),
|
||||||
|
cronExpression: z.string().min(1).max(200).nullable().optional(),
|
||||||
|
timezone: z.string().min(1).max(120).nullable().optional(),
|
||||||
|
agentSlug: z.string().min(1).max(100).nullable().optional(),
|
||||||
|
prompt: z.string().min(1).max(20000).optional(),
|
||||||
|
model: z.string().min(1).max(200).nullable().optional(),
|
||||||
|
skillMetadata: ScheduleSkillMetadataSchema.nullable().optional(),
|
||||||
|
})
|
||||||
|
export type UpdateScheduleJobRequest = z.infer<typeof UpdateScheduleJobRequestSchema>
|
||||||
|
|
||||||
|
export const PromptTemplateSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
title: z.string(),
|
||||||
|
category: z.string(),
|
||||||
|
cadenceHint: z.string(),
|
||||||
|
suggestedName: z.string(),
|
||||||
|
suggestedDescription: z.string(),
|
||||||
|
description: z.string(),
|
||||||
|
prompt: z.string(),
|
||||||
|
createdAt: z.number(),
|
||||||
|
updatedAt: z.number(),
|
||||||
|
})
|
||||||
|
export type PromptTemplate = z.infer<typeof PromptTemplateSchema>
|
||||||
|
|
||||||
|
export const CreatePromptTemplateRequestSchema = z.object({
|
||||||
|
title: z.string().min(1).max(120).transform((s) => s.trim()),
|
||||||
|
category: z.string().min(1).max(60).transform((s) => s.trim()),
|
||||||
|
cadenceHint: z.string().min(1).max(60).transform((s) => s.trim()),
|
||||||
|
suggestedName: z.string().min(1).max(120).transform((s) => s.trim()),
|
||||||
|
suggestedDescription: z.string().max(500).default('').transform((s) => s.trim()),
|
||||||
|
description: z.string().max(500).default('').transform((s) => s.trim()),
|
||||||
|
prompt: z.string().min(1).max(20000).transform((s) => s.trim()),
|
||||||
|
})
|
||||||
|
export type CreatePromptTemplateRequest = z.infer<typeof CreatePromptTemplateRequestSchema>
|
||||||
|
|
||||||
|
export const UpdatePromptTemplateRequestSchema = CreatePromptTemplateRequestSchema.partial()
|
||||||
|
export type UpdatePromptTemplateRequest = z.infer<typeof UpdatePromptTemplateRequestSchema>
|
||||||
@@ -99,3 +99,17 @@ export type {
|
|||||||
CreateKvEntryRequest,
|
CreateKvEntryRequest,
|
||||||
UpdateKvEntryRequest,
|
UpdateKvEntryRequest,
|
||||||
} from '../schemas/memory'
|
} from '../schemas/memory'
|
||||||
|
|
||||||
|
export type {
|
||||||
|
ScheduleMode,
|
||||||
|
ScheduleRunTriggerSource,
|
||||||
|
ScheduleRunStatus,
|
||||||
|
ScheduleSkillMetadata,
|
||||||
|
ScheduleJob,
|
||||||
|
ScheduleRun,
|
||||||
|
CreateScheduleJobRequest,
|
||||||
|
UpdateScheduleJobRequest,
|
||||||
|
PromptTemplate,
|
||||||
|
CreatePromptTemplateRequest,
|
||||||
|
UpdatePromptTemplateRequest,
|
||||||
|
} from '../schemas/schedule'
|
||||||