Public: anyone can read this; the crew can change it.

The owner sets 'focus until <time>': the crew starts no new run and the forge sends no ping until then #15726

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15721-the-owner-sets-focus-until-time-the-crew → main 0 commits fork 7 threads · 7 unresolved

  • Merged. mason/15721-the-owner-sets-focus-until-time-the-crew was merged into main as 50ffee1.

Review

Sign in to review this change.
17 files changed +486 −11
docs/features/focus.md added +12
@@ -0,0 +1,12 @@
1 ---
2 topic: Every setting, by topic
3 row: Focus until a time
4 ---
5 # Focus until a time
6
7 Phone notifications on Settings carries a Focus line with `1h` and `4h` (`End` while one is set) in its action row; `Tomorrow` and instants are for the other doors. The home shows "Focus until 16:00" with **End** while one is set, and nothing when it is not.
8
9 - The dispatcher (`src/crew/dispatch.ts`) starts no new crew run in the owner's repositories (held as `focus`, in the run's log and vitals). Runs already going finish; a run carrying on after a pause is already going. Checks on a person's own pushes are not the dispatcher's and run as ever.
10 - The notifier (`src/crew/notify.ts`) sends no ask's ping; what asked meanwhile is told once, within a minute of the end, in the usual words. A restart during focus starts from nothing seen, so everything that asks is told at the end rather than lost. A drain page and a failed-release page are alarms, not pings: they go through focus, because holding a broken release from the admin for up to 7 days would hide it.
11 - The value is a user setting, `focus_until` (`src/crew/focus.ts`): an instant at most 7 days ahead. Past or too far is refused with `past` or `too_far`. It lapses by the clock; nothing sweeps it.
12 - Same action: MCP `notify` with `{ action: "focus", for }` (no `for` reads it); the terminal's phone-notifications screen, key `f`.
src/crew/dispatch.ts +18
@@ -57,6 +57,7 @@ import { bugsFirst } from "../flow/bugs.ts";
5757 import { forgeFailed } from "../flow/alarm_lane.ts";
5858 import { byDials } from "./team_share.ts";
5959 import { peopleFirst } from "./people_first.ts";
60 import { inFocus } from "./focus.ts";
6061 import { inMaintenance } from "../maintenance/state.ts";
6162 import { gateQueue } from "../flow/valve_gate.ts";
6263 import { ARCHIVED_WHY, getRepoById, type Repo } from "../core/repos.ts";
@@ -1697,6 +1698,13 @@ export function pump(
16971698 // reads every queued run, to say which the pace or a limit holds (#11518).
16981699 const weeks = new Map<string, ReturnType<typeof weekFor>>();
16991700 const capDay = new Map<string, string | null>();
1701 // Whether each owner is in focus (#15721): one read per owner per pass, not one per queued run.
1702 const focusOf = new Map<string, boolean>();
1703 const focused = (ownerId: string): boolean => {
1704 let on = focusOf.get(ownerId);
1705 if (on === undefined) focusOf.set(ownerId, (on = inFocus(app.db, ownerId)));
1706 return on;
1707 };
17001708 for (const queued of gated.order) {
17011709 // One run per issue at a time: this one waits for its sibling, not for a slot.
17021710 // A sibling that hangs is still caught: the running run goes stale on its
@@ -1719,6 +1727,16 @@ export function pump(
17191727 }
17201728 continue;
17211729 }
1730 // The owner's focus (#15721): nothing new starts in their repositories; a run carrying on
1731 // (attempt > 0) is already going, and finishes.
1732 if (fresh.attempt === 0 && home !== undefined && focused(home.ownerId)) {
1733 held.set(fresh.id, "focus");
1734 if (!noted.has(fresh.id)) {
1735 noted.add(fresh.id);
1736 appendRunLog(app.config.dataDir, fresh.id, "queued, not started: its owner is in focus and the crew starts nothing new until it ends");
1737 }
1738 continue;
1739 }
17221740 // The week's ceiling holds every path that starts a run in an autonomous
17231741 // repository: assigned, review, feedback and check runs as much as picks (#8873).
17241742 if (home !== undefined && home.autonomy === "autonomous") {
src/crew/focus.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * "Focus until <time>" (#15721): the owner asks the crew to stay out of the way. While the instant
3 * is ahead, the dispatcher starts no new crew run in the owner's repositories (`crew/dispatch.ts`)
4 * and the notifier holds its pings (`crew/notify.ts`); what was held arrives once when it ends.
5 * Runs already going finish, and checks on a person's own pushes are not the dispatcher's.
6 *
7 * One user setting, an ISO instant. It lapses by comparison with the clock, so no sweeper has to
8 * remember it; a stale value reads as none. Plain data in and out: the db, a user id, a clock.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { getUserSetting, setUserSetting } from "../core/settings.ts";
13 import { err, ok, type Result } from "../kernel/result.ts";
14
15 const KEY = "focus_until";
16 const HOUR_MS = 3_600_000;
17 /** The furthest ahead a focus may be set: a week. */
18 export const FOCUS_MAX_MS = 7 * 24 * HOUR_MS;
19
20 export type FocusError = "invalid" | "past" | "too_far";
21
22 export const FOCUS_ERRORS: Record<FocusError, string> = {
23 invalid: "Say '1h', '4h', 'tomorrow', 'off', or an instant like 2026-11-24T16:00:00Z.",
24 past: "That time has already passed: focus must end in the future.",
25 too_far: "Focus can last at most 7 days.",
26 };
27
28 /** The next 08:00 UTC after `now`: "until tomorrow" is the morning, never more than a day away. */
29 function tomorrow(now: number): number {
30 const d = new Date(now);
31 const at = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), 8);
32 return at > now ? at : at + 24 * HOUR_MS;
33 }
34
35 /** When the focus ends, or null when none is set or it has lapsed. */
36 export function focusUntil(db: Database, userId: string, now = Date.now()): string | null {
37 const at = getUserSetting(db, userId, KEY);
38 if (at === undefined || at === "") return null;
39 const ms = Date.parse(at);
40 return Number.isFinite(ms) && ms > now ? at : null;
41 }
42
43 /** Whether this person is in focus now. */
44 export const inFocus = (db: Database, userId: string, now = Date.now()): boolean => focusUntil(db, userId, now) !== null;
45
46 /** The instant a choice or an instant names (null for off), or why it is refused. */
47 export function parseFocus(raw: string, now = Date.now()): Result<string | null, FocusError> {
48 const text = raw.trim();
49 if (text === "" || text === "off") return ok(null);
50 let ms: number;
51 if (text === "1h") ms = now + HOUR_MS;
52 else if (text === "4h") ms = now + 4 * HOUR_MS;
53 else if (text === "tomorrow") ms = tomorrow(now);
54 else {
55 if (!/^\d{4}-\d{2}-\d{2}T[\d:.]+(Z|[+-]\d{2}:\d{2})$/.test(text)) return err("invalid");
56 ms = Date.parse(text);
57 if (!Number.isFinite(ms)) return err("invalid");
58 if (ms <= now) return err("past");
59 if (ms - now > FOCUS_MAX_MS) return err("too_far");
60 }
61 return ok(new Date(ms).toISOString());
62 }
63
64 /** Saves a focus (or clears it for "off"); the instant it ends, or null when cleared. */
65 export function setFocus(db: Database, userId: string, raw: string, now = Date.now()): Result<string | null, FocusError> {
66 const parsed = parseFocus(raw, now);
67 if (!parsed.ok) return parsed;
68 if (parsed.value === null) db.query("DELETE FROM user_setting WHERE user_id = ?1 AND key = ?2").run(userId, KEY);
69 else setUserSetting(db, userId, KEY, parsed.value);
70 return parsed;
71 }
72
73 /** The clock time of an instant, UTC, as the home line says it: "16:00". */
74 export const focusClock = (until: string): string => new Date(until).toISOString().slice(11, 16);
75
76 /** The one line for the settings page, before its choices. */
77 export function focusSentence(until: string | null): string {
78 return until === null ? "Focus:" : `Focus until ${focusClock(until)} UTC.`;

Plain words: a bare 'Focus:' label before buttons is a sentence fragment; say 'Focus: off.' or similar.

79 }
src/crew/notify.ts +18
@@ -50,6 +50,7 @@ import { loadClog } from "../flow/clog_tick.ts";
5050 import { redactSecrets } from "../kernel/log.ts";
5151 import { forgeCeiling } from "../flow/ceiling.ts";
5252 import { askLinesFor } from "../web/studio/asks.ts";
53 import { inFocus } from "./focus.ts";
5354 import { during } from "../perf/jobs.ts";
5455
5556 const KEY = "notify_url";
@@ -373,6 +374,11 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
373374 let queue: Promise<void> = Promise.resolve();
374375 let stopped = false;
375376
377 /**
378 * Per person: in focus when last looked at, so the pager tells them the minute it ends (#15721).
379 */
380 const focused = new Set<string>();
381
376382 const people = (): string[] =>
377383 app.db
378384 .query<
@@ -498,6 +504,16 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
498504 seen.delete(userId);
499505 return;
500506 }
507 // In focus (#15721) nothing is looked at, so `seen` stays as it was and what asks meanwhile is
508 // new, once, when focus ends. A baseline (a restart) must not record what asks now as seen, or
509 // the held asks would vanish: it starts from nothing seen, so all that asks is told at the end.
510 // Alarms (a drain, a failed release) are not pings: they are paged through focus.
511 if (inFocus(app.db, userId, now())) {
512 if (!seen.has(userId)) seen.set(userId, new Set());
513 focused.add(userId);
514 return;
515 }
516 focused.delete(userId);
501517 // What asks them; for an admin, who joined (`actions/accounts.ts`); and
502518 // a milestone they watch that landed (`core/watches.ts`), which links
503519 // to itself.
@@ -605,6 +621,8 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
605621 queue = queue.then(async () => {
606622 try {
607623 for (const id of people()) await page(id, false);
624 // Focus that has ended: what asked meanwhile is told now, not at the next ten-minute look.
625 for (const id of [...focused]) if (!inFocus(app.db, id, now())) await tell(id, false);
608626 await pageRollback();
609627 } catch (error) {
610628 app.log.error("notify failed", { error: String(error) });
src/http/marks/settings.json +1
@@ -11,6 +11,7 @@
1111 "/settings/telemetry": "admin",
1212 "/settings": "open",
1313 "/settings/notify": "open",
14 "/settings/focus": "open",
1415 "/settings/dotfiles": "open",
1516 "/settings/edge/link": "open",
1617 "/settings/edge/unlink": "open",
src/http/mcp/tools/notify.ts +15 −3
@@ -1,17 +1,29 @@
11 import { scopeAllows } from "../../../core/tokens.ts";
22 import { NOTIFY_ERRORS, notifyHost, notifyUrlOf, setNotifyUrl } from "../../../crew/notify.ts";
3 import { FOCUS_ERRORS, focusUntil, setFocus } from "../../../crew/focus.ts";
34 import { good, bad, type Tool } from "../shared.ts";
45
56 export const tool: Tool = {
67 name: "notify",
7 doc: "`{ url? }`: read (its host only), set or, with an empty `url`, turn off your phone notify URL, as Settings does; a person's, saving needs an admin token",
8 doc: "`{ url? }`: read (its host only), set or, with an empty `url`, turn off your phone notify URL, as Settings does; a person's, saving needs an admin token. `{ action: \"focus\", for? }` (`1h`, `4h`, `tomorrow`, `off` or an instant within 7 days): the crew starts no new run and no ping is sent until then; no `for` reads it",
89 description: "Read, set or clear your phone notify URL.",
9 inputSchema: { type: "object", properties: { url: { type: "string" } } },
10 inputSchema: { type: "object", properties: { url: { type: "string" }, action: { type: "string", enum: ["focus"] }, for: { type: "string" } } },
1011 writes: true,
11 readsWithout: "url",
12 readsWithout: ["url", "for"],
1213 run(ctx, user, args) {
1314 if (user.kind === "agent") return bad("forbidden", "a notify URL is a person's, not an agent's");
1415 const { url } = args;
16 if (args["action"] !== undefined) {
17 if (args["action"] !== "focus") return bad("invalid", "action is focus");
18 const until = () => ({ focusUntil: focusUntil(ctx.app.db, user.id) });
19 const choice = args["for"];
20 if (choice === undefined) return good(until());
21 if (typeof choice !== "string") return bad("invalid", "send for as text: 1h, 4h, tomorrow, off or an instant");
22 if (!scopeAllows(ctx.auth.scope ?? "ro", "rw")) return bad("forbidden", "setting a focus needs a token that can write");
23 const saved = setFocus(ctx.app.db, user.id, choice);
24 if (!saved.ok) return bad("invalid", FOCUS_ERRORS[saved.error]);
25 return good(until());
26 }
1527 if (url === undefined) {
1628 const host = notifyHost(notifyUrlOf(ctx.app.db, user.id));
1729 return good({ set: host !== undefined, host: host ?? null });
src/http/settings_routes.ts +2
@@ -113,6 +113,7 @@ import {
113113 shellStop,
114114 shellsStopIdle,
115115 notifyUpdate,
116 focusUpdate,
116117 edgeLink,
117118 edgeUnlink,
118119 parentUnlink,
@@ -172,6 +173,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
172173 router.add("POST", "/settings/account/keep", accountKeep);
173174 router.add("POST", "/settings/account/close/options", closeOptions);
174175 router.add("POST", "/settings/notify", notifyUpdate);
176 router.add("POST", "/settings/focus", focusUpdate);
175177 router.add("POST", "/settings/dotfiles", dotfilesUpdate);
176178 router.add("POST", "/settings/edge/link", edgeLink);
177179 router.add("POST", "/settings/edge/unlink", edgeUnlink);
src/runs/held.ts +2 −1
@@ -21,7 +21,7 @@ import type { Database } from "bun:sqlite";
2121 export const HELD_FRESH_MS = 2 * 60_000;
2222
2323 /** Why the dispatcher held a run. */
24 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone";
24 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap" | "clone" | "focus";
2525
2626 /** How vitals names each cause: "2 by a shut valve". */
2727 export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
@@ -33,6 +33,7 @@ export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
3333 memory: "the forge's memory near its limit",
3434 cap: "a bet's daily cap",
3535 clone: "a clone backing off",
36 focus: "the owner's focus",
3637 };
3738
3839 /** How long a pass remembers when it last held a run; a day bounds the map. */
src/tui/screens/notify.ts +22
@@ -8,6 +8,7 @@
88 */
99
1010 import { NOTIFY_ERRORS, claimTest, notifyHost, notifyUrlOf, post, sendTest, setNotifyUrl, type Sender } from "../../crew/notify.ts";
11 import { FOCUS_ERRORS, focusClock, focusUntil, setFocus } from "../../crew/focus.ts";
1112 import type { Ctx, Screen } from "../app/app.ts";
1213 import { binding } from "../app/keys.ts";
1314 import { style } from "../term/style.ts";
@@ -38,14 +39,19 @@ export function notifyScreen(f: Session, ctx: Ctx): Screen {
3839 binding(["s"], "set the URL"),
3940 ...(host() === undefined ? [] : [binding(["t"], "send a test")]),
4041 binding(["x"], "turn off"),
42 binding(["f"], "focus: 1h, 4h, tomorrow, off"),
4143 ];
4244 },
4345 render(area, s) {
4446 const c = ctx.theme.c;
4547 const h = host();
48 const until = f.user === undefined ? null : focusUntil(f.app.db, f.user.id);
49 const focusLine = (): string =>
50 until === null ? "Focus: off. No new runs, pings held while on." : `Focus until ${focusClock(until)} UTC: no new runs, pings held.`;
4651 const lines = [
4752 h === undefined ? "Off. s sets a URL (an ntfy topic, https)." : `On: notifications go to ${h}.`,
4853 "The address is a secret and is never shown past its host.",
54 focusLine(),
4955 ...(note === "" ? [] : ["", note]),
5056 ];
5157 lines.forEach((l, i) => {
@@ -68,6 +74,22 @@ export function notifyScreen(f: Session, ctx: Ctx): Screen {
6874 );
6975 return true;
7076 }
77 if (e.key === "f") {
78 ctx.push(
79 promptScreen(ctx, screen, {
80 title: "Focus",
81 label: "1h, 4h, tomorrow or off",
82 onSubmit: (raw) => {
83 if (f.user === undefined) return undefined;
84 const done = setFocus(f.app.db, f.user.id, raw);
85 if (!done.ok) return FOCUS_ERRORS[done.error];
86 note = done.value === null ? "Focus ended." : "Focus set.";
87 return undefined;
88 },
89 }),
90 );
91 return true;
92 }
7193 if (e.key === "t") {
7294 const h = host();
7395 if (h === undefined || f.user === undefined) return true;
src/web/pages/account.ts +34 −2
@@ -29,6 +29,7 @@ import {
2929 notifyUrlOf,
3030 setNotifyUrl,
3131 } from "../../crew/notify.ts";
32 import { FOCUS_ERRORS, focusSentence, focusUntil, setFocus } from "../../crew/focus.ts";
3233 import { forgeHost, noreplyAddress } from "../../core/commit_identity.ts";
3334 import { ABILITIES, roleOf, rowOf, type Ability } from "../../core/roles.ts";
3435 import { linkEdgeLogin, linkedLogin, unlinkEdgeLogin } from "../../core/edge_links.ts";
@@ -191,6 +192,21 @@ const refusal = (message: string | undefined): Html =>
191192 </div>`,
192193 );
193194
195 /**
196 * Focus (#15721) sits with the pings it holds, in the notify form's own action row: a person's
197 * only, its buttons posting to `/settings/focus`. Nothing but a word and the choices is added.
198 */
199 function focusActions(ctx: Ctx): Html | null {
200 const user = ctx.auth.user!;
201 if (user.kind !== "user") return null;
202 const to = "/settings/focus";
203 const until = focusUntil(ctx.app.db, user.id);
204 return html`<span class="small muted">${focusSentence(until)}</span>

Box 1: 'until tomorrow' is missing from the control (only 1h and 4h). Add a Tomorrow button. Also the buttons need aria-labels ('Focus for 1 hour'); '1h' alone is not a name.

205 ${until === null
206 ? html`${btn("1h", { name: "for", value: "1h", formaction: to })} ${btn("4h", { name: "for", value: "4h", formaction: to })}`
207 : btn("End", { name: "for", value: "off", formaction: to })}`;
208 }
209
194210 function notifyView(ctx: Ctx, error?: string): Html {
195211 const host = notifyHost(notifyUrlOf(ctx.app.db, ctx.auth.user!.id));
196212 return block(
@@ -202,10 +218,11 @@ function notifyView(ctx: Ctx, error?: string): Html {
202218 type: "url",
203219 autocomplete: "off",
204220 placeholder: host === undefined ? "https://ntfy.sh/your-topic" : "••••••••",
205 hint: host === undefined ? "https: only." : `Sending to ${host}. https: only.`,
221 hint: host === undefined ? "https only." : `Sending to ${host}.`,
206222 })}
207223 <div class="form-actions">
208 ${btn("Save notify URL", { variant: "primary" })}
224 ${btn("Save", { variant: "primary" })}
225 ${focusActions(ctx)}
209226 </div>
210227 ${refusal(error)}
211228 </form>`,
@@ -667,6 +684,21 @@ export async function notifyUpdate(ctx: Ctx): Promise<Response> {
667684 });
668685 }
669686
687 // POST /settings/focus
688 export async function focusUpdate(ctx: Ctx): Promise<Response> {
689 if (!ctx.auth.user) return signInFirst(ctx);
690 if (ctx.auth.user.kind !== "user") return forbiddenPage(ctx, "A focus is a person's, not an agent's.");
691 const form = await readForm(ctx, "admin");
692 if (form instanceof Response) return form;
693 const saved = setFocus(ctx.app.db, ctx.auth.user.id, field(form, "for"));
694 if (!saved.ok)
695 return accountShell(ctx, "profile", "Settings", notifyView(ctx, FOCUS_ERRORS[saved.error]), 422);
696 const to = field(form, "back") === "home" ? "/" : "/settings";
697 return flashTo(ctx, to, {
698 message: saved.value === null ? "Focus ended." : "Focus set.",
699 });
700 }
701
670702 // POST /settings
671703 export async function accountUpdate(ctx: Ctx): Promise<Response> {
672704 if (!ctx.auth.user) return signInFirst(ctx);
src/web/pages/home_flow.ts +2 −1
@@ -15,6 +15,7 @@
1515 * version without being drawn. The page is a static picture with scripts off.
1616 */
1717
18 import { focusLine } from "../studio/held.ts";
1819 import { time } from "../time_element.ts";
1920 import { requestHolds } from "../../http/conditional.ts";
2021 import { setCookie } from "../../auth/cookies.ts";
@@ -542,7 +543,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
542543 ${spawned === undefined ? firstWeekBlock(ctx.app.db, user) : null}
543544 <div class="hf-tell">${tellBox(ctx, user)}</div>`;
544545 // A client who asked for the whole home (`?all=1`) has a way back to their apps.
545 const after = html`${ctx.url.searchParams.has("all") ? html`<p class="small muted" id="lean-home"><a href="/">Just my apps</a></p>` : null}${requestsCard(ctx, "home")}
546 const after = html`${ctx.url.searchParams.has("all") ? html`<p class="small muted" id="lean-home"><a href="/">Just my apps</a></p>` : null}${focusLine(ctx, user)}${requestsCard(ctx, "home")}
546547 ${spawned?.url === undefined ? null : html`<p class="small muted" id="forge-address">Your forge: <a href="${spawned.url}">${new URL(spawned.url).host}</a></p>`}
547548 ${startedFromLine(ctx.app.db, ctx.app.config.dataDir, user)}`;
548549 const forges = wide ? await timePhaseAsync(ctx.request, "forges", () => forgesRegion(ctx.app, false)) : null;
src/web/studio/held.ts +16
@@ -4,6 +4,7 @@
44 * gate, when — and a link that opens the list.
55 */
66
7 import { focusClock, focusUntil } from "../../crew/focus.ts";
78 import { gateHold } from "../../core/gate_hold.ts";
89 import { reposWithGateTitle } from "../../core/pillars.ts";
910 import { canWrite, listReposOwnedBy, type Repo } from "../../core/repos.ts";
@@ -48,3 +49,18 @@ export function heldLine(ctx: Ctx, user: User): Html | null {
4849 )}
4950 </section>`;
5051 }
52
53 /**
54 * The home's one quiet line while the owner is in focus (#15721): "Focus until 16:00" and a one-tap
55 * end.
56 */
57 export function focusLine(ctx: Ctx, user: User): Html | null {
58 if (user.kind !== "user") return null;
59 const until = focusUntil(ctx.app.db, user.id);
60 if (until === null) return null;
61 return html`<form method="post" action="/settings/focus" class="small muted inline" id="focus-line">
62 <span>Focus until ${focusClock(until)}</span>

Principle 8 / experience: 'Focus until 16:00' has no zone or date; settings says UTC, home does not. Fix: use the time element or add 'UTC', and the day when it is not today. Also give the End button an accessible name ('End focus').

63 <input type="hidden" name="back" value="home" />
64 <button type="submit" name="for" value="off" class="link">End</button>
65 </form>`;
66 }
src/web/studio/home.ts +2 −2
@@ -73,7 +73,7 @@ import { parseBefore } from "../../feed/timeline.ts";
7373 import { parseCursor } from "../../feed/feed.ts";
7474 import { applySavedFilter } from "./filter_back.ts";
7575 import { composer, publicFeed, feedJs, feedNote, feedRegion } from "./feed.ts";
76 import { heldLine } from "./held.ts";
76 import { focusLine, heldLine } from "./held.ts";
7777 import { waitingLine } from "./kpi_row.ts";
7878 import { feedCandidateCache } from "../../feed/feed.ts";
7979 import { notePhase, notePhaseRest, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
@@ -326,7 +326,7 @@ export async function studioHome(
326326 // Before the first tell the card is the one box and carries the key line and the composer.
327327 const firstTell = steps.some((s) => s.key === "tell" && !s.done);
328328 const lean = html`<h1 class="sr-only">Home</h1>
329 ${firstSteps} ${address} ${startedFromLine(ctx.app.db, ctx.app.config.dataDir, user)} ${firstTell ? null : composer(ctx, user)} ${apps} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${everydayLine(steps)}
329 ${firstSteps} ${address} ${startedFromLine(ctx.app.db, ctx.app.config.dataDir, user)} ${firstTell ? null : composer(ctx, user)} ${apps} ${firstTell ? null : crewKeyCard(ctx)} ${heldLine(ctx, user)} ${focusLine(ctx, user)} ${everydayLine(steps)}
330330 <div class="stack">
331331 <p class="small muted">
332332 <a href="/?all=1">Show everything</a>
test/account-help.test.ts +2 −2
@@ -69,7 +69,7 @@ test("constraints stay as one-line hints tied by aria-describedby", async () =>
6969 expect(pw).toContain("At least 10 characters.");
7070 expect(pw).toMatch(/aria-describedby="[^"]*-hint"/);
7171 const profile = await get("/settings");
72 expect(profile).toContain("https: only.");
72 expect(profile).toContain("https only.");
7373 });
7474
7575 test("a saved notify URL shows only its host, as a hint", async () => {
@@ -81,6 +81,6 @@ test("a saved notify URL shows only its host, as a hint", async () => {
8181 });
8282 expect(set.status).toBeLessThan(400);
8383 const body = await get("/settings");
84 expect(body).toContain("Sending to ntfy.sh. https: only.");
84 expect(body).toContain("Sending to ntfy.sh.");
8585 expect(body).not.toContain("secret-topic");
8686 });
test/focus.test.ts added +224
@@ -0,0 +1,224 @@
1 /**
2 * "Focus until <time>" (#15721): no new run, no ping, until it ends; the boundary names its errors.
3 */
4 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5 import { chmodSync, writeFileSync } from "node:fs";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRun, getRun } from "../src/core/runs.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { startCrew } from "../src/crew/dispatch.ts";
14 import { focusUntil, parseFocus, setFocus } from "../src/crew/focus.ts";
15 import { setNotifyUrl, startNotifier, type Sender } from "../src/crew/notify.ts";
16 import { serve } from "../src/http/server.ts";
17 import { pollUntil } from "./helpers/poll.ts";
18 import { heldRuns } from "../src/runs/held.ts";
19
20 const HOUR = 3_600_000;
21 const NOW = Date.parse("2026-11-23T12:00:00Z");
22
23 describe("the setting at its boundary", () => {
24 test("the choices name an instant; off clears", () => {
25 expect(parseFocus("1h", NOW)).toEqual({ ok: true, value: "2026-11-23T13:00:00.000Z" });
26 expect(parseFocus("4h", NOW)).toEqual({ ok: true, value: "2026-11-23T16:00:00.000Z" });
27 expect(parseFocus("tomorrow", NOW)).toEqual({ ok: true, value: "2026-11-24T08:00:00.000Z" });
28 expect(parseFocus("off", NOW)).toEqual({ ok: true, value: null });
29 expect(parseFocus("", NOW)).toEqual({ ok: true, value: null });
30 });
31 test("a past, a too-far and a malformed value are refused by name", () => {
32 expect(parseFocus("2026-11-23T11:00:00Z", NOW)).toEqual({ ok: false, error: "past" });
33 expect(parseFocus(new Date(NOW + 7 * 24 * HOUR + 1000).toISOString(), NOW)).toEqual({ ok: false, error: "too_far" });
34 expect(parseFocus(new Date(NOW + 7 * 24 * HOUR).toISOString(), NOW).ok).toBe(true);
35 expect(parseFocus("whenever", NOW)).toEqual({ ok: false, error: "invalid" });
36 });
37 });
38
39 describe("in focus", () => {
40 let dataDir: string;
41 let app: App;
42 let owner: User;
43 let repoId = "";
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-focus-"));
47 app = createApp({ dataDir, port: 0, disk: () => ({ freeBytes: 100, totalBytes: 100 }) });
48 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
49 if (!made.ok) throw new Error(String(made.error));
50 owner = made.value;
51 repoId = crypto.randomUUID();
52 app.db.query("INSERT INTO repo (id, owner_id, name, visibility, created_at) VALUES (?1, ?2, 'f', 'private', ?3)").run(repoId, owner.id, new Date().toISOString());
53 });
54 afterAll(async () => {
55 app.close();
56 await rm(dataDir, { recursive: true, force: true });
57 });
58
59 test("a focus lapses on its own, with nothing to sweep it", () => {
60 expect(setFocus(app.db, owner.id, "1h", NOW).ok).toBe(true);
61 expect(focusUntil(app.db, owner.id, NOW + HOUR - 1)).not.toBeNull();
62 expect(focusUntil(app.db, owner.id, NOW + HOUR)).toBeNull();
63 setFocus(app.db, owner.id, "off", NOW);
64 });
65
66 test("a run is not started in focus, and is started after", async () => {
67 expect(setFocus(app.db, owner.id, "1h").ok).toBe(true);
68 const run = createRun(app.db, { repoId, kind: "agent" });
69 // A check on a person's own push is not the crew's to hold: focus never names it.
70 const check = createRun(app.db, { repoId, kind: "check" });
71 const servers = await serve(app);
72 const fake = join(dataDir, "fake-claude");
73 writeFileSync(fake, `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi\nexit 1\n`);
74 chmodSync(fake, 0o755);
75 const crew = await startCrew(app, { forgeUrl: servers.url, localUrl: servers.url, binary: fake, concurrency: 2, budgetUsd: 1, runTimeoutMs: 60_000, tickMs: 20 });
76 try {
77 await pollUntil(() => heldRuns(app.db).get(run.id) === "focus", "the run held for focus", 10_000);
78 expect(heldRuns(app.db).get(run.id)).toBe("focus");
79 expect(getRun(app.db, run.id)?.state).toBe("queued");
80 expect(heldRuns(app.db).has(check.id)).toBe(false);
81 setFocus(app.db, owner.id, "off");
82 await pollUntil(() => getRun(app.db, run.id)?.state !== "queued", "the run started", 10_000);
83 expect(getRun(app.db, run.id)?.state).not.toBe("queued");
84 } finally {
85 await crew.stop();
86 servers.stop();
87 }
88 });
89
90 test("a ping is held in focus and sent once when it ends", async () => {
91 const posts: string[] = [];
92 const send: Sender = async (_url, body) => {
93 posts.push(body);
94 return true;
95 };
96 let clock = Date.now();
97 expect(setNotifyUrl(app.db, owner.id, "https://ntfy.example.test/focus-topic").ok).toBe(true);
98 const notifier = startNotifier(app, { forgeUrl: "https://forge.example.test", send, now: () => clock });
99 await notifier.settled();
100 try {
101 expect(setFocus(app.db, owner.id, "1h", clock).ok).toBe(true);
102 // A new ask while in focus: an outside person asks for an account.
103 await createUser(app.db, { origin: "seed", trusted: true, username: "newcomer", email: "[email protected]", password: "a-good-passphrase" });
104 app.bus.append({ kind: "user.created" });
105 await notifier.settled();
106 await notifier.tick();
107 expect(posts).toHaveLength(0);
108 // Focus ends: the pager's next minute tells it, once.
109 clock += 2 * HOUR;
110 await notifier.tick();
111 await notifier.settled();
112 const told = posts.length;
113 expect(told).toBeGreaterThan(0);
114 await notifier.tick();
115 await notifier.settled();
116 expect(posts).toHaveLength(told);
117 } finally {
118 await notifier.close();
119 }
120 });
121 });
122
123 describe("a restart during focus", () => {
124 test("keeps what was held: the baseline does not record it as seen", async () => {
125 const dataDir = await mkdtemp(join(tmpdir(), "forge-focus-restart-"));
126 const app = createApp({ dataDir, port: 0, disk: () => ({ freeBytes: 100, totalBytes: 100 }) });
127 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
128 if (!made.ok) throw new Error(String(made.error));
129 const posts: string[] = [];
130 const send: Sender = async (_url, body) => {
131 posts.push(body);
132 return true;
133 };
134 let clock = Date.now();
135 try {
136 expect(setNotifyUrl(app.db, made.value.id, "https://ntfy.example.test/restart").ok).toBe(true);
137 expect(setFocus(app.db, made.value.id, "1h", clock).ok).toBe(true);
138 // Someone asks for an account, and then the process restarts: its baseline runs in focus.
139 await createUser(app.db, { origin: "seed", trusted: true, username: "newcomer", email: "[email protected]", password: "a-good-passphrase" });
140 const notifier = startNotifier(app, { forgeUrl: "https://forge.example.test", send, now: () => clock });
141 await notifier.settled();
142 expect(posts).toHaveLength(0);
143 clock += 2 * HOUR;
144 await notifier.tick();
145 await notifier.settled();
146 expect(posts.length).toBeGreaterThan(0);
147 await notifier.close();
148 } finally {
149 app.close();
150 await rm(dataDir, { recursive: true, force: true });
151 }
152 });
153 });
154
155 describe("POST /settings/focus", () => {
156 let dataDir: string;
157 let app: App;
158 let servers: Awaited<ReturnType<typeof serve>>;
159 let cookie = "";
160 let agentCookie = "";
161
162 beforeAll(async () => {
163 dataDir = await mkdtemp(join(tmpdir(), "forge-focus-route-"));
164 app = createApp({ dataDir, port: 0 });
165 servers = await serve(app);
166 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
167 if (!made.ok) throw new Error(String(made.error));
168 const bot = await createUser(app.db, { origin: "seed", trusted: true, username: "helper", email: "[email protected]", password: "a-good-passphrase" });
169 if (!bot.ok) throw new Error(String(bot.error));
170 app.db.query("UPDATE user SET is_agent = 1 WHERE username = 'helper'").run();
171 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
172 agentCookie = `forge_session=${createSession(app.db, bot.value.id).token}`;
173 owner = made.value;
174 });
175 afterAll(async () => {
176 servers.stop();
177 app.close();
178 await rm(dataDir, { recursive: true, force: true });
179 });
180 let owner: User;
181
182 const post = (form: Record<string, string>, o: { cookie?: string; origin?: string } = {}) =>
183 fetch(`${servers.url}/settings/focus`, {
184 method: "POST",
185 headers: { ...(o.cookie === undefined ? {} : { cookie: o.cookie }), origin: o.origin ?? servers.url },
186 body: new URLSearchParams(form),
187 redirect: "manual",
188 });
189 const get = async (path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
190
191 test("signed out is sent to sign in and sets nothing", async () => {
192 const res = await post({ for: "1h" });
193 expect(res.status).not.toBe(200);
194 expect(focusUntil(app.db, owner.id)).toBeNull();
195 });
196 test("an agent is refused", async () => {
197 const res = await post({ for: "1h" }, { cookie: agentCookie });
198 expect(res.status).toBe(403);
199 });
200 test("a cross-origin post is refused", async () => {
201 const res = await post({ for: "1h" }, { cookie, origin: "https://evil.example" });
202 expect(res.status).toBeGreaterThanOrEqual(400);
203 expect(focusUntil(app.db, owner.id)).toBeNull();
204 });
205 test("a bad value is a 422 with the named error", async () => {
206 const res = await post({ for: "whenever" }, { cookie });
207 expect(res.status).toBe(422);
208 expect(await res.text()).toContain("Say &#39;1h&#39;, &#39;4h&#39;");
209 expect(focusUntil(app.db, owner.id)).toBeNull();
210 });
211 test("a good value sets it, the settings and home say so, and back=home returns home", async () => {
212 expect(await get("/")).not.toContain('id="focus-line"');
213 const res = await post({ for: "1h" }, { cookie });
214 expect(res.status).toBe(303);
215 expect(res.headers.get("location")).toBe("/settings");
216 expect(focusUntil(app.db, owner.id)).not.toBeNull();
217 expect(await get("/settings")).toContain("Focus until");
218 expect(await get("/")).toContain('id="focus-line"');
219 const off = await post({ for: "off", back: "home" }, { cookie });
220 expect(off.headers.get("location")).toBe("/");
221 expect(focusUntil(app.db, owner.id)).toBeNull();
222 expect(await get("/")).not.toContain('id="focus-line"');
223 });
224 });
test/mcp-notify.test.ts +14
@@ -120,4 +120,18 @@ describe("MCP notify", () => {
120120 expect(read.text).toContain("forbidden");
121121 expect((await call(botToken, { url: "https://ntfy.example.com/x" })).error).toBe(true);
122122 });
123
124 test("action focus sets, reads and ends a focus, and names its refusals", async () => {
125 expect(JSON.parse((await call(narrow, { action: "focus" })).text)).toEqual({ focusUntil: null });
126 const set = JSON.parse((await call(narrow, { action: "focus", for: "1h" })).text);
127 expect(Date.parse(set.focusUntil)).toBeGreaterThan(Date.now());
128 expect((await call(ro, { action: "focus", for: "4h" })).error).toBe(true);
129 const past = await call(narrow, { action: "focus", for: "2020-01-01T00:00:00Z" });
130 expect(past.error).toBe(true);
131 expect(past.text).toContain("already passed");
132 const far = await call(narrow, { action: "focus", for: new Date(Date.now() + 8 * 86_400_000).toISOString() });
133 expect(far.text).toContain("7 days");
134 expect(JSON.parse((await call(narrow, { action: "focus", for: "off" })).text)).toEqual({ focusUntil: null });
135 expect((await call(botToken, { action: "focus", for: "1h" })).error).toBe(true);
136 });
123137 });
test/tui-notify.test.ts +23
@@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
7 import { FOCUS_ERRORS, focusUntil } from "../src/crew/focus.ts";
78 import { NOTIFY_ERRORS, notifyUrlOf } from "../src/crew/notify.ts";
89 import { createUser, getUserByName } from "../src/core/users.ts";
910 import { createForgeApp } from "../src/tui/forge.ts";
@@ -118,6 +119,28 @@ describe("phone notifications in the terminal", () => {
118119 h.stop();
119120 });
120121
122 test("f sets a focus, refuses a bad one by name, and off ends it", async () => {
123 const alice = getUserByName(app.db, "alice")!;
124 const h = boot("alice");
125 await h.open();
126 await h.press("f");
127 await h.type("whenever");
128 await h.press("enter");
129 expect(h.text()).toContain(FOCUS_ERRORS.invalid.slice(0, 30));
130 expect(focusUntil(app.db, alice.id)).toBeNull();
131 await h.press("esc");
132 await h.press("f");
133 await h.type("1h");
134 await h.press("enter");
135 expect(focusUntil(app.db, alice.id)).not.toBeNull();
136 expect(h.text()).toContain("Focus set.");
137 await h.press("f");
138 await h.type("off");
139 await h.press("enter");
140 expect(focusUntil(app.db, alice.id)).toBeNull();
141 h.stop();
142 });
143
121144 test("x when already off says so", async () => {
122145 const h = boot("alice");
123146 await h.open();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs