fix(schedules): share run columns and session joins in latestRunsBySchedule

This commit is contained in:
Riqwan Thamir committed 2026-12-03 16:51:38 +01:00
1 parent 5d0ca8c790
commit 040232420e
3 files changed
+66 -70

No files matched your search

+26 -26
View File
@@ -176,32 +176,32 @@ After a confirmed connection from Apps, selecting **Open chat** records `app_con
### Runs, models, and connected services
| Event | What it records |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `turn_started` | Source, channel, background flag, execution mode, owner-requested flag, selected public model when available, and task taxonomy version when supported. |
| `turn_completed` | The same context, outcome, result (`reply`, `task_started`, `needs_owner`, `no_reply`, `failed`, `cancelled`, `interrupted`, `retried`, or `skipped`), execution/queue milliseconds, whether it ran the one-time first brief or a daily brief saved from a yes to it, bounded waiting or failure reason, and a model failure's class and HTTP status. |
| `task_classified` | One fixed task purpose, classification status, and taxonomy version for an execution segment. |
| `task_finished` | Committed task status (`done` or `cancelled`) and actor (`owner` or `agent`). |
| `prepared_work_saved` | A changed preparation or saved offer message, with `prepared` or `notified` outcome. |
| `prepared_work_updated` | Changed owner-requested control: `useful`, `not_useful`, `handled`, `dismiss`, or `snooze`. |
| `chat_stopped`, `task_stopped`, `conversation_reset` | Server-accepted stop or completed reset. |
| `tool_used` | Fixed tool category, outcome, milliseconds, and subagent flag. A failed `send_message` adds one fixed `failure_reason`: `invalid_presentation`, `invalid_arguments`, `empty_message`, `pick_with_final` or `delivery`. |
| `model_used` | Provider/public model, purpose (`agent`, `memory`, `review`, `tasks`, `task_classification`), bounded request kind, memory operation when known, attempt number when known, outcome, token counts, milliseconds, and estimated `cost_usd` when priced. |
| `model_connection_changed`, `model_connection_observed` | Provider, API-key/subscription/OAuth method, status or selected-model state, and bounded effort. |
| `connection_changed`, `connection_observed` | Public app or `custom`, connection method, and status/bounded failure reason where applicable. |
| `connection_inventory_observed` | Zero-inclusive latest observed connected app types and their count. Public app slugs and `custom` only; no account count or names. |
| `runtime_active` | Once per UTC day while Nod's engine runs, and again after a restart, with whether the engine started that day. No other property. |
| `runtime_stopped` | Once when Nod's engine shuts down in an orderly way, with how long it had been running (`under_1h`, `under_1d`, `over_1d`). No other property. |
| `channel_connection_observed` | Telegram or WhatsApp and a bounded disabled, setup-pending, connected, or configured-unverified state. No handle, number, or account ID. |
| `service_used` | App, method, outcome, milliseconds, bounded failure reason, and optional preparation phase. Local file actions count as `local_files`, without paths or file names. |
| `source_read` | Source category (`connected_app`, `tasks`, `other`), discovery/record-read operation, outcome, milliseconds, and bounded record/unavailable counts. |
| `confirmation_changed` | Asked/approved/declined/executed/expired/uncertain, fixed action kind, and turn source. |
| `secure_entry_changed` | Sign-in/payment/code kind and state: submitted, failed or uncertain for a saved login or code; requested, superseded, approved, submitted, failed or uncertain for a payment. A step stopped before entry uses failed. An uncertain step may have reached the website. |
| `settings_updated` | Accepted settings request by section, operation, and optional channel; can include unchanged writes. Channel operations name the request, not confirmed connection or disconnection. |
| `setting_changed` | Committed setting change by fixed setting, owner/agent/system actor, and bounded state when available. Includes the preparation allowance, without its amount, and the model for schedules, work Nod starts on its own, one schedule or one task as default, configured or, for the first two, light, never the model. No free-form values. |
| `schedule_changed` | Create/update/delete, once/recurring kind, bounded cadence, user/agent/system actor, and whether it is the one-time first brief or a daily brief saved from a yes to it. |
| `memory_changed` | Note/skill, save/forget/archive/clear, and owner/agent/background actor. |
| `vault_changed`, `vault_imported` | Login/card kind and operation, or number imported. No domains or inventory. |
| Event | What it records |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `turn_started` | Source, channel, background flag, execution mode, owner-requested flag, selected public model when available, and task taxonomy version when supported. |
| `turn_completed` | The same context, outcome, result (`reply`, `task_started`, `needs_owner`, `no_reply`, `failed`, `cancelled`, `interrupted`, `retried`, or `skipped`), execution/queue milliseconds, whether it ran the one-time first brief or a daily brief saved from a yes to it, bounded waiting or failure reason, and a model failure's class and HTTP status. |
| `task_classified` | One fixed task purpose, classification status, and taxonomy version for an execution segment. |
| `task_finished` | Committed task status (`done` or `cancelled`) and actor (`owner` or `agent`). |
| `prepared_work_saved` | A changed preparation or saved offer message, with `prepared` or `notified` outcome. |
| `prepared_work_updated` | Changed owner-requested control: `useful`, `not_useful`, `handled`, `dismiss`, or `snooze`. |
| `chat_stopped`, `task_stopped`, `conversation_reset` | Server-accepted stop or completed reset. |
| `tool_used` | Fixed tool category, outcome, milliseconds, and subagent flag. A failed `send_message` adds one fixed `failure_reason`: `invalid_presentation`, `invalid_arguments`, `empty_message`, `pick_with_final` or `delivery`. |
| `model_used` | Provider/public model, purpose (`agent`, `memory`, `review`, `tasks`, `task_classification`), bounded request kind, memory operation when known, attempt number when known, outcome, token counts, milliseconds, and estimated `cost_usd` when priced. |
| `model_connection_changed`, `model_connection_observed` | Provider, API-key/subscription/OAuth method, status or selected-model state, and bounded effort. |
| `connection_changed`, `connection_observed` | Public app or `custom`, connection method, and status/bounded failure reason where applicable. |
| `connection_inventory_observed` | Zero-inclusive latest observed connected app types and their count. Public app slugs and `custom` only; no account count or names. |
| `runtime_active` | Once per UTC day while Nod's engine runs, and again after a restart, with whether the engine started that day. No other property. |
| `runtime_stopped` | Once when Nod's engine shuts down in an orderly way, with how long it had been running (`under_1h`, `under_1d`, `over_1d`). No other property. |
| `channel_connection_observed` | Telegram or WhatsApp and a bounded disabled, setup-pending, connected, or configured-unverified state. No handle, number, or account ID. |
| `service_used` | App, method, outcome, milliseconds, bounded failure reason, and optional preparation phase. Local file actions count as `local_files`, without paths or file names. |
| `source_read` | Source category (`connected_app`, `tasks`, `other`), discovery/record-read operation, outcome, milliseconds, and bounded record/unavailable counts. |
| `confirmation_changed` | Asked/approved/declined/executed/expired/uncertain, fixed action kind, and turn source. |
| `secure_entry_changed` | Sign-in/payment/code kind and state: submitted, failed or uncertain for a saved login or code; requested, superseded, approved, submitted, failed or uncertain for a payment. A step stopped before entry uses failed. An uncertain step may have reached the website. |
| `settings_updated` | Accepted settings request by section, operation, and optional channel; can include unchanged writes. Channel operations name the request, not confirmed connection or disconnection. |
| `setting_changed` | Committed setting change by fixed setting, owner/agent/system actor, and bounded state when available. Includes the preparation allowance, without its amount, and the model for schedules, work Nod starts on its own, one schedule or one task as default, configured or, for the first two, light, never the model. No free-form values. |
| `schedule_changed` | Create/update/delete, once/recurring kind, bounded cadence, user/agent/system actor, and whether it is the one-time first brief or a daily brief saved from a yes to it. |
| `memory_changed` | Note/skill, save/forget/archive/clear, and owner/agent/background actor. |
| `vault_changed`, `vault_imported` | Login/card kind and operation, or number imported. No domains or inventory. |
A failed `turn_completed` has the failure reason `spending_limit`, `model`, `offline`, or `unknown`. `offline` means the request couldn't reach the model provider because of a network failure on this computer, such as a failed name lookup or no route to the provider; earlier releases counted it under `model`. A `model` failure adds `failure_class`: `authentication`, `permission`, `rate_limited`, `quota_exhausted`, `timeout`, `unavailable`, `invalid_request`, `tools_unsupported`, `context_too_large`, `output_limit`, `invalid_tool_calls`, or `unknown`. `output_limit` is a reply the model cut off at its output limit. `invalid_tool_calls` is a turn stopped because calls to one tool failed five times without a successful call and the last failure was a call Nod couldn't accept, such as invalid arguments or an unknown tool; when the last failure came from Nod's side, such as a failed trust check, the turn stays `unknown`. Earlier releases counted both under `unknown`. It also adds `provider_status`, the provider's HTTP status number, when there was one. Nod works the class out on the owner's runtime and sends only that fixed value and the number, never the provider's error text or error code. `quota_exhausted` covers a used-up quota, usage allowance, or credit balance. `context_too_large` covers a request larger than the model or its token limit accepts.
+29 -44
View File
@@ -51,6 +51,31 @@ const runTurn = `JOIN LATERAL (
ORDER BY CASE WHEN u.status='running' THEN 0 WHEN u.status='queued' THEN 1
WHEN ${waitingTurnSql('u')} THEN 2 ELSE 3 END,u.created_at DESC,u.id DESC LIMIT 1
) u ON true`;
const runColumns = `r.id,r.schedule_id AS "scheduleId",r.title,r.turn_id AS "turnId",
r.scheduled_for AS "scheduledFor",r.time_zone AS "timeZone",r.created_at AS "createdAt",
u.status,u.error,r.observation,r.observed_at AS "observedAt",
m.id AS "messageId",m.text AS "messageText",files.id AS "attachmentMessageId",
(u.status='succeeded' AND u.error IS NULL AND r.observation IS NULL AND NOT EXISTS (
SELECT 1 FROM turns st JOIN messages sm ON sm.turn_id=st.id AND sm.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id) AND sm.role='assistant'
)) AS quiet,
to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "cursorAt"`;
const runJoins = `${runTurn}
LEFT JOIN LATERAL (
SELECT m.id,left(m.text,4000) AS text
FROM turns st JOIN messages m ON m.turn_id=st.id AND m.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id)
AND m.role='assistant' AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
ORDER BY (m.text<>'') DESC,st.created_at DESC,m.created_at DESC,m.id DESC LIMIT 1
) m ON true
LEFT JOIN LATERAL (
SELECT m.id
FROM turns st JOIN messages m ON m.turn_id=st.id AND m.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id)
AND m.role='assistant' AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
AND jsonb_array_length(m.attachments)>0
ORDER BY st.created_at DESC,m.created_at DESC,m.id DESC LIMIT 1
) files ON true`;
const timingSchema = z.object({
kind: z.enum(['once', 'recurring']).default('recurring'),
cron: z.string().trim().min(1).nullable().optional(),
@@ -809,31 +834,8 @@ export function createSchedules(dependencies: ScheduleDependencies) {
const connection = shared ?? pool;
const rows = (
await connection.query<RunRow>(
`SELECT r.id,r.schedule_id AS "scheduleId",r.title,r.turn_id AS "turnId",
r.scheduled_for AS "scheduledFor",r.time_zone AS "timeZone",r.created_at AS "createdAt",
u.status,u.error,r.observation,r.observed_at AS "observedAt",
m.id AS "messageId",m.text AS "messageText",files.id AS "attachmentMessageId",
(u.status='succeeded' AND u.error IS NULL AND r.observation IS NULL AND NOT EXISTS (
SELECT 1 FROM turns st JOIN messages sm ON sm.turn_id=st.id AND sm.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id) AND sm.role='assistant'
)) AS quiet,
to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "cursorAt"
FROM schedule_runs r ${runTurn}
LEFT JOIN LATERAL (
SELECT m.id,left(m.text,4000) AS text
FROM turns st JOIN messages m ON m.turn_id=st.id AND m.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id)
AND m.role='assistant' AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
ORDER BY (m.text<>'') DESC,st.created_at DESC,m.created_at DESC,m.id DESC LIMIT 1
) m ON true
LEFT JOIN LATERAL (
SELECT m.id
FROM turns st JOIN messages m ON m.turn_id=st.id AND m.owner_id=st.owner_id
WHERE st.owner_id=r.owner_id AND (st.id=r.turn_id OR st.session_id=r.turn_id)
AND m.role='assistant' AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
AND jsonb_array_length(m.attachments)>0
ORDER BY st.created_at DESC,m.created_at DESC,m.id DESC LIMIT 1
) files ON true
`SELECT ${runColumns}
FROM schedule_runs r ${runJoins}
WHERE r.owner_id=$1 AND ($2::uuid IS NULL OR r.schedule_id=$2)
AND ($3::timestamptz IS NULL OR (r.created_at,r.id)<($3::timestamptz,$4::uuid))
ORDER BY r.created_at DESC,r.id DESC LIMIT $5`,
@@ -1067,30 +1069,13 @@ export function createSchedules(dependencies: ScheduleDependencies) {
const rows = (
await pool.query<RunRow>(
`SELECT DISTINCT ON (r.schedule_id)
r.id,r.schedule_id AS "scheduleId",r.title,r.turn_id AS "turnId",
r.scheduled_for AS "scheduledFor",r.time_zone AS "timeZone",r.created_at AS "createdAt",
u.status,u.error,r.observation,r.observed_at AS "observedAt",
m.id AS "messageId",m.text AS "messageText",files.id AS "attachmentMessageId",
to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "cursorAt"
${runColumns}
FROM (
SELECT DISTINCT ON (schedule_id) *
FROM schedule_runs
WHERE owner_id=$1 AND schedule_id=ANY($2::uuid[])
ORDER BY schedule_id,created_at DESC,id DESC
) r ${runTurn}
LEFT JOIN LATERAL (
SELECT m.id,left(m.text,4000) AS text FROM messages m
WHERE m.turn_id=u.id AND m.owner_id=u.owner_id AND m.role='assistant'
AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
ORDER BY (m.text<>'') DESC,m.created_at DESC,m.id DESC LIMIT 1
) m ON true
LEFT JOIN LATERAL (
SELECT m.id FROM messages m
WHERE m.turn_id=u.id AND m.owner_id=u.owner_id AND m.role='assistant'
AND m.hidden_at IS NULL AND ${activeThreadSql('m')}
AND jsonb_array_length(m.attachments)>0
ORDER BY m.created_at DESC,m.id DESC LIMIT 1
) files ON true
) r ${runJoins}
ORDER BY r.schedule_id`,
[ownerId, scheduleIds],
)
+11
View File
@@ -4452,6 +4452,17 @@ test(
.runs.find((entry) => entry.id === briefing.runId);
assert.equal(hiddenHistory?.messageId, null);
assert.equal(hiddenHistory?.quiet, false);
const listed = (await request('GET', '/api/schedules')).json<
Array<{
id: string;
lastRun: { id: string; messageId: string | null; quiet?: boolean } | null;
}>
>();
assert.equal(
listed.find((entry) => entry.id === briefing.scheduleId)?.lastRun?.quiet,
false,
);
assert.equal(listed.find((entry) => entry.id === watch.scheduleId)?.lastRun?.quiet, true);
await db.pool.query('UPDATE messages SET hidden_at=NULL WHERE id=$1', [
briefingRun!.messageId,
]);