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

The client list shows when each sent forge link was first opened and last seen, in plain words #12832

Merged opened this

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

Merged

torque/forge:torque/12694-the-client-list-shows-when-each-sent-for → main 5 commits fork 2 threads · 2 unresolved

  • Merged. torque/12694-the-client-list-shows-when-each-sent-for was merged into main as c7ccd2e.

Review

Sign in to review this change.
8 files changed +268 −10
src/spawn/claim.ts +30 −1
@@ -54,6 +54,8 @@ interface Stored {
5454 readonly u: string | null;
5555 /** When the spawner took it back, ISO; absent while it stands. */
5656 readonly r?: string;
57 /** When a browser first opened the claim page, ISO; absent until one did. */
58 readonly o?: string;
5759 }
5860
5961 export type ClaimState =
@@ -427,6 +429,8 @@ export interface LinkInfo {
427429 readonly revokedAt: string | null;
428430 /** When the link was spent (someone opened it and made an account), ISO; absent while unspent. */
429431 readonly usedAt?: string | null;
432 /** When a person's browser first opened the claim page, ISO; null while none did. */
433 readonly openedAt?: string | null;
430434 /** When the link stops working, ISO. */
431435 readonly expiresAt?: string;
432436 }
@@ -456,7 +460,7 @@ const stateOf = (s: Stored, now: number): LinkState =>
456460 /** The claim link in this forge's own database; null when it has none. */
457461 export function linkOf(db: Database, now = Date.now()): LinkInfo | null {
458462 const found = readStored(db);
459 return found === undefined ? null : { state: stateOf(found.stored, now), revokedAt: found.stored.r ?? null, usedAt: found.stored.u, expiresAt: found.stored.e };
463 return found === undefined ? null : { state: stateOf(found.stored, now), revokedAt: found.stored.r ?? null, usedAt: found.stored.u, openedAt: found.stored.o ?? null, expiresAt: found.stored.e };
460464 }
461465
462466 /** Replace the stored link only if nobody changed it since it was read. */
@@ -468,6 +472,31 @@ function swap(db: Database, orgId: string, from: Found, next: Stored): boolean {
468472 );
469473 }
470474
475 /**
476 * Whether a request is a person's browser opening a page: a GET that accepts
477 * HTML and carries no prefetch purpose. A chat unfurl or a link prefetcher
478 * (`Purpose`/`Sec-Purpose: prefetch`, `X-Moz: prefetch`, `X-Purpose: preview`,
479 * or an accept header that does not ask for HTML) is not someone looking.
480 */
481 export function isBrowserOpen(req: Request): boolean {

Heuristic only: unfurl bots that send Accept: text/html with no Purpose header count as opened. Documented, but a user-agent bot check would tighten it.

482 if (req.method !== "GET") return false;
483 if (!(req.headers.get("accept") ?? "").toLowerCase().includes("text/html")) return false;
484 for (const h of ["purpose", "sec-purpose", "x-purpose", "x-moz"])
485 if (/prefetch|preview|prerender/i.test(req.headers.get(h) ?? "")) return false;
486 return true;
487 }
488
489 /**
490 * Remember the first time the open link's page was opened; false when it was not open or
491 * already noted.
492 */
493 export function noteOpened(db: Database, now = Date.now()): boolean {
494 const row = db.query<{ user_id: string }, [string]>("SELECT user_id FROM user_setting WHERE key = ?1").get(KEY);
495 const found = readStored(db);
496 if (row === null || found === undefined || found.stored.o !== undefined || stateOf(found.stored, now) !== "open") return false;
497 return swap(db, row.user_id, found, { ...found.stored, o: new Date(now).toISOString() });
498 }
499
471500 /** Take back an open link: from now it answers "ended". False when it was not open. */
472501 export function revokeClaim(db: Database, orgId: string, now = Date.now()): boolean {
473502 const found = readStored(db, orgId);
src/spawn/clients.ts +35 −1
@@ -193,7 +193,7 @@ function linkOfBody(v: unknown): LinkInfo | null {
193193 const { state, revokedAt } = v as Record<string, unknown>;
194194 if (!LINK_STATES.includes(state as LinkState)) return null;
195195 const iso = (x: unknown): string | null => (typeof x === "string" && !Number.isNaN(Date.parse(x)) ? x : null);
196 return { state: state as LinkState, revokedAt: iso(revokedAt), usedAt: iso((v as Record<string, unknown>)["usedAt"]) };
196 return { state: state as LinkState, revokedAt: iso(revokedAt), usedAt: iso((v as Record<string, unknown>)["usedAt"]), openedAt: iso((v as Record<string, unknown>)["openedAt"]) };
197197 }
198198
199199 async function probe(app: App, child: Child): Promise<ForgeState | undefined> {
@@ -542,10 +542,44 @@ export function stageOf(r: Omit<ClientRow, "attention" | "stage">, now: number):
542542 : make("signedin", at(r.link?.usedAt));
543543 }
544544 if (r.link?.state === "used") return make("opened", at(r.link.usedAt));
545 if (r.link?.openedAt != null) return make("opened", r.link.openedAt);
545546 const sent = r.sentAt === null ? NaN : Date.parse(r.sentAt);
546547 return make("sent", r.sentAt, !Number.isNaN(sent) && now - sent > UNCLAIMED_MS);
547548 }
548549
550 /**
551 * What the sender is told about a link in plain words: when it was sent, whether and when a
552 * browser opened it, when a person was last seen there. "Opened" means a browser asked for the
553 * claim page, not that a person read it; a link spent before opens were noted is opened with no
554 * time, never a guessed one.
555 */
556 export interface Seen {
557 /** ISO of the send, or null when the ledger did not say. */
558 readonly sentAt: string | null;
559 /** True once a browser opened the page or the link was spent. */
560 readonly opened: boolean;
561 /** ISO of the first browser open; null while unopened, or spent before opens were noted. */
562 readonly openedAt: string | null;
563 /** ISO of a person's last action there; null until they signed in. */
564 readonly lastSeenAt: string | null;
565 }
566
567 /** Null while the forge is still being made or did not answer: nothing is claimed unknown. */
568 export function seenOf(r: Pick<ClientRow, "made" | "claimed" | "sentAt" | "link" | "lastActivityAt">): Seen | null {
569 if (!r.made || r.claimed === null || r.link === null) return null;
570 const openedAt = r.link.openedAt ?? null;
571 return { sentAt: r.sentAt, opened: openedAt !== null || r.link.usedAt != null || r.link.state === "used", openedAt, lastSeenAt: r.claimed ? r.lastActivityAt : null };
572 }
573
574 /** The one line as parts to join with " · ": the words, and the instant to say beside them. */
575 export function seenParts(s: Seen): { words: string; at: string | null }[] {
576 return [
577 ...(s.sentAt === null ? [] : [{ words: "sent", at: s.sentAt }]),
578 s.opened ? { words: s.openedAt === null ? "opened (time not noted)" : "opened", at: s.openedAt } : { words: "not opened yet", at: null },
579 ...(s.lastSeenAt === null ? [] : [{ words: "last seen", at: s.lastSeenAt }]),
580 ];
581 }
582
549583 /** Rows that need the owner first, by reason; then by last activity, newest first. */
550584 export function orderRows(rows: readonly Omit<ClientRow, "attention" | "stage" | "archive">[], now: number): ClientRow[] {
551585 const tier = (a: Attention | null) => (a === null ? ATTENTION_ORDER.length : ATTENTION_ORDER.indexOf(a));
src/tui/screens/forges.ts +10 −4
@@ -6,7 +6,7 @@
66
77 import type { Ctx, Screen } from "../app/app.ts";
88 import { binding } from "../app/keys.ts";
9 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
9 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, seenOf, seenParts, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
1010 import { useLine } from "../../spawn/usage.ts";
1111 import { timeAgo } from "../../web/ui.ts";
1212 import { card } from "../ui/widgets.ts";
@@ -26,16 +26,22 @@ import type { Session } from "../session.ts";
2626 import { appLinkSummary, appLinkWords } from "../../spawn/app_links.ts";
2727
2828 /** [name, "Not reporting · for Maria · Claimed · 3 apps running"] per row; an empty line when none. */
29 export function forgeLines(rows: readonly ClientRow[]): [string, string][] {
29 export function forgeLines(rows: readonly ClientRow[], sender = false): [string, string][] {

seenLine(r, sender) is computed four times in one array literal; compute it once above. Not blocking.

3030 if (rows.length === 0) return [["", "You have not sent a forge yet"]];
3131 return rows.flatMap((r): [string, string][] => [[
3232 r.name,
33 [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, crewHeldWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), r.stage?.words ?? null, r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.made ? (r.lastActivityAt === null ? "no person has done anything here" : `a person last did something ${timeAgo(r.lastActivityAt)}`) : null, claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`]
33 [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, crewHeldWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link), runningWords(r), seenLine(r, sender) !== null && r.stage?.key !== "tell" && r.stage?.resend !== true ? null : r.stage?.words ?? null, seenLine(r, sender), r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, r.made && seenLine(r, sender) === null ? (r.lastActivityAt === null ? "no person has done anything here" : `a person last did something ${timeAgo(r.lastActivityAt)}`) : null, claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "no heartbeat yet" : `heartbeat ${timeAgo(r.lastHeartbeatAt)}`]
3434 .filter((m): m is string => m !== null)
3535 .join(" · "),
3636 ], ...firstScreenLines(r), ...appLinkLines(r), ...addressLines(r)]);
3737 }
3838
39 /** "sent 3d ago · opened 1d ago · last seen 2h ago", as /forges says it; for an admin only. */
40 function seenLine(r: ClientRow, sender: boolean): string | null {
41 const seen = sender ? seenOf(r) : null;
42 return seen === null ? null : seenParts(seen).map((p) => (p.at === null ? p.words : `${p.words} ${timeAgo(p.at)}`)).join(" · ");
43 }
44
3945 /** "link open", "link ended (undo with u)": what the sender can do about the link, as /forges shows it. */
4046 function linkWords(link: LinkInfo | null): string | null {
4147 if (link === null || link.state === "used") return null;
@@ -81,7 +87,7 @@ export function ownCodePicks(app: App, rows: readonly ClientRow[]): { id: string
8187 }
8288
8389 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session): Screen {
84 const lines = forgeLines(rows);
90 const lines = forgeLines(rows, session?.user?.isAdmin === true);
8591 // Stop and Remove are the page's buttons, through the same actions (`spawn/manage.ts`).
8692 const choose = (title: string, act: (name: string) => void): void => {
8793 const items = rows.filter((r) => r.made).map((r) => ({ id: r.name, label: r.name, hint: r.awake === true ? "awake" : "asleep" }));
src/web/pages/claim.ts +3
@@ -57,6 +57,8 @@ import {
5757 unburnClaim,
5858 type ClaimState,
5959 type Spawned,
60 isBrowserOpen,
61 noteOpened,
6062 } from "../../spawn/claim.ts";
6163 import { pageHead, CAME_FROM_ELSEWHERE } from "../chrome.ts";
6264 import { field, readForm } from "../form.ts";
@@ -323,6 +325,7 @@ async function fragmentPage(ctx: Ctx, own: boolean): Promise<Response> {
323325 // The forge has one link at a time, so its state says nothing about any
324326 // particular code: a stale or made-up code only ever meets "unknown" on the POST.
325327 const link = linkOf(ctx.app.db);
328 if (!own && link?.state === "open" && isBrowserOpen(ctx.request)) noteOpened(ctx.app.db);
326329 if (link !== null && link.state !== "open")
327330 return dead(
328331 ctx,
src/web/pages/forges.ts +13 −3
@@ -9,7 +9,7 @@
99 import type { Ctx } from "../../http/context.ts";
1010 import { claimsBill } from "../../actions/forge_bill.ts";
1111 import { billRow } from "./bills.ts";
12 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, memoryOf, servedRows, dropServed, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
12 import { ATTENTION_WORDS, firstScreenOf, CLAIM_WORDS, claimState, memoryOf, seenOf, seenParts, type Seen, servedRows, dropServed, creditWords, crewHeldWords, graceWords, runningWords, spendWords, monthWords, type ClientRow } from "../../spawn/clients.ts";
1313 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
1414 import { notFoundPage, pageHead } from "../chrome.ts";
1515 import { html, type Html } from "../html.ts";
@@ -66,8 +66,15 @@ function spendNote(r: ClientRow): Html | null {
6666 : html`<span data-spend="ok">${s.words}</span>`;
6767 }
6868
69 /** "sent 3d ago · opened 1d ago · last seen 2h ago": the one line for where the link stands. */
70 function seenWords(seen: Seen): Html {
71 const parts = seenParts(seen).map((p) => html`${p.words}${p.at === null ? null : html` ${time(p.at)}`}`);
72 return html`<span data-seen data-opened="${seen.opened ? "yes" : "no"}">${parts.map((p, i) => (i === 0 ? p : html` · ${p}`))}</span>`;
73 }
74
6975 export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false): Html {
7076 const state = claimState(r);
77 const seen = seenOf(r);
7178 const meta = [
7279 r.for === null ? null : html`for ${r.for}`,
7380 r.apps.length === 0 ? null : html`${r.apps.join(", ")}`,
@@ -84,10 +91,13 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
8491 monthNote(r),
8592 creditWords(r) === null ? null : html`<span data-credit>${creditWords(r)}</span>`,
8693 graceWords(r) === null ? null : html`<span data-grace>${graceWords(r)}</span>`,
87 r.stage === null
94 // With the seen line, the stage and the activity words would say the same thing twice;
95 // only what it does not say (a resend, the last tell) keeps its own words.
96 r.stage === null || (seen !== null && r.stage.key !== "tell" && !r.stage.resend)
8897 ? null
8998 : html`<span data-stage="${r.stage.key}"${r.stage.resend ? html` data-resend` : null}>${r.stage.words}${r.stage.at === null ? null : html` ${time(r.stage.at)}`}</span>`,
90 r.made ? (r.lastActivityAt === null ? html`<span data-activity>no one has done anything here yet</span>` : html`<span data-activity>a person last did something ${time(r.lastActivityAt)}</span>`) : null,
99 seen === null ? null : seenWords(seen),
100 r.made && seen === null ? (r.lastActivityAt === null ? html`<span data-activity>no one has done anything here yet</span>` : html`<span data-activity>a person last did something ${time(r.lastActivityAt)}</span>`) : null,
91101 claimedWords(r) === null ? null : html`<span data-claimed-by>${claimedWords(r)}</span>`,
92102 keepWords(r) === null ? null : html`<span data-keep>${keepWords(r)}</span>`,
93103 r.noticedAt === null || r.noticedAt === undefined ? null : html`<span data-noticed>owner told ${time(r.noticedAt)}</span>`,
test/client-states.test.ts +3 −1
@@ -67,7 +67,9 @@ describe("client states", () => {
6767
6868 test("the page says the same words and offers resend only when stale", () => {
6969 const fresh = String(forgeRow(stage(), NOW));
70 expect(fresh).toContain(`>${STAGE_WORDS.sent} `);
70 // The stage's "Sent" is folded into the one seen line (#12694), not said twice.
71 expect(fresh).toContain("data-seen");
72 expect(fresh).not.toContain(`>${STAGE_WORDS.sent} `);
7173 expect(fresh).not.toContain("Resend");
7274 const stale = String(forgeRow(stage({ sentAt: ago(4 * DAY) }), NOW));
7375 expect(stale).toContain(STALE_WORDS);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs