fix(missions): prepare recurring activation and distinguish scheduled waiting (#1507)
Some checks are pending
Publish help / build (push) Waiting to run
Publish help / deploy (push) Blocked by required conditions

## Summary

I make recurring Missions start without a technical activation dialog
and distinguish confirmed waiting from completion (backlog item 18).

I found that Start asked for both global and project
`experimental.schedules` changes, could overwrite an explicit global
OFF, and could reject the first Play when scheduling was already ON but
lacked an activation receipt. Between passages, recurring entries could
look completed or remain green indefinitely.

## User-visible changes

- I prepare scheduling automatically on Start/Resume in the mission's
project only, without writing global configuration.
- I preserve every explicit `schedules: false` (global, project or
inherited, including masked values) and environment OFF. Refusals
identify the responsible layer, offer **Open scheduling settings** for
an authorized editable file, and keep technical details behind the
information button. `all_flags: false` is not treated as explicit
scheduling OFF.
- I release a refused activation request only when the server's
`notApplied` proof exactly matches its `requestID` and
`expectedRevision`, confirming no document mutation and no existing
intent; after correcting the setting, a fresh explicit Start works. I
retain genuinely uncertain requests, and recovery never starts Play
automatically.
- I keep the clicked action loading until the HTTP response arrives,
with `aria-busy` and an accessible announcement.
- I show confirmed waiting with the palette accent and a static neutral
underline. Prepared entries have no underline; pause and interruption
have distinct shapes; unconfirmed state is neutral.
- I keep a new successful passage green until an attentive explicit
selection or **Mark as read** acknowledges that exact passage, then
restore waiting when scheduling remains active. Restored selection and a
new result on an already selected row leave it unread. I apply the same
rules to daily entries and unified scheduled documents.

## Approach and edge cases

I resolve the native flag through `Flag.resolve` in the mission's
Location, qualify the consumed private contract against OpenCode 2.3.0,
and fail safely when it is unavailable. Already-ON scheduling produces a
ready proof without configuration writes. I retain the original identity
and digests of persisted two-target intentions, observe attempted
effects, and never replay their global writes.

I share a pure status projection and key read acknowledgements by
`passageID` / `history[].id`, rather than a schedule-wide completion
flag. Lost acknowledgements preserve the original request; explicit
reconciliation does not silently restart Play. I retain revision,
connection and ownership fences around activation and control feedback.

## Validation

I rebased the six commits onto `dev` at `c8dae86ea` without conflicts;
`git range-diff` confirmed all six patches unchanged.

- I reran both server/UI typechecks successfully.
- Before the review fixes, I reran the focused server
activation/capability/flag/calendar/route/contract tests successfully.
- Before the review fixes, I reran the ten Mission browser files after
the rebase successfully.
- I reran the help checks: **31/31 passed**, validating **28 pages × 10
languages**.
- I verified [PR Build Validation run
43573451762](https://github.com/NeuralNomadsAI/CodeNomad/actions/runs/43573451762):
**success** at `2e22de117d`, including all
four browser shards. I retain the preceding final-QA evidence that the
start-intent file passed **9/9 five consecutive times**.
- I verified the isolated native OpenCode 2.3.0 activation/settings
qualification logs and the already-ON → Play → admitted-passage receipt.
They cover project-only writes, unchanged global settings, explicit
OFF/environment provenance, native flag precedence and lost
acknowledgements.

I include the corrections from the technical and UI/UX reviews. The
shared low-contrast focus outline on Parchment remains outside this
change.

## Documentation

I update `docs/help/<locale>/missions.md` in all ten languages (`en`,
`de`, `es`, `fr`, `he`, `ja`, `ne`, `ru`, `tr`, `zh-Hans`), along with
`MISSIONS.md`, `MISSIONS_RECURRING.md`, `MISSIONS_NATIVE_CONTRACTS.md`,
`OPENCODE_RUNTIME_SETUP.md`, `PLUGIN_CONTROLS.md` and `SETTINGS.md`
under `dev-docs/`.

## Long files touched

I flag these existing files for their size rather than expanding this
change into unrelated refactoring (approximate lines):

- `packages/server/src/api-types.ts`: 1,005
- `packages/server/src/opencode/missions-plugin.ts`: 1,058
- `packages/ui/src/lib/api-client.ts`: 1,010
-
`packages/ui/src/components/instance/shell/right-panel/tabs/MissionControl.tsx`:
889
- `packages/ui/tests/browser/mission-control.test.ts`: 1,707
- `packages/ui/tests/browser/mission-schedule-list.test.ts`: 1,000
This commit is contained in:
Pascal André 2026-11-14 12:24:43 +01:00 • committed by GitHub
parent 52f5a66c05
commit 2541a9195a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
91 changed files with 1989 additions and 353 deletions

View file

@ -474,7 +474,7 @@ Scheduling. Agents and models uses the shared Settings disclosure with an inline
requested-profile summary and Agent / Model / Thinking columns. Its fold state
survives editor drafts; catalog demand follows its visibility. Options and Scheduling
stay open. Notes begins at one line and grows with its content. Blocking profile
errors remain beside the disclosure; scheduling activation is confirmed at Play.
errors remain beside the disclosure; scheduling activation is prepared at Play.
Objective, Title and Notes share the instructions group. The footer names Save
configuration with a text button; the Configuration picker uses the bookmark glyph.
Catalog reads use the panel's existing read indicator and preserve form geometry.
@ -585,12 +585,19 @@ last capability display during same-owner revalidation, so a passive
refresh preserves an in-flight pointer click; control dispatch rereads capability.
`MissionActionBar` retains its primary glyph for an unchanged action key, preserving
the native pointer target while a fresh action object updates its other fields.
Play and Resume use informed native activation. Run now requires an enabled
Play and Resume automatically prepare project-only native activation when a ready
receipt is missing. An already enabled Location receives a zero-target ready proof
without configuration writes. Run now requires an enabled
effective native setting, with an explicit disabled explanation and a fresh
capability check before reservation. Its click preserves settings activation.
First native activation
asks for confirmation with the exact configuration paths; an uncertain activation
keeps Play unsent. A direct positive activation acknowledgement may continue the
Explicit OFF exposes a scheduling-settings action only for a server-openable configuration
ID; the responsible layer/path or environment explanation stays behind a keyboard-focusable
information tip. The existing configuration editor selects that exact catalogued file.
The requested action alone shows a full-opacity 14px loading glyph and `aria-busy`
during its bounded HTTP requests, with one persistent external status announcement;
confirmation dialogs and uncertain or confirmed-publication waits keep their ordinary glyphs.
Reduced motion uses the shared animation limit. An uncertain activation keeps Play
unsent and exposes the original receipt read. A direct positive activation acknowledgement may continue the
same user intention under its original view fences. Read-only recovery of activation
retains the publication barrier and leaves the next Play explicit. Never replay an
action or continue Play automatically from recovered activation or display publication.
@ -1143,10 +1150,12 @@ the next native `experimental` object (`opencode/experimental-layers.ts`) belong
the Global write target and equals its fresh document, since native entries lag
behind writes and normalize what they load; otherwise the object stays. The snapshot
flags such an object (`emptyExperimental`) so Inherit can repair it.
The shared two-key editor
The shared experimental editor
(`opencode/native-experimental-settings.ts`) materializes inherited
`schedules:true` when setting a depth would hide that activation, preserves an
explicit local false and depth zero, and copies only these two known keys.
explicit local false and depth zero. Creating a block for scheduling copies every
effective experimental option from the target's lower-priority whole block;
existing blocks retain their own options.
A remaining schedules
block selects the native depth default unless it also holds a depth. Native
settings refuse simultaneous JSON/JSONC files in one layer. The schedule
@ -1379,7 +1388,8 @@ answers mutations with 405 and writes `browser-report.json` to the absolute
- Journal editor reconciliation reads the original history request and exact text independently of the task window. Task pages preserve document and cleanup metadata; missing rows require the named display read their reader needs. Current daily/native-scheduled readers acquire their source before bounded task/report windows. The document RPC schema carries the dormant-journal marker and first-Play input digest with the projected summary.
- The open create/edit/delete editor lives in window memory per panel scope (`stores/mission-editor-state.ts`), never in the native view layout. A hidden project keeps it mounted and usable on return; when the panel unmounts (another right-panel tab) an idle editor stashes its draft and reopens with it, while one with a request in flight or held closes and settles through its creation/recurrence hold. Editor activity follows the live view: `lib/mission-view-fence.ts` captures guard one operation from capture to completion, never a component's lifetime.
- The Missions panel header (`components/mission-picker.tsx`, `styles/panels/mission-picker.css`) is two lines with one rule under the header, sticky at the top of the scrolling panel (`.mission-control-header`): a right-aligned toolbar ([+] create, then the panel's preferences gear and refresh), then the selection line. The selected item's icon toolbar mounts there through `MissionActionBar` and `MissionActionSlot`, followed by the always-shown **Filter missions** field; a narrow panel wraps the filter above the toolbar (`flex-wrap: wrap-reverse`). `MissionRows` uses the session list's row classes (`session-list-item`, `session-item-base`, `session-item-expander`, `session-item-select`, `session-item-title--clamp`): chevron, a flag (repeat icon for a schedule) coloured by its mark, then the title (`lib/mission-display.ts`); full state lives in the tooltip and screen-reader text. The filter always keeps the selected row. Selection uses `--list-item-highlight-*`; never use the input-field surface (`--surface-base`) as a panel or popup background.
- Flags and task icons share the session status palette (`mission-picker-model.ts`, `missionMark`/`scheduleMark`). A requested answer uses permission red; only a question the Mission can open reddens its flag. Observed work uses working yellow with pulse; interrupted and paused use warning orange. A completed Mission this window has not shown uses idle green (`markMissionsFinishedSeen` in `stores/mission-view-state.ts`), seeded from initial completion observations and marked seen only when shown in a focused window. Its per-project watermark on `finishSequence` retains unseen completions and individual acknowledgements within the layout bound; advancing that bound counts older completions as seen. A prepared Mission uses `--accent-primary` blue. Seen completed, failed, blocked and retired tasks stay neutral; active tasks pulse yellow, requested answers are red, unseen finished tasks are green, and tasks not started (assigned, ready, waiting on dependencies) are blue. Blue never reaches the chevron. Never reuse red for anything but a requested answer. Status words and icon shapes keep outcomes accessible independently of colour.
- Flags and task icons share the session status palette (`mission-picker-model.ts`, `missionMark`/`scheduleMark`). A requested answer uses permission red; only a question the Mission can open reddens its flag. Observed work uses working yellow with pulse; interrupted and paused use warning orange. A completed Mission this window has not shown uses idle green (`markMissionsFinishedSeen` in `stores/mission-view-state.ts`), seeded from initial completion observations and marked seen only when shown in a focused window. Its per-project watermark on `finishSequence` retains unseen completions and individual acknowledgements within the layout bound; advancing that bound counts older completions as seen. A prepared Mission uses the palette's `--accent-primary`. Seen completed, failed, blocked and retired tasks stay neutral; active tasks pulse yellow, requested answers are red, unseen finished tasks are green, and tasks not started (assigned, ready, waiting on dependencies) use the accent. Never apply the accent to the chevron or reuse red for anything but a requested answer. Status words and icon shapes keep outcomes accessible independently of colour.
- Daily and unified scheduled documents adapt to one pure schedule-mark projection. A confirmed future native wake uses the ordinary icon in opaque `--accent-primary` with a static 8×1px `--text-secondary` underline, three pixels below its 16px SVG in a shared 16×20px HTML cell. Prepared uses the accent icon alone; Pause uses `Pause`, interruption uses `AlertTriangle`, both warning orange. Native uncertainty, stale display evidence and unresolved controls use neutral **State unconfirmed**. Requests, interruption and uncertainty take priority over successful-history attention; Pause takes priority over a pending passage. The first loaded historical success starts seen. Later successful passages stay green until an explicit row selection in the active attentive window or **Mark as read** acknowledges the captured daily `passageID` or unified history `id`. Per-window/project/document-format/schedule layout state retains exact positive passage identities within the layout-value bound. Restored selection and newly arriving results preserve unread attention. Acknowledged success returns to confirmed waiting while armed, otherwise neutral; terminal Stop is neutral. Hover, focus, selection and reduced motion preserve the waiting underline.
- Row actions live in the header's selection line (`components/mission-action-bar.tsx`, `mission-selected-actions.tsx`): Play/Pause (coordinator recovery for an interrupted Mission and resumption of a failed one), Stop, a schedule's Run now, the reader eye, Open conversation, delete and `ActionOverflowMenu`. Every action stays in place, disabled when inapplicable under its owner and H9 guards. Overflow order is request an update, interrupt now, Save configuration and edit; the trigger is disabled when all entries are disabled. Secondary actions, including schedule checks and the configuration name field, stay at the top of the selected detail only while present. Command announcements and recovery actions belong to the persistent header; progress and errors join the primary button's tooltip instead of adding a line under the row. Retrying an unconfirmed control from the header ⟳ first reads its exact status, then resends only its still-unconfirmed original request/revision from that explicit click. Stop confirms first. Delete automatically submits once using the shared `missionDeleteSessions` preference frozen into that request; a failed or unconfirmed deletion retains its consumed automatic-submit state, original retry identity, option and error in the editor draft across remounts. Only explicit Retry continues that deletion. Shared contextual-help actions retain the shared help glyph, keyboard access and localized destination; opening help preserves selection, reader and editor state.
- The panel follows the session list. Its single selection is a Mission/schedule row or one task of that row's Mission/passage (`selectedTask` in `stores/mission-view-state.ts`); only the selected row or task is highlighted (`.session-item-active`, `aria-current`), and selecting a row clears the task. Only the chevron (`SessionExpander`) expands or collapses. A Mission with known `MissionSummary.taskCount` zero, or a read map without tasks, uses the session list's spacer; an absent count retains the chevron. Its context menu Mark as read acknowledges the row's unseen finished tasks and own unseen completion. `MissionRows` renders the selected detail once between its surrounding rows, preserving controls and retries through selection changes. Collapse hides that mounted detail; a selected Mission without tasks keeps its action-only detail visible. Expanded rows persist per project in `expanded`, bounded by `MAX_EXPANDED`; an unselected schedule's chevron selects and expands it, while an unselected one-time Mission's chevron expands its task preview without selecting it. Nothing is selected by default. Opening a conversation preserves the selected Mission/task.
- The detail (`components/mission-tracking.tsx`, `styles/panels/mission-detail.css`) holds secondary actions such as the configuration name field and the task tree; prose belongs in the central reader or info tips. `components/mission-task-tree.tsx` is THE task view: one session-list row per task (`.session-list-item`, `.session-item-base.session-item-nested`, one level deep), a status icon then title. `mission-graph.tsx` draws only declared `blockedBy` dependencies, completed and retired included, from measured status icons; never infer native ancestry. Lanes start under the Mission row's chevron at a fixed step; `--mission-graph-extra` increases row indentation when necessary. Clicking a task selects it; a correlated red request also opens its question. `missionTaskRowState` supplies both task-row state and the Mission chevron's `data-child-activity` priority: input, active, unseen finished task. A finished task stays green until selection, its icon button (`lib/toggle-sweep.ts` supports sweeping), or Mark as read acknowledges it. `stores/mission-task-seen.ts` retains the per-project first-use boundary, per-Mission Mark as read watermark and individually seen task versions.

View file

@ -147,7 +147,7 @@ Exact request receipts remain point reads through `scheduleRead`.
| --- | --- | --- |
| `@opencode/client/service` | `discover({file})` returns Endpoint/undefined; `headers(endpoint)` builds authentication; public `Info` describes registration fields | Exact absolute registration, bounded non-secret id/pid/url/version projection, current PID/incarnation before dispatch and inside receiving RPC. Keep credentials in operation memory. For wake transport, forbid ensure/start/stop/terminate, CLI children, standalone and alternate namespaces. |
| Client HTTP/RPC | `OpenCode.make(...).rpc(definition).method(input,{location,signal})` | Acquired authenticated connection, exact native directory and cancellation; preserve uncertainty after dispatch. |
| Schedule HTTP contract | `experimental.schedule.create/list/get/pause/resume/delete`, `{data:Info}`, session-filtered list, delete 204 | `opencode/native-schedule-capability.ts` recognizes the consumed request/response shapes read-only. Read `experimental.schedules` independently from the highest-priority whole native block. Never create probe schedules. |
| Schedule HTTP contract | `experimental.schedule.create/list/get/pause/resume/delete`, `{data:Info}`, session-filtered list, delete 204 | `opencode/native-schedule-capability.ts` recognizes the consumed request/response shapes read-only. The Location's `scheduleFlag` RPC reads native flag resolution independently. Never create probe schedules. |
| Plugin Session facade | get/create/prompt/synthetic/interrupt/context | Prefer facade methods when they expose the required operation. Preserve exact session/message IDs and fixed profiles at admission. Use bounded point/page reads for source coverage. |
| Session/AISDK hooks | prompt/context/title/compaction/language | Context admission requires the exact durable user message and schedule correlation. Title/compaction/language carry only local technical work. Treat metadata as correlation within service privileges. |
| Native context message classification | Context message IDs select native carrier records | [Read bounds and authority](MISSIONS_NATIVE_SCHEDULE_TRANSPORT.md#context-read-authority-and-bounds). |
@ -169,6 +169,7 @@ documents without imposing a runtime version list.
| Session message readers | messages({sessionID,limit,order,cursor:{id,direction}}) → array; message({sessionID,messageID}) → Info/undefined | Same adapter: ≤32 messages/source, ≤256 KiB native message, 16,384-character launch envelope; point-read anchor and each message, stable complete prefix, source placement/bytes rechecked after I/O. Deleted/moved/changed anchors block. |
| Session active | `active` is an Effect returning a ReadonlySet | `native-passage-observation.ts`: actual Set, ≤4096 sessions. Treat activity as a process-local observation. Require correlated durable terminal evidence and complete family quiescence for restart settlement. Keep an old execution claim uncertain during asynchronous native recovery. |
| `@opencode/Location` | directory/workspaceID/project{id,directory,canonical} | `native-service-adapter.ts`, `native-service-clock.ts`, recurrence readers: structural Location.Info fields, exact native/physical placement and current graph checks after I/O and before effects. |
| `@opencode/Flag`, `@opencode/Config` | `resolve(entries).schedules` → `{enabled:boolean,source:"env"|"config"|"default"}`; `entries()` → Effect of ordered documents/directories | `native-schedule-flag.ts`: receiving RPC/Location graph, checked methods/Effect, at most 256 entries, checked result and live Location/lifecycle before and after the read. `scheduleFlag` returns only effective state and provenance (`environment`, `experimental-block`, `all-flags`, `channel-default`). The calendar facade uses this same reader before carrier effects and retains `Schedule.enabled(sessionID)` for the carrier's own Location. Missing service or shape blocks admission. |
| `@opencode/storage/Database` | db.$client.unsafe(sql,params).withoutTransform → Effect rows; db.transaction(callback,{behavior:"immediate"}) | `native-recurrence-storage.ts`, `native-passage-observation.ts`: current graph, actual SQL client/transaction, safe row types and synchronous query guard. Preserve the driver's transaction Context when composing effects. Asynchronous-only reads cannot implement the synchronous admission fence. |
| KV/CAS SQL | kv(key,value,time_created,time_updated); plugin namespace is plugin ID encoded as padded UTF-16 hex | `native-recurrence-storage.ts`: exact project key/bytes/revision, immediate transaction, conditional update and readback. Publish invalidation after commit; an invalidation failure preserves the committed result. |
| Family SQL | session_v2 placement/parent/time_suspended, session_inbox, session_message id/type/seq/content/idle | `native-passage-observation.ts`: family ≤4096, exact message/inbox presence and nonnegative counts. Anchor the original input in durable seq order and require a later terminal idle as the latest projection. Count failures only between that input and terminal, then recheck family, claims and requests. Missing anchor/terminal or any remaining claim keeps uncertainty. |
@ -409,14 +410,32 @@ remain covered by the separate scheduled-product qualification.
`native-experimental-settings.ts` shares the depth/schedules JSONC reader and
editor. Preserve explicit false/zero and local companions; materialize inherited
true schedules when writing a depth, and preserve depth from the target's own
lower-priority block only when creating an experimental block for schedules.
An existing block keeps its depth key or native default unchanged. Copy only
those two known keys.
true schedules when writing a depth. Creating an experimental block for schedules
copies every effective experimental option from the target's lower-priority whole
block. An existing block keeps its own options and native defaults.
`PluginControls` owns connection/Location/deletion fences, byte expectations and
the physical file lock. Duplicate keys, invalid parents and simultaneous JSON/
JSONC in one layer refuse settings edits.
Native flag precedence is environment overrides (a specific key before `all`),
the key in the highest-priority whole `experimental` block, then true from the
highest-priority document setting `experimental.all_flags`, then the daemon's
channel default. `all_flags:false` falls through to that default. The daemon's
Flag service supplies environment and channel decisions.
Activation refuses every discovered explicit `schedules:false`, including a
hidden lower layer, and a native environment OFF. An upper experimental block
masking the project target also refuses activation. `schedule-activation-refused`
responses identify the reason, provenance, layer, discovered path, `openable` and
`configFileID`. An editor action requires an openable ID with exact membership
in the existing global config-file inventory; environment refusals expose their
source through the information tip.
An activation refusal before any document mutation, for an identity without an
existing intent, includes `notApplied: { requestID, expectedRevision }`. This exact
proof releases that local request for a fresh explicit Start after configuration
correction. A refusal after a document mutation attempt or for an existing intent
retains the original request and its explicit receipt recovery.
Native regression: `node --import tsx
scripts/test-mission-experimental-settings-native.mjs <absolute-isolated-cli>`.
It exercises real discovery/whole-block precedence/watcher acknowledgement and
@ -426,7 +445,16 @@ The product preparation endpoint is
`/api/workspaces/:id/missions/:missionID/schedule-settings`: GET reads its document;
POST accepts only `requestID` and `expectedDocumentRevision`. It holds the owned
worktree admission, refreshes authority before every typed `documentActivation`
phase and composes the two-file executor with native document CAS. Readiness keeps
phase and composes the project-only executor with native document CAS. An already
enabled Location records a ready proof with zero targets and zero config writes.
The sole writable target is the owned Location's project configuration; global
configuration contributes discovery, refusal and exact editor targeting.
Existing ready proofs retain their original request/revision, authority and digests;
preparation revalidates them read-only. Incomplete persisted intentions containing
a global target observe exact already-attempted effects only; never write global
or unattempted targets during their reconciliation. An attempted effect without
matching proof keeps its original barrier.
Readiness requires the effective native flag in the acquired Location and keeps
the Mission paused. Immediate objects refuse this path. A failed intent with no
attempted write can be replaced only by a new explicit request at the fresh
document revision; an attempted effect retains its original request fence.

View file

@ -280,6 +280,20 @@ may continue the same user intention; recovered activation leaves Play explicit.
Never replay a mutation or start Play from receipt recovery or display publication.
List and detail also expose `observation`, `availableActions` and `blockReason`.
The shared list mark uses the current observation's temporal generation and positive
active principal/next-wake evidence for **Waiting for scheduled run**. Daily documents
use the native snapshot's positively observed running state and next date. A missing,
stale, blocked or unresolved observation keeps **State unconfirmed**. Successful-history
attention and exact passage acknowledgement follow the shared marks contract in
`MISSIONS.md` (Agent conventions): accent icon with a static neutral underline for
confirmed waiting, accent alone for prepared, orange Pause or warning triangle for
pause/interruption, yellow pulse during a passage and green for a new successful
passage awaiting review. Explicit attentive selection or **Mark as read** acknowledges
that exact passage and returns an armed schedule to waiting. The context menu captures
its passage identity when opened; a result arriving while it is open stays unread.
Unselected rows count requests from their live coordinator and loaded descendants;
the selected passage uses its authoritative request coverage. First-loaded history
starts read. Acknowledged finished schedules and terminal Stop use neutral.
Their `technical` projection exposes only the recorded current/retiring carrier
session and calendar identifiers, role, slot, temporal generation and pending
cleanup. It derives these from the same document read, including attempted
@ -333,8 +347,19 @@ adapter, with zero model requests.
`GET /api/workspaces/:id/missions/scheduled/capabilities` reads the acquired
connection's consumed API contract, effective schedules flag and origin. Its
read-only activation plan exposes the target scopes/paths or a refusal category.
The native document preparation endpoint owns authenticated configuration writes.
read-only activation plan exposes the project target/path or a refusal category,
responsible layer and discovered path. Native `scheduleFlag` resolution supplies
the effective state and provenance. Environment OFF and every discovered explicit
document OFF refuse preparation, including an OFF hidden by a higher ON.
The native document preparation endpoint owns authenticated project-only
configuration writes; an already enabled Location receives a zero-target ready
proof. Existing ready proofs are retained and revalidated read-only.
Play/Resume perform this preparation automatically under the original view fences.
A structured refusal offers **Open scheduling settings** only for a server-openable
configuration ID; source/path and environment details use the focusable **i** tip.
The requested button shows loading and `aria-busy` during HTTP work, with a status
announcement. Uncertain activation keeps the exact receipt check available and
leaves the next Play explicit after recovery.
Both display routes revalidate workspace, connection, physical checkout and request
lifetime after asynchronous work. Missing methods or capabilities return an
explicit unavailable response. UI reads use the shared secondary HTTP budget.
@ -675,6 +700,9 @@ Retain pending passage identity and observations rather than clearing live work.
Desired running without a live native Job is displayed as **Interrupted** with
an interruption reason. Service restart therefore leaves scheduling Interrupted.
An archived daily passage ending without a report keeps its history outcome;
a positively running daily Job with a future date shows **Waiting for scheduled run**.
Failed passages retain their interruption attention.
Do not rearm from plugin load, a read, UI reopen or backend reconnect.
Only explicit Resume may restore scheduling; pending work is reconciled first.
An Interrupted schedule keeps its passage pending. Resume reconciles its original

View file

@ -20,10 +20,13 @@ never upgrade or restart a user's service.
separately from an untested version. Optional configuration reload follows
its own route presence. Never probe support with a write.
Scheduled Missions additionally require the consumed Schedule contract and enabled
`experimental.schedules` in the discovered global configuration and effective whole
Location block. Targeted, confirmed activation and exact read-back are described in
[Missions](MISSIONS.md) and [native contracts](MISSIONS_NATIVE_CONTRACTS.md).
Scheduled Missions additionally require the consumed Schedule contract and an enabled
effective native `experimental.schedules` flag in the acquired Location. Play/Resume
prepare project-only activation automatically, preserving every discovered explicit
OFF and native environment OFF. An already enabled Location receives a ready proof
without configuration writes. Native flag resolution, targeted activation and exact
read-back are described in [Missions](MISSIONS.md) and
[native contracts](MISSIONS_NATIVE_CONTRACTS.md).
Missing APIs, explicit OFF, a masking block, failed activation or missing exact
calendar registration keep the schedule paused or in an explained error state.
Play of a Mission without launch criteria follows its own admission path.

View file

@ -280,23 +280,25 @@ receives the current acquired configuration entries and native target position.
Missions settings request strict document acquisition, rejecting JSON and JSONC
coexistence in the same layer; plugin source edits retain the selected target
and propagate their deadline signal through acquisition and commit. Missions'
`native-experimental-settings.ts` edits only schedules/depth, retaining explicit
`native-experimental-settings.ts` authors schedules/depth, retaining explicit
companion values. Depth writes preserve inherited schedule activation when the
local block omits its flag. Schedule activation materializes inherited depth
only when creating a whole-block override. Adding schedules to an existing block
keeps its effective depth choice, including the native default selected by an
local block omits its flag. Schedule activation copies every effective inherited
experimental option when creating a whole-block override. Adding schedules to an
existing block keeps its options, including the native default selected by an
absent depth key. Existing file-byte expectations and the
physical replacement lock fence concurrent writers.
`editConfigDocuments` prepares and verifies each required target before its first
rename. The Missions activation journal records the plan before effects, an
attempt before each rename, and each exact acknowledgement. A read-only target
or conflicting source refuses preparation; a partial global/project write keeps
its durable receipts and preserves the successful write. An uncertain attempted
write is reconciled only by its exact result bytes, preserving a later explicit
OFF. `native-schedule-settings-activation.ts` acknowledges readiness only after
the native global and effective Location blocks both enable schedules, within
ten seconds, under the acquired connection and host/distro authority.
rename. The Missions activation journal records its project-only plan before effects,
an attempt before each rename, and each exact acknowledgement. A read-only target,
masking block, discovered explicit OFF or native environment OFF refuses preparation.
An already enabled Location receives a zero-target ready proof without configuration
writes. Persisted intentions with global targets retain exact attempted effects for
read-only reconciliation. Never write global or unattempted targets from those intentions.
An uncertain attempted write is reconciled only by its exact result bytes, preserving
a later explicit OFF. `native-schedule-settings-activation.ts` acknowledges readiness
after the effective native Location flag enables schedules, within ten seconds,
under the acquired connection and host/distro authority.
OpenCode watches these configuration roots. Never restart the daemon or report a
successful file write as an active plugin: the mutation response publishes the

View file

@ -4,6 +4,8 @@ Settings rows and actions, the native Preferences window and its project context
## Agent conventions
- `openSettingsConfigFile(id)` opens Configuration files and selects only an ID present in the editor's server catalogue. It shares `openSettingsRow`'s short-lived same-origin hint with native Preferences on Electron and Tauri. A reopened editor preserves its dirty-discard confirmation; unavailable IDs preserve the current file. The editor consumes each target once and focuses its file selector.
- Settings → OpenCode's logging card opens `OpenCodeLogsAction` in the common non-modal `OutputWindow`. Read once on explicit opening and on Refresh; closing, disposal and executable selection changes abort/fence the request. Global log snapshots stay in the mounted settings reader, separate from session state. The `switch-to-info` command/shortcut opens OpenCode settings and keeps existing key overrides. Version, executable, service actions and diagnostics share this global settings scope.
- Reuse `SettingsInfoTip` for contextual help with `help={{ page: "opencode", anchor: "login-start" }}`. Its short localized `text` remains the hover/focus tooltip; click, Enter or touch opens `helpUrl(locale, page, anchor)` through `openExternalUrl`, with a localized failure alert. The span's link role, cancelled label default and stopped activation events keep containing labels, disclosures and controls unchanged. Without `help`, touch toggles the explanation. `SettingsChoiceRow.help` and behavior-registry `help` carry the same destination. Use only relevant published sections with matching explicit ids in every locale; dynamic diagnostics can remain tooltip-only, and actionable popovers keep `SettingsInfoLink` or `InfoPopoverButton`. Destinations and gesture/native-opener behavior are covered by `lib/help-url.test.ts` and `tests/browser/settings-info-tip.test.ts`.

View file

@ -42,7 +42,7 @@ Kalenderbasierte Zeitplanung benötigt einen expliziten Agenten und ein Modell f
### Automatisch starten {#automatic-start}
**Automatisch starten** steht außerhalb der Zeitplanung und ist standardmäßig aus. Ausgeschaltet erstellt es eine pausierte Mission für späteres ▶ Starten. Eingeschaltet fordert es den Start nach bestätigter Erstellung unter den üblichen Prüfungen und gegebenenfalls mit Zustimmung zu nativen Einstellungen an.
**Automatisch starten** steht außerhalb der Zeitplanung und ist standardmäßig aus. Ausgeschaltet erstellt es eine pausierte Mission für späteres ▶ Starten. Eingeschaltet fordert es den Start nach bestätigter Erstellung mit den üblichen Prüfungen und automatischer Vorbereitung der Zeitplanung an.
Bei verlorener Bestätigung bleibt der Start nach Lesen der Quittung manuell. Behalten Sie die ursprüngliche unbestätigte Anfrage und prüfen Sie Liste und Unterhaltung vor einer erneuten Erstellung.
@ -58,6 +58,8 @@ Verfügbar sind einmal jetzt, alle N Stunden, täglich, ausgewählte Wochentage,
Einmal jetzt erhält seinen Zeitpunkt beim Start und bietet nur eine Gelegenheit; eine nicht erfüllte Bedingung kann diese verbrauchen. Zeitplanung benötigt den verfügbaren OpenCode-Dienst und Ausführungshost.
Beim Starten oder Fortsetzen wird die Zeitplanung automatisch in der OpenCode-Projektkonfiguration vorbereitet. Ein ausdrückliches OFF bleibt erhalten: **Zeitplanungseinstellungen öffnen** öffnet, wenn angeboten, die zuständige Datei; **i** zeigt Herkunft oder Umgebungsdetails. Nur während der Anfrage zeigt die betätigte Schaltfläche den Ladevorgang. Ein unbestätigtes Ergebnis bietet eine Prüfung; nach wiederhergestellter Aktivierung starten Sie ausdrücklich selbst.
### Ereignisse und Kombinationen {#scheduling-conditions}
Wählen Sie **Repository-Aktivität → Ereignis**, danach optionale Filter in derselben Karte. Git-Commits teilen dieses Menü mit Ereignissen des automatisch erkannten GitHub-, GitLab- oder Gitea-Repositorys, wie in Contribute (`upstream`, dann `origin`). Alle drei unterstützen neue und zusammengeführte PRs/MRs sowie neue Issues mit optionalem **Autor**, einschließlich `dependabot[bot]`. Die Ereignisauswahl legt das Repository fest; gespeicherte Kriterien behalten ihr Ziel.
@ -90,9 +92,11 @@ Weitere Einträge und Aufgaben laden am Listenende automatisch. Aufgabenseiten b
### Farben und Zustände {#status-colours}
Die Flagge zeigt den Missionszustand, der Chevron die Aufmerksamkeit ihrer Aufgaben. Wiederkehrende Einträge haben ein Wiederholungssymbol. Rot verlangt eine Antwort, pulsierendes Gelb zeigt beobachtete Arbeit, Orange Pause/Unterbrechung, Grün einen ungesehenen Abschluss und Blau Vorbereitung beziehungsweise noch nicht gestartete Aufgaben.
Die Flagge zeigt den Missionszustand, der Chevron die Aufmerksamkeit ihrer Aufgaben. Wiederkehrende Einträge haben ein Wiederholungssymbol. Rot verlangt eine Antwort, pulsierendes Gelb zeigt beobachtete Arbeit. Ein orangefarbenes Pausensymbol bedeutet Pause, ein orangefarbenes Warndreieck Unterbrechung. Grün kennzeichnet eine abgeschlossene Mission, Aufgabe oder einen erfolgreichen Durchlauf zum Ansehen.
Auswahl oder grüne Aufgabensymbole bestätigen Ergebnisse; das Chevron-Menü bietet **Als gelesen markieren**. Status und Ergebnis sind getrennt: ein Blocker ist nicht zwingend eine Frage, ein Bericht beweist nicht das Ende aller nativen Vorgänge. Zurückgezogene Aufgaben bleiben im Verlauf.
Ein Akzentsymbol mit einem kleinen statischen neutralen Strich darunter bedeutet **Wartet auf geplanten Durchlauf**: der nächste Weckzeitpunkt ist bestätigt. Der Akzent folgt der Palette. Das Akzentsymbol allein steht für Vorbereitung oder noch nicht gestartete Aufgaben. Angesehene Abschlüsse, gestoppte Zeitpläne und **Status unbestätigt** sind neutral; lesen Sie den Statustext.
Auswahl oder Klick/Streichen über grüne Aufgabensymbole bestätigt Ergebnisse; das Chevron-Menü bietet **Als gelesen markieren**. Bei **Erfolgreicher Durchlauf zum Ansehen** bestätigt eine ausdrückliche Auswahl der wiederkehrenden Zeile im aktiven Fenster oder **Als gelesen markieren** genau diesen Durchlauf. Bei aktiver Zeitplanung kehrt das Symbol zum Warten zurück, sonst zu neutral. Wiederhergestellte Auswahl und neue Ergebnisse in einer bereits ausgewählten Zeile bleiben ungelesen. Historische Erfolge beim ersten Laden gelten als gelesen. Zurückgezogene Aufgaben bleiben im Verlauf.
### Fragen und Entscheidungen {#questions}

View file

@ -46,7 +46,7 @@ Calendar-backed scheduling requires an explicit agent and model for the coordina
### Start automatically {#automatic-start}
**Start automatically** is outside Scheduling and off by default. Leave it off to create a paused Mission, then use ▶ **Start** in the header. Turn it on to request Start after creation is confirmed, with the ordinary checks and any required native-settings consent.
**Start automatically** is outside Scheduling and off by default. Leave it off to create a paused Mission, then use ▶ **Start** in the header. Turn it on to request Start after creation is confirmed, with the ordinary checks and automatic scheduling preparation.
If creation's acknowledgement is lost, reading its receipt leaves Start manual. An unconfirmed creation keeps its original request; inspect the list and conversation before creating anything again.
@ -62,6 +62,8 @@ Schedules include Once, now, Every N hours, Every day, Selected weekdays, Day of
**Once, now** takes its instant at Start, rather than when the form opens. It offers one opportunity, which a condition can consume without launching. Choose a repeating schedule for later opportunities. Scheduling runs while its OpenCode service and execution host are available.
Starting or resuming prepares scheduling in the project's OpenCode configuration automatically. An explicit OFF is preserved: use **Open scheduling settings** when offered to open the responsible file, and the **i** tip for its source or environment details. The clicked button shows loading only during the request. An unconfirmed result offers verification; recovered activation leaves Start explicit.
### Events and combinations {#scheduling-conditions}
Choose **Repository activity → Event**, then any optional filters in the same card. Git branch commits share this menu with events from the automatically detected GitHub, GitLab or Gitea repository, using the same detection as Contribute (`upstream`, then `origin`). All three support new PRs/MRs, merged PRs/MRs and new issues, with optional **Author**, including `dependabot[bot]`. Choosing an event fixes its repository; saved criteria retain their targets.
@ -100,13 +102,18 @@ More directory entries and tasks load as you approach the end. Loaded task pages
The flag shows the Mission's state; its chevron carries its tasks' attention state. A recurring entry uses a repeat icon.
| Colour | Meaning |
| Colour and shape | Meaning |
| --- | --- |
| Red | An open question or permission needs your answer. Select the asking Mission or task to open the interruption dock. |
| Yellow, pulsing | Native work was observed running. |
| Orange | Paused or interrupted, with an action to continue. |
| Green | A Mission or task finished and has not been seen in this window. Select it, click or sweep green task icons, or use **Mark as read** on the chevron's context menu. |
| Blue | Prepared Mission or a task that has not started. |
| Orange pause symbol | Paused. |
| Orange warning triangle | Interrupted, with an action to continue. |
| Green | A Mission, task or successful scheduled run awaits review in this window. |
| Accent icon with a small static neutral line below | **Waiting for scheduled run**: the next wake is confirmed. The accent follows your palette. |
| Accent icon alone | Prepared Mission or a task that has not started. |
| Neutral | Reviewed completion, stopped schedule or **State unconfirmed**; read the status text. |
Select a green Mission or task, click or sweep green task icons, or use **Mark as read** on the chevron's context menu. For **Successful run to review**, explicitly select the recurring row in the active window or use **Mark as read** to acknowledge that run. Its icon returns to waiting while scheduling remains active, otherwise neutral. Restored selection and results arriving on an already selected row keep the new result unread. Historical successes present on first loading start as read.
Status text distinguishes Assigned, Active, Waiting, Blocked, Done, Failed and Retired. A reported blockage is not necessarily a question for you. A recorded result is not proof that every native operation has stopped. Retiring a task keeps its history.

View file

@ -42,7 +42,7 @@ La programación basada en calendario requiere agente y modelo explícitos para
### Iniciar automáticamente {#automatic-start}
**Iniciar automáticamente** está fuera de Programación y desactivado por defecto. Desactivado crea una Misión en pausa para iniciarla después desde ▶. Activado solicita el inicio tras confirmar la creación, con las comprobaciones habituales y el consentimiento nativo necesario.
**Iniciar automáticamente** está fuera de Programación y desactivado por defecto. Desactivado crea una Misión en pausa para iniciarla después desde ▶. Activado solicita el inicio tras confirmar la creación, con las comprobaciones habituales y la preparación automática de la programación.
Si se pierde la confirmación, leer el recibo deja el inicio manual. Conserva la solicitud original no confirmada y comprueba lista y conversación antes de crear otra vez.
@ -56,6 +56,8 @@ El primer criterio es **Una vez, ahora**. **Añadir un criterio** agrega otro. E
Hay una vez ahora, cada N horas, diario, días de semana, día del mes y cron. Se usa la zona guardada; su campo aparece si difiere de la del sistema. Los meses sin el día elegido se omiten. Una vez ahora fija su instante al iniciar y ofrece una sola oportunidad, que una condición puede consumir sin lanzar. Se necesitan OpenCode y el equipo de ejecución disponibles.
Al iniciar o reanudar, la programación se prepara automáticamente en la configuración OpenCode del proyecto. Se conserva un OFF explícito: **Abrir los ajustes de programación**, cuando esté disponible, abre el archivo responsable; **i** muestra el origen o los detalles del entorno. El botón pulsado indica carga solo durante la solicitud. Un resultado sin confirmar permite verificarlo; recuperar la activación deja el inicio como acción explícita.
### Eventos y combinaciones {#scheduling-conditions}
Elige **Actividad del repositorio → Evento** y los filtros opcionales en la misma tarjeta. Los commits de Git comparten este menú con los eventos del repositorio GitHub, GitLab o Gitea detectado automáticamente, como en Contribute (`upstream`, luego `origin`). Los tres admiten nuevas PR/MR, PR/MR fusionadas y nuevas issues, con **Autor (opcional)**, incluido `dependabot[bot]`. Elegir un evento fija su repositorio; los criterios guardados conservan su destino.
@ -88,9 +90,11 @@ Más entradas y tareas se cargan automáticamente al acercarse al final. Las pá
### Colores y estados {#status-colours}
La bandera muestra la Misión y el chevrón la atención de sus tareas; las recurrentes usan repetición. Rojo pide respuesta, amarillo pulsante indica trabajo observado, naranja pausa/interrupción, verde un resultado no visto y azul preparación o tarea no iniciada.
La bandera muestra la Misión y el chevrón la atención de sus tareas; las recurrentes usan repetición. Rojo pide respuesta y amarillo pulsante indica trabajo observado. Un símbolo de pausa naranja indica pausa; un triángulo de advertencia naranja, interrupción. Verde indica una Misión, tarea o ejecución correcta pendiente de revisión.
Seleccionar o pulsar/barrer iconos verdes confirma resultados; el menú del chevrón permite marcarlos como leídos. Un bloqueo no siempre es una pregunta; un informe no prueba que toda operación nativa haya terminado. Las tareas retiradas conservan historial.
Un icono de acento con una pequeña línea neutra estática debajo significa **Esperando ejecución programada**: la próxima activación está confirmada. El acento sigue la paleta. El icono de acento solo indica preparación o una tarea sin iniciar. Los resultados revisados, las programaciones detenidas y **Estado sin confirmar** son neutros; consulta el texto de estado.
Seleccionar o pulsar/barrer iconos verdes confirma resultados; el menú del chevrón ofrece **Marcar como leído**. Para **Ejecución correcta por revisar**, selecciona explícitamente la fila recurrente en la ventana activa o usa **Marcar como leído** para confirmar esa ejecución. El icono vuelve a espera si la programación sigue activa; en caso contrario, a neutro. La selección restaurada y los resultados que llegan a una fila ya seleccionada mantienen el nuevo resultado sin leer. Los éxitos históricos presentes en la primera carga comienzan como leídos. Las tareas retiradas conservan historial.
### Preguntas y decisiones {#questions}

View file

@ -46,7 +46,7 @@ Une programmation gérée par calendrier nécessite un agent et un modèle expli
### Démarrer automatiquement {#automatic-start}
**Démarrer automatiquement** se trouve hors de Programmation et reste décoché par défaut. Laissez-le décoché pour créer une Mission en pause, puis utilisez ▶ **Démarrer** dans l’en-tête. Cochez-le pour demander le démarrage après confirmation de la création, avec les contrôles habituels et l’éventuel consentement aux réglages natifs.
**Démarrer automatiquement** se trouve hors de Programmation et reste décoché par défaut. Laissez-le décoché pour créer une Mission en pause, puis utilisez ▶ **Démarrer** dans l’en-tête. Cochez-le pour demander le démarrage après confirmation de la création, avec les contrôles habituels et la préparation automatique de la programmation.
Si l’accusé de création est perdu, lire le reçu laisse le démarrage manuel. Une création non confirmée garde sa requête d’origine ; vérifiez la liste et la conversation avant de créer à nouveau.
@ -62,6 +62,8 @@ Les horaires proposent Une fois, maintenant, Toutes les N heures, Tous les jours
**Une fois, maintenant** prend son instant au démarrage, pas à l’ouverture du formulaire. Il offre une seule occasion, qu’une condition peut consommer sans lancement. Choisissez une récurrence pour des occasions ultérieures. La programmation fonctionne tant que son service OpenCode et son hôte d’exécution sont disponibles.
Le démarrage ou la reprise prépare automatiquement la programmation dans la configuration OpenCode du projet. Un OFF explicite est conservé : **Ouvrir les réglages de programmation**, lorsque proposé, ouvre le fichier responsable ; le **i** révèle sa provenance ou les détails d’environnement. Le bouton sollicité affiche le chargement pendant la requête seulement. Un résultat non confirmé propose une vérification ; l’activation récupérée laisse le démarrage explicite.
### Événements et combinaisons {#scheduling-conditions}
Choisissez **Activité du dépôt → Événement**, puis les filtres éventuels dans la même carte. Les commits Git partagent ce menu avec les événements du dépôt GitHub, GitLab ou Gitea détecté automatiquement, comme dans Contribute (`upstream`, puis `origin`). Les trois proposent les nouvelles PR/MR, les PR/MR fusionnées et les nouvelles issues, avec un **Auteur (facultatif)**, y compris `dependabot[bot]`. Choisir un événement fixe son dépôt ; les critères enregistrés conservent leur cible.
@ -100,13 +102,18 @@ Les missions et tâches suivantes se chargent à l’approche de la fin. Les pag
Le drapeau indique l’état de la Mission ; son chevron porte l’attention de ses tâches. Une entrée récurrente utilise une icône de répétition.
| Couleur | Sens |
| Couleur et forme | Sens |
| --- | --- |
| Rouge | Une question ou permission attend votre réponse. Sélectionnez la Mission ou la tâche concernée pour ouvrir le panneau d’interruption. |
| Jaune pulsant | Une activité native a été observée. |
| Orange | En pause ou interrompue, avec une action pour continuer. |
| Vert | Une Mission ou tâche terminée n’a pas encore été vue dans cette fenêtre. Sélectionnez-la, cliquez ou balayez les icônes vertes des tâches, ou choisissez **Marquer comme lu** dans le menu du chevron. |
| Bleu | Mission préparée ou tâche qui n’a pas commencé. |
| Symbole pause orange | En pause. |
| Triangle d’avertissement orange | Interrompue, avec une action pour continuer. |
| Vert | Une Mission, tâche ou exécution programmée réussie attend votre consultation dans cette fenêtre. |
| Icône d’accent avec un petit trait neutre statique dessous | **En attente programmée** : le prochain réveil est confirmé. L’accent suit votre palette. |
| Icône d’accent seule | Mission préparée ou tâche qui n’a pas commencé. |
| Neutre | Fin consultée, programmation arrêtée ou **État non confirmé** ; lisez le texte d’état. |
Sélectionnez une Mission ou tâche verte, cliquez ou balayez les icônes vertes des tâches, ou choisissez **Marquer comme lu** dans le menu du chevron. Pour **Passage réussi à consulter**, sélectionnez explicitement la ligne récurrente dans la fenêtre active ou utilisez **Marquer comme lu** pour acquitter ce passage. L’icône revient à l’attente si la programmation reste active, sinon au neutre. La sélection restaurée et les résultats reçus sur une ligne déjà sélectionnée gardent le nouveau résultat à consulter. Les succès historiques présents au premier chargement commencent comme lus.
Le texte d’état distingue Affectée, Active, En attente, Bloquée, Terminée, Échouée et Retirée. Un blocage signalé n’est pas nécessairement une question pour vous. Un résultat enregistré ne prouve pas que chaque opération native est arrêtée. Retirer une tâche conserve son historique.

View file

@ -42,7 +42,7 @@
### התחלה אוטומטית {#automatic-start}
**התחלה אוטומטית** נמצאת מחוץ לתזמון וכבויה כברירת מחדל. כשהיא כבויה, המשימה נוצרת בהשהיה להפעלה מאוחרת ב־▶. כשהיא מופעלת, מתבקשת התחלה לאחר אישור היצירה, בכפוף לבדיקות ולאישור ההגדרות המקוריות הנדרש.
**התחלה אוטומטית** נמצאת מחוץ לתזמון וכבויה כברירת מחדל. כשהיא כבויה, המשימה נוצרת בהשהיה להפעלה מאוחרת ב־▶. כשהיא מופעלת, מתבקשת התחלה לאחר אישור היצירה, עם הבדיקות הרגילות והכנה אוטומטית של התזמון.
אם אישור היצירה אבד, קריאת הקבלה משאירה את ההתחלה ידנית. שמרו את הבקשה המקורית שלא אושרה ובדקו רשימה ושיחה לפני יצירה נוספת.
@ -56,6 +56,8 @@
האפשרויות כוללות עכשיו פעם אחת, כל N שעות, כל יום, ימי שבוע, יום בחודש ו־cron. אזור הזמן השמור קובע, והשדה מופיע כשיש הבדל מהמערכת. חודשים בלי היום הנבחר מדולגים. עכשיו פעם אחת נקבע בהפעלה ומעניק הזדמנות אחת, שתנאי יכול לצרוך ללא הרצה. שירות OpenCode ומחשב הביצוע צריכים להיות זמינים.
התחלה או המשך מכינים את התזמון אוטומטית בתצורת OpenCode של הפרויקט. מצב OFF מפורש נשמר: **פתיחת הגדרות התזמון**, כאשר האפשרות זמינה, פותחת את הקובץ האחראי; **i** מציג את המקור או את פרטי הסביבה. הכפתור שנלחץ מציג טעינה רק בזמן הבקשה. תוצאה לא מאושרת מאפשרת בדיקה; לאחר שחזור ההפעלה נדרשת התחלה מפורשת.
### אירועים ושילובים {#scheduling-conditions}
בחרו **פעילות במאגר → אירוע**, ואז מסננים אופציונליים באותו כרטיס. קומיטים של Git חולקים את התפריט עם אירועי מאגר GitHub, GitLab או Gitea המזוהה אוטומטית, כמו ב-Contribute (`upstream`, ואז `origin`). שלושתם תומכים ב-PR/MR חדשים, ב-PR/MR שמוזגו וב-Issues חדשים, עם **מחבר (אופציונלי)**, כולל `dependabot[bot]`. בחירת אירוע קובעת את המאגר; קריטריונים שמורים שומרים על היעד שלהם.
@ -88,9 +90,11 @@
### צבעים ומצבים {#status-colours}
הדגל מציג את מצב המשימה והחץ את תשומת הלב למטלותיה; רשומה חוזרת משתמשת בסמל חזרה. אדום ממתין לתשובה, צהוב פועם מציין עבודה שנצפתה, כתום השהיה/הפסקה, ירוק תוצאה שלא נראתה וכחול הכנה או מטלה שטרם החלה.
הדגל מציג את מצב המשימה והחץ את תשומת הלב למטלותיה; רשומה חוזרת משתמשת בסמל חזרה. אדום ממתין לתשובה וצהוב פועם מציין עבודה שנצפתה. סמל השהיה כתום מציין השהיה ומשולש אזהרה כתום מציין הפסקה. ירוק מציין משימה, מטלה או הרצה מוצלחת הממתינות לעיון.
בחירה, לחיצה/החלקה על סמלי מטלות ירוקים או סימון כנקרא מתפריט החץ מאשרים תוצאות. מכשול אינו תמיד שאלה; דוח אינו מוכיח שכל פעולה מקורית הסתיימה. מטלות שנמשכו נשמרות בהיסטוריה.
סמל בצבע ההדגשה עם קו ניטרלי קטן וקבוע מתחתיו מציין **בהמתנה להרצה מתוזמנת**: מועד ההתעוררות הבא אושר. צבע ההדגשה נקבע לפי ערכת הצבעים. סמל הדגשה לבדו מציין הכנה או מטלה שטרם התחילה. השלמות שנקראו, תזמונים שנעצרו ו־**מצב לא מאומת** מוצגים בצבע ניטרלי; קראו את טקסט המצב.
בחירה או לחיצה/החלקה על סמלי מטלות ירוקים מאשרות תוצאות; תפריט החץ מציע **סמן כנקרא**. עבור **הרצה שהצליחה וממתינה לעיון**, בחירה מפורשת בשורה החוזרת בחלון הפעיל או **סמן כנקרא** מאשרות את ההרצה המסוימת. הסמל חוזר להמתנה כשהתזמון פעיל, ואחרת לצבע ניטרלי. בחירה ששוחזרה ותוצאות חדשות בשורה שכבר נבחרה משאירות את התוצאה החדשה לעיון. הצלחות היסטוריות בטעינה הראשונה נחשבות כנקראו. מטלות שנמשכו נשמרות בהיסטוריה.
### שאלות והחלטות {#questions}

View file

@ -42,7 +42,7 @@
### 自動的に開始 {#automatic-start}
**自動的に開始** はスケジュールの外にあり、既定でオフです。オフなら一時停止で作成して後で▶から開始します。オンなら作成の確認後、通常の検査と必要なネイティブ設定への同意を経て開始を要求します。
**自動的に開始** はスケジュールの外にあり、既定でオフです。オフなら一時停止で作成して後で▶から開始します。オンなら作成の確認後、通常の検査とスケジュールの自動準備を経て開始を要求します。
作成の確認が失われた場合、受領記録を読んでも開始は手動です。元の未確認要求を保持し、再作成前に一覧と会話を確認してください。
@ -56,6 +56,8 @@
今すぐ1回、N時間ごと、毎日、曜日、毎月の日、cronがあります。保存したタイムゾーンに従い、システムと異なるときにゾーン欄が表示されます。指定日のない月はスキップします。今すぐ1回は開始時の時刻を使う1回の機会で、条件によって実行せず消費することがあります。OpenCodeサービスと実行ホストが必要です。
開始または再開時に、プロジェクトのOpenCode設定でスケジュールを自動的に準備します。明示的なOFFは保持されます。**スケジュール設定を開く**が表示された場合は対象ファイルを開き、**i**で設定元や環境の詳細を確認できます。押したボタンはリクエスト中のみ読み込みを表示します。結果が未確認の場合は確認操作が表示され、復旧した有効化の後も開始は明示的な操作が必要です。
### イベントと組み合わせ {#scheduling-conditions}
**リポジトリのアクティビティ → イベント**を選び、同じカード内で必要なフィルターを設定します。Git コミットと、自動検出された GitHub・GitLab・Gitea のイベントが同じメニューに並びます。検出は Contribute と共通で、`upstream`、次に `origin` を使います。3 種とも新規 PR/MR、マージされた PR/MR、新規 Issue に対応し、**作成者(任意)**に `dependabot[bot]` などを指定できます。イベントを選ぶと対象リポジトリが固定され、保存済み条件は対象を保持します。
@ -88,9 +90,11 @@
### 色と状態 {#status-colours}
旗はミッション、山形はタスクの要注意状態を示し、繰り返し項目には反復アイコンがあります。赤は回答待ち、脈動する黄は観測した作業、橙は停止/中断、緑は未確認の完了、青は準備または未開始です。
旗はミッション、山形はタスクの要注意状態を示し、繰り返し項目には反復アイコンがあります。赤は回答待ち、脈動する黄は観測した作業を示します。橙の一時停止記号は一時停止、橙の警告三角形は中断です。緑は確認待ちのミッション、タスク、成功した実行を示します。
選択、緑のタスクアイコンのクリック/なぞり、山形メニューの既読操作で確認します。障害は必ずしも人への質問ではなく、レポートは全ネイティブ操作の終了を証明しません。撤回したタスクも履歴に残ります。
アクセント色のアイコンの下に小さな静止した中立色の線があると、**スケジュール実行を待機中**で、次の起動時刻が確認済みです。アクセント色はパレットに従います。線のないアクセント色のアイコンは準備済みまたは未開始を示します。確認済みの完了、停止したスケジュール、**状態未確認**は中立色です。状態のテキストも確認してください。
選択、緑のタスクアイコンのクリック/なぞり、山形メニューの**既読にする**で結果を確認します。**成功した実行を確認**では、アクティブなウィンドウで繰り返し行を明示的に選択するか、**既読にする**でその実行を確認します。スケジュールが有効なら待機表示へ、それ以外は中立色へ戻ります。復元された選択や選択済み行に届いた新しい結果は未読のままです。初回読み込み時の過去の成功は既読として扱います。撤回したタスクも履歴に残ります。
### 質問と判断 {#questions}

View file

@ -42,7 +42,7 @@
### स्वतः सुरु गर्नुहोस् {#automatic-start}
**स्वतः सुरु गर्नुहोस्** समयतालिकाबाहिर छ र सुरुमा बन्द हुन्छ। बन्द हुँदा विरामको मिसन बनाएर पछि ▶ बाट सुरु गरिन्छ। खोल्दा सिर्जना पुष्टि भएपछि सामान्य जाँच र आवश्यक नेटिभ सेटिङ सहमतिसहित सुरु गर्न अनुरोध हुन्छ।
**स्वतः सुरु गर्नुहोस्** समयतालिकाबाहिर छ र सुरुमा बन्द हुन्छ। बन्द हुँदा विरामको मिसन बनाएर पछि ▶ बाट सुरु गरिन्छ। खोल्दा सिर्जना पुष्टि भएपछि सामान्य जाँच र समयतालिकाको स्वतः तयारीसहित सुरु गर्न अनुरोध हुन्छ।
सिर्जनाको पुष्टि हराए रसिद पढेपछि पनि सुरुवात म्यानुअल रहन्छ। मूल अपुष्ट अनुरोध राख्नुहोस्; फेरि सिर्जना गर्नुअघि सूची र कुराकानी जाँच्नुहोस्।
@ -56,6 +56,8 @@
एकपटक अहिले, प्रत्येक N घण्टा, दैनिक, हप्ताका दिन, महिनाको दिन र cron छन्। सुरक्षित समय क्षेत्र लागू हुन्छ; प्रणालीभन्दा फरक हुँदा क्षेत्र देखिन्छ। रोजेको दिन नभएको महिना छोडिन्छ। एकपटक अहिलेले सुरु गर्दाको समय लिन्छ; सर्तले एकमात्र अवसर नचलाइकन खर्च गर्न सक्छ। OpenCode सेवा र कार्यान्वयन होस्ट उपलब्ध चाहिन्छ।
सुरु वा पुनः सुरु गर्दा परियोजनाको OpenCode कन्फिगरेसनमा समयतालिका स्वतः तयार हुन्छ। स्पष्ट OFF कायम रहन्छ: उपलब्ध हुँदा **समयतालिकाका सेटिङ खोल्नुहोस्** ले जिम्मेवार फाइल खोल्छ; **i** ले स्रोत वा वातावरणको विवरण देखाउँछ। थिचिएको बटनले अनुरोध चल्दा मात्र लोडिङ देखाउँछ। अपुष्ट परिणाम जाँच गर्न सकिन्छ; सक्रियता पुनः प्राप्त भएपछि पनि सुरु गर्ने कार्य स्पष्ट रूपमा गर्नुपर्छ।
### घटना र संयोजन {#scheduling-conditions}
**रिपोजिटरी गतिविधि → घटना** छान्नुहोस्, त्यसपछि उही कार्डमा ऐच्छिक फिल्टर राख्नुहोस्। Git कमिट र स्वतः पत्ता लगाइएको GitHub, GitLab वा Gitea रिपोजिटरीका घटना एउटै मेनुमा छन्। Contribute कै पहिचानले पहिले `upstream`, त्यसपछि `origin` प्रयोग गर्छ। तीनैमा नयाँ PR/MR, मर्ज भएका PR/MR र नयाँ मुद्दा, साथै `dependabot[bot]` सहित **लेखक (ऐच्छिक)** उपलब्ध छन्। घटना छान्दा रिपोजिटरी तय हुन्छ; सुरक्षित मापदण्डले आफ्नो लक्ष्य कायम राख्छ।
@ -88,9 +90,11 @@
### रङ र अवस्था {#status-colours}
झन्डाले मिसनको अवस्था, चेभ्रोनले कार्यहरूको ध्यान अवस्था देखाउँछ; दोहोरिने प्रविष्टिमा पुनरावृत्ति चिन्ह हुन्छ। रातोले उत्तर पर्खन्छ, धड्किने पहेँलोले देखिएको काम, सुन्तलाले विराम/अवरोध, हरियोले नहेरिएको परिणाम र नीलोले तयारी वा नसुरु कार्य जनाउँछ।
झन्डाले मिसनको अवस्था, चेभ्रोनले कार्यहरूको ध्यान अवस्था देखाउँछ; दोहोरिने प्रविष्टिमा पुनरावृत्ति चिन्ह हुन्छ। रातोले उत्तर पर्खन्छ र धड्किने पहेँलोले देखिएको काम जनाउँछ। सुन्तला विराम चिन्हले विराम र सुन्तला चेतावनी त्रिकोणले अवरोध देखाउँछ। हरियोले समीक्षा गर्न बाँकी मिसन, कार्य वा सफल सञ्चालन जनाउँछ।
चयन, हरियो कार्य चिन्हमा क्लिक/तान्ने वा चेभ्रोन मेनुबाट पढिएको चिह्न लगाउँदा परिणाम पुष्टि हुन्छ। बाधा सधैँ प्रश्न होइन; प्रतिवेदनले सबै नेटिभ कार्य सकिएको प्रमाण दिँदैन। फिर्ता गरिएका कार्य इतिहासमा रहन्छन्।
एक्सेन्ट रङको चिन्हमुनि सानो स्थिर तटस्थ रेखाले **निर्धारित सञ्चालनको प्रतीक्षामा** जनाउँछ: अर्को जागरणको समय पुष्टि भएको छ। एक्सेन्ट रङ प्यालेटअनुसार हुन्छ। रेखाबिनाको एक्सेन्ट चिन्हले तयारी वा नसुरु कार्य देखाउँछ। हेरिएका समाप्ति, रोकिएका समयतालिका र **स्थिति पुष्टि भएको छैन** तटस्थ हुन्छन्; अवस्थाको पाठ पढ्नुहोस्।
चयन वा हरियो कार्य चिन्हमा क्लिक/तान्दा परिणाम पुष्टि हुन्छ; चेभ्रोन मेनुले **पढिएको रूपमा चिन्ह लगाउनुहोस्** दिन्छ। **समीक्षा गर्न बाँकी सफल सञ्चालन** का लागि सक्रिय विन्डोमा दोहोरिने पङ्क्ति स्पष्ट रूपमा छान्नुहोस् वा **पढिएको रूपमा चिन्ह लगाउनुहोस्** प्रयोग गरेर त्यही सञ्चालन पुष्टि गर्नुहोस्। समयतालिका सक्रिय हुँदा चिन्ह प्रतीक्षामा फर्कन्छ, अन्यथा तटस्थ हुन्छ। पुनर्स्थापित चयन र पहिल्यै छानिएको पङ्क्तिमा आएका नयाँ परिणाम नपढिएका रहन्छन्। पहिलो लोडमा भएका पुराना सफलताहरू पढिएका मानिन्छन्। फिर्ता गरिएका कार्य इतिहासमा रहन्छन्।
### प्रश्न र निर्णय {#questions}

View file

@ -42,7 +42,7 @@
### Запускать автоматически {#automatic-start}
**Запускать автоматически** находится вне Расписания и по умолчанию выключено. Выключенное создаёт миссию на паузе для последующего ▶ запуска. Включённое запрашивает старт после подтверждения создания с обычными проверками и необходимым согласием на нативные настройки.
**Запускать автоматически** находится вне Расписания и по умолчанию выключено. Выключенное создаёт миссию на паузе для последующего ▶ запуска. Включённое запрашивает старт после подтверждения создания с обычными проверками и автоматической подготовкой расписания.
Если подтверждение потеряно, чтение квитанции оставляет запуск ручным. Сохраняйте исходный неподтверждённый запрос; перед повторным созданием проверьте список и разговор.
@ -56,6 +56,8 @@
Доступны однократный запуск сейчас, каждые N часов, ежедневно, дни недели, день месяца и cron. Используется сохранённый пояс; поле пояса появляется при отличии от системного. Месяцы без выбранного дня пропускаются. Однократный запуск получает время при старте; условие может израсходовать единственную возможность без запуска. Нужны доступные служба OpenCode и узел исполнения.
При запуске или возобновлении расписание автоматически подготавливается в конфигурации OpenCode проекта. Явное OFF сохраняется: **Открыть настройки расписания**, если доступно, открывает ответственный файл; **i** показывает источник или сведения об окружении. Нажатая кнопка показывает загрузку только во время запроса. Неподтверждённый результат можно проверить; после восстановления активации запуск остаётся явным действием.
### События и сочетания {#scheduling-conditions}
Выберите **Активность репозитория → Событие**, затем дополнительные фильтры в той же карточке. Коммиты Git находятся в одном меню с событиями автоматически определённого репозитория GitHub, GitLab или Gitea, как в Contribute (`upstream`, затем `origin`). Все три поддерживают новые и объединённые PR/MR и новые задачи с необязательным **Автором**, включая `dependabot[bot]`. Выбор события фиксирует репозиторий; сохранённые критерии сохраняют цель.
@ -88,9 +90,11 @@
### Цвета и состояния {#status-colours}
Флаг показывает миссию, шеврон — внимание её задач; повторяющиеся записи имеют значок повтора. Красный ждёт ответа, пульсирующий жёлтый означает наблюдаемую работу, оранжевый — паузу/прерывание, зелёный — непросмотренный результат, синий — подготовку или незапущенную задачу.
Флаг показывает миссию, шеврон — внимание её задач; повторяющиеся записи имеют значок повтора. Красный ждёт ответа, пульсирующий жёлтый означает наблюдаемую работу. Оранжевый символ паузы обозначает паузу, оранжевый предупреждающий треугольник — прерывание. Зелёный отмечает миссию, задачу или успешный запуск, ожидающий просмотра.
Выбор, щелчок/проведение по зелёным значкам задач или отметка прочитанным в меню шеврона подтверждает результаты. Блокировка не всегда вопрос; отчёт не доказывает завершение всех нативных операций. Отозванные задачи остаются в истории.
Акцентный значок с небольшой неподвижной нейтральной чертой снизу означает **Ожидание запуска по расписанию**: следующее пробуждение подтверждено. Акцентный цвет зависит от палитры. Значок без черты обозначает подготовку или незапущенную задачу. Просмотренные завершения, остановленные расписания и **Состояние не подтверждено** нейтральны; читайте текст состояния.
Выбор или щелчок/проведение по зелёным значкам задач подтверждает результаты; меню шеврона предлагает **Отметить как прочитанное**. Для **Успешный запуск для просмотра** явно выберите повторяющуюся строку в активном окне или нажмите **Отметить как прочитанное**, подтверждая именно этот запуск. При активном расписании значок возвращается к ожиданию, иначе — к нейтральному виду. Восстановленный выбор и новые результаты в уже выбранной строке сохраняют новый результат непрочитанным. Исторические успехи при первой загрузке считаются прочитанными. Отозванные задачи остаются в истории.
### Вопросы и решения {#questions}

View file

@ -42,7 +42,7 @@ Takvim tabanlı zamanlama, koordinatör ve rehberin her rolü için açık bir a
### Otomatik başlat {#automatic-start}
**Otomatik başlat**, Zamanlama dışındadır ve varsayılan olarak kapalıdır. Kapalıyken görev duraklatılmış oluşturulur ve daha sonra ▶ ile başlatılır. Açıkken oluşturma doğrulanınca olağan kontroller ve gerekli yerel ayar onayıyla başlatma istenir.
**Otomatik başlat**, Zamanlama dışındadır ve varsayılan olarak kapalıdır. Kapalıyken görev duraklatılmış oluşturulur ve daha sonra ▶ ile başlatılır. Açıkken oluşturma doğrulanınca olağan kontroller ve otomatik zamanlama hazırlığıyla başlatma istenir.
Oluşturma onayı kaybolursa makbuzu okumak otomatik başlatmaz. Doğrulanmamış asıl isteği koruyun; yeniden oluşturmadan önce listeyi ve konuşmayı kontrol edin.
@ -56,6 +56,8 @@ Alt ajan derinliği bilgileri etkin kaynağı **OpenCode yapılandırma dosyası
Bir kez şimdi, N saatte bir, günlük, haftanın günleri, ayın günü ve cron seçenekleri vardır. Kayıtlı saat dilimi kullanılır; sistemden farklıysa dilim alanı görünür. Seçilen günün bulunmadığı ay atlanır. Bir kez şimdi, zamanı Başlat'ta alır; koşul bu tek fırsatı çalıştırmadan tüketebilir. OpenCode hizmeti ve yürütme makinesi kullanılabilir olmalıdır.
Başlatma veya sürdürme sırasında zamanlama projenin OpenCode yapılandırmasında otomatik hazırlanır. Açık OFF korunur: sunulduğunda **Zamanlama ayarlarını aç** sorumlu dosyayı açar; **i** kaynak veya ortam ayrıntılarını gösterir. Tıklanan düğme yalnızca istek sırasında yükleniyor durumunu gösterir. Onaylanmamış sonuç doğrulanabilir; etkinleştirme kurtarıldıktan sonra başlatma açık bir işlem olarak kalır.
### Olaylar ve birleşimler {#scheduling-conditions}
**Depo etkinliği → Olay** seçin, ardından aynı karttaki isteğe bağlı filtreleri kullanın. Git commit’leri, otomatik algılanan GitHub, GitLab veya Gitea deposunun olaylarıyla aynı menüdedir. Algılama Contribute ile ortaktır: önce `upstream`, sonra `origin`. Üçü de yeni ve birleştirilmiş PR/MR ile yeni issue olaylarını ve `dependabot[bot]` dahil isteğe bağlı **Yazar** filtresini destekler. Olay seçimi depoyu sabitler; kayıtlı ölçütler hedeflerini korur.
@ -88,9 +90,11 @@ Liste sonuna yaklaşınca yeni kayıtlar ve işler otomatik yüklenir. İş sayf
### Renkler ve durumlar {#status-colours}
Bayrak Görevin durumunu, şevron işlerinin dikkat durumunu gösterir; tekrarlanan kayıtta tekrar simgesi vardır. Kırmızı yanıt bekler, titreşen sarı gözlenen çalışmayı, turuncu duraklama/kesintiyi, yeşil görülmemiş sonucu, mavi hazırlığı veya başlamamış işi gösterir.
Bayrak Görevin durumunu, şevron işlerinin dikkat durumunu gösterir; tekrarlanan kayıtta tekrar simgesi vardır. Kırmızı yanıt bekler, titreşen sarı gözlenen çalışmayı gösterir. Turuncu duraklatma simgesi duraklamayı, turuncu uyarı üçgeni kesintiyi belirtir. Yeşil, incelenmeyi bekleyen bir Görevi, işi veya başarılı çalıştırmayı gösterir.
Seçim, yeşil iş simgesine tıklama/süpürme veya şevron menüsünden okundu işaretleme sonuçları temizler. Engel her zaman insan sorusu değildir; rapor, tüm yerel işlemlerin sona erdiğini kanıtlamaz. Geri çekilen işin geçmişi tutulur.
Altında küçük, sabit ve nötr bir çizgi olan vurgu renkli simge **Zamanlanmış çalıştırma bekleniyor** demektir: sonraki uyanma doğrulanmıştır. Vurgu rengi palete bağlıdır. Çizgisiz vurgu simgesi hazırlığı veya başlamamış işi belirtir. İncelenmiş tamamlanmalar, durdurulmuş zamanlamalar ve **Durum doğrulanmadı** nötrdür; durum metnini okuyun.
Seçim veya yeşil iş simgesine tıklama/süpürme sonuçları onaylar; şevron menüsünde **Okundu olarak işaretle** bulunur. **İncelenecek başarılı çalıştırma** için etkin pencerede tekrarlanan satırı açıkça seçin veya **Okundu olarak işaretle** ile tam o çalıştırmayı onaylayın. Zamanlama etkinse simge beklemeye, aksi durumda nötre döner. Geri yüklenen seçim ve zaten seçili satıra gelen yeni sonuçlar okunmamış kalır. İlk yüklemedeki geçmiş başarılar okunmuş sayılır. Geri çekilen işin geçmişi tutulur.
### Sorular ve kararlar {#questions}

View file

@ -42,7 +42,7 @@
### 自动启动 {#automatic-start}
**自动启动**位于计划之外,默认关闭。关闭时创建暂停的任务,之后用 ▶ 启动;开启时在创建确认后请求启动,仍执行通常的检查及所需的原生设置确认。
**自动启动**位于计划之外,默认关闭。关闭时创建暂停的任务,之后用 ▶ 启动;开启时在创建确认后请求启动,并执行通常的检查和自动计划准备。
创建确认丢失后,读取回执仍需手动启动。保留原始未确认请求,再次创建前先检查列表和对话。
@ -56,6 +56,8 @@
可选一次现在、每 N 小时、每天、选定星期、每月某日和 cron。时间遵循保存的时区;与系统不同才显示时区字段。没有指定日期的月份会跳过。一次现在以启动时刻为准,只有一次机会,条件可能消耗机会而不启动。需要 OpenCode 服务和执行主机可用。
启动或恢复时,会在项目的 OpenCode 配置中自动准备计划功能。明确的 OFF 设置会保留:如有**打开计划设置**操作,可打开负责该设置的文件;**i** 可显示来源或环境详情。只有请求期间,所点击的按钮才会显示加载状态。未确认的结果可进行核查;恢复启用状态后,仍需明确执行启动操作。
### 事件和组合 {#scheduling-conditions}
选择**仓库活动 → 事件**,再在同一卡片中填写可选筛选条件。Git 提交与自动检测到的 GitHub、GitLab 或 Gitea 仓库事件共用一个菜单,检测方式与 Contribute 相同:先 `upstream`,再 `origin`。三者都支持新建 PR/MR、已合并 PR/MR 和新建 Issue,并可按**作者(可选)**筛选,包括 `dependabot[bot]`。选择事件会固定其仓库;已保存条件保留原目标。
@ -88,9 +90,11 @@
### 颜色和状态 {#status-colours}
旗帜显示任务状态,箭头显示子任务的待关注状态;重复任务使用循环图标。红色等待回答,脉动黄色表示观察到工作,橙色表示暂停/中断,绿色表示未查看的完成结果,蓝色表示准备或尚未启动。
旗帜显示任务状态,箭头显示子任务的待关注状态;重复任务使用循环图标。红色等待回答,脉动黄色表示观察到工作。橙色暂停符号表示暂停,橙色警告三角形表示中断。绿色表示待查看的任务、子任务或成功运行。
选择、点击/扫过绿色子任务图标,或用箭头菜单标记已读可确认结果。阻塞不一定是向你提问;报告不证明所有原生操作已结束。撤回子任务会保留历史。
强调色图标下方的小型静止中性色横线表示**等待计划运行**:下一次唤醒已确认。强调色随调色板变化。单独的强调色图标表示已准备或尚未启动。已查看的完成结果、已停止的计划和**状态未确认**显示为中性色;请阅读状态文字。
选择任务、点击/扫过绿色子任务图标,或使用箭头菜单中的**标为已读**可确认结果。对于**成功运行待查看**,在活动窗口中明确选择重复任务行,或使用**标为已读**确认该次运行。计划仍启用时图标恢复等待状态,否则恢复中性色。恢复的选择和已选中行收到的新结果会保留新结果的未读状态。首次加载时已有的历史成功视为已读。撤回子任务会保留历史。
### 问题和决策 {#questions}

View file

@ -20,8 +20,11 @@ export interface MissionScheduleCapability {
api: { available: true } | { available: false; reason: "missing-api" | "incompatible-contract" }
enabled: boolean
origin: string | null
provenance?: "environment" | "experimental-block" | "all-flags" | "channel-default"
activation: { available: true; targets: Array<{ path: string; scope: "global" | "project" }> }
| { available: false; reason: string; targets: [] }
| { available: false; reason: string; targets: []; code?: "schedule-activation-refused";
refusal?: { reason: "explicit-off" | "masked"; provenance: "environment" | "experimental-block" | "all-flags" | "channel-default";
layer: "environment" | "global" | "project" | "inherited" | "imposed"; path?: string; openable: boolean; configFileID?: string } }
}
export type {

View file

@ -122,6 +122,10 @@ const result = { type: "object", properties: { document: { ...summary, type: ["o
/** Native RPC validates the wire first; the strict domain codec and signed action
* are revalidated before any document or native effect. */
export const missionScheduleRpcMethods = {
scheduleFlag: { input: { type: "object", properties: {}, additionalProperties: false },
output: { type: "object", properties: { enabled: { type: "boolean" },
provenance: { type: "string", enum: ["environment", "experimental-block", "all-flags", "channel-default"] } },
required: ["enabled", "provenance"], additionalProperties: false } },
scheduleList: { input: { type: "object", properties: { after: text, limit: { type: "integer", minimum: 1, maximum: MISSION_SCHEDULE_PAGE_MAX } }, additionalProperties: false },
output: { type: "object", properties: { version: { const: 1 }, projectID: text, next: text,
schedules: { type: "array", maxItems: MISSION_SCHEDULE_PAGE_MAX, items: summary } }, required: ["version", "projectID", "schedules"], additionalProperties: false } },

View file

@ -114,6 +114,7 @@ export interface MissionsPluginContext extends MissionCatalogClient {
register(
definition: typeof CODENOMAD_MISSIONS_RPC,
handlers: {
scheduleFlag(input: unknown): Promise<unknown>
scheduleList(input: unknown): Promise<unknown>
scheduleRead(input: unknown): Promise<unknown>
scheduleControl(input: unknown): Promise<unknown>
@ -227,6 +228,7 @@ export async function setupMissionsPlugin(context: MissionsPluginContext, transp
try {
await policy?.configure(control)
const handlers: Parameters<MissionsPluginContext["rpc"]["register"]>[1] = {
scheduleFlag: async () => { throw new Error("Native Mission schedule flag graph unavailable") },
scheduleList: async () => { throw new Error("Native Mission schedule graph unavailable") },
scheduleRead: async () => { throw new Error("Native Mission schedule graph unavailable") },
scheduleControl: async () => { throw new Error("Native Mission schedule graph unavailable") },
@ -296,6 +298,7 @@ export async function setupMissionsPlugin(context: MissionsPluginContext, transp
delete: async (input, context) => { assertActive(); return mutationResult(context, () => control.delete(parseDeleteMissionInput(input))) },
}
rpcRegistration = await context.rpc.register(CODENOMAD_MISSIONS_RPC, {
scheduleFlag: tracked(handlers.scheduleFlag),
scheduleList: tracked(handlers.scheduleList),
scheduleRead: tracked(handlers.scheduleRead), scheduleControl: tracked(handlers.scheduleControl),
scheduleCarrierRead: tracked(handlers.scheduleCarrierRead),

View file

@ -11,6 +11,7 @@ import { acquireNativeMissionScheduleAuthority, NATIVE_MISSION_SCHEDULE_CONTROL_
import { controlNativeMissionSchedule } from "./native-mission-schedule-control"
import { readMissionSchedulePage } from "../../missions/mission-schedule-list"
import { nativeMissionScheduleObservation } from "./native-mission-schedule-display"
import { readNativeScheduleFlag } from "./native-schedule-flag"
const readInput = z.object({ missionID: documentID, requestID: z.string().min(1).max(128).optional() }).strict()
const carrierInput = z.object({ sessionID: nativeDocumentID }).strict()
@ -20,6 +21,7 @@ const carrierInput = z.object({ sessionID: nativeDocumentID }).strict()
export function nativeMissionScheduleHandlers(ctx: Plugin.Context, artifacts?: NativeScheduleArtifacts) {
const invocation = nativeInvocation(NATIVE_MISSION_SCHEDULE_CONTROL_TIMEOUT_MS)
return {
scheduleFlag: () => readNativeScheduleFlag(ctx).pipe(Effect.orDie),
scheduleList: (raw: unknown) => invocation.capture(Effect.tryPromise(() => invocation.check(run =>
readMissionSchedulePage({ scan: input => run(ctx.storage.scan(input)) }, ctx.location.project, raw,
doc => nativeMissionScheduleObservation(ctx, doc, run)))).pipe(Effect.orDie)),

View file

@ -38,6 +38,7 @@ async function facade(t: test.TestContext, availability: (state: { enabled: bool
Effect.provideService(Context.Service<never, unknown>("@opencode/Location"), location),
Effect.provideService(Context.Service<never, unknown>("@opencode/LocationLifecycle"), { isClosed: () => state.closed }),
Effect.provideService(Context.Service<never, unknown>("@opencode/Config"), { entries: () => Effect.succeed([{ type: "document", info: { experimental: { schedules: state.enabled } } }]) }),
Effect.provideService(Context.Service<never, unknown>("@opencode/Flag"), { resolve: () => ({ schedules: { enabled: state.enabled, source: "config" } }) }),
Effect.provideService(Context.Service<never, unknown>("@opencode/Session"), { remove: () => Effect.void, active: Effect.succeed(new Set()) }),
Effect.provideService(Context.Service<never, unknown>("@opencode/storage/Database"), { db: { $client: { unsafe: () => ({ withoutTransform: Effect.sync(() => state.row === undefined ? [] : [{ data: state.row }]) }) } } }),
Effect.provideService(Scope.Scope, scope)))

View file

@ -18,6 +18,7 @@ import type { MissionCalendarWhen } from "../../missions/mission-calendar-plan"
import type { MissionWake } from "../../missions/mission-document"
import { NATIVE_SCHEDULE_CARRIER_MODEL, NATIVE_SCHEDULE_CARRIER_TITLE } from "./native-schedule-carrier"
import { NATIVE_SCHEDULE_CARRIER_MARKER, NATIVE_SCHEDULE_CARRIER_SIGNAL } from "./native-schedule-carrier-binding"
import { readNativeScheduleFlag } from "./native-schedule-flag"
type NativeEffect = Effect.Effect<unknown, unknown>
type Target = { missionID: string; descriptor: MissionCalendarOwnerSlot }
@ -42,7 +43,7 @@ export const nativeScheduleCalendarMatches = (info: NativeScheduleCalendarInfo,
info.sessionID === slot.sessionID && info.name === slot.name && canonicalAuthority(info.when) === canonicalAuthority(slot.when)
&& info.endsAt === slot.endsAt && info.remainingRuns === null && (slot.anchorAt === undefined || info.createdAt === slot.anchorAt)
const tag = (id: string) => Context.Service<never, unknown>(id)
const scheduleTag = tag("@opencode/Schedule"), locationTag = tag("@opencode/Location"), configTag = tag("@opencode/Config")
const scheduleTag = tag("@opencode/Schedule"), locationTag = tag("@opencode/Location")
const sessionTag = tag("@opencode/Session"), databaseTag = tag("@opencode/storage/Database"), lifecycleTag = tag("@opencode/LocationLifecycle")
const method = Schema.declare<(...args: any[]) => NativeEffect>((value): value is (...args: any[]) => NativeEffect => Predicate.isFunction(value))
const schedulesShape = Schema.Struct({ create: method, list: method, get: method, pause: method, resume: method, remove: method, enabled: method })
@ -66,11 +67,10 @@ export const acquireNativeScheduleCalendarService = Effect.fn("missions.acquireS
}
const schedules = Schema.decodeUnknownSync(schedulesShape)(required(scheduleTag))
const location = Schema.decodeUnknownSync(Schema.toType(Schema.Struct(Location.Info.fields)))(required(locationTag))
const config = required(configTag) as { entries(): NativeEffect }
const sessions = required(sessionTag) as { remove(id: string): NativeEffect; active: NativeEffect }
const database = required(databaseTag) as { db: { $client: SqlClient.SqlClient } }
const lifecycle = required(lifecycleTag) as { isClosed(): boolean }
if (!Predicate.isFunction(config.entries) || !Predicate.isFunction(sessions.remove) || !Effect.isEffect(sessions.active)
if (!Predicate.isFunction(sessions.remove) || !Effect.isEffect(sessions.active)
|| !Predicate.isFunction(database.db?.$client?.unsafe) || !Predicate.isFunction(lifecycle.isClosed) || !carrierAgent) throw new Error("Native calendar cleanup/config contract unavailable")
let active = true
yield* Effect.addFinalizer(() => Effect.sync(() => { active = false }))
@ -99,10 +99,7 @@ export const acquireNativeScheduleCalendarService = Effect.fn("missions.acquireS
})
const enabled = Effect.fnUntraced(function* () {
assertCurrent()
const entries = yield* config.entries()
if (!Array.isArray(entries) || entries.length > 256) throw new Error("Native calendar configuration incomplete")
const latest = [...entries].reverse().find(entry => entry?.type === "document" && entry.info?.experimental !== undefined)
if (latest?.info.experimental?.schedules !== true) throw new Error("Native calendar schedules disabled")
if (!(yield* readNativeScheduleFlag(ctx)).enabled) throw new Error("Native calendar schedules disabled")
assertCurrent()
})
const carrier = Effect.fnUntraced(function* (target: Target) {

View file

@ -0,0 +1,34 @@
import assert from "node:assert/strict"
import test from "node:test"
import { Context, Effect } from "effect"
import { readNativeScheduleFlag } from "./native-schedule-flag"
test("native flag reader uses the acquired resolver and classifies only its bounded non-secret result", async () => {
const location = { directory: "/fixture", project: { id: "project", canonical: "/fixture" } }
let entries: any[] = [], state = { enabled: false, source: "default" }, closed = false
const read = () => Effect.runPromise(readNativeScheduleFlag({ location } as any).pipe(
Effect.provideService(Context.Service<never, unknown>("@opencode/Config"), { entries: () => Effect.succeed(entries) }),
Effect.provideService(Context.Service<never, unknown>("@opencode/Flag"), { resolve: (input: unknown) => {
assert.equal(input, entries); return { schedules: state, unrelated: { secret: "private" } }
} }),
Effect.provideService(Context.Service<never, unknown>("@opencode/Location"), location),
Effect.provideService(Context.Service<never, unknown>("@opencode/LocationLifecycle"), { isClosed: () => closed }),
))
for (const enabled of [true, false]) {
state = { enabled, source: "default" }
assert.deepEqual(await read(), { enabled, provenance: "channel-default" })
entries = [{ type: "document", info: { experimental: { schedules: !enabled } } }]
state = { enabled, source: "env" }
assert.deepEqual(await read(), { enabled, provenance: "environment" })
state.source = "config"
assert.deepEqual(await read(), { enabled, provenance: "experimental-block" })
}
entries = [{ type: "document", info: { experimental: { all_flags: true } } },
{ type: "document", info: { experimental: {} } }]
state = { enabled: true, source: "config" }
assert.deepEqual(await read(), { enabled: true, provenance: "all-flags" })
state.source = "unknown"; await assert.rejects(read(), /resolution unavailable/)
state.source = "config"; entries = new Array(257).fill({ type: "directory", path: "/fixture" })
await assert.rejects(read(), /configuration incomplete/)
entries = []; closed = true; await assert.rejects(read(), /Location retired/)
})

View file

@ -0,0 +1,43 @@
import { Context, Effect, Option } from "effect"
import type { Plugin } from "@opencode/plugin/effect"
import type { ConfigEntry } from "@opencode/client"
export type NativeScheduleFlag = { enabled: boolean; provenance: "environment" | "experimental-block" | "all-flags" | "channel-default" }
/** Read in the receiving Location graph, with the daemon's own overrides/channel.
* The private Flag.resolve/Config.entries shapes are checked before use. */
export const readNativeScheduleFlag = Effect.fn("missions.readScheduleFlag")(function* (ctx: Pick<Plugin.Context, "location">) {
const graph = yield* Effect.context<never>()
const required = (name: string) => {
const service = Context.getOption(graph, Context.Service<never, unknown>(name))
if (Option.isNone(service)) throw new Error("Native schedule flag contract unavailable")
return service.value
}
const config = required("@opencode/Config") as { entries(): Effect.Effect<ConfigEntry[], unknown> }
const flags = required("@opencode/Flag") as { resolve(entries: readonly ConfigEntry[]): Record<string, { enabled: boolean; source: string }> }
const location = required("@opencode/Location") as { directory: string; workspaceID?: string; project: { id: string; canonical: string } }
const lifecycle = required("@opencode/LocationLifecycle") as { isClosed(): boolean }
const current = () => {
if (typeof lifecycle.isClosed !== "function" || lifecycle.isClosed() !== false
|| location.directory !== ctx.location.directory || location.workspaceID !== ctx.location.workspaceID
|| location.project?.id !== ctx.location.project.id || location.project?.canonical !== ctx.location.project.canonical)
throw new Error("Native schedule flag Location retired")
}
current()
if (typeof config.entries !== "function" || typeof flags.resolve !== "function") throw new Error("Native schedule flag contract unavailable")
const effect = config.entries()
if (!Effect.isEffect(effect)) throw new Error("Native schedule flag configuration unavailable")
const entries = yield* effect
if (!Array.isArray(entries) || entries.length > 256 || entries.some(entry => !entry
|| entry.type !== "directory" && (entry.type !== "document" || !entry.info || typeof entry.info !== "object")))
throw new Error("Native schedule flag configuration incomplete")
const state = flags.resolve(entries)?.schedules
if (!state || typeof state.enabled !== "boolean" || !["env", "config", "default"].includes(state.source))
throw new Error("Native schedule flag resolution unavailable")
const block = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental !== undefined)
const provenance: NativeScheduleFlag["provenance"] = state.source === "env" ? "environment"
: state.source === "default" ? "channel-default"
: block?.type === "document" && block.info.experimental?.schedules !== undefined ? "experimental-block" : "all-flags"
current()
return { enabled: state.enabled, provenance } satisfies NativeScheduleFlag
})

View file

@ -54,7 +54,7 @@ test("companion inheritance uses the block before the target, not the final proj
entry("/project/.opencode/opencode.jsonc", { todo: true })]
assert.deepEqual(inheritedMissionExperimental(entries, "/global/opencode.jsonc", "/project"), { schedules: true, subagent_depth: 2 })
assert.deepEqual(inheritedMissionExperimental(entries, "/project/.opencode/opencode.jsonc", "/project"), { subagent_depth: 8 })
assert.deepEqual(effectiveMissionExperimental(entries), { origin: "/project/.opencode/opencode.jsonc" })
assert.deepEqual(effectiveMissionExperimental(entries), { todo: true, origin: "/project/.opencode/opencode.jsonc" })
assert.deepEqual(inheritedMissionExperimental(entries.slice(0, -1), "/project/.opencode/opencode.jsonc", "/project"), { subagent_depth: 8 })
const globalWrite = editMissionExperimental(document("{}"), "schedules", true,
inheritedMissionExperimental(entries, "/global/opencode.jsonc", "/project"), "global")
@ -70,6 +70,14 @@ test("companion inheritance uses the block before the target, not the final proj
], "/project/.opencode/opencode.jsonc", "/project"), {}, "POSIX case remains significant")
})
test("creating an activation block preserves all effective inherited experimental options", () => {
const inherited = { subagent_depth: 0, todo: true, background_compaction: false, all_flags: false,
image_generate: { model: "fixture/image" }, location_idle_timeout: "4 hours" }
const saved = editMissionExperimental(document('{\r\n\t// keep\r\n\t"model":"keep"\r\n}\r\n'), "schedules", true, inherited)
assert.deepEqual(value(saved), { model: "keep", experimental: { ...inherited, schedules: true } })
assert.match(saved, /\r\n\t\/\/ keep/)
})
test("both paths reject malformed or ambiguous parents and companion keys", () => {
for (const text of ['{"experimental":false}', '{"experimental":null}', '{"experimental":{},"experimental":{}}',
'{"experimental":{"schedules":true,"schedules":false}}', '{"experimental":{"subagent_depth":0,"subagent_depth":2}}',

View file

@ -4,7 +4,7 @@ import type { ConfigEntry } from "@opencode/client"
import { PluginControlDocumentError, type PluginControlDocument } from "./plugin-control-document"
import { editNativeSetting, readNativeSetting, removeEmptyNativeObject } from "./native-setting-document"
export interface MissionExperimentalSettings { schedules?: boolean; subagent_depth?: number }
export interface MissionExperimentalSettings { [key: string]: unknown; schedules?: boolean; subagent_depth?: number }
export function nativeSettingExpectation(document: PluginControlDocument): string {
return createHash("sha256").update(JSON.stringify([
@ -20,11 +20,10 @@ function settings(value: unknown): MissionExperimentalSettings {
if (block.schedules !== undefined && typeof block.schedules !== "boolean"
|| block.subagent_depth !== undefined && (!Number.isSafeInteger(block.subagent_depth) || Number(block.subagent_depth) < 0))
throw new PluginControlDocumentError("Invalid Missions experimental setting", "invalid")
return { ...(block.schedules === undefined ? {} : { schedules: block.schedules as boolean }),
...(block.subagent_depth === undefined ? {} : { subagent_depth: block.subagent_depth as number }) }
return { ...block } as MissionExperimentalSettings
}
/** Native precedence selects one whole block. Only the two owned keys leave this reader. */
/** Native precedence selects one whole block; authors preserve its inherited companions. */
export function effectiveMissionExperimental(entries: readonly ConfigEntry[]) {
const entry = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental !== undefined)
return entry?.type === "document"
@ -78,7 +77,7 @@ export function inheritedMissionExperimental(entries: readonly ConfigEntry[], ta
/** Both authors use one JSONC edit under the existing physical-file lock/byte expectation. */
export function editMissionExperimental(
document: PluginControlDocument,
key: keyof MissionExperimentalSettings,
key: "schedules" | "subagent_depth",
value: boolean | number | undefined,
inherited: MissionExperimentalSettings,
scope: "global" | "project" = "project",
@ -89,7 +88,7 @@ export function editMissionExperimental(
throw new PluginControlDocumentError("OpenCode schedules are explicitly disabled in this document", "conflict")
settings({ [key]: value })
let current = document
const apply = (field: keyof MissionExperimentalSettings, next: unknown) => {
const apply = (field: string, next: unknown) => {
const updated = editNativeSetting(current, ["experimental", field], next)
current = { ...current, text: current.byteOrderMark ? updated.slice(1) : updated }
}
@ -99,9 +98,8 @@ export function editMissionExperimental(
// still shadows it and needs the same companion preservation as a save.
if (value !== undefined || block && Object.keys(block).some(field => field !== "subagent_depth")) apply("schedules", true)
}
if (key === "schedules" && readNativeSetting(document, ["experimental"]) === undefined
&& local.subagent_depth === undefined && inherited.subagent_depth !== undefined)
apply("subagent_depth", inherited.subagent_depth)
if (key === "schedules" && readNativeSetting(document, ["experimental"]) === undefined)
for (const [field, companion] of Object.entries(inherited)) if (field !== key) apply(field, companion)
apply(key, value)
return removeEmptyNativeObject(current, ["experimental"])
?? `${current.byteOrderMark ? "\uFEFF" : ""}${current.text}`

View file

@ -52,6 +52,7 @@ test("identical inline request/response structures qualify like refs, while malf
test("read-only reader keeps API support, effective per-Location flag and origin separate and fences replacement", async () => {
let current = true, owned = true, requests = 0, enabled = false
const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("replaced") },
client: { rpc: () => ({ scheduleFlag: async () => ({ enabled, provenance: enabled ? "experimental-block" : "channel-default" }) }) },
fetch: async (url: URL, options: RequestInit) => {
requests++; assert.equal(url.pathname, "/openapi.json"); assert.equal(options.method, undefined)
return Response.json(contract())
@ -66,10 +67,29 @@ test("read-only reader keeps API support, effective per-Location flag and origin
const reader = new NativeScheduleCapabilityReader(documents, { getSharedServiceConnection: async () => connection } as any)
const snapshot = await reader.read("w", { directory: "/project" })
assert.deepEqual(snapshot.api, { available: true }); assert.equal(snapshot.enabled, false)
assert.equal(snapshot.origin, "/project/opencode.jsonc")
assert.equal(snapshot.origin, null)
enabled = true; assert.equal((await reader.read("w", { directory: "/project" })).enabled, true)
owned = false; const before = requests
await assert.rejects(reader.read("w", { directory: "/other" }), /unowned/); assert.equal(requests, before)
owned = true; current = false
await assert.rejects(reader.read("w", { directory: "/project" }), /replaced/)
})
test("capability trusts daemon environment, all-flags and channel defaults rather than document-only inference", async () => {
let flag = { enabled: true, provenance: "all-flags" }
const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() {},
fetch: async () => Response.json(contract()), client: { rpc: () => ({ scheduleFlag: async () => flag }) } }
const documents: any = { readConfigDocuments: async () => ({ location: { directory: "/project" }, documents: [], entries: [
{ type: "document", path: "/global/opencode.jsonc", info: { experimental: { all_flags: true } } },
{ type: "document", path: "/project/opencode.jsonc", info: { experimental: {} } },
] }) }
const reader = new NativeScheduleCapabilityReader(documents, { getSharedServiceConnection: async () => connection } as any)
assert.equal((await reader.read("w", { directory: "/project" })).origin, "/global/opencode.jsonc")
for (const provenance of ["environment", "channel-default"]) for (const enabled of [true, false]) {
flag = { enabled, provenance }
const view = await reader.read("w", { directory: "/project" })
assert.equal(view.enabled, enabled); assert.equal(view.origin, null); assert.equal(view.provenance, provenance)
}
flag = { enabled: true, provenance: "unknown" }
await assert.rejects(reader.read("w", { directory: "/project" }))
})

View file

@ -1,7 +1,8 @@
import type { PluginControlLocation } from "../api-types"
import type { WorkspaceManager } from "../workspaces/manager"
import { readRuntimeContract } from "./compatibility/negotiate"
import { effectiveMissionExperimental, readMissionExperimental } from "./native-experimental-settings"
import { readMissionExperimental } from "./native-experimental-settings"
import { readNativeScheduleFlag, nativeScheduleFlagOrigin } from "./native-schedule-flag"
import { PluginControlsError, type PluginControls } from "./plugin-controls"
type ObjectValue = Record<string, any>
@ -78,8 +79,8 @@ export class NativeScheduleCapabilityReader {
for (const document of snapshot.documents) readMissionExperimental(document.document)
const contract = await readRuntimeContract(connection.endpoint, connection.fetch, AbortSignal.timeout(5_000))
connection.assertCurrent()
const experimental = effectiveMissionExperimental(snapshot.entries)
return { location: snapshot.location, api: nativeScheduleCapability(contract), enabled: experimental.schedules === true,
origin: experimental.origin }
const flag = await readNativeScheduleFlag(connection, location)
return { location: snapshot.location, api: nativeScheduleCapability(contract), enabled: flag.enabled,
provenance: flag.provenance, origin: nativeScheduleFlagOrigin(snapshot.entries, flag) }
}
}

View file

@ -0,0 +1,26 @@
import { z } from "zod"
import type { ConfigEntry } from "@opencode/client"
import type { ServiceConnection } from "../workspaces/opencode-service"
import type { PluginControlLocation } from "../api-types"
import { CODENOMAD_MISSIONS_RPC } from "../missions/rpc"
import { effectiveMissionExperimental } from "./native-experimental-settings"
export const nativeScheduleFlagSchema = z.object({ enabled: z.boolean(),
provenance: z.enum(["environment", "experimental-block", "all-flags", "channel-default"]) }).strict()
export type NativeScheduleFlag = z.infer<typeof nativeScheduleFlagSchema>
/** The daemon, rather than the desktop backend, owns environment and channel defaults. */
export async function readNativeScheduleFlag(connection: ServiceConnection, location: PluginControlLocation) {
connection.assertCurrent()
const result = nativeScheduleFlagSchema.parse(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({},
{ location, signal: AbortSignal.timeout(5_000) }))
connection.assertCurrent()
return result
}
export function nativeScheduleFlagOrigin(entries: readonly ConfigEntry[], flag: NativeScheduleFlag): string | null {
if (flag.provenance === "experimental-block") return effectiveMissionExperimental(entries).origin
if (flag.provenance !== "all-flags") return null
const entry = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental?.all_flags !== undefined)
return entry?.type === "document" ? entry.path ?? null : null
}

View file

@ -1,11 +1,12 @@
import assert from "node:assert/strict"
import { createHash } from "node:crypto"
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import test from "node:test"
import { parse } from "jsonc-parser"
import { PluginControls } from "./plugin-controls"
import { editMissionExperimental, inheritedMissionExperimental } from "./native-experimental-settings"
import { editMissionExperimental, inheritedMissionExperimental, nativeSettingExpectation } from "./native-experimental-settings"
import { nativeScheduleContractFixture } from "./native-schedule-capability-fixture"
import { NativeScheduleSettingsActivation, type NativeScheduleActivationIntent, type NativeScheduleActivationJournal } from "./native-schedule-settings-activation"
@ -14,15 +15,26 @@ async function fixture(run: (value: any) => Promise<void>) {
const global = path.join(root, "global"), project = path.join(root, "project")
await mkdir(global); await mkdir(project)
const globalFile = path.join(global, "opencode.jsonc"), projectFile = path.join(project, "opencode.jsonc")
await writeFile(globalFile, '{"experimental":{"schedules":false,"subagent_depth":2}}\n')
await writeFile(globalFile, '{"experimental":{"subagent_depth":2}}\n')
await writeFile(projectFile, '\uFEFF{\r\n\t// keep\r\n\t"experimental":{"subagent_depth":8,"todo":true}\r\n}\r\n')
let current = true, extra: any[] = [], stale = false, selected: string | undefined, includeProject = true
let flag: { enabled: boolean; provenance: string } | undefined
const entries = async () => [{ type: "document", path: globalFile,
info: stale ? { experimental: { schedules: false } } : parse(await readFile(globalFile, "utf8")) },
info: stale ? { experimental: { subagent_depth: 2 } } : parse(await readFile(globalFile, "utf8")) },
{ type: "directory", path: global }, ...(includeProject ? [{ type: "document", path: projectFile,
info: stale ? { experimental: { subagent_depth: 8 } } : parse((await readFile(projectFile, "utf8")).replace(/^\uFEFF/, "")) }] : []), ...extra]
info: stale ? { experimental: { subagent_depth: 8 } } : parse((await readFile(projectFile, "utf8")).replace(/^\uFEFF/, "")) }]
: await readFile(path.join(project, ".opencode", "opencode.jsonc"), "utf8").then(text => [{
type: "document", path: path.join(project, ".opencode", "opencode.jsonc"), info: parse(text) }]).catch(() => [])), ...extra]
const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("replaced") },
fetch: async () => Response.json(nativeScheduleContractFixture()), client: { config: { get: entries }, plugin: { list: async () => ({ data: [] }) } } }
fetch: async () => Response.json(nativeScheduleContractFixture()), client: { config: { get: entries }, plugin: { list: async () => ({ data: [] }) },
rpc: () => ({ scheduleFlag: async () => {
if (flag) return flag
const documents = (await entries()).filter(entry => entry.type === "document")
const block = [...documents].reverse().find(entry => entry.info.experimental !== undefined)?.info.experimental
const all = [...documents].reverse().find(entry => entry.info.experimental?.all_flags !== undefined)?.info.experimental.all_flags
return { enabled: block?.schedules ?? all === true,
provenance: block?.schedules !== undefined ? "experimental-block" : all === true ? "all-flags" : "channel-default" }
} }) } }
const manager: any = { get: () => ({}), getSharedServiceConnection: async () => connection,
getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined,
ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned",
@ -40,7 +52,7 @@ async function fixture(run: (value: any) => Promise<void>) {
attempting: async scope => { stored.targets.find(target => target.scope === scope)!.attempted = true; await save() },
acknowledged: async (scope, digest) => { const target = stored.targets.find(target => target.scope === scope)!
assert.equal(target.resultDigest, digest); target.acknowledged = true; await save() },
ready: async origin => { assert.equal(origin, projectFile); assert.ok(stored.targets.every(target => target.acknowledged)); ready = true },
ready: async () => { assert.ok(stored.targets.every(target => target.acknowledged)); ready = true },
}
const prepare = async () => { const plan = await activation().prepare("w", location)
stored = { ...plan, targets: plan.targets.map(target => ({ ...target, attempted: false, acknowledged: false })) }; await save(); return structuredClone(stored) }
@ -48,24 +60,25 @@ async function fixture(run: (value: any) => Promise<void>) {
reload: async () => JSON.parse(await readFile(journalFile, "utf8")), intent: () => stored, ready: () => ready,
current: (value: boolean) => { current = value }, extra: (value: any[]) => { extra = value },
stale: (value: boolean) => { stale = value }, selected: (value: string) => { selected = value },
flag: (value: typeof flag) => { flag = value },
missingProject: async () => { await rm(projectFile); includeProject = false } }) }
finally { await chmod(globalFile, 0o600).catch(() => {}); await chmod(projectFile, 0o600).catch(() => {}); await rm(root, { recursive: true, force: true }) }
}
test("two-document activation prepares both files, journals each effect and requires native effective acknowledgement", async () => fixture(async f => {
test("project-only activation journals its effect and requires native effective acknowledgement", async () => fixture(async f => {
const before = await readFile(f.globalFile, "utf8")
const intent = await f.prepare()
assert.equal(await readFile(f.globalFile, "utf8"), before, "preparation creates no config effect")
assert.deepEqual(intent.targets.map((target: any) => target.scope), ["global", "project"])
assert.deepEqual(intent.targets.map((target: any) => target.scope), ["project"])
await f.activation().apply("w", f.location, intent, f.journal)
assert.equal(f.ready(), true)
assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { schedules: true, subagent_depth: 2 })
assert.equal(await readFile(f.globalFile, "utf8"), before)
const project = await readFile(f.projectFile, "utf8")
assert.match(project, /^\uFEFF/); assert.match(project, /\r\n\t\/\/ keep/)
assert.deepEqual(parse(project.slice(1)).experimental, { subagent_depth: 8, todo: true, schedules: true })
}))
test("a read-only project refuses before the first global rename", async () => fixture(async f => {
test("a read-only project refuses before any effect", async () => fixture(async f => {
await chmod(f.projectFile, 0o400)
const intent = await f.prepare(), original = await readFile(f.globalFile, "utf8")
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /read-only|denied|permitted/i)
@ -74,17 +87,13 @@ test("a read-only project refuses before the first global rename", async () => f
assert.equal(f.ready(), false)
}))
test("a read-only global file and a newly required project target refuse the whole preparation", async () => fixture(async f => {
test("a read-only global file permits project-only activation", async () => fixture(async f => {
await chmod(f.globalFile, 0o400)
const intent = await f.prepare()
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /read-only|denied|permitted/i)
await chmod(f.globalFile, 0o600)
await writeFile(f.projectFile, "{}")
const single = await f.prepare()
assert.equal(single.targets.length, 1)
await writeFile(f.projectFile, '{"experimental":{"subagent_depth":0}}')
await assert.rejects(f.activation().apply("w", f.location, single, f.journal), /targets changed/)
assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, false)
const original = await readFile(f.globalFile, "utf8")
await f.activation().apply("w", f.location, intent, f.journal)
assert.equal(f.ready(), true)
assert.equal(await readFile(f.globalFile, "utf8"), original)
}))
test("a concurrent depth author cannot overwrite the activation companion", { timeout: 5_000 }, async () => fixture(async f => {
@ -113,7 +122,7 @@ test("a concurrent depth author cannot overwrite the activation companion", { ti
test("explicit OFF and changed targets refuse without a global side effect", async () => fixture(async f => {
const intent = await f.prepare(), original = await readFile(f.globalFile, "utf8")
await writeFile(f.projectFile, '{"experimental":{"schedules":false,"subagent_depth":0}}')
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /explicitly disabled/)
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), (error: any) => error.code === "schedule-activation-refused" && error.refusal.path === f.projectFile)
assert.equal(await readFile(f.globalFile, "utf8"), original)
await writeFile(f.projectFile, '{"experimental":{"subagent_depth":0}}')
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /changed/)
@ -122,8 +131,8 @@ test("explicit OFF and changed targets refuse without a global side effect", asy
test("an imposed higher block is refused; a different selected host cannot reuse the same native paths", async () => fixture(async f => {
const intent = await f.prepare()
f.extra([{ type: "document", info: { experimental: { subagent_depth: 4, schedules: false } } }])
await assert.rejects(f.activation().prepare("w", f.location), /higher-priority/)
f.extra([{ type: "document", info: { experimental: { subagent_depth: 4 } } }])
await assert.rejects(f.activation().prepare("w", f.location), (error: any) => error.refusal.reason === "masked")
f.extra([]); f.selected("another-distro")
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /authority changed/)
assert.equal(f.ready(), false)
@ -131,25 +140,24 @@ test("an imposed higher block is refused; a different selected host cannot reuse
test("the first imposed block after an absent project insertion point refuses before any write", async () => fixture(async f => {
await f.missingProject()
f.extra([{ type: "document", info: { experimental: { schedules: false } } }])
f.extra([{ type: "document", info: { experimental: {} } }])
const original = await readFile(f.globalFile, "utf8")
await assert.rejects(f.activation().prepare("w", f.location), /higher-priority/)
await assert.rejects(f.activation().prepare("w", f.location), (error: any) => error.refusal.reason === "masked")
assert.equal(await readFile(f.globalFile, "utf8"), original)
await assert.rejects(readFile(path.join(f.project, ".opencode", "opencode.jsonc")), /ENOENT/)
assert.equal(f.ready(), false)
}))
test("lost global acknowledgement is adopted exactly after reload before the unattempted project write", async () => fixture(async f => {
test("lost project acknowledgement is adopted exactly after reload without rewriting", async () => fixture(async f => {
const intent = await f.prepare()
await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal,
acknowledged: async (scope: "global" | "project", digest: string) => { if (scope === "global") throw Error("lost ACK"); await f.journal.acknowledged(scope, digest) },
acknowledged: async () => { throw Error("lost ACK") },
}), /lost ACK/)
assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, true)
assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, undefined)
assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, undefined)
assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, true)
assert.equal(f.ready(), false)
const persisted = await f.reload()
assert.equal(persisted.targets[0].attempted, true); assert.equal(persisted.targets[0].acknowledged, false)
assert.equal(persisted.targets[1].attempted, false)
await f.activation().apply("w", f.location, persisted, f.journal)
assert.equal(f.ready(), true)
}))
@ -164,16 +172,92 @@ test("an uncertain attempted effect with original bytes is never resent", async
assert.equal(f.ready(), false)
}))
test("connection retirement after the global write preserves a partial intention without rollback", async () => fixture(async f => {
test("connection retirement after the project write preserves its intention without rollback", async () => fixture(async f => {
const intent = await f.prepare()
await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal,
acknowledged: async (scope: "global" | "project", digest: string) => { await f.journal.acknowledged(scope, digest); f.current(false) },
}), /replaced|connection/)
assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, true)
assert.equal(f.intent().targets[1].attempted, false)
}), (error: any) => /replaced|connection/.test(error.message) || error.cause?.message === "replaced")
assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, true)
assert.equal(f.intent().targets[0].attempted, true)
assert.equal(f.ready(), false)
}))
test("already ON produces zero targets and zero file writes", async () => fixture(async f => {
await writeFile(f.projectFile, '{"experimental":{"schedules":true}}')
const original = await readFile(f.projectFile, "utf8"), global = await readFile(f.globalFile, "utf8")
const intent = await f.prepare()
assert.deepEqual(intent.targets, [])
await chmod(f.projectFile, 0o400); await chmod(f.globalFile, 0o400)
await f.activation().apply("w", f.location, intent, f.journal)
assert.equal(f.ready(), true)
await f.activation().verify("w", f.location, intent.authority)
assert.equal(await readFile(f.projectFile, "utf8"), original)
assert.equal(await readFile(f.globalFile, "utf8"), global)
}))
for (const layer of ["global", "inherited", "project"]) test(`explicit ${layer} OFF refuses even when hidden by ON`, async () => fixture(async f => {
await writeFile(f.projectFile, '{"experimental":{"schedules":true}}')
if (layer === "global") await writeFile(f.globalFile, '{"experimental":{"schedules":false}}')
else if (layer === "project") await writeFile(f.projectFile, '{"experimental":{"schedules":false}}')
else f.extra([{ type: "document", path: path.join(f.root, "ancestor.jsonc"), info: { experimental: { schedules: false } } },
{ type: "document", info: { experimental: { schedules: true } } }])
const before = await readFile(f.globalFile, "utf8")
await assert.rejects(f.prepare(), (error: any) => error.code === "schedule-activation-refused" && error.refusal.layer === layer)
assert.equal(await readFile(f.globalFile, "utf8"), before)
}))
test("environment OFF refuses; channel defaults and all_flags:false permit a project activation", async () => fixture(async f => {
f.flag({ enabled: false, provenance: "environment" })
await assert.rejects(f.prepare(), (error: any) => error.refusal.layer === "environment" && error.refusal.path === undefined)
f.flag({ enabled: false, provenance: "channel-default" })
await writeFile(f.globalFile, '{"experimental":{"all_flags":false}}')
assert.deepEqual((await f.prepare()).targets.map((target: any) => target.scope), ["project"])
for (const provenance of ["environment", "channel-default", "all-flags"]) {
f.flag({ enabled: true, provenance })
assert.deepEqual((await f.prepare()).targets, [])
}
}))
test("a global OFF appearing after preparation refuses before the project write attempt", async () => fixture(async f => {
const intent = await f.prepare(), original = await readFile(f.projectFile, "utf8")
await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal,
prepared: async (plan: any) => {
await f.journal.prepared(plan)
await writeFile(f.globalFile, '{"experimental":{"schedules":false}}')
},
}), (error: any) => error.code === "schedule-activation-refused")
assert.equal(await readFile(f.projectFile, "utf8"), original)
assert.equal(f.intent().targets[0].attempted, false)
}))
test("an absent project config inherits all effective options into its new activation block", async () => fixture(async f => {
await f.missingProject()
const inherited = { subagent_depth: 0, todo: true, background_compaction: false, all_flags: false }
await writeFile(f.globalFile, JSON.stringify({ experimental: inherited }))
const intent = await f.prepare()
assert.deepEqual(intent.targets.map((target: any) => target.scope), ["project"])
await f.activation().apply("w", f.location, intent, f.journal)
assert.deepEqual(parse(await readFile(intent.targets[0].path, "utf8")).experimental, { ...inherited, schedules: true })
}))
test("legacy global intentions observe attempted bytes only and never write an unattempted target", async () => fixture(async f => {
const single = await f.prepare()
const view = await f.controls.readConfigDocuments("w", f.location, undefined, true)
const global = view.documents.find((item: any) => item.scope === "global")
const updated = editMissionExperimental(global.document, "schedules", true, {}, "global")
const target = { scope: "global" as const, path: global.path, expectation: nativeSettingExpectation(global.document),
resultDigest: createHash("sha256").update(updated).digest("hex"), attempted: false, acknowledged: false }
const intent = { ...single, targets: [target, ...single.targets] }
const original = await readFile(f.globalFile, "utf8")
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /observation/)
assert.equal(await readFile(f.globalFile, "utf8"), original)
await writeFile(f.globalFile, updated); target.attempted = true
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /observation/)
assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, undefined)
target.attempted = false
await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /before this activation attempt/)
}))
test("watcher lag expires at ten seconds and can never publish readiness later", async () => fixture(async f => {
const intent = await f.prepare(); f.stale(true)
const started = performance.now()

View file

@ -3,9 +3,9 @@ import type { PluginControlLocation, PluginControlScope } from "../api-types"
import type { WorkspaceManager } from "../workspaces/manager"
import { readRuntimeContract } from "./compatibility/negotiate"
import { encodePluginControlOriginal } from "./plugin-control-document"
import { readNativeSetting } from "./native-setting-document"
import { editMissionExperimental, effectiveMissionExperimental, inheritedMissionExperimental,
import { editMissionExperimental, inheritedMissionExperimental,
nativeExperimentalTargetPosition, nativeSettingExpectation, readMissionExperimental } from "./native-experimental-settings"
import { readNativeScheduleFlag, nativeScheduleFlagOrigin, type NativeScheduleFlag } from "./native-schedule-flag"
import { nativeScheduleCapability } from "./native-schedule-capability"
import { PluginControlsError, type NativeConfigDocuments, type NativeConfigEdit, type PluginControls } from "./plugin-controls"
@ -22,30 +22,39 @@ export interface NativeScheduleActivationJournal {
const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex")
const digestPattern = /^[a-f0-9]{64}$/
/** Plan only from acquired native discovery. Upper imposed blocks cannot be bypassed. */
export function planNativeScheduleActivation(view: NativeConfigDocuments): NativeConfigEdit[] {
const global = view.documents.find(item => item.scope === "global")
const project = view.documents.find(item => item.scope === "project")
if (!global) throw new PluginControlsError("Global OpenCode configuration is unavailable", "unavailable")
const local = project && readMissionExperimental(project.document)
if (local?.schedules === false) throw new PluginControlsError("Project schedules are explicitly disabled", "forbidden")
const effective = effectiveMissionExperimental(view.entries)
const target = project ?? global
const position = nativeExperimentalTargetPosition(view.entries, target.path, view.location.directory)
const imposed = view.entries.slice(position.after).some(entry => entry.type === "document" && entry.info.experimental !== undefined)
if (imposed && effective.schedules !== true)
throw new PluginControlsError("A higher-priority OpenCode configuration prevents schedule activation", "forbidden")
const edits: NativeConfigEdit[] = []
const add = (item: typeof global, scope: PluginControlScope) => {
const updated = editMissionExperimental(item.document, "schedules", true,
inheritedMissionExperimental(view.entries, item.path, view.location.directory), scope)
edits.push({ scope, path: item.path, expectation: nativeSettingExpectation(item.document), updated })
export type NativeScheduleActivationRefusal = { reason: "explicit-off" | "masked";
provenance: NativeScheduleFlag["provenance"]; layer: "environment" | "global" | "project" | "inherited" | "imposed"; path?: string }
export class NativeScheduleActivationRefused extends PluginControlsError {
readonly code = "schedule-activation-refused"
constructor(readonly refusal: NativeScheduleActivationRefusal) {
super("Native schedule activation refused by configuration", "forbidden")
}
if (readMissionExperimental(global.document).schedules !== true) add(global, "global")
const block = project && readNativeSetting(project.document, ["experimental"])
if (project && !imposed && local?.schedules !== true && (block !== undefined || effective.origin !== null && effective.origin !== global.path))
add(project, "project")
return edits
}
/** Plan only from acquired native discovery. Upper imposed blocks cannot be bypassed. */
export function planNativeScheduleActivation(view: NativeConfigDocuments, flag: NativeScheduleFlag): NativeConfigEdit[] {
const project = view.documents.find(item => item.scope === "project")
const refuse = (path: string | undefined, reason: NativeScheduleActivationRefusal["reason"] = "explicit-off"): never => {
const scope = view.documents.find(item => item.path === path)?.scope
throw new NativeScheduleActivationRefused({ reason, provenance: "experimental-block",
layer: reason === "masked" ? "imposed" : scope ?? (path ? "inherited" : "imposed"), ...(path ? { path } : {}) })
}
// Inspect every discovered layer, including OFF hidden by a higher ON; the
// owned raw documents also fence native watcher lag before a write.
for (const entry of view.entries)
if (entry.type === "document" && entry.info.experimental?.schedules === false) refuse(entry.path)
for (const item of view.documents)
if (readMissionExperimental(item.document).schedules === false) refuse(item.path)
if (!flag.enabled && flag.provenance === "environment")
throw new NativeScheduleActivationRefused({ reason: "explicit-off", provenance: "environment", layer: "environment" })
if (flag.enabled) return []
if (!project) throw new PluginControlsError("Project OpenCode configuration is unavailable", "unavailable")
const position = nativeExperimentalTargetPosition(view.entries, project.path, view.location.directory)
const imposed = view.entries.slice(position.after).find(entry => entry.type === "document" && entry.info.experimental !== undefined)
if (imposed?.type === "document") refuse(imposed.path, "masked")
const updated = editMissionExperimental(project.document, "schedules", true,
inheritedMissionExperimental(view.entries, project.path, view.location.directory))
return [{ scope: "project", path: project.path, expectation: nativeSettingExpectation(project.document), updated }]
}
/** Authenticated Play preparation owns the durable journal callbacks. This executor
@ -66,29 +75,40 @@ export class NativeScheduleSettingsActivation {
const contract = await readRuntimeContract(connection.endpoint, connection.fetch, AbortSignal.timeout(5_000))
connection.assertCurrent()
if (!nativeScheduleCapability(contract).available) throw new PluginControlsError("Native schedule API is unavailable", "unavailable")
return { view, connection }
const flag = await readNativeScheduleFlag(connection, location)
return { view, connection, flag }
}
async prepare(workspaceID: string, location: PluginControlLocation): Promise<NativeScheduleActivationPlan> {
const { view } = await this.context(workspaceID, location)
return { authority: this.authority(workspaceID, view), targets: planNativeScheduleActivation(view).map(item => ({
const { view, flag } = await this.context(workspaceID, location)
return { authority: this.authority(workspaceID, view), targets: planNativeScheduleActivation(view, flag).map(item => ({
scope: item.scope, path: item.path, expectation: item.expectation, resultDigest: hash(item.updated),
})) }
}
async verify(workspaceID: string, location: PluginControlLocation, authority: string): Promise<void> {
const { view, flag } = await this.context(workspaceID, location)
if (this.authority(workspaceID, view) !== authority)
throw new PluginControlsError("OpenCode configuration authority changed", "conflict")
planNativeScheduleActivation(view, flag)
if (!flag.enabled) throw new PluginControlsError("Native schedule activation is not effective", "conflict")
}
async apply(workspaceID: string, location: PluginControlLocation, intent: NativeScheduleActivationIntent,
journal: NativeScheduleActivationJournal): Promise<void> {
if (!digestPattern.test(intent.authority) || intent.targets.length > 2 || new Set(intent.targets.map(item => item.scope)).size !== intent.targets.length
|| intent.targets.some(item => !["global", "project"].includes(item.scope) || !digestPattern.test(item.expectation)
|| !digestPattern.test(item.resultDigest) || typeof item.attempted !== "boolean" || typeof item.acknowledged !== "boolean"))
throw new PluginControlsError("Invalid native schedule activation intent", "invalid")
const { connection } = await this.context(workspaceID, location)
const { connection, flag } = await this.context(workspaceID, location)
// Two-target persisted intentions keep their exact identity and digests;
// reconciliation observes effects already attempted and never resumes writes.
const legacy = intent.targets.some(target => target.scope === "global")
const acknowledged: NativeScheduleActivationTarget[] = []
await this.documents.editConfigDocuments(workspaceID, location, view => {
connection.assertCurrent()
if (this.authority(workspaceID, view) !== intent.authority)
throw new PluginControlsError("OpenCode configuration authority changed", "conflict")
// Recheck OFF and imposed layers before any preparation/rename, even on replay.
const required = planNativeScheduleActivation(view)
if (required.some(edit => !intent.targets.some(target => target.scope === edit.scope && target.path === edit.path)))
const required = planNativeScheduleActivation(view, flag)
if (!legacy && required.some(edit => !intent.targets.some(target => target.scope === edit.scope && target.path === edit.path)))
throw new PluginControlsError("OpenCode activation targets changed; refresh before saving", "conflict")
return intent.targets.flatMap(target => {
const actual = view.documents.find(item => item.scope === target.scope && item.path === target.path)
@ -101,6 +121,8 @@ export class NativeScheduleSettingsActivation {
}
if (target.attempted || target.acknowledged)
throw new PluginControlsError("Native schedule configuration effect is uncertain", "conflict")
if (legacy)
throw new PluginControlsError("Original native schedule activation requires observation of its attempted effects", "conflict")
if (nativeSettingExpectation(actual.document) !== target.expectation)
throw new PluginControlsError("OpenCode configuration changed; activation remains paused", "conflict")
const updated = editMissionExperimental(actual.document, "schedules", true,
@ -117,6 +139,14 @@ export class NativeScheduleSettingsActivation {
},
beforeCommit: async edit => {
connection.assertCurrent()
const fresh = await this.context(workspaceID, location)
connection.assertCurrent()
if (this.authority(workspaceID, fresh.view) !== intent.authority)
throw new PluginControlsError("OpenCode configuration authority changed", "conflict")
const required = planNativeScheduleActivation(fresh.view, fresh.flag)
if (!required.some(target => target.path === edit.path && target.scope === edit.scope
&& target.expectation === edit.expectation && hash(target.updated) === hash(edit.updated)))
throw new PluginControlsError("OpenCode configuration changed before activation", "conflict")
await journal.attempting(edit.scope, hash(edit.updated))
},
afterWrite: async edit => {
@ -139,11 +169,10 @@ export class NativeScheduleSettingsActivation {
const view = await this.documents.readConfigDocuments(workspaceID, location, undefined, true)
connection.assertCurrent(); controller.signal.throwIfAborted()
if (this.authority(workspaceID, view) !== intent.authority) throw new PluginControlsError("OpenCode configuration authority changed", "conflict")
planNativeScheduleActivation(view)
const global = view.documents.find(item => item.scope === "global")!
const nativeGlobal = [...view.entries].reverse().find(entry => entry.type === "document" && entry.path === global.path && entry.info.experimental !== undefined)
const effective = effectiveMissionExperimental(view.entries)
if (nativeGlobal?.type === "document" && nativeGlobal.info.experimental?.schedules === true && effective.schedules === true) return effective.origin
const effective = await readNativeScheduleFlag(connection, location)
controller.signal.throwIfAborted()
planNativeScheduleActivation(view, effective)
if (effective.enabled) return nativeScheduleFlagOrigin(view.entries, effective)
await new Promise(resolve => setTimeout(resolve, 100))
controller.signal.throwIfAborted()
}

View file

@ -60,6 +60,12 @@ function defaultConfigFileEntries(): ConfigFileEntry[] {
return resolveOpenCodeGlobalConfigPaths()
}
/** Exact inventory membership only; a supplied path never grants file access. */
export function configFileEditorID(filePath: string): string | undefined {
const same = (value: string) => process.platform === "win32" ? path.normalize(value).toLowerCase() : path.normalize(value)
return defaultConfigFileEntries().find(file => same(file.absolutePath) === same(filePath))?.id
}
function listConfigFiles(files: ConfigFileEntry[]): ConfigFileDescriptor[] {
return files.map(({ absolutePath: _absolutePath, ...file }) => file)
}

View file

@ -0,0 +1,24 @@
import assert from "node:assert/strict"
import os from "node:os"
import path from "node:path"
import test from "node:test"
import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation"
import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal"
test("refusal exposes editor actions only for exact existing global inventory membership", () => {
for (const extension of ["json", "jsonc"]) {
const file = path.join(os.homedir(), ".config", "opencode", `opencode.${extension}`)
const refusal = missionScheduleActivationRefusal(new NativeScheduleActivationRefused({
reason: "explicit-off", provenance: "experimental-block", layer: "global", path: file }))
assert.equal(refusal?.openable, true)
assert.equal(refusal?.configFileID, extension === "json" ? "opencode-global-config" : "opencode-global-config-jsonc")
}
for (const file of [path.resolve("project/.opencode/opencode.jsonc"), "/remote/config/opencode.json"]) {
const refusal = missionScheduleActivationRefusal(new NativeScheduleActivationRefused({
reason: "explicit-off", provenance: "experimental-block", layer: "inherited", path: file }))
assert.equal(refusal?.openable, false); assert.equal(refusal?.configFileID, undefined)
}
assert.deepEqual(missionScheduleActivationRefusal(new NativeScheduleActivationRefused({
reason: "explicit-off", provenance: "environment", layer: "environment" })),
{ reason: "explicit-off", provenance: "environment", layer: "environment", openable: false })
})

View file

@ -0,0 +1,8 @@
import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation"
import { configFileEditorID } from "./config-files"
export function missionScheduleActivationRefusal(error: unknown) {
if (!(error instanceof NativeScheduleActivationRefused)) return undefined
const configFileID = error.refusal.path && configFileEditorID(error.refusal.path)
return { ...error.refusal, openable: Boolean(configFileID), ...(configFileID ? { configFileID } : {}) }
}

View file

@ -19,7 +19,7 @@ async function fixture(run: (f: any) => Promise<void>) {
const global = path.join(root, "global"), project = path.join(root, "project")
await mkdir(global); await mkdir(project)
const globalFile = path.join(global, "opencode.jsonc"), projectFile = path.join(project, "opencode.jsonc")
await writeFile(globalFile, '{"experimental":{"schedules":false,"subagent_depth":2},"private":"must-stay-out-of-document"}')
await writeFile(globalFile, '{"experimental":{"subagent_depth":2},"private":"must-stay-out-of-document"}')
await writeFile(projectFile, '{"experimental":{"subagent_depth":8}}')
const values = new Map<string, MissionJsonValue>(), phases: string[] = []
const documents = new NativeMissionDocumentStore({ get: async key => structuredClone(values.get(key)),
@ -36,16 +36,21 @@ async function fixture(run: (f: any) => Promise<void>) {
launch: { timing: { kind: "every", intervalMs: 900_000 }, condition: null, ends: { at: null, afterMs: null, maxLaunches: null } },
}, Date.now(), () => true)
let owned = true, current = true, lose = false
let afterPhase: ((action: string) => Promise<void>) | undefined
const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("retired") },
fetch: async () => Response.json(nativeScheduleContractFixture()), client: {
location: { get: async () => ({ directory: project, project: { id: "project", canonical: project, directory: project } }) },
plugin: { list: async () => ({ data: [{ id: "codenomad.missions", state: { status: "active" } }] }) },
config: { get: async () => [{ type: "document", path: globalFile, info: parse(await readFile(globalFile, "utf8")) },
{ type: "directory", path: global }, { type: "document", path: projectFile, info: parse(await readFile(projectFile, "utf8")) }] },
rpc: () => ({ documentCapabilities: async () => ({ version: 1 }), documentActivation: async (input: any) => {
rpc: () => ({ documentCapabilities: async () => ({ version: 1 }),
scheduleFlag: async () => ({ enabled: parse(await readFile(projectFile, "utf8")).experimental?.schedules === true,
provenance: parse(await readFile(projectFile, "utf8")).experimental?.schedules === undefined ? "channel-default" : "experimental-block" }),
documentActivation: async (input: any) => {
phases.push(input.action)
const result = await applyMissionDocumentActivation(documents, input, () => true, project)
if (lose && input.action === "acknowledged" && input.scope === "global") { lose = false; throw Error("lost native reply") }
await afterPhase?.(input.action)
if (lose && input.action === "acknowledged" && input.scope === "project") { lose = false; throw Error("lost native reply") }
return result
} }),
} }
@ -62,18 +67,19 @@ async function fixture(run: (f: any) => Promise<void>) {
const url = "/api/workspaces/w/missions/msn_scheduled/schedule-settings"
const headers = { authorization: "Bearer fixture" }, payload = { requestID: "activate-original", expectedDocumentRevision: 0 }
try { await run({ app, url, headers, payload, documents, values, phases, globalFile, projectFile,
afterPhase: (callback: typeof afterPhase) => { afterPhase = callback },
owned: (value: boolean) => { owned = value }, current: (value: boolean) => { current = value }, lose: () => { lose = true } }) }
finally { await app.close(); await chmod(globalFile, 0o600).catch(() => {}); await rm(root, { recursive: true, force: true }) }
}
test("HTTP preparation composes actual durable RPC phases with both config effects and keeps the mission paused", async () => fixture(async f => {
test("HTTP preparation composes durable RPC phases with only the project effect and keeps the mission paused", async () => fixture(async f => {
const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(response.statusCode, 200, response.body)
const doc = response.json().document
assert.equal(doc.state, "paused"); assert.equal(doc.firstPlayedAt, null); assert.equal(doc.launchedCount, 0)
assert.equal(doc.scheduleActivation.state, "ready")
assert.ok(doc.scheduleActivation.targets.every((target: any) => target.attempted && target.acknowledged))
assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { schedules: true, subagent_depth: 2 })
assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { subagent_depth: 2 })
assert.deepEqual(parse(await readFile(f.projectFile, "utf8")).experimental, { subagent_depth: 8, schedules: true })
assert.ok(!JSON.stringify([...f.values]).includes("must-stay-out-of-document"))
const repeat = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
@ -85,20 +91,99 @@ test("HTTP preparation composes actual durable RPC phases with both config effec
assert.equal(JSON.stringify([...f.values]), before, "status is read-only")
}))
test("lost native acknowledgement exposes a partial intention and explicit same-request reconciliation finishes only the remaining write", async () => fixture(async f => {
test("lost native acknowledgement retains the original intention and exact reconciliation only observes its project write", async () => fixture(async f => {
f.lose()
const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(first.statusCode, 503)
const partial = await f.documents.read("msn_scheduled")
assert.equal(partial.state, "paused"); assert.equal(partial.scheduleActivation.state, "failed")
assert.equal(partial.scheduleActivation.targets[0].acknowledged, true)
assert.equal(partial.scheduleActivation.targets[1].attempted, false)
assert.equal(parse(await readFile(f.projectFile, "utf8")).experimental.schedules, undefined)
assert.equal(partial.scheduleActivation.targets.length, 1)
assert.equal(parse(await readFile(f.projectFile, "utf8")).experimental.schedules, true)
const retry = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(retry.statusCode, 200, retry.body)
assert.equal(retry.json().document.scheduleActivation.state, "ready")
}))
test("already ON creates an empty ready proof and a fresh preparation preserves it read-only", async () => fixture(async f => {
await writeFile(f.projectFile, '{"experimental":{"schedules":true,"todo":true}}')
const original = await readFile(f.projectFile, "utf8")
const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(first.statusCode, 200, first.body)
const before = first.json().document
assert.equal(before.scheduleActivation.state, "ready")
assert.deepEqual(before.scheduleActivation.targets, [])
const next = await f.app.inject({ method: "POST", url: f.url, headers: f.headers,
payload: { requestID: "fresh-request", expectedDocumentRevision: before.revision } })
assert.equal(next.statusCode, 200, next.body)
assert.deepEqual(next.json().document, before)
assert.equal(await readFile(f.projectFile, "utf8"), original)
await writeFile(f.projectFile, '{"experimental":{"schedules":false}}')
const refused = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(refused.statusCode, 403, refused.body)
assert.equal(refused.json().code, "schedule-activation-refused")
assert.equal(refused.json().notApplied, undefined, "the ready original identity remains retained")
assert.deepEqual((await f.documents.read("msn_scheduled")).scheduleActivation, before.scheduleActivation)
}))
test("an explicit hidden global OFF returns its layer/path without editor authorization or writes", async () => fixture(async f => {
await writeFile(f.globalFile, '{"experimental":{"schedules":false}}')
await writeFile(f.projectFile, '{"experimental":{"schedules":true}}')
const before = await f.documents.read("msn_scheduled")
const files = await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8")))
const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(response.statusCode, 403, response.body)
assert.equal(response.json().code, "schedule-activation-refused")
assert.deepEqual(response.json().refusal, { reason: "explicit-off", provenance: "experimental-block",
layer: "global", path: f.globalFile, openable: false })
assert.deepEqual(response.json().notApplied, { requestID: f.payload.requestID, expectedRevision: 0 })
assert.deepEqual(await f.documents.read("msn_scheduled"), before)
assert.deepEqual(f.phases, ["read"], "no mutation is attempted for a definitive refusal")
assert.deepEqual(await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8"))), files)
await writeFile(f.globalFile, '{"experimental":{"subagent_depth":2}}')
const next = await f.app.inject({ method: "POST", url: f.url, headers: f.headers,
payload: { requestID: "explicit-after-correction", expectedDocumentRevision: 0 } })
assert.equal(next.statusCode, 200, next.body)
assert.equal(next.json().document.state, "paused")
}))
test("OFF after intent preparation and on its exact retry retains uncertainty without no-effect proof", async () => fixture(async f => {
f.afterPhase(async (action: string) => {
if (action === "prepare") await writeFile(f.projectFile, '{"experimental":{"schedules":false}}')
})
const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(response.statusCode, 403, response.body)
assert.equal(response.json().code, "schedule-activation-refused")
assert.equal(response.json().notApplied, undefined)
const doc = await f.documents.read("msn_scheduled")
assert.equal(doc.scheduleActivation.requestID, f.payload.requestID)
assert.equal(doc.scheduleActivation.state, "failed")
const retry = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(retry.statusCode, 403, retry.body)
assert.equal(retry.json().notApplied, undefined)
}))
test("a ready legacy two-target proof retains its original identity and digests on fresh preparation", async () => fixture(async f => {
await writeFile(f.globalFile, '{"experimental":{"schedules":true}}')
await writeFile(f.projectFile, '{"experimental":{"schedules":true}}')
const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload })
assert.equal(first.statusCode, 200, first.body)
const doc = await f.documents.read("msn_scheduled")
const legacy = await f.documents.change(doc.id, doc.revision, () => true, (next: any) => {
next.scheduleActivation.targets = [
{ scope: "global", path: f.globalFile }, { scope: "project", path: f.projectFile },
].map(target => ({ ...target, expectation: "a".repeat(64), resultDigest: "b".repeat(64), attempted: true, acknowledged: true }))
})
const global = await readFile(f.globalFile, "utf8"), project = await readFile(f.projectFile, "utf8")
const refreshed = await f.app.inject({ method: "POST", url: f.url, headers: f.headers,
payload: { requestID: "new-ready-verification", expectedDocumentRevision: legacy.revision } })
assert.equal(refreshed.statusCode, 200, refreshed.body)
assert.deepEqual(refreshed.json().document.scheduleActivation, legacy.scheduleActivation)
assert.equal(refreshed.json().document.revision, legacy.revision)
assert.equal(await readFile(f.globalFile, "utf8"), global)
assert.equal(await readFile(f.projectFile, "utf8"), project)
}))
test("route ownership, authentication, revision and input boundaries refuse before any config effect", async () => fixture(async f => {
const before = await readFile(f.globalFile, "utf8")
assert.equal((await f.app.inject({ method: "POST", url: f.url, payload: f.payload })).statusCode, 401)

View file

@ -7,11 +7,12 @@ import { PluginControlsError } from "../../opencode/plugin-controls"
import { requestAdmission } from "../request-admission"
import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation"
import { missionScheduleActivationJournal } from "./mission-schedule-activation-journal"
import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal"
const params = z.object({ id: z.string().min(1).max(200), missionID: z.string().regex(/^[A-Za-z0-9_-]{3,100}$/) }).strict()
const identity = z.object({ requestID: z.string().min(1).max(128), expectedDocumentRevision: z.number().int().nonnegative().safe() }).strict()
type Deps = { workspaceManager: MissionMapMutationManager; worktreeDeletionFence?: WorktreeDeletionFence;
scheduleSettingsActivation?: Pick<NativeScheduleSettingsActivation, "prepare" | "apply"> }
scheduleSettingsActivation?: Pick<NativeScheduleSettingsActivation, "prepare" | "apply" | "verify"> }
/** Authenticated preparation only. The calendar owner performs Play/arming after
* its own complete capability, admission and fresh effective-setting checks. */
@ -25,11 +26,13 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De
? { ...raw, expectedDocumentRevision: Number((raw as Record<string, unknown>).expectedDocumentRevision) } : raw)
if (!selected.success || !input.success) return reply.code(400).send({ error: "Invalid Mission activation request" })
const lifetime = requestAdmission(request, reply)
let noEffect = false
try {
const owned = await prepareMissionMapMutation({ manager: deps.workspaceManager, fence: deps.worktreeDeletionFence,
workspaceID: selected.data.id, signal: lifetime.signal, wait: lifetime.wait })
return await owned.run(async (rpc, options) => {
const guarded = { documentActivation: async (...args: Parameters<typeof rpc.documentActivation>) => {
if ((args[0] as { action?: unknown } | undefined)?.action !== "read") noEffect = false
await owned.refresh()
return rpc.documentActivation(...args)
} }
@ -41,6 +44,14 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De
return reply.code(409).send({ error: "Mission schedule preparation unavailable", code: "schedule-activation-unavailable" })
const previous = before.scheduleActivation
const same = previous?.requestID === input.data.requestID && previous.expectedRevision === input.data.expectedDocumentRevision
noEffect = !same
if (previous?.state === "ready" && (same || before.revision === input.data.expectedDocumentRevision)) {
await deps.scheduleSettingsActivation.verify(selected.data.id, options.location, previous.authority)
await owned.refresh()
const after = await adapter.read()
if (after.revision !== before.revision) throw new PluginControlsError("Mission activation changed during verification", "conflict")
return { document: after }
}
if (!same && (before.revision !== input.data.expectedDocumentRevision
|| previous && (previous.state !== "failed" || previous.targets.some(target => target.attempted))))
return reply.code(409).send({ error: "Original Mission activation remains unresolved", code: "schedule-activation-conflict" })
@ -54,6 +65,7 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De
await deps.scheduleSettingsActivation.apply(selected.data.id, options.location, intent, adapter.journal)
return { document: await adapter.read() }
} catch (error) {
if (noEffect && missionScheduleActivationRefusal(error)) throw error
const code = error instanceof PluginControlsError ? `configuration-${error.kind}` : "configuration-unconfirmed"
// This records metadata only. Attempt markers and successful writes
// survive failure; an uncertain target is never rolled back/replayed.
@ -64,7 +76,10 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De
} catch (error) {
const status = error instanceof MissionMapMutationError ? error.status : error instanceof PluginControlsError
? error.kind === "forbidden" ? 403 : error.kind === "invalid" ? 400 : error.kind === "conflict" ? 409 : 503 : 503
return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed", code: "schedule-activation-pending" })
const refusal = missionScheduleActivationRefusal(error)
return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed",
code: refusal ? "schedule-activation-refused" : "schedule-activation-pending", ...(refusal ? { refusal,
...(noEffect ? { notApplied: { requestID: input.data.requestID, expectedRevision: input.data.expectedDocumentRevision } } : {}) } : {}) })
} finally { lifetime.dispose() }
},
})

View file

@ -2,7 +2,7 @@ import assert from "node:assert/strict"
import test from "node:test"
import Fastify from "fastify"
import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation"
import { PluginControlsError } from "../../opencode/plugin-controls"
import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation"
import { registerMissionScheduleList } from "./mission-schedule-list"
async function fixture(t: test.TestContext) {
@ -25,7 +25,8 @@ async function fixture(t: test.TestContext) {
enabled: state.enabled, origin: "/config/opencode.jsonc" }) },
scheduleSettingsActivation: { prepare: async () => {
calls.push("prepare-read-only"); state.prepare?.()
if (state.forbidden) throw new PluginControlsError("Explicit project OFF", "forbidden")
if (state.forbidden) throw new NativeScheduleActivationRefused({ reason: "explicit-off", provenance: "experimental-block",
layer: "project", path: "/project/opencode.jsonc" })
return { authority: "a".repeat(64), targets: [{ scope: "project", path: "/project/opencode.jsonc", expectation: "secret-expectation", resultDigest: "secret-result" }] }
} },
} as never)
@ -57,6 +58,9 @@ test("capability distinguishes missing API, activable OFF and explicit refusal w
f.state.forbidden = true
response = await f.get("", true)
assert.equal(response.json().activation.reason, "forbidden")
assert.equal(response.json().activation.code, "schedule-activation-refused")
assert.deepEqual(response.json().activation.refusal, { reason: "explicit-off", provenance: "experimental-block",
layer: "project", path: "/project/opencode.jsonc", openable: false })
f.state.api = false
response = await f.get("", true)
assert.equal(response.json().api.reason, "missing-api")

View file

@ -8,6 +8,7 @@ import { PluginControlsError } from "../../opencode/plugin-controls"
import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation"
import { requestAdmission } from "../request-admission"
import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation"
import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal"
const params = z.object({ id: z.string().min(1).max(200) }).strict()
const directory = z.string().min(1).max(4096).refine(value => !value.includes("\0")).optional()
@ -48,7 +49,9 @@ export function registerMissionScheduleList(app: FastifyInstance, deps: Deps) {
const plan = await lifetime.wait(deps.scheduleSettingsActivation.prepare(selected.data.id, owned.location))
activation = { available: true, targets: plan.targets.map(({ path, scope }) => ({ path, scope })) }
} catch (error) {
activation = { available: false, reason: error instanceof PluginControlsError ? error.kind : "unavailable", targets: [] }
const refusal = missionScheduleActivationRefusal(error)
activation = { available: false, reason: error instanceof PluginControlsError ? error.kind : "unavailable", targets: [],
...(refusal ? { code: "schedule-activation-refused", refusal } : {}) }
}
}
await owned.refresh()

View file

@ -37,7 +37,7 @@ import type { NativeScheduleCapabilityReader } from "../../opencode/native-sched
interface MissionRouteDeps {
scheduleCapability?: Pick<NativeScheduleCapabilityReader, "read">
scheduleSettingsActivation?: Pick<NativeScheduleSettingsActivation, "prepare" | "apply">
scheduleSettingsActivation?: Pick<NativeScheduleSettingsActivation, "prepare" | "apply" | "verify">
workspaceManager: Pick<WorkspaceManager, "get" | "getServiceLocation" | "getSharedServiceClient" | "ownsLocation"
| "getSharedServiceConnection" | "getServiceDirectoryForPath" | "getWorktreeIdentityForPath"
| "getHostPathForServicePath" | "getServiceWslDistro">

View file

@ -741,7 +741,7 @@ const MissionControl: Component<MissionControlProps> = (props) => {
expanded={() => missionProjectView(scope()).expanded ?? []}
onExpanded={keys => updateMissionProjectView(scope(), { expanded: keys.slice(-MAX_EXPANDED) })}
markRead={key => {
if (!key.startsWith("mission:")) return undefined
if (!key.startsWith("mission:")) return key.startsWith("schedule:") ? recurrence.markRead(key) : scheduled.markRead(key)
const id = key.slice("mission:".length), entry = missionEntries().find(item => item.key === key)
const unseen = rowQuestions().get(id)?.unseen ?? [], finished = entry?.mark === "done"
// Like a session hierarchy: clears the finished-unseen tasks and the Mission's own completion.
@ -761,6 +761,10 @@ const MissionControl: Component<MissionControlProps> = (props) => {
onSelect={entry => {
const [kind, id] = [entry.key.slice(0, entry.key.indexOf(":")), entry.key.slice(entry.key.indexOf(":") + 1)]
if (kind === "schedule" || kind === "scheduled") {
// Capture this displayed result before selection starts any reads. A
// restored selection or a later success never inherits this gesture.
const acknowledge = entry.mark === "done" ? (kind === "schedule" ? recurrence : scheduled).markRead(entry.key) : undefined
if (treeShown() && documentAttention() && !editor()) acknowledge?.()
intent++
const follow = viewing()
batch(() => {

View file

@ -1,6 +1,6 @@
import { Show, createContext, createMemo, createSignal, onCleanup, onMount, useContext, type Accessor, type JSX } from "solid-js"
import { Portal } from "solid-js/web"
import { ArrowUpRight, BookmarkPlus, PauseCircle, Eye, FastForward, Pause, Pencil, Play, RefreshCw, Square, Trash2 } from "lucide-solid"
import { ArrowUpRight, BookmarkPlus, Loader2 as LoaderCircle, PauseCircle, Eye, FastForward, Pause, Pencil, Play, RefreshCw, Square, Trash2 } from "lucide-solid"
import { useI18n } from "../lib/i18n"
import ActionOverflowMenu, { type ActionOverflowMenuItem } from "./action-overflow-menu"
import type { MissionPrimaryAction } from "./mission-lifecycle-controls"
@ -30,7 +30,7 @@ export function MissionActionBar(props: {
openLabel?: string
/** Interrupts a graceful Pause's still-running steps at once. */
interrupt?: MissionPrimaryAction
onEdit?: () => void; onDelete?: () => void; editDisabled?: boolean; deleteDisabled?: boolean
onEdit?: () => void; onDelete?: () => void; editDisabled?: boolean; deleteDisabled?: boolean; deleteBusy?: boolean
runNow?: MissionPrimaryAction; secondary?: JSX.Element; feedback?: JSX.Element
/** The brief name form belongs to the deliberately revealed task detail. */
secondaryInDetail?: boolean
@ -80,17 +80,17 @@ export function MissionActionBar(props: {
let bar: HTMLDivElement | undefined
const toolbar = () => <div ref={bar} class="mission-action-bar" role="toolbar" aria-label={props.label}>
<button type="button" class="mission-control-icon-button" aria-label={primaryLabel()} title={[primaryLabel(), feedbackText()].filter(Boolean).join(" — ")}
disabled={!props.primary || props.primary.disabled} onClick={() => void props.primary?.onSelect()}>
{primaryIcon(primaryKey())}
disabled={!props.primary || props.primary.disabled || props.primary.busy} aria-busy={props.primary?.busy || undefined} onClick={() => void props.primary?.onSelect()}>
<Show when={props.primary?.busy} fallback={primaryIcon(primaryKey())}><LoaderCircle class="h-3.5 w-3.5 animate-spin" aria-hidden="true" /></Show>
</button>
<button type="button" class="mission-control-icon-button" aria-label={stopLabel()} title={stopLabel()}
disabled={!props.stop || props.stop.disabled} onClick={() => void props.stop?.onSelect()}>
<Square class="h-3.5 w-3.5" aria-hidden="true" />
disabled={!props.stop || props.stop.disabled || props.stop.busy} aria-busy={props.stop?.busy || undefined} onClick={() => void props.stop?.onSelect()}>
<Show when={props.stop?.busy} fallback={<Square class="h-3.5 w-3.5" aria-hidden="true" />}><LoaderCircle class="h-3.5 w-3.5 animate-spin" aria-hidden="true" /></Show>
</button>
<Show when={props.runNow}>{runNow =>
<button type="button" class="mission-control-icon-button" aria-label={runNow().ariaLabel ?? runNow().label} title={runNow().ariaLabel ?? runNow().label}
disabled={runNow().disabled} onClick={() => void runNow().onSelect()}>
<FastForward class="h-3.5 w-3.5" aria-hidden="true" />
disabled={runNow().disabled || runNow().busy} aria-busy={runNow().busy || undefined} onClick={() => void runNow().onSelect()}>
<Show when={runNow().busy} fallback={<FastForward class="h-3.5 w-3.5" aria-hidden="true" />}><LoaderCircle class="h-3.5 w-3.5 animate-spin" aria-hidden="true" /></Show>
</button>}
</Show>
<button type="button" class="mission-control-icon-button icon-toggle mission-overview-toggle" aria-pressed={props.reading}
@ -102,7 +102,9 @@ export function MissionActionBar(props: {
<ArrowUpRight class="h-4 w-4" aria-hidden="true" />
</button>
<button type="button" class="mission-control-icon-button" aria-label={t("missionsPanel.picker.delete")} title={t("missionsPanel.picker.delete")}
disabled={!props.onDelete || props.deleteDisabled} onClick={() => props.onDelete?.()}><Trash2 class="h-4 w-4" aria-hidden="true" /></button>
disabled={!props.onDelete || props.deleteDisabled || props.deleteBusy} aria-busy={props.deleteBusy || undefined} onClick={() => props.onDelete?.()}>
<Show when={props.deleteBusy} fallback={<Trash2 class="h-4 w-4" aria-hidden="true" />}><LoaderCircle class="h-3.5 w-3.5 animate-spin" aria-hidden="true" /></Show>
</button>
<ActionOverflowMenu label={t("messageItem.actions.more")} items={menu} triggerClass="mission-control-icon-button" />
</div>
const mount = () => props.inline ? undefined : slot?.()

View file

@ -11,7 +11,7 @@ import { instances } from "../stores/instances"
import { showConfirmDialog } from "../stores/alerts"
import { missionLifecycleIntents, missionLifecycleSource } from "../stores/mission-lifecycle-intents"
import { partialInterrupt } from "./mission-native-execution-model"
export interface MissionPrimaryAction { key: string; label: string; ariaLabel?: string; disabled?: boolean; onSelect: () => void | Promise<void> }
export interface MissionPrimaryAction { key: string; label: string; ariaLabel?: string; disabled?: boolean; busy?: boolean; onSelect: () => void | Promise<void> }
/** Explicit refresh-then-resend of a selected item's unconfirmed control, owned
* by the panel's refresh button. `reconcile` is read-only and resolves true only

View file

@ -0,0 +1,14 @@
import { getPermissionQueue } from "../stores/instances"
import { getFormQueue } from "../stores/forms"
import { sessions } from "../stores/session-state"
import { getSessionAncestorIdsFromMap } from "../stores/session-tree"
/** Unselected passages use their live coordinator and loaded native descendants. */
export function missionPassageRequests(instanceId: string, root?: string): number {
if (!root) return 0
const family = sessions().get(instanceId) ?? new Map()
const owned = (sessionID?: string) => Boolean(sessionID)
&& (sessionID === root || getSessionAncestorIdsFromMap(family, sessionID!).includes(root))
return getFormQueue(instanceId).filter(form => owned(form.sessionID)).length
+ getPermissionQueue(instanceId).filter(permission => owned(permission.sessionID)).length
}

View file

@ -1,6 +1,8 @@
import assert from "node:assert/strict"
import test from "node:test"
import { filterMissionPickerEntries, missionMark, scheduleMark, type MissionPickerEntry } from "./mission-picker-model"
import { filterMissionPickerEntries, missionMark, scheduleMark, unifiedScheduleMark, type MissionPickerEntry } from "./mission-picker-model"
import type { RecurrenceSchedule } from "../stores/mission-recurrence"
import type { UnifiedMissionSchedule } from "../stores/mission-schedules"
const entry = (key: string, mark: MissionPickerEntry["mark"] = "idle", title = key): MissionPickerEntry => ({ key, title, status: "", mark })
@ -24,18 +26,53 @@ test("a mission's mark: an answer first, then resumable stops, observed work, an
})
test("schedule mark: an answer first, then the schedule's state, the live passage and a retryable failure", () => {
const schedule = (state: string, pending: { status: string } | null, outcome?: string) =>
({ state, pending, latestResult: outcome ? { outcome } : null })
const schedule = (state: RecurrenceSchedule["state"], pending: { status: NonNullable<RecurrenceSchedule["pending"]>["status"] } | null,
outcome?: NonNullable<RecurrenceSchedule["latestResult"]>["outcome"]): RecurrenceSchedule =>
({ id: "daily", revision: 1, title: "Daily", clock: { time: "09:00", zone: "UTC" }, history: [], actions: [],
state, pending: pending ? { ...pending, passageID: "pending" } : null,
latestResult: outcome ? { outcome, passageID: "last", dueAt: 1, settledAt: 2 } : null, controls: [], nextDueAt: Date.now() + 60_000 })
assert.equal(scheduleMark(schedule("running", { status: "running" }), 1), "permission")
assert.equal(scheduleMark(schedule("running", { status: "running" }, "failed")), "working")
assert.equal(scheduleMark(schedule("running", { status: "uncertain" })), "idle")
assert.equal(scheduleMark(schedule("running", { status: "uncertain" })), "unconfirmed")
assert.equal(scheduleMark(schedule("running", null, "failed")), "interrupted", "Run now retries a failed run")
assert.equal(scheduleMark(schedule("interrupted", null, "completed")), "interrupted")
assert.equal(scheduleMark(schedule("paused", null, "completed")), "paused")
assert.equal(scheduleMark(schedule("paused", null, "failed")), "paused", "a pause is the user's own choice")
assert.equal(scheduleMark(schedule("stopped", null, "failed")), "idle", "a stopped schedule offers nothing to continue")
assert.equal(scheduleMark(schedule("unavailable", null, "failed")), "idle")
assert.equal(scheduleMark(schedule("running", null, "completed")), "idle")
assert.equal(scheduleMark(schedule("running", null, "completed")), "waiting")
assert.equal(scheduleMark(schedule("running", null, "ended-without-report")), "waiting",
"an archived reportless passage does not interrupt the positively running daily scheduler")
assert.equal(scheduleMark(schedule("running", null, "completed"), 0, false), "done")
assert.equal(scheduleMark(schedule("running", null, "completed"), 0, false, false), "unconfirmed")
assert.equal(scheduleMark({ ...schedule("running", null), nextDueAt: null }), "unconfirmed")
assert.equal(scheduleMark({ ...schedule("running", null), nextDueAt: 5 }, 0, true, true, 10), "unconfirmed")
assert.equal(scheduleMark({ ...schedule("running", null), lastError: { code: "wake-failed", at: 1 } }), "unconfirmed")
})
test("unified documents share daily priorities and require current positive calendar observation", () => {
const doc = { state: "running", firstPlayedAt: 1, timeGeneration: 3, blockReason: null, control: null, pendingPassage: null,
latestResult: null, observation: { state: "known", nativeStatus: "active", timeGeneration: 3, nextDueAt: 100 } } as UnifiedMissionSchedule
const mark = (patch: Partial<UnifiedMissionSchedule> = {}, seen = true, requests = 0, fresh = true) =>
unifiedScheduleMark({ ...doc, ...patch }, requests, seen, fresh, 50)
assert.equal(mark(), "waiting")
assert.equal(mark({ observation: { ...doc.observation, state: "unknown" } }), "unconfirmed")
assert.equal(mark({ observation: { ...doc.observation, timeGeneration: 2 } }), "unconfirmed")
assert.equal(mark({ observation: { ...doc.observation, nativeStatus: "paused", nextDueAt: null } }), "unconfirmed")
assert.equal(mark({ observation: { ...doc.observation, nextDueAt: 40 } }), "unconfirmed")
assert.equal(mark({}, true, 0, false), "unconfirmed")
assert.equal(mark({ blockReason: "unknown" }), "unconfirmed")
assert.equal(mark({ blockReason: "failed" }, false), "interrupted")
const pendingPassage = { id: "passage" } as NonNullable<UnifiedMissionSchedule["pendingPassage"]>
assert.equal(mark({ pendingPassage }), "working")
assert.equal(mark({ pendingPassage, state: "paused" }), "paused")
assert.equal(mark({ pendingPassage, state: "paused" }, false, 1), "permission")
assert.equal(mark({ state: "paused", firstPlayedAt: null, observation: { ...doc.observation, state: "unarmed" } }), "prepared")
const latestResult = { id: "A", outcome: "completed" } as NonNullable<UnifiedMissionSchedule["latestResult"]>
assert.equal(mark({ latestResult }, false), "done")
assert.equal(mark({ latestResult }), "waiting")
assert.equal(mark({ state: "finished", latestResult }, false), "done")
assert.equal(mark({ state: "finished", latestResult }), "idle")
assert.equal(mark({ state: "stopped", latestResult }, false), "idle")
})
test("filter matches titles case-insensitively", () => {

View file

@ -1,9 +1,9 @@
/** One visual state per Mission or schedule, on the session palette: colour shows
* only what needs attention now. Red asks for an answer, yellow works, orange is
* stopped (interrupted, or paused) with an action to continue, green finished
* since last seen, blue is prepared and ready to start like a composed prompt;
* anything else is idle. Outcomes themselves are status text. */
export type MissionMark = "permission" | "interrupted" | "working" | "paused" | "done" | "prepared" | "idle"
import type { RecurrenceSchedule } from "../stores/mission-recurrence"
import type { UnifiedMissionSchedule } from "../stores/mission-schedules"
/** Colour carries attention; the waiting underline and pause/warning shapes
* distinguish states independently of the palette's accent contrast. */
export type MissionMark = "permission" | "interrupted" | "working" | "paused" | "done" | "prepared" | "waiting" | "unconfirmed" | "idle"
export interface MissionPickerEntry {
/** `mission:<id>` or `schedule:<id>`. */
@ -41,18 +41,57 @@ export function missionMark(mission: { status: string; runState?: string }, inpu
return input.coordinatorState === "idle-without-report" ? "interrupted" : "idle"
}
/** Recurring schedule: an open request of its live passage asks for an answer; a
* stopped schedule rests and a paused one stays paused; an interrupted schedule,
* or a running one whose latest run failed (Run now retries), is orange; a live
* passage works. */
export function scheduleMark(schedule: { state: string; pending: { status: string } | null; latestResult: { outcome: string } | null },
openRequests = 0): MissionMark {
if (openRequests > 0) return "permission"
if (schedule.state === "paused") return "paused"
if (schedule.state === "interrupted") return "interrupted"
if (schedule.state !== "running") return "idle"
if (schedule.pending) return schedule.pending.status === "uncertain" ? "idle" : "working"
return schedule.latestResult?.outcome === "failed" ? "interrupted" : "idle"
interface ScheduleMarkFacts {
state: string; prepared: boolean; uncertain: boolean; interrupted: boolean
pending: boolean; waiting: boolean; outcome?: string
}
/** Both document adapters use the same priority, including Pause over pending work.
* Only a positive native observation can supply waiting or working. */
function projectScheduleMark(facts: ScheduleMarkFacts, openRequests: number, seen: boolean): MissionMark {
if (openRequests) return "permission"
if (facts.state === "stopped") return "idle"
if (facts.interrupted) return "interrupted"
if (facts.uncertain) return "unconfirmed"
if (facts.prepared) return "prepared"
if (facts.state === "paused") return "paused"
if (facts.pending) return "working"
if (facts.outcome === "failed") return "interrupted"
if (facts.outcome === "completed" && !seen) return "done"
return facts.waiting ? "waiting" : "idle"
}
export function scheduleMark(schedule: RecurrenceSchedule, openRequests = 0, seen = true, fresh = true, now = Date.now()): MissionMark {
return projectScheduleMark({ state: schedule.state, prepared: false,
interrupted: schedule.state === "interrupted" || schedule.state === "running" && !schedule.pending
&& schedule.latestResult?.outcome === "failed",
uncertain: !fresh || schedule.controls.some(control => !control.controlsComplete) || Boolean(schedule.lastError)
|| schedule.state !== "paused" && (schedule.pending?.status === "uncertain"
|| schedule.state === "running" && !schedule.pending && !(schedule.nextDueAt !== null && schedule.nextDueAt > now)),
pending: schedule.state !== "paused" && Boolean(schedule.pending),
waiting: schedule.state === "running" && schedule.nextDueAt !== null && schedule.nextDueAt > now,
outcome: schedule.latestResult?.outcome }, openRequests, seen)
}
export function unifiedScheduleMark(doc: UnifiedMissionSchedule, openRequests = 0, seen = true, fresh = true, now = Date.now()): MissionMark {
const prepared = doc.firstPlayedAt === null && doc.state === "paused"
const observed = doc.observation.state === "known" && doc.observation.timeGeneration === doc.timeGeneration
const failure = Boolean(doc.blockReason && ["failed", "ended-without-report"].includes(doc.blockReason))
|| doc.state !== "paused" && !doc.pendingPassage && Boolean(doc.latestResult && doc.latestResult.outcome !== "completed")
const waiting = observed && doc.state === "running" && (doc.observation.nativeStatus === "active" || doc.observation.nativeStatus === "mixed")
&& doc.observation.nextDueAt !== null && doc.observation.nextDueAt > now
const uncertain = !fresh || Boolean(doc.control?.pending) || Boolean(doc.blockReason && !failure)
|| !prepared && (doc.observation.state === "unknown" || doc.observation.timeGeneration !== doc.timeGeneration
|| doc.state === "running" && !doc.pendingPassage && !waiting)
return projectScheduleMark({ state: doc.state, prepared, interrupted: Boolean(failure),
uncertain, pending: doc.state !== "paused" && Boolean(doc.pendingPassage),
waiting,
outcome: doc.latestResult?.outcome }, openRequests, seen)
}
export function missionMarkStateKey(mark: MissionMark): string | undefined {
return mark === "waiting" ? "missionsPanel.state.waiting" : mark === "done" ? "missionsPanel.state.unreadSuccess"
: mark === "unconfirmed" ? "missionsPanel.state.unconfirmed" : mark === "prepared" ? "missions.control.run.prepared"
: mark === "interrupted" ? "missionsPanel.state.interrupted" : undefined
}
export function filterMissionPickerEntries(entries: readonly MissionPickerEntry[], query: string): MissionPickerEntry[] {

View file

@ -1,6 +1,6 @@
import { For, Show, createEffect, createMemo, createSignal, onCleanup, type JSX } from "solid-js"
import { Dynamic } from "solid-js/web"
import { ChevronRight, Flag, Plus, Repeat } from "lucide-solid"
import { AlertTriangle, Flag, Pause, Plus, Repeat } from "lucide-solid"
import { useI18n } from "../lib/i18n"
import SessionExpander from "./session-expander"
import { preserveListFocus } from "../lib/preserve-list-focus"
@ -102,6 +102,8 @@ export function MissionRows(props: {
const open = () => opened().has(key)
const previewing = () => !isSelected() && open()
const label = () => t(open() ? "missionsPanel.row.collapse" : "missionsPanel.row.expand")
// The menu acts on the passage visible when it opened, even after a refresh.
const [markRead, setMarkRead] = createSignal<(() => void)>()
// The session list's own row classes (session-layout.css, session-tree.css).
return <><div class="session-list-item mission-row" data-mission-key={key}>
<div class={`session-item-base ${highlighted() ? "session-item-active" : "session-item-inactive"}`}>
@ -109,8 +111,8 @@ export function MissionRows(props: {
{/* The session list's chevron: right-click marks the whole hierarchy as read. */}
<SessionExpander class="session-item-expander opacity-80 hover:opacity-100 hover:bg-surface-hover" expanded={open()}
activity={entry().childActivity} label={label()} title={label()}
markReadLabel={t("sessionList.expand.markRead")} markReadDisabled={!props.markRead?.(key)}
onMarkRead={() => props.markRead?.(key)?.()} onOpenChange={() => undefined}
markReadLabel={t("sessionList.expand.markRead")} markReadDisabled={!markRead()}
onMarkRead={() => markRead()?.()} onOpenChange={open => { if (open) setMarkRead(() => props.markRead?.(key)) }}
onToggle={() => {
// A schedule's children are its selected detail: expanding one selects it.
if (!isSelected() && !props.expandable?.(key)) props.onSelect(entry())
@ -119,7 +121,10 @@ export function MissionRows(props: {
</Show>
<button type="button" class="session-item-select mission-row-select" aria-current={highlighted() ? "true" : undefined} title={describe(entry())}
onClick={() => props.onSelect(entry())}>
<Dynamic component={key.startsWith("mission:") ? Flag : Repeat} class="mission-row-flag w-4 h-4 flex-shrink-0" data-mark={entry().mark} aria-hidden="true" />
<span class="mission-row-mark" data-mark={entry().mark} aria-hidden="true">
<Dynamic component={entry().mark === "paused" ? Pause : entry().mark === "interrupted" ? AlertTriangle
: key.startsWith("mission:") ? Flag : Repeat} class="mission-row-flag w-4 h-4 flex-shrink-0" data-mark={entry().mark} />
</span>
<bdi class="session-item-title session-item-title--clamp">{entry().title}</bdi><span class="sr-only">{entry().status}</span>
</button>
</div>

View file

@ -1,18 +1,16 @@
import { For, Show, createEffect, createMemo, createSignal, onCleanup, type JSX } from "solid-js"
import { For, Show, createEffect, createMemo, createSignal, onCleanup, untrack, type JSX } from "solid-js"
import { serverApi } from "../lib/api-client"
import { useI18n } from "../lib/i18n"
import { showConfirmDialog } from "../stores/alerts"
import { MissionActionBar } from "./mission-action-bar"
import { scheduleMark, type MissionPickerEntry } from "./mission-picker-model"
import { missionMarkStateKey, scheduleMark, type MissionPickerEntry } from "./mission-picker-model"
import type { MissionControlRetry, MissionPrimaryAction } from "./mission-lifecycle-controls"
import { useMissionRecurrence, type RecurrenceSchedule, type RecurrenceAction } from "../stores/mission-recurrence"
import { missionProjectView, updateMissionProjectView } from "../stores/mission-view-state"
import { markScheduleSuccessSeen, missionProjectView, scheduleSuccessSeen, seedScheduleSuccessSeen, updateMissionProjectView } from "../stores/mission-view-state"
import { showSessionChatFor } from "../stores/session-previews"
import { activeSessionId } from "../stores/sessions"
import { getPermissionQueue, instances } from "../stores/instances"
import { getFormQueue } from "../stores/forms"
import { sessions } from "../stores/session-state"
import { getSessionAncestorIdsFromMap } from "../stores/session-tree"
import { instances } from "../stores/instances"
import { missionPassageRequests } from "./mission-passage-requests"
import { getOpenCodeInstanceGeneration } from "../stores/opencode-data"
import { missionScheduleText } from "./mission-schedule-text"
import { createRecurrenceControlIntent, completedRecurrenceControl, completedRecurrenceManual, partialRecurrenceControl,
@ -21,9 +19,13 @@ import { createRecurrenceControlIntent, completedRecurrenceControl, completedRec
// Lost replies survive remounts. Only an exact status read releases the hold.
const unresolved = new Map<string, RecurrenceControlIntent>()
const partialResults = new Map<string, RecurrenceControlStatus>()
// Bumped on each exact release, so every mounted control drops that request
// even when the release lands after its context changed.
// Retained requests also fence visual marks while their native outcome is unknown.
// Exact releases reach mounted controls even after their context changed.
const [releases, setReleases] = createSignal(0)
const holdIntent = (key: string, intent: RecurrenceControlIntent) => {
if (unresolved.get(key) === intent) return
unresolved.set(key, intent); setReleases(value => value + 1)
}
const sameIntent = (a: RecurrenceControlIntent, b: RecurrenceControlIntent) => a.scheduleID === b.scheduleID && a.requestID === b.requestID
&& a.expectedRevision === b.expectedRevision && a.action === b.action && a.directory === b.directory
const PRIMARY: RecurrenceAction[] = ["resume", "play", "pause"]
@ -40,6 +42,7 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
const key = createMemo(() => JSON.stringify([props.identity, props.schedule.id]))
const [held, setHeld] = createSignal(unresolved.get(key()))
const [busy, setBusy] = createSignal(false)
const [pendingAction, setPendingAction] = createSignal<RecurrenceAction | "status">()
const [partial, setPartial] = createSignal(partialResults.get(key()))
// Message key of the last request proven to have had no effect.
const [refusal, setRefusal] = createSignal<string>()
@ -52,7 +55,7 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
createEffect(() => {
const identity = key(); props.active()
connection()
generation++; setHeld(unresolved.get(identity)); setPartial(partialResults.get(identity)); setBusy(false); setRefusal(undefined)
generation++; setHeld(unresolved.get(identity)); setPartial(partialResults.get(identity)); setBusy(false); setPendingAction(undefined); setRefusal(undefined)
})
onCleanup(() => { generation++ })
const incomplete = () => props.schedule.controls.filter(control => control.controlsComplete !== true)
@ -110,7 +113,7 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
if (retry ? !retryCapable() : !capable(action)) return
const identity = key(), captured = generation, instanceId = props.instanceId
const intent = retry ?? createRecurrenceControlIntent(props.schedule.id, props.schedule.revision, action, props.directory)
unresolved.set(identity, intent); setHeld(intent); setBusy(true); setRefusal(undefined)
holdIntent(identity, intent); setHeld(intent); setBusy(true); setPendingAction(action); setRefusal(undefined)
try {
if (action === "run-now") {
const result = await serverApi.runMissionRecurrenceNow(instanceId, intent)
@ -127,7 +130,7 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
// The exact request is released wherever it is; only its own context sees the message.
if (refusal) settle(intent, identity, refusal, captured === generation)
}
finally { if (captured === generation) setBusy(false) }
finally { if (captured === generation) { setBusy(false); setPendingAction(undefined) } }
}
/** Read-only status read. A refresh (`reconcile`) records a witness only when its
* own completed read, still in this context, leaves the exact request partial. */
@ -136,8 +139,8 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
witness = undefined
// A refresh's own row read must not skip it; the explicit button keeps the full gate.
if (!intent || busy() || !(reconcile ? props.retryEnabled() : props.enabled())) return false
unresolved.set(identity, intent); setHeld(intent)
setBusy(true)
holdIntent(identity, intent); setHeld(intent)
setBusy(true); setPendingAction("status")
try {
if (intent.action === "run-now") {
const result = await serverApi.missionRecurrenceRunNowStatus(props.instanceId, intent)
@ -154,7 +157,7 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
}
}
} catch { /* Retain the exact request identity. */ }
finally { if (captured === generation) setBusy(false) }
finally { if (captured === generation) { setBusy(false); setPendingAction(undefined) } }
return Boolean(witness)
}
/** Resends only the request its preceding read witnessed, once, in that same context. */
@ -176,31 +179,33 @@ function createRecurrenceControls(props: { schedule: RecurrenceSchedule; identit
? "missionsPanel.action.runNow" : action === "play" ? "missionsPanel.action.start" : action === "stop" ? "missionsPanel.action.stop"
: `missionsPanel.action.${action}`)
const description = (action: RecurrenceAction) => t(`missions.recurrence.${action}`, { id: props.schedule.title })
const primaryAction = () => !heldIntent() ? PRIMARY.find(action => props.schedule.actions.includes(action))
const primaryAction = () => PRIMARY.includes(pendingAction() as RecurrenceAction) ? pendingAction() as RecurrenceAction
: !heldIntent() ? PRIMARY.find(action => props.schedule.actions.includes(action))
: supersedable() ? PRIMARY.find(action => SUPERSEDING.includes(action) && props.schedule.actions.includes(action)) : undefined
const statusAction = (): MissionPrimaryAction => ({ key: "status", label: t("missionsPanel.action.checkStatus"),
ariaLabel: t("missions.recurrence.check", { id: props.schedule.title }), disabled: busy() || !props.enabled(), onSelect: () => void check() })
ariaLabel: t("missions.recurrence.check", { id: props.schedule.title }), disabled: busy() || !props.enabled(), busy: pendingAction() === "status", onSelect: () => void check() })
const primary = (): MissionPrimaryAction | undefined => {
const action = primaryAction()
if (heldIntent() && !action) return statusAction()
return action ? { key: action, label: label(action), ariaLabel: description(action), disabled: !capable(action), onSelect: () => act(action) } : undefined
return action ? { key: action, label: label(action), ariaLabel: description(action), disabled: !capable(action), busy: pendingAction() === action, onSelect: () => act(action) } : undefined
}
// Always the schedule's own Stop, disabled when unavailable or a request is held,
// so the toolbar never falls back to the one-time Mission wording.
const stopAction = (): MissionPrimaryAction => ({ key: "stop", label: label("stop"), ariaLabel: description("stop"), disabled: !capable("stop"), onSelect: stop })
const stopAction = (): MissionPrimaryAction => ({ key: "stop", label: label("stop"), ariaLabel: description("stop"), disabled: !capable("stop"), busy: pendingAction() === "stop", onSelect: stop })
// The panel refresh first reads the exact request's status, then resends it
// only when that completed read leaves it partially applied.
const retry: MissionControlRetry = { pending: () => Boolean(heldIntent()) && props.retryEnabled(),
reconcile: () => check(true), resend }
// Always present for schedules, disabled while unavailable or a request is held.
const runNow = (): MissionPrimaryAction => ({ key: "run-now", label: label("run-now"), ariaLabel: description("run-now"),
disabled: !capable("run-now"), onSelect: () => act("run-now") })
const feedback = <Show when={heldIntent()} fallback={<Show when={refusal()}>{message => <small role="status">{t(message())}</small>}</Show>}>
<small role="status">{t("missions.recurrence.uncertain")}</small></Show>
disabled: !capable("run-now"), busy: pendingAction() === "run-now", onSelect: () => act("run-now") })
const feedback = <p role="status">{pendingAction() ? t(pendingAction() === "play" ? "missionsPanel.action.starting"
: pendingAction() === "resume" ? "missionsPanel.action.resuming" : pendingAction() === "run-now" ? "missionsPanel.action.runningNow"
: "missions.control.mutation.pending") : heldIntent() ? t("missions.recurrence.uncertain") : refusal() ? t(refusal()!) : ""}</p>
// While a superseding action holds the primary place, the unknown intent's exact status read stays one click away.
const statusButton = <button type="button" class="window-action" title={statusAction().ariaLabel} aria-label={statusAction().ariaLabel}
disabled={statusAction().disabled} onClick={() => statusAction().onSelect()}>{statusAction().label}</button>
const superseding = createMemo(() => Boolean(heldIntent() && primaryAction()))
const superseding = createMemo(() => Boolean(heldIntent() && primaryAction() && !busy()))
const secondary = () => superseding() ? statusButton : undefined
return { primary, stop: stopAction, runNow, retry, feedback, secondary }
}
@ -223,6 +228,13 @@ export function createMissionRecurrenceList(props: { instanceId: string; project
// explicit refresh's own in-flight row read must not silently skip it.
const admissible = () => !error() && props.active() && snapshot()?.projectID === props.projectID && Boolean(props.projectID)
const valid = () => !loading() && admissible()
const seenScope = () => JSON.stringify([props.scope, props.projectID])
createEffect(() => {
const schedules = snapshot()?.schedules, scope = seenScope()
if (!schedules || error()) return
untrack(() => { for (const schedule of schedules) seedScheduleSuccessSeen(scope, "daily", schedule.id,
schedule.latestResult?.outcome === "completed" ? schedule.latestResult.passageID : undefined) })
})
const text = missionScheduleText(t, locale)
const { date } = text
/** One sentence; its action is the row's primary control (Resume). */
@ -261,19 +273,18 @@ export function createMissionRecurrenceList(props: { instanceId: string; project
const passageRequests = (schedule: RecurrenceSchedule) => {
const selected = schedule.id === props.selectedSchedule ? props.selectedRequests : undefined
if (selected && selected.passageID === schedule.pending?.passageID) return selected.count
const root = schedule.pending?.conversationID
if (!root) return 0
const family = sessions().get(props.instanceId) ?? new Map()
const owned = (sessionID?: string) => Boolean(sessionID)
&& (sessionID === root || getSessionAncestorIdsFromMap(family, sessionID!).includes(root))
return getFormQueue(props.instanceId).filter(form => owned(form.sessionID)).length
+ getPermissionQueue(props.instanceId).filter(permission => owned(permission.sessionID)).length
return missionPassageRequests(props.instanceId, schedule.pending?.conversationID)
}
const entries = createMemo((): MissionPickerEntry[] => (snapshot()?.schedules ?? []).map(schedule => {
releases()
const held = unresolved.has(JSON.stringify([JSON.stringify([props.instanceId, props.projectID, props.scope]), schedule.id]))
const state = t(`missions.recurrence.state.${schedule.state}`), next = text.next(schedule)
const mark = scheduleMark(schedule, passageRequests(schedule))
const mark = scheduleMark(schedule, passageRequests(schedule), !schedule.latestResult
|| scheduleSuccessSeen(seenScope(), "daily", schedule.id, schedule.latestResult.passageID), !error() && !held)
const stateKey = missionMarkStateKey(mark)
return { key: `schedule:${schedule.id}`, title: schedule.title, mark,
status: [t("missionsPanel.dailyBadge"), state, mark === "permission" ? t("missionsPanel.task.input") : "", next, text.every(schedule)]
status: [t("missionsPanel.dailyBadge"), mark === "unconfirmed" && (schedule.state === "paused" || schedule.state === "stopped") ? state : "",
stateKey ? t(stateKey) : state, mark === "permission" ? t("missionsPanel.task.input") : "", next, text.every(schedule)]
.filter(Boolean).join(" · ") }
}))
const selectedId = () => snapshot()?.schedules.some(schedule => schedule.id === props.selectedSchedule) ? props.selectedSchedule : undefined
@ -305,5 +316,11 @@ export function createMissionRecurrenceList(props: { instanceId: string; project
</section>
}}</Show>
</>
return { entries, view, listView, loading }
const markRead = (key: string) => {
const schedule = snapshot()?.schedules.find(item => key === `schedule:${item.id}`), result = schedule?.latestResult
const scope = seenScope()
return schedule && result?.outcome === "completed" && !scheduleSuccessSeen(scope, "daily", schedule.id, result.passageID)
? () => markScheduleSuccessSeen(scope, "daily", schedule.id, result.passageID) : undefined
}
return { entries, view, listView, loading, markRead }
}

View file

@ -9,6 +9,10 @@ import { getOpenCodeInstanceGeneration } from "../stores/opencode-data"
import { instances } from "../stores/instances"
import { requiresMissionCalendar } from "../../../server/src/missions/mission-launch-kind"
import { partialMissionScheduleReceipt as partialReceipt, refusedMissionScheduleReceipt, type MissionScheduleControlReceipt as ControlReceipt } from "../lib/mission-schedule-receipt"
import type { MissionScheduleCapability } from "../../../server/src/api-types"
import { HttpResponseError } from "../lib/retryable-file-search"
type ActivationRefusal = Extract<MissionScheduleCapability["activation"], { available: false }>["refusal"]
// Exact dispatched identities survive navigation and remount. Unresolved entries
// never evict; the ceiling refuses another control rather than forgetting one.
@ -28,6 +32,8 @@ export function createMissionScheduleControls(props: { instanceId: string; proje
const { t } = useI18n()
const identity = () => JSON.stringify([props.instanceId, props.projectID, props.directory, props.document().id])
const [busy, setBusy] = createSignal(false), [feedback, setFeedback] = createSignal<string>()
const [pendingAction, setPendingAction] = createSignal<Action>()
const [refusal, setRefusal] = createSignal<ActivationRefusal>()
let alive = true
onCleanup(() => { alive = false })
const held = () => unifiedScheduleHold(identity())
@ -44,12 +50,16 @@ export function createMissionScheduleControls(props: { instanceId: string; proje
createEffect(() => {
const owner = capabilityOwner(); props.refreshVersion()
untrack(() => {
if (owner !== previousOwner) { setBusy(false); setCapability("loading"); previousOwner = owner }
if (owner !== previousOwner) { setBusy(false); setPendingAction(undefined); setRefusal(undefined); setFeedback(undefined); setCapability("loading"); previousOwner = owner }
if (!props.active()) return
const currentView = capture(), abort = new AbortController()
const current = () => currentView() && !abort.signal.aborted
void serverApi.fetchMissionScheduleCapability(props.instanceId, props.directory, abort.signal).then(value => {
if (current()) setCapability(value.api.available ? value.enabled ? "available" : value.activation.available ? "activatable" : "missing" : "missing")
if (current()) {
setCapability(value.api.available ? value.enabled ? "available" : value.activation.available ? "activatable" : "missing" : "missing")
setRefusal(value.api.available && !value.activation.available ? value.activation.refusal : undefined)
if (value.activation.available && feedback() === "missions.scheduleList.activationRefused") setFeedback(undefined)
}
}).catch(() => { if (current()) setCapability("missing") })
onCleanup(() => abort.abort())
})
@ -72,7 +82,7 @@ export function createMissionScheduleControls(props: { instanceId: string; proje
&& !held()
async function receipt(key: string, hold: Hold, current: () => boolean) {
const doc = props.document(), result = await serverApi.fetchMissionSchedule(props.instanceId, doc.id,
{ directory: props.directory, requestID: hold.requestID }).catch(error => {
{ directory: props.directory, requestID: hold.requestID }, AbortSignal.timeout(30_000)).catch(error => {
const result = partialReceipt(error); if (result) return result; throw error
})
if (exactMissionScheduleControl(result, hold, doc.id)) {
@ -108,43 +118,48 @@ export function createMissionScheduleControls(props: { instanceId: string; proje
async function act(action: Action, creation = false) {
if (!capable(action, creation)) return
const current = capture(), key = identity(), original = props.document()
setBusy(true); setFeedback(undefined)
setBusy(true); setPendingAction(action); setFeedback(undefined); setRefusal(undefined)
let dispatched: Hold | undefined
try {
// The button/confirmation describes an exact revision, not a live draft.
const latest = await serverApi.fetchMissionSchedule(props.instanceId, original.id, { directory: props.directory })
const latest = await serverApi.fetchMissionSchedule(props.instanceId, original.id, { directory: props.directory }, AbortSignal.timeout(30_000))
if (!current()) return
if (!latest.document || latest.document.id !== original.id || latest.document.revision !== original.revision) {
setFeedback("missions.scheduleList.conflict"); props.refresh(); return
}
if (action === "stop" || action === "delete" || action === "run-now") {
setPendingAction(undefined)
const confirmed = await showConfirmDialog(t(`missions.scheduleList.confirm.${action}`, { title: original.configuration.title }),
{ variant: "warning", confirmLabel: label(action), cancelLabel: t("missions.simple.cancel") })
if (!confirmed || !current() || props.document().revision !== original.revision) return
setPendingAction(action)
}
let revision = original.revision
if (["play", "resume", "run-now"].includes(action) && requiresMissionCalendar(original.configuration.launch)) {
const capability = await serverApi.fetchMissionScheduleCapability(props.instanceId, props.directory)
const capability = await serverApi.fetchMissionScheduleCapability(props.instanceId, props.directory, AbortSignal.timeout(30_000))
if (!current()) return
if (!capability.activation.available && capability.activation.refusal) {
setRefusal(capability.activation.refusal); setFeedback("missions.scheduleList.activationRefused"); return
}
if (!capability.api.available || !capability.enabled && !capability.activation.available) {
setFeedback("missions.scheduling.capability.missing"); return
}
if (action === "run-now" && !capability.enabled) {
setFeedback("missions.scheduleList.runNowRequiresEnabled"); return
}
if (!capability.enabled) {
const targets = capability.activation.targets.map(item => item.path).join("\n")
const confirmed = await showConfirmDialog(t("missions.scheduleList.activate", { paths: targets }),
{ variant: "warning", confirmLabel: label(action), cancelLabel: t("missions.simple.cancel") })
if (!confirmed || !current() || props.document().revision !== original.revision) return
if (action !== "run-now" && (!capability.enabled || latest.document.scheduleActivation?.state !== "ready")) {
if (holds.size >= 128 && !holds.has(key)) { setFeedback("missions.scheduleList.capacity"); return }
const activation: Hold = { phase: "activation", action, requestID: generateUUID(), expectedRevision: revision, partial: false, document: original }
// An ON display alone cannot replace the server's ready proof.
// A retained proof keeps its original identity on the server.
const previous = latest.document.scheduleActivation
const activation: Hold = { phase: "activation", action, requestID: previous?.state === "ready" ? previous.requestID : generateUUID(),
expectedRevision: previous?.state === "ready" ? previous.expectedRevision : revision, partial: false, document: original }
holds.set(key, activation); dispatched = activation; bump()
const value = await serverApi.missionScheduleSettings(props.instanceId, original.id,
{ requestID: activation.requestID, expectedDocumentRevision: revision }, true)
const proof = value.document.scheduleActivation
if (!Number.isSafeInteger(value.document.revision) || value.document.revision < revision
|| proof?.requestID !== activation.requestID || proof.expectedRevision !== revision || proof.state !== "ready") return
|| proof?.requestID !== activation.requestID || proof.expectedRevision !== activation.expectedRevision || proof.state !== "ready") return
settle(key, activation, current, value.document.revision); dispatched = undefined
if (!current()) return
revision = value.document.revision
@ -165,18 +180,33 @@ export function createMissionScheduleControls(props: { instanceId: string; proje
else if (current()) await receipt(key, request, current)
if (current()) props.refresh()
} catch (error) {
if (dispatched?.phase === "control" && refusedMissionScheduleReceipt(error, dispatched, original.id) && holds.get(key) === dispatched) {
if (error instanceof HttpResponseError && error.code === "schedule-activation-refused") {
const body = error.body as { refusal?: ActivationRefusal; notApplied?: { requestID?: string; expectedRevision?: number } } | undefined
if (dispatched?.phase === "activation" && holds.get(key) === dispatched
&& body?.notApplied?.requestID === dispatched.requestID && body.notApplied.expectedRevision === dispatched.expectedRevision) {
holds.delete(key); bump()
}
if (current()) { setRefusal(body?.refusal); setFeedback("missions.scheduleList.activationRefused") }
// Without exact no-effect proof, preserve the original activation.
} else if (dispatched?.phase === "activation" && error instanceof HttpResponseError
&& ["schedule-activation-conflict", "schedule-activation-unavailable"].includes(error.code ?? "") && holds.get(key) === dispatched) {
holds.delete(key); bump()
if (current()) setFeedback("missions.scheduleList.conflict")
} else if (dispatched?.phase === "control" && refusedMissionScheduleReceipt(error, dispatched, original.id) && holds.get(key) === dispatched) {
if (dispatched.minimumRevision !== undefined) settle(key, dispatched, current, dispatched.minimumRevision)
else { holds.delete(key); bump(); if (current()) props.refresh() }
if (current()) setFeedback("missions.scheduleList.conflict")
} else if (current() && !dispatched) setFeedback("missions.scheduleList.readFailed")
}
finally { if (current()) { setBusy(false); props.refresh() } }
finally { if (current()) { setBusy(false); setPendingAction(undefined); props.refresh() } }
}
const label = (action: Action) => t(action === "delete" ? "missionsPanel.picker.delete" : action === "run-now" ? "missionsPanel.action.runNow"
: action === "play" ? "missionsPanel.action.start" : `missionsPanel.action.${action}`)
// Direct creation already has an exact document receipt. Its continuation still
// rereads the document and capability before any activation or Play dispatch.
return { held, publishing, busy, feedback, capability, capable, act, reconcile, label,
const progress = () => pendingAction() ? pendingAction() === "play" ? "missionsPanel.action.starting"
: pendingAction() === "resume" ? "missionsPanel.action.resuming" : pendingAction() === "run-now" ? "missionsPanel.action.runningNow"
: "missions.control.mutation.pending" : undefined
return { held, publishing, busy, pendingAction, progress, feedback, refusal, capability, capable, act, reconcile, label,
startCreated: () => act("play", true) }
}

View file

@ -1,13 +1,16 @@
import { For, Show, createMemo, createSignal, createEffect, type JSX } from "solid-js"
import { For, Show, createMemo, createSignal, createEffect, untrack, type JSX } from "solid-js"
import { useI18n } from "../lib/i18n"
import { useMissionSchedules, unifiedScheduleHold, type UnifiedMissionSchedule } from "../stores/mission-schedules"
import type { MissionPickerEntry } from "./mission-picker-model"
import { missionMarkStateKey, unifiedScheduleMark, type MissionPickerEntry } from "./mission-picker-model"
import { markScheduleSuccessSeen, scheduleSuccessSeen, seedScheduleSuccessSeen } from "../stores/mission-view-state"
import { describeMissionCriteria, missionCriteriaZone } from "./mission-scheduling-summary"
import { createMissionScheduleControls } from "./mission-schedule-controls"
import { MissionActionBar } from "./mission-action-bar"
import { missionLaunchLimit, missionLaunchModel } from "../../../server/src/missions/mission-launch-kind"
import { MissionScheduleDiagnostics } from "./mission-schedule-diagnostics"
import { SettingsInfoTip } from "./settings/settings-info-tip"
import { openSettingsConfigFile } from "../stores/settings-screen"
import { missionPassageRequests } from "./mission-passage-requests"
export function createMissionScheduleList(props: { instanceId: string; projectID?: string; directory: string;
active: () => boolean; enabled: () => boolean; refresh: number; selected?: string; detailId: string;
@ -21,6 +24,14 @@ export function createMissionScheduleList(props: { instanceId: string; projectID
const list = useMissionSchedules({ instanceId: () => props.instanceId, projectID: () => props.projectID,
directory: () => props.directory, active: props.active, refresh: () => props.refresh + revision(), selected: () => props.selected })
const schedules = () => list.rows().filter(row => row.kind === "schedule")
const seenScope = () => JSON.stringify([props.directory, props.projectID])
createEffect(() => {
const docs = schedules(), scope = seenScope()
if (list.error()) return
const fresh = docs.filter(doc => list.fresh(doc.id))
untrack(() => { for (const doc of fresh) seedScheduleSuccessSeen(scope, "scheduled", doc.id,
doc.latestResult?.outcome === "completed" ? doc.latestResult.id : undefined) })
})
createEffect(() => {
const doc = schedules().find(row => row.id === props.selected)
// Retire the former passage selection before releasing its current-source demand.
@ -35,14 +46,17 @@ export function createMissionScheduleList(props: { instanceId: string; projectID
? doc.observation.nativeStatus ?? "unknown" : doc.observation.state}`)
const zoneOf = (doc: UnifiedMissionSchedule) => missionCriteriaZone(doc.configuration.launch)
const nextWake = (doc: UnifiedMissionSchedule) => `${t(doc.observation.kind === "check" ? "missions.scheduleList.nextCheck" : "missions.scheduleList.nextWake")} · ${date(doc.observation.nextDueAt, zoneOf(doc))}`
const entries = createMemo((): MissionPickerEntry[] => schedules().map(doc => ({ key: `scheduled:${doc.id}`,
title: doc.configuration.title,
mark: doc.id === props.selected && doc.pendingPassage?.id === props.selectedRequests?.passageID && (props.selectedRequests?.count ?? 0) > 0 ? "permission"
: doc.blockReason ? "interrupted" : doc.pendingPassage ? "working" : doc.firstPlayedAt === null && doc.state === "paused" ? "prepared"
: doc.state === "paused" ? "paused" : doc.state === "finished" ? "done" : "idle",
status: [t(`missions.scheduleList.state.${doc.state}`),
doc.id === props.selected && doc.pendingPassage?.id === props.selectedRequests?.passageID && (props.selectedRequests?.count ?? 0) > 0 ? t("missionsPanel.task.input") : "",
criteria(doc), nextWake(doc)].filter(Boolean).join(" · ") })))
const entries = createMemo((): MissionPickerEntry[] => schedules().map(doc => {
const requests = doc.id === props.selected && doc.pendingPassage?.id === props.selectedRequests?.passageID ? props.selectedRequests?.count ?? 0
: missionPassageRequests(props.instanceId, doc.pendingPassage?.coordinatorSessionID)
const held = unifiedScheduleHold(JSON.stringify([props.instanceId, props.projectID, props.directory, doc.id]))
const mark = unifiedScheduleMark(doc, requests, !doc.latestResult || scheduleSuccessSeen(seenScope(), "scheduled", doc.id, doc.latestResult.id),
!list.error() && list.fresh(doc.id) && !held)
const stateKey = missionMarkStateKey(mark)
return { key: `scheduled:${doc.id}`, title: doc.configuration.title, mark,
status: [t(stateKey ?? `missions.scheduleList.state.${doc.state}`), requests ? t("missionsPanel.task.input") : "",
criteria(doc), nextWake(doc)].filter(Boolean).join(" · ") }
}))
const refresh = () => setRevision(value => value + 1)
const publishing = () => unifiedScheduleHold(JSON.stringify([props.instanceId, props.projectID, props.directory, props.selected]))?.phase === "publication"
/** Inventory-wide notice; the directory owns the shared continuation button. */
@ -59,9 +73,15 @@ export function createMissionScheduleList(props: { instanceId: string; projectID
enabled: () => props.enabled() && !list.error() && list.fresh(id), refreshVersion: () => props.refresh + revision(), refresh,
onDeleted: () => props.onDeleted(id) })
const [expanded, expand] = createSignal(false)
const primary = () => (["pause", "resume", "play"] as const).find(action => doc().availableActions.includes(action))
const primary = () => (["pause", "resume", "play"] as const).find(action => controls.pendingAction() === action)
?? (["pause", "resume", "play"] as const).find(action => doc().availableActions.includes(action))
const action = (name: "play" | "resume" | "pause" | "stop" | "run-now") => ({ key: name, label: controls.label(name),
disabled: !controls.capable(name), onSelect: () => controls.act(name) })
disabled: !controls.capable(name), busy: controls.pendingAction() === name, onSelect: () => controls.act(name) })
const status = () => controls.progress() ?? (controls.held() ? controls.busy() ? undefined
: controls.publishing() ? "missions.scheduleList.confirmedRefreshing" : "missions.scheduleList.uncertain"
: controls.feedback() ?? (controls.refusal() ? "missions.scheduleList.activationRefused"
: controls.capability() === "missing" ? "missions.scheduling.capability.missing"
: controls.capability() === "activatable" ? "missions.scheduleList.runNowRequiresEnabled" : undefined))
const zone = () => zoneOf(doc()), model = createMemo(() => missionLaunchModel(doc().configuration.launch))
const editable = () => props.active() && props.enabled() && !list.error() && list.fresh(id)
&& !controls.held() && !controls.busy() && doc().availableActions.includes("configure")
@ -69,14 +89,17 @@ export function createMissionScheduleList(props: { instanceId: string; projectID
<MissionActionBar label={t("missionsPanel.picker.actions")} reading={props.passage?.reading ?? props.overview?.reading ?? expanded()} onToggleReader={() => props.passage ? props.passage.onToggle() : props.overview ? props.overview.onToggle() : expand(value => !value)}
primary={primary() ? action(primary()!) : undefined} stop={action("stop")} runNow={action("run-now")}
onEdit={() => { if (editable()) props.onEdit(id) }} editDisabled={!editable()}
onDelete={() => void controls.act("delete")} deleteDisabled={!controls.capable("delete")}
onDelete={() => void controls.act("delete")} deleteDisabled={!controls.capable("delete")} deleteBusy={controls.pendingAction() === "delete"}
onOpenConversation={doc().pendingPassage ? () => props.onOpenConversation(doc().pendingPassage!.coordinatorSessionID) : undefined}
secondary={<Show when={controls.held()}><button type="button" class="window-action" disabled={controls.busy()} onClick={() => void controls.reconcile()}>{t("missions.scheduling.readReceipt")}</button></Show>}
feedback={<>
<Show when={controls.held()}><p role="status">{t(controls.publishing() ? "missions.scheduleList.confirmedRefreshing" : "missions.scheduleList.uncertain")}</p></Show>
<Show when={controls.feedback()}>{key => <p role="status">{t(key())}</p>}</Show>
<Show when={controls.capability() === "missing"}><p role="status">{t("missions.scheduling.capability.missing")}</p></Show>
<Show when={controls.capability() === "activatable"}><p role="status">{t("missions.scheduleList.runNowRequiresEnabled")}</p></Show>
<p role="status">{status() ? t(status()!) : ""}</p>
<Show when={controls.refusal()}>{refusal => <>
<Show when={refusal().openable && refusal().configFileID}><button type="button" class="window-action"
onClick={() => void openSettingsConfigFile(refusal().configFileID!)}>{t("missionsPanel.action.openSchedulingSettings")}</button></Show>
<SettingsInfoTip text={`${t(refusal().layer === "environment" ? "missions.scheduleList.activationRefused.environment"
: "missions.scheduleList.activationRefused.document", { layer: t(`missions.scheduleList.activationRefused.layer.${refusal().layer}`) })}${refusal().path ? `\n${refusal().path}` : ""}`} />
</>}</Show>
</>} />
<dl class="mission-schedule-facts">
<dt>{t("missions.scheduling.when")}</dt><dd><bdi>{criteria(doc())}</bdi></dd>
@ -111,7 +134,12 @@ export function createMissionScheduleList(props: { instanceId: string; projectID
</>
const ownsSession = (sessionID: string) => schedules().some(doc => doc.id === props.selected
&& (doc.pendingPassage?.coordinatorSessionID === sessionID || doc.history.some(item => item.coordinatorSessionID === sessionID)))
const markRead = (key: string) => {
const doc = schedules().find(item => key === `scheduled:${item.id}`), result = doc?.latestResult, scope = seenScope()
return doc && result?.outcome === "completed" && !scheduleSuccessSeen(scope, "scheduled", doc.id, result.id)
? () => markScheduleSuccessSeen(scope, "scheduled", doc.id, result.id) : undefined
}
return { entries, view, listView, refresh, ownsSession, loading: list.loading,
next: list.next, more: list.more, retry: list.refresh, error: list.error,
next: list.next, more: list.more, retry: list.refresh, error: list.error, markRead,
representation: (id: string) => list.error() || list.loading() || !list.fresh(id) ? undefined : list.rows().find(row => row.id === id)?.kind }
}

View file

@ -1,5 +1,5 @@
import { Select } from "@kobalte/core/select"
import { createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense, type Component } from "solid-js"
import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense, untrack, type Component } from "solid-js"
import { ChevronDown, RefreshCw, Save } from "lucide-solid"
import type { ConfigFileDescriptor } from "../../../../server/src/api-types"
import { serverApi } from "../../lib/api-client"
@ -7,6 +7,7 @@ import { useI18n } from "../../lib/i18n"
import { showToastNotification } from "../../lib/notifications"
import { showConfirmDialog } from "../../stores/alerts"
import { registerSettingsDirtyGuard } from "../../stores/settings-dirty-guard"
import { claimSettingsRow, settingsRowTarget } from "../../stores/settings-screen"
const LazyMonacoFileViewer = lazy(() =>
import("../file-viewer/monaco-file-viewer").then((module) => ({ default: module.MonacoFileViewer })),
@ -20,10 +21,16 @@ export const ConfigFilesSettingsSection: Component = () => {
const [originalContent, setOriginalContent] = createSignal("")
const [exists, setExists] = createSignal<boolean | null>(null)
const [loadingList, setLoadingList] = createSignal(false)
const [loaded, setLoaded] = createSignal(false)
const [loadingContent, setLoadingContent] = createSignal(false)
const [saving, setSaving] = createSignal(false)
const [error, setError] = createSignal<string | null>(null)
let loadVersion = 0
let selector: HTMLButtonElement | undefined
const targetedFile = () => {
const target = settingsRowTarget()
return target?.startsWith("config-file:") ? target.slice("config-file:".length) : undefined
}
const selectedFile = createMemo(() => files().find((file) => file.id === selectedFileId()) ?? null)
const dirty = createMemo(() => content() !== originalContent())
@ -50,14 +57,16 @@ export const ConfigFilesSettingsSection: Component = () => {
}
}
const confirmDiscardIfDirty = async () => {
if (!dirty()) return true
return showConfirmDialog(t("settings.configFiles.confirmDiscard.message"), {
let discardConfirmation: Promise<boolean> | undefined
const confirmDiscardIfDirty = () => {
if (!dirty()) return Promise.resolve(true)
// A native file hint and its Preferences request share the same consent.
return discardConfirmation ??= showConfirmDialog(t("settings.configFiles.confirmDiscard.message"), {
variant: "warning",
confirmLabel: t("settings.configFiles.confirmDiscard.confirmLabel"),
cancelLabel: t("settings.configFiles.confirmDiscard.cancelLabel"),
dismissible: false,
})
}).finally(() => { discardConfirmation = undefined })
}
const loadFiles = async () => {
@ -65,11 +74,12 @@ export const ConfigFilesSettingsSection: Component = () => {
setError(null)
try {
const response = await serverApi.listConfigFiles()
setFiles(response)
const first = response[0]
const first = response.find(file => file.id === targetedFile()) ?? response[0]
if (first) {
await loadContent(first)
}
setFiles(response)
setLoaded(true)
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : t("settings.configFiles.errors.loadList"))
} finally {
@ -83,6 +93,15 @@ export const ConfigFilesSettingsSection: Component = () => {
if (!confirmed) return
await loadContent(file)
}
createEffect(() => {
const target = settingsRowTarget()
if (!target?.startsWith("config-file:") || !loaded() || loadingList()) return
const file = files().find(file => file.id === targetedFile())
untrack(() => {
if (!claimSettingsRow(target)) return
if (file) void handleFileChange(file).then(() => selector?.focus())
})
})
const handleReload = async () => {
const file = selectedFile()
@ -142,7 +161,7 @@ export const ConfigFilesSettingsSection: Component = () => {
</Select.Item>
)}
>
<Select.Trigger class="selector-trigger config-files-selector-trigger" aria-label={t("settings.configFiles.selector.label")}>
<Select.Trigger ref={selector} class="selector-trigger config-files-selector-trigger" aria-label={t("settings.configFiles.selector.label")}>
<div class="config-files-selector-value">
<Select.Value<ConfigFileDescriptor>>
{(state) => (

View file

@ -837,12 +837,13 @@ export const serverApi = {
controlMissionSchedule(instanceId: string, missionID: string, input: { action: "play" | "resume" | "pause" | "stop" | "check" | "run-now" | "delete";
requestID: string; expectedRevision: number; directory?: string; deleteManagedSessions?: boolean }): Promise<import("../../../server/src/api-types").MissionScheduleRead> {
return request(`/api/workspaces/${encodeURIComponent(instanceId)}/missions/${encodeURIComponent(missionID)}/schedule`, {
method: "POST", body: JSON.stringify(input) })
method: "POST", body: JSON.stringify(input), signal: AbortSignal.timeout(30_000) })
},
missionScheduleSettings(instanceId: string, missionID: string, input: { requestID: string; expectedDocumentRevision: number }, apply = false): Promise<{ document: import("../../../server/src/missions/mission-document-one-time").MissionDocumentSummary }> {
const url = `/api/workspaces/${encodeURIComponent(instanceId)}/missions/${encodeURIComponent(missionID)}/schedule-settings`
return apply ? request(url, { method: "POST", body: JSON.stringify(input) })
: secondaryRead(undefined, () => request(`${url}?${new URLSearchParams({ requestID: input.requestID, expectedDocumentRevision: String(input.expectedDocumentRevision) })}`))
const signal = AbortSignal.timeout(30_000)
return apply ? request(url, { method: "POST", body: JSON.stringify(input), signal })
: secondaryRead(signal, () => request(`${url}?${new URLSearchParams({ requestID: input.requestID, expectedDocumentRevision: String(input.expectedDocumentRevision) })}`, { signal }))
},
/** The same read, with the full map, from the authoritative full snapshot, for admitting an application-authored prompt. */
fetchMissionAdmission(instanceId: string, missionId: string): Promise<MissionReadResponse<MissionMap>> {

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Zu viele unbestätigte Befehle. Klären Sie eine gespeicherte Anfrage vor der nächsten.",
"missions.scheduleList.uncertain": "Diese Anfrage ist unbestätigt. Ihre ursprüngliche Identität bleibt erhalten. Gespeicherte Anfrage aktualisieren; kein automatisches erneutes Senden.",
"missions.scheduleList.confirmedRefreshing": "Aktion bestätigt. Vor einer weiteren Aktion wird auf die aktualisierte Ansicht gewartet. Verwenden Sie Gespeicherte Anfrage aktualisieren zum erneuten Lesen.",
"missions.scheduleList.activate": "Diese Aktion erfordert native Zeitplanung. experimental.schedules in diesen Konfigurationsdokumenten aktivieren?\n{paths}\nDie Aktivierung muss vor dieser Aktion bestätigt werden. Ein ausdrückliches OFF bleibt erhalten.",
"missionsPanel.action.openSchedulingSettings": "Zeitplanungseinstellungen öffnen",
"missions.scheduleList.activationRefused": "Die Zeitplanung ist in den OpenCode-Einstellungen deaktiviert.",
"missions.scheduleList.activationRefused.environment": "Die Umgebung des OpenCode-Dienstes deaktiviert experimental.schedules. Ändern Sie diese Umgebung und aktualisieren Sie anschließend.",
"missions.scheduleList.activationRefused.document": "{layer}: Diese Konfiguration blockiert experimental.schedules. Prüfen Sie sie und aktualisieren Sie anschließend.",
"missions.scheduleList.confirm.stop": "„{title}“ endgültig stoppen? Künftige Durchläufe werden deaktiviert. Bereits ausgelöste Werkzeugeffekte können weiterlaufen; Gespräche und Ergebnisse bleiben erhalten.",
"missions.scheduleList.confirm.delete": "„{title}“ löschen? Künftige Durchläufe werden vor dem Entfernen deaktiviert. Gespräche und Ergebnisse bleiben erhalten. Unbestätigte Bereinigung bleibt sichtbar.",
"missions.scheduleList.confirm.run-now": "„{title}“ jetzt ausführen? Seine Zeitpläne behalten ihre Termine. Ein ungeklärter Durchlauf verhindert Überschneidungen.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "Wählen Sie eine verfügbare Projektquelle oder gültige explizite Dateipfade.",
"missions.scheduling.error.empty": "Dieser Kalender hat keinen zukünftigen Termin.",
"missions.scheduling.error.capability": "Zeitplanung ist nicht verfügbar. Behalten Sie den Entwurf oder entfernen Sie die Startkriterien.",
"missions.scheduleList.activationRefused.layer.project": "Projektkonfiguration",
"missions.scheduleList.activationRefused.layer.global": "Globale Konfiguration",
"missions.scheduleList.activationRefused.layer.inherited": "Geerbte Konfiguration",
"missions.scheduleList.activationRefused.layer.imposed": "Vorgegebene Konfiguration",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Wird gestartet…",
"missionsPanel.action.resuming": "Wird fortgesetzt…",
"missionsPanel.action.runningNow": "Durchlauf wird gestartet…",
"missionsPanel.pages.raw": "JSON-Rohdaten seitenweise lesen",
"missionsPanel.pages.rawPage": "JSON-Rohdatenseite {page} von {total}",
"missionsPanel.pages.previous": "Vorherige Seite",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "Zeitplan-ID",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "In Arbeit",
"missionsPanel.state.waiting": "Wartet auf geplanten Durchlauf",
"missionsPanel.state.unreadSuccess": "Erfolgreicher Durchlauf zum Ansehen",
"missionsPanel.state.unconfirmed": "Status unbestätigt",
"missionsPanel.state.interrupted": "Unterbrochen",
"missionsPanel.run.completed": "Abgeschlossen",
"missionsPanel.run.failed": "Fehlgeschlagen",

View file

@ -81,7 +81,14 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Too many unconfirmed commands. Resolve a saved request before sending another.",
"missions.scheduleList.uncertain": "This request is unconfirmed. Its original identity is kept. Refresh the saved request; nothing is resent automatically.",
"missions.scheduleList.confirmedRefreshing": "Action confirmed. Waiting for the updated view before another action. Use Refresh saved request to retry the read.",
"missions.scheduleList.activate": "This action requires native scheduling. Enable experimental.schedules in these configuration documents?\n{paths}\nActivation must be confirmed before this action proceeds. An explicit OFF is preserved.",
"missionsPanel.action.openSchedulingSettings": "Open scheduling settings",
"missions.scheduleList.activationRefused": "Scheduling is disabled in OpenCode settings.",
"missions.scheduleList.activationRefused.environment": "The OpenCode service environment disables experimental.schedules. Update that environment, then refresh.",
"missions.scheduleList.activationRefused.document": "{layer}: this configuration blocks experimental.schedules. Review it, then refresh.",
"missions.scheduleList.activationRefused.layer.project": "Project configuration",
"missions.scheduleList.activationRefused.layer.global": "Global configuration",
"missions.scheduleList.activationRefused.layer.inherited": "Inherited configuration",
"missions.scheduleList.activationRefused.layer.imposed": "Imposed configuration",
"missions.scheduleList.confirm.stop": "Stop “{title}” permanently? Future passages are disabled. Engaged tool effects may continue; conversations and results are kept.",
"missions.scheduleList.confirm.delete": "Delete “{title}”? Future passages are disabled before removal. Conversations and results are kept. Unconfirmed cleanup remains visible.",
"missions.scheduleList.confirm.run-now": "Run “{title}” now? Its schedules keep their slots. An unresolved passage blocks overlap.",

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Starting…",
"missionsPanel.action.resuming": "Resuming…",
"missionsPanel.action.runningNow": "Starting run…",
"missionsPanel.pages.raw": "Read raw JSON pages",
"missionsPanel.pages.rawPage": "Raw JSON page {page} of {total}",
"missionsPanel.pages.previous": "Previous page",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "Schedule ID",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "In progress",
"missionsPanel.state.waiting": "Waiting for scheduled run",
"missionsPanel.state.unreadSuccess": "Successful run to review",
"missionsPanel.state.unconfirmed": "State unconfirmed",
"missionsPanel.state.interrupted": "Interrupted",
"missionsPanel.run.completed": "Completed",
"missionsPanel.run.failed": "Failed",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Demasiados comandos sin confirmar. Resuelve una solicitud guardada antes de enviar otra.",
"missions.scheduleList.uncertain": "Esta solicitud no está confirmada. Se conserva su identidad original. Actualiza la solicitud guardada; no se reenvía automáticamente.",
"missions.scheduleList.confirmedRefreshing": "Acción confirmada. Esperando la vista actualizada antes de otra acción. Usa Actualizar la solicitud guardada para volver a leer.",
"missions.scheduleList.activate": "Esta acción requiere programación nativa. ¿Activar experimental.schedules en estos documentos de configuración?\n{paths}\nLa activación debe confirmarse antes de continuar. Se conserva un OFF explícito.",
"missionsPanel.action.openSchedulingSettings": "Abrir los ajustes de programación",
"missions.scheduleList.activationRefused": "La programación está desactivada en los ajustes de OpenCode.",
"missions.scheduleList.activationRefused.environment": "El entorno del servicio OpenCode desactiva experimental.schedules. Modifica ese entorno y actualiza.",
"missions.scheduleList.activationRefused.document": "{layer}: esta configuración bloquea experimental.schedules. Revísala y actualiza.",
"missions.scheduleList.confirm.stop": "¿Detener «{title}» definitivamente? Se desactivan las futuras pasadas. Los efectos de herramientas iniciados pueden continuar; se conservan conversaciones y resultados.",
"missions.scheduleList.confirm.delete": "¿Eliminar «{title}»? Se desactivan futuras pasadas antes de retirarla. Se conservan conversaciones y resultados. La limpieza sin confirmar sigue visible.",
"missions.scheduleList.confirm.run-now": "¿Ejecutar «{title}» ahora? Sus horarios conservan sus franjas. Un pase sin resolver impide el solapamiento.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "Elija una fuente disponible del proyecto o rutas explícitas válidas.",
"missions.scheduling.error.empty": "Este calendario no tiene ningún horario futuro.",
"missions.scheduling.error.capability": "La programación no está disponible. Conserve el borrador o quite los criterios de lanzamiento.",
"missions.scheduleList.activationRefused.layer.project": "Configuración del proyecto",
"missions.scheduleList.activationRefused.layer.global": "Configuración global",
"missions.scheduleList.activationRefused.layer.inherited": "Configuración heredada",
"missions.scheduleList.activationRefused.layer.imposed": "Configuración impuesta",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Iniciando…",
"missionsPanel.action.resuming": "Reanudando…",
"missionsPanel.action.runningNow": "Iniciando ejecución…",
"missionsPanel.pages.raw": "Leer páginas de JSON sin procesar",
"missionsPanel.pages.rawPage": "Página de JSON sin procesar {page} de {total}",
"missionsPanel.pages.previous": "Página anterior",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "ID de programación",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "En curso",
"missionsPanel.state.waiting": "Esperando ejecución programada",
"missionsPanel.state.unreadSuccess": "Ejecución correcta por revisar",
"missionsPanel.state.unconfirmed": "Estado sin confirmar",
"missionsPanel.state.interrupted": "Interrumpida",
"missionsPanel.run.completed": "Completada",
"missionsPanel.run.failed": "Fallida",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Trop de commandes non confirmées. Résolvez une requête enregistrée avant d’en envoyer une autre.",
"missions.scheduleList.uncertain": "Cette requête reste non confirmée. Son identité d’origine est conservée. Actualisez la requête enregistrée ; aucun renvoi automatique.",
"missions.scheduleList.confirmedRefreshing": "Action confirmée. En attente de la vue actualisée avant une autre action. Utilisez Actualiser la requête enregistrée pour relire.",
"missions.scheduleList.activate": "Cette action nécessite la programmation native. Activer experimental.schedules dans ces documents de configuration ?\n{paths}\nL’activation doit être confirmée avant de poursuivre cette action. Un OFF explicite est conservé.",
"missionsPanel.action.openSchedulingSettings": "Ouvrir les réglages de programmation",
"missions.scheduleList.activationRefused": "La programmation est désactivée dans les réglages OpenCode.",
"missions.scheduleList.activationRefused.environment": "L’environnement du service OpenCode désactive experimental.schedules. Modifiez cet environnement, puis actualisez.",
"missions.scheduleList.activationRefused.document": "{layer} : cette configuration bloque experimental.schedules. Vérifiez-la, puis actualisez.",
"missions.scheduleList.confirm.stop": "Arrêter définitivement « {title} » ? Les futurs passages sont désactivés. Les effets d’outils engagés peuvent continuer ; conversations et résultats sont conservés.",
"missions.scheduleList.confirm.delete": "Supprimer « {title} » ? Les futurs passages sont désactivés avant le retrait. Conversations et résultats sont conservés. Le nettoyage non confirmé reste visible.",
"missions.scheduleList.confirm.run-now": "Exécuter « {title} » maintenant ? Ses horaires conservent leurs créneaux. Un passage non résolu empêche le chevauchement.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "Choisissez une source disponible du projet ou des chemins de fichiers explicites valides.",
"missions.scheduling.error.empty": "Ce calendrier n’a aucun créneau à venir.",
"missions.scheduling.error.capability": "Programmation indisponible. Conservez le brouillon ou retirez les critères de lancement.",
"missions.scheduleList.activationRefused.layer.project": "Configuration du projet",
"missions.scheduleList.activationRefused.layer.global": "Configuration globale",
"missions.scheduleList.activationRefused.layer.inherited": "Configuration héritée",
"missions.scheduleList.activationRefused.layer.imposed": "Configuration imposée",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Démarrage…",
"missionsPanel.action.resuming": "Reprise…",
"missionsPanel.action.runningNow": "Lancement du passage…",
"missionsPanel.pages.raw": "Lire les pages JSON brutes",
"missionsPanel.pages.rawPage": "Page JSON brute {page} sur {total}",
"missionsPanel.pages.previous": "Page précédente",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "ID de planification",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "En cours",
"missionsPanel.state.waiting": "En attente programmée",
"missionsPanel.state.unreadSuccess": "Passage réussi à consulter",
"missionsPanel.state.unconfirmed": "État non confirmé",
"missionsPanel.state.interrupted": "Interrompue",
"missionsPanel.run.completed": "Terminée",
"missionsPanel.run.failed": "Échec",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "יותר מדי פקודות לא מאושרות. יש להסדיר בקשה שמורה לפני שליחת בקשה נוספת.",
"missions.scheduleList.uncertain": "הבקשה אינה מאושרת. הזהות המקורית נשמרת. יש לרענן את הבקשה השמורה; דבר לא נשלח שוב אוטומטית.",
"missions.scheduleList.confirmedRefreshing": "הפעולה אושרה. ממתינים לתצוגה המעודכנת לפני פעולה נוספת. השתמשו ברענון הבקשה השמורה לקריאה חוזרת.",
"missions.scheduleList.activate": "פעולה זו דורשת תזמון מקורי. להפעיל experimental.schedules במסמכי התצורה הבאים?\n{paths}\nנדרש אישור ההפעלה לפני המשך הפעולה. מצב OFF מפורש נשמר.",
"missionsPanel.action.openSchedulingSettings": "פתיחת הגדרות התזמון",
"missions.scheduleList.activationRefused": "התזמון מושבת בהגדרות OpenCode.",
"missions.scheduleList.activationRefused.environment": "סביבת השירות של OpenCode משביתה את experimental.schedules. יש לעדכן את הסביבה ואז לרענן.",
"missions.scheduleList.activationRefused.document": "{layer}: תצורה זו חוסמת את experimental.schedules. יש לבדוק אותה ואז לרענן.",
"missions.scheduleList.confirm.stop": "לעצור את ״{title}״ לצמיתות? הרצות עתידיות יושבתו. השפעות כלים שכבר החלו עשויות להמשיך; שיחות ותוצאות נשמרות.",
"missions.scheduleList.confirm.delete": "למחוק את ״{title}״? הרצות עתידיות יושבתו לפני ההסרה. שיחות ותוצאות נשמרות. ניקוי שלא אושר נשאר גלוי.",
"missions.scheduleList.confirm.run-now": "להריץ את „{title}” עכשיו? התזמונים שלה שומרים על המועדים. מעבר שלא נפתר חוסם חפיפה.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "יש לבחור מקור זמין בפרויקט או נתיבי קבצים מפורשים תקינים.",
"missions.scheduling.error.empty": "ללוח הזה אין מועד עתידי.",
"missions.scheduling.error.capability": "התזמון אינו זמין. שמרו את הטיוטה או הסירו את קריטריוני ההפעלה.",
"missions.scheduleList.activationRefused.layer.project": "הגדרות הפרויקט",
"missions.scheduleList.activationRefused.layer.global": "הגדרות כלליות",
"missions.scheduleList.activationRefused.layer.inherited": "הגדרות בירושה",
"missions.scheduleList.activationRefused.layer.imposed": "הגדרות כפויות",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "מתחיל…",
"missionsPanel.action.resuming": "ממשיך…",
"missionsPanel.action.runningNow": "מתחיל הרצה…",
"missionsPanel.pages.raw": "קריאת דפי JSON גולמיים",
"missionsPanel.pages.rawPage": "דף JSON גולמי {page} מתוך {total}",
"missionsPanel.pages.previous": "הדף הקודם",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "מזהה תזמון",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "בתהליך",
"missionsPanel.state.waiting": "בהמתנה להרצה מתוזמנת",
"missionsPanel.state.unreadSuccess": "הרצה שהצליחה וממתינה לעיון",
"missionsPanel.state.unconfirmed": "מצב לא מאומת",
"missionsPanel.state.interrupted": "נקטעה",
"missionsPanel.run.completed": "הושלמה",
"missionsPanel.run.failed": "נכשלה",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "未確認のコマンドが多すぎます。保存済みのリクエストを解決してから送信してください。",
"missions.scheduleList.uncertain": "リクエストは未確認です。元の識別情報を保持しています。保存済みのリクエストを更新してください。自動再送は行いません。",
"missions.scheduleList.confirmedRefreshing": "操作は確認済みです。次の操作の前に最新表示を待っています。「保存済みリクエストを更新」で読み取りをやり直してください。",
"missions.scheduleList.activate": "この操作にはネイティブスケジュールが必要です。次の設定文書でexperimental.schedulesを有効にしますか?\n{paths}\n操作を続ける前に有効化の確認が必要です。明示的なOFFは保持されます。",
"missionsPanel.action.openSchedulingSettings": "スケジュール設定を開く",
"missions.scheduleList.activationRefused": "OpenCodeの設定でスケジュールが無効になっています。",
"missions.scheduleList.activationRefused.environment": "OpenCodeサービスの環境でexperimental.schedulesが無効になっています。環境を変更してから更新してください。",
"missions.scheduleList.activationRefused.document": "{layer}: この設定がexperimental.schedulesをブロックしています。確認してから更新してください。",
"missions.scheduleList.confirm.stop": "「{title}」を完全に停止しますか?今後の実行を無効にします。開始済みツールの影響は続く場合があります。会話と結果は保持されます。",
"missions.scheduleList.confirm.delete": "「{title}」を削除しますか?削除前に今後の実行を無効にします。会話と結果は保持されます。未確認の後処理は表示され続けます。",
"missions.scheduleList.confirm.run-now": "「{title}」を今すぐ実行しますか?スケジュールのスロットは維持されます。未解決のパッセージがあると重複は防止されます。",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "利用可能なプロジェクトの対象、または有効な明示的ファイルパスを選択してください。",
"missions.scheduling.error.empty": "この暦には将来の予定がありません。",
"missions.scheduling.error.capability": "スケジュールを利用できません。下書きを保持するか、起動条件を削除してください。",
"missions.scheduleList.activationRefused.layer.project": "プロジェクト設定",
"missions.scheduleList.activationRefused.layer.global": "グローバル設定",
"missions.scheduleList.activationRefused.layer.inherited": "継承された設定",
"missions.scheduleList.activationRefused.layer.imposed": "強制された設定",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "開始中…",
"missionsPanel.action.resuming": "再開中…",
"missionsPanel.action.runningNow": "実行を開始中…",
"missionsPanel.pages.raw": "生のJSONをページ単位で読む",
"missionsPanel.pages.rawPage": "生のJSON:{page} / {total} ページ",
"missionsPanel.pages.previous": "前のページ",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "スケジュール ID",
"missionsPanel.schedule.zoned": "{time}({zone})",
"missionsPanel.state.inProgress": "進行中",
"missionsPanel.state.waiting": "スケジュール実行を待機中",
"missionsPanel.state.unreadSuccess": "成功した実行を確認",
"missionsPanel.state.unconfirmed": "状態未確認",
"missionsPanel.state.interrupted": "中断",
"missionsPanel.run.completed": "完了",
"missionsPanel.run.failed": "失敗",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "धेरै आदेश अपुष्ट छन्। अर्को पठाउनुअघि सुरक्षित अनुरोध समाधान गर्नुहोस्।",
"missions.scheduleList.uncertain": "यो अनुरोध अपुष्ट छ। यसको मूल पहिचान राखिएको छ। सुरक्षित अनुरोध ताजा गर्नुहोस्; स्वतः फेरि पठाइँदैन।",
"missions.scheduleList.confirmedRefreshing": "कार्य पुष्टि भयो। अर्को कार्यअघि ताजा दृश्य पर्खिँदै छ। फेरि पढ्न सुरक्षित अनुरोध ताजा गर्नुहोस् प्रयोग गर्नुहोस्।",
"missions.scheduleList.activate": "यो कार्यका लागि मूल तालिका आवश्यक छ। यी कन्फिगरेसन कागजातमा experimental.schedules सक्रिय गर्ने?\n{paths}\nकार्य अघि बढाउनुअघि सक्रियता पुष्टि हुनुपर्छ। स्पष्ट OFF कायम रहन्छ।",
"missionsPanel.action.openSchedulingSettings": "समयतालिकाका सेटिङ खोल्नुहोस्",
"missions.scheduleList.activationRefused": "OpenCode सेटिङमा समयतालिका निष्क्रिय छ।",
"missions.scheduleList.activationRefused.environment": "OpenCode सेवाको वातावरणले experimental.schedules निष्क्रिय पारेको छ। त्यो वातावरण परिवर्तन गरेर ताजा गर्नुहोस्।",
"missions.scheduleList.activationRefused.document": "{layer}: यो कन्फिगरेसनले experimental.schedules रोक्छ। जाँच गरेर ताजा गर्नुहोस्।",
"missions.scheduleList.confirm.stop": "“{title}” स्थायी रूपमा रोक्ने? भावी चरणहरू निष्क्रिय हुन्छन्। सुरु भइसकेका उपकरण प्रभाव चलिरहन सक्छन्; संवाद र परिणाम सुरक्षित रहन्छन्।",
"missions.scheduleList.confirm.delete": "“{title}” मेटाउने? हटाउनुअघि भावी चरण निष्क्रिय गरिन्छन्। संवाद र परिणाम सुरक्षित रहन्छन्। अपुष्ट सफाइ देखिइरहन्छ।",
"missions.scheduleList.confirm.run-now": "“{title}” अहिले चलाउने? यसका समयतालिकाले आफ्ना स्लट राख्छन्। समाधान नभएको पासले ओभरल्याप रोक्छ।",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "उपलब्ध परियोजना स्रोत वा मान्य तोकिएका फाइल पथ छान्नुहोस्।",
"missions.scheduling.error.empty": "यो पात्रोमा भविष्यको कुनै समय छैन।",
"missions.scheduling.error.capability": "समयतालिका उपलब्ध छैन। मस्यौदा राख्नुहोस् वा सुरु गर्ने मापदण्डहरू हटाउनुहोस्।",
"missions.scheduleList.activationRefused.layer.project": "परियोजना कन्फिगरेसन",
"missions.scheduleList.activationRefused.layer.global": "विश्वव्यापी कन्फिगरेसन",
"missions.scheduleList.activationRefused.layer.inherited": "विरासतमा प्राप्त कन्फिगरेसन",
"missions.scheduleList.activationRefused.layer.imposed": "अनिवार्य कन्फिगरेसन",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "सुरु हुँदैछ…",
"missionsPanel.action.resuming": "पुनः सुरु हुँदैछ…",
"missionsPanel.action.runningNow": "चक्र सुरु हुँदैछ…",
"missionsPanel.pages.raw": "कच्चा JSON पृष्ठहरू पढ्नुहोस्",
"missionsPanel.pages.rawPage": "कच्चा JSON पृष्ठ {page}, जम्मा {total}",
"missionsPanel.pages.previous": "अघिल्लो पृष्ठ",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "तालिका ID",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "प्रगतिमा",
"missionsPanel.state.waiting": "निर्धारित सञ्चालनको प्रतीक्षामा",
"missionsPanel.state.unreadSuccess": "समीक्षा गर्न बाँकी सफल सञ्चालन",
"missionsPanel.state.unconfirmed": "स्थिति पुष्टि भएको छैन",
"missionsPanel.state.interrupted": "अवरुद्ध",
"missionsPanel.run.completed": "सम्पन्न",
"missionsPanel.run.failed": "असफल",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Слишком много неподтверждённых команд. Разрешите сохранённый запрос перед новым.",
"missions.scheduleList.uncertain": "Запрос не подтверждён. Исходная идентичность сохранена. Обновите сохранённый запрос; автоматической повторной отправки нет.",
"missions.scheduleList.confirmedRefreshing": "Действие подтверждено. Ожидается обновлённое представление перед следующим действием. Используйте Обновить сохранённый запрос для повторного чтения.",
"missions.scheduleList.activate": "Для этого действия нужно нативное расписание. Включить experimental.schedules в этих файлах конфигурации?\n{paths}\nПеред продолжением требуется подтверждение активации. Явное OFF сохраняется.",
"missionsPanel.action.openSchedulingSettings": "Открыть настройки расписания",
"missions.scheduleList.activationRefused": "Расписание отключено в настройках OpenCode.",
"missions.scheduleList.activationRefused.environment": "Окружение службы OpenCode отключает experimental.schedules. Измените окружение и обновите данные.",
"missions.scheduleList.activationRefused.document": "{layer}: эта конфигурация блокирует experimental.schedules. Проверьте её и обновите данные.",
"missions.scheduleList.confirm.stop": "Остановить «{title}» окончательно? Будущие проходы отключаются. Уже начатые эффекты инструментов могут продолжаться; разговоры и результаты сохраняются.",
"missions.scheduleList.confirm.delete": "Удалить «{title}»? Будущие проходы отключаются до удаления из списка. Разговоры и результаты сохраняются. Неподтверждённая очистка остаётся видимой.",
"missions.scheduleList.confirm.run-now": "Запустить «{title}» сейчас? Его расписания сохраняют свои слоты. Неразрешённый проход блокирует наложение.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "Выберите доступный источник проекта или корректные явные пути файлов.",
"missions.scheduling.error.empty": "У этого календаря нет будущего времени.",
"missions.scheduling.error.capability": "Планирование недоступно. Сохраните черновик или удалите критерии запуска.",
"missions.scheduleList.activationRefused.layer.project": "Конфигурация проекта",
"missions.scheduleList.activationRefused.layer.global": "Глобальная конфигурация",
"missions.scheduleList.activationRefused.layer.inherited": "Унаследованная конфигурация",
"missions.scheduleList.activationRefused.layer.imposed": "Принудительная конфигурация",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Запуск…",
"missionsPanel.action.resuming": "Возобновление…",
"missionsPanel.action.runningNow": "Запуск прохода…",
"missionsPanel.pages.raw": "Читать исходный JSON по страницам",
"missionsPanel.pages.rawPage": "Страница исходного JSON {page} из {total}",
"missionsPanel.pages.previous": "Предыдущая страница",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "ID расписания",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "Выполняется",
"missionsPanel.state.waiting": "Ожидание запуска по расписанию",
"missionsPanel.state.unreadSuccess": "Успешный запуск для просмотра",
"missionsPanel.state.unconfirmed": "Состояние не подтверждено",
"missionsPanel.state.interrupted": "Прервана",
"missionsPanel.run.completed": "Завершено",
"missionsPanel.run.failed": "Сбой",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "Çok fazla onaylanmamış komut var. Yenisini göndermeden önce kayıtlı bir isteği çözün.",
"missions.scheduleList.uncertain": "Bu istek onaylanmadı. Özgün kimliği korunuyor. Kayıtlı isteği yenileyin; otomatik yeniden gönderim yapılmaz.",
"missions.scheduleList.confirmedRefreshing": "Eylem doğrulandı. Başka bir eylemden önce güncel görünüm bekleniyor. Yeniden okumak için Kayıtlı isteği yenile kullanın.",
"missions.scheduleList.activate": "Bu işlem yerel zamanlama gerektirir. Bu yapılandırma belgelerinde experimental.schedules etkinleştirilsin mi?\n{paths}\nİşlem sürmeden önce etkinleştirme onaylanmalıdır. Açık OFF korunur.",
"missionsPanel.action.openSchedulingSettings": "Zamanlama ayarlarını aç",
"missions.scheduleList.activationRefused": "OpenCode ayarlarında zamanlama devre dışı.",
"missions.scheduleList.activationRefused.environment": "OpenCode hizmet ortamı experimental.schedules özelliğini devre dışı bırakıyor. Ortamı güncelleyip yenileyin.",
"missions.scheduleList.activationRefused.document": "{layer}: bu yapılandırma experimental.schedules özelliğini engelliyor. İnceleyip yenileyin.",
"missions.scheduleList.confirm.stop": "“{title}” kalıcı olarak durdurulsun mu? Gelecek geçişler devre dışı bırakılır. Başlatılmış araç etkileri sürebilir; konuşmalar ve sonuçlar korunur.",
"missions.scheduleList.confirm.delete": "“{title}” silinsin mi? Kaldırmadan önce gelecek geçişler devre dışı bırakılır. Konuşmalar ve sonuçlar korunur. Onaysız temizlik görünür kalır.",
"missions.scheduleList.confirm.run-now": "“{title}” şimdi çalıştırılsın mı? Zamanlamaları dilimlerini korur. Çözülmemiş bir geçiş çakışmayı engeller.",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "Kullanılabilir proje kaynağı veya geçerli açık dosya yolları seçin.",
"missions.scheduling.error.empty": "Bu takvimde gelecekte zaman yok.",
"missions.scheduling.error.capability": "Zamanlama kullanılamıyor. Taslağı koruyun veya başlatma ölçütlerini kaldırın.",
"missions.scheduleList.activationRefused.layer.project": "Proje yapılandırması",
"missions.scheduleList.activationRefused.layer.global": "Genel yapılandırma",
"missions.scheduleList.activationRefused.layer.inherited": "Devralınan yapılandırma",
"missions.scheduleList.activationRefused.layer.imposed": "Zorunlu yapılandırma",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "Başlatılıyor…",
"missionsPanel.action.resuming": "Sürdürülüyor…",
"missionsPanel.action.runningNow": "Geçiş başlatılıyor…",
"missionsPanel.pages.raw": "Ham JSON sayfalarını oku",
"missionsPanel.pages.rawPage": "Ham JSON sayfası {page} / {total}",
"missionsPanel.pages.previous": "Önceki sayfa",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "Zamanlama kimliği",
"missionsPanel.schedule.zoned": "{time} ({zone})",
"missionsPanel.state.inProgress": "Sürüyor",
"missionsPanel.state.waiting": "Zamanlanmış çalıştırma bekleniyor",
"missionsPanel.state.unreadSuccess": "İncelenecek başarılı çalıştırma",
"missionsPanel.state.unconfirmed": "Durum doğrulanmadı",
"missionsPanel.state.interrupted": "Kesintiye uğradı",
"missionsPanel.run.completed": "Tamamlandı",
"missionsPanel.run.failed": "Başarısız",

View file

@ -81,7 +81,10 @@ export const missionSchedulingMessages = {
"missions.scheduleList.capacity": "未确认的命令过多。请先解决一条已保存的请求,再发送新请求。",
"missions.scheduleList.uncertain": "此请求尚未确认,已保留原始身份。请刷新已保存的请求;不会自动重新发送。",
"missions.scheduleList.confirmedRefreshing": "操作已确认。等待更新后的视图才能进行其他操作。请使用“刷新已保存的请求”重新读取。",
"missions.scheduleList.activate": "此操作需要原生计划功能。是否在以下配置文件中启用 experimental.schedules?\n{paths}\n确认启用后才会继续此操作。明确的 OFF 设置会保留。",
"missionsPanel.action.openSchedulingSettings": "打开计划设置",
"missions.scheduleList.activationRefused": "OpenCode 设置已禁用计划功能。",
"missions.scheduleList.activationRefused.environment": "OpenCode 服务环境禁用了 experimental.schedules。请修改该环境,然后刷新。",
"missions.scheduleList.activationRefused.document": "{layer}:此配置阻止了 experimental.schedules。请检查后刷新。",
"missions.scheduleList.confirm.stop": "永久停止“{title}”?后续轮次将被禁用。已开始的工具效果可能继续;对话和结果会保留。",
"missions.scheduleList.confirm.delete": "删除“{title}”?移除前会禁用后续轮次。对话和结果会保留。未确认的清理仍然可见。",
"missions.scheduleList.confirm.run-now": "立即运行“{title}”?其计划保留原有时段。未解决的执行会阻止重叠。",
@ -174,4 +177,8 @@ export const missionSchedulingMessages = {
"missions.scheduling.error.source": "请选择可用的项目来源或有效的指定文件路径。",
"missions.scheduling.error.empty": "此日历没有未来时段。",
"missions.scheduling.error.capability": "计划不可用。请保留草稿或移除启动条件。",
"missions.scheduleList.activationRefused.layer.project": "项目配置",
"missions.scheduleList.activationRefused.layer.global": "全局配置",
"missions.scheduleList.activationRefused.layer.inherited": "继承的配置",
"missions.scheduleList.activationRefused.layer.imposed": "强制配置",
}

View file

@ -1,4 +1,7 @@
export const missionsPanelMessages = {
"missionsPanel.action.starting": "正在启动…",
"missionsPanel.action.resuming": "正在恢复…",
"missionsPanel.action.runningNow": "正在启动本次运行…",
"missionsPanel.pages.raw": "分页读取原始 JSON",
"missionsPanel.pages.rawPage": "原始 JSON 第 {page} 页,共 {total} 页",
"missionsPanel.pages.previous": "上一页",
@ -41,6 +44,9 @@ export const missionsPanelMessages = {
"missionsPanel.technical.schedule": "计划 ID",
"missionsPanel.schedule.zoned": "{time}({zone})",
"missionsPanel.state.inProgress": "进行中",
"missionsPanel.state.waiting": "等待计划运行",
"missionsPanel.state.unreadSuccess": "成功运行待查看",
"missionsPanel.state.unconfirmed": "状态未确认",
"missionsPanel.state.interrupted": "已中断",
"missionsPanel.run.completed": "已完成",
"missionsPanel.run.failed": "失败",

View file

@ -66,6 +66,8 @@ const key = (id = selected.id, project = "project", directory = "/repo") => JSON
function setup(retain: boolean | "preserve" = true, list?: () => Promise<MissionScheduleList>) {
if (retain !== "preserve") holds.clear()
fixture.enabled = true
fixture.settings = async (_instance, _id, input) => ({ document: { revision: input.expectedDocumentRevision,
scheduleActivation: { requestID: input.requestID, expectedRevision: input.expectedDocumentRevision, state: "ready" } } })
const hold = { phase: "control" as const, action: "play" as const, requestID: "original_request", expectedRevision: 7, partial: true, document: selected }
if (retain === true) {
holds.set(key(), hold)
@ -224,7 +226,8 @@ const confirmed = (hold: Pick<ReturnType<typeof setup>["hold"], "action" | "requ
test("a native pre-write refusal releases only the matching UI control and keeps Stop available", async () => {
for (const exact of [true, false]) {
const h = setup(false), c = controlsFor(h), doc = { ...selected, availableActions: ["play", "stop"] as typeof selected.availableActions }
const h = setup(false), c = controlsFor(h), doc = { ...selected, availableActions: ["play", "stop"] as typeof selected.availableActions,
scheduleActivation: { requestID: "ready_receipt", expectedRevision: 0, state: "ready" as const, authority: "a".repeat(64), targets: [], effectiveOrigin: null } }
try {
fixture.detail = async () => ({ pending: false, document: doc })
await until(() => h.store.fresh(selected.id) && c.controls()?.capability() === "available")

View file

@ -16,7 +16,8 @@ Object.assign(globalThis, { window: {
} })
const { initializeClientState } = await import("./client-state")
await initializeClientState()
const { markMissionsFinishedSeen, seedMissionFinishedSeen, missionDisclosureOpen, missionFinishedSeen, missionProjectView, setMissionDisclosureOpen, updateMissionProjectView } = await import("./mission-view-state")
const { markMissionsFinishedSeen, seedMissionFinishedSeen, missionDisclosureOpen, missionFinishedSeen, missionProjectView, setMissionDisclosureOpen, updateMissionProjectView,
markScheduleSuccessSeen, scheduleSuccessSeen, seedScheduleSuccessSeen } = await import("./mission-view-state")
const playbookReader = { missionId: "debug", kind: "playbook", taskMode: "independent" } as const
// The completions a project lists at the end, with whether each reads as seen.
@ -75,6 +76,12 @@ async function projectControls() {
}
if (reload) {
if (process.env.MISSION_PASSAGE_CHECK) test("exact passage acknowledgement survives reload without acknowledging a replacement", () => {
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "A"), true)
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "B"), true)
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "C"), false)
assert.equal(scheduleSuccessSeen("passages", "scheduled", "schedule", "B"), false)
})
if (process.env.MISSION_COLLISION_CHECK) test("legacy collision positives survive reload before the originally viewed row is discovered", () => {
const { folder, scope, rows } = JSON.parse(process.env.MISSION_COLLISION_CHECK!)
assert.deepEqual(rows.map((row: ReturnType<typeof completion>) => missionFinishedSeen(scope, row)), [true, false, true, true])
@ -107,6 +114,24 @@ if (reload) {
assert.equal(missionProjectView("unknown-playbook").reader, undefined)
})
} else {
test("schedule success uses exact passage identity, initial history, ownership and captured acknowledgement", () => {
seedScheduleSuccessSeen("passages", "daily", "schedule", "A")
seedScheduleSuccessSeen("passages", "scheduled", "schedule")
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "A"), true, "historical success on first load is already seen")
seedScheduleSuccessSeen("passages", "daily", "schedule", "B")
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "B"), false, "refresh never reseeds")
const lateA = () => markScheduleSuccessSeen("passages", "daily", "schedule", "A")
lateA()
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "B"), false)
markScheduleSuccessSeen("passages", "daily", "schedule", "B")
lateA()
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "B"), true)
assert.equal(scheduleSuccessSeen("passages", "daily", "schedule", "C"), false, "next result recreates unread attention")
assert.equal(scheduleSuccessSeen("passages", "scheduled", "schedule", "B"), false, "document formats have distinct scopes")
seedScheduleSuccessSeen("other-project", "daily", "schedule")
assert.equal(scheduleSuccessSeen("other-project", "daily", "schedule", "A"), false)
reloadWith({ MISSION_PASSAGE_CHECK: "1" })
})
test("discovering a colliding legacy positive first preserves the original seen mission and unopened boundary", () => {
const folder = "/legacy-collision", scope = JSON.stringify([folder, "project"])
const rows = [{ id: "historical", finishSequence: 1 }, { id: "unopened", finishSequence: 2 },

View file

@ -218,3 +218,48 @@ export function forgetMissionView(scope: string, missionId: string): void {
})
setVersion(v => v + 1)
}
export type ScheduleOwner = "daily" | "scheduled"
const [scheduleSeenVersion, setScheduleSeenVersion] = createSignal(0)
const scheduleSeen = new Map<string, ReadonlySet<string>>()
function scheduleSeenKey(scope: string, owner: ScheduleOwner, id: string) {
return `mission-passage-seen-${key(JSON.stringify([scope, owner, id]))}`
}
function readScheduleSeen(scope: string, owner: ScheduleOwner, id: string): ReadonlySet<string> | undefined {
scheduleSeenVersion()
const storageKey = scheduleSeenKey(scope, owner, id)
if (!scheduleSeen.has(storageKey)) {
try {
const value: unknown = JSON.parse(readClientLayoutValue(storageKey) ?? "null")
if (Array.isArray(value) && value.every(item => typeof item === "string" && item.length <= 240))
scheduleSeen.set(storageKey, new Set(value))
} catch { /* A missing positive acknowledgement leaves new results unread. */ }
}
return scheduleSeen.get(storageKey)
}
function saveScheduleSeen(scope: string, owner: ScheduleOwner, id: string, values: ReadonlySet<string>): void {
const storageKey = scheduleSeenKey(scope, owner, id)
scheduleSeen.set(storageKey, values)
const saved: string[] = []
for (const value of [...values].reverse()) {
if (JSON.stringify([...saved, value]).length > MAX_LAYOUT_VALUE_LENGTH) break
saved.unshift(value)
}
writeClientLayoutValue(storageKey, JSON.stringify(saved))
setScheduleSeenVersion(value => value + 1)
}
/** As for one-time Missions, the first loaded historical success starts seen.
* Each schedule seeds independently because the unified inventory is paged. */
export function seedScheduleSuccessSeen(scope: string, owner: ScheduleOwner, id: string, passageID?: string): void {
if (readScheduleSeen(scope, owner, id)) return
saveScheduleSeen(scope, owner, id, new Set(passageID ? [passageID] : []))
}
export function scheduleSuccessSeen(scope: string, owner: ScheduleOwner, id: string, passageID: string): boolean {
return readScheduleSeen(scope, owner, id)?.has(passageID) ?? true
}
/** Capture the displayed passage before invoking this, including for late callbacks.
* Retain exact positive identities: acknowledging A can never acknowledge B. */
export function markScheduleSuccessSeen(scope: string, owner: ScheduleOwner, id: string, passageID: string): void {
const previous = readScheduleSeen(scope, owner, id) ?? new Set<string>()
if (!previous.has(passageID)) saveScheduleSeen(scope, owner, id, new Set([...previous, passageID]))
}

View file

@ -59,7 +59,7 @@ export async function openSettings(section?: SettingsSectionId, toggle = false)
export const toggleSettings = (section?: SettingsSectionId) => openSettings(section, true)
/** Stable setting-row anchors (the row's `id`), independent of their labels. */
export type SettingsRowId = "opencode-login-start"
export type SettingsRowId = "opencode-login-start" | `config-file:${string}`
const SETTINGS_ROWS = new Set<SettingsRowId>(["opencode-login-start"])
const ROW_HINT_KEY = "codenomad.settings.rowTarget", ROW_HINT_MS = 15_000
const [settingsRowTarget, setSettingsRowTarget] = createSignal<SettingsRowId>()
@ -80,11 +80,14 @@ export async function openSettingsRow(section: SettingsSectionId, row: SettingsR
try { localStorage.setItem(ROW_HINT_KEY, JSON.stringify({ section, row, at: Date.now() })) } catch { /* the section still opens */ }
return openSettings(section)
}
/** Configuration IDs are selected only after matching the editor's server catalogue. */
export const openSettingsConfigFile = (id: string) => openSettingsRow("config-files", `config-file:${id}`)
/** Preferences windows adopt a fresh hint for their active section, once. */
export function adoptSettingsRowHint(section: SettingsSectionId) {
let hint: { section?: unknown; row?: unknown; at?: unknown } | undefined
try { hint = JSON.parse(localStorage.getItem(ROW_HINT_KEY) ?? "null") ?? undefined } catch { hint = undefined }
if (!hint || hint.section !== section || !SETTINGS_ROWS.has(hint.row as SettingsRowId)
if (!hint || hint.section !== section || !(SETTINGS_ROWS.has(hint.row as SettingsRowId)
|| section === "config-files" && typeof hint.row === "string" && hint.row.startsWith("config-file:") && hint.row.length <= 2048)
|| typeof hint.at !== "number" || Math.abs(Date.now() - hint.at) > ROW_HINT_MS) return
try { localStorage.removeItem(ROW_HINT_KEY) } catch { /* consumed by the signal below */ }
targetRow(hint.row as SettingsRowId, section)

View file

@ -1,6 +1,7 @@
/* Selected Mission/schedule icon toolbar (mission-action-bar.tsx), mounted in the
header's selection line, with the header's icon geometry. */
.mission-action-bar { display: flex; align-items: center; gap: 2px; min-width: 0; }
.mission-action-bar .mission-control-icon-button:disabled[aria-busy="true"] { opacity: 1; }
/* Text actions (Save as brief, a schedule's checks) share a wrapping row at the top
of the selection's detail, left-aligned. */
.mission-action-texts { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-xs) var(--space-sm); min-width: 0; }

View file

@ -19,12 +19,14 @@
.mission-rows { margin-inline: calc(-1 * var(--space-sm)); }
.mission-rows[hidden] { display: none; }
.mission-rows > ul { margin: 0; padding: 0; list-style: none; }
.mission-row-mark { position: relative; display: inline-flex; align-items: flex-start; flex: 0 0 16px; width: 16px; height: 20px; }
.mission-row-mark[data-mark="waiting"]::after { content: ""; position: absolute; top: 19px; left: 4px; width: 8px; height: 1px; background: var(--text-secondary); }
.mission-row-flag { color: var(--text-muted); }
.mission-row-flag[data-mark="working"] { color: var(--session-status-working-fg); animation: pulse 1.5s ease-in-out infinite; }
.mission-row-flag[data-mark="permission"] { color: var(--session-status-permission-fg); }
.mission-row-flag[data-mark="done"] { color: var(--session-status-idle-fg); }
.mission-row-flag:is([data-mark="paused"], [data-mark="interrupted"]) { color: var(--status-warning); }
.mission-row-flag[data-mark="prepared"] { color: var(--accent-primary); }
.mission-row-flag:is([data-mark="prepared"], [data-mark="waiting"]) { color: var(--accent-primary); }
/* An expanded row's children: its task rows span the panel like subsession rows,
each with its own separator; other content (a schedule's detail, the brief name
field, command feedback) is indented under the row. */

View file

@ -0,0 +1,72 @@
import assert from "node:assert/strict"
import { after, before, test } from "node:test"
import { chromium, type Browser } from "playwright"
import { borrowFixture } from "./fixture-borrow"
import { armFixtureNavigationBudget } from "./mission-panel-route"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { prepareGitPrototypeAssets } from "./fixtures/git-history-assets.mjs"
let browser: Browser, url: string
before(async () => {
prepareGitPrototypeAssets()
const fixture = await borrowFixture({ name: "config-file-target", routes: [{ path: "/config", html:
'<html><body><div id="root"></div><script type="module" src="/tests/browser/fixtures/config-file-target.tsx"></script></body></html>' }] })
url = fixture.url
browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined })
armFixtureNavigationBudget(browser)
})
after(async () => { await browser?.close() })
for (const native of [false, true]) test(`${native ? "native Preferences hint" : "embedded opening"} selects only a catalogued config and supports reopening`, async () => {
const page = await browser.newPage(), reads: string[] = [], writes: string[] = [], errors: string[] = [], resources: string[] = []
page.setDefaultTimeout(20_000)
page.on("pageerror", error => errors.push(error.message))
page.on("response", response => { if (response.status() >= 400) resources.push(`${response.status()} ${response.url()}`) })
try {
const publicPath = fileURLToPath(new URL("../../src/renderer/public", import.meta.url))
await page.context().route(new RegExp("^[^?#]*//[^/]+/monaco(/vs/|\\.worker\\.js)"),
route => route.fulfill({ path: path.join(publicPath, decodeURIComponent(new URL(route.request().url()).pathname)) }))
await page.route("**/api/**", route => {
const request = route.request(), path = new URL(request.url()).pathname
if (request.method() !== "GET") writes.push(path)
if (path === "/api/config-files") return route.fulfill({ json: [
{ id: "first", label: "First config", path: "/config/first.jsonc", format: "jsonc" },
{ id: "responsible", label: "Responsible config", path: "/config/responsible.jsonc", format: "jsonc" },
] })
if (path.startsWith("/api/config-files/")) {
reads.push(path)
return route.fulfill({ json: { contents: "{}\n", exists: true } })
}
return route.fulfill({ json: path === "/api/storage/config/ui" ? { settings: { locale: "en" } } : {} })
})
await page.goto(url)
await page.waitForFunction(() => (window as any).configTarget)
const open = (id: string) => page.evaluate(({ id, native }) => (window as any).configTarget[native ? "native" : "open"](id), { id, native })
await open("responsible")
const selector = page.locator(".config-files-selector-trigger")
await selector.filter({ hasText: "Responsible config" }).waitFor()
assert.deepEqual(reads, ["/api/config-files/responsible/content"])
await open("first"); await selector.filter({ hasText: "First config" }).waitFor()
assert.equal(reads.at(-1), "/api/config-files/first/content")
const count = reads.length
await open("unknown")
await page.waitForFunction(() => !(window as any).configTarget.pending())
assert.equal(reads.length, count, "an absent server ID never becomes a file read")
const editor = page.locator(".monaco-editor .view-lines").first()
await editor.click({ position: { x: 8, y: 8 } })
await page.keyboard.press("Control+Home"); await page.keyboard.type(" ")
await page.getByText("Unsaved changes", { exact: true }).waitFor()
await open("responsible")
const dialog = page.getByRole("dialog")
await dialog.waitFor()
if (native) await page.evaluate(() => (window as any).configTarget.checkDiscard())
await dialog.getByRole("button", { name: "Keep editing", exact: true }).click()
if (native) await page.waitForFunction(() => (window as any).configTarget.discardResult === false)
assert.match(await selector.innerText(), /First config/)
assert.equal(reads.length, count, "cancel preserves the dirty file without loading the requested target")
assert.deepEqual(writes, [])
assert.deepEqual(errors, [])
} catch (error) { throw new Error(`${error}\n${JSON.stringify({ errors, resources, editor: (await page.locator(".config-files-editor-shell").innerHTML()).slice(0, 1000) })}`) }
finally { await page.close() }
})

View file

@ -0,0 +1,25 @@
import { Show, createSignal } from "solid-js"
import { render } from "solid-js/web"
import { ConfigFilesSettingsSection } from "../../../src/components/settings/config-files-settings-section"
import { ConfigProvider } from "../../../src/stores/preferences"
import { I18nProvider } from "../../../src/lib/i18n"
import { ThemeProvider } from "../../../src/lib/theme"
import { adoptSettingsRowHint, openSettingsConfigFile, settingsRowTarget } from "../../../src/stores/settings-screen"
import AlertDialog from "../../../src/components/alert-dialog"
import { confirmSettingsDiscard } from "../../../src/stores/settings-dirty-guard"
import "../../../src/index.css"
function Fixture() {
const [mounted, mount] = createSignal(false)
Object.assign(window, { configTarget: {
open: async (id: string) => { await openSettingsConfigFile(id); mount(true) },
native: (id: string, at = Date.now()) => {
localStorage.setItem("codenomad.settings.rowTarget", JSON.stringify({ section: "config-files", row: `config-file:${id}`, at }))
adoptSettingsRowHint("config-files"); mount(true)
},
pending: settingsRowTarget,
checkDiscard: () => { void confirmSettingsDiscard().then(result => { (window as any).configTarget.discardResult = result }) },
} })
return <><Show when={mounted()}><ConfigFilesSettingsSection /></Show><AlertDialog /></>
}
render(() => <ConfigProvider><I18nProvider><ThemeProvider><Fixture /></ThemeProvider></I18nProvider></ConfigProvider>, document.getElementById("root")!)

View file

@ -1590,7 +1590,8 @@ test("top-level mission rows expose short one-line titles, semantic states, read
assert.equal(await selectedMissionTitle(page).count(), 0)
// Each entry is one line: a status mark and the title; the state · time stays in the tooltip and screen-reader text.
const parts = await rows[0].evaluate(el => [...el.children].map(child => child.getAttribute("class")!.split(" ")[0]))
assert.deepEqual(parts, ["lucide", "session-item-title", "sr-only"])
assert.deepEqual(parts, ["mission-row-mark", "session-item-title", "sr-only"])
assert.equal(await rows[0].locator(".mission-row-mark > svg.mission-row-flag").count(), 1)
assert.match(await rows[0].locator(".sr-only").textContent() ?? "", /^In progress · /)
assert.match(await rows[0].getAttribute("title") ?? "", new RegExp(`^${titleOf(0).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} — In progress · `))
const title = await rows[0].locator(".session-item-title").evaluate(el => ({ overflow: getComputedStyle(el).textOverflow, wrap: getComputedStyle(el).whiteSpace }))

View file

@ -39,7 +39,7 @@ function created(body: Record<string, unknown>): MissionMap {
}
async function setup(page: Page) {
const errors: string[] = [], creates: Array<Record<string, unknown>> = [], controls: string[] = []
const errors: string[] = [], creates: Array<Record<string, unknown>> = [], controls: string[] = [], activations: Record<string, any>[] = []
let list: MissionMap[] = []
let scheduled: Awaited<ReturnType<typeof pausedMissionScheduleReceipt>> | undefined
page.setDefaultTimeout(15_000); page.setDefaultNavigationTimeout(60_000)
@ -54,7 +54,16 @@ async function setup(page: Page) {
await page.route("**/api/workspaces/fixture/missions**", async route => {
const request = route.request(), path = new URL(request.url()).pathname
if (path.endsWith("/control")) { controls.push(path); return route.abort() }
if (path.endsWith("/capabilities")) return route.fulfill({ json: { location: { directory: "/fixture" }, api: { available: true }, enabled: true } })
if (path.endsWith("/capabilities")) return route.fulfill({ json: { location: { directory: "/fixture" }, api: { available: true }, enabled: true,
origin: null, activation: { available: true, targets: [] } } })
if (request.method() === "POST" && path.endsWith("/schedule-settings")) {
const input = request.postDataJSON(); activations.push(input)
assert.equal(input.expectedDocumentRevision, scheduled!.document!.revision)
scheduled = { ...scheduled!, document: { ...scheduled!.document!, revision: scheduled!.document!.revision + 1,
scheduleActivation: { requestID: input.requestID, expectedRevision: input.expectedDocumentRevision,
authority: "a".repeat(64), state: "ready", targets: [], effectiveOrigin: null } } }
return route.fulfill({ json: { document: scheduled.document } })
}
if (request.method() === "GET" && path.endsWith("/msn_created/schedule") && scheduled) return route.fulfill({ json: scheduled })
if (request.method() === "GET" && path.endsWith("/missions/scheduled")) return route.fulfill({ json: {
version: 1, projectID: "project", schedules: scheduled ? [scheduled.document] : [] } })
@ -72,7 +81,7 @@ async function setup(page: Page) {
}
return route.fulfill({ json: {} })
})
return { errors, creates, controls, get scheduled() { return scheduled } }
return { errors, creates, controls, activations, get scheduled() { return scheduled } }
}
const submitReady = (page: Page) => page.waitForFunction(() => !(document.querySelector('form.mission-editor button[type="submit"]') as HTMLButtonElement)?.disabled)
@ -394,7 +403,7 @@ for (const lost of [false, true]) test(`opted-in schedule creation sends one Pla
if (route.request().method() !== "POST") return route.fallback()
const input = route.request().postDataJSON(); controls.push(input)
return lost ? route.abort("connectionreset") : route.fulfill({ json: { ...fixture.scheduled, pending: false,
document: { ...fixture.scheduled!.document, revision: 1, control: { requestID: input.requestID,
document: { ...fixture.scheduled!.document, revision: input.expectedRevision + 1, control: { requestID: input.requestID,
expectedRevision: input.expectedRevision, action: "play", pending: false } } } })
})
const holds = () => page.evaluate(async () => {
@ -415,10 +424,12 @@ for (const lost of [false, true]) test(`opted-in schedule creation sends one Pla
assert.equal(fixture.creates.length, 1)
assert.equal(controls.length, 1)
assert.equal(controls[0].action, "play")
assert.equal(controls[0].expectedRevision, 0)
assert.equal(fixture.activations.length, 1, "the ON setting still gets a ready activation proof")
assert.equal(fixture.activations[0].expectedDocumentRevision, 0)
assert.equal(controls[0].expectedRevision, 1, "Play uses the activated revision")
if (lost) {
const held = await holds()
assert.deepEqual(held, [{ phase: "control", action: "play", requestID: controls[0].requestID, expectedRevision: 0 }])
assert.deepEqual(held, [{ phase: "control", action: "play", requestID: controls[0].requestID, expectedRevision: 1 }])
await page.evaluate(() => window.missionEditorLifetime.mount(false))
await page.evaluate(() => window.missionEditorLifetime.mount(true))
assert.deepEqual(await holds(), held)

View file

@ -129,10 +129,8 @@ test("direct scheduled creation arms once through exact activation and Play revi
const page = await browser.newPage(), f = await setup(page, { enabled: false })
try {
const saving = save(page)
const dialog = page.getByRole("dialog")
await dialog.getByText("/private/config/opencode.jsonc", { exact: false }).waitFor()
await dialog.getByRole("button", { name: "Start", exact: true }).click()
await saving; await saved(page)
assert.equal(await page.getByRole("dialog").count(), 0)
assert.deepEqual(f.posts.map(post => post.action ?? "activation"), ["create", "activation", "play"])
assert.equal(f.posts[2].expectedRevision, f.posts[1].expectedDocumentRevision + 1)
await page.evaluate(() => (window as any).creationStartFixture.repeat())
@ -160,7 +158,6 @@ test("lost activation remains retained on remount; receipt recovery leaves Play
const page = await browser.newPage(), f = await setup(page, { enabled: false, lose: "activation" })
try {
const saving = save(page)
await page.getByRole("dialog").getByRole("button", { name: "Start", exact: true }).click()
await saving; await saved(page)
assert.equal(await page.evaluate(() => (window as any).creationStartFixture.held()?.phase), "activation")
await page.evaluate(() => (window as any).creationStartFixture.mount(false))
@ -178,7 +175,6 @@ test("view departure after activation dispatch fences its direct Play continuati
f.activationGate = new Promise<void>(resolve => { release = resolve })
try {
const saving = save(page)
await page.getByRole("dialog").getByRole("button", { name: "Start", exact: true }).click()
await page.waitForFunction(() => (window as any).creationStartFixture.held()?.phase === "activation")
await page.evaluate(() => (window as any).creationStartFixture.activate(false))
release(); await saving
@ -193,11 +189,11 @@ test("lost scheduled Play keeps its exact original control across helper disposa
try {
await save(page); await saved(page)
const held = await page.evaluate(() => (window as any).creationStartFixture.held())
assert.equal(held.action, "play"); assert.equal(held.requestID, f.posts[1].requestID)
assert.equal(held.action, "play"); assert.equal(held.requestID, f.posts[2].requestID)
await page.evaluate(() => (window as any).creationStartFixture.mount(false))
await page.evaluate(() => (window as any).creationStartFixture.mount(true))
assert.equal(await page.evaluate(() => (window as any).creationStartFixture.held()?.requestID), held.requestID)
assert.deepEqual(f.posts.map(post => post.action), ["create", "play"])
assert.deepEqual(f.posts.map(post => post.action ?? "activation"), ["create", "activation", "play"])
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
@ -227,9 +223,10 @@ test("real editor adopts discovered project before creation; lost Play remains r
assert.deepEqual(f.posts.map(post => [post.action, post.target]), [
["create", "/api/workspaces/fixture/missions/scheduled"],
[undefined, "/api/workspaces/fixture/missions/msn_created/schedule-settings"],
["play", "/api/workspaces/fixture/missions/msn_created/schedule"],
])
const play = f.posts[1]
const play = f.posts[2]
const retained = await page.evaluate(() => (window as any).realCreationStartFixture.held())
assert.ok(retained, "the Play holder must use the discovered project, matching normal schedule controls")
assert.equal(retained.phase, "control"); assert.equal(retained.action, "play")
@ -254,7 +251,7 @@ test("real editor adopts discovered project before creation; lost Play remains r
assert.equal(receiptReads[0].searchParams.get("directory"), "/fixture")
const recovered = await page.evaluate(() => (window as any).realCreationStartFixture.held())
assert.equal(recovered.requestID, play.requestID); assert.equal(recovered.minimumRevision, f.revision)
assert.deepEqual(f.posts.map(post => post.action), ["create", "play"], "receipt recovery must never send another Play")
assert.deepEqual(f.posts.map(post => post.action ?? "activation"), ["create", "activation", "play"], "receipt recovery must never send another Play")
assert.deepEqual(f.failedRequests, [{ method: "POST", path: "/api/workspaces/fixture/missions/msn_created/schedule" }])
assert.deepEqual(f.errors, [])
} finally { await page.close() }

View file

@ -113,7 +113,8 @@ test("the list is a list: one-line titled entries, nothing below until a selecti
assert.equal(await detail(page).count(), 0, "no selection, no detail")
assert.equal(await selectedMissionTitle(page).count(), 0, "nothing is selected by default")
for (const entry of await inlineEntries(page).all()) {
assert.deepEqual(await entry.evaluate(el => [...el.children].map(child => child.getAttribute("class")!.split(" ")[0])), ["lucide", "session-item-title", "sr-only"])
assert.deepEqual(await entry.evaluate(el => [...el.children].map(child => child.getAttribute("class")!.split(" ")[0])), ["mission-row-mark", "session-item-title", "sr-only"])
assert.equal(await entry.locator(".mission-row-mark > svg.mission-row-flag").count(), 1)
const [row, title, line] = await entry.evaluate(el => { const title = el.querySelector(".session-item-title")!
return [el.getBoundingClientRect().height, title.getBoundingClientRect().height, parseFloat(getComputedStyle(title).lineHeight)] })
assert.ok(title <= line + 0.5 && row <= 32, "exactly one short line, even for long titles")
@ -228,7 +229,8 @@ test("recurring selected: Daily entry, Next in the schedule zone, current tree s
try {
await open(page, [audit, active], [schedule])
await (await inlineMissionEntry(page, "Daily source review")).waitFor()
assert.match(await missionEntryStatus(page, "Daily source review"), /^Daily · Running · Next: (today|tomorrow) 8:15 AM \(UTC\)( · |$)/)
assert.match(await missionEntryStatus(page, "Daily source review"), /^Daily · Waiting for scheduled run · Next: (today|tomorrow) 8:15 AM \(UTC\)( · |$)/)
assert.equal(await (await inlineMissionEntry(page, "Daily source review")).locator(".mission-row-mark").getAttribute("data-mark"), "waiting")
await selectMission(page, "Daily source review")
assert.deepEqual(await toolbar(page), [["Pause schedule Daily source review", false], ["Stop schedule Daily source review", false],
["Run Daily source review now", false], ["Summary", false], ["Open conversation", true], ["Delete selected mission…", true], ["More actions", true]])
@ -266,7 +268,7 @@ test("a viewer in the schedule's own zone sees no zone label", async () => {
try {
await open(page, [], [schedule])
await (await inlineMissionEntry(page, "Daily source review")).waitFor()
assert.match(await missionEntryStatus(page, "Daily source review"), /^Daily · Running · Next: (today|tomorrow) 8:15 AM( · |$)/)
assert.match(await missionEntryStatus(page, "Daily source review"), /^Daily · Waiting for scheduled run · Next: (today|tomorrow) 8:15 AM( · |$)/)
assert.doesNotMatch(await missionEntryStatus(page, "Daily source review"), /\(UTC\)/)
} finally { await page.close() }
})

View file

@ -113,6 +113,29 @@ async function holdPartial(page: Page, action: "pause" | "stop", title = TITLE)
// The partial result schedules a row read; feedback can precede its publication.
await missionRow(page, title).locator(".sr-only", { hasText: action === "pause" ? /^Daily · Paused/ : /^Daily · Stopped/ }).waitFor({ state: "attached" })
}
test("daily Resume keeps its loading button and progress announcement until HTTP settles", async () => {
const daily = { ...schedule(), state: "paused" as const, nextDueAt: null, actions: ["resume", "stop", "run-now"] as RecurrenceSchedule["actions"] }
const { page, state } = await openPage([daily]), gate = deferred(), submitted = deferred()
state.controlReply.set(daily.id, async route => { submitted.release(); await gate.promise; await route.abort("connectionreset") })
try {
await selectMission(page, TITLE)
const resume = missionToolbarAction(page, `Resume schedule ${TITLE}`)
await resume.click(); await submitted.promise
assert.equal(await resume.getAttribute("aria-busy"), "true")
assert.equal(await resume.isDisabled(), true)
assert.equal(await resume.locator("svg.animate-spin").count(), 1)
assert.equal(await missionToolbarAction(page, STOP).getAttribute("aria-busy"), null)
const status = page.locator(".mission-picker-selection-actions .mission-action-feedback [role=status]")
assert.equal(await status.count(), 1); assert.equal(await status.textContent(), "Resuming…")
assert.equal(await missionToolbarAction(page, CHECK()).count(), 0, "no premature uncertain-result button")
gate.release()
await missionToolbarAction(page, CHECK()).waitFor()
assert.equal(await status.count(), 1); assert.equal(await status.textContent(), UNCONFIRMED)
assert.equal(await page.locator(".mission-action-bar [aria-busy=true]").count(), 0)
assert.deepEqual(state.errors, [])
} finally { gate.release(); await page.close() }
})
/** Starts an event-driven row read that stays in flight until released. */
async function rowReadInFlight(page: Page, state: Awaited<ReturnType<typeof openPage>>["state"]) {
const gate = deferred(), before = state.rows

View file

@ -402,6 +402,7 @@ test("a partial Pause, a failed status read and a live Job keep every hold witho
await refresh(page)
await expectLifecycle(page, [[CHECK, true], [STOP, false], [RUN_NOW, false]])
assert.equal(await statusText(page).count(), 0)
const pause = (await f.read()).controls[1]!
// Failed status reads keep it held.
f.native.statusFails = true
for (let index = 0; index < 2; index++) { await missionToolbarAction(page, CHECK).click(); await page.waitForTimeout(200) }
@ -420,8 +421,11 @@ test("a partial Pause, a failed status read and a live Job keep every hold witho
assert.equal(f.native.writes.length, 2)
f.native.statusFails = false
await missionRefresh(page).click()
// Loading restores Pause before the retry reaches native; wait for its exact completion.
await until(async () => (await f.read()).controls.find(item => item.requestID === pause.requestID)?.controlsComplete === true)
await missionToolbarAction(page, CHECK).waitFor({ state: "hidden" })
assert.match(f.native.writes[2]!, /^pause:.*:retry$/)
assert.equal(f.native.writes[2], `pause:${pause.requestID}:retry`)
assert.equal(f.native.writes.length, 3, "only the exact partial Pause was retried")
assert.equal(await f.permitFree(), true)
assert.deepEqual(opened.errors, [])
} finally { await opened.page.close(); await f.dispose() }

View file

@ -204,7 +204,7 @@ test("rows say Next, stuck passages explain their one action, history is plain a
try {
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45_000 })
await waitForEntryStatus(page, TITLE, /Next: /)
assert.match(await missionEntryStatus(page, TITLE), /^Daily · Running · Next: /, "a running entry names its state, then its next run")
assert.match(await missionEntryStatus(page, TITLE), /^Daily · State unconfirmed · Next: /, "an uncertain passage names the uncertainty before its next run")
// The picker selects the Mission (not its open coordinator conversation); its toolbar owns its primary control.
await waitForEntryStatus(page, "One-time review", /^Prepared · /)
const once = await inlineMissionEntry(page, "One-time review")

View file

@ -15,6 +15,7 @@ import type { MissionDocument } from "../../../server/src/missions/mission-docum
import type { MissionJsonValue } from "../../../server/src/missions/model"
import { missionLaunchModel, type MissionConfiguration } from "../../../server/src/missions/launch-policy"
import { legacyLaunch } from "../../../server/src/missions/legacy-launch-test-helper"
import { BUILT_IN_COLOR_SCHEMES } from "../../src/lib/theme-scheme"
let browser: Browser, url: string, events: Server, eventsURL: string
before(async () => {
@ -39,7 +40,7 @@ const profiles = { coordinator: { agent: "coordinator", model: { providerID: "p"
roles: { specialist: { agent: "specialist", model: { providerID: "p", id: "m" } } } }
async function setup(page: Page, options: { seed?: boolean; enabled?: boolean; available?: boolean; locale?: string; journalGate?: Promise<void>; outsidePage?: boolean } = {}) {
page.setDefaultTimeout(15_000)
const values = new Map<string, MissionJsonValue>(), posts: Record<string, any>[] = [], reads: string[] = [], errors: string[] = []
const values = new Map<string, MissionJsonValue>(), posts: Record<string, any>[] = [], activations: Record<string, any>[] = [], reads: string[] = [], errors: string[] = []
const store = new NativeMissionDocumentStore({ get: async key => values.get(key),
compareAndSet: async (key, value) => { values.set(key, structuredClone(value)) } }, "project", "fixture")
const config = { title: "Inspect local changes", objective: "Inspect local changes and report useful findings.", template: "custom" as const,
@ -98,16 +99,19 @@ async function setup(page: Page, options: { seed?: boolean; enabled?: boolean; a
if (target.endsWith("/missions")) await options.journalGate
return route.fulfill({ json: { available: true, version: 1, projectID: "project", missions: [], summaries: [], generatedAt: 1, discardedEvents: 0 } })
}
const body = request.postDataJSON(); posts.push({ ...body, target })
const body = request.postDataJSON()
if (target.endsWith("/schedule-settings")) {
activations.push({ ...body, target })
if (options.enabled === false) posts.push({ ...body, target })
assert.equal(body.expectedDocumentRevision, doc!.revision, "activation uses the revision admitted by the UI")
activation = body
doc = await store.change(doc!.id, doc!.revision, () => true, value => { value.scheduleActivation = { requestID: body.requestID,
if (doc!.scheduleActivation?.state !== "ready") doc = await store.change(doc!.id, doc!.revision, () => true, value => { value.scheduleActivation = { requestID: body.requestID,
expectedRevision: body.expectedDocumentRevision, authority: "a".repeat(64), state: "ready", targets: [], effectiveOrigin: "/private/config/opencode.jsonc" } })
enabled = true
if (lost === "activation") return route.abort("connectionreset")
return route.fulfill({ json: { document: missionDocumentSummary(doc) } })
}
posts.push({ ...body, target })
if (body.action === "create") doc = await store.create("msn_schedule", { ...config, ...body.configuration }, Date.now(), () => true)
else if (body.action === "delete") deleted = true
else doc = await store.change(doc!.id, body.expectedRevision, () => true, value => {
@ -135,7 +139,7 @@ async function setup(page: Page, options: { seed?: boolean; enabled?: boolean; a
await page.evaluate(() => (window as any).missionFixture.connectCatalog())
if (!streamObserved) await page.waitForResponse(response => response.headers()["content-type"] === "text/event-stream")
page.off("response", observeStream)
return { posts, reads, errors, store, get doc() { return doc! }, result,
return { posts, activations, reads, errors, store, get doc() { return doc! }, result,
addSchedule: async (id: string, change: Partial<MissionConfiguration>) => {
extras.push(await store.create(id, { ...config, ...change } as MissionConfiguration, Date.now(), () => true))
},
@ -158,6 +162,65 @@ const deferred = () => {
const promise = new Promise<void>(yes => { resolve = yes })
return { promise, resolve }
}
test("unified waiting and exact successful passages distinguish prepared, pause, unknown and finished", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
const entry = page.locator('[data-mission-key="scheduled:msn_schedule"] .mission-row-select')
const waitMark = (expected: string) => page.waitForFunction(expected =>
document.querySelector('[data-mission-key="scheduled:msn_schedule"] .mission-row-flag')?.getAttribute("data-mark") === expected, expected)
const refresh = () => page.evaluate(() => (window as any).missionFixture.refresh())
const success = async (requestID: string) => {
await f.change(doc => {
changes.reserve(doc, { kind: "manual", requestID }, Date.now(), [])
changes.admitted(doc, doc.pending!.id, Date.now())
changes.settle(doc, doc.pending!.id, "completed", Date.now())
})
const latest = f.doc.history.at(-1)!.id
const published = page.waitForResponse(async response => new URL(response.url()).pathname.endsWith("/missions/scheduled")
&& (await response.json()).schedules?.some((row: any) => row.latestResult?.id === latest))
await refresh(); await (await published).finished()
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
await waitMark("done")
}
try {
await entry.waitFor(); await waitMark("prepared")
assert.equal(await entry.locator(".mission-row-mark").evaluate(element => getComputedStyle(element, "::after").content), "none")
await select(page); await click(page, "Play"); await waitMark("waiting")
assert.match(await entry.getAttribute("title") ?? "", /Waiting for scheduled run/)
await click(page, "Pause"); await waitMark("paused")
await click(page, "Resume"); await waitMark("waiting")
await success("first-result")
const first = f.doc.history.at(-1)!.id
await entry.click(); await waitMark("waiting")
await success("second-result")
assert.notEqual(f.doc.history.at(-1)!.id, first)
const second = f.doc.history.at(-1)!.id
await page.locator('[data-mission-key="scheduled:msn_schedule"] .session-item-expander').click({ button: "right" })
await success("third-result")
await page.getByRole("menuitem", { name: "Mark as read", exact: true }).click()
assert.equal(await entry.locator(".mission-row-mark").getAttribute("data-mark"), "done", "the later passage stays unread")
assert.deepEqual(await page.evaluate(async ({ second, third }) => {
const { scheduleSuccessSeen } = await import("/src/stores/mission-view-state.ts")
const scope = JSON.stringify(["fixture", "project"])
return [second, third].map(id => scheduleSuccessSeen(scope, "scheduled", "msn_schedule", id))
}, { second, third: f.doc.history.at(-1)!.id }), [true, false])
await page.locator('[data-mission-key="scheduled:msn_schedule"] .session-item-expander').click({ button: "right" })
await page.getByRole("menuitem", { name: "Mark as read", exact: true }).click()
await waitMark("idle") // The third passage exhausted this fixture's launch limit.
await f.change(doc => { doc.state = "finished" }); await refresh(); await waitMark("idle")
await f.change(doc => { doc.state = "running" })
await page.route(url => url.pathname.endsWith("/missions/scheduled"), route => {
const doc = f.result().document!
return route.fulfill({ json: { version: 1, projectID: "project", schedules: [{ ...doc,
observation: { ...doc.observation, state: "unknown", nativeStatus: null, nextDueAt: null } }] } })
})
await refresh(); await waitMark("unconfirmed")
assert.match(await entry.getAttribute("title") ?? "", /State unconfirmed/)
assert.equal(await entry.locator(".mission-row-mark").evaluate(element => getComputedStyle(element, "::after").content), "none")
await f.change(doc => { doc.state = "stopped" }); await refresh(); await waitMark("idle")
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
async function select(page: Page) {
const entry = page.locator(".mission-rows button.mission-row-select").filter({ hasText: "Inspect local changes" })
await entry.click()
@ -254,13 +317,11 @@ test("revision conflict is refused before dispatch and preserves the refreshed c
} finally { await page.close() }
})
test("informed activation lists exact paths and its lost ACK never sends Play automatically", async () => {
test("silent activation with a lost ACK never sends Play automatically", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true, enabled: false })
try {
await select(page); f.lost = "activation"; await click(page, "Play")
const dialog = page.getByRole("dialog")
assert.match(await dialog.innerText(), /experimental.schedules.*\/private\/config\/opencode.jsonc/s)
await dialog.getByRole("button", { name: "Start", exact: true }).click()
assert.equal(await page.getByRole("dialog").count(), 0)
await button(page, "Refresh saved request").waitFor()
// Receipt settlement releases the hold before its parent's list revalidation.
// Wait for that exact activated revision to traverse the real response/render path.
@ -280,6 +341,321 @@ test("informed activation lists exact paths and its lost ACK never sends Play au
} finally { await page.close() }
})
test("already ON without a receipt prepares on the server; only Start loads and double clicks send one Play", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
const gate = deferred(), submitted = deferred()
try {
await select(page)
const start = button(page, "Start"), bounds = await start.boundingBox()
await page.route("**/schedule-settings", async route => {
if (route.request().method() === "POST") { submitted.resolve(); await gate.promise }
return route.fallback()
})
await start.click(); await submitted.promise
assert.equal(await start.getAttribute("aria-busy"), "true")
assert.deepEqual(await start.boundingBox(), bounds)
assert.equal(await button(page, "Stop…").getAttribute("aria-busy"), null)
const status = page.locator(".mission-picker-selection-actions [role=status]")
assert.equal(await status.count(), 1)
assert.equal(await status.textContent(), "Starting…")
assert.equal(await page.getByRole("dialog").count(), 0)
await start.evaluate(element => element.dispatchEvent(new MouseEvent("click", { bubbles: true })))
for (const scheme of BUILT_IN_COLOR_SCHEMES) {
await page.evaluate(async scheme => {
const module = await import("/src/lib/theme-scheme.ts")
module.applyColorScheme(module.normalizeColorScheme(scheme))
}, scheme.id)
const sample = await start.evaluate(element => {
const style = getComputedStyle(element), svg = element.querySelector("svg")!
const canvas = document.createElement("canvas").getContext("2d")!
const probe = document.createElement("span"); probe.style.color = "var(--surface-canvas)"; element.append(probe)
const [icon, surface] = [getComputedStyle(svg).color, getComputedStyle(probe).color].map(color => {
canvas.fillStyle = color; canvas.fillRect(0, 0, 1, 1)
return [...canvas.getImageData(0, 0, 1, 1).data].slice(0, 3)
})
probe.remove()
return { opacity: style.opacity, icon, surface, width: parseFloat(getComputedStyle(svg).width) }
})
const luminance = (rgb: number[]) => rgb.map(v => v / 255).map(v => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4)
.reduce((total, v, i) => total + v * [.2126, .7152, .0722][i], 0)
const [a, b] = [luminance(sample.icon), luminance(sample.surface)].sort((a, b) => b - a)
assert.ok((a + .05) / (b + .05) >= 3, `${scheme.id}: ${JSON.stringify(sample)}`)
assert.equal(sample.opacity, "1"); assert.equal(sample.width, 14)
}
await page.emulateMedia({ reducedMotion: "reduce" })
const motion = await start.locator("svg").evaluate(element => {
const style = getComputedStyle(element)
return { duration: style.animationDuration, iterations: style.animationIterationCount }
})
assert.equal(motion.iterations, "1"); assert.ok(parseFloat(motion.duration) <= .00001)
gate.resolve()
await button(page, "Pause").and(page.locator(":enabled")).waitFor()
assert.equal(f.activations.length, 1); assert.deepEqual(f.posts.map(post => post.action), ["play"])
assert.equal(await page.locator(".mission-action-bar [aria-busy=true]").count(), 0)
assert.deepEqual(f.errors, [])
} finally { gate.resolve(); await page.close() }
})
for (const layer of ["project", "global", "inherited", "imposed", "environment"] as const)
test(`explicit ${layer} OFF exposes only the supported repair action and hides details behind keyboard info`, async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
try {
await select(page)
const openable = layer === "project" || layer === "global", path = layer === "environment" ? undefined : "/private/responsible/opencode.jsonc"
const refusal = { reason: "explicit-off", provenance: layer === "environment" ? "environment" : "experimental-block",
layer, path, openable, ...(openable ? { configFileID: "responsible-config" } : {}) }
await page.evaluate(() => { (window as any).electronAPI.openPreferences = (section: string) => { (window as any).openedSection = section } })
await page.route("**/missions/scheduled/capabilities*", route => route.fulfill({ json: { location: { directory: "fixture" },
api: { available: true }, enabled: true, origin: path ?? null, activation: { available: false, targets: [],
reason: "explicit-off", code: "schedule-activation-refused", refusal } } }))
await click(page, "Play")
const repair = button(page, "Open scheduling settings")
await page.locator(".mission-picker-selection-actions [role=status]").filter({ hasText: "Scheduling is disabled" }).waitFor()
assert.equal(await repair.count(), openable ? 1 : 0)
assert.equal(f.posts.length, 0); assert.equal(f.activations.length, 0)
const info = page.locator(".mission-action-feedback .settings-info-tip")
await info.focus()
await page.getByRole("tooltip").filter({ hasText: layer === "environment" ? "service environment" : path! }).waitFor()
if (layer !== "environment") assert.match(await page.getByRole("tooltip").innerText(), /^(Project|Global|Inherited|Imposed) configuration:/)
assert.doesNotMatch(await page.locator(".mission-picker-selection-actions").innerText(), /experimental\.schedules|\/private\/responsible/)
if (openable) {
await repair.click()
await page.waitForFunction(() => (window as any).openedSection === "config-files")
const hint = await page.evaluate(() => JSON.parse(localStorage.getItem("codenomad.settings.rowTarget")!))
assert.equal(hint.row, "config-file:responsible-config")
}
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
const refusalLayers = ["project", "global", "inherited", "imposed"] as const
const refusalLabels = {
en: ["Project configuration", "Global configuration", "Inherited configuration", "Imposed configuration"],
fr: ["Configuration du projet", "Configuration globale", "Configuration héritée", "Configuration imposée"],
de: ["Projektkonfiguration", "Globale Konfiguration", "Geerbte Konfiguration", "Vorgegebene Konfiguration"],
es: ["Configuración del proyecto", "Configuración global", "Configuración heredada", "Configuración impuesta"],
he: ["הגדרות הפרויקט", "הגדרות כלליות", "הגדרות בירושה", "הגדרות כפויות"],
ja: ["プロジェクト設定", "グローバル設定", "継承された設定", "強制された設定"],
ne: ["परियोजना कन्फिगरेसन", "विश्वव्यापी कन्फिगरेसन", "विरासतमा प्राप्त कन्फिगरेसन", "अनिवार्य कन्फिगरेसन"],
ru: ["Конфигурация проекта", "Глобальная конфигурация", "Унаследованная конфигурация", "Принудительная конфигурация"],
tr: ["Proje yapılandırması", "Genel yapılandırma", "Devralınan yapılandırma", "Zorunlu yapılandırma"],
"zh-Hans": ["项目配置", "全局配置", "继承的配置", "强制配置"],
}
for (const [locale, labels] of Object.entries(refusalLabels)) test(`${locale}: all document OFF sources are localized in the real information tip`, async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true, locale })
let layer: typeof refusalLayers[number] = "project"
try {
await select(page)
await page.route("**/missions/scheduled/capabilities*", route => route.fulfill({ json: { location: { directory: "fixture" },
api: { available: true }, enabled: true, origin: null, activation: { available: false, targets: [],
refusal: { reason: "explicit-off", provenance: "experimental-block", layer, path: "/private/source.jsonc", openable: false } } } }))
for (const [index, value] of refusalLayers.entries()) {
layer = value
await page.locator(".mission-picker-actions button").last().click()
const info = page.locator(".mission-action-feedback .settings-info-tip")
await info.focus()
const tip = page.getByRole("tooltip").filter({ hasText: labels[index] })
await tip.waitFor()
assert.match(await tip.innerText(), /\/private\/source\.jsonc/)
}
assert.equal(f.posts.length, 0); assert.equal(f.activations.length, 0)
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
test("unselected unified passages prioritize their coordinator and descendant requests over working", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
const entry = page.locator('[data-mission-key="scheduled:msn_schedule"] .mission-row-select')
try {
await f.change(doc => {
changes.play(doc, "play-probe", Date.now(), []); doc.synchronization = null
changes.reserve(doc, { kind: "manual", requestID: "request-probe" }, Date.now(), [])
changes.admitted(doc, doc.pending!.id, Date.now())
})
await page.evaluate(() => (window as any).missionFixture.refresh())
await page.waitForFunction(() => document.querySelector('[data-mission-key="scheduled:msn_schedule"] .mission-row-mark')?.getAttribute("data-mark") === "working")
const root = f.doc.pending!.coordinatorSessionID
await page.evaluate(root => {
;(window as any).missionFixture.seedCoordinators([root, "ses_child"], { ses_child: root })
;(window as any).missionFixture.queuePermission("ses_child", "child-permission")
}, root)
await page.waitForFunction(() => document.querySelector('[data-mission-key="scheduled:msn_schedule"] .mission-row-mark')?.getAttribute("data-mark") === "permission")
assert.equal(await entry.getAttribute("aria-current"), null)
assert.match(await entry.getAttribute("title") ?? "", /Awaiting your input/)
await page.evaluate(async root => {
const { clearPermissionQueue } = await import("/src/stores/instances.ts")
clearPermissionQueue("fixture")
;(window as any).missionFixture.queuePermission(root, "root-permission")
}, root)
assert.equal(await entry.locator(".mission-row-mark").getAttribute("data-mark"), "permission")
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
for (const action of ["Start", "Pause", "Resume", "Run now"] as const)
test(`${action} loads only its requested button and keeps Run now confirmation separate`, async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
const gate = deferred(), submitted = deferred()
try {
await f.change(doc => {
if (action !== "Start") doc.firstPlayedAt = Date.now()
doc.state = action === "Pause" ? "running" : "paused"
doc.scheduleActivation = { requestID: "ready_activation", expectedRevision: 0, authority: "a".repeat(64), state: "ready", targets: [], effectiveOrigin: null }
})
await page.evaluate(() => (window as any).missionFixture.refresh()); await select(page)
await page.route("**/msn_schedule/schedule", async route => {
if (route.request().method() === "POST") {
submitted.resolve(); await gate.promise
if (action !== "Run now") {
const request = route.request().postDataJSON()
f.posts.push(request)
const value = f.result()
return route.fulfill({ json: { ...value, pending: false,
document: { ...value.document, control: { ...request, pending: false } } } })
}
}
return route.fallback()
})
await button(page, action).click()
if (action === "Run now") {
const dialog = page.getByRole("dialog")
await dialog.waitFor()
assert.equal(await page.locator('.mission-action-bar button[aria-label="Run now"]').getAttribute("aria-busy"), null)
await dialog.getByRole("button", { name: action, exact: true }).click()
}
await submitted.promise
if (action !== "Run now") {
const published = page.waitForResponse(async response => new URL(response.url()).pathname.endsWith("/missions/scheduled")
&& (await response.json()).schedules?.some((row: any) => row.state === (action === "Pause" ? "paused" : "running")))
await f.change(doc => {
if (action === "Start") { changes.play(doc, "early-publication", Date.now(), []); doc.synchronization = null }
else doc.state = action === "Pause" ? "paused" : "running"
})
await page.evaluate(() => (window as any).missionFixture.refresh())
await (await published).finished()
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
}
assert.equal(await button(page, action).getAttribute("aria-busy"), "true")
assert.equal(await page.locator(".mission-action-bar [aria-busy=true]").count(), 1)
assert.equal(await page.locator(".mission-picker-selection-actions [role=status]").textContent(), action === "Resume" ? "Resuming…"
: action === "Start" ? "Starting…" : action === "Run now" ? "Starting run…" : "Saving…")
gate.resolve()
await page.waitForFunction(() => !document.querySelector(".mission-action-bar [aria-busy=true]"))
assert.equal(f.posts.length, 1); assert.equal(f.activations.length, 0)
assert.deepEqual(f.errors, [])
} finally { gate.resolve(); await page.close() }
})
test("a server activation conflict stops the spinner and releases the undispatched Play for review", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
try {
await select(page)
await page.route("**/schedule-settings", route => route.fulfill({ status: 409, json: { code: "schedule-activation-conflict" } }))
await click(page, "Play")
await page.locator(".mission-picker-selection-actions [role=status]").filter({ hasText: "The Mission changed" }).waitFor()
assert.equal(await button(page, "Start").getAttribute("aria-busy"), null)
assert.equal(await button(page, "Refresh saved request").count(), 0)
assert.equal(f.posts.length, 0); assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
for (const leave of ["selection", "remount", "connection"] as const)
test(`late activation after ${leave} preserves its proof but never continues the old Play`, async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
const gate = deferred(), submitted = deferred(), responded = deferred()
try {
await f.addSchedule("msn_other", { title: "Other schedule" })
await page.evaluate(() => (window as any).missionFixture.refresh())
await select(page)
await page.route("**/schedule-settings", async route => {
if (route.request().method() === "POST") { submitted.resolve(); await gate.promise; await route.fallback(); responded.resolve(); return }
return route.fallback()
})
await click(page, "Play"); await submitted.promise
if (leave === "selection") await page.locator(".mission-row-select").filter({ hasText: "Other schedule" }).click()
if (leave === "remount") {
await page.evaluate(() => (window as any).missionFixture.mount(false))
await page.evaluate(() => (window as any).missionFixture.mount(true))
}
if (leave === "connection") await page.evaluate(async () => {
const path = "/src/stores/instances.ts"
const module = await import(path), old = module.instances().get("fixture")
module.updateInstance("fixture", { client: Object.create(old.client) })
})
gate.resolve(); await responded.promise
await page.waitForFunction(() => !document.querySelector(".mission-action-bar [aria-busy=true]"))
assert.equal(f.activations.length, 1)
assert.equal(f.posts.filter(post => post.action === "play").length, 0)
assert.deepEqual(f.errors, [])
} finally { gate.resolve(); await page.close() }
})
test("structured server OFF after dispatch retains its exact activation and a failed read never starts Play", async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
let request: any
try {
await select(page)
await page.route("**/schedule-settings", async route => {
if (route.request().method() === "GET") return route.fallback()
request = route.request().postDataJSON()
await f.change(doc => { doc.scheduleActivation = { requestID: request.requestID, expectedRevision: request.expectedDocumentRevision,
authority: "a".repeat(64), state: "failed", targets: [], effectiveOrigin: null, errorCode: "configuration-conflict" } })
return route.fulfill({ status: 409, json: { code: "schedule-activation-refused",
refusal: { reason: "explicit-off", provenance: "environment", layer: "environment", openable: false } } })
})
await click(page, "Play")
await button(page, "Refresh saved request").waitFor()
assert.equal(await button(page, "Start").getAttribute("aria-busy"), null)
assert.equal(await button(page, "Open scheduling settings").count(), 0)
assert.equal(f.posts.length, 0)
await button(page, "Refresh saved request").click()
await button(page, "Refresh saved request").and(page.locator(":enabled")).waitFor()
assert.ok(f.reads.some(url => url.includes(`requestID=${request.requestID}`)))
assert.equal(await button(page, "Start").isDisabled(), true)
assert.equal(f.posts.length, 0, "failed recovery never replays activation or Play")
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
for (const proof of ["exact", "foreign-request", "foreign-revision"] as const)
test(`OFF refusal with ${proof} no-effect proof only releases the exact activation for explicit Start`, async () => {
const page = await browser.newPage(), f = await setup(page, { seed: true })
let request: any, attempts = 0
try {
await select(page)
await page.route("**/schedule-settings", async route => {
if (route.request().method() === "GET" || attempts++) return route.fallback()
request = route.request().postDataJSON()
return route.fulfill({ status: 403, json: { code: "schedule-activation-refused",
notApplied: { requestID: proof === "foreign-request" ? "other" : request.requestID,
expectedRevision: request.expectedDocumentRevision + (proof === "foreign-revision" ? 1 : 0) },
refusal: { reason: "explicit-off", provenance: "environment", layer: "environment", openable: false } } })
})
const refused = page.waitForResponse(response => new URL(response.url()).pathname.endsWith("/schedule-settings")
&& response.request().method() === "POST" && response.status() === 403)
await click(page, "Play"); await (await refused).finished()
await page.waitForFunction(() => !document.querySelector(".mission-action-bar [aria-busy=true]"))
assert.equal(f.doc.scheduleActivation, null)
assert.equal(f.posts.length, 0, "refusal never sends Play")
await page.evaluate(() => (window as any).missionFixture.refresh())
if (proof === "exact") {
await button(page, "Start").and(page.locator(":enabled")).waitFor()
assert.equal(await button(page, "Refresh saved request").count(), 0)
assert.equal(f.posts.length, 0, "configuration correction and refresh never start Play")
await click(page, "Play")
await button(page, "Pause").and(page.locator(":enabled")).waitFor()
assert.equal(f.posts.filter(post => post.action === "play").length, 1)
assert.notEqual(f.activation?.requestID, request.requestID)
} else {
await button(page, "Refresh saved request").click()
await button(page, "Refresh saved request").and(page.locator(":enabled")).waitFor()
assert.equal(await button(page, "Start").isDisabled(), true)
assert.equal(f.posts.length, 0, "a negative receipt cannot release a mismatched proof")
}
assert.deepEqual(f.errors, [])
} finally { await page.close() }
})
for (const scenario of ["control ACK", "recovered control", "activation ACK", "recovered activation"] as const)
test(`confirmed publication barrier retains ${scenario} across stale inventory and remount`, async () => {
const page = await browser.newPage(), activation = scenario.includes("activation")
@ -298,7 +674,6 @@ test(`confirmed publication barrier retains ${scenario} across stale inventory a
await page.evaluate(() => (window as any).missionFixture.refresh()); await started.promise
if (scenario.startsWith("recovered")) f.lost = activation ? "activation" : "play"
await click(page, "Play")
if (activation) await page.getByRole("dialog").getByRole("button", { name: "Start", exact: true }).click()
if (scenario.startsWith("recovered")) {
await page.locator(".mission-picker-selection-actions").getByRole("status").filter({ hasText: "This request is unconfirmed" }).waitFor()
await button(page, "Refresh saved request").click()
@ -354,7 +729,6 @@ test("a confirmed activation stays known through read failure and stale recovery
const stale = structuredClone(f.result().document)
f.lost = "activation"
await click(page, "Play")
await page.getByRole("dialog").getByRole("button", { name: "Start", exact: true }).click()
await page.locator(".mission-picker-selection-actions").getByRole("status").filter({ hasText: "This request is unconfirmed" }).waitFor()
let mode: "failed" | "stale" | "current" = "failed"
await page.route("**/missions/scheduled?*", route => route.fulfill(mode === "failed" ? { status: 503, json: {} }
@ -553,7 +927,7 @@ test("a positively recorded partial request offers no Check passage; its exact r
const page = await browser.newPage(), f = await setup(page, { seed: true })
try {
await select(page); f.partial = "play"; await click(page, "Play")
await button(page, "Refresh saved request").waitFor()
await button(page, "Refresh saved request").and(page.locator(":enabled")).waitFor()
const original = f.posts[0]
assert.equal(await button(page, "Check passage").count(), 0)
f.resolve()
@ -567,13 +941,14 @@ test("a positively recorded partial request offers no Check passage; its exact r
for (const negativeFirst of [true, false]) test(`cold reopen keeps the first page, cursor and original held request when selected detail is partial 503 (${negativeFirst ? "negative then positive" : "FIRST positive receipt"})`, async () => {
const page = await browser.newPage({ viewport: { width: 900, height: 240 } }), f = await setup(page, { seed: true, outsidePage: true })
const originalRevision = f.doc.revision
let originalRevision = f.doc.revision
let release!: () => void
const continuation = new Promise<void>(resolve => { release = resolve })
try {
await select(page); f.partial = "play"; await click(page, "Play")
await button(page, "Refresh saved request").waitFor()
await button(page, "Refresh saved request").and(page.locator(":enabled")).waitFor()
const original = f.posts[0]
originalRevision = f.doc.scheduleActivation!.expectedRevision + 1
await page.evaluate(() => (window as any).missionFixture.mount(false))
f.outside = true
// Keep the selected object outside the freshly read inventory while asserting

View file

@ -12,6 +12,7 @@ import { recurrenceCurrentPageInput } from "../../../server/src/missions/recurre
import { projectMissionPanel } from "../../../server/src/missions/mission-panel-projection"
import { missionPanelPage } from "../../../server/src/missions/mission-panel-page"
import { activityActorWindow, missionActivityContext } from "../../../server/src/missions/mission-activity-context"
import { BUILT_IN_COLOR_SCHEMES } from "../../src/lib/theme-scheme"
let browser: Browser, url: string
before(async () => {
@ -287,3 +288,121 @@ test("a failed mission reads as interrupted and resumes through coordinator reco
assert.deepEqual(errors, [])
} finally { await page.close() }
})
test("daily waiting, unread passage identities, restoration and paused/warning shapes use the real shared rows", async () => {
const schedule: RecurrenceSchedule = { id: "rec_marks", title: "Daily marks", revision: 1, state: "running",
clock: { time: "09:00", zone: "UTC" }, nextDueAt: Date.now() + 3_600_000, pending: null, latestResult: null,
history: [], actions: ["pause", "stop", "run-now"], controls: [] }
const { page, errors } = await open(() => [mission("other", { runState: "prepared" })], () => [], [schedule])
const entry = page.locator('[data-mission-key="schedule:rec_marks"] .mission-row-select')
const waitMark = (expected: string) => page.waitForFunction(expected =>
document.querySelector('[data-mission-key="schedule:rec_marks"] .mission-row-flag')?.getAttribute("data-mark") === expected, expected)
const refreshDaily = () => page.evaluate(async data => {
const { serverEvents } = await import("/src/lib/server-events.ts")
;(serverEvents as any).dispatchBatch([{ type: "instance.event", instanceId: "fixture",
event: { type: "rpc.codenomad.missions.scheduleChanged", data } }])
}, { scheduleID: schedule.id, revision: schedule.revision })
const success = async (id: string) => {
const result = { passageID: id, outcome: "completed" as const, dueAt: Date.now() - 2, settledAt: Date.now() - 1 }
schedule.history.push(result); schedule.latestResult = result; schedule.revision++
const published = page.waitForResponse(async response => new URL(response.url()).pathname.endsWith("/missions/recurrence")
&& (await response.json()).schedules?.some((row: any) => row.latestResult?.passageID === id))
await refreshDaily(); await (await published).finished()
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
await waitMark("done")
}
try {
await fixtureCall(page, "connectCatalog")
await entry.waitFor(); await waitMark("waiting")
assert.match(await entry.getAttribute("title") ?? "", /Waiting for scheduled run.*Next:/)
// All ready-made palettes, on idle, hover, focus and selected rows. The
// secondary-text underline supplies the shape contrast even on pale accents.
for (const scheme of BUILT_IN_COLOR_SCHEMES) {
await page.evaluate(async id => {
const module = await import("/src/lib/theme-scheme.ts")
module.applyColorScheme(module.normalizeColorScheme(id))
}, scheme.id)
for (const state of ["idle", "hover", "focus", "selected"] as const) {
if (state === "idle") { await (await inlineMissionEntry(page, "Objective other")).click(); await page.mouse.move(0, 0) }
if (state === "hover") await entry.hover()
if (state === "focus") { await page.mouse.move(0, 0); await entry.focus() }
if (state === "selected") await entry.click()
const sample = await entry.evaluate(element => {
const cell = element.querySelector(".mission-row-mark")!, icon = cell.querySelector("svg")!, line = getComputedStyle(cell, "::after")
const style = getComputedStyle(cell), svg = getComputedStyle(icon), row = getComputedStyle(element.parentElement!)
const probe = document.createElement("span"); element.append(probe)
probe.style.color = "var(--text-secondary)"; const secondary = getComputedStyle(probe).color
probe.style.color = "var(--accent-primary)"; const accent = getComputedStyle(probe).color
probe.style.color = "var(--surface-canvas)"; const surface = getComputedStyle(probe).color
const canvas = document.createElement("canvas").getContext("2d")!
canvas.fillStyle = surface; canvas.fillRect(0, 0, 1, 1)
canvas.fillStyle = row.backgroundColor; canvas.fillRect(0, 0, 1, 1)
if (row.backgroundImage !== "none" || element.parentElement!.matches(":hover")) {
probe.style.color = "var(--surface-hover-overlay)"; canvas.fillStyle = getComputedStyle(probe).color; canvas.fillRect(0, 0, 1, 1)
}
const background = [...canvas.getImageData(0, 0, 1, 1).data].slice(0, 3)
canvas.clearRect(0, 0, 1, 1); canvas.fillStyle = line.backgroundColor; canvas.fillRect(0, 0, 1, 1)
const foreground = [...canvas.getImageData(0, 0, 1, 1).data].slice(0, 3)
probe.remove()
return { width: style.width, height: style.height, lineWidth: line.width, lineHeight: line.height, lineTop: line.top,
lineColor: line.backgroundColor, secondary, accent, color: svg.color, opacity: svg.opacity,
animation: svg.animationName, lineOpacity: line.opacity, foreground, background }
})
assert.deepEqual([sample.width, sample.height, sample.lineWidth, sample.lineHeight, sample.lineTop], ["16px", "20px", "8px", "1px", "19px"])
assert.equal(sample.lineColor, sample.secondary); assert.equal(sample.color, sample.accent)
assert.equal(sample.opacity, "1"); assert.equal(sample.lineOpacity, "1"); assert.equal(sample.animation, "none")
const lum = (rgb: number[]) => rgb.map(v => v / 255).map(v => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4)
.reduce((sum, v, i) => sum + v * [.2126, .7152, .0722][i], 0)
const [a, b] = [lum(sample.foreground), lum(sample.background)].sort((a, b) => b - a)
assert.ok((a + .05) / (b + .05) >= 3, `${scheme.id}/${state}: ${JSON.stringify(sample)}`)
}
}
await success("pas_A")
await fixtureCall(page, "flush")
await page.reload()
await fixtureCall(page, "connectCatalog")
await entry.waitFor(); await waitMark("done")
assert.equal(await entry.getAttribute("aria-current"), "true", "selection restores, unread result remains")
await entry.click(); await waitMark("waiting")
await success("pas_B")
// Explicit Mark as read also works without selecting a schedule.
await page.locator('[data-mission-key="schedule:rec_marks"] .session-item-expander').click({ button: "right" })
await success("pas_B_next")
await page.getByRole("menuitem", { name: "Mark as read", exact: true }).click()
assert.equal(await mark(page, "Daily marks"), "done", "the open menu acknowledges B, not the later passage")
assert.deepEqual(await page.evaluate(async () => {
const { scheduleSuccessSeen } = await import("/src/stores/mission-view-state.ts")
const scope = JSON.stringify(["fixture", "project"])
return ["pas_B", "pas_B_next"].map(id => scheduleSuccessSeen(scope, "daily", "rec_marks", id))
}), [true, false])
await page.locator('[data-mission-key="schedule:rec_marks"] .session-item-expander').click({ button: "right" })
await page.getByRole("menuitem", { name: "Mark as read", exact: true }).click()
await waitMark("waiting")
// A result arriving while the panel is hidden stays unread on returning.
await page.evaluate(() => (window as any).missionFixture.active(false))
const result = { passageID: "pas_C", outcome: "completed" as const, dueAt: Date.now() - 2, settledAt: Date.now() - 1 }
schedule.history.push(result); schedule.latestResult = result; schedule.revision++
await page.evaluate(() => (window as any).missionFixture.active(true))
await waitMark("done")
await entry.click(); await waitMark("waiting")
await page.emulateMedia({ reducedMotion: "reduce" })
schedule.pending = { passageID: "pas_D", status: "running" }; schedule.revision++
await refreshDaily(); await waitMark("working")
const motion = await entry.locator("svg").evaluate(element => {
const style = getComputedStyle(element); return [style.animationDuration, style.animationIterationCount]
})
assert.ok(parseFloat(motion[0]) <= .00001); assert.equal(motion[1], "1")
schedule.state = "paused"; schedule.nextDueAt = null; schedule.revision++
await refreshDaily(); await waitMark("paused")
assert.equal(await entry.locator("svg rect").count(), 2, "Pause has two bars")
schedule.state = "interrupted"; schedule.pending.status = "uncertain"; schedule.revision++
await refreshDaily(); await waitMark("interrupted")
assert.equal(await entry.locator("svg path").count(), 3, "interruption has a warning triangle and exclamation")
schedule.state = "running"; schedule.nextDueAt = Date.now() + 3_600_000; schedule.revision++
await refreshDaily(); await waitMark("unconfirmed")
assert.match(await entry.getAttribute("title") ?? "", /State unconfirmed/)
schedule.state = "stopped"; schedule.nextDueAt = null; schedule.revision++
await refreshDaily(); await waitMark("idle")
assert.deepEqual(errors, [])
} finally { await page.close() }
})

View file

@ -74,8 +74,9 @@ export async function writeFixtureServiceRegistration(env, { url, pid, version,
// `registry` points the daemon's package installs at a loopback fake npm registry
// (`npm_config_registry`), so package fixtures never reach the public registry.
// `service` enables native persisted calendar wakes in this owned child only.
// `flags` sets OPENCODE_FLAGS in the owned daemon for native flag qualification.
// `run` also receives the daemon's `env`, the environment of every other fixture-owned child.
export async function withProductRuntime(cli, prepare, run, { projectConfig = false, registry, service = false } = {}) {
export async function withProductRuntime(cli, prepare, run, { projectConfig = false, registry, service = false, flags } = {}) {
assert(cli && path.isAbsolute(cli), "Pass an absolute isolated CLI executable path")
assert(!registry || /^http:\/\/127\.0\.0\.1:\d+\/?$/.test(registry), "A fixture registry must be loopback")
const root = await mkdtemp(path.join(await fixtureParent({ projectConfig }), "product-native-"))
@ -84,7 +85,7 @@ export async function withProductRuntime(cli, prepare, run, { projectConfig = fa
...(registry ? { npm_config_registry: registry, npm_config_audit: "false", npm_config_fund: "false" } : {}),
OPENCODE_CONFIG_DIR: path.join(root, "config"), OPENCODE_DB: path.join(root, "fixture.db"),
...(projectConfig ? {} : { OPENCODE_CONFIG_PROJECT_DISABLE: "1" }), OPENCODE_DISABLE_MODELS_FETCH: "1", OPENCODE_DISABLE_FFF: "1",
OPENCODE_SERVER_PASSWORD: password })
OPENCODE_SERVER_PASSWORD: password, ...(flags === undefined ? {} : { OPENCODE_FLAGS: flags }) })
await mkdir(env.OPENCODE_CONFIG_DIR)
const configuration = await prepare({ root, configDirectory: env.OPENCODE_CONFIG_DIR })
const requests = []

View file

@ -1,6 +1,6 @@
// Real native config discovery/watcher, no schedule creation or model request.
import assert from "node:assert/strict"
import { readFile, rm, writeFile } from "node:fs/promises"
import { mkdir, readFile, rm, writeFile } from "node:fs/promises"
import path from "node:path"
import { setTimeout as delay } from "node:timers/promises"
import { parse } from "jsonc-parser"
@ -10,10 +10,19 @@ import { SubagentDepthSettings } from "../packages/server/src/opencode/subagent-
import { NativeScheduleCapabilityReader } from "../packages/server/src/opencode/native-schedule-capability.ts"
import { editMissionExperimental, inheritedMissionExperimental, nativeSettingExpectation } from "../packages/server/src/opencode/native-experimental-settings.ts"
import { NativeScheduleSettingsActivation } from "../packages/server/src/opencode/native-schedule-settings-activation.ts"
import { DesktopPluginLifecycle } from "../packages/server/src/opencode/desktop-plugin-lifecycle.ts"
import { resolveDesktopPluginPaths } from "../packages/server/src/opencode/desktop-plugin-paths.ts"
import { CODENOMAD_MISSIONS_RPC } from "../packages/server/src/missions/rpc.ts"
await withProductRuntime(process.argv[2], async ({ configDirectory }) => {
await writeFile(path.join(configDirectory, "opencode.jsonc"), '{"experimental":{"subagent_depth":2,"schedules":true}}\n')
}, async ({ root, connection, requests }) => {
assert.equal((await connection.client.server.info()).version, "2.3.0")
const plugin = new DesktopPluginLifecycle("missions")
const paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: process.argv[2] })
assert.ok(paths.config.startsWith(root))
await plugin.start(paths)
try {
const manager = {
get: () => ({}), getSharedServiceConnection: async () => connection,
getServiceDirectoryForPath: async (_id, directory) => directory === root ? root : undefined,
@ -32,6 +41,10 @@ await withProductRuntime(process.argv[2], async ({ configDirectory }) => {
do { if (await check()) return; await delay(100) } while (Date.now() < deadline)
throw Error(`Native watcher did not acknowledge ${description}`)
}
await until(async () => (await connection.client.plugin.list({ location })).data.some(entry =>
entry.id === "codenomad.missions" && entry.state.status === "active"), "private Missions plugin")
assert.deepEqual(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({}, { location }),
{ enabled: true, provenance: "experimental-block" })
const initial = await depths.read("fixture", location)
assert.equal(initial.effectiveDepth, 2)
assert.deepEqual((await schedules.read("fixture", location)).api, { available: true })
@ -72,8 +85,14 @@ await withProductRuntime(process.argv[2], async ({ configDirectory }) => {
await until(async () => (await connection.client.config.get({ location })).some(entry =>
entry.type === "document" && entry.path === globalFile && entry.info.experimental?.schedules === false), "global OFF before activation")
const activate = () => new NativeScheduleSettingsActivation(controls, manager)
await assert.rejects(activate().prepare("fixture", location), error =>
error.code === "schedule-activation-refused" && error.refusal.path === globalFile)
await writeFile(globalFile, '{"experimental":{"subagent_depth":2}}\n')
await until(async () => (await connection.client.config.get({ location })).some(entry =>
entry.type === "document" && entry.path === globalFile && entry.info.experimental?.schedules === undefined), "global OFF cleared")
const globalBefore = await readFile(globalFile, "utf8")
const plan = await activate().prepare("fixture", location)
assert.deepEqual(plan.targets.map(item => item.scope), ["global", "project"])
assert.deepEqual(plan.targets.map(item => item.scope), ["project"])
const intent = { ...plan, targets: plan.targets.map(target => ({ ...target, attempted: false, acknowledged: false })) }
const intentFile = path.join(root, "activation-intent.json")
const save = () => writeFile(intentFile, JSON.stringify(intent))
@ -83,15 +102,15 @@ await withProductRuntime(process.argv[2], async ({ configDirectory }) => {
prepared: async () => { await save() },
attempting: async scope => { intent.targets.find(item => item.scope === scope).attempted = true; await save() },
acknowledged: async scope => {
if (scope === "global" && lose) { lose = false; throw Error("lost activation ACK") }
if (scope === "project" && lose) { lose = false; throw Error("lost activation ACK") }
intent.targets.find(item => item.scope === scope).acknowledged = true; await save()
},
ready: async origin => { assert.equal(origin, file); ready = true },
}
await assert.rejects(activate().apply("fixture", location, structuredClone(intent), journal), /lost activation ACK/)
assert.equal(ready, false)
assert.equal(parse(await readFile(globalFile, "utf8")).experimental.schedules, true)
assert.equal(parse(await readFile(file, "utf8")).experimental.schedules, undefined)
assert.equal(await readFile(globalFile, "utf8"), globalBefore)
assert.equal(parse(await readFile(file, "utf8")).experimental.schedules, true)
await activate().apply("fixture", location, JSON.parse(await readFile(intentFile, "utf8")), journal)
assert.equal(ready, true)
assert.ok(intent.targets.every(target => target.acknowledged))
@ -109,7 +128,63 @@ await withProductRuntime(process.argv[2], async ({ configDirectory }) => {
await until(async () => (await schedules.read("fixture", location)).enabled, "schedule activation preserving existing depth default")
assert.equal((await depths.read("fixture", location)).effectiveDepth, depthBefore)
assert.equal(requests.length, 0)
console.log("PASS native 2.2.3 capability, whole-block precedence, both writer orders, depth 0/removal, effective watcher read, explicit OFF, BOM/EOL/comments, ambiguous JSON/JSONC; zero provider HTTP")
console.log("PASS two-document prepared activation, durable fixture-port intent/attempts, lost global ACK adoption before project write and positive effective native acknowledgement")
const enabledPlan = await activate().prepare("fixture", location)
assert.deepEqual(enabledPlan.targets, [])
assert.equal(await readFile(globalFile, "utf8"), globalBefore)
console.log("PASS native 2.3.0 Flag RPC, whole-block precedence, both writer orders, depth 0/removal, effective watcher read, explicit global/project OFF, BOM/EOL/comments, ambiguous JSON/JSONC; zero provider HTTP")
console.log("PASS project-only activation, durable intent/attempts, lost project ACK observation, positive native acknowledgement and zero-target already-ON plan")
console.log("PASS schedule activation preserves the effective native depth of an existing project experimental block")
} finally { await plugin.stop() }
}, { projectConfig: true })
// Each case owns a fresh daemon: its environment is independent of the backend's.
for (const scenario of [
{ name: "environment OFF over configured ON", flags: "fixture,-schedules", global: { schedules: true },
enabled: false, provenance: "environment", refused: true },
{ name: "environment ON", flags: "fixture,schedules", global: {},
enabled: true, provenance: "environment" },
{ name: "all-flags below a project block", global: { all_flags: true }, project: { todo: true },
enabled: true, provenance: "all-flags" },
{ name: "all-flags false falls through to the channel default", global: { all_flags: false }, project: {},
enabled: false, provenance: "channel-default" },
]) {
await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
await writeFile(path.join(configDirectory, "opencode.jsonc"), JSON.stringify({ experimental: scenario.global }))
if (scenario.project) {
await mkdir(path.join(root, ".opencode"))
await writeFile(path.join(root, ".opencode", "opencode.jsonc"), JSON.stringify({ experimental: scenario.project }))
}
}, async ({ root, connection, requests }) => {
const plugin = new DesktopPluginLifecycle("missions"), location = { directory: root }
const paths = await resolveDesktopPluginPaths(connection, { kind: "host", platform: process.platform, binary: process.argv[2] })
assert.ok(paths.config.startsWith(root))
await plugin.start(paths)
try {
const deadline = Date.now() + 15_000
while (!(await connection.client.plugin.list({ location })).data.some(entry =>
entry.id === "codenomad.missions" && entry.state.status === "active")) {
assert.ok(Date.now() < deadline, "Private flag plugin unavailable")
await delay(100)
}
assert.deepEqual(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({}, { location }),
{ enabled: scenario.enabled, provenance: scenario.provenance })
const manager = { get: () => ({}), getSharedServiceConnection: async () => connection,
getServiceDirectoryForPath: async (_id, directory) => directory === root ? root : undefined,
ownsLocation: async (_id, selected) => selected.directory === root, getWorktreeIdentityForPath: async () => "flag-fixture",
getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix",
getServiceWslDistro: () => undefined, getHostPathForServicePath: async (_id, value) => value }
const controls = new PluginControls({ workspaceManager: manager, worktreeDeletionFence: { enter: () => () => {} }, logger: {} })
const activate = new NativeScheduleSettingsActivation(controls, manager)
const globalFile = path.join(paths.config, "opencode.jsonc"), original = await readFile(globalFile, "utf8")
if (scenario.refused) await assert.rejects(activate.prepare("fixture", location), error =>
error.code === "schedule-activation-refused" && error.refusal.layer === "environment")
else {
const plan = await activate.prepare("fixture", location)
assert.deepEqual(plan.targets.map(target => target.scope), scenario.enabled ? [] : ["project"])
}
assert.equal(await readFile(globalFile, "utf8"), original)
assert.equal(requests.length, 0)
console.log(`PASS native ${scenario.name}: exact provenance, correct plan/refusal, zero configuration writes/provider HTTP`)
} finally { await plugin.stop() }
}, { projectConfig: true, flags: scenario.flags })
}

View file

@ -24,13 +24,13 @@ await mkdir(scratch, { recursive: true })
Object.assign(process.env, { TEMP: scratch, TMP: scratch, LOCALAPPDATA: scratch, APPDATA: scratch })
await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
for (const key of ["HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", "XDG_DATA_HOME"]) process.env[key] = root
await writeFile(path.join(configDirectory, "opencode.jsonc"), '{"experimental":{"schedules":false,"subagent_depth":2},"fixturePrivate":"DO-NOT-PERSIST"}\n')
await writeFile(path.join(configDirectory, "opencode.jsonc"), '{"experimental":{"subagent_depth":2},"fixturePrivate":"DO-NOT-PERSIST"}\n')
await mkdir(path.join(root, ".opencode"))
await writeFile(path.join(root, ".opencode", "opencode.jsonc"), '{"experimental":{"subagent_depth":8}}\n')
return { update: "disable", snapshots: false, permissions: [{ action: "*", resource: "*", effect: "allow" }] }
}, async ({ client, root, requests, connection }) => {
const info = await client.server.info()
assert.equal(info.version, "2.2.3")
assert.equal(info.version, "2.3.0")
rememberRuntime(connection.endpoint, { version: info.version, pid: info.pid, discovery: "info" })
const manager = new WorkspaceManager({ rootDir: root, logger: pino({ level: "silent" }), eventBus: new EventBus(),
settings: { getOwner: () => ({ environmentVariables: {} }), readEnvironmentForAdmission: async () => ({}) },
@ -77,15 +77,18 @@ await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
const executor = new NativeScheduleSettingsActivation(controls, manager)
let lose = true
registerMissionRoutes(app, { workspaceManager: manager, worktreeDeletionFence: fence, scheduleSettingsActivation: {
prepare: (...args) => executor.prepare(...args), apply: (id, loc, intent, journal) => executor.apply(id, loc, intent, {
prepare: (...args) => executor.prepare(...args), verify: (...args) => executor.verify(...args),
apply: (id, loc, intent, journal) => executor.apply(id, loc, intent, {
...journal, acknowledged: async (scope, digest) => {
await journal.acknowledged(scope, digest)
if (scope === "global" && lose) { lose = false; throw Error("lost native activation reply") }
if (scope === "project" && lose) { lose = false; throw Error("lost native activation reply") }
},
}),
} })
const url = `/api/workspaces/${workspace.id}/missions/msn_activation_native/schedule-settings`
const payload = { requestID: "activate-original", expectedDocumentRevision: 0 }
const globalFile = path.join(paths.config, "opencode.jsonc")
const globalBefore = await readFile(globalFile, "utf8")
const first = await app.inject({ method: "POST", url, payload })
assert.equal(first.statusCode, 503, first.body)
const read = await app.inject({ method: "GET", url: `${url}?requestID=activate-original&expectedDocumentRevision=0` })
@ -93,7 +96,8 @@ await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
receipt.partial = read.json().document
assert.equal(receipt.partial.state, "paused"); assert.equal(receipt.partial.scheduleActivation.state, "failed")
assert.equal(receipt.partial.scheduleActivation.targets[0].acknowledged, true)
assert.equal(receipt.partial.scheduleActivation.targets[1].attempted, false)
assert.equal(receipt.partial.scheduleActivation.targets.length, 1)
assert.equal(receipt.partial.scheduleActivation.targets[0].scope, "project")
const retry = await app.inject({ method: "POST", url, payload })
assert.equal(retry.statusCode, 200, retry.body)
receipt.ready = retry.json().document
@ -102,10 +106,15 @@ await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
const repeated = await app.inject({ method: "POST", url, payload })
assert.equal(repeated.statusCode, 200, repeated.body)
assert.equal(repeated.json().document.revision, receipt.ready.revision)
const fresh = await app.inject({ method: "POST", url, payload: { requestID: "fresh-after-ready",
expectedDocumentRevision: receipt.ready.revision } })
assert.equal(fresh.statusCode, 200, fresh.body)
assert.deepEqual(fresh.json().document, receipt.ready)
assert.equal(await readFile(globalFile, "utf8"), globalBefore)
assert.equal(requests.length, 0)
assert.ok(!JSON.stringify(receipt).includes("DO-NOT-PERSIST"))
receipt.status = "passed"
console.log("PASS production HTTP + native document RPC/CAS: both config files, durable attempts/ACKs, lost reply reconciliation, positive native read, paused throughout, zero model HTTP")
console.log("PASS native 2.3.0 production HTTP + document RPC/CAS: project-only effect, unchanged global config, lost reply observation, native Flag readiness, retained ready proof, paused throughout, zero model HTTP")
} catch (error) { receipt.status = "failed"; receipt.error = error.message; throw error }
finally { await plugin.stop(); await app.close(); await manager.shutdown()
await writeFile(path.join(root, "schedule-activation-receipt.json"), JSON.stringify(receipt, null, 2)) }