Skip to content

Commit c98db61

Browse files
authored
Merge pull request #1508 from i098/fm/cf-commute-brief
feat(imessage): commute brief card when moving toward home or office
2 parents cd36b54 + a598117 commit c98db61

7 files changed

Lines changed: 363 additions & 1 deletion

File tree

‎apps/imessage/bridge.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import { brief, deskLog, heartbeat, keyOf, ownership, permanent, probeKit, Queue
5454
import { openThreadSenders } from "./sender-log.ts";
5555
import { listenFrom, transcribe } from "./transcribe.ts";
5656
import { describePlaces, digest, insideAny, isUrgent, loadHeld, loadPlaces, parseQuietCommand, PLACE_RADIUS_M, saveHeld, savePlaces, type HeldText, type LocationPoint, type QuietCommand } from "./quiet-places.ts";
57+
import { commuteBrief, destinationPlaces, detectTrip, loadCommute, renderBrief, saveCommute } from "./commute.ts";
5758

5859

5960
let stopping = false;
@@ -127,6 +128,7 @@ const TYPING_MAX_MS = 300_000; // the desk typing bubble never outlives a reques
127128
const RETRY_MS = Number(env.FM_IMESSAGE_RETRY_MS || 1000); // the first retry step of the outbox and the downloads
128129
const REACT_MAX_MS = Number(env.FM_IMESSAGE_REACT_MAX_MS || 120_000); // a tapback older than this is dropped, not retried
129130
const HELD_CHECK_MS = env.FM_IMESSAGE_TEST === "1" && env.FM_IMESSAGE_TEST_HELD_CHECK_MS ? Number(env.FM_IMESSAGE_TEST_HELD_CHECK_MS) : 60_000; // how often a held set re-checks the location
131+
const COMMUTE_POLL_MS = Number(env.FM_IMESSAGE_COMMUTE_POLL_MS || 60_000); // how often the commute check samples the location; 0 turns it off
130132
const LOCATION_MAX_AGE_MS = 300_000; // an older Find My fix decides neither a hold nor a release
131133
// systemd's StateDirectory= sets STATE_DIRECTORY; the directory is private to the account.
132134
const STATE = env.STATE_DIRECTORY || `${env.HOME}/.local/state/fm-imessage`;
@@ -1895,6 +1897,60 @@ async function checkHeld() {
18951897
queueQuietReply(dest, digest(held));
18961898
trace(dest.id, "quiet-digest");
18971899
}
1900+
// Commute brief: while a place named "home" or "office" exists, each poll samples the location once. A fresh
1901+
// fix meaningfully closer to one than the stored fix starts a trip toward it; the card then goes out once per
1902+
// trip, and the trip clears on arrival inside either destination. The card lists the open decisions and the
1903+
// finished work since the last card, from the firstmate home's status files (commute.ts). Location keeps only
1904+
// the last fix, in memory here and in state/commute.json; nothing else of the fixes persists.
1905+
let commuting = false;
1906+
async function pollCommute() {
1907+
if (commuting || stopping) return;
1908+
commuting = true;
1909+
try {
1910+
const places = destinationPlaces(loadPlaces(STATE));
1911+
if (!places.length) return;
1912+
const loc = await locationNow(true); // a departure must not wait out the arrival cache
1913+
if (!loc) return;
1914+
const st = loadCommute(STATE);
1915+
const fix = { latitude: loc.latitude, longitude: loc.longitude, at: Math.floor(Date.now() / 1000), ...(Number.isFinite(loc.accuracy) ? { accuracy: loc.accuracy } : {}) };
1916+
if (st.trip) {
1917+
if (insideAny(places, loc)) {
1918+
st.trip = undefined; // arrived: the trip ends, so the next trip can get its own card
1919+
st.fix = fix;
1920+
saveCommute(STATE, st);
1921+
return;
1922+
}
1923+
if (st.trip.sentAt) return; // one card per trip, already out
1924+
// The card is due but not out yet; fall through to send it.
1925+
} else {
1926+
if (!st.fix || Date.now() - st.fix.at * 1000 > 30 * 60_000) {
1927+
st.fix = fix; // the first fix, or one too old to judge movement from, only starts the next comparison
1928+
saveCommute(STATE, st);
1929+
return;
1930+
}
1931+
const place = detectTrip(st.fix, fix, places);
1932+
st.fix = fix;
1933+
if (!place) {
1934+
saveCommute(STATE, st);
1935+
return;
1936+
}
1937+
st.trip = { place: place.name, sentAt: 0 };
1938+
}
1939+
const dest = proactiveRef ?? latestRef;
1940+
if (!dest) { saveCommute(STATE, st); return; } // no chat yet; the trip stays due for the next poll
1941+
const text = renderBrief(commuteBrief(FM_HOME, st.lastBriefAt ?? 0));
1942+
st.trip!.sentAt = Math.floor(Date.now() / 1000);
1943+
st.lastBriefAt = Math.floor(Date.now() / 1000);
1944+
saveCommute(STATE, st);
1945+
queueQuietReply(dest, text);
1946+
trace(dest.id, "commute-brief");
1947+
} catch (e) {
1948+
log("commute brief")(e);
1949+
} finally {
1950+
commuting = false;
1951+
}
1952+
}
1953+
if (COMMUTE_POLL_MS > 0) setInterval(() => void pollCommute(), COMMUTE_POLL_MS);
18981954
function appendHeld(text: string, ref: Ref, placeName: string) {
18991955
const held = loadHeld(STATE);
19001956
held.push({ id: ref.id, at: Date.now(), text, place: placeName });

‎apps/imessage/commute.test.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { afterAll, expect, test } from "bun:test";
5+
import { commuteBrief, destinationPlaces, detectTrip, loadCommute, renderBrief, saveCommute } from "./commute.ts";
6+
7+
const dir = mkdtempSync(join(tmpdir(), "commute-"));
8+
afterAll(() => rmSync(dir, { recursive: true, force: true }));
9+
10+
const HOME = { name: "home", lat: 1.5, lon: 2.5, radiusM: 100 };
11+
const OFFICE = { name: "office", lat: 1.8, lon: 2.8, radiusM: 100 };
12+
const OTHER = { name: "gym", lat: 5, lon: 5, radiusM: 100 };
13+
14+
test("destinationPlaces keeps only places named home or office", () => {
15+
expect(destinationPlaces([HOME, OFFICE, OTHER])).toEqual([HOME, OFFICE]);
16+
expect(destinationPlaces([OTHER])).toEqual([]);
17+
expect(destinationPlaces([{ ...HOME, name: "Home" }, { ...OFFICE, name: "OFFICE" }])).toEqual([
18+
{ ...HOME, name: "Home" },
19+
{ ...OFFICE, name: "OFFICE" },
20+
]);
21+
});
22+
23+
test("detectTrip needs a meaningfully closer fix outside the place", () => {
24+
const far = { latitude: 41, longitude: -74 };
25+
const closer = { latitude: 40.9, longitude: -73.9 };
26+
expect(detectTrip(far, closer, [HOME])).toEqual(HOME);
27+
// A few meters closer is jitter, not a trip.
28+
expect(detectTrip({ latitude: 41, longitude: -74 }, { latitude: 40.9999, longitude: -73.9999 }, [HOME])).toBeUndefined();
29+
// The margin grows with the fixes' reported error.
30+
expect(detectTrip({ latitude: 41, longitude: -74, accuracy: 200 }, { latitude: 40.9999, longitude: -73.9999, accuracy: 200 }, [HOME])).toBeUndefined();
31+
// Moving away is not a trip.
32+
expect(detectTrip(closer, far, [HOME])).toBeUndefined();
33+
// Already inside the place is not a new trip.
34+
expect(detectTrip({ latitude: 40.9, longitude: -73.9 }, { latitude: 1.5001, longitude: 2.5001 }, [HOME])).toBeUndefined();
35+
});
36+
37+
test("detectTrip picks the destination gained on most", () => {
38+
const prev = { latitude: 0, longitude: 0 };
39+
const now = { latitude: 1, longitude: 0 }; // 111 km east
40+
const home = { name: "home", lat: 2, lon: 0, radiusM: 100 }; // 111 km closer
41+
const office = { name: "office", lat: 5, lon: 5, radiusM: 100 }; // ~74 km closer
42+
expect(detectTrip(prev, now, [home, office])).toEqual(home);
43+
});
44+
45+
test("the commute state persists and a corrupt file reads empty", () => {
46+
expect(loadCommute(dir)).toEqual({});
47+
const state = { fix: { latitude: 1, longitude: 2, at: 3, accuracy: 5 }, trip: { place: "home", sentAt: 0 }, lastBriefAt: 5 };
48+
saveCommute(dir, state);
49+
expect(loadCommute(dir)).toEqual(state);
50+
writeFileSync(join(dir, "commute.json"), "not json");
51+
expect(loadCommute(dir)).toEqual({});
52+
});
53+
54+
function homeWith(contents: Record<string, string>): string {
55+
const home = mkdtempSync(join(dir, "home-"));
56+
mkdirSync(join(home, "state"));
57+
for (const [name, body] of Object.entries(contents)) writeFileSync(join(home, "state", name), body);
58+
return home;
59+
}
60+
61+
test("commuteBrief lists open decisions and finished work since the last card", () => {
62+
const home = homeWith({
63+
"alpha.status": "done [at=101]: PR https://github.com/i098/Crewship/pull/1507\n",
64+
"beta.status": "needs-decision [at=200]: which option for the fallback file=/home/secret/path.txt\n",
65+
"gamma.status": "done [at=50]: older work, before the last card\n",
66+
"delta.status": "needs-decision [at=150]: first ask\nresolved [at=151]: answered\n",
67+
});
68+
const b = commuteBrief(home, 100);
69+
expect(b.finished).toEqual(["alpha: PR https://github.com/i098/Crewship/pull/1507"]);
70+
// gamma is before `since`; delta resolved, so it is not open.
71+
expect(b.decisions).toEqual(["beta: needs-decision: which option for the fallback file="]);
72+
expect(b.decisions[0]).not.toContain("/home/secret");
73+
});
74+
75+
test("a keyed decision stays open until its own resolved line", () => {
76+
const home = homeWith({
77+
"one.status": "needs-decision [at=1] [key=alpha]: pick a\nneeds-decision [at=2] [key=beta]: pick b\nresolved [key=alpha] [at=3]: answered\n",
78+
});
79+
const b = commuteBrief(home, 0);
80+
expect(b.decisions).toEqual(["one: needs-decision: pick b"]);
81+
});
82+
83+
test("finished work sorts newest first and caps the card", () => {
84+
const home = homeWith({
85+
"a.status": "done [at=1]: first\n",
86+
"b.status": "done [at=2]: second\n",
87+
"c.status": "done [at=3]: third\n",
88+
});
89+
const b = commuteBrief(home, 0);
90+
expect(b.finished).toEqual([
91+
"c: third",
92+
"b: second",
93+
"a: first",
94+
]);
95+
});
96+
97+
test("commuteBrief tolerates a missing home and a corrupt status file", () => {
98+
expect(commuteBrief(join(dir, "nope"), 0)).toEqual({ decisions: [], finished: [] });
99+
const home = homeWith({ "bad.status": "\u0000not utf8" });
100+
expect(commuteBrief(home, 0)).toEqual({ decisions: [], finished: [] });
101+
});
102+
103+
test("renderBrief shapes one card with both sections", () => {
104+
const out = renderBrief({ decisions: ["beta: needs-decision: which option"], finished: ["alpha: PR https://github.com/i098/Crewship/pull/1507"] });
105+
expect(out).toContain("Commute brief");
106+
expect(out).toContain("Open decisions:");
107+
expect(out).toContain("- beta: needs-decision: which option");
108+
expect(out).toContain("Finished work since the last brief:");
109+
expect(out).toContain("- alpha: PR https://github.com/i098/Crewship/pull/1507");
110+
const empty = renderBrief({ decisions: [], finished: [] });
111+
expect(empty).toContain("- none");
112+
});

‎apps/imessage/commute.ts‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Commute brief: when the shared location starts moving toward a tagged home or office, the bridge sends
2+
// one card with the open decisions and the finished work since the last card (bridge.ts). Location is read
3+
// and compared here and never printed; only the last fix needed for direction, the in-flight trip, and the
4+
// last-card time persist, in the private state directory. The card text comes from the firstmate home's
5+
// status files, which list the open decisions and the finished work per task; cleanText strips anything
6+
// private (paths, key/corr tokens, task prefixes) before it can leave the host.
7+
import { readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8+
import { cleanText } from "./clean.ts";
9+
import { metersBetween, type LocationPoint, type QuietPlace } from "./quiet-places.ts";
10+
11+
export type CommuteState = {
12+
fix?: LocationPoint & { at: number; accuracy?: number }; // the last sample, replaced on every poll
13+
trip?: { place: string; sentAt: number }; // sentAt 0 means detected but not yet out
14+
lastBriefAt?: number; // epoch seconds of the last card, to bound "finished work since"
15+
};
16+
17+
export function loadCommute(dir: string): CommuteState {
18+
try {
19+
const parsed: unknown = JSON.parse(readFileSync(`${dir}/commute.json`, "utf8"));
20+
if (!parsed || typeof parsed !== "object") return {};
21+
const s = parsed as Record<string, unknown>;
22+
const out: CommuteState = {};
23+
const f = s.fix as Partial<LocationPoint> & { at?: unknown; accuracy?: unknown } | undefined;
24+
if (f && typeof f === "object" && Number.isFinite(f.latitude) && Number.isFinite(f.longitude) && Number.isFinite(f.at)) {
25+
out.fix = { latitude: f.latitude as number, longitude: f.longitude as number, at: f.at as number };
26+
if (Number.isFinite(f.accuracy)) out.fix.accuracy = f.accuracy as number;
27+
}
28+
const t = s.trip as { place?: unknown; sentAt?: unknown } | undefined;
29+
if (t && typeof t === "object" && typeof t.place === "string" && Number.isFinite(t.sentAt)) {
30+
out.trip = { place: t.place, sentAt: t.sentAt as number };
31+
}
32+
if (Number.isFinite(s.lastBriefAt)) out.lastBriefAt = s.lastBriefAt as number;
33+
return out;
34+
} catch {
35+
return {};
36+
}
37+
}
38+
39+
export function saveCommute(dir: string, state: CommuteState) {
40+
writeFileSync(`${dir}/commute.json.tmp`, JSON.stringify(state), { mode: 0o600 });
41+
renameSync(`${dir}/commute.json.tmp`, `${dir}/commute.json`);
42+
}
43+
44+
// A commute destination is a tagged place named "home" or "office"; any other name is not a destination.
45+
export function destinationPlaces(places: readonly QuietPlace[]): QuietPlace[] {
46+
return places.filter((p) => p.name.toLowerCase() === "home" || p.name.toLowerCase() === "office");
47+
}
48+
49+
const TRIP_MARGIN_M = 50; // the smallest gain that counts as movement, before the fixes' own error
50+
51+
// A trip starts when a fresh fix is meaningfully closer to a destination than the previous fix and outside it.
52+
// The margin covers the combined error of the two fixes, so standing still cannot start a trip.
53+
// Among several destinations, the one gained on most wins; it also carries the trip's place name.
54+
export function detectTrip(prev: LocationPoint, now: LocationPoint, places: readonly QuietPlace[]): QuietPlace | undefined {
55+
const margin = TRIP_MARGIN_M + (prev.accuracy ?? 0) + (now.accuracy ?? 0);
56+
let best: { place: QuietPlace; gainM: number } | undefined;
57+
for (const p of places) {
58+
const target = { latitude: p.lat, longitude: p.lon };
59+
const gainM = metersBetween(prev, target) - metersBetween(now, target);
60+
if (gainM <= margin || metersBetween(now, target) <= p.radiusM) continue;
61+
if (!best || gainM > best.gainM) best = { place: p, gainM };
62+
}
63+
return best?.place;
64+
}
65+
66+
const STATUS_DIR = "state";
67+
const DONE_RE = /^done \[at=(\d+)\]/;
68+
const STATE_RE = /^(needs-decision|blocked|resolved)\b/;
69+
const KEY_RE = /\[key=([^\]]+)\]/;
70+
const DETAIL_RE = /\]:\s(.*)$/;
71+
72+
// The card text parts from a firstmate home: the still-open decisions (a decisions line stays open until a
73+
// `resolved` line with the same key, or, keyless, until any `resolved` line) and the done lines newer than
74+
// the last card. A missing or unreadable home and status file contribute nothing.
75+
export function commuteBrief(home: string, since: number): { decisions: string[]; finished: string[] } {
76+
const decisions: string[] = [];
77+
const finished: { at: number; text: string }[] = [];
78+
let names: string[];
79+
try {
80+
names = readdirSync(`${home}/${STATUS_DIR}`).sort();
81+
} catch {
82+
return { decisions, finished };
83+
}
84+
for (const name of names) {
85+
if (!name.endsWith(".status")) continue;
86+
const id = name.slice(0, -7);
87+
let lines: string[];
88+
try {
89+
lines = readFileSync(`${home}/${STATUS_DIR}/${name}`, "utf8").split("\n");
90+
} catch {
91+
continue;
92+
}
93+
const open = new Map<string, { word: string; text: string }>();
94+
for (const raw of lines) {
95+
const line = raw.trim();
96+
if (!line) continue;
97+
const detail = DETAIL_RE.exec(line)?.[1] ?? "";
98+
const done = DONE_RE.exec(line);
99+
if (done && Number(done[1]!) > since) {
100+
const text = cleanText(detail);
101+
if (text) finished.push({ at: Number(done[1]!), text: `${id}: ${text}` });
102+
continue;
103+
}
104+
const word = STATE_RE.exec(line)?.[1];
105+
if (!word) continue;
106+
const key = KEY_RE.exec(line)?.[1];
107+
if (word === "resolved") {
108+
open.delete(key ?? `${id}:keyless`);
109+
} else {
110+
const text = cleanText(detail);
111+
if (text) open.set(key ?? `${id}:keyless`, { word, text: `${id}: ${word}: ${text}` });
112+
}
113+
}
114+
for (const { text } of open.values()) decisions.push(text);
115+
}
116+
const done = finished.sort((a, b) => b.at - a.at).slice(0, 10).map((f) => f.text);
117+
if (finished.length > 10) done.push(`(+${finished.length - 10} more)`);
118+
return { decisions, finished: done };
119+
}
120+
121+
export function renderBrief(b: { decisions: string[]; finished: string[] }): string {
122+
const lines = ["Commute brief", "Open decisions:"];
123+
if (!b.decisions.length) lines.push("- none");
124+
else for (const d of b.decisions) lines.push(`- ${d}`);
125+
lines.push("Finished work since the last brief:");
126+
if (!b.finished.length) lines.push("- none");
127+
else for (const f of b.finished) lines.push(`- ${f}`);
128+
return lines.join("\n");
129+
}

‎blueprint/ansible/tasks/imessage.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
dest: "{{ crewship_imessage_dir }}/stage/{{ item }}"
2929
mode: "0644"
3030
remote_src: true
31-
loop: [bridge.ts, bluebubbles.ts, cards.ts, clean.ts, desk.ts, desk-actions.ts, desk-claim.ts, desk-files.ts, desk-deadline.ts, desk-delegate.ts, desk-deny.ts, desk-helper.ts, desk-pane.ts, desk-scripts.ts, desk-session.ts, desk-session-turn.ts, desk-tools.yml, dispatch-policy.ts, front.ts, herdr-watch.ts, image.ts, inception-desk.ts, instagram-webhook.ts, memory.ts, outbox.ts, ownership.ts, quiet-places.ts, relay.ts, standby.ts, reply-target.ts, selfheal.ts, sender-log.ts, ste.ts, stuck-watch.ts, subagent.ts, tokenlog.ts, transcribe.ts, webchat.ts, zoom.ts]
31+
loop: [bridge.ts, bluebubbles.ts, cards.ts, clean.ts, commute.ts, desk.ts, desk-actions.ts, desk-claim.ts, desk-files.ts, desk-deadline.ts, desk-delegate.ts, desk-deny.ts, desk-helper.ts, desk-pane.ts, desk-scripts.ts, desk-session.ts, desk-session-turn.ts, desk-tools.yml, dispatch-policy.ts, front.ts, herdr-watch.ts, image.ts, inception-desk.ts, instagram-webhook.ts, memory.ts, outbox.ts, ownership.ts, quiet-places.ts, relay.ts, standby.ts, reply-target.ts, selfheal.ts, sender-log.ts, ste.ts, stuck-watch.ts, subagent.ts, tokenlog.ts, transcribe.ts, webchat.ts, zoom.ts]
3232
notify: deploy fm-imessage
3333

3434
- name: Install the STE style files for the bridge

‎changelog.d/1478.added.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added a commute brief: when the shared location starts moving toward a tagged `home` or `office`, the bridge sends one card with the open decisions and the finished work since the last card, once per trip.

‎docs/imessage.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,16 @@ Every 60 seconds while texts are held, the bridge re-checks the location. When y
892892

893893
Privacy: the raw Find My fix is read only to compare it with the places and is then discarded. Only the tagged places (name, center, radius) and the held texts persist, both in the private state directory on the host. Nothing leaves the host.
894894

895+
## Commute brief
896+
897+
When the shared location starts moving toward a place named `home` or `office`, the bridge sends one card with the open decisions and the finished work since the last card.
898+
One card per trip: a card goes out once, and the next card waits until that trip ends at the place.
899+
900+
- Tag home or office with the quiet-place commands above, naming the place exactly `home` or `office`. Other place names are not destinations.
901+
- Every 60 seconds while a home or office exists, the bridge re-checks the location (`FM_IMESSAGE_COMMUTE_POLL_MS` changes the interval; `0` turns it off).
902+
- Open decisions come from the `needs-decision` and `blocked` state lines of `$FM_HOME/state/*.status`; finished work is the `done` lines newer than the last card. Absolute paths are dropped from the card text.
903+
- Privacy: the raw Find My fix is kept only until the next sample replaces it. The last fix, the in-flight trip, and the last-card time are the only records that persist, in `state/commute.json` on the host. Nothing leaves the host except the card text.
904+
895905
## Enable it
896906

897907
The iMessage bridge and optional card tunnel use `/bin/sh` to source `~/super.env` and export its assignments before starting.

0 commit comments

Comments
 (0)