diff --git a/.gitignore b/.gitignore index 363f851..2b3c7c1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ .DS_Store node_modules/ notes/ +.impeccable/mocks/ +.impeccable/questions/ diff --git a/.impeccable/briefs/manager.md b/.impeccable/briefs/manager.md new file mode 100644 index 0000000..77f810f --- /dev/null +++ b/.impeccable/briefs/manager.md @@ -0,0 +1,50 @@ +# Surface brief: manager list + job details + +Mode: Operate. Visual authority: Tern itself (user's theme, Tern view nodes); no new world. Code-led. +Approved by Brendan 2026-10-13 after shape (sketch: .impeccable/mocks/decision/hybrid.png). + +## Job and audience +Tern users checking agent work. First question answered: what happened since I last looked; then what needs me; then what runs next. Typical 3–10 jobs, rarely >20. + +## Structure +- **Default list layout: Timeline.** Results since the user last looked above a "now" rule; every active recurring job exactly once below it, at its next run (time-ordered). The now rule appears only when there are results above it or runs in progress at it; sections with no rows are never shown. When nothing is new, a single muted quiet line follows the header ("Nothing new since 08:00." / "Nothing has run yet. runs first, 18:00 (in 9h 52m)."). Running / needs-you runs sit on the now rule (running job shows "next HH:MM" inline instead of a second row). One-shot jobs below until they run. Bottom group: paused, needs fixing, manual-only. +- **Classic layout (setting):** today's grouped job list (Needs you, Needs fixing, Running, Upcoming, Paused & finished), with the shared row/toolbar fixes. +- **Job details:** layout-3 detail: header (name, state, next run), latest result line called out (failure tone when failed), settings as key/value, run list with one-line summary, duration, cost. No chart. +- **Width:** at ≥ ~150 cols (cx.cols; tune with screenshots) details sit beside the list and follow selection, in both layouts. Narrower: Enter opens details full-width. + +## New / seen +- New results highlighted until visible in the open manager briefly, then fade (default). Setting "New results": fade once seen | stay until cleared. +- A failure keeps its ✗ on the job until its next success. +- Last-looked marker advances when leaving the manager. +- Backlog: ≤ ~8 new results → one row each. More → one row per job ("PR triage · 84 runs since Mon · 70 ✓ · 12 ↷ · 2 ✗ · latest …"); failures and needs-you always get their own rows above. Rows do NOT expand; opening the job shows all its runs. "Mark all seen" key and button appear only when something is unseen. Counts tracked independently of the 50-run retention; run lists say "latest 50 of N" when truncated. + +## Toolbar +Job actions and global actions are two groups of the same buttons, apart by space, with the selected job named above the job group; keys shown inside buttons; Delete and Pause all last in their groups, in muted text; separate hint row removed. Forms and dialogs use the same buttons. + +## Settings +Manager Settings sheet gains a "Manager" page: Layout (Timeline default | Classic job list), New results (fade once seen | stay until cleared). Palette command "Agent Scheduler: Settings". + +## Styling (approved 2026-10-13: "B with A's markers"; mocks .impeccable/mocks/style/) +- UI font (--sans) for names/summaries; mono with tabular digits for times/durations/costs. +- New results: thin left-edge marker (accent; --bad for failures), not full-row wash; fades once seen. +- Selection: accent outline + light tint; glides between rows (spring-follow). +- Now rule: accent rule (no glow) with a filled "now · HH:MM" pill; countdown digits roll (-stencil-text-effect: numeric). +- Running row on the now rule: --live gradient wash + slow pulsing dot. +- Details: raised card (--card, --r-card, soft shadow); failure called out in a bordered --bad tint block + "Last run failed" badge; settings in a recessed --l1 block. +- Dock: one outlined button style everywhere (no tray); the Enter/default action is accent-tinted. +- All motion off under prefers-reduced-motion. Light theme: times use --t2 not --t3; status glyphs slightly larger. Verify against 2+ real omp themes in Tern. + +## Time format +Setting "Time format": Automatic (default; follow system, 24-hour fallback) | 12-hour | 24-hour. Centralize all time formatting in one helper (lib currently has ~29 os.date calls); applies to manager, notifications, status line, Carly text. Parsing already accepts both. + +## Keep +All current keys, section vocabulary, Tern theme/components, plain-English copy. + +## Anti-goals +No charts/stat tiles (remove the run-duration bar chart). No inline expanding rows. + +## Also fix +Missed ≠ failed in counts; `0 */2 * * *` reads "every 2 hours"; "Invalid job id.." double period; "d d" spacing. + +## Open +Exact width cutoff (tune on screenshots). diff --git a/CHANGELOG.md b/CHANGELOG.md index 3473cfd..5ecbd47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,37 @@ User-facing changes per release. Update with `tern plugin install github.com/bmanturner/tern-agent-scheduler --force`. +## 0.4.0 (2026-10-16) + +Built and tested on Tern 0.9.0. **Update Tern to 0.9.0:** on an older Tern, the manager asks you to check setup and Settings › Status flags the Tern version. + +### Added + +- **Timeline**, the manager's new default view: results since you last looked, a **Now** rule, then each active job at its next run, with paused, manual-only and broken jobs at the bottom. A run in progress sits on the Now rule. When nothing is new, one line says so ("Nothing new since 08:00."), and on a first visit it names the first run. More than eight new results fold into one summary per job, with failures still listed one by one. **Settings › Display › Layout** brings back the **Classic job list**. +- In panes 150 columns or wider, a job's details sit beside the list and follow the selection. They call out the latest result and list each run on one line with its outcome, duration and cost. +- New results fade after three seconds, or stay highlighted until you mark them seen (**Settings › Display › New results**). `s` or **Mark all seen** clears them, and a failure marker stays on the job until its next success. +- **Time format**: Automatic (follows your system, with a 24-hour fallback), 12-hour or 24-hour, used for schedules, previews, notifications, the status line and Carly. Until now times were always 24-hour. +- **Agent Scheduler: Settings** in the palette. + +### Changed + +- Settings is one page, **Agent Scheduler Settings**, with Status, Display, Where runs start, Limits and Setup sections. **Status** says whether Agent Scheduler is ready to run jobs, lists each problem with what to do about it, and **Check again** checks in place. The Check setup dialog is gone; what it said about when jobs run is now in Help. +- In Settings, Time format and Layout are buttons (←/→ also switch them), number rows take a typed value after Enter, a rejected value stays in its field with the reason above it, and a changed setting shows a dot and **Reset**. Tab and Shift+Tab move between rows; a key legend sits at the bottom. +- Help (`?`) groups the keys into The selected job, Move and open, and All jobs, written the way you type them (`P` is shift+p). +- One look for every button in the manager, the job form and its dialogs, each with its key inside. The default action, the one Enter does, is highlighted. +- On the job form's **Only when** page, a condition that's off shows only its switch, and its settings appear when you turn it on (nothing you set is lost). **Check now** appears once a condition is on. +- With no jobs, the manager offers its examples under a "Start from an example" heading; Enter opens the selected one as a draft that's saved only when you save it. +- A job's history is one line per run instead of a chart. + +### Fixed + +- On Tern 0.9.0, a scheduled run no longer ends as "Closed by you." a few seconds after it starts while omp keeps running in its tab. Agent Scheduler didn't recognise its own run tabs in the shape Tern 0.9.0 lists them. +- Runs missed while your computer was asleep no longer count as failures. +- Schedules with a cron step read naturally ("Every 2 hours"). +- Every run is listed at its start time, and countdowns round up to the minute. +- With window glass on, Settings no longer lets the job list show through. +- "Invalid job id." no longer ends in two periods. + ## 0.3.2 (2026-10-13) Built and tested on Tern 0.8.3. diff --git a/PRODUCT.md b/PRODUCT.md new file mode 100644 index 0000000..96d1979 --- /dev/null +++ b/PRODUCT.md @@ -0,0 +1,67 @@ +# Product + + + +## Platform + +web + +"web" here means Tern's own view engine, not a browser: the plugin draws its screens with Tern view nodes (`tern.ui`), an HTML-like element subset and a CSS subset that Tern renders natively. There is no JavaScript, no browser layout engine and no custom fonts. The plugin runs on Tern desktop for macOS and Linux. The manager also opens in Tern's web client and on iPhone/iPad, but palette commands, the status line, needs-you notices and Carly tools need a desktop window. + +## Users + +Primary users are Tern closed-beta users: power users who live in the terminal and already run omp agents in Tern panes. They want agent work to happen on a schedule while they keep working, and to check in on it without leaving Tern. The plugin's author is one of these users, but design decisions favor the wider Tern user base over personal preference. + +They open the manager for two reasons equally often: to see what ran, what failed and what needs them, and to create or adjust jobs. + +## Product Purpose + +Agent Scheduler gives Tern the scheduled agent tasks that the Claude and ChatGPT desktop apps already have, built natively into Tern. On top of that it adds things terminal-heavy users expect: cron and plain-English schedules, conditions that hold a run back (new commits, hours, run and spend limits, a user script, an AI check), and runs that land in real Tern tabs. + +Success means Stencil adopts it into Tern. To get there it has to be trusted with unattended work and used by a large share of Tern users. + +## Positioning + +It's meant to match what other tools already offer, not to stand apart from them: what the Claude and ChatGPT desktop apps do for scheduled tasks, delivered inside Tern and fitting Tern's way of working. Where it goes further, it's because terminal power users need it: each run is a real omp session in a Tern tab that can be opened and continued, conditions decide whether a due run is worth starting, and all jobs, prompts and history stay on the user's machine. + +## Operating Context + +- A job is a saved prompt plus a schedule, a folder, an omp role, an approval mode and a time limit. A run is one execution of it. +- Runs start in a background **Scheduled runs** session without taking focus. The user hears about them through the status line, toasts and desktop notifications when something needs them or fails. +- Jobs run only while Tern's session service is running. Nothing runs while the computer is asleep. Missed runs follow the job's catch-up setting. +- The manager is a Tern block. The palette has Open manager, New job, Run a job now and Go to run that needs you. Carly, Tern's assistant, can create, list, run and pause jobs. +- Remote hosts each keep their own jobs and manager. + +## Capabilities and Constraints + +- **Terminology** (use exactly these words): job, run, needs you, needs fixing, Hands-off, Only when, skipped, missed, quiet. +- **Agent support:** omp only for now. UI wording should stay agent-neutral so other agents can be added later without rewriting copy. Undecided: which agents, and when. +- **Security model:** only the host half creates or changes jobs and settings. Windows send allowlisted intents only. Hands-off is the default approval mode and always shows its warning. +- **Platform limits:** window-half calls have a 50 ms budget. Views use Tern's built-in node kinds and its CSS subset. Plugin CSS must be scoped to the plugin's surfaces. +- **Data:** stored in Tern's plugin data folder. The plugin makes no network requests of its own. + +## Brand Commitments + +- **Looks like part of Tern.** Follow the user's Tern theme through Tern's theme variables and semantic tones. No separate brand, palette or logo. +- **Keyboard-first, never keyboard-only.** Everything doable by key must also be clickable. +- **Plain-English voice.** Sentence case, short, no jargon, no exclamation marks, no emoji in copy. Errors say what happened, then what to do. Times are concrete and local (`Mon 12 Oct 09:00`), in 24-hour or 12-hour form per the user's Time format setting (Automatic follows the system). + +## Evidence on Hand + +- README (`README.md`) and the changelog (`CHANGELOG.md`). +- Design history in `docs/DESIGN.md` and `docs/design/` (ux.md, decisions.md, engine.md, launch.md, architecture.md). These are historical; the code and README win where they disagree. +- Screenshots in `docs/screenshots/`. +- A UI audit with screenshots of every manager screen in dark, light and narrow layouts (seeded test data, not real usage): `~/Dev/personal/tern-agent-scheduler-audit/`. +- The public GitHub repo has 13 stars. There are no usage numbers, testimonials or adoption data yet; don't invent any. + +## Product Principles + +1. **Trust before features.** Users have to be willing to leave unattended runs going, so every run's outcome, cost and reason is visible, and nothing fails or gets skipped silently. +2. **Outcomes and authoring are equal.** The manager has to make "what happened / what needs me" and "create or change a job" both fast. Neither should be buried behind the other. +3. **Never steal focus.** Runs start in the background. The user goes to a run only when they choose to. +4. **Native to Tern.** It should feel like a part of Tern that Stencil could ship as-is: Tern's theme, Tern's components, Tern's keyboard conventions. +5. **Parity first, power second.** Cover what other desktop agent apps offer for scheduled tasks plainly, then add terminal-power-user depth without making the simple path harder. + +## Accessibility & Inclusion + +Status is never shown by color alone: every state has a glyph and words. Tern's simulated preferences (reduced motion, increased contrast, differentiate without color) should be respected where the plugin's views are affected. No other product-specific requirement has been established. diff --git a/README.md b/README.md index cabd168..5a2bea7 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,10 @@ Scheduled [omp](https://github.com/can1357/oh-my-pi) agent runs for [Tern](https://stencil.so/tern): cron, presets, plain English or one-shot, each launched into its own tab while you keep working. -![The Agent Scheduler manager: a run in progress showing its model, tool calls, cost, running time and the tool it is using now, above four upcoming jobs with their schedules, last results and next run times](docs/screenshots/manager.png) + + + The Agent Scheduler manager's timeline: results since you last looked (a failed test run, a quiet audit and finished runs with their summaries) above the Now rule, a run in progress on it with its model, tool calls, cost and current tool, then the next runs and a paused job + Write a prompt, pick a folder and say when ("weekdays 9am", "every 2h", `0 9 * * 1-5`). At that time Agent Scheduler starts omp in a background **Scheduled runs** session, watches it, and records how the run ended. Your focus never moves. The status line, toasts and desktop notifications tell you when something needs you or fails, and every run keeps its session so you can open it and carry on. @@ -20,19 +23,22 @@ A job can also wait for something worth doing: new commits on a branch, working ## Install -Built and tested on Tern 0.8.3. Runs on macOS or Linux (not Windows yet) and needs [omp](https://github.com/can1357/oh-my-pi). On Linux, desktop notifications use `notify-send` (libnotify). +Built and tested on Tern 0.9.0. Runs on macOS or Linux (not Windows yet) and needs [omp](https://github.com/can1357/oh-my-pi). On Linux, desktop notifications use `notify-send` (libnotify). ```sh tern plugin install github.com/bmanturner/tern-agent-scheduler ``` -Press `ctrl+alt+shift+m` to open the manager (`ctrl+alt+shift+s` also works on macOS). With no jobs yet, it offers three examples you can save as they are or edit first. To update, run the install command again with `--force`; [CHANGELOG.md](CHANGELOG.md) lists what changed. +Press `ctrl+alt+shift+m` to open the manager (`ctrl+alt+shift+s` also works on macOS). With no jobs yet, it offers three examples to start from; Enter opens one in the New job form, and nothing is saved until you save it. To update, run the install command again with `--force`; [CHANGELOG.md](CHANGELOG.md) lists what changed. ## Create a job Press `n` in the manager, or `ctrl+alt+shift+j` anywhere. The folder starts as the focused pane's directory. -![The New job form: name, prompt, a schedule typed as "every friday 4pm" with a preview of the next three runs, folder and role](docs/screenshots/new-job.png) + + + The New job form: name, prompt, a schedule typed as "every friday 4pm" with a preview of the next runs, folder and role + | Field | What it sets | | --- | --- | @@ -93,11 +99,18 @@ Your own check runs in the job's folder with a 30 s limit and gets a JSON file d ## The manager -Jobs are grouped into **Needs you**, **Needs fixing**, **Running**, **Upcoming** and **Paused & finished**. A run in progress shows its model, tool calls, cost and running time, with what it is doing now underneath. +The default **Timeline** lists the results since you last looked, a **Now** rule, then each active job at its next run; paused, manual-only and broken jobs sit at the bottom. A run in progress sits on the Now rule, which only appears when something is above it or on it. When nothing is new, one line says so ("Nothing new since 08:00."), and on a first visit it names the first run ("Nothing has run yet. pr-review-digest runs first, 18:00 (in 9h 52m)."). More than eight new results fold into one summary per job, with failures still listed one by one. -Press `enter` on a job for its details: the prompt, a bar per recent run (red for failures), and each run's summary, duration and cost. +At 150 columns or wider, a job's details sit beside the list and follow the selection; Enter moves to its runs and Escape returns to the jobs. In narrower panes, Enter opens the details full-width. **Settings › Display › Layout** brings back the **Classic job list**, grouped into Needs you, Needs fixing, Running, Upcoming and Paused & finished. -![A job's detail view: schedule, folder, safety and the prompt, then a bar chart of recent run durations with one failed run in red, and the run list with summaries, durations and costs](docs/screenshots/job-detail.png) + + + A wide manager with the timeline on the left and the selected job's details on the right: its latest result, schedule, folder, role and prompt, and one line per run with its outcome, duration and cost + + +Job details show the latest result, the job's settings and prompt, and one line per run with its outcome, duration and cost; failed and missed runs are counted separately. **Settings › Display › Time format** picks **Automatic** (your system's 12- or 24-hour preference, else 24-hour), **12-hour** or **24-hour** for every time Agent Scheduler shows, including notifications, the status line and Carly. + +New results fade three seconds after you open the manager; choose **Stay until marked seen** under **Settings › Display › New results** to keep them highlighted. Press `s` or click **Mark all seen** to clear them; the button and key only appear when there is something to mark. A failure marker stays on the job until its next success. | Key | Does | | --- | --- | @@ -108,9 +121,10 @@ Press `enter` on a job for its details: the prompt, a bar per recent run (red fo | `o` | Open the run's tab, or resume its session if the tab is gone | | `space` | Pause or resume | | `d` `d` | Delete (`u` undoes it for 10 s) | -| `?` | Every key | +| `s` | Mark all results seen | +| `?` | Help: every key, and when jobs run | -From anywhere in Tern, the palette has **Agent Scheduler: Open manager** (`ctrl+alt+shift+m`), **New job…** (`ctrl+alt+shift+j`), **Run a job now…** (`ctrl+alt+shift+r`) and **Go to run that needs you** (`ctrl+alt+shift+a`). +From anywhere in Tern, the palette has **Agent Scheduler: Open manager** (`ctrl+alt+shift+m`), **New job…** (`ctrl+alt+shift+j`), **Run a job now…** (`ctrl+alt+shift+r`) and **Go to run that needs you** (`ctrl+alt+shift+a`). **Agent Scheduler: Settings** opens the manager’s Settings. ### Carly @@ -128,11 +142,11 @@ Ask Tern's assistant to create, list, run or pause jobs, or to check a job's con - **Remote hosts:** jobs run on the machine the plugin is installed on. To schedule runs on a remote host you've attached in Tern, install the plugin there too (run the install command in a pane on that host); it keeps its own jobs and manager, which **Open manager** and **New job…** open while you're in one of that host's sessions. This computer's status line, notifications, Carly and the other palette commands cover only this computer's jobs, and a run on the remote host that waits for your approval isn't noticed. - **Failures:** a run that hits its time limit is stopped. After three failures in a row the job pauses itself and tells you. - **Finished run tabs:** the 5 most recent are kept and older ones are closed; their sessions can still be resumed. -- **Settings** (`,` in the manager) cover where runs appear, how many run at once (2), how many finished tabs to keep, and the late limit for missed runs. **Settings › Setup** checks that Tern and omp are found, and lets you set omp's path if it's somewhere unusual. +- **Settings** (`,` in the manager) is one page with five sections. **Status** says whether Agent Scheduler is ready to run jobs and what to fix if it isn't (**Check again** checks again). **Display** sets the time format, the layout and how new results are shown. **Where runs start** covers which session runs appear in, its name, and whether it comes to the front. **Limits** covers how many jobs run at once (2), how many finished tabs to keep, and how late a missed run may still start. **Setup** lets you set omp's path if it's somewhere unusual and opens the data folder. ## Your data -Jobs, prompts and run history live in Tern's plugin data folder (**Settings › Setup › Open data folder**): `~/Library/Application Support/Tern/plugin-data/tern-agent-scheduler/` on macOS, `~/.local/state/tern/plugin-data/tern-agent-scheduler/` on Linux. If its files are ever damaged, the manager offers **Start fresh**. +Jobs, prompts and run history live in Tern's plugin data folder (**Settings › Setup › Data folder**): `~/Library/Application Support/Tern/plugin-data/tern-agent-scheduler/` on macOS, `~/.local/state/tern/plugin-data/tern-agent-scheduler/` on Linux. If its files are ever damaged, the manager offers **Start fresh**. > [!WARNING] > Anything that can write to the data folder can create jobs or change what they run, including Hands-off ones. Keep it private to your user. diff --git a/blocks/manager.luau b/blocks/manager.luau index 7adff2f..da459f8 100644 --- a/blocks/manager.luau +++ b/blocks/manager.luau @@ -62,6 +62,9 @@ local def: BlockDef = { pane_id = pane_id(cx), token = nil, mode = "list", + looked_at = jobs.settings().last_looked or 0, + seen_results = {}, + seen_pending = {}, sel = nil, sel_idx = 1, folds = saved_folds(s.folds), @@ -82,6 +85,8 @@ local def: BlockDef = { state.cwd_hint = cwd if type(s.form) == "table" and F.restore(state, s.form) then -- An open New/Edit form survives a plugin reload or restart. + elseif saved == nil and args[1] == "settings" then + S.open_settings(state) elseif saved == nil and args[1] == "new" then F.open_new(state, { cwd = cwd }) elseif s.mode == "detail" and type(s.selected_id) == "string" then @@ -111,6 +116,10 @@ local def: BlockDef = { end, view = function(state, _cx) + if state.split_focus and state.cx.cols < C.SPLIT_COLS then + state.mode = "detail" + state.split_focus = false + end local main: Node local dock: Node if state.mode == "form" and state.form ~= nil then @@ -140,6 +149,11 @@ local def: BlockDef = { if k.ctrl or k.meta or k.alt then return false end + if state.mode == "list" and state.split_focus and state.cx.cols >= C.SPLIT_COLS then + if k.name == "escape" then state.split_focus = false; return true end + if k.name == "n" or k.name == "u" or k.name == "s" or C.is_shift_letter(k, "p") or k.name == "a" then return L.key(state, k) end + return D.key(state, k) + end if state.mode == "detail" and D.job(state) ~= nil then return D.key(state, k) end @@ -153,7 +167,11 @@ local def: BlockDef = { F.event(state, ev) elseif state.mode == "detail" and D.job(state) ~= nil then D.event(state, ev) + elseif state.cx.cols >= C.SPLIT_COLS and type(ev.id) == "string" and string.find(ev.id, ".detail.", 1, true) then + state.split_focus = true + D.event(state, ev) else + if ev.ev == "select" or ev.ev == "activate" or ev.act == "pick" then state.split_focus = false end L.event(state, ev) end end, diff --git a/docs/design/manager-timeline.md b/docs/design/manager-timeline.md new file mode 100644 index 0000000..6acdb16 --- /dev/null +++ b/docs/design/manager-timeline.md @@ -0,0 +1,41 @@ +# Manager timeline behavior + +The approved surface brief is `.impeccable/briefs/manager.md`. The implementation keeps Tern’s native nodes and semantic theme colors; `manager.css` contains the scoped layout rules. No chart remains. + +## Checkpoints and visibility + +The host owns `settings.last_looked`, `manager_layout` (`timeline` or `classic`) and `manager_results` (`fade` or `stay`). Window Settings only opens a manager block with `settings` args; no new write intent was added. + +Tern’s BlockDef has init, view, key, event, resize and save, but no closed, hidden or visible callback. The fallback starts a host `tern.timer(3000, ...)` when a new result is rendered. It checks `tern.pane.list()` for liveness and refuses to clear while a sheet or form covers the list. A timer checkpoint excludes later completions. The current visit keeps its result rows and baseline, while their semantic fresh role is removed; the next visit starts at the persisted checkpoint. Stay until marked seen disables these timers. `s` clears immediately. + +Limit: pane existence is not visibility. A background tab can remain alive, and the native API does not report which result rows have actually scrolled into view. Consequently this fallback approximates an open-manager visit, not a measured viewport impression. Select Stay until marked seen when explicit acknowledgement is important. Last-looked advances on the fallback, not on actual departure. + +## Retention and migration + +Each job’s host state has `manager_history`: total and pending outcome counters, latest outcome id, and a failure flag. The runner updates these for terminal outcomes before ledger pruning, including skipped and missed slots. Missed and cancelled outcomes are not failures; a success clears the failure flag. The timeline aggregates above eight new outcomes, while retained failure records still receive individual rows. Enter opens details rather than expanding a summary. + +Existing installations seed counters from their retained ledger. Outcomes deleted before this feature was installed cannot be reconstructed, so migrated totals initially describe retained history. Thereafter the counters survive the 50-record default retention. A failure whose record has already been pruned is represented by the aggregate failure count, not a fabricated individual row. The run list states `latest N of M` when its retained/displayed history is shorter than the counter. + +All displayed run timestamps now use start time (created/scheduled time when no terminal started). Completion remains the new-result checkpoint, not the displayed clock. Header and rows share a render-time reference and ceil future minutes; durations remain separate. + +## Structure and keyboard + +`C.SPLIT_COLS = 150` is the single split breakpoint. At that width, selection updates the adjacent details; Enter focuses its run list and Escape restores job-list keys. Narrow layouts open details full-width. `s` marks all seen in the job list. Existing list job-action keys remain available, and `?` documents the new key. + +Semantic CSS hooks include `tas.split`, `tas.timeline`, `tas.detail`, `tas.job-row`, `tas.live-row`, `tas.now-rule`, `tas.last-looked`, `tas.timeline-heading`, `tas.new`, `tas.new-failed`, `tas.seen`, `tas.latest`, `tas.latest-failed`, `tas.detail-title`, `tas.detail-status`, `tas.detail-settings`, `tas.detail-prompt`, `tas.prompt-action`, `tas.run-heading`, `tas.run-list`, `tas.run-row`, `tas.dock-actions`, `tas.dock-job`, `tas.dock-global`, `tas.dock-action` and `tas.dock-danger`. All CSS is scoped to `plugin.tern-agent-scheduler.manager`. + +## Approved visual pass and clock preferences + +`manager.css` scopes UI-font labels, mono/tabular measurements, 2px new-result markers (accent/failure), accent selection outlines, a filled now pill/rule, live gradient/dot, raised detail card, failure callout/badge, recessed settings and one outlined button style with inline keycaps (docks, forms, dialogs) to this plugin. Seen markers transition for 600ms with `--out`. Native selection is retained: `-stencil-follow` requires explicit translation targets and would fight the list's own row selection, so no follower overlay is installed. Numeric effects are attached to changing clock/measurement spans. Reduced-motion media and `.sf-still` disable authored motion. Static captures verify paint/layout, not animation trajectories; the seeded matrix has no running-agent row. + +`timefmt` is the shared display-clock module. `time_host` resolves Automatic once using host process calls and caches `time_format` in cache.json; macOS force preferences take precedence over locale, and Linux reads only locale `t_fmt` (including `%r` shorthand). Failure falls back to 24-hour. Snapshots carry the resolved format; window readers never run a detection process. Explicit 12-hour/24-hour preferences persist in settings. Previously stored free-text reasons and agent-authored summaries are not rewritten (the fixture's old “02:00” missed reason remains literal). + +Review fixes also give selected results matching detail-history selection, strip heading markers from the first two meaningful prompt lines, use a compact prompt button, and consistently name the acknowledgement option “Stay until marked seen”. Classic countdowns now use the same ceil-minute text rather than a separate seconds timer. + +Final captures: `~/Dev/personal/tern-agent-scheduler-audit/redesign2/` — wide dark/light, narrow dark/details, Manager settings plus time choices, explicit 12-hour, Classic, Nord, Catppuccin and a sandbox-only backlog (12 appended runs; 14 PR-triage records). Vision inspection completed in two batches. No clipping/overlap defects remain; native ellipsis and Settings overlay occlusion are expected. Nord's theme-provided red is visually less prominent than its body ink; no measured contrast certification is claimed. The Linux host reported `t_fmt="%r"`, cached and resolved as 12-hour. Tests and git diff whitespace checks pass. No user Tern configuration was changed. + +## Verification + +`npx --yes bun run test` runs the existing suite plus `runner_manager`. Bun was not on PATH; npx Bun works without installing into the user’s Tern configuration. The new tests cover ordering, in-flight deduplication, manual grouping, separate missed/failure counts, 84-result aggregation after pruning, checkpoint races, stay/fade behavior, covered-list guards, cron steps and settings validation. Palette tests cover Settings launch args. + +Headless captures use only the isolated `~/.hermes/cache/scratch/ternshot` sandbox. Wide timeline/details, narrow timeline, narrow details, Classic and Manager settings were captured in both themes at 1440×900 or 760×800 logical pixels (PNG output is 2×). Final files live under `~/Dev/personal/tern-agent-scheduler-audit/redesign/`. Two inspection rounds found and corrected the prompt-hint wrap. Backlog fixture reseeding requested tool approval and did not execute; no backlog screenshot is claimed. Live running/needs-you grouping has model coverage but no real-agent screenshot. diff --git a/docs/screenshots/job-detail.png b/docs/screenshots/job-detail.png deleted file mode 100644 index 660b632..0000000 Binary files a/docs/screenshots/job-detail.png and /dev/null differ diff --git a/docs/screenshots/job-details-dark.png b/docs/screenshots/job-details-dark.png new file mode 100644 index 0000000..29aeb3e Binary files /dev/null and b/docs/screenshots/job-details-dark.png differ diff --git a/docs/screenshots/job-details-light.png b/docs/screenshots/job-details-light.png new file mode 100644 index 0000000..e5f3f63 Binary files /dev/null and b/docs/screenshots/job-details-light.png differ diff --git a/docs/screenshots/manager-dark.png b/docs/screenshots/manager-dark.png new file mode 100644 index 0000000..82c6953 Binary files /dev/null and b/docs/screenshots/manager-dark.png differ diff --git a/docs/screenshots/manager-light.png b/docs/screenshots/manager-light.png new file mode 100644 index 0000000..451ff1f Binary files /dev/null and b/docs/screenshots/manager-light.png differ diff --git a/docs/screenshots/manager.png b/docs/screenshots/manager.png deleted file mode 100644 index 688e4be..0000000 Binary files a/docs/screenshots/manager.png and /dev/null differ diff --git a/docs/screenshots/new-job-dark.png b/docs/screenshots/new-job-dark.png new file mode 100644 index 0000000..a4ef9b8 Binary files /dev/null and b/docs/screenshots/new-job-dark.png differ diff --git a/docs/screenshots/new-job-light.png b/docs/screenshots/new-job-light.png new file mode 100644 index 0000000..7c1ae47 Binary files /dev/null and b/docs/screenshots/new-job-light.png differ diff --git a/docs/screenshots/new-job.png b/docs/screenshots/new-job.png deleted file mode 100644 index f7ef946..0000000 Binary files a/docs/screenshots/new-job.png and /dev/null differ diff --git a/lib/carly.luau b/lib/carly.luau index 3d9982b..224e313 100644 --- a/lib/carly.luau +++ b/lib/carly.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Window half: Carly exports (list, add, run, pause jobs) and a short request context. Creation is -- done by the host (`carly_create` intent + reply file); this half only pre-validates and relays. @@ -118,7 +119,7 @@ local function next_text(at: any, j: any, paused_all: boolean): string elseif paused_all then return "all jobs paused" elseif type(at) == "number" then - return os.date("%a %d %b %H:%M", at) + return timefmt.date("%a %d %b %H:%M", at) end return "manual only" end diff --git a/lib/commands.luau b/lib/commands.luau index dc06adf..fdd60a2 100644 --- a/lib/commands.luau +++ b/lib/commands.luau @@ -177,6 +177,9 @@ function commands.register() return end registered = true + tern.command({ id = "settings", title = "Settings", icon = "settings", group = GROUP, run = function(cx: WindowCx) + cx:new_block(const.MANAGER_KIND, { "settings", pane_cwd(cx) }, "tab") + end }) tern.command({ id = "open-manager", title = "Open manager", diff --git a/lib/cond_eval.luau b/lib/cond_eval.luau index e20cd0e..dd52a2a 100644 --- a/lib/cond_eval.luau +++ b/lib/cond_eval.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/cond_eval.luau : evaluates a job's "Only when" conditions (git, window, budget, script check, AI question), keeps the -- per-job watermarks in state.json (`watch.conditions`), never requires runner. Host only. local ids = require("./ids") @@ -279,7 +280,7 @@ end -- ---------- evaluation ---------- local function hhmm(m: number): string - return string.format("%02d:%02d", m // 60, m % 60) + return timefmt.clock(m // 60, m % 60) end local function eval_window(c: { [string]: any }, label: string, now: number): Out @@ -593,7 +594,7 @@ local function eval_ask(job: Job, c: { [string]: any }, opts: { [string]: any }, "", "- Job: " .. one_line(tostring(job.name or "")), "- Folder: " .. one_line(tostring(job.cwd or "")), - "- Now: " .. os.date("%a %Y-%m-%d %H:%M %Z", now), + "- Now: " .. timefmt.date("%a %Y-%m-%d %H:%M %Z", now), "- Started by: " .. started_by, "- Last run: " .. last_line, } diff --git a/lib/conditions.luau b/lib/conditions.luau index 3b81bc4..bd997ff 100644 --- a/lib/conditions.luau +++ b/lib/conditions.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/conditions.luau : job conditions (pure): structured build, describe, sig, stored-shape check. Loaded by both halves. local schedule = require("./schedule") local ids = require("./ids") @@ -39,7 +40,7 @@ local function path_ok(p: string): boolean end local function hhmm(m: number): string - return string.format("%02d:%02d", m // 60, m % 60) + return timefmt.clock(m // 60, m % 60) end conditions.hhmm = hhmm diff --git a/lib/cron.luau b/lib/cron.luau index e19d9de..3733c12 100644 --- a/lib/cron.luau +++ b/lib/cron.luau @@ -1,3 +1,4 @@ +local timefmt = require("./timefmt") -- lib/cron.luau : pure, no tern.* calls. Local time zone only. local cron = {} -- cron.clock = { time, date }: injectable for tests; the default is set after civil_secs below. @@ -264,7 +265,7 @@ cron.MIN_INTERVAL_S = MIN_INTERVAL_S -- ---------- describe ---------- local DOWN = { [0]="Sun","Mon","Tue","Wed","Thu","Fri","Sat" } -local function hhmm(h, m) return string.format("%02d:%02d", h, m) end +local function hhmm(h, m) return timefmt.clock(h, m) end local function ranges(list: { number }, name: (number) -> string): string local out, i = {}, 1 while i <= #list do @@ -285,9 +286,18 @@ function cron.describe(spec): string -- times phrase local every: string? = nil local when: string - if nm == 1 and nh == 24 then every = "Every hour at :" .. string.format("%02d", spec.minutes[1]); when = every - elseif nm >= 2 and 60 % nm == 0 and spec.minutes[1] == 0 and spec.minutes[2] == 60 // nm then - every = "Every " .. (60 // nm) .. " minutes" .. (nh < 24 and (" during hours " .. ranges(spec.hours, tostring)) or ""); when = every + local function step(xs, limit) + if #xs < 2 or xs[1] ~= 0 then return nil end + local n = xs[2] + for i, v in xs do if v ~= (i - 1) * n then return nil end end + return if xs[#xs] + n >= limit then n else nil + end + local hs, ms = step(spec.hours, 24), step(spec.minutes, 60) + if nm == 1 and hs ~= nil and hs > 1 then + every = "Every " .. hs .. " hours" .. (if spec.minutes[1] == 0 then "" else " at :" .. string.format("%02d", spec.minutes[1])); when = every + elseif nm == 1 and nh == 24 then every = "Every hour at :" .. string.format("%02d", spec.minutes[1]); when = every + elseif ms ~= nil then + every = "Every " .. ms .. " minutes" .. (nh < 24 and (" during hours " .. ranges(spec.hours, tostring)) or ""); when = every elseif nh * nm <= 6 then local ts = {} for _, h in ipairs(spec.hours) do for _, m in ipairs(spec.minutes) do table.insert(ts, hhmm(h, m)) end end diff --git a/lib/fmt.luau b/lib/fmt.luau index 2bb071c..cc5b068 100644 --- a/lib/fmt.luau +++ b/lib/fmt.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Formatting shared by API-backed blocks: timestamps, relative ages, counts, durations, clipping. -- Both halves. @@ -37,9 +38,9 @@ function fmt.ago(t: number?, now: number): string elseif os.date("%Y-%m-%d", t) == os.date("%Y-%m-%d", now - 86400) then return "yesterday" elseif os.date("%Y", t) == os.date("%Y", now) then - return (string.gsub(os.date("%d %b", t), "^0", "")) + return (string.gsub(timefmt.date("%d %b", t), "^0", "")) end - return (string.gsub(os.date("%d %b %Y", t), "^0", "")) + return (string.gsub(timefmt.date("%d %b %Y", t), "^0", "")) end -- 950, 1.2k, 34k, 1.5M: keeps the count column narrow. diff --git a/lib/intents.luau b/lib/intents.luau index 554fc98..850e111 100644 --- a/lib/intents.luau +++ b/lib/intents.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/intents.luau : host side of the window -> host protocol (EN §2.3 + plan overrides 8-9). -- Files `intents/--.json`, applied in name order inside a time budget and removed -- after applying. 13 allowlisted kinds (const.INTENT_KINDS); everything else (create/update/delete/ @@ -195,7 +196,7 @@ local function carly_create(p: { [string]: any }, h: Handlers) local nxt = "manual only" if type(st.next_run) == "number" then local dok, d = pcall(function() - return os.date("%a %d %b %H:%M", st.next_run) + return timefmt.date("%a %d %b %H:%M", st.next_run) end) if dok and type(d) == "string" then nxt = d diff --git a/lib/jobs.luau b/lib/jobs.luau index 349b922..484e179 100644 --- a/lib/jobs.luau +++ b/lib/jobs.luau @@ -1,4 +1,6 @@ --!strict +local time_host = require("./time_host") +local timefmt = require("./timefmt") -- lib/jobs.luau : jobs.json, state.json, settings.json, prompts/, trash/ (EN §1, §2). Host only; the -- manager and the runner call it in-process (single writer). local const = require("./const") @@ -59,6 +61,10 @@ local function default_settings(): { [string]: any } catchup_spacing_s = const.CATCHUP_SPACING_S_DEFAULT, catchup_window_s = const.CATCHUP_DEFAULT_S, max_finished_panes = const.MAX_FINISHED_PANES, + manager_layout = "timeline", + manager_results = "fade", + time_format = "automatic", + last_looked = 0, retain_runs = 50, retain_days = 90, defaults = { @@ -138,7 +144,7 @@ end local function tz_record(): { [string]: any } local abbr = "" pcall(function() - abbr = os.date("%Z") :: string + abbr = timefmt.date("%Z") :: string end) return { abbr = abbr } end @@ -224,6 +230,8 @@ function jobs.load(now: number): string fill_defaults(settings_tbl, default_settings()) end + time_host.configure(settings_tbl.time_format) + local data = store.load("jobs", const.CAP_JOBS) if type(data) == "table" then seq = tonumber(data.seq) or 0 @@ -396,6 +404,14 @@ end local function check_setting(k: string, v: any): string? if k == "paused_all" or k == "show_next_in_status" or k == "keep_awake" or k == "welcomed" or k == "first_scheduled_toast_done" then return need(type(v) == "boolean", k .. " must be true or false.") + elseif k == "time_format" then + return need(in_enum(v, { "automatic", "12h", "24h" }), "Pick Automatic, 12-hour or 24-hour.") + elseif k == "manager_layout" then + return need(in_enum(v, { "timeline", "classic" }), "Pick Timeline or Classic job list.") + elseif k == "manager_results" then + return need(in_enum(v, { "fade", "stay" }), "Pick Fade once seen or Stay until marked seen.") + elseif k == "last_looked" then + return need(type(v) == "number" and v >= 0, "Use a valid time.") elseif k == "max_concurrent" then return need(int_in(v, 1, 10), "Run at most 1 to 10 jobs at once.") elseif k == "cap_wait_s" then @@ -478,6 +494,7 @@ function jobs.set_settings(patch: { [string]: any }): (boolean, string?) settings_tbl[k] = v end end + if patch.time_format ~= nil then time_host.configure(settings_tbl.time_format) end local ok, err = save_settings() if not ok then return false, err @@ -565,7 +582,7 @@ function jobs.describe(job: Job): string local w = cron.clock.date("*t", tonumber(s.run_at) or 0) local names = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } - return string.format("Once, %s %d %s %02d:%02d", names[w.wday] or "", w.day, months[w.month] or "", w.hour, w.min) + return string.format("Once, %s %d %s %s", names[w.wday] or "", w.day, months[w.month] or "", timefmt.clock(w.hour, w.min)) end -- Re-arm: cursor = armed_at = now, interval anchor floored to the minute, next_run recomputed. diff --git a/lib/launcher.luau b/lib/launcher.luau index 6564845..1a308cf 100644 --- a/lib/launcher.luau +++ b/lib/launcher.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/launcher.luau : LA §2-§4, §7.2. Single-flight FIFO launch queue: stage the images the prompt links, write the run -- files, ensure the run session, `tern new tab|session … --keep-open -- omp …`, parse ids as strings, best-effort -- rename/focus. omp gets `@/prompt.md` plus one `@/images/.` per staged image. @@ -143,7 +144,7 @@ end local function local_time(t: number): string local ok, s = pcall(function() - return os.date("%a %Y-%m-%d %H:%M %Z", t) + return timefmt.date("%a %Y-%m-%d %H:%M %Z", t) end) if ok and type(s) == "string" then return s diff --git a/lib/ledger.luau b/lib/ledger.luau index 9410166..718dd7c 100644 --- a/lib/ledger.luau +++ b/lib/ledger.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/ledger.luau : run records, state transitions, reason sentences, retention (EN §7). -- One JSONL file per job under ledger/.jsonl (backup-then-write through store). Host only. local const = require("./const") @@ -192,7 +193,7 @@ local DAYS = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } local function day_time(t: number): string local w = cron.clock.date("*t", t) - return string.format("%s %02d:%02d", DAYS[(w.wday or 1)] or "", w.hour, w.min) + return string.format("%s %s", DAYS[(w.wday or 1)] or "", timefmt.clock(w.hour, w.min)) end ledger.day_time = day_time -- Local calendar day of a time, e.g. "2026-10-12"; folding of AI skips never crosses it. diff --git a/lib/mgr_common.luau b/lib/mgr_common.luau index 575e40e..263bd72 100644 --- a/lib/mgr_common.luau +++ b/lib/mgr_common.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Manager (host block) shared state type, copy and small helpers. Required by every lib/mgr_*.luau view; -- calls tern.* only inside functions. @@ -102,12 +103,12 @@ export type Sheet = { run_id: string?, job_id: string?, -- settings sheet - page: string?, focus: string?, editing: { row: string, initial: string, option: string? }?, field: textfield.Field?, warnings: { [string]: string }?, checking: boolean?, + checked_at: number?, text: string?, code: string?, override: string?, @@ -138,16 +139,21 @@ export type State = { cwd_hint: string?, -- tern.now() (ms) until which the last delete can be undone. undo_until: number?, + split_focus: boolean?, + history_baseline: any?, + looked_at: number?, + seen_results: { [string]: boolean }?, + seen_pending: { [string]: boolean }?, } +C.SPLIT_COLS = 150 + C.AVAILABILITY = "Jobs run while Tern's session service is running. It keeps running after you close windows as long as a terminal or run is still open. Nothing runs while your " .. platform.machine() .. " is asleep, or after a restart until you open Tern." C.NO_WINDOW = - "With no Tern window open, a run that stops to ask for approval waits silently until you open a window or its time limit is reached. Launch failures, early exits, time-outs and blocked jobs still send a notification." - -C.WINDOWS = "With several Tern windows open, scheduled runs start in the first window." + "With no Tern window open, a run that stops for approval waits until you open one or its time limit ends. Failed starts, early exits, time-outs and blocked jobs still notify you." C.HANDS_OFF_WARNING = "Hands-off runs commands and edits files as you, with your credentials, while you're away. Only use it for prompts you'd trust unattended." @@ -187,11 +193,6 @@ function C.with(node: Node, props: { [string]: any }): Node return node end -function C.badge(label: string, tone: string, act: string, key: string, value: string?): Node - local click = if value ~= nil then act .. "=" .. value else act - return C.with(ui.badge(label, tone), { key = key, actions = { click = click } }) -end - local SHORT_LABELS: { [string]: string } = { ["+ New"] = "+", ["Open run"] = "Open", @@ -262,16 +263,21 @@ end function C.in_text(t: number, now: number): string local d = t - now - if d < 60 and d > -60 then + if d <= 0 and d > -60 then return "now" elseif d < 0 then return C.span_text(-d) .. " ago" end - return "in " .. C.span_text(d) + local minutes = math.ceil(d / 60) + if minutes < 60 then return string.format("in %dm", minutes) end + if minutes < 1440 then + return string.format("in %dh%s", minutes // 60, if minutes % 60 == 0 then "" else string.format(" %dm", minutes % 60)) + end + return string.format("in %dd%s", minutes // 1440, if (minutes % 1440) // 60 == 0 then "" else string.format(" %dh", (minutes % 1440) // 60)) end function C.abs(t: number): string - return (string.gsub(os.date("%a %d %b %H:%M", t), "^(%a+) 0", "%1 ")) + return (string.gsub(timefmt.date("%a %d %b %H:%M", t), "^(%a+) 0", "%1 ")) end local function day_key(t: number): string @@ -280,7 +286,7 @@ end -- UX §0 relative time rules: time today, "tomorrow 09:00", "Mon 09:00" within 6 days, else "12 Oct 09:00". function C.when_text(t: number, now: number): string - local hm = os.date("%H:%M", t) + local hm = timefmt.date("%H:%M", t) if day_key(t) == day_key(now) then return hm elseif day_key(t) == day_key(now + 86400) then @@ -288,9 +294,20 @@ function C.when_text(t: number, now: number): string elseif day_key(t) == day_key(now - 86400) then return "yesterday " .. hm elseif math.abs(t - now) < 6 * 86400 then - return os.date("%a ", t) .. hm + return timefmt.date("%a ", t) .. hm + end + return (string.gsub(timefmt.date("%d %b ", t), "^0", "")) .. hm +end + +-- Every clickable action in the manager (docks, forms, dialogs) is this one button, so they all share one look. +function C.action_button(label: string, key: string, tone: string, act: string, id: string, value: string?): Node + local kids: { Node } = { tern.ui.el("span", { text = label }) } + if key ~= "" then + table.insert(kids, tern.ui.el("kbd", { text = key })) end - return (string.gsub(os.date("%d %b ", t), "^0", "")) .. hm + return tern.ui.el("button", { key = id, tone = tone, + role = if act == "delete" or act == "pause_all" then "tas.dock-danger" else "tas.dock-action", + actions = { click = act .. (if value then "=" .. value else "") } }, kids) end function C.cost_text(cost: any): string @@ -365,7 +382,7 @@ function C.parse_item(item: any): (string?, string?) if type(item) ~= "string" then return nil, nil end - local sec, key = string.match(item, "^main%.([%w_%-]+)%.([%w_%-:]+)$") + local sec, key = string.match(item, "([%w_%-]+)%.([%w_%-:]+)$") return sec, key end diff --git a/lib/mgr_detail.luau b/lib/mgr_detail.luau index 5090f2f..b809732 100644 --- a/lib/mgr_detail.luau +++ b/lib/mgr_detail.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Manager detail mode (UX §3.5): one job's settings, its prompt and its last 20 runs from the ledger. local ui = tern.ui @@ -11,6 +12,7 @@ local jobs = require("./jobs") local ledger = require("./ledger") local conditions = require("./conditions") +local H = require("./mgr_history") local D = {} type State = C.State @@ -82,7 +84,7 @@ local function when_text(job: any): string local s: any = job.schedule local text = jobs.describe(job) if s.kind == "cron" then - return string.format("%s (local, %s) · %s", text, os.date("%Z", C.now()), s.expr) + return string.format("%s (local, %s) · %s", text, timefmt.date("%Z", C.now()), s.expr) end return text end @@ -117,7 +119,7 @@ end -- Runs --------------------------------------------------------------------------------------------------------- local function run_item(run: any, now: number, tier: number): Node - local props: { [string]: any } = { key = run.run_id } + local props: { [string]: any } = { key = run.run_id, role = "tas.run-row" } local t: number = run.started or run.created or run.slot or now local suffix = "" if run.trigger == "manual" then @@ -137,7 +139,7 @@ local function run_item(run: any, now: number, tier: number): Node elseif run.state == "needs_input" then props.tone = "warning" end - props.label = { ui.span(string.format("%s%s%s", if glyph ~= nil then glyph .. " " else "", C.when_text(t, now), suffix)) } + props.label = { ui.span(string.format("%s%s%s", if glyph ~= nil then glyph .. " " else "", C.when_text(t, now), suffix), "mono") } local not_attached = "" if type(run.images) == "table" and type(run.images.skipped) == "table" and #run.images.skipped > 0 then @@ -164,6 +166,8 @@ local function run_item(run: any, now: number, tier: number): Node table.insert(parts, not_attached) end detail = table.concat(parts, " · ") + elseif type(run.summary) == "string" and run.summary ~= "" then + detail = clip(run.summary, 120) elseif type(run.reason) == "string" and run.reason ~= "" then detail = clip(run.reason, 120) if not_attached ~= "" then @@ -179,7 +183,7 @@ local function run_item(run: any, now: number, tier: number): Node detail ..= " · ran without checking conditions" end if tier >= 2 and detail ~= "" then - props.detail = { ui.span(detail, "muted") } + table.insert(props.label, ui.span(" " .. string.gsub(run.state, "_", " ") .. " · " .. detail, "muted")) end local value = "" if type(run.started) == "number" and type(run.ended) == "number" then @@ -199,7 +203,7 @@ local function runs_of_job(state: State): { any } if d == nil then return {} end - local ok, list = pcall(ledger.recent, d.job_id, 20) + local ok, list = pcall(ledger.recent, d.job_id, 50) if ok and type(list) == "table" then return list end @@ -244,6 +248,18 @@ local function demote_headings(text: string): string return table.concat(out, "\n") end +-- A compact plain-text preview, without Markdown heading punctuation. +function D.prompt_preview(text: string): string + local lines = {} + for line in string.gmatch(text, "[^\r\n]+") do + line = string.gsub(line, "^%s*#+%s*", "") + line = string.gsub(line, "%s+#+%s*$", "") + if string.match(line, "%S") then table.insert(lines, line) end + if #lines >= 2 then break end + end + return table.concat(lines, " · ") +end + -- First `max` lines of `text` as Markdown source (an unclosed code fence is closed), and whether lines were dropped. local function md_head(text: string, max: number): (string, boolean) local lines: { string } = {} @@ -292,75 +308,7 @@ local function expanded_card(run: any): Node return C.with(ui.card({ ui.span("Last message", "strong") }, lines), { key = "expanded" }) end --- History chart ------------------------------------------------------------------------------------------------ - -local FAILED: { [string]: boolean } = { failed = true, timed_out = true, blocked = true, missed = true, cancelled = true } -local DONE: { [string]: boolean } = { - finished = true, - failed = true, - timed_out = true, - blocked = true, - missed = true, - cancelled = true, - skipped = true, -} - --- Nodes for the history chart: one `el` bar per run (oldest left, coloured by outcome via manager.css), and a summary --- line. Empty when fewer than two runs have ended. -local function history_nodes(runs: { any }): { Node } - local done: { any } = {} - for i = #runs, 1, -1 do -- ledger is newest first - local r = runs[i] - if DONE[r.state] and #done < 20 then - table.insert(done, r) - end - end - if #done < 2 then - return {} - end - local bars: { Node } = {} - local failed, total = 0, 0 - local durs: { number } = {} - local maxdur = 0 - local entries: { { dur: number, bad: boolean, tip: string } } = {} - for _, r in done do - local dur = 0 - if type(r.started) == "number" and type(r.ended) == "number" then - dur = math.max(0, r.ended - r.started) - end - if dur > 0 then - table.insert(durs, dur) - maxdur = math.max(maxdur, dur) - end - if type(r.cost) == "number" then - total += r.cost - end - local bad = FAILED[r.state] == true - if bad then - failed += 1 - end - local t: number = r.started or r.created or r.slot or r.ended or 0 - local tip = string.format("%s · %s · %s · %s", C.abs(t), if dur > 0 then C.duration_text(dur) else "didn't start", C.cost_text(r.cost), (string.gsub(r.state, "_", " "))) - table.insert(entries, { dur = dur, bad = bad, tip = tip }) - end - for i, e in entries do - local bucket = if maxdur > 0 then math.floor(20 * e.dur / maxdur + 0.5) else 0 - local outcome = if e.bad then "fail" elseif e.dur > 0 then "ok" else "none" - table.insert(bars, ui.el("div", { key = "hb" .. i, class = "tas-bar", title = e.tip, attrs = { ["data-h"] = bucket, ["data-o"] = outcome } })) - end - table.sort(durs) - local median = if #durs > 0 then (durs[(#durs + 1) // 2] + durs[#durs // 2 + 1]) / 2 else 0 - local out: { Node } = { - ui.el("div", { key = "hist-chart", class = "tas-bars" }, bars), - } - local parts = { string.format("%d runs", #done), string.format("%d failed", failed) } - if median > 0 then - table.insert(parts, "median " .. C.duration_text(median)) - end - table.insert(parts, C.cost_text(total) .. " total") - table.insert(out, C.text({ ui.span(table.concat(parts, " · "), "muted") }, "hist-sum")) - return out -end +-- History is text, not a chart. Counters are independent of ledger retention. -- View --------------------------------------------------------------------------------------------------------- @@ -387,174 +335,58 @@ function D.hints_text(cols: number): Node return C.text(spans, "hints") end -function D.view(state: State): (Node, Node) +function D.view(state: State, embedded: boolean?, frame_now: number?): (Node, Node) local d = state.detail :: { job_id: string, sel: string?, expanded: string? } local job: any = jobs.get(d.job_id) local js: any = jobs.state(d.job_id) - local now = C.now() - local cols = state.cx.cols + local now = frame_now or C.now() + local cols = if embedded then state.cx.cols / 2 else state.cx.cols local tier = C.tier(cols) local runs = runs_of_job(state) local sel = selected_run(state, runs) - - local status: string - local next_secs: number? = nil - if job.enabled == false then - status = if js.paused_reason == "failures" - then "Paused after failures" - elseif js.paused_reason == "conditions" then "Paused: its conditions couldn't be checked" - elseif js.done == true then "Finished" - else "Paused" - elseif type(js.next_run) == "number" then - if js.next_run - now < 3600 and js.next_run - now > 0 then - status = "Active · next in" - next_secs = js.next_run - now - else - status = "Active · next " .. C.in_text(js.next_run, now) - end - else - status = "Active · manual only" - end - local title_spans: { Span | string } = { - ui.span("Agent Scheduler › ", "muted"), - ui.span(job.name, "strong"), - ui.span(" @" .. tostring(job.role), "muted"), - ui.span(" " .. status, if job.enabled == false then "warning" else "muted"), - } - local children: { Node } = {} - if next_secs ~= nil then - table.insert( - children, - ui.node("row", { key = "title", gap = "sm" }, { - ui.text(title_spans), - ui.node("elapsed", { key = "next-in", age = -math.floor(next_secs * 1000), format = "short" }), - }) - ) - else - table.insert(children, C.text(title_spans, "title")) - end - -- A run in flight: live timer plus what it is doing now. - local live_run: any = nil - for _, r in A.runs_of(job.id) do - if r.state == "running" or r.state == "needs_input" or r.state == "launching" then - live_run = r - break - end - end - if live_run ~= nil then - local t0: number = live_run.started or live_run.state_since or now - local lv: any = runner.live(live_run.run_id) - local label = if live_run.state == "needs_input" then "Needs you" elseif live_run.state == "launching" then "Starting" else "Running" - local bits: { Node } = { - ui.node("spinner", { key = "live-spin", style = "dots", tone = if live_run.state == "needs_input" then "warning" else "accent", label = label }), - ui.node("elapsed", { key = "live-elapsed", age = math.max(0, math.floor((now - t0) * 1000)) }), - } - local extra: { string } = {} - if lv ~= nil then - local tool: any = lv.tool - if type(tool) == "table" then - local d = if type(tool.detail) == "string" and tool.detail ~= "" then ": " .. clip(tool.detail, 70) else "" - table.insert(extra, tostring(tool.name) .. d) - end - if type(lv.tools) == "number" and lv.tools > 0 then - table.insert(extra, string.format("%d tool call%s", lv.tools, if lv.tools == 1 then "" else "s")) - end - if type(lv.cost) == "number" then - table.insert(extra, C.cost_text(lv.cost)) - end - end - if #extra > 0 then - table.insert(bits, ui.text({ ui.span("· " .. table.concat(extra, " · "), "muted") })) - end - table.insert(children, ui.node("row", { key = "live", gap = "sm" }, bits)) - end - if job.created_by == "carly" and type(job.created_at) == "number" then - table.insert(children, C.text({ ui.span("Added by Carly · " .. (string.gsub(os.date("%a %d %b", job.created_at), "^(%a+) 0", "%1 ")), "muted") }, "carly")) - end - local has_conditions = type(job.conditions) == "table" and #job.conditions > 0 - local facts: { { Spans } } = { - kv("When", when_text(job)), + local h = H.ensure(job.id) + local status = if js.done then "✓ Finished" elseif job.enabled == false then "Ⅱ Paused" else "○ Active" + local live = A.runs_of(job.id)[1] + if live then status = if live.state == "needs_input" then "! Needs you" else "● Running" end + if type(js.next_run) == "number" and job.enabled ~= false then status ..= " · next " .. C.when_text(js.next_run, now) end + local children: { Node } = { + C.with(C.text({ ui.span(job.name, "strong") }, "title"), { role = "tas.detail-title" }), + C.with(C.text({ ui.span(status, if live then "accent" else "muted") }, "status"), { role = "tas.detail-status" }), } - if has_conditions then - table.insert(facts, kv("Only when", conditions.describe(job.conditions))) - end - for _, row in { - kv("If asleep", C.catch_up_label(job.catch_up, job.catch_up_window_s or tonumber(jobs.settings().catchup_window_s))), - kv("Next", next_times(job, js, now)), - kv("Role", "@" .. tostring(job.role)), + local latest = runs[1] + if latest then + local bad = H.failed(latest) + local outcome = string.gsub(latest.state, "_", " ") + local summary = latest.summary or latest.reason or "No summary recorded." + if bad then table.insert(children, C.with(ui.badge("Last run failed", "error"), { key = "failed-badge", role = "tas.failure-badge" })) end + table.insert(children, ui.node("col", { key = "latest", role = if bad then "tas.latest-failed" else "tas.latest", gap = "xs" }, { + ui.text({ ui.span((GLYPH[latest.state] or "·") .. " Latest result · " .. outcome .. " · " .. C.when_text(latest.started or latest.created or latest.slot or now, now), if bad then "error" else "strong") }), + ui.text({ ui.span(summary, if bad then "error" else "muted") }), + })) + end + local facts = { + kv("When", jobs.describe(job)), kv("Folder", C.tilde(job.cwd)), - kv("Appears", appears_text()), - kv("Safety", safety_text(job)), - kv("After", after_text()), - } do - table.insert(facts, row) - end - table.insert( - children, - C.with( - ui.kv(facts), - { key = "facts" } - ) - ) - if not has_conditions then - local recent: { any } = {} - for _, r in runs do - if r.started ~= nil then - table.insert(recent, r) - if #recent >= 10 then - break - end - end - end - local quiet_n, quiet_sum = 0, 0 - for _, r in recent do - if r.outcome_flag == "quiet" then - quiet_n += 1 - end - if type(r.cost) == "number" then - quiet_sum += r.cost - end - end - if quiet_n >= 8 then - table.insert( - children, - C.text({ - ui.span( - string.format("Quiet %d of the last 10 runs (%s spent). Turn on “Only when: new commits”? Press e.", quiet_n, C.cost_text(quiet_sum)), - "muted" - ), - }, "nudge") - ) - end - end + kv("Agent", "@" .. tostring(job.role) .. " · " .. C.approval_label(job.approval) .. " · stops after " .. C.span_text(job.max_runtime_s or 1800)), + kv("Only when", if type(job.conditions) == "table" and #job.conditions > 0 then conditions.describe(job.conditions) else "Always runs when due"), + kv("If asleep", C.catch_up_label(job.catch_up, job.catch_up_window_s or tonumber(jobs.settings().catchup_window_s))), + } + table.insert(children, C.with(ui.kv(facts), { key = "facts", role = "tas.detail-settings" })) local prompt = jobs.prompt(d.job_id) or "" - table.insert(children, C.text({ ui.span("Prompt", "muted"), ui.span(" "), ui.span("p", "key"), ui.span(" opens the file", "muted") }, "prompt-h")) - if string.match(prompt, "%S") ~= nil then - local src, cut = md_head(demote_headings(prompt), 8) - table.insert(children, C.with(ui.md(src), { key = "prompt-md" })) - if cut then - table.insert(children, C.text({ ui.span("…", "muted") }, "prompt-more")) - end - end - table.insert(children, ui.rule({ ui.span("RUNS (last 20)", "dim") })) - for _, n in history_nodes(runs) do - table.insert(children, n) - end + table.insert(children, C.with(ui.kv({ kv("Prompt", clip(D.prompt_preview(prompt), if embedded then 160 else 240)) }), { key = "prompt", role = "tas.detail-prompt" })) + table.insert(children, C.with(C.action_button("Open prompt file", "p", "neutral", "prompt", "prompt-file", job.id), { role = "tas.prompt-action" })) + local counts = h.totals + local label = string.format("%d runs · %d failed · %d missed", counts.total, counts.failed, counts.missed) + if counts.total > #runs then label ..= string.format(" · latest %d of %d", #runs, counts.total) end + table.insert(children, C.with(ui.rule({ ui.span(label, "muted") }), { key = "run-heading", role = "tas.run-heading" })) local items: { Node } = {} for _, r in runs do - table.insert(items, run_item(r, now, tier)) - end - table.insert( - children, - ui.node("list", { - key = "runs", - selected = if sel ~= nil then C.item_id("runs", sel.run_id) else nil, - empty = { ui.span("— never run. Press r to run it now.", "muted") }, - }, items) - ) - if sel ~= nil and d.expanded == sel.run_id then - table.insert(children, expanded_card(sel)) + local node = run_item(r, now, tier) + if sel and r.run_id == sel.run_id then node.p.mark = "pick" end + table.insert(items, node) end + table.insert(children, ui.node("list", { key = "runs", role = "tas.run-list", selected = if sel then (if embedded then C.item_id("runs", sel.run_id) else "main.detail-card.runs." .. sel.run_id) else nil, empty = { ui.span("Never run. Press r to run it now.", "muted") } }, items)) + if sel ~= nil and d.expanded == sel.run_id then table.insert(children, expanded_card(sel)) end -- Dock. local ctx: Node @@ -579,11 +411,8 @@ function D.view(state: State): (Node, Node) end local acts: { Node } = {} local function add(label: string, tone: string, act: string, key: string, value: string?) - if cols >= 70 then - table.insert(acts, C.badge(label, tone, act, key, value)) - elseif cols >= 56 then - table.insert(acts, C.badge(C.short_label(label), tone, act, key, value)) - end + local keys = { open_run = "enter", run = "r", edit = "e", pause = "space", delete = "dd", back = "esc", check_conditions = "i" } + table.insert(acts, C.action_button(label, keys[act] or "", if act == "delete" then "error" else tone, act, key, value)) end if sel ~= nil then local closed = sel.session_file ~= nil and not (sel.block ~= nil and sel.pane_closed_at == nil) @@ -598,8 +427,13 @@ function D.view(state: State): (Node, Node) local armed = state.armed == job.id add(if armed then "Confirm delete" else "Delete", if armed then "error" else "neutral", "delete", "delete", job.id) add("Back", "neutral", "back", "back") - local dock = ui.col({ ctx, C.with(ui.row(acts), { key = "acts" }), D.hints_text(cols) }) - return ui.col(children), dock + local back = table.remove(acts) + local dock = ui.col({ ctx, C.with(ui.row({ + ui.node("row", { key = "job-actions", role = "tas.dock-job", gap = "xs" }, acts), + ui.node("row", { key = "global-actions", role = "tas.dock-global", gap = "xs" }, { back }), + }), { key = "acts", role = "tas.dock-actions" }) }) + if embedded then return ui.col(children), dock end + return ui.col({ ui.node("col", { key = "detail-card", role = "tas.detail", gap = "sm" }, children) }), dock end -- Keys ---------------------------------------------------------------------------------------------------------- @@ -742,7 +576,9 @@ function D.event(state: State, ev: UiEvent) if act == "back" then A.back(state) elseif type(value) == "string" then - if act == "run" then + if act == "prompt" then + A.edit_prompt(state, value) + elseif act == "run" then A.run_now(state, value) elseif act == "check_conditions" then S.check_conditions(state, value) diff --git a/lib/mgr_form.luau b/lib/mgr_form.luau index df084b1..1d2be88 100644 --- a/lib/mgr_form.luau +++ b/lib/mgr_form.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Manager form mode (UX §4.11): the 9-row New job / Edit form as a `prefs` page in `main`, with a multi-line -- Prompt editor card, a live schedule preview, a role picker (sheets) and Save / Save & run now. @@ -568,7 +569,7 @@ function F.preview(form: Form): string if rec == nil then return "" end - local tz = os.date("%Z", now) + local tz = timefmt.date("%Z", now) if rec.kind == "manual" then return "Manual only · runs when you press r. Never on a schedule." elseif rec.kind == "once" then @@ -615,9 +616,22 @@ end -- Rows ------------------------------------------------------------------------------------------- local function summary_line(text: string): string - local first = C.trim(string.match(text, "^[^\r\n]*") or "") + -- First meaningful lines as plain text: Markdown heading marks dropped, up to two lines joined. + local lines: { string } = {} + local more = false + for line in string.gmatch(text, "[^\r\n]+") do + line = C.trim((string.gsub(string.gsub(line, "^%s*#+%s*", ""), "%s+#+%s*$", ""))) + if line ~= "" then + if #lines >= 2 then + more = true + break + end + table.insert(lines, line) + end + end + local first = table.concat(lines, " · ") local clipped = if (utf8.len(first) or #first) > 90 then string.sub(first, 1, utf8.offset(first, 90) or 90) .. "…" else first - if clipped ~= first or string.find(text, "\n", 1, true) ~= nil then + if more and clipped == first then clipped ..= " …" end return clipped @@ -697,9 +711,6 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { local function warn(row: string): string? return if shown(form, row) then errors[row] else nil end - local function off(on: boolean, row: string): string? - return if on then nil else string.format("Turn on “%s” first.", ROW_LABEL[row]) - end local now_hint: string local v: any = form.verdict @@ -747,7 +758,7 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { id = "c_now", label = ROW_LABEL.c_now, hint = now_hint, - control = { k = "action", act = "c_now", label = "Check now" }, + control = if only_when_on(form) then { k = "action", act = "c_now", label = "Check now" } else { k = "keys", keys = C.arr({}) }, }, }, }, @@ -758,16 +769,15 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { { id = "c_commits", label = ROW_LABEL.c_commits, - hint = "Checks git in the job's folder. The first run notes where the branch is and waits; after that a run starts only if something landed since the last successful run, and the agent gets the list.", + hint = "Wait for new commits since the last successful run.", warning = warn("c_commits"), control = { k = "switch", on = form.c_commits }, }, { id = "c_branch", label = ROW_LABEL.c_branch, - hint = branch_hint, + hint = "The first check records the branch and waits. Later runs give the agent the new commits. " .. branch_hint, warning = branch_warning, - disabled = off(form.c_commits, "c_commits"), control = { k = "choice", style = "menu", @@ -780,7 +790,6 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { label = ROW_LABEL.c_paths, hint = "Space-separated, inside the job's folder, e.g. src docs.", warning = warn("c_paths"), - disabled = off(form.c_commits, "c_commits"), control = { k = "text", value = form.c_paths.text, placeholder = "Any folder", mono = true }, }, }, @@ -800,28 +809,24 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { id = "c_days", label = ROW_LABEL.c_days, warning = warn("c_days"), - disabled = off(form.c_window, "c_window"), control = { k = "multi", values = days_values, options = days_options }, }, { id = "c_from", label = ROW_LABEL.c_from, warning = warn("c_from"), - disabled = off(form.c_window, "c_window"), control = time_control("c_from", form.c_from), }, { id = "c_to", label = ROW_LABEL.c_to, warning = warn("c_to"), - disabled = off(form.c_window, "c_window"), control = time_control("c_to", form.c_to), }, { id = "c_outside", label = ROW_LABEL.c_outside, warning = warn("c_outside"), - disabled = off(form.c_window, "c_window"), control = { k = "choice", style = "segmented", @@ -838,15 +843,15 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { { id = "c_limits", label = ROW_LABEL.c_limits, - hint = "Counts this job's runs since midnight (or since Monday). Test runs don't count; a run with unknown cost counts as the job's typical cost.", + hint = "Cap this job's runs or spending per day or week.", warning = warn("c_limits"), control = { k = "switch", on = form.c_limits }, }, { id = "c_runs", label = ROW_LABEL.c_runs, + hint = "Counts since midnight, or Monday for weekly limits. Test runs don't count.", warning = warn("c_runs"), - disabled = off(form.c_limits, "c_limits"), control = number_control({ 1, 2, 3, 4, 5, 6, 8, 10, 12, 24 }, form.c_runs, function(n: number): string return if n == 1 then "1 run" else string.format("%d runs", n) end), @@ -854,15 +859,14 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { { id = "c_usd", label = ROW_LABEL.c_usd, + hint = "Unknown costs use this job's typical cost.", warning = warn("c_usd"), - disabled = off(form.c_limits, "c_limits"), control = number_control({ 0.5, 1, 2, 3, 5, 10, 20, 50 }, form.c_usd, money_label), }, { id = "c_per", label = ROW_LABEL.c_per, warning = warn("c_per"), - disabled = off(form.c_limits, "c_limits"), control = { k = "choice", style = "segmented", @@ -879,15 +883,15 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { { id = "c_check", label = ROW_LABEL.c_check, - hint = "For anything the others can't express. It runs in the job's folder (30 s limit) with a JSON file describing the run as its argument. Exit 0 runs, 1 skips, anything else blocks the run and tells you. It may print REASON: (shown in history), CONTEXT: lines (given to the agent) and CURSOR: (handed back next time). Saving the job approves the script as it is; if it changes, runs are blocked until you save again.", + hint = "Run your script to decide whether there is work to do.", warning = warn("c_check"), control = { k = "switch", on = form.c_check }, }, { id = "c_script", label = ROW_LABEL.c_script, + hint = "Runs in the job's folder with a run JSON file as its argument (30 s limit). Exit 0 runs; 1 skips; other exits block and notify you. Print REASON: for history, CONTEXT: for the agent, or CURSOR: for the next check. Saving approves this script; changes block runs until you save again.", warning = warn("c_script"), - disabled = off(form.c_check, "c_check"), control = { k = "text", value = form.c_script.text, placeholder = "./scripts/has-work.sh", mono = true }, }, }, @@ -899,16 +903,15 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { { id = "c_ask", label = ROW_LABEL.c_ask, - hint = "For judgement calls. After the other conditions say yes, a model reads your question, can look at the job's folder (read-only), and answers run or skip. It also sees what the other conditions found, like the new commits. Each check is one model call; its cost counts toward Limits.", + hint = "Ask a model after the other conditions pass.", warning = warn("c_ask"), control = { k = "switch", on = form.c_ask }, }, { id = "c_ask_prompt", label = ROW_LABEL.c_ask_prompt, - hint = "Write it as a yes/no question about the current state. It gets the job's name, folder, time and last run.", + hint = "Ask a yes/no question. The model sees the job, last run and other conditions' results, and can read the job's folder. Each check costs one model call, counted toward Limits.", warning = warn("c_ask_prompt"), - disabled = off(form.c_ask, "c_ask"), control = { k = "text", value = summary_line(form.c_ask_prompt.text), placeholder = "Run only if there are open pull requests that need a review." }, }, { @@ -916,7 +919,6 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { label = ROW_LABEL.c_ask_role, hint = "A small, fast model is usually enough.", warning = warn("c_ask_role"), - disabled = off(form.c_ask, "c_ask"), changed = form.c_ask_role ~= "smol", defaultLabel = "@smol", control = { k = "choice", value = form.c_ask_role, options = { { value = form.c_ask_role, label = "@" .. form.c_ask_role } }, style = "menu" }, @@ -927,6 +929,11 @@ local function only_when_sections(state: State, errs: { [string]: string }?): { -- After a Check now, each switched-on condition gets its own "Right now" row right after its switch. local NOW_FOR = { c_commits = { "c_commits_now", "commits" }, c_window = { "c_window_now", "window" }, c_limits = { "c_limits_now", "budget" }, c_check = { "c_check_now", "check" }, c_ask = { "c_ask_now", "ask" } } for _, sec in sections do + local toggle = sec.rows[1] + if toggle.control.k == "switch" and not toggle.control.on then + -- Hide dependents, not their draft values. Navigation uses this same row set. + sec.rows = { toggle } + end for i, r in sec.rows do local nf = NOW_FOR[r.id] if nf ~= nil and r.control.on == true then @@ -962,14 +969,14 @@ function F.sections(state: State, errs: { [string]: string }?): { P.Section } break end end - local prompt_hint = "Enter edits it · ctrl+o opens it as a file. Say what to do if something is unclear. Nobody is watching a scheduled run." + local prompt_hint = "Enter to edit · ctrl+o to open as a file. Say how to handle unclear instructions while you’re away." if #form.prompt.text > 4000 then prompt_hint = string.format("%d characters · long prompts read better as a file (ctrl+o)", #form.prompt.text) end local folder_path = expand(form.folder.text) local folder_warning = warn("folder") - local folder_hint: string? = "Enter types a path. Runs always start in this folder." + local folder_hint: string? = "Runs start in this folder. Enter to edit the path." if folder_warning == nil and folder_path ~= "" and C.home() ~= "" and folder_path == validate.strip_slashes(C.home()) then folder_warning = "omp may work in a temporary folder instead of your home folder. Pick a project folder for predictable results." end @@ -987,7 +994,7 @@ function F.sections(state: State, errs: { [string]: string }?): { P.Section } local catch_options: { any } = {} for _, o in C.CATCH_UPS do - table.insert(catch_options, { value = o.value, label = if o.value == "within" then C.catch_up_label("within", window_s(form)) else o.label }) + table.insert(catch_options, { value = o.value, label = if o.value == "within" then (string.gsub(C.catch_up_label("within", window_s(form)), "when you're back, ", "")) else o.label }) end local approval_options: { any } = {} for _, o in C.APPROVALS do @@ -1096,7 +1103,7 @@ function F.sections(state: State, errs: { [string]: string }?): { P.Section } { id = "active", label = ROW_LABEL.active, - hint = "Off saves the job paused. Good for a canary: save paused, then press r.", + hint = "Off saves the job paused. You can still run it manually.", changed = not form.enabled, defaultLabel = "On", control = { k = "switch", on = form.enabled }, @@ -1886,6 +1893,9 @@ function F.view(state: State): (Node, Node) local cx = state.cx local errs = F.errors(state) local sections = F.sections(state, errs) + if P.find(sections, form.focus) == nil then + form.focus = P.move(sections, nil, 1) + end local editing: any = nil local e = form.editing @@ -1900,9 +1910,10 @@ function F.view(state: State): (Node, Node) local props: { [string]: any } = { key = "prefs", + role = "tas.job-form", title = "Agent Scheduler", lead = if form.page == "only_when" - then "A due run starts only if every condition that's on says yes. Otherwise it's skipped and noted in the job's history, and you aren't notified. Run now asks before it ignores them." + then "All enabled conditions must pass. A no skips the due run and records it in history without notifying you. Run now asks before ignoring a condition." elseif form.id ~= nil then "Change this job. Saved changes apply from its next run." else "Run an omp agent on a schedule.", pages = C.arr({ @@ -1950,20 +1961,20 @@ function F.view(state: State): (Node, Node) end status = { ui.span("Fix: " .. table.concat(names, ", "), "warning") } else - status = { ui.span("Save & run now runs it once right away, exactly as scheduled. It can change files.", "muted") } + status = { ui.span("Save & run now uses these settings. If an Only when condition says no, you’ll be asked first. It can change files.", "muted") } end local blocked = next(errs) ~= nil local narrow = cx.cols < 70 local acts: { Node } = { - C.badge(if narrow then "Save" else "Save ^⏎", if blocked then "muted" else "accent", "save", "save"), - C.badge(if narrow then "Run" else "Save & run now ^⇧⏎", "neutral", "save_run", "save_run"), - C.badge(if narrow then "Cancel" else "Cancel esc", "neutral", "cancel", "cancel"), + C.action_button("Save", if narrow then "" else "^⏎", if blocked then "muted" else "accent", "save", "save"), + C.action_button(if narrow then "Run" else "Save & run now", if narrow then "" else "^⇧⏎", "neutral", "save_run", "save_run"), + C.action_button("Cancel", if narrow then "" else "esc", "neutral", "cancel", "cancel"), } - local dock = ui.col({ + local dock = C.with(ui.col({ C.text(status, "status"), C.with(ui.row(acts), { key = "acts" }), C.text({ ui.span(F.hints(cx.cols, if e ~= nil then e.row else nil, form.page), "muted") }, "hints"), - }) + }), { role = "tas.form-dock" }) return main, dock end @@ -2111,7 +2122,7 @@ local function activate(state: State, row: string): boolean elseif row == "only_when" then switch_page(state, "only_when") return true - elseif row == "c_now" then + elseif row == "c_now" and only_when_on(form) then check_now(state) return true end @@ -2274,7 +2285,7 @@ function F.event(state: State, ev: UiEvent) switch_page(state, ev.value) elseif act == "only_when" then switch_page(state, "only_when") - elseif act == "c_now" then + elseif act == "c_now" and only_when_on(form) then check_now(state) elseif act == "close" then -- Close on an open menu's button (it carries a row) closes the menu; the header's Close leaves the form. diff --git a/lib/mgr_history.luau b/lib/mgr_history.luau new file mode 100644 index 0000000..bc611fe --- /dev/null +++ b/lib/mgr_history.luau @@ -0,0 +1,62 @@ +--!strict +-- Host-owned counters survive ledger retention. Older installations can only seed retained history. +local jobs = require("./jobs") +local ledger = require("./ledger") +local H = {} +local TERMINAL = { finished = true, failed = true, timed_out = true, blocked = true, missed = true, cancelled = true, skipped = true } +function H.failed(r: any): boolean + return r.state == "failed" or r.state == "timed_out" or r.state == "blocked" +end +local function add(c: any, r: any) + local n = tonumber(r.count) or 1 + c.total += n + if H.failed(r) then c.failed += n + elseif r.state == "missed" then c.missed += n + elseif r.state == "skipped" then c.skipped += n + elseif r.state == "finished" then c.ok += n end +end +local function empty(): any + return { total = 0, failed = 0, missed = 0, skipped = 0, ok = 0 } +end +function H.ensure(id: string): any + local st: any = jobs.state(id) + if type(st.manager_history) == "table" then return st.manager_history end + local h = { totals = empty(), pending = empty(), latest = nil, failed = false } + local runs = ledger.recent(id, 10000) + for i = #runs, 1, -1 do + local r = runs[i] + if TERMINAL[r.state] and r.trigger ~= "test" then + add(h.totals, r) + if (r.ended or r.slot or 0) > (jobs.settings().last_looked or 0) then add(h.pending, r) end + h.latest = r.run_id + if H.failed(r) then h.failed = true elseif r.state == "finished" then h.failed = false end + end + end + st.manager_history = h + return h +end +function H.record(run: any) + if not TERMINAL[run.state] or run.trigger == "test" then return end + local st: any = jobs.state(run.job_id) + local existed = type(st.manager_history) == "table" + local h = H.ensure(run.job_id) + -- First seed already includes this just-persisted outcome. + if existed and h.latest ~= run.run_id then + add(h.totals, run) + add(h.pending, run) + end + h.latest = run.run_id + if H.failed(run) then h.failed = true elseif run.state == "finished" then h.failed = false end +end +function H.clear(at: number) + for _, j in jobs.list() do + local pending = empty() + for _, r in ledger.recent(j.id, 10000) do + if TERMINAL[r.state] and r.trigger ~= "test" and (r.ended or r.slot or 0) > at then add(pending, r) end + end + H.ensure(j.id).pending = pending + end + jobs.set_settings({ last_looked = math.max(at, jobs.settings().last_looked or 0) }) + jobs.save_state() +end +return H diff --git a/lib/mgr_list.luau b/lib/mgr_list.luau index b7792d2..a99dfc4 100644 --- a/lib/mgr_list.luau +++ b/lib/mgr_list.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Manager list mode (UX §3): Needs you / Needs fixing / Running / Upcoming / Paused & finished, the empty state with -- three example jobs, the dock (context line, action badges, key hints) and the list keys. @@ -11,9 +12,13 @@ local jobs = require("./jobs") local Live = require("./mgr_live") local runner = require("./runner") local store = require("./store") +local platform = require("./platform") local conditions = require("./conditions") local cond_eval = require("./cond_eval") +local T = require("./mgr_timeline") +local D = require("./mgr_detail") +local H = require("./mgr_history") local L = {} type State = C.State @@ -30,6 +35,8 @@ export type Model = { total: number, next_job: any?, next_at: number?, + quiet: string?, + unseen: boolean, } -- Setup checks that inform but never mean the scheduler is broken (UX §6.2). @@ -85,8 +92,8 @@ local function run_job(run: any): any return { id = run.job_id, name = run.job_name or "deleted job", role = run.role or "default", cwd = run.cwd or "", created_by = "user" } end -function L.model(state: State): Model - local now = C.now() +function L.model(state: State, frame_now: number?): Model + local now = frame_now or C.now() local secs: { [string]: { Row } } = { needs = {}, fix = {}, running = {}, upcoming = {}, paused = {} } local inflight_jobs: { [string]: boolean } = {} @@ -170,6 +177,8 @@ function L.model(state: State): Model total = #jobs.list() + #jobs.invalid(), next_job = nil, next_at = nil, + quiet = nil, + unseen = false, } if #upcoming > 0 and upcoming[1].at ~= math.huge then model.next_job = upcoming[1].row.job @@ -188,7 +197,13 @@ function L.model(state: State): Model end end end - return model + if jobs.settings().manager_layout == "classic" then + for _, j in jobs.list() do + if H.ensure(j.id).pending.total > 0 then model.unseen = true; break end + end + return model + end + return T.model(state, model, now) end local function find_selected(state: State, model: Model): Row? @@ -269,7 +284,7 @@ local function last_text(last: any, now: number): string if type(last) ~= "table" then return "— never run" end - local t: number = last.ended or last.started or last.slot or now + local t: number = last.started or last.slot or now local glyph = GLYPH[last.state] or "·" local tail = if last.quiet == true then "quiet" else OUTCOME[last.state] return string.format("%s %s%s", glyph, C.when_text(t, now), if tail ~= nil then " " .. tail else "") @@ -306,10 +321,13 @@ end local function item_node(row: Row, now: number, tier: number): Node local job: any = row.job - local props: { [string]: any } = { key = row.key } + local props: { [string]: any } = { key = row.key, role = "tas.job-row" } local detail_parts: { string } = {} local value: string = "" local sec = row.sec + if sec == "rest" then + sec = if row.kind == "invalid" or (row.js and (row.js.paused_reason == "blocked" or row.js.paused_reason == "conditions")) then "fix" elseif job.schedule.kind == "manual" and job.enabled ~= false then "manual" else "paused" + end if row.kind == "invalid" then props.label = { ui.span(job.name, "strong") } @@ -376,7 +394,7 @@ local function item_node(row: Row, now: number, tier: number): Node local since: number = (type(last_run) == "table" and last_run.ended) or job.created_at or now if now - since >= 14 * 86400 then detail_parts = { - string.format("Hasn't run since %s: %s (%d checks)", os.date("%b %d", since), tostring(W.skips.text), W.skips.n), + string.format("Hasn't run since %s: %s (%d checks)", timefmt.date("%b %d", since), tostring(W.skips.text), W.skips.n), } end end @@ -404,7 +422,8 @@ local function item_node(row: Row, now: number, tier: number): Node end else local last: any = js.last_run - local failed = type(last) == "table" and (last.state == "failed" or last.state == "timed_out") + local failed = H.ensure(job.id).failed + if failed and not (type(last) == "table" and (last.state == "failed" or last.state == "timed_out")) then table.insert(detail_parts, "✗ Previous failure") end props.icon = if failed then "x-circle" else "clock" props.tone = if failed then "error" else "muted" local nxt: any = js.next_run @@ -429,7 +448,7 @@ local function item_node(row: Row, now: number, tier: number): Node elseif sec == "upcoming" and type(js_next) == "number" and js_next - now < 300 then tone = "accent" end - props.value = { ui.span(value, tone) } + props.value = { ui.span(value, tone .. " mono") } props.aria = string.format("%s, %s", job.name, value) return ui.node("item", props) end @@ -483,54 +502,36 @@ local function data_problem(): string? return nil end -local function row_badges(state: State, row: Row?): { Node } - local cols = state.cx.cols +local function row_badges(state: State, row: Row?, model: Model): { Node } local out: { Node } = {} - -- `min_cols` hides a long-label badge on narrower panes (its key still works). - local function add(label: string, tone: string, act: string, key: string, value: string?, min_cols: number?) - local shown = badge_label(label, cols) - if min_cols ~= nil and cols < min_cols then - shown = nil - end - if shown ~= nil then - table.insert(out, C.badge(shown, tone, act, key, value)) - end + local function add(label, key, act, value, tone) + table.insert(out, C.action_button(label, key, tone or "neutral", act, act, value)) end if data_problem() ~= nil then - -- The only way out of damaged data, so these show at every width. - table.insert(out, C.badge("Start fresh", "error", "start_fresh", "fresh")) - table.insert(out, C.badge("Open data folder", "neutral", "open_data", "data")) + add("Start fresh", "", "start_fresh", nil, "error") + add("Open data folder", "", "open_data", nil) end - add("+ New", "accent", "new", "new") - if row ~= nil and row.kind == "invalid" then - local armed = state.armed == row.key - add(if armed then "Confirm delete" else "Delete", if armed then "error" else "neutral", "delete", "delete", row.key) - elseif row ~= nil and row.kind == "run" then - local run: any = row.run - add("Open run", "accent", "open_run", "open", run.run_id) - add("Stop", "neutral", "stop_run", "stop", run.run_id) - add("History", "neutral", "history", "history", run.job_id) - elseif row ~= nil and row.kind == "job" then + if row ~= nil and row.kind ~= "invalid" then local job: any = row.job - local running = #A.runs_of(job.id) > 0 - add("Run now", "accent", "run", "run", job.id) - add("Edit", "neutral", "edit", "edit", job.id) - add(if job.enabled == false then "Resume" else "Pause", "neutral", "pause", "pause", job.id) - if running then - add("Open run", "neutral", "open_job", "open", job.id) - end - add("History", "neutral", "history", "history", job.id) - add("Duplicate", "neutral", "duplicate", "duplicate", job.id, 100) - local armed = state.armed == job.id - add(if armed then "Confirm delete" else "Delete", if armed then "error" else "neutral", "delete", "delete", job.id) - end - if state.undo_until ~= nil and tern.now() < state.undo_until then - add("Undo", "accent", "undo", "undo") - end - add("Settings", "neutral", "settings", "settings") - add(if jobs.paused_all() then "Resume all" else "Pause all", "neutral", "pause_all", "pause_all", nil, 100) - add("?", "neutral", "help", "help") - return out + add("Open", "enter", "details", job.id, "accent") + add("Run now", "r", "run", job.id) + add("Edit", "e", "edit", job.id) + add(if job.enabled == false then "Resume" else "Pause", "space", "pause", job.id) + if state.cx.cols >= 110 then add("Duplicate", "c", "duplicate", job.id) end + end + if row ~= nil then + add(if state.armed == row.key then "Confirm delete" else "Delete", "dd", "delete", (row.job :: any).id, "error") + end + local job_actions = out + out = {} + add("New job", "n", "new", nil) + add("Settings", ",", "settings", nil) + if model.unseen then add("Mark all seen", "s", "seen", nil) end + add("Help", "?", "help", nil) + if state.undo_until ~= nil and tern.now() < state.undo_until then add("Undo", "u", "undo", nil, "accent") end + -- Set apart and last, like Delete in the job group. + add(if jobs.paused_all() then "Resume all" else "Pause all", "P", "pause_all", nil, "warning") + return { ui.node("row", { key = "job-actions", role = "tas.dock-job", gap = "sm" }, job_actions), ui.node("row", { key = "global-actions", role = "tas.dock-global", gap = "sm" }, out) } end local function setup_failing(): boolean @@ -580,7 +581,7 @@ local function context_line(state: State, model: Model, row: Row?): Node return C.text({ ui.span(DATA_TEXT[problem], "warning") }, "ctx") end if row ~= nil and row.kind == "invalid" then - return C.text({ ui.span(string.format("This job can't be read: %s. d d removes it, or open the data folder to fix jobs.json.", row.error or "unknown error"), "warning") }, "ctx") + return C.text({ ui.span(string.format("This job can't be read: %s. dd removes it, or open the data folder to fix jobs.json.", string.gsub(row.error or "unknown error", "%.$", "")), "warning") }, "ctx") end if jobs.paused_all() then return C.text({ ui.span("All jobs are paused. Press shift+p to resume.", "warning") }, "ctx") @@ -588,6 +589,9 @@ local function context_line(state: State, model: Model, row: Row?): Node if setup_failing() then return setup_line() end + if row ~= nil then + return C.text({ ui.span((row.job :: any).name, "strong"), ui.span(if state.split_focus then " · runs selected · esc returns to jobs" else " · selected job", "muted") }, "ctx") + end if model.next_job ~= nil and model.next_at ~= nil then local at: number = model.next_at return C.text({ ui.span("Next: ", "muted"), ui.span((model.next_job :: any).name, "strong"), ui.span(string.format(" %s (%s)", C.in_text(at, now), C.abs(at)), "muted") }, "ctx") @@ -597,7 +601,7 @@ end -- Header ---------------------------------------------------------------------------------------------------- -local function header_node(model: Model): Node +local function header_node(model: Model, now: number): Node local parts: { string } = { string.format("%d active", model.active) } if model.running > 0 then table.insert(parts, string.format("%d running", model.running)) @@ -606,7 +610,7 @@ local function header_node(model: Model): Node table.insert(parts, string.format("%d needs you", model.needs)) end if model.next_at ~= nil then - table.insert(parts, "next " .. C.span_text(model.next_at - C.now())) + table.insert(parts, "next " .. string.gsub(C.in_text(model.next_at, now), "^in ", "")) end return C.text({ ui.span("Agent Scheduler", "strong"), ui.span(" " .. table.concat(parts, " · "), "muted") }, "header") end @@ -623,15 +627,29 @@ end local function example_view(state: State): (Node, Node) local items: { Node } = {} + local split = state.cx.cols >= C.SPLIT_COLS + local narrow = C.tier(if split then state.cx.cols / 2 else state.cx.cols) < 3 for i, ex in EXAMPLES do + local selected_row = i == state.example_sel + local label = { ui.span(ex.name, "strong") } + local detail: { Node } + local value: { Node }? + if narrow then + detail = { ui.span(ex.about, "muted") } + value = if selected_row then { ui.span(" ⏎ use", "key") } else nil + else + detail = { ui.span(string.format("%s · @smol · %s", ex.when, ex.cost), "muted") } + value = { ui.span(ex.about, "muted") } + if selected_row then table.insert(value, ui.span(" ⏎ use", "key")) end + end table.insert( items, ui.node("item", { key = tostring(i), - label = { ui.span(ex.name, "strong") }, - detail = { ui.span(string.format("%s · @smol · %s", ex.when, ex.cost), "muted") }, - value = { ui.span(ex.about, "muted") }, - icon = "timer", + label = label, + detail = detail, + value = value, + icon = "lightbulb", }) ) end @@ -639,31 +657,45 @@ local function example_view(state: State): (Node, Node) local main = ui.col({ C.text({ ui.span("Run an omp agent on a schedule.", "strong") }, "title"), C.text({ ui.span("Pick a time, write a prompt, point it at a folder. Runs show up here when they need you.", "muted") }, "body"), - C.text({ ui.span("START FROM AN EXAMPLE", "dim") }, "head"), + C.with(ui.rule({ ui.span("Start from an example", "muted") }), { key = "head", role = "tas.timeline-heading" }), ui.node("list", { key = "examples", selected = selected }, items), C.with( - ui.text({ ui.span(C.AVAILABILITY .. " ", "muted"), ui.span("Details", "key") }), + ui.text({ ui.span("Jobs run while Tern's session service is running, never while your " .. platform.machine() .. " is asleep. ", "muted"), ui.span("Details", "key") }), { key = "avail", actions = { click = "setup" } } ), }) - local acts: { Node } = {} + local job_actions: { Node } = {} local problem = data_problem() if problem ~= nil then - table.insert(acts, C.badge("Start fresh", "error", "start_fresh", "fresh")) - table.insert(acts, C.badge("Open data folder", "neutral", "open_data", "data")) - end - table.insert(acts, C.badge("+ New", "accent", "new", "new")) - table.insert(acts, C.badge("Settings", "neutral", "settings", "settings")) - table.insert(acts, C.badge("?", "neutral", "help", "help")) - local dock_children: { Node } = {} + table.insert(job_actions, C.action_button("Start fresh", "", "error", "start_fresh", "start_fresh")) + table.insert(job_actions, C.action_button("Open data folder", "", "neutral", "open_data", "open_data")) + end + table.insert(job_actions, C.action_button("Use example", "enter", "accent", "example", "example")) + local global_actions: { Node } = { + C.action_button("New job", "n", "neutral", "new", "new"), + C.action_button("Settings", ",", "neutral", "settings", "settings"), + C.action_button("Help", "?", "neutral", "help", "help"), + } + local ctx: Node if problem ~= nil then - table.insert(dock_children, C.text({ ui.span(DATA_TEXT[problem], "warning") }, "ctx")) + ctx = C.text({ ui.span(DATA_TEXT[problem], "warning") }, "ctx") elseif setup_failing() then - table.insert(dock_children, setup_line()) + ctx = setup_line() + else + local ex = EXAMPLES[state.example_sel] + ctx = C.text({ + ui.span("No jobs yet. ⏎ opens ", "muted"), + ui.span(if ex ~= nil then ex.name else "an example", "strong"), + ui.span(" as a draft; nothing is saved until you save it.", "muted"), + }, "ctx") end - table.insert(dock_children, C.with(ui.row(acts), { key = "acts" })) - table.insert(dock_children, C.text({ ui.span("⏎", "key"), ui.span(" use example ", "muted"), ui.span("n", "key"), ui.span(" new job ", "muted"), ui.span("?", "key"), ui.span(" how it works", "muted") }, "hints")) - local dock = ui.col(dock_children) + local dock = ui.col({ + ctx, + C.with(ui.row({ + ui.node("row", { key = "job-actions", role = "tas.dock-job", gap = "sm" }, job_actions), + ui.node("row", { key = "global-actions", role = "tas.dock-global", gap = "sm" }, global_actions), + }), { key = "acts", role = "tas.dock-actions" }), + }) return main, dock end @@ -695,35 +727,52 @@ local function upcoming_detail(row: Row, now: number, tier: number): string end function L.view(state: State): (Node, Node) - local model = L.model(state) + local now = C.now() + local model = L.model(state, now) if model.total == 0 then return example_view(state) end local row = L.sync(state, model) - local now = C.now() - local tier = C.tier(state.cx.cols) - local children: { Node } = { header_node(model) } + local split = state.cx.cols >= C.SPLIT_COLS + local tier = C.tier(if split then state.cx.cols / 2 else state.cx.cols) + local timeline = jobs.settings().manager_layout ~= "classic" + local children: { Node } = { header_node(model, now) } + if timeline and model.quiet ~= nil then + table.insert(children, C.with(C.text({ ui.span(model.quiet, "muted") }, "quiet"), { key = "quiet", role = "tas.quiet" })) + end for _, sec in model.sections do - table.insert(children, section_header(sec)) - if not sec.collapsed then + if timeline and sec.id == "now" then + table.insert(children, ui.el("div", { key = "h-now", role = "tas.now-rule" }, { ui.el("span", { role = "tas.now-pill", text = sec.title }) })) + else + table.insert(children, if timeline then C.with(ui.rule({ ui.span(sec.title, "muted") }), { key = "h-" .. sec.id, role = if sec.id == "results" then "tas.last-looked" else "tas.timeline-heading" }) else section_header(sec)) + end + if not sec.collapsed and #sec.rows > 0 then local selected: string? = nil if sec.id == "needs" or sec.id == "running" then -- In-flight runs are `agent` nodes, which a `list` can't select: keep them in a col. local nodes: { Node } = {} for _, r in sec.rows do - table.insert(nodes, Live.agent_row(r, now, tier, row ~= nil and r == row)) + local node = Live.agent_row(r, now, tier, row ~= nil and r == row) + local nxt = jobs.state((r.job :: any).id).next_run + local props: any = node.p + props.role = "tas.live-row" + if timeline and type(nxt) == "number" then table.insert(props.badges, { text = "next " .. timefmt.date("%H:%M", nxt) }) end + table.insert(nodes, node) end table.insert(children, ui.node("col", { key = sec.id, gap = "xs" }, nodes)) else local items: { Node } = {} for _, r in sec.rows do - if Live.counts_down(r, now) then + if r.kind == "result" then + table.insert(items, T.result(state, r)) + elseif not timeline and Live.counts_down(r, now) then table.insert(items, Live.countdown_row(r, now, tier, row ~= nil and r == row, job_label(r.job, tier), upcoming_detail(r, now, tier))) else table.insert(items, item_node(r, now, tier)) end if row ~= nil and r == row then selected = r.id + items[#items].p.mark = "pick" end end table.insert(children, ui.node("list", { key = sec.id, selected = selected }, items)) @@ -732,15 +781,34 @@ function L.view(state: State): (Node, Node) end local dock = ui.col({ context_line(state, model, row), - C.with(ui.row(row_badges(state, row)), { key = "acts" }), - L.hints_text(state.cx.cols), + C.with(ui.row(row_badges(state, row, model)), { key = "acts", role = "tas.dock-actions" }), }) + if split and row ~= nil and row.kind ~= "invalid" then + local id = (row.job :: any).id + if state.detail == nil or state.detail.job_id ~= id then state.detail = { job_id = id, sel = nil, expanded = nil } end + if row.kind == "result" and not state.split_focus then state.detail.sel = (row.run :: any).run_id end + local detail = D.view(state, true, now) + local left = ui.node("col", { key = "timeline", role = "tas.timeline", gap = "sm" }, children) + local right = C.with(detail, { key = "detail", role = "tas.detail" }) + -- Native lists require absolute node ids after nesting. + local function rebase(n: any, prefix: string) + if n.p and type(n.p.selected) == "string" then n.p.selected = string.gsub(n.p.selected, "^main%.", prefix .. ".") end + for _, child in n.c or {} do rebase(child, prefix) end + end + rebase(left, "main.split.timeline"); rebase(right, "main.split.detail") + return ui.col({ ui.node("row", { key = "split", role = "tas.split", gap = "lg" }, { left, right }) }), dock + end return ui.col(children), dock end -- Keys -------------------------------------------------------------------------------------------------------- local function enter(state: State, row: Row) + if state.cx.cols >= C.SPLIT_COLS and row.kind ~= "invalid" and row.sec ~= "needs" then + state.detail = { job_id = (row.job :: any).id, sel = nil, expanded = nil } + state.split_focus = true + return + end if row.kind == "run" then local run: any = row.run if row.sec == "needs" then @@ -748,8 +816,8 @@ local function enter(state: State, row: Row) else A.open_detail(state, run.job_id) end - elseif row.kind == "job" then - A.open_detail(state, row.key) + elseif row.kind == "job" or row.kind == "result" then + A.open_detail(state, (row.job :: any).id) end end @@ -783,7 +851,7 @@ local function job_id_of(row: Row): string if row.kind == "run" then return (row.run :: any).job_id end - return row.key + return (row.job :: any).id end -- Starts the form for a new job or opens a settings sheet, etc.; `true` when the state changed. @@ -794,6 +862,10 @@ local function key_inner(state: State, k: Key): boolean? if name == "?" or (name == "/" and k.shift) then S.open_help(state) return true + elseif name == "s" then + if not model.unseen then return false end + T.clear(state) + return true elseif name == "," then S.open_settings(state) return true @@ -979,6 +1051,15 @@ function L.event(state: State, ev: UiEvent) A.pause_all(state) elseif act == "new" then A.new_job(state) + elseif act == "details" then + local row = L.sync(state, L.model(state)) + if row then + if state.split_focus then D.key(state, { name = "enter" } :: any) else enter(state, row) end + end + elseif act == "seen" then + if L.model(state).unseen then T.clear(state) end + elseif act == "example" then + use_example(state, state.example_sel) elseif act == "settings" then S.open_settings(state) elseif act == "help" then diff --git a/lib/mgr_live.luau b/lib/mgr_live.luau index 81c01e2..af0e14f 100644 --- a/lib/mgr_live.luau +++ b/lib/mgr_live.luau @@ -149,16 +149,15 @@ function M.countdown_row(row: Row, now: number, tier: number, selected: boolean, local soon = nxt - now < 300 local tone = if soon then "accent" else "muted" local last: any = js.last_run - local failed = type(last) == "table" and (last.state == "failed" or last.state == "timed_out") + local failed = require("./mgr_history").ensure((row.job :: any).id).failed -- Same parts as a list `item` (icon, label, detail, value); manager.css gives the row an item's metrics. local parts: { Node } = { ui.node("icon", { key = "i", name = if failed then "x-circle" else "clock", tone = if failed then "error" else "muted" }), C.with(ui.text(label), { key = "l" }), C.with(ui.text({ ui.span(detail or "", "muted") }), { key = "d", grow = 1, shrink = 1 }), } - local when = if tier >= 3 then C.when_text(nxt, now) .. " · in " else "in " - table.insert(parts, C.with(ui.text({ ui.span(when, tone) }), { key = "w" })) - table.insert(parts, ui.node("elapsed", { key = "t", age = -math.floor((nxt - now) * 1000), format = "clock", tone = tone })) + local when = (if tier >= 3 then C.when_text(nxt, now) .. " · " else "") .. C.in_text(nxt, now) + table.insert(parts, C.with(ui.text({ ui.span(when, tone .. " mono") }), { key = "w" })) return ui.node("row", { key = row.key, role = "tas.soon", diff --git a/lib/mgr_sheets.luau b/lib/mgr_sheets.luau index f7a0f38..6aaa6d0 100644 --- a/lib/mgr_sheets.luau +++ b/lib/mgr_sheets.luau @@ -1,12 +1,14 @@ --!strict --- Manager layer: role and presets pickers, stop confirm, "Run it now and watch?", key help, the Setup sheet and --- the Settings sheet. State lives in `state.sheet`; the manager routes keys and events here while a sheet is open. +-- Manager layer: role and presets pickers, stop confirm, "Run it now and watch?", key help and the Settings sheet +-- (one page: setup status, display, where runs start, limits). State lives in `state.sheet`; the manager routes +-- keys and events here while a sheet is open. local ui = tern.ui local C = require("./mgr_common") local P = require("./mgr_prefs") local F = require("./mgr_form") local textfield = require("./textfield") +local timefmt = require("./timefmt") local schedule = require("./schedule") local cron = require("./cron") local const = require("./const") @@ -40,25 +42,37 @@ local PRESETS: { Preset } = { { id = "manual", label = "Manual only", phrase = "manual" }, } -local HELP_KEYS: { { string } } = { - { "j k ↑ ↓", "Move the selection (g / G first / last)" }, - { "enter", "Open the job (a run that needs you: open its terminal)" }, - { "n", "New job" }, - { "e", "Edit the job" }, - { "r", "Run now" }, - { "i", "Check a job's conditions now" }, - { "space", "Pause or resume the job" }, - { "d d", "Delete the job (any other key cancels)" }, - { "u", "Undo the last delete (10 s)" }, - { "c", "Duplicate the job" }, - { "h", "History" }, - { "o", "Open the job's run terminal" }, - { "x", "Stop the running run" }, - { "p", "Edit the prompt file" }, - { "a", "Jump to a run that needs you" }, - { "⇧P", "Pause all / resume all (shift+p)" }, - { ",", "Settings" }, - { "esc", "Back" }, +type HelpRow = { keys: { string }, text: string } + +-- Keys as the dock writes them: lowercase as typed, a capital means shift (P is shift+p, p is the prompt file). +local HELP_JOB: { HelpRow } = { + { keys = { "r" }, text = "Run now" }, + { keys = { "e" }, text = "Edit" }, + { keys = { "space" }, text = "Pause or resume" }, + { keys = { "c" }, text = "Duplicate" }, + { keys = { "i" }, text = "Check its conditions now" }, + { keys = { "p" }, text = "Edit its prompt file" }, + { keys = { "h" }, text = "History" }, + { keys = { "o" }, text = "Open its run terminal" }, + { keys = { "x" }, text = "Stop its running run" }, + { keys = { "dd" }, text = "Delete (any other key cancels)" }, + { keys = { "u" }, text = "Undo a delete, for 10 s" }, +} + +local HELP_MOVE: { HelpRow } = { + { keys = { "j", "k" }, text = "Move the selection (or ↑ ↓)" }, + { keys = { "g", "G" }, text = "First or last job" }, + { keys = { "enter" }, text = "Open the job, or the terminal of a run that needs you" }, + { keys = { "a" }, text = "Jump to a run that needs you" }, + { keys = { "esc" }, text = "Back" }, +} + +local HELP_ALL: { HelpRow } = { + { keys = { "n" }, text = "New job" }, + { keys = { "s" }, text = "Mark all results seen" }, + { keys = { "P" }, text = "Pause or resume all jobs" }, + { keys = { "," }, text = "Settings" }, + { keys = { "?" }, text = "This help" }, } -- Picker helpers ---------------------------------------------------------------------------------------- @@ -333,8 +347,8 @@ local function confirm_stop_node(state: State, sheet: Sheet): Node return dialog("Stop " .. run_name(sheet.run_id) .. "?", "sm", { C.text({ ui.span("This closes the run's terminal. Its record stays, and Open run can resume the session.", "muted") }, "body"), C.with(ui.row({ - C.badge("Stop run y", "error", "stop_yes", "yes"), - C.badge("Keep esc", "neutral", "stop_no", "no"), + C.action_button("Stop run", "y", "error", "stop_yes", "yes"), + C.action_button("Keep", "esc", "neutral", "stop_no", "no"), }), { key = "acts" }), }) end @@ -348,8 +362,8 @@ local function first_run_node(_state: State, _sheet: Sheet): Node ), }, "body"), C.with(ui.row({ - C.badge("Run now ⏎", "accent", "first_yes", "yes"), - C.badge("Not now esc", "neutral", "first_no", "no"), + C.action_button("Run now", "⏎", "accent", "first_yes", "yes"), + C.action_button("Not now", "esc", "neutral", "first_no", "no"), }), { key = "acts" }), }) end @@ -359,8 +373,8 @@ local function run_anyway_node(_state: State, sheet: Sheet): Node C.text({ ui.span("Not running: " .. tostring(sheet.text or "a condition said no") .. ".") }, "body"), C.text({ ui.span("Run anyway runs it once now without checking its conditions.", "muted") }, "note"), C.with(ui.row({ - C.badge("Run anyway ⏎", "accent", "anyway_yes", "yes"), - C.badge("Cancel esc", "neutral", "anyway_no", "no"), + C.action_button("Run anyway", "⏎", "accent", "anyway_yes", "yes"), + C.action_button("Cancel", "esc", "neutral", "anyway_no", "no"), }), { key = "acts" }), }) end @@ -406,21 +420,47 @@ local function conditions_node(_state: State, sheet: Sheet): Node end local acts: { Node } = {} if sheet.job_id ~= nil and #seen > 0 then - table.insert(acts, C.badge("Forget what it has seen f", "neutral", "cond_forget", "forget")) + table.insert(acts, C.action_button("Forget what it has seen", "f", "neutral", "cond_forget", "forget")) end - table.insert(acts, C.badge("Close esc", "neutral", "cond_close", "close")) + table.insert(acts, C.action_button("Close", "esc", "neutral", "cond_close", "close")) table.insert(body, C.with(ui.row(acts), { key = "acts" })) return dialog("Conditions · " .. name, "md", body) end -local function help_node(_state: State, _sheet: Sheet): Node - local rows: { { Spans } } = {} - for _, r in HELP_KEYS do - table.insert(rows, { { ui.span(r[1], "key") }, { ui.span(r[2]) } }) +local function help_group(key: string, title: string, rows: { HelpRow }): Node + local items: { Node } = {} + for _, r in rows do + local caps: { Node } = {} + for _, k in r.keys do + table.insert(caps, ui.el("kbd", { text = k })) + end + table.insert(items, ui.el("dt", {}, caps)) + table.insert(items, ui.el("dd", { text = r.text })) end - return dialog("Keys", "md", { - ui.kv(rows), - C.text({ ui.span("Most actions also have a button under the list. esc closes this.", "muted") }, "foot"), + return ui.el("section", { key = key, class = "tas-help-group" }, { + ui.el("h3", { text = title }), + ui.el("dl", {}, items), + }) +end + +local function help_node(_state: State, _sheet: Sheet): Node + return dialog("Help", "lg", { + ui.el("div", { key = "keys", class = "tas-help-cols" }, { + help_group("job", "The selected job", HELP_JOB), + ui.el("div", { key = "side", class = "tas-help-stack" }, { + help_group("move", "Move and open", HELP_MOVE), + help_group("all", "All jobs", HELP_ALL), + }), + }), + ui.el("section", { key = "when", class = "tas-help-when" }, { + ui.el("h3", { text = "When jobs run" }), + ui.el("p", { text = C.AVAILABILITY }), + ui.el("p", { text = C.NO_WINDOW }), + }), + C.with(ui.row({ + C.text({ ui.span("Most of these are also buttons under the list.", "muted") }, "note"), + C.action_button("Close", "esc", "neutral", "help_close", "close"), + }), { key = "foot", role = "tas.help-foot" }), }) end @@ -440,43 +480,10 @@ local function heartbeat_text(): string if ok and type(health) == "table" then local hb: any = (health :: any).hb if type(hb) == "number" and hb > 0 then - return "Last scheduler tick " .. C.span_text(C.now() - hb) .. " ago." + return "Scheduler heartbeat " .. C.span_text(C.now() - hb) .. " ago." end end - return "The scheduler hasn't ticked yet." -end - -local function setup_node(_state: State, sheet: Sheet): Node - local body: { Node } = {} - for i, row in setup_rows() do - local glyph, tone - if row.ok == true then - glyph, tone = "✓ ", "muted" - elseif row.ok == false and INFO_ROWS[row.id] then - glyph, tone = "! ", "warning" - elseif row.ok == false then - glyph, tone = "✗ ", "error" - else - glyph, tone = "· ", "muted" - end - table.insert(body, C.text({ ui.span(glyph, tone), ui.span(tostring(row.label), "strong"), ui.span(" " .. tostring(row.text), "muted") }, "row" .. i)) - end - if #body == 0 then - table.insert(body, C.text({ ui.span("No results yet. Press c to check.", "muted") }, "none")) - end - table.insert(body, C.text({ ui.span(heartbeat_text(), "muted") }, "hb")) - table.insert(body, C.text({ ui.span(C.AVAILABILITY, "muted") }, "avail")) - table.insert(body, C.text({ ui.span(C.NO_WINDOW, "muted") }, "nowin")) - table.insert(body, C.text({ ui.span(C.WINDOWS, "muted") }, "wins")) - table.insert( - body, - C.with(ui.row({ - C.badge(if sheet.checking == true then "Checking…" else "Check again c", "accent", "setup_check", "check"), - C.badge("Open data folder", "neutral", "open_data", "data"), - C.badge("Close esc", "neutral", "close_sheet", "close"), - }), { key = "acts" }) - ) - return ui.node("overlay", { key = "dialog", head = "Check setup", size = "md", modal = true }, body) + return "The scheduler hasn't started yet." end local function run_setup_check(state: State, sheet: Sheet) @@ -487,6 +494,7 @@ local function run_setup_check(state: State, sheet: Sheet) local started = pcall(function() runner.check_setup(function() sheet.checking = false + sheet.checked_at = C.now() C.render(state) end) end) @@ -511,6 +519,77 @@ end -- Settings --------------------------------------------------------------------------------------------------- +-- What each settings row resets to. `catchup_window_s` is in hours, as the row shows it; `focus` is the switch. +local DEFAULTS: { [string]: any } = { + time_format = "automatic", + manager_layout = "timeline", + manager_results = "fade", + placement = "session", + focus = false, + session_name = const.SESSION_NAME_DEFAULT, + omp_path = "", + max_concurrent = const.MAX_CONCURRENT_DEFAULT, + max_finished_panes = const.MAX_FINISHED_PANES, + catchup_window_s = const.CATCHUP_DEFAULT_S // 3600, +} + +local CATCHUP_LABELS: { [string]: string } = { + ["1"] = "1 h", + ["2"] = "2 h", + ["3"] = "3 h", + ["6"] = "6 h", + ["12"] = "12 h", + ["24"] = "1 day", + ["48"] = "2 days", + ["72"] = "3 days", + ["168"] = "1 week", +} + +-- Marks `row` with whether its value differs from the default, and how that default reads. +local function with_default(row: P.Row, value: any, default_label: string): P.Row + row.changed = value ~= DEFAULTS[row.id] + row.defaultLabel = default_label + return row +end + +local function short_path(p: string): string + local rest = p:match("^~/(.*)$") + if rest == nil then + return p + end + local segs = string.split(rest, "/") + if #segs <= 2 then + return p + end + return "~/" .. segs[1] .. "/…/" .. segs[#segs] +end + +-- The typed range of each number row; the draft is checked against it before it is saved. `catchup_window_s` is hours. +local NUMBER_LIMITS: { [string]: { number } } = { + max_concurrent = { 1, 10 }, + max_finished_panes = { const.MAX_FINISHED_PANES_MIN, const.MAX_FINISHED_PANES_MAX }, + catchup_window_s = { 1, 168 }, +} + +-- A number row's control. While its value is being typed the kit shows the draft in a text field instead. +local function number_control(sheet: Sheet, id: string, value: number, extra: { [string]: any }?): { [string]: any } + local e = sheet.editing + if e ~= nil and e.row == id and sheet.field ~= nil then + return { k = "text", value = tostring(value) } + end + local limits = NUMBER_LIMITS[id] + local c: { [string]: any } = { k = "number", value = value, min = limits[1], max = limits[2] } + for k, v in extra or {} do + c[k] = v + end + return c +end + +-- The next step for a failed setup check whose own text doesn't give one. +local NEXT_STEP: { [string]: string } = { + data = "Check its permissions: Setup › Data folder › Open.", +} + local function settings_sections(state: State, sheet: Sheet): { P.Section } local s = jobs.settings() local d: any = s.defaults @@ -519,116 +598,215 @@ local function settings_sections(state: State, sheet: Sheet): { P.Section } local where = if type(placement) == "table" and placement.where == "tab" then "tab" else "session" local warn = sheet.warnings or {} local window_s = if type(s.catchup_window_s) == "number" then s.catchup_window_s else const.CATCHUP_DEFAULT_S + local window_h = math.max(1, window_s // 3600) local panes = if type(s.max_finished_panes) == "number" then s.max_finished_panes else const.MAX_FINISHED_PANES local session_name = if type(s.session_name) == "string" then s.session_name else const.SESSION_NAME_DEFAULT - if sheet.page == "setup" then - return { - { - id = "setup", - title = "Setup", - rows = { - { - id = "check", - label = "Check setup", - hint = heartbeat_text(), - control = { k = "action", act = "check", label = "Check…" }, - }, - { - id = "avail", - label = "Availability", - hint = C.AVAILABILITY, - control = { k = "action", act = "details", label = "Details" }, + local omp_path = if type(s.omp_path) == "string" then s.omp_path else "" + local concurrent = tonumber(s.max_concurrent) or const.MAX_CONCURRENT_DEFAULT + local time_format = s.time_format or "automatic" + local layout = s.manager_layout or "timeline" + local results = s.manager_results or "fade" + local focus_on = def.focus == "front" + + -- Setup checks: a blocking failure means jobs won't run; INFO_ROWS only inform. + local blocking = false + local problems: { string } = {} + local availability = false + local omp_check: any = nil + for _, r in setup_rows() do + if r.id == "omp" then + omp_check = r + end + if r.ok == false then + local info = INFO_ROWS[r.id] == true + blocking = blocking or not info + local line = (if info then "! " else "✗ ") .. tostring(r.label) .. ": " .. tostring(r.text) + if NEXT_STEP[r.id] ~= nil then + line ..= " " .. NEXT_STEP[r.id] + end + table.insert(problems, line) + availability = availability or r.id == "heartbeat" or r.id == "keepalive" + end + end + if availability then + table.insert(problems, C.AVAILABILITY) + end + local status_hint = heartbeat_text() + if sheet.checked_at ~= nil then + status_hint = "Checked " .. timefmt.date("%H:%M", sheet.checked_at) .. " · " .. status_hint + end + + local omp_hint = "Agent Scheduler starts each run with omp." + if omp_check ~= nil and omp_check.ok == true then + local f = bins.found() + if f.omp ~= nil and f.omp ~= "" then + local ver = (f.omp_version or ""):gsub("^omp[/ ]", "") + local at = C.tilde(f.omp) + omp_hint ..= if ver ~= "" then " Found " .. ver .. " at " .. at .. "." else " Found at " .. at .. "." + else + omp_hint ..= " Found " .. tostring(omp_check.text) .. "." + end + end + omp_hint ..= " Leave empty to find it automatically." + local omp_warning: string? = warn.omp_path + if omp_warning == nil and omp_check ~= nil and omp_check.ok == false then + omp_warning = tostring(omp_check.text) + end + + local time_hint = if time_format == "12h" + then "Times show as 2:30 pm." + elseif time_format == "24h" then "Times show as 14:30." + else "Follows your system, with a 24-hour fallback." + + return { + { + id = "health", + title = "Status", + rows = { + { + id = "status", + label = if blocking then "Not ready to run jobs" else "✓ Ready to run jobs", + hint = status_hint, + warning = if #problems > 0 then table.concat(problems, "\n") else nil, + control = { k = "action", act = "check", label = if sheet.checking == true then "Checking…" else "Check again" }, + }, + }, + }, + { + id = "display", + title = "Display", + rows = { + with_default({ + id = "time_format", + label = "Time format", + hint = time_hint, + control = { + k = "choice", + style = "segmented", + value = time_format, + options = { { value = "automatic", label = "Automatic" }, { value = "12h", label = "12-hour" }, { value = "24h", label = "24-hour" } }, }, - { - id = "omp_path", - label = "omp path", - hint = "Where Agent Scheduler finds omp. Leave it empty to find omp automatically.", - warning = warn.omp_path, - control = { k = "text", value = if type(s.omp_path) == "string" then s.omp_path else "", placeholder = "Automatic", mono = true }, + }, time_format, "Automatic"), + with_default({ + id = "manager_layout", + label = "Layout", + control = { + k = "choice", + style = "segmented", + value = layout, + options = { { value = "timeline", label = "Timeline" }, { value = "classic", label = "Classic job list" } }, }, - { - id = "data", - label = "Data folder", - hint = tern.plugin.data, - control = { k = "action", act = "open_data", label = "Open data folder" }, + }, layout, "Timeline"), + with_default({ + id = "manager_results", + label = "New results", + hint = "Fade after three seconds in the manager, or keep highlights until you mark all seen.", + control = { + k = "choice", + style = "menu", + value = results, + options = { { value = "fade", label = "Fade once seen" }, { value = "stay", label = "Stay until marked seen" } }, }, - }, + }, results, "Fade once seen"), }, - } - end - return { + }, { id = "runs", - title = "Runs", + title = "Where runs start", rows = { - { + with_default({ id = "placement", - label = "Where runs appear", - hint = C.WINDOWS, + label = "Session", + hint = "Runs open as background tabs, in the first Tern window if several are open.", warning = warn.placement, control = { k = "choice", - value = where, style = "menu", + value = where, options = { - { value = "session", label = "Scheduled runs session, background tab" }, - { value = "tab", label = "Background tab in the current session" }, + { value = "session", label = "Scheduled runs session", detail = "A background tab in a session of its own, named below." }, + { value = "tab", label = "Current session", detail = "A background tab in the session you're using." }, }, }, - }, - { - id = "focus", - label = "Bring to front when it starts", - hint = "Off: the run starts quietly and you stay where you are.", - warning = warn.focus, - control = { k = "switch", on = def.focus == "front" }, - }, - { + }, where, "Scheduled runs session"), + with_default({ id = "session_name", - label = "Run session name", - hint = "The session scheduled runs open in.", + label = "Session name", + hint = "The name of the Scheduled runs session.", warning = warn.session_name, control = { k = "text", value = session_name }, - }, - { - id = "max_finished_panes", - label = "Finished run panes to keep", - hint = string.format( - "Each finished run keeps an omp process open, roughly 100–500 MB. Tern closes the oldest beyond %d; Open run reopens any of them.", - panes - ), - warning = warn.max_finished_panes, - control = { k = "number", value = panes, min = const.MAX_FINISHED_PANES_MIN, max = const.MAX_FINISHED_PANES_MAX }, - }, - { + }, session_name, const.SESSION_NAME_DEFAULT), + with_default({ + id = "focus", + label = "Bring to front when it starts", + hint = if focus_on + then "On: Tern switches to the run's tab as soon as it starts." + else "Off: the run starts quietly and you stay where you are.", + warning = warn.focus, + control = { k = "switch", on = focus_on }, + }, focus_on, "Off"), + }, + }, + { + id = "limits", + title = "Limits", + rows = { + with_default({ id = "max_concurrent", label = "Jobs running at once", hint = "A run over the limit waits, then is skipped with a reason.", warning = warn.max_concurrent, - control = { k = "number", value = tonumber(s.max_concurrent) or const.MAX_CONCURRENT_DEFAULT, min = 1, max = 10 }, - }, - { + control = number_control(sheet, "max_concurrent", concurrent), + }, concurrent, tostring(const.MAX_CONCURRENT_DEFAULT)), + with_default({ + id = "max_finished_panes", + label = "Finished run tabs to keep", + hint = "Each finished run keeps an omp process open, roughly 100–500 MB. Tern closes the oldest tabs past this number; Open run reopens any of them.", + warning = warn.max_finished_panes, + control = number_control(sheet, "max_finished_panes", panes), + }, panes, tostring(const.MAX_FINISHED_PANES)), + with_default({ id = "catchup_window_s", - label = "Late limit for missed runs", - hint = "If your " .. platform.machine() .. " was asleep: a run later than this is recorded as missed.", + label = "If your " .. platform.machine() .. " was asleep", + hint = "How late a missed run can be and still start when you're back. Later ones are recorded as missed.", warning = warn.catchup_window_s, - control = { k = "number", value = math.max(1, window_s // 3600), min = 1, max = 168, unit = "h" }, + control = number_control(sheet, "catchup_window_s", window_h, { unit = "h", labels = CATCHUP_LABELS }), + }, window_h, "3 h"), + }, + }, + { + id = "setup", + title = "Setup", + rows = { + with_default({ + id = "omp_path", + label = "omp", + hint = omp_hint, + warning = omp_warning, + control = { k = "text", value = omp_path, placeholder = "Find automatically", mono = true }, + }, omp_path, "Find automatically"), + { + id = "data", + label = "Data folder", + hint = short_path(C.tilde(tern.plugin.data)), + control = { k = "action", act = "open_data", label = "Open" }, }, }, }, } end -local function settings_pages(): { any } - return C.arr({ - { id = "runs", label = "Runs", icon = "timer" }, - { id = "setup", label = "Setup", icon = "shield-alert" }, - }) +-- The key legend at the bottom of the sheet; it follows what the keys do right now. +local function keys_legend(sheet: Sheet): string + if sheet.editing == nil then + return "↑↓ move · ←→ change · ⏎ edit · esc close" + elseif sheet.field ~= nil then + return "⏎ save · esc cancel" + end + return "↑↓ choose · ⏎ pick · esc cancel" end local function settings_node(state: State, sheet: Sheet): Node - sheet.page = sheet.page or "runs" - local sections = settings_sections(state, sheet) local editing: any = nil local e = sheet.editing if e ~= nil then @@ -641,20 +819,24 @@ local function settings_node(state: State, sheet: Sheet): Node end return ui.node("prefs", { key = "prefs", - title = "Settings", - pages = settings_pages(), - page = sheet.page, - lead = if sheet.page == "setup" then "Is Agent Scheduler able to run jobs?" else "How scheduled runs start and what Tern keeps.", - sections = P.node_sections(sections), + role = "tas.settings", + title = "Agent Scheduler Settings", + pages = C.arr({ { id = "settings", label = "Agent Scheduler", icon = "timer" } }), + page = "settings", + sections = P.node_sections(settings_sections(state, sheet)), focus = sheet.focus, editing = editing, - }, {}) + }, { + C.with(C.text({ ui.span(keys_legend(sheet), "muted") }, "keys"), { key = "keys", role = "tas.settings-keys" }), + }) end --- Applies the settings row `id` with `value`; a problem is shown on the row. -local function apply_setting(state: State, sheet: Sheet, id: string, value: any) +-- Applies the settings row `id` with `value`; a problem is shown on the row. True when the value was saved. +local function apply_setting(state: State, sheet: Sheet, id: string, value: any): boolean local patch: { [string]: any } - if id == "placement" then + if id == "manager_layout" or id == "manager_results" or id == "time_format" then + patch = { [id] = value } + elseif id == "placement" then patch = { defaults = { placement = { where = value } } } elseif id == "focus" then patch = { defaults = { focus = if value == true then "front" else "keep" } } @@ -677,9 +859,10 @@ local function apply_setting(state: State, sheet: Sheet, id: string, value: any) bins.invalidate() run_setup_check(state, sheet) end - else - warnings[id] = err or "That value isn't allowed." + return true end + warnings[id] = err or "That value isn't allowed." + return false end local function settings_row(state: State, sheet: Sheet, id: string?): P.Row? @@ -687,9 +870,8 @@ local function settings_row(state: State, sheet: Sheet, id: string?): P.Row? end local function settings_act(state: State, sheet: Sheet, act: string) - if act == "check" or act == "details" then - state.sheet = { kind = "setup" } - run_setup_check(state, state.sheet) + if act == "check" then + run_setup_check(state, sheet) elseif act == "open_data" then open_data_folder() end @@ -700,10 +882,17 @@ local function settings_activate(state: State, sheet: Sheet, row: P.Row): boolea local c = row.control if c.k == "switch" then apply_setting(state, sheet, row.id, not c.on) + elseif c.k == "choice" and c.style == "segmented" then + -- Enter steps to the next option, wrapping. + local values = P.option_values(c) + local to = values[((table.find(values, c.value) or 0) % #values) + 1] + if to ~= nil then + apply_setting(state, sheet, row.id, to) + end elseif c.k == "choice" then sheet.editing = { row = row.id, initial = tostring(c.value), option = c.value } sheet.field = nil - elseif c.k == "text" then + elseif c.k == "text" or c.k == "number" then sheet.editing = { row = row.id, initial = tostring(c.value or "") } sheet.field = textfield.new(tostring(c.value or "")) elseif c.k == "action" then @@ -720,19 +909,35 @@ local function close_editing(sheet: Sheet) end local function key_settings(state: State, sheet: Sheet, k: Key): boolean? - sheet.page = sheet.page or "runs" local name = k.name local e = sheet.editing if e ~= nil then local row = settings_row(state, sheet, e.row) if sheet.field ~= nil then if name == "enter" then - if sheet.field.text ~= e.initial then - apply_setting(state, sheet, e.row, sheet.field.text) + -- A rejected value keeps the editor open on the draft, with the problem on the row. + local draft = sheet.field.text + local limits = NUMBER_LIMITS[e.row] + local value: any = draft + if limits ~= nil and draft ~= e.initial then + local n = if string.match(C.trim(draft), "^%d+$") ~= nil then tonumber(C.trim(draft)) else nil + if n == nil or n < limits[1] or n > limits[2] then + local warnings = sheet.warnings or {} + sheet.warnings = warnings + warnings[e.row] = string.format("Type a whole number from %d to %d.", limits[1], limits[2]) + return true + end + value = n + end + if draft == e.initial then + (sheet.warnings or {})[e.row] = nil + close_editing(sheet) + elseif apply_setting(state, sheet, e.row, value) then + close_editing(sheet) end - close_editing(sheet) return true elseif name == "escape" then + (sheet.warnings or {})[e.row] = nil close_editing(sheet) return true end @@ -768,17 +973,14 @@ local function key_settings(state: State, sheet: Sheet, k: Key): boolean? if name == "escape" then state.sheet = nil return true - elseif name == "up" or name == "down" then - local target = P.move(settings_sections(state, sheet), sheet.focus, if name == "up" then -1 else 1) + elseif name == "up" or name == "down" or name == "tab" then + local back = name == "up" or (name == "tab" and k.shift == true) + local target = P.move(settings_sections(state, sheet), sheet.focus, if back then -1 else 1) if target == nil then return false end sheet.focus = target return true - elseif name == "tab" then - sheet.page = if sheet.page == "runs" then "setup" else "runs" - sheet.focus = nil - return true end local row = settings_row(state, sheet, sheet.focus) if row == nil then @@ -787,22 +989,22 @@ local function key_settings(state: State, sheet: Sheet, k: Key): boolean? if name == "left" or name == "right" then local c = row.control local dir = if name == "left" then -1 else 1 - if c.k == "choice" then - local values = P.option_values(c) - local at = table.find(values, c.value) or 0 - local j = math.clamp(at + dir, 1, math.max(#values, 1)) - if values[j] == nil or values[j] == c.value then - return false - end - apply_setting(state, sheet, row.id, values[j]) - return true - elseif c.k == "number" then + if c.k == "number" then local n = P.step_number(c, dir) if n == nil then return false end apply_setting(state, sheet, row.id, n) return true + elseif c.k == "choice" and c.style == "segmented" then + -- No wrap: the ends stay put. + local values = P.option_values(c) + local to = values[(table.find(values, c.value) or 0) + dir] + if to == nil then + return false + end + apply_setting(state, sheet, row.id, to) + return true end return false elseif name == "enter" or name == "space" then @@ -815,11 +1017,7 @@ local function event_settings(state: State, sheet: Sheet, ev: UiEvent) local kind = ev.ev local item = ev.item if kind == "action" then - if ev.act == "page" and type(ev.value) == "string" then - sheet.page = ev.value - sheet.focus = nil - close_editing(sheet) - elseif ev.act == "close" then + if ev.act == "close" then if ev.value == nil or ev.value == tern.json.null then state.sheet = nil else @@ -830,9 +1028,16 @@ local function event_settings(state: State, sheet: Sheet, ev: UiEvent) end elseif kind == "change" and type(item) == "string" then local row = settings_row(state, sheet, item) - if row ~= nil and ev.value ~= nil and ev.value ~= tern.json.null then - apply_setting(state, sheet, item, ev.value) - sheet.focus = item + if row ~= nil then + -- A null value is Reset: back to the row's default. + local value = ev.value + if value == nil or value == tern.json.null then + value = DEFAULTS[item] + end + if value ~= nil then + apply_setting(state, sheet, item, value) + sheet.focus = item + end end close_editing(sheet) elseif kind == "activate" and type(item) == "string" then @@ -848,12 +1053,12 @@ end -- Entry points ----------------------------------------------------------------------------------------------- function S.open_settings(state: State) - state.sheet = { kind = "settings", page = "runs", warnings = {} } + state.sheet = { kind = "settings", focus = "status", warnings = {} } end function S.open_setup(state: State) - state.sheet = { kind = "setup" } - run_setup_check(state, state.sheet) + S.open_settings(state) + run_setup_check(state, state.sheet :: Sheet) end function S.open_help(state: State) @@ -897,8 +1102,6 @@ function S.layer(state: State): Node? return conditions_node(state, sheet) elseif kind == "help" then return help_node(state, sheet) - elseif kind == "setup" then - return setup_node(state, sheet) elseif kind == "settings" then return settings_node(state, sheet) end @@ -994,15 +1197,6 @@ function S.key(state: State, k: Key): boolean? return true end return false - elseif kind == "setup" then - if name == "escape" then - state.sheet = nil - return true - elseif name == "c" or name == "enter" then - run_setup_check(state, sheet) - return true - end - return false elseif kind == "help" then if name == "escape" or name == "?" or name == "q" or name == "enter" then state.sheet = nil @@ -1042,12 +1236,8 @@ function S.event(state: State, ev: UiEvent) do_run_anyway(state, sheet) elseif act == "cond_forget" then do_forget(state, sheet) - elseif act == "stop_no" or act == "first_no" or act == "anyway_no" or act == "cond_close" or act == "close_sheet" then + elseif act == "stop_no" or act == "first_no" or act == "anyway_no" or act == "cond_close" or act == "help_close" then state.sheet = nil - elseif act == "setup_check" then - run_setup_check(state, sheet) - elseif act == "open_data" then - open_data_folder() end end end diff --git a/lib/mgr_timeline.luau b/lib/mgr_timeline.luau new file mode 100644 index 0000000..6fc5023 --- /dev/null +++ b/lib/mgr_timeline.luau @@ -0,0 +1,162 @@ +--!strict +local timefmt = require("./timefmt") +-- Timeline projection shares the classic list's selection and action routing. +local C = require("./mgr_common") +local jobs = require("./jobs") +local ledger = require("./ledger") +local H = require("./mgr_history") +local ui = tern.ui +local T = {} +local TERMINAL = { finished = true, failed = true, timed_out = true, blocked = true, skipped = true, missed = true, cancelled = true } +local GLYPH = { finished = "✓", failed = "✗", timed_out = "✗", blocked = "✗", skipped = "↷", missed = "◌", cancelled = "■" } +function T.clear(state: any) + H.clear(C.now()) + state.looked_at = C.now() + state.history_baseline = nil + state.seen_results = {} + C.notice(state, "All results marked seen.") +end +function T.model(state: any, model: any, frame_now: number?): any + local results, nexts, bottom, live = {}, {}, {}, {} + local since = state.looked_at or jobs.settings().last_looked or 0 + local busy = {} + for _, sec in model.sections do + for _, row in sec.rows do + if row.kind == "run" then busy[row.job.id] = true; table.insert(live, row) end + end + end + for _, sec in model.sections do + for _, row in sec.rows do + if row.kind ~= "run" and not busy[row.job.id] then + if row.kind == "job" and sec.id == "upcoming" and row.job.schedule.kind ~= "manual" then table.insert(nexts, row) + else table.insert(bottom, row) end + end + end + end + state.history_baseline = state.history_baseline or {} + local counts, total = {}, 0 + for _, j in jobs.list() do + local h = H.ensure(j.id) + local base = state.history_baseline[j.id] + if base == nil then + base = {} + for k, n in h.totals do base[k] = n - (h.pending[k] or 0) end + state.history_baseline[j.id] = base + end + local c = {} + for k, n in h.totals do c[k] = math.max(0, n - (base[k] or 0)) end + counts[j.id] = c + total += c.total + for _, r in ledger.recent(j.id, 500) do + if TERMINAL[r.state] and r.trigger ~= "test" and (r.ended or r.slot or 0) > since then + table.insert(results, { sec = "results", key = r.run_id, id = C.item_id("results", r.run_id), kind = "result", job = j, run = r, js = jobs.state(j.id) }) + end + end + end + table.sort(results, function(a, b) + local x, y = a.run.ended or a.run.slot or 0, b.run.ended or b.run.slot or 0 + return if x == y then a.key < b.key else x < y + end) + if total > 8 then + -- Failures keep their own rows (pinned above). Each other job folds into one summary row whose + -- "latest" names its newest result that isn't pinned, so a failure is never shown twice. + local folded, latest, singles = {}, {}, {} + for _, row in results do + if H.failed(row.run) then + table.insert(folded, row) + else + latest[row.job.id] = row + end + end + for _, j in jobs.list() do + local c = counts[j.id] + local r = latest[j.id] + if c.total == 1 and r ~= nil then + -- One new run: show it as itself; a summary of one reads oddly. + table.insert(singles, r) + elseif c.total > 1 then + local parts = {} + local function add(n: number?, word: string) + if (n or 0) > 0 then table.insert(parts, string.format("%d %s", n, word)) end + end + add(c.ok, "finished") + add(c.skipped, "skipped") + add(c.missed, "missed") + add(c.failed, "failed, shown above") + local text = string.format("%d %s since %s: %s", c.total, if c.total == 1 then "run" else "runs", if since > 0 then timefmt.date("%a", since) else "your first visit", table.concat(parts, ", ")) + if r then text ..= " · latest “" .. tostring(r.run.summary or r.run.reason or r.run.state) .. "”" end + table.insert(folded, { sec = "results", key = j.id, id = C.item_id("results", j.id), kind = "result", job = j, run = if r then r.run else {}, js = jobs.state(j.id), error = text }) + end + end + for _, r in singles do table.insert(folded, r) end + results = folded + end + model.sections, model.flat, model.by_id = {}, {}, {} + local function section(id, title, rows) + local sec = { id = id, title = title, rows = rows, collapsed = false, count = #rows } + table.insert(model.sections, sec) + for _, row in rows do + row.sec = id; row.id = C.item_id(id, row.key) + table.insert(model.flat, row); model.by_id[row.id] = row + end + end + local needs, running = {}, {} + for _, r in live do table.insert(if r.sec == "needs" then needs else running, r) end + local now_at = frame_now or C.now() + model.unseen = #results > 0 + model.quiet = nil + if #results == 0 then + if since > 0 then + model.quiet = string.format("Nothing new since %s.", C.when_text(since, now_at)) + elseif model.next_job ~= nil and model.next_at ~= nil then + local at: number = model.next_at + model.quiet = string.format("Nothing has run yet. %s runs first, %s (%s).", (model.next_job :: any).name, C.when_text(at, now_at), C.in_text(at, now_at)) + else + model.quiet = "Nothing has run yet." + end + end + if #results > 0 then section("results", if since > 0 then "You last looked " .. C.abs(since) else "Results so far", results) end + -- Keep needs/running section identities for their existing key semantics. + if #results > 0 or #live > 0 then section("now", "now · " .. timefmt.date("%H:%M", now_at), {}) end + if #needs > 0 then section("needs", "Needs you", needs) end + if #running > 0 then section("running", "Running", running) end + if #nexts > 0 then section("upcoming", "Next runs", nexts) end + if #bottom > 0 then section("rest", "Paused & needs fixing", bottom) end + return model +end +function T.result(state: any, row: any): Node + local r = row.run + local seen = state.seen_results or {} + state.seen_results = seen + local stamp = row.key .. ":" .. tostring(r.ended or r.slot or 0) + local fresh = not seen[stamp] + local bad = H.failed(r) + local text = row.error or tostring(r.summary or r.reason or r.state or "No result recorded") + text = string.match(text, "^[^\r\n]*") or text + local status = if r.outcome_flag == "quiet" then "quiet" else string.gsub(r.state or "finished", "_", " ") + local time = if row.error then "" else timefmt.date("%a %H:%M", r.started or r.created or r.slot or C.now()) .. " " + local node = ui.node("item", { key = row.key, role = if fresh then (if bad then "tas.new-failed" else "tas.new") else "tas.seen", + label = { ui.span(time, "mono"), ui.span((GLYPH[r.state] or "·") .. " " .. row.job.name, "strong"), ui.span(" · " .. status, if bad then "error" else "muted") }, + detail = { ui.span(text, if bad then "error" else "muted") }, + value = if not row.error and r.started and r.ended then { ui.span(C.duration_text(r.ended - r.started) .. " · " .. C.cost_text(r.cost), "mono") } else nil }) + -- Tern has no block visibility/closed event. A host timer is the documented fallback. + -- Never clear while a form/sheet covers the list; fresh outcomes get their own timer. + state.seen_pending = state.seen_pending or {} + if fresh and not state.seen_pending[stamp] and state.sheet == nil and jobs.settings().manager_results ~= "stay" then + state.seen_pending[stamp] = true + local checkpoint = C.now() + tern.timer(3000, function() + state.seen_pending[stamp] = nil + if state.mode ~= "list" or state.sheet ~= nil or jobs.settings().manager_results == "stay" then return end + local alive = false + for _, p in tern.pane.list() do if p.pane == state.cx.pane then alive = true end end + if not alive then return end + seen[stamp] = true + -- Keep this visit's rows in place; the next visit starts from this checkpoint. + H.clear(checkpoint) + C.render(state) + end) + end + return node +end +return T diff --git a/lib/runner.luau b/lib/runner.luau index 5c0be6b..1e4ab2d 100644 --- a/lib/runner.luau +++ b/lib/runner.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/runner.luau : the clock (EN §5-§7, LA §8-§10). Host only; outlives every manager block. -- pump (PUMP_MS, armed first): intents -> events -> [slow tick: due scan, liveness, housekeeping, -- heartbeat] -> advance runs (admission, timeouts, debounce) -> flush dirty state. @@ -210,6 +211,7 @@ local function record_outcome(run: Run) if job == nil then return end + require("./mgr_history").record(run) local st = jobs.state(job.id) local test = run.trigger == "test" local launched_like = state == "finished" or state == "failed" or state == "timed_out" or state == "cancelled" or state == "blocked" @@ -802,7 +804,7 @@ end local function slot_local(slot: number): string? local ok, s = pcall(function() - return os.date("%a %Y-%m-%d %H:%M", slot) + return timefmt.date("%a %Y-%m-%d %H:%M", slot) end) return ok and s :: string or nil end @@ -2066,12 +2068,12 @@ end setup_rows = function(): { SetupRow } local f = bins.found() local rows: { SetupRow } = {} - local tern_ok = f.tern ~= nil and version_at_least(f.tern_version or "", 0, 8, 3) + local tern_ok = f.tern ~= nil and version_at_least(f.tern_version or "", 0, 9, 0) table.insert(rows, { id = "tern", label = "Tern version", ok = tern_ok, - text = tern_ok and (f.tern_version or "") or "Agent Scheduler is built and tested on Tern 0.8.3. Update Tern.", + text = tern_ok and (f.tern_version or "") or "Agent Scheduler is built and tested on Tern 0.9.0. Update Tern.", }) table.insert(rows, { id = "omp", @@ -2102,9 +2104,9 @@ setup_rows = function(): { SetupRow } label = "Scheduler heartbeat", ok = hb_ok, text = if not hb_ok - then "The scheduler isn't ticking. Reload plugins (palette: Reload plugins)." + then "The scheduler has stopped. Reload plugins (palette: Reload plugins)." elseif S.last_hb == 0 then "The scheduler is starting." - else "The scheduler is ticking.", + else "The scheduler is running.", }) local health = store.health() local data_ok = health == "ok" and S.data_probe ~= false diff --git a/lib/snapshot.luau b/lib/snapshot.luau index 9413531..fdc71d5 100644 --- a/lib/snapshot.luau +++ b/lib/snapshot.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- lib/snapshot.luau : host -> window read model. Writes snapshot.json and bumps kv "hot" (EN §2.4). local const = require("./const") local jobs = require("./jobs") @@ -165,6 +166,7 @@ function snapshot.publish(view: View, now: number) end local snap: { [string]: any } = { format = 1, + time_format = timefmt.get(), rev = rev, at = now, paused_all = paused_all, diff --git a/lib/status.luau b/lib/status.luau index d68483c..101e61b 100644 --- a/lib/status.luau +++ b/lib/status.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Window half: the status-line segment (UX §2.3, §7.4), the scheduler stall watchdog (EN §5.5) and -- toasts from snapshot transitions (UX §7.3). The formatter only reads an upvalue; a timer -- refreshes it from the cached snapshot. Nothing here runs at load time. @@ -268,7 +269,7 @@ end local function next_text(at: any): string if type(at) == "number" then - return os.date("%a %d %b %H:%M", at) + return timefmt.date("%a %d %b %H:%M", at) end return "manual only" end diff --git a/lib/tern_state.luau b/lib/tern_state.luau index 2804f8e..fba98cf 100644 --- a/lib/tern_state.luau +++ b/lib/tern_state.luau @@ -1,9 +1,10 @@ --!strict -- lib/tern_state.luau : the one reader of `tern ls --json` (LA §2.0, R14). Sessions, blocks, liveness. --- Ids are turned into strings BEFORE decoding. A block is "ours" only when it was started as --- `/bin/zsh -l -c ''` (args[2] == "-c") and args[3] carries `/runs///` (V29): --- after a daemon restart a pane keeps its block id but becomes a bare login shell (args = {"-l"}) --- while `command` still shows the old command line, so `command` is never used for ownership. +-- Ids are turned into strings BEFORE decoding. A block is "ours" only when it was started as a shell +-- `-c ''` (Tern lists the argv as {"-c", cmd}, or {"-l", "-c", cmd} for a login shell) whose +-- command carries `/runs///prompt.md` (V29): after a daemon restart a pane keeps its block id but +-- becomes a bare shell (no "-c") while `command` still shows the old command line, so `command` is never used +-- for ownership. local bins = require("./bins") @@ -39,10 +40,15 @@ local MARKER = "@.-/runs/(j_[%w]+)/(r_[%w_]+)/prompt%.md" -- Run key ("/") a block belongs to, or nil. function tern_state.marker(b: any): string? local args = b.args - if type(args) ~= "table" or args[2] ~= "-c" or type(args[3]) ~= "string" then + if type(args) ~= "table" then return nil end - local job, run = (args[3] :: string):match(MARKER) + local at = if args[1] == "-c" then 2 elseif args[2] == "-c" then 3 else nil + local cmd = if at ~= nil then args[at] else nil + if type(cmd) ~= "string" then + return nil + end + local job, run = cmd:match(MARKER) if job == nil then return nil end diff --git a/lib/time_host.luau b/lib/time_host.luau new file mode 100644 index 0000000..307e5b0 --- /dev/null +++ b/lib/time_host.luau @@ -0,0 +1,68 @@ +--!strict +-- Host only: resolve Automatic once and persist it alongside the other regenerable caches. +local bins = require("./bins") +local platform = require("./platform") +local timefmt = require("./timefmt") +local time_host = {} +local selected = "automatic" +local probing = false + +local function run(argv: { string }, cb: (string?) -> ()) + local ok = pcall(function() + (tern :: any).process.run(argv, { timeout_ms = 2000 }, function(r: any) + cb(if r.status == 0 and not r.timed_out then tostring(r.stdout) else nil) + end) + end) + if not ok then cb(nil) end +end + +function time_host.locale_format(text: string?): string + -- Only t_fmt, never t_fmt_ampm (which exists even in 24-hour locales). + local pattern = if text then ("\n" .. text):match("\nt_fmt=([^\r\n]*)") else nil + return if pattern and (pattern:find("%%p") or pattern:find("%%I") or pattern:find("%%r")) then "12h" else "24h" +end + +local function enabled(text: string?): boolean + local value = if text then text:match("^%s*(.-)%s*$") else nil + return value == "1" or value == "true" or value == "YES" +end + +function time_host.configure(value: any) + selected = if value == "12h" or value == "24h" then value else "automatic" + if selected ~= "automatic" then + timefmt.set(selected) + return + end + local cached = bins.cache().time_format + if cached == "12h" or cached == "24h" then + timefmt.set(cached) + return + end + timefmt.set("24h") + if probing then return end + probing = true + local function finish(format: string) + probing = false + bins.cache().time_format = format + bins.cache_save() + -- A setting may have changed while the probe was in flight. + if selected == "automatic" then timefmt.set(format) end + end + local function locale() + run({ "/usr/bin/locale", "-k", "LC_TIME" }, function(text) + finish(time_host.locale_format(text)) + end) + end + if platform.is_mac() then + run({ "/usr/bin/defaults", "read", "-g", "AppleICUForce12HourTime" }, function(twelve) + if enabled(twelve) then return finish("12h") end + run({ "/usr/bin/defaults", "read", "-g", "AppleICUForce24HourTime" }, function(twenty_four) + if enabled(twenty_four) then finish("24h") else locale() end + end) + end) + else + locale() + end +end + +return time_host diff --git a/lib/timefmt.luau b/lib/timefmt.luau new file mode 100644 index 0000000..6ef1d7c --- /dev/null +++ b/lib/timefmt.luau @@ -0,0 +1,31 @@ +--!strict +-- Shared presentation only. No filesystem, process, or scheduler dependencies. +local timefmt = {} +local resolved = "24h" + +function timefmt.set(value: any) + resolved = if value == "12h" then "12h" else "24h" +end + +function timefmt.get(): string + return resolved +end + +function timefmt.clock(hour: number, minute: number): string + if resolved == "12h" then + hour %= 24 + return string.format("%d:%02d %s", if hour % 12 == 0 then 12 else hour % 12, minute, if hour < 12 then "am" else "pm") + end + return string.format("%02d:%02d", hour, minute) +end + +-- Presentation patterns retain their calendar fields; clocks share the selected format. +function timefmt.date(pattern: string, at: number?): string + if not pattern:find("%%H:%%M") then return os.date(pattern, at) :: string end + local stamp = at or os.time() + local clock = timefmt.clock(tonumber(os.date("%H", stamp)) or 0, tonumber(os.date("%M", stamp)) or 0) + local display = string.gsub(pattern, "%%H:%%M", clock) + return os.date(display, stamp) :: string +end + +return timefmt diff --git a/lib/wsnap.luau b/lib/wsnap.luau index 7494930..92b5baa 100644 --- a/lib/wsnap.luau +++ b/lib/wsnap.luau @@ -1,4 +1,5 @@ --!strict +local timefmt = require("./timefmt") -- Window half: the host's published snapshot, cached. snapshot.json is re-read only when the kv key -- `hot` reports a new `rev`. Nothing here runs at load time. @@ -18,6 +19,7 @@ local function read(): boolean local okd, value = pcall(tern.json.decode, text) if okd and type(value) == "table" and (value :: any).format == 1 then snap = value :: any + timefmt.set((value :: any).time_format) return true end return false diff --git a/manager.css b/manager.css index e4b2183..4dac271 100644 --- a/manager.css +++ b/manager.css @@ -1,135 +1,158 @@ -/* Agent Scheduler manager: job history bar chart (Detail view). */ -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bars { - display: flex; - flex-direction: row; - align-items: flex-end; - gap: 3px; - /* The main region is a flex column that shrinks its children; keep the track its full height. */ - flex: 0 0 56px; - height: 56px; - min-height: 56px; - padding: 2px 0; - box-sizing: border-box; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar { - flex: 0 0 14px; - width: 14px; - min-height: 2px; - border-radius: 2px 2px 0 0; - background: var(--sf-ok, var(--ok)); -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-o='fail'] { - background: var(--sf-bad, var(--bad)); -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-o='none'] { - background: var(--sf-muted); - opacity: 0.6; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='0'] { - height: 2px; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='1'] { - height: 5%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='2'] { - height: 10%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='3'] { - height: 15%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='4'] { - height: 20%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='5'] { - height: 25%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='6'] { - height: 30%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='7'] { - height: 35%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='8'] { - height: 40%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='9'] { - height: 45%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='10'] { - height: 50%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='11'] { - height: 55%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='12'] { - height: 60%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='13'] { - height: 65%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='14'] { - height: 70%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='15'] { - height: 75%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='16'] { - height: 80%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='17'] { - height: 85%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='18'] { - height: 90%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='19'] { - height: 95%; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .tas-bar[data-h='20'] { - height: 100%; -} +/* Native Tern, theme-owned colors. Selection stays native; no follower overlay. */ +/* prefs has no search-less prop or documented search-focus event. Hide its inert + search only in the job form; Settings and other plugins keep their native UI. */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] .pf-search { display: none; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] .pf { font-family: var(--sans); } +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.form-dock'] { font-family: var(--sans); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] [data-row='when'] .h, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] [data-row='stop'] .pf-pick, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] [data-row='c_from'] .pf-pick, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] [data-row='c_to'] .pf-pick, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] .pf-step .v { font-family: var(--mono); font-variant-numeric: tabular-nums; } +/* Essential policy values must remain readable even on the native narrow rail. */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.job-form'] [data-row='catch_up'] .pf-pick { white-space: normal; height: auto; } +/* In a block the layer's prefs sheet overlays main (no aside), and --panel is translucent under window glass. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .sf-prefs { background: var(--pop-bg); backdrop-filter: blur(24px) saturate(1.4); box-shadow: -12px 0 32px -16px rgb(0 0 0 / 35%); } +/* Settings is one page: the nav strip, search and eyebrow have nothing to navigate or number. Brand row and close stay. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-search, +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-groups, +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-eyebrow { display: none; } +/* Keyboard row focus needs a clear accent ring; the kit's 1px grey is ~2:1 against the sheet. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-row.focus { box-shadow: inset 0 0 0 2px var(--accent); border-radius: var(--r-ctl); } +/* Row rule: controls narrow enough to sit beside a readable label (the switch, short action buttons) stay inline; wider ones (segments, picks, fields, steppers) stack under the label in this ~440px sheet. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) { flex-direction: column; flex-wrap: nowrap; align-items: stretch; gap: 0; padding: 11px 14px 12px; } +/* Dissolve the label box so its parts become row items: the title, hint (or warning) and control can be ordered directly in the stacked row. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s'], [data-row='status']) .pf-lbl { display: contents; } +/* Title first, as a flex line so the kit's warning icon sits inline at its start, vertically centred; right padding is reserved for the Reset button so a changed row never rewraps its label. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-lbl .t { order: 1; padding-right: 40px; display: flex; align-items: center; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-lbl .t .ico.pf-warn-ic { flex: none; margin: 0 6px 0 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-lbl .h { order: 2; margin-top: 2px; } +/* Control on its own line under the hint, so layout does not flip with hint length. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-ctl { order: 3; flex: none; margin: 10px 0 0; display: flex; align-items: center; justify-content: flex-start; gap: 8px; } +/* A rejected value's reason (.h.pf-warn) takes the hint's place above the control, right where the user is fixing the field; the plain hint is hidden meanwhile so the row grows by at most a line. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-row.warn:is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path'], [data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-lbl .h:not(.pf-warn) { display: none; } +/* Reset sits at the row's top-right on the label line; out of flow, so the control keeps its full width when a row becomes changed. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-row .pf-reset { position: absolute; top: 8px; right: 10px; order: 0; } +/* Picks and text fields span the row (no 260px cap) so long option labels are not truncated; steppers keep natural width. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path']) .pf-pop { flex: 1 1 0; min-width: 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path']) .pf-pick, +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement'], [data-row='session_name'], [data-row='omp_path']) .pf-in { width: 100%; max-width: none; min-width: 0; flex: 1 1 0; box-sizing: border-box; } +/* Full-width picks: value at the left, chevron at the right edge (the kit anchors the open menu to the right edge). */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout'], [data-row='manager_results'], [data-row='placement']) .pf-pick { justify-content: space-between; text-align: left; } +/* The data row's hint is a filesystem path. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='data'] .pf-lbl .h { font-family: var(--mono); } +/* Placeholder uses --t3 (--t4 is 3.2:1 on the row card, under the 4.5:1 floor) in sans so it does not read as a typed path. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-in .ph { color: var(--t3); font-family: var(--sans); } +/* The switch row stays inline; its Reset keeps the kit's in-flow place beside the switch instead of overlapping it. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='focus'] .pf-reset { position: static; } +/* Settings is one page: the brand row's "Settings" is the only title, so the page head (title and lead) is redundant. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-head { display: none; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-doc { display: flex; flex-direction: column; min-height: 100%; padding: 4px 16px 0; } +/* Segments span the row with equal-width buttons; the kit only does this for .stack rows. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout']) .pf-seg { flex: 1 1 0; min-width: 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='time_format'], [data-row='manager_layout']) .pf-seg button { flex: 1 1 0; min-width: 0; padding: 0 6px; } +/* While typing a number the kit shows a text field; give it the stepper's width (30 + 104 + 30) so the row does not jump. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] :is([data-row='max_concurrent'], [data-row='max_finished_panes'], [data-row='catchup_window_s']) .pf-in { width: 164px; flex: none; box-sizing: border-box; } +/* The status row keeps its own layout: problems are one per line and wrap under the Check again button. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='status'] { flex-wrap: wrap; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='status'] .pf-lbl .t { order: 1; flex: 1 1 0; min-width: 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='status'] .pf-ctl { order: 2; flex: none; margin-left: auto; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='status'] .pf-lbl .h { order: 3; flex: 1 0 100%; margin-top: 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-row='status'] .pf-lbl .h.pf-warn { order: 4; white-space: pre-line; } +/* Tern's CSS has no scroll-margin; scroll-padding on the scroller is the closest, keeping a focused row's grown reason clear of the pinned key legend. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-scroll { scroll-padding-bottom: 64px; } +/* Section headings share the row labels' left edge (card inset 16px + row padding 14px). */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-sec { margin-top: 16px; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-sec-t { margin-left: 14px; } +/* Room between the last card and the key legend pinned at the bottom. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-sec:last-of-type { margin-bottom: 20px; } +/* Header uses the same 16px side inset as the content cards, so the brand mark and close sit on the card edges. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-nav { padding-left: 16px; padding-right: 16px; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-brand { padding-left: 0; } +/* Key legend pinned to the sheet bottom while rows scroll under it; muted 12px like the job form's key hints. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] .pf-extra { position: sticky; bottom: 0; margin: auto -16px 0; padding: 10px 30px 12px; background: var(--pop-bg); box-shadow: inset 0 1px 0 var(--l2); } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.settings'] [data-role='tas.settings-keys'] { font-size: 12px; line-height: 1.4; color: var(--t3); } -/* Upcoming row with a live countdown: a `row`, not an `item` (an item can't hold an `elapsed`), so it borrows - the item's metrics, hover and selection styling to sit flush with its neighbours. */ -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'] { - display: flex; - align-items: center; - gap: 8px; - min-width: 0; - min-height: calc(var(--sf-lh) + 6px); - padding: 0 8px 0 10px; - white-space: pre; - color: var(--t1); - cursor: pointer; - transition: - background-color 0.12s var(--ease), - box-shadow 0.12s var(--ease); -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'] > * { - flex: none; - min-width: 0; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'] > .sf-text:nth-child(3) { - flex: 1 1 0; - overflow: hidden; - text-overflow: ellipsis; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'] > .sf-text:nth-child(2) { - flex: 0 1 auto; - overflow: hidden; - text-overflow: ellipsis; -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon']:hover { - background-color: var(--l1); -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'][data-mark='pick'], -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'][data-mark='pick']:hover { - background-color: var( - --sf-sel, - light-dark(rgb(from var(--accent) r g b/10%), rgb(from var(--accent) r g b/16%)) - ); - box-shadow: inset 2px 0 0 var(--accent); -} -.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row[data-role='tas.soon'][data-mark='pick']::after { - display: none; +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] { font-family: var(--sans); --sf-sel: rgb(from var(--accent) r g b / 8%); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.split'] { align-items: flex-start; min-width: 0; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.timeline'], +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.detail'] { flex: 1 1 0; min-width: 0; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.detail'] { background: var(--card); border: 1px solid var(--l3); border-radius: var(--r-card); padding: 16px; box-shadow: 0 8px 24px -10px rgb(from var(--t1) r g b / 16%); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.detail-title'] { font-size: 17px; font-weight: 650; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-item { border-radius: var(--r-ctl); margin: 2px 0; padding-top: 7px; padding-bottom: 7px; border-left: 2px solid transparent; transition: border-color 600ms var(--out), background-color 180ms var(--out); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.new'] { border-left-color: var(--accent); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.new-failed'] { border-left-color: var(--bad); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.seen'] { border-left-color: transparent; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-mark='pick'] { background: rgb(from var(--accent) r g b / 12%); box-shadow: inset 0 0 0 1px var(--accent); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-mark='pick']:hover, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-list .sf-item[data-mark='pick']:hover { background: rgb(from var(--accent) r g b / 16%); box-shadow: inset 0 0 0 1px var(--accent); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-t-mono, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-t-num, +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-elapsed { font-family: var(--mono); font-variant-numeric: tabular-nums; color: var(--t2); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-t-mono { -stencil-text-effect: numeric; -stencil-text-duration: 300ms; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-icon { font-size: 15px; } +/* The quiet line takes the place of the "You last looked" rule and keeps that rule's single-row height: plain text, no extra margin. */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.quiet'] { color: var(--t3); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.now-rule'] { display: flex; align-items: center; position: relative; margin: 12px 0; min-height: 24px; } +/* The now line is a plain 1px accent line; the old 8px glow was invisible (ΔRGB ≈ 6). */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.now-rule']::before { content: ''; position: absolute; left: 0; right: 0; top: 50%; height: 1px; background: var(--accent); } +/* Pill text is --grad-ink (opaque #05070b, the documented "text that reads on the accent gradient"), not --panel, which is translucent under window glass (2.3:1). Expect ~9:1 on the dark theme's amber accent and ~5.4:1 on the light theme's blue. */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.now-pill'] { position: relative; margin-left: 10px; padding: 3px 9px; border-radius: var(--r-chip); background: var(--accent); color: var(--grad-ink); font-family: var(--mono); font-variant-numeric: tabular-nums; font-weight: 600; -stencil-text-effect: numeric; } +/* The value column (schedule, "in 2d 21h") never shrinks or truncates (the kit caps it at 40%); the detail column shrinks and ellipsizes first, then the label. */ +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] .sf-item .sf-item-value { flex: none; max-width: none; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.live-row'] { position: relative; padding-left: 14px; border-radius: var(--r-ctl); background: linear-gradient(to right, rgb(from var(--live) r g b / 14%), transparent); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.live-row']::before { content: ''; position: absolute; left: 4px; top: 14px; width: 6px; height: 6px; border-radius: 50%; background: var(--live); animation: tas-live-pulse 3s var(--ease) infinite; } +@keyframes tas-live-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .4; } } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.latest'], +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.latest-failed'] { padding: 10px 12px; border-radius: var(--r-ctl); border: 1px solid var(--l2); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.latest-failed'] { background: rgb(from var(--bad) r g b / 10%); border-color: rgb(from var(--bad) r g b / 40%); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.detail-settings'] { background: var(--l1); padding: 12px; border-radius: var(--r-ctl); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.prompt-action'], +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.failure-badge'] { align-self: flex-start; flex: none; } +/* Plugin buttons only (button.sf-el): the kit's own buttons (close, stepper, switch, picks, menu items, nav tabs) keep their native look. */ +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el { display: inline-flex; align-items: center; gap: 8px; color: var(--t1); background: transparent; border: 1px solid var(--l2); border-radius: var(--r-ctl); padding: 5px 9px; font-family: var(--sans); cursor: pointer; } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el:hover { background: var(--l2); } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el:focus-visible { outline: 1px solid var(--accent); } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el kbd { font-family: var(--mono); font-size: 11px; color: var(--t2); background: var(--l1); border-radius: 3px; padding: 1px 3px; } +/* Tone says what a button does, not which group it's in: the Enter/default action is accent-tinted (text stays --t1, so it reads in light and dark), a blocked Save is dimmed, and a destructive confirm in a dialog reads in --bad. */ +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el[data-tone='accent'] { border-color: rgb(from var(--accent) r g b / 55%); background: rgb(from var(--accent) r g b / 10%); } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el[data-tone='accent']:hover { background: rgb(from var(--accent) r g b / 18%); } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el[data-tone='muted'] { color: var(--t3); } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'] button.sf-el[data-role='tas.dock-action'][data-tone='error'] { color: var(--bad); } +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] .sf-row { flex-wrap: wrap; row-gap: 6px; } +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.dock-actions'] { gap: 20px; align-items: center; } +/* Job and global actions are the same buttons; the 20px gap and the " · selected job" caption above the job group show their scope. A tray or a divider on one group read as a second theme, and a divider dangled when the dock wrapped. */ +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.dock-job'], +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.dock-global'] { gap: 6px; } +/* Delete and Pause all end their groups in muted text, with the same border and spacing as every other button: an extra left margin indented them whenever the dock wrapped. */ +.sf-dock[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.dock-danger'] { color: var(--t2); } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.soon'] { display: flex; align-items: center; gap: 8px; min-width: 0; min-height: calc(var(--sf-lh) + 6px); padding: 7px 8px 7px 10px; white-space: pre; color: var(--t1); cursor: pointer; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.soon'] > * { flex: none; min-width: 0; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.soon'] > .sf-text:nth-child(3) { flex: 1 1 0; overflow: hidden; text-overflow: ellipsis; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.soon'] > .sf-text:nth-child(2) { flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis; } +.sf-main[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.soon']:hover { background: var(--l1); } +/* Help: three key groups in two columns that wrap to one when the layer is narrow (flex-wrap; the grid repeat(auto-fit) form isn't supported), content inset to the title's edge. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-cols { display: flex; flex-wrap: wrap; gap: 18px 32px; padding: 8px 9px 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-cols > * { flex: 1 1 260px; min-width: 0; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-stack { display: flex; flex-direction: column; gap: 18px; } +/* Group headings are small and muted (--t3, the kv key colour): the keys carry the weight. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-group h3, +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-when h3 { margin: 0 0 8px; font: 550 12px/16px var(--sans); color: var(--t3); } +/* One key-column width (fits "space" and "enter") in every group, so all descriptions start on the same line. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-group dl { margin: 0; display: grid; grid-template-columns: 50px minmax(0, 1fr); column-gap: 12px; row-gap: 7px; align-items: baseline; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-group dt { display: flex; gap: 3px; } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-group dd { margin: 0; color: var(--t1); } +/* Keycaps match the dock's (mono 11px, --t2 on --l1), evened out so single letters line up. */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-group kbd { font: 500 11px/18px var(--mono); color: var(--t2); background: var(--l1); box-shadow: inset 0 0 0 1px var(--l2); border-radius: 4px; padding: 0 5px; min-width: 18px; text-align: center; } +/* "When jobs run" sits under a hairline: two short notes at the card's full width (a narrower measure left one-word last lines). */ +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-when { margin: 18px 9px 0; padding-top: 14px; border-top: 1px solid var(--l2); } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] .tas-help-when p { margin: 0 0 6px; color: var(--t2); } +.sf-layer[data-surface='plugin.tern-agent-scheduler.manager'] [data-role='tas.help-foot'] { margin: 12px 9px 4px; justify-content: space-between; align-items: center; gap: 12px; } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'].sf-still *, +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'].sf-still *::before { animation: none !important; transition: none !important; -stencil-text-effect: none !important; -stencil-follow: none !important; } +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'].sf-paused *, +.sf-region[data-surface='plugin.tern-agent-scheduler.manager'].sf-covered * { animation-play-state: paused; } +@media (prefers-reduced-motion: reduce) { + .sf-region[data-surface='plugin.tern-agent-scheduler.manager'] *, + .sf-region[data-surface='plugin.tern-agent-scheduler.manager'] *::before { animation: none !important; transition: none !important; -stencil-text-effect: none !important; -stencil-follow: none !important; } } diff --git a/plugin.toml b/plugin.toml index c9d0697..894c5de 100644 --- a/plugin.toml +++ b/plugin.toml @@ -1,7 +1,7 @@ schema = 1 id = "tern-agent-scheduler" name = "Agent Scheduler" -version = "0.3.2" +version = "0.4.0" description = "Schedule omp agent runs: cron, presets, natural language and one-shot jobs, launched into a Scheduled runs session." icon = "timer" host = "host.luau" diff --git a/test/fake_tern.luau b/test/fake_tern.luau index 2162478..18c835a 100644 --- a/test/fake_tern.luau +++ b/test/fake_tern.luau @@ -30,7 +30,7 @@ local fake = { } fake.live_panes = {} -- pane ids (strings) reported by tern.pane.list() fake.installed = { - [fake.tern_bin] = "tern 0.8.3 (test)\n", + [fake.tern_bin] = "tern 0.9.0 (test)\n", [fake.omp_bin] = "omp/18.9.1\n", } @@ -539,7 +539,7 @@ local function tern_new(argv) quoted[k] = quote(a) end local b = { - id = new_id(), title = "omp", cwd = cwd, program = "/bin/zsh", args = { "-l", "-c", table.concat(quoted, " ") }, + id = new_id(), title = "omp", cwd = cwd, program = "/bin/zsh", args = { "-c", table.concat(quoted, " ") }, command = table.concat(quoted, " "), keep_open = true, live = true, } fake.blocks[b.id] = b diff --git a/test/golden/runner_form.txt b/test/golden/runner_form.txt new file mode 100644 index 0000000..4285422 --- /dev/null +++ b/test/golden/runner_form.txt @@ -0,0 +1,4 @@ +PASS all-off conditions collapse; Check now absent and inert +PASS every toggle reveals dependents, preserves drafts and keyboard order +PASS collapsing clears stale Check now results +PASS compact missed-run labels preserve threshold and policy diff --git a/test/golden/runner_manager.txt b/test/golden/runner_manager.txt new file mode 100644 index 0000000..6d34678 --- /dev/null +++ b/test/golden/runner_manager.txt @@ -0,0 +1,12 @@ +PASS timeline order, manual group, running deduplication, missed != failed +PASS backlog counts independent of retention +PASS host checkpoint and mark-all-seen +PASS cron steps and manager setting validation +PASS stay/fade settings, sheet guard and live-pane timer +PASS now rule leads when only a live run is above next runs +PASS calm timeline: no results, no now rule, quiet line +PASS live-only timeline: now rule without results, quiet line kept +PASS results with no last-looked time are titled Results so far +PASS mark all seen only when something is unseen +PASS first visit names the first run +PASS empty state: example heading, Use example action opens a draft diff --git a/test/golden/runner_settings.txt b/test/golden/runner_settings.txt new file mode 100644 index 0000000..8beb024 --- /dev/null +++ b/test/golden/runner_settings.txt @@ -0,0 +1,7 @@ +PASS settings layer: no lead, five sections, segmented controls, key legend +PASS rejected text stays editing with a warning; Esc cancels and clears +PASS reset restores the default +PASS segmented rows: Right selects next, Left stops at the start, Enter wraps +PASS number rows: typing validates, Esc cancels, a whole number saves +PASS Tab and Shift+Tab move row focus +PASS open_setup opens Settings at Status; Esc closes diff --git a/test/golden/runner_time.txt b/test/golden/runner_time.txt new file mode 100644 index 0000000..1700dcd --- /dev/null +++ b/test/golden/runner_time.txt @@ -0,0 +1,4 @@ +PASS midnight/noon and shared schedule, manager, condition and notification clocks +PASS macOS preferences, locale detection, fallback and persisted probe cache +PASS setting default, validation, persistence and in-flight preference change +PASS snapshot carries resolved format; window consumes it without spawning diff --git a/test/runner_commands.luau b/test/runner_commands.luau index 72d5e77..0c37e30 100644 --- a/test/runner_commands.luau +++ b/test/runner_commands.luau @@ -53,6 +53,9 @@ assert(opened[1].args[2] == "/home/needz/app", "remote pane's folder: " .. tostr defs["new-job"].run(window("remote", "/home/needz/app")) assert(opened[2].args[1] == "new" and opened[2].args[2] == "/home/needz/app", "new job in the remote folder") +defs["settings"].run(window("remote", "/home/needz/app")) +assert(opened[3].args[1] == "settings" and opened[3].how == "tab", "Settings opens its manager sheet") + -- Carly creates jobs on this machine, so a remote pane's folder is still refused there. local cwd, why = commands.focused_cwd(window("remote", "/home/needz/app")) assert(cwd == "" and why ~= nil, "focused_cwd refuses a remote pane") diff --git a/test/runner_form.luau b/test/runner_form.luau new file mode 100644 index 0000000..d896035 --- /dev/null +++ b/test/runner_form.luau @@ -0,0 +1,62 @@ +-- Native job form: collapsed conditions retain drafts and share keyboard structure. +tern.ui = { + span = function(t, s) return { t = t, s = s } end, + node = function(k, p, c) return { k = k, props = p, children = c } end, +} +local F, P = __mods.mgr_form, __mods.mgr_prefs +local form = F.new({ name = "Review", prompt = "Review changes", cwd = "/home/u/proj" }, nil, "New job") +local state = { form = form, cx = { render = function() end } } +form.page = "only_when" +local sections = F.sections(state) +assert(#P.flat(sections) == 6, "only status and five toggles when all off") +local now = P.find(sections, "c_now") +assert(now.control.k == "keys" and now.control.act == nil) +assert(now.hint == "Nothing to check: this job always runs when due.") +form.focus = "c_now" +assert(not F.key(state, { name = "enter" }), "no keyboard check with all off") +F.event(state, { ev = "action", act = "c_now" }) +assert(form.checking == nil and form.verdict == nil) +print("PASS all-off conditions collapse; Check now absent and inert") +local groups = { + { "c_commits", "c_branch", "c_paths" }, + { "c_window", "c_days", "c_from", "c_to", "c_outside" }, + { "c_limits", "c_runs", "c_usd", "c_per" }, + { "c_check", "c_script" }, + { "c_ask", "c_ask_prompt", "c_ask_role" }, +} +form.c_branch = "develop" +__mods.textfield.set(form.c_paths, "src docs") +__mods.textfield.set(form.c_script, "./check.sh") +__mods.textfield.set(form.c_ask_prompt, "Is there work?") +for _, group in groups do + local toggle = group[1] + F.event(state, { ev = "change", item = toggle, value = true }) + sections = F.sections(state) + assert(form.focus == toggle) + assert(P.find(sections, "c_now").control.label == "Check now") + for i = 2, #group do assert(P.find(sections, group[i]) ~= nil, group[i]) end + assert(P.move(sections, toggle, 1) == group[2], "keyboard enters expanded fields") + F.event(state, { ev = "change", item = toggle, value = false }) + sections = F.sections(state) + for i = 2, #group do assert(P.find(sections, group[i]) == nil, group[i]) end + assert(form.focus == toggle, "collapse keeps focus on switch") + assert(P.find(sections, "c_now").control.act == nil) +end +assert(form.c_branch == "develop" and form.c_paths.text == "src docs") +assert(form.c_script.text == "./check.sh" and form.c_ask_prompt.text == "Is there work?") +assert(form.c_from == 540 and form.c_to == 1080 and form.c_runs == 3) +assert(next(F.only_when_input(form)) == nil, "hidden drafts do not enable conditions") +print("PASS every toggle reveals dependents, preserves drafts and keyboard order") +form.c_commits = true +form.verdict = { ok = true, results = { { type = "commits", result = "pass", text = "New commits" } } } +assert(P.find(F.sections(state), "c_commits_now") ~= nil) +F.event(state, { ev = "change", item = "c_commits", value = false }) +assert(form.verdict == nil and P.find(F.sections(state), "c_commits_now") == nil) +print("PASS collapsing clears stale Check now results") +form.page = "job" +form.catch_up_window_s = 5400 +local row = P.find(F.sections(state), "catch_up") +assert(row.control.options[1].label == "Run once if under 90m late") +assert(row.control.options[2].label == "Run once, however late") +assert(row.control.options[3].label == "Skip missed runs") +print("PASS compact missed-run labels preserve threshold and policy") diff --git a/test/runner_io.luau b/test/runner_io.luau index c2ca50e..65cfbc9 100644 --- a/test/runner_io.luau +++ b/test/runner_io.luau @@ -6,28 +6,31 @@ local function res(stdout) return { status = 0, stdout = stdout, stderr = "", timed_out = false } end --- F1: only a launch argv (`@/prompt.md`) carries the marker; a resumed conversation does not +-- F1: only a launch argv (`@/prompt.md`) carries the marker; a resumed conversation does not. +-- Tern lists the shell argv as {"-c", cmd}; a login shell's {"-l", "-c", cmd} is marked the same way. local launch = { - args = { "-l", "-c", "'/opt/homebrew/bin/omp' --model '@default' --session-dir '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session' " + args = { "-c", "'/opt/homebrew/bin/omp' --model '@default' --session-dir '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session' " .. "--config '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/omp.yml' '@/d/runs/j_ab12cd34/r_ab12cd34_1760000000/prompt.md' 'Run the scheduled job.'" }, } local spaced = { args = { "-l", "-c", "'/opt/homebrew/bin/omp' '@/Users/u/Library/Application Support/Tern/plugin-data/x/runs/j_ab12cd34/r_ab12cd34_5/prompt.md' 'Run.'" }, } local resume = { - args = { "-l", "-c", "'/opt/homebrew/bin/omp' --session-dir '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session' --resume '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session/a.jsonl' " + args = { "-c", "'/opt/homebrew/bin/omp' --session-dir '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session' --resume '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/session/a.jsonl' " .. "--config '/d/runs/j_ab12cd34/r_ab12cd34_1760000000/omp.yml'" }, } local bare = { args = { "-l" } } +local empty = { args = {} } assert(tern_state.marker(launch) == "j_ab12cd34/r_ab12cd34_1760000000", "launch argv is marked: " .. tostring(tern_state.marker(launch))) -assert(tern_state.marker(spaced) == "j_ab12cd34/r_ab12cd34_5", "launch argv with a spaced data path is marked") +assert(tern_state.marker(spaced) == "j_ab12cd34/r_ab12cd34_5", "login-shell launch argv with a spaced data path is marked") assert(tern_state.marker(resume) == nil, "resume argv is not marked") assert(tern_state.marker(bare) == nil, "bare login shell is not marked") +assert(tern_state.marker(empty) == nil, "bare shell is not marked") print("PASS F1 marker only on launch argv") -- F14: sessions listed under `detached` still map their panes local st = tern_state.parse( - '{"sessions":[],"detached":[{"id":7,"name":"Scheduled runs","tabs":[{"id":8,"name":"t","blocks":[{"id":9,"args":["-l","-c","omp \'@/d/runs/j_ab12cd34/r_ab12cd34_1/prompt.md\'"]}]}]}]}' + '{"sessions":[],"detached":[{"id":7,"name":"Scheduled runs","tabs":[{"id":8,"name":"t","blocks":[{"id":9,"args":["-c","omp \'@/d/runs/j_ab12cd34/r_ab12cd34_1/prompt.md\'"]}]}]}]}' ) assert(st ~= nil and st.session_ids["Scheduled runs"] == "7", "detached session id mapped") assert(st.by_run["j_ab12cd34/r_ab12cd34_1"] ~= nil and st.by_run["j_ab12cd34/r_ab12cd34_1"].session_shown == false, "detached pane mapped as hidden") @@ -107,7 +110,7 @@ local function resolve_with(settings) return got, err end local custom_omp = "/home/u/custom/omp" -fake.installed = { [fake.tern_bin] = "tern 0.8.3 (test)\n", [custom_omp] = "omp/18.9.1\n", ["/home/u/.bun/bin/omp"] = "omp/18.9.1\n" } +fake.installed = { [fake.tern_bin] = "tern 0.9.0 (test)\n", [custom_omp] = "omp/18.9.1\n", ["/home/u/.bun/bin/omp"] = "omp/18.9.1\n" } local b1 = resolve_with({ omp_path = custom_omp }) assert(b1 ~= nil and b1.omp == custom_omp, "omp_path setting wins") fake.installed[custom_omp] = nil @@ -127,7 +130,7 @@ fake.override.zsh = nil print("PASS F18/F68 omp lookup") -- F15: a forced re-resolve keeps the known paths while probes run -fake.installed = { [fake.tern_bin] = "tern 0.8.3 (test)\n", [fake.omp_bin] = "omp/18.9.1\n" } +fake.installed = { [fake.tern_bin] = "tern 0.9.0 (test)\n", [fake.omp_bin] = "omp/18.9.1\n" } resolve_with({}) bins.resolve({}, function() end, true) assert(bins.found().tern == fake.tern_bin and bins.found().omp == fake.omp_bin, "paths kept while re-resolving") diff --git a/test/runner_manager.luau b/test/runner_manager.luau new file mode 100644 index 0000000..7f661cc --- /dev/null +++ b/test/runner_manager.luau @@ -0,0 +1,176 @@ +-- Manager timeline, retained counters, seen behavior and cron humanizer. +tern.ui = { + span = function(t, s) return { t = t, s = s } end, + node = function(k, p, c) return { k = k, p = p, c = c } end, + el = function(k, p, c) return { k = k, p = p, c = c } end, + text = function(spans) return { k = "text", p = {}, c = spans } end, + rule = function(spans) return { k = "rule", p = {}, c = spans } end, + col = function(c) return { k = "col", p = {}, c = c } end, + row = function(c) return { k = "row", p = {}, c = c } end, + badge = function(label, tone) return { k = "badge", p = { label = label, tone = tone }, c = {} } end, +} +local jobs, ledger, runner = __mods.jobs, __mods.ledger, __mods.runner +local H, T, C = __mods.mgr_history, __mods.mgr_timeline, __mods.mgr_common +fake.dirs["/home/u/proj"] = true +fake.set_wall(fake.chicago(2026, 10, 12, 10, 0, 0)) +runner.load() +local now = os.time() +local job = jobs.create({ name = "Recurring", when = "every 2h", cwd = "/home/u/proj" }, "review", "user", now) +local manual = jobs.create({ name = "Manual", when = "manual", cwd = "/home/u/proj" }, "review", "user", now) +local function finish(i, status) + local t = now - 300 + i + local r = ledger.new(job, { run_id = "r_" .. job.id:sub(3) .. "_" .. i, now = t, slot = t }) + ledger.transition(r, status, nil, { summary = "Result " .. i }, t) + H.record(r) + return r +end +finish(1, "failed") +finish(2, "missed") +finish(3, "cancelled") +assert(H.ensure(job.id).totals.failed == 1) +assert(H.ensure(job.id).totals.missed == 1) +assert(H.ensure(job.id).failed, "missed/cancelled must not clear the failure") +local function base(live) + local rows = { + { sec = "upcoming", key = job.id, job = job, js = jobs.state(job.id), kind = "job" }, + { sec = "upcoming", key = manual.id, job = manual, js = jobs.state(manual.id), kind = "job" }, + } + local sections = { { id = "upcoming", rows = rows } } + if live then table.insert(sections, { id = "running", rows = { { sec = "running", key = "r_live", kind = "run", job = job, run = { run_id = "r_live", job_id = job.id } } } }) end + return { sections = sections } +end +local state = { looked_at = now - 400, mode = "list", cx = { pane = 123, render = function() end } } +local m = T.model(state, base(false)) +assert(#m.sections[1].rows == 3) +assert(m.sections[1].rows[1].run.state == "failed", "results ascend toward now") +assert(m.sections[#m.sections].title == "Paused & needs fixing") +local busy = T.model(state, base(true)) +local next_count, live_count = 0, 0 +for _, r in busy.flat do + if r.job.id == job.id and r.sec == "upcoming" then next_count += 1 end + if r.job.id == job.id and r.sec == "running" then live_count += 1 end +end +assert(next_count == 0 and live_count == 1, "running job has no next-run duplicate") +print("PASS timeline order, manual group, running deduplication, missed != failed") +for i = 4, 84 do finish(i, "skipped") end +ledger.prune(job.id, { retain_runs = 5, retain_days = 90 }, now) +local h = H.ensure(job.id) +assert(h.totals.total == 84 and h.pending.total == 84, "counts survive pruning") +m = T.model(state, base(false)) +local summary = m.sections[1].rows[#m.sections[1].rows] +assert(summary.error:find("84 runs", 1, true), summary.error) +assert(summary.error:find("1 failed, shown above", 1, true), summary.error) +assert(not summary.error:find("✗", 1, true), "summary uses words, not glyph counts") +print("PASS backlog counts independent of retention") +-- A newer completion must remain pending when an older three-second cohort fades. +local cutoff = now - 219 +H.clear(cutoff) +assert(h.pending.total == 3, "only results through the checkpoint are seen") +assert(jobs.settings().last_looked == cutoff) +T.clear(state) +assert(h.pending.total == 0 and state.looked_at == now) +print("PASS host checkpoint and mark-all-seen") +for expr, expected in { ["0 */2 * * *"] = "Every 2 hours", ["0 */5 * * *"] = "Every 5 hours", ["*/7 * * * *"] = "Every 7 minutes", ["*/15 * * * *"] = "Every 15 minutes" } do + assert(__mods.cron.describe(__mods.cron.parse(expr)) == expected, expr) +end +assert(jobs.set_settings({ manager_layout = "classic", manager_results = "stay" })) +assert(not jobs.set_settings({ manager_layout = "bad" })) +print("PASS cron steps and manager setting validation") +-- Stay does not schedule a fade. Fade pauses under sheets and checks pane liveness. +fake.live_panes = { "123" } +local result = { key = "result", job = job, run = { state = "finished", ended = now, summary = "Reviewed" } } +T.result(state, result) +fake.advance(3100) +assert(next(state.seen_results) == nil, "stay keeps the highlight") +jobs.set_settings({ manager_results = "fade" }) +T.result(state, result) +state.sheet = { kind = "settings" } +fake.advance(3100) +assert(next(state.seen_results) == nil, "covered list is not marked seen") +state.sheet = nil +T.result(state, result) +fake.advance(3100) +assert(next(state.seen_results) ~= nil, "three-second fade") +print("PASS stay/fade settings, sheet guard and live-pane timer") +-- Review regressions: start times agree, future minutes ceil, previews omit heading syntax. +assert(C.in_text(now + 1501, now) == "in 26m") +assert(C.in_text(now + 1, now) == "in 1m") +assert(C.in_text(now + 6 * 3600 + 61, now) == "in 6h 2m") +assert(C.in_text(now, now) == "now") +assert(__mods.mgr_detail.prompt_preview("\n# Nightly tests\n\nDo the work.\nExtra") == "Nightly tests · Do the work.") +result.run.started = now - 600 +result.run.created = now - 601 +local result_node = T.result(state, result) +assert(result_node.p.label[1].t == __mods.timefmt.date("%a %H:%M", now - 600) .. " ") +local timed = T.model(state, base(true), now) +assert(timed.sections[1].id == "now", "no results above now: the now rule leads") +assert(timed.sections[1].title == "now · " .. __mods.timefmt.date("%H:%M", now)) +print("PASS now rule leads when only a live run is above next runs") +-- Calm, live-only, first-visit and unseen behavior (timeline layout). +assert(jobs.set_settings({ manager_layout = "timeline" })) +local function section(model, id) + for _, s in model.sections do + if s.id == id then return s end + end +end +local function starts(s, prefix) return type(s) == "string" and s:sub(1, #prefix) == prefix end +local function mkstate(looked_at) + return { + cx = { pane = 123, cols = 100, render = function() end }, + pane_id = "123", mode = "list", looked_at = looked_at, + seen_results = {}, seen_pending = {}, sel_idx = 1, folds = {}, + notice_at = 0, example_sel = 1, + } +end +local calm = mkstate(now) +local mc = T.model(calm, base(false)) +assert(section(mc, "results") == nil and section(mc, "now") == nil, "calm timeline has no results or now rule") +assert(starts(mc.quiet, "Nothing new since "), tostring(mc.quiet)) +assert(mc.unseen == false, "nothing to mark seen") +print("PASS calm timeline: no results, no now rule, quiet line") +local ml = T.model(calm, base(true)) +assert(section(ml, "results") == nil and section(ml, "now") ~= nil, "live run alone keeps the now rule") +assert(type(ml.quiet) == "string" and ml.unseen == false) +print("PASS live-only timeline: now rule without results, quiet line kept") +local mr = T.model(mkstate(0), base(false)) +assert(section(mr, "results").title == "Results so far", section(mr, "results").title) +assert(mr.quiet == nil and mr.unseen == true) +print("PASS results with no last-looked time are titled Results so far") +local function key(state, name) + return __mods.mgr_list.key(state, { name = name, shift = false, ctrl = false, alt = false, meta = false }) +end +assert(key(calm, "s") == false, "s with nothing unseen does nothing") +local unseen = mkstate(now - 400) +assert(key(unseen, "s") == true, "s marks results seen") +assert(unseen.looked_at >= now, "checkpoint advanced") +print("PASS mark all seen only when something is unseen") +-- First visit: a job with no runs, nothing has run yet. +local ids = {} +for _, j in jobs.list() do table.insert(ids, j.id) end +for _, id in ids do assert(jobs.delete(id, now)) end +local fresh = jobs.create({ name = "Fresh review", when = "every 2h", cwd = "/home/u/proj" }, "review", "user", now) +local first = mkstate(0) +local mf = __mods.mgr_list.model(first) +assert(starts(mf.quiet, "Nothing has run yet. "), tostring(mf.quiet)) +assert(mf.quiet:find("Fresh review runs first, ", 1, true), mf.quiet) +assert(section(mf, "results") == nil and section(mf, "now") == nil and mf.unseen == false) +print("PASS first visit names the first run") +-- Empty state: examples, one primary action, no job left. +assert(jobs.delete(fresh.id, now)) +local function find(node, pred) + if type(node) ~= "table" then return nil end + if node.p ~= nil and pred(node) then return node end + for _, c in node.c or {} do + local hit = find(c, pred) + if hit then return hit end + end +end +local empty = mkstate(0) +local main, dock = __mods.mgr_list.view(empty) +local heading = find(main, function(n) return n.p.role == "tas.timeline-heading" end) +assert(heading ~= nil and heading.c[1].t == "Start from an example", "empty state heading") +local use = find(dock, function(n) return n.k == "button" and n.p.actions ~= nil and n.p.actions.click == "example" end) +assert(use ~= nil, "dock offers Use example") +__mods.mgr_list.event(empty, { ev = "action", act = "example" }) +assert(empty.form ~= nil, "Use example opens the New job form") +print("PASS empty state: example heading, Use example action opens a draft") diff --git a/test/runner_settings.luau b/test/runner_settings.luau new file mode 100644 index 0000000..1eb627c --- /dev/null +++ b/test/runner_settings.luau @@ -0,0 +1,176 @@ +-- The single Settings page: layer shape, keys, editing errors, reset, segments, number typing and entry points. +tern.ui = { + span = function(t, s) return { t = t, s = s } end, + node = function(k, p, c) return { k = k, p = p, c = c } end, + el = function(k, p, c) return { k = k, p = p, c = c } end, + text = function(spans) return { k = "text", p = {}, spans = spans } end, +} +local jobs, runner = __mods.jobs, __mods.runner +local S = __mods.mgr_sheets +fake.set_wall(fake.chicago(2026, 10, 12, 10, 0, 0)) +runner.load() + +local function key(state, name, extra) + local k = { name = name, shift = false, ctrl = false, alt = false, meta = false } + for f, v in extra or {} do k[f] = v end + return S.key(state, k) +end +local function fresh() + assert(jobs.set_settings({ max_concurrent = 2, catchup_window_s = 10800, time_format = "automatic", session_name = "Scheduled runs" })) + local state = { mode = "list", cx = { pane = 1, render = function() end } } + S.open_settings(state) + return state +end +local function node(state) + local n = S.layer(state) + assert(n ~= nil and n.k == "prefs", "layer is a prefs node") + return n +end +local function legend(state) + for _, c in node(state).c or {} do + if c.p and c.p.role == "tas.settings-keys" then + local out = "" + for _, sp in c.spans do out ..= sp.t end + return out + end + end +end +local function row(state, id) + for _, s in node(state).p.sections do + for _, r in s.rows do + if r.id == id then return r end + end + end + error("no row " .. id) +end +local function focus_on(state, id) + for _ = 1, 20 do + if state.sheet.focus == id then return end + key(state, "down") + end + error("could not focus " .. id .. " (at " .. tostring(state.sheet.focus) .. ")") +end + +-- a. shape +do + local state = fresh() + local n = node(state) + local p = n.p + assert(p.role == "tas.settings", "role") + assert(p.lead == nil, "no lead: the brand row carries the title") + assert(p.focus == "status", "opens on status") + local want = { "health", "display", "runs", "limits", "setup" } + assert(#p.sections == #want, "five sections") + for i, id in want do assert(p.sections[i].id == id, "section " .. i .. " is " .. id) end + local runs = {} + for _, s in p.sections do + if s.id == "runs" then for _, r in s.rows do table.insert(runs, r.id) end end + end + local want_runs = { "placement", "session_name", "focus" } + assert(#runs == #want_runs, "three runs rows") + for i, id in want_runs do assert(runs[i] == id, "runs row " .. i .. " is " .. id) end + assert(row(state, "time_format").control.style == "segmented", "time format is segmented") + assert(row(state, "manager_layout").control.style == "segmented", "layout is segmented") + assert(legend(state) == "↑↓ move · ←→ change · ⏎ edit · esc close", tostring(legend(state))) + for _, s in p.sections do + for _, r in s.rows do + local c = r.control + for _, o in (c and c.options) or {} do + local label = type(o) == "table" and o.label or tostring(o) + assert(not string.find(label, "(default)", 1, true), "option label carries (default): " .. label) + end + end + end + print("PASS settings layer: no lead, five sections, segmented controls, key legend") +end + +-- b. rejected text keeps the editor open with the error on the row +do + local state = fresh() + focus_on(state, "session_name") + key(state, "enter") + assert(state.sheet.editing and state.sheet.editing.row == "session_name", "editing opens") + for _ = 1, 60 do key(state, "backspace") end + key(state, "paste", { text = "bad/name" }) + key(state, "enter") + assert(state.sheet.editing ~= nil and state.sheet.editing.row == "session_name", "editor stays open") + assert(row(state, "session_name").warning == "Session names use letters, numbers, spaces, . _ - (up to 40).", tostring(row(state, "session_name").warning)) + assert(jobs.settings().session_name == "Scheduled runs", "rejected value is not saved") + key(state, "escape") + assert(state.sheet.editing == nil, "Esc closes the editor") + assert(row(state, "session_name").warning == nil, "Esc clears the warning") + assert(state.sheet ~= nil, "Esc while editing keeps the sheet") + print("PASS rejected text stays editing with a warning; Esc cancels and clears") +end + +-- c. reset +do + local state = fresh() + assert(jobs.set_settings({ max_concurrent = 5 })) + assert(row(state, "max_concurrent").changed == true, "changed before reset") + S.event(state, { ev = "change", item = "max_concurrent", value = tern.json.null }) + assert(jobs.settings().max_concurrent == 2, "back to default") + assert(not row(state, "max_concurrent").changed, "row no longer changed") + print("PASS reset restores the default") +end + +-- d. segments +do + local state = fresh() + focus_on(state, "time_format") + key(state, "left") + assert(jobs.settings().time_format == "automatic", "Left at the first option changes nothing") + key(state, "right") + assert(jobs.settings().time_format == "12h", "Right selects the next option: " .. tostring(jobs.settings().time_format)) + assert(jobs.set_settings({ time_format = "24h" })) + key(state, "enter") + assert(jobs.settings().time_format == "automatic", "Enter at the last option wraps to the first") + print("PASS segmented rows: Right selects next, Left stops at the start, Enter wraps") +end + +-- d2. number typing +do + local state = fresh() + focus_on(state, "max_concurrent") + key(state, "enter") + assert(state.sheet.editing and state.sheet.editing.row == "max_concurrent", "number editor opens") + assert(legend(state) == "⏎ save · esc cancel", tostring(legend(state))) + for _ = 1, 10 do key(state, "backspace") end + key(state, "paste", { text = "x" }) + key(state, "enter") + assert(state.sheet.editing ~= nil and state.sheet.editing.row == "max_concurrent", "editor stays open on a bad draft") + assert(row(state, "max_concurrent").warning == "Type a whole number from 1 to 10.", tostring(row(state, "max_concurrent").warning)) + assert(jobs.settings().max_concurrent == 2, "rejected draft is not saved") + key(state, "escape") + assert(state.sheet.editing == nil, "Esc closes the number editor") + assert(row(state, "max_concurrent").warning == nil, "Esc clears the warning") + key(state, "enter") + for _ = 1, 10 do key(state, "backspace") end + key(state, "paste", { text = "3" }) + key(state, "enter") + assert(state.sheet.editing == nil, "a valid draft closes the editor") + assert(jobs.settings().max_concurrent == 3, "typed value is saved") + assert(jobs.set_settings({ max_concurrent = 2 })) + print("PASS number rows: typing validates, Esc cancels, a whole number saves") +end + +-- e. Tab +do + local state = fresh() + assert(state.sheet.focus == "status") + key(state, "tab") + assert(state.sheet.focus == "time_format", "Tab moves to the next row: " .. tostring(state.sheet.focus)) + key(state, "tab", { shift = true }) + assert(state.sheet.focus == "status", "Shift+Tab moves back") + print("PASS Tab and Shift+Tab move row focus") +end + +-- f. entry points +do + local state = { mode = "list", cx = { pane = 1, render = function() end } } + S.open_setup(state) + assert(state.sheet.kind == "settings" and state.sheet.focus == "status", "open_setup opens Settings on Status") + key(state, "escape") + assert(state.sheet == nil, "Esc closes the sheet") + print("PASS open_setup opens Settings at Status; Esc closes") +end diff --git a/test/runner_setup.luau b/test/runner_setup.luau index b6c228b..6234eae 100644 --- a/test/runner_setup.luau +++ b/test/runner_setup.luau @@ -63,5 +63,5 @@ print("PASS no heartbeat alarm right after a sleep") fake.events = {} fake.advance(130000) local dead = heartbeat() -assert(dead.ok == false and dead.text:find("isn't ticking", 1, true), "stalled tick: " .. tostring(dead.ok)) +assert(dead.ok == false and dead.text:find("has stopped", 1, true), "stalled tick: " .. tostring(dead.ok)) print("PASS a tick stalled while awake still fails") diff --git a/test/runner_time.luau b/test/runner_time.luau new file mode 100644 index 0000000..a614912 --- /dev/null +++ b/test/runner_time.luau @@ -0,0 +1,99 @@ +-- Presentation, host detection/cache, persisted choice and host -> window propagation. +local timefmt, host, bins = __mods.timefmt, __mods.time_host, __mods.bins +local jobs, cron = __mods.jobs, __mods.cron +local midnight = fake.chicago(2026, 10, 13, 0, 0) +local noon = fake.chicago(2026, 10, 13, 12, 0) +fake.set_wall(noon) +for mode, expected in { ["12h"] = { "12:00 am", "12:00 pm", "2:00 pm" }, ["24h"] = { "00:00", "12:00", "14:00" } } do + timefmt.set(mode) + assert(timefmt.date("%H:%M", midnight) == expected[1]) + assert(timefmt.date("%H:%M", noon) == expected[2]) + assert(timefmt.date("%H:%M", noon + 7200) == expected[3]) + assert(timefmt.clock(0, 0) == expected[1] and timefmt.clock(12, 0) == expected[2]) + assert(cron.describe(cron.parse("0 14 * * *")):find(expected[3], 1, true)) + assert(__mods.ledger.day_time(noon):find(expected[2], 1, true)) + assert(jobs.describe({ schedule = { kind = "once", run_at = noon } }):find(expected[2], 1, true)) + assert(__mods.mgr_common.abs(noon):find(expected[2], 1, true)) + assert(__mods.conditions.hhmm(0) == expected[1]) +end +print("PASS midnight/noon and shared schedule, manager, condition and notification clocks") + +local function result(stdout, status) + return { stdout = stdout, status = status or 0, timed_out = false } +end +local function detect(os_name, twelve, twenty_four, locale) + bins.cache().time_format = nil + tern.runtime = { os = os_name } + fake.override.defaults = function(argv) + return result(if argv[4] == "AppleICUForce12HourTime" then twelve else twenty_four) + end + fake.override.locale = function() return result(locale) end + host.configure("automatic") + fake.advance(0) + return timefmt.get() +end +assert(detect("macos", "1\n", "0\n", 't_fmt="%H:%M:%S"') == "12h") +assert(detect("macos", "0\n", "1\n", 't_fmt="%I:%M:%S %p"') == "24h") +assert(detect("macos", "", "", 't_fmt="%I:%M:%S %p"') == "12h") +assert(detect("linux", "", "", 't_fmt="%I:%M:%S"') == "12h") +assert(detect("linux", "", "", 't_fmt="%H:%M:%S %p"') == "12h") +assert(detect("linux", "", "", 't_fmt="%H:%M:%S"\nt_fmt_ampm="%I:%M:%S %p"') == "24h") +assert(detect("linux", "", "", "garbage") == "24h") +bins.cache().time_format = nil +fake.override.locale = function() error("spawn failed") end +host.configure("automatic") +assert(timefmt.get() == "24h") +bins.cache().time_format = nil +fake.override.locale = function() return result("", 1) end +host.configure("automatic") +fake.advance(0) +assert(timefmt.get() == "24h") +assert(detect("linux", "", "", 't_fmt="%I:%M %p"') == "12h") +local cached = tern.json.decode(fake.read("/d/cache.json")) +assert(cached.time_format == "12h") +local calls = #fake.calls +host.configure("automatic") +assert(#fake.calls == calls and timefmt.get() == "12h", "cache avoids another probe") +print("PASS macOS preferences, locale detection, fallback and persisted probe cache") + +jobs.load(noon) +assert(jobs.settings().time_format == "automatic") +for _, mode in { "12h", "24h", "automatic" } do + assert(jobs.set_settings({ time_format = mode })) + assert(tern.json.decode(fake.read("/d/settings.json")).time_format == mode) + jobs.load(noon) + assert(jobs.settings().time_format == mode) + assert(timefmt.get() == (if mode == "24h" then "24h" else "12h")) +end +assert(not jobs.set_settings({ time_format = "bad" })) +assert(#fake.calls == calls, "explicit settings and cached automatic never probe") +-- An asynchronous detection must not overwrite a newer explicit choice. +bins.cache().time_format = nil +host.configure("automatic") +assert(jobs.set_settings({ time_format = "24h" })) +fake.advance(0) +assert(timefmt.get() == "24h") +print("PASS setting default, validation, persistence and in-flight preference change") + +assert(jobs.set_settings({ time_format = "12h" })) +__mods.snapshot.publish({ inflight = {}, managers = {}, setup_ok = true, scheduler = "ok", welcome = false }, noon) +assert(tern.json.decode(fake.read("/d/snapshot.json")).time_format == "12h") +timefmt.set("24h") -- stand in for the window's separate module instance +local run = tern.process.run +local window_spawns = 0 +tern.process.run = function() + window_spawns += 1 + error("window must never spawn") +end +__mods.wsnap.reset() +assert(__mods.wsnap.poll()) +assert(timefmt.date("%H:%M", noon) == "12:00 pm") +assert(window_spawns == 0) +tern.process.run = run +-- A new host module instance reuses the on-disk cache after a plugin reload. +__mods.bins = nil +__mods.time_host = nil +calls = #fake.calls +__mods.time_host.configure("automatic") +assert(timefmt.get() == "12h" and #fake.calls == calls) +print("PASS snapshot carries resolved format; window consumes it without spawning")