Rewrite the Timer app

This commit is contained in:
James Babcock committed 2026-09-04 02:23:58 -07:00
1 parent 99a8b97169
commit f601a62c75
14 files changed
+2990 -826

No files matched your search

@@ -388,11 +388,11 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen
if (statusBarNotification == null || statusBarNotification.getNotification() == null) {
return false;
}
// The dashboard's own persistent foreground notification is noise, but
// Timer expiry notifications deliberately flow through the same mirror
// and modal path as notifications from other Android apps.
if (service.getPackageName().equals(statusBarNotification.getPackageName())
&& !FaceclawTimerNotifications.isTimerNotification(statusBarNotification)) {
// Our own notifications stay out of the mirror: the foreground-service
// one is noise, and the Timers app rings on the glasses itself (its
// phone notification is for the phone), so mirroring it would stack a
// notification modal over the ringing screen.
if (service.getPackageName().equals(statusBarNotification.getPackageName())) {
return false;
}
Notification notification = statusBarNotification.getNotification();
@@ -12,12 +12,18 @@ import android.os.Build;
import com.tns.NativeScriptActivity;
/** Android alarm + notification bridge used by the on-glasses Timer app. */
/**
* Android alarm + notification bridge used by the on-glasses Timers app, for
* countdown timers and alarms alike: one AlarmManager alarm per item posts a
* phone notification at the moment of expiry, even when the app process is
* asleep or gone.
*/
public final class FaceclawTimerNotifications {
public static final String CHANNEL_ID = "faceclaw-timers";
static final String ACTION_EXPIRE = "com.faceclaw.app.action.TIMER_EXPIRE";
static final String EXTRA_TIMER_ID = "timerId";
static final String EXTRA_DURATION_LABEL = "durationLabel";
static final String EXTRA_TITLE = "title";
static final String EXTRA_TEXT = "text";
private static final String TIMER_TAG_PREFIX = "faceclaw-timer:";
private static final String PREFS_NAME = "faceclaw-timer-notifications";
@@ -26,10 +32,10 @@ public final class FaceclawTimerNotifications {
private FaceclawTimerNotifications() {}
/**
* Schedule an Android alarm as the durable path. The worker also keeps a
* Schedule an Android alarm as the durable path. The engine also keeps a
* normal JS timeout for prompt delivery while the process is awake.
*/
public static void schedule(Context context, long timerId, long triggerAtMs, String durationLabel) {
public static void schedule(Context context, long timerId, long triggerAtMs, String title, String text) {
Context appContext = context.getApplicationContext();
preferences(appContext).edit().putBoolean(firedKey(timerId), false).apply();
@@ -37,7 +43,7 @@ public final class FaceclawTimerNotifications {
if (manager == null) {
return;
}
PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, durationLabel);
PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, title, text);
long triggerAt = Math.max(System.currentTimeMillis(), triggerAtMs);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !manager.canScheduleExactAlarms()) {
@@ -58,7 +64,7 @@ public final class FaceclawTimerNotifications {
Context appContext = context.getApplicationContext();
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(expiryPendingIntent(appContext, timerId, ""));
alarmManager.cancel(expiryPendingIntent(appContext, timerId, "", ""));
}
NotificationManager notificationManager =
(NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
@@ -68,17 +74,17 @@ public final class FaceclawTimerNotifications {
preferences(appContext).edit().remove(firedKey(timerId)).apply();
}
/** Worker-timeout path. Cancels the backup alarm and posts at most once. */
public static void fireNow(Context context, long timerId, String durationLabel) {
/** Engine-timeout path. Cancels the backup alarm and posts at most once. */
public static void fireNow(Context context, long timerId, String title, String text) {
Context appContext = context.getApplicationContext();
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(expiryPendingIntent(appContext, timerId, durationLabel));
alarmManager.cancel(expiryPendingIntent(appContext, timerId, title, text));
}
showExpiredOnce(appContext, timerId, durationLabel);
showExpiredOnce(appContext, timerId, title, text);
}
static synchronized void showExpiredOnce(Context context, long timerId, String durationLabel) {
static synchronized void showExpiredOnce(Context context, long timerId, String title, String text) {
SharedPreferences preferences = preferences(context);
String firedKey = firedKey(timerId);
if (preferences.getBoolean(firedKey, false)) {
@@ -103,10 +109,11 @@ public final class FaceclawTimerNotifications {
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? new Notification.Builder(context, CHANNEL_ID)
: new Notification.Builder(context);
String label = durationLabel == null || durationLabel.trim().isEmpty() ? "Timer" : durationLabel + " timer";
String contentTitle = title == null || title.trim().isEmpty() ? "Timer finished" : title;
String contentText = text == null || text.trim().isEmpty() ? "Time's up" : text;
Notification notification = builder
.setContentTitle("Timer finished")
.setContentText(label + " is up")
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(context.getApplicationInfo().icon)
.setContentIntent(contentIntent)
.setCategory(Notification.CATEGORY_ALARM)
@@ -122,7 +129,7 @@ public final class FaceclawTimerNotifications {
}
}
/** Only Timer notifications from our own package should enter the mirror. */
/** Identifies this bridge's notifications among our own package's (see the listener service). */
public static boolean isTimerNotification(android.service.notification.StatusBarNotification item) {
if (item == null || item.getNotification() == null) {
return false;
@@ -156,12 +163,14 @@ public final class FaceclawTimerNotifications {
private static PendingIntent expiryPendingIntent(
Context context,
long timerId,
String durationLabel
String title,
String text
) {
Intent intent = new Intent(context, FaceclawTimerReceiver.class);
intent.setAction(ACTION_EXPIRE);
intent.putExtra(EXTRA_TIMER_ID, timerId);
intent.putExtra(EXTRA_DURATION_LABEL, durationLabel == null ? "" : durationLabel);
intent.putExtra(EXTRA_TITLE, title == null ? "" : title);
intent.putExtra(EXTRA_TEXT, text == null ? "" : text);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
@@ -4,7 +4,7 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/** Receives durable timer alarms even if the NativeScript worker is asleep. */
/** Receives durable timer/alarm expiries even if the NativeScript side is asleep. */
public class FaceclawTimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
@@ -15,7 +15,8 @@ public class FaceclawTimerReceiver extends BroadcastReceiver {
if (timerId == 0) {
return;
}
String durationLabel = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_DURATION_LABEL);
FaceclawTimerNotifications.showExpiredOnce(context, timerId, durationLabel);
String title = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TITLE);
String text = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TEXT);
FaceclawTimerNotifications.showExpiredOnce(context, timerId, title, text);
}
}
+3 -2
View File
@@ -7,11 +7,12 @@
* Long-press now opens the system context menu and tap-then-hold the app context menu (games keep long-press as a move while playing)
* Content beneath an open context menu is dimmed
* Add a keyboard-input button to the phone home screen
* Add a light sensor demo to the Developer app
* Move Calculator, Microphones, Nightscout, and Roam apps to Prototpyes folder by default
* Navigate app: Location indicator rotates based on the compass
* Navigate app: Add saved home/work and recent address settings
* Navigate app: Darken the map background color
* Add a light sensor demo to the Developer app
* Move Calculator, Microphones, Nightscout, and Roam apps to Prototpyes folder by default
* Timer app: Fully rewritten, with new better UI
## 0.6.4 - 2026-09-02
* Context menus are centered and include window title
+30 -10
View File
@@ -1,17 +1,37 @@
import { launchWorkerAppWindow, type AppDefinition } from "../app-definition";
import { type AppDefinition } from "../app-definition";
import { shell } from "../../ui/shell/shell";
import { registerTimerTools } from "../../assistant/timer-tools";
import { timerEngine, timersWakeSetting } from "./timer-engine";
import { createTimerAppWindow, startTimersTrayIcon, TIMER_SURFACE_ID, TIMER_WINDOW_ID } from "./timer-app";
/**
* Timers, stopwatch and alarms. The clock engine boots with the shell so
* timers and alarms fire (and the assistant's timer.* / alarm.* tools work)
* with no window open; launching only opens the view on it.
*/
const timerApp: AppDefinition = {
appId: "timer",
title: "Timer",
title: "Timers",
icon: "timer",
launch: (ctx) =>
launchWorkerAppWindow(ctx, {
createWorker: () => new Worker("./timer-app.worker"),
windowId: "timer:main",
title: "Timer",
iconLetter: "T",
icon: "timer",
}),
boot: (ctx) => {
timerEngine.boot({
playBuzzer: (payload) => ctx.actions.playBuzzerSequence(payload),
onRing: () => {
// Bring the ringing item on screen: focus the Timers window, then
// wake the display if it is off (a setting, since a wearer may
// prefer the phone notification alone while the glasses sleep).
void ctx
.launchApp("timer")
.then(() => {
if (timersWakeSetting.get() && !shell.isScreenOn()) shell.wake("window");
})
.catch((error) => console.error(`timers ring launch failed: ${error}`));
},
});
startTimersTrayIcon();
registerTimerTools((appId) => ctx.launchApp(appId));
},
launch: (ctx) => ctx.launchInProcessApp(TIMER_WINDOW_ID, TIMER_SURFACE_ID, createTimerAppWindow),
};
export default timerApp;
File diff suppressed because it is too large. Load diff
-751
View File
@@ -1,751 +0,0 @@
/**
* Timer app worker. The singleton window contains a stopwatch plus a list of
* independently scheduled countdown timers. Android AlarmManager owns the
* durable expiry path; worker timeouts keep the live UI prompt.
*/
import "@nativescript/core/globals";
import { type UiFont, GrayImage } from "../../graphics/image";
import { flattenPlanesWithDraws, planesFingerprint, type Plane } from "../../graphics/plane";
import { prepareFrameDraws } from "../../graphics/glyph-wire";
import { getFont } from "../../graphics/bdffont";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import * as frameTimings from "../../native/frame-timings";
import { getActiveDisplay } from "../../native/active-display";
import {
cancelTimerNotification,
fireTimerNotification,
scheduleTimerNotification,
} from "../../native/timer-notifications";
import { WindowMenu } from "../../ui/window-menu";
import type { WorkerAppMessage, WorkerAppReply } from "../../ui/shell/worker-window";
import type { ToolResult, ToolSpec } from "../../assistant/tool-registry";
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK, GESTURE_SCROLL, type InputEvent } from "../../ui/gestures";
import { clamp } from "../../util/numeric-util";
declare const global: any;
declare const com: any;
const RENDER_INTERVAL_MS = 100;
const TIMER_ROW_HEIGHT = 34;
const TIMER_LIST_TOP = 52;
const FOOTER_HEIGHT = 34;
const largeFont = getFont("terminus32");
const mediumFont = getFont("terminus24");
// Resolved per use so a font-setting change applies without a worker restart.
function smallFont(): UiFont {
return getDefaultSmallFont();
}
type TimerView = "stopwatch" | "timers" | "editor";
type TimerWindow = {
windowId: string;
surfaceId: string;
title: string;
viewportWidth: number;
viewportHeight: number;
foreground: boolean;
/** Whether this window is the shell's input target (pushed with each message). */
focused: boolean;
/** Tap-then-hold window menu; created on first open. */
menu: WindowMenu | null;
view: TimerView;
stopwatchAction: number;
timerSelection: number;
editorField: number;
editorHours: number;
editorMinutes: number;
editorSeconds: number;
editorMessage: string;
renderTimer: ReturnType<typeof setInterval> | null;
lastSubmittedFingerprint: string;
};
type CountdownTimer = {
id: number;
durationMs: number;
endAtMs: number;
expired: boolean;
expiryTimeout: ReturnType<typeof setTimeout> | null;
};
const TIMER_TOOLS: ToolSpec[] = [
{
name: "set_timer",
description:
"Start a new countdown timer. Give the duration as hours/minutes/seconds; at least one must be nonzero. Returns the timer's number and when it will finish.",
inputSchema: {
type: "object",
properties: {
hours: { type: "number", description: "Hours component of the duration (default 0)." },
minutes: { type: "number", description: "Minutes component of the duration (default 0)." },
seconds: { type: "number", description: "Seconds component of the duration (default 0)." },
},
additionalProperties: false,
},
availability: "open",
},
{
name: "list_timers",
description:
"List the countdown timers: each timer's number, its original duration, and the time remaining (or that it has finished).",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
availability: "open",
},
{
name: "cancel_timer",
description:
"Cancel a running countdown timer, or dismiss a finished one. Give the timer number from list_timers; it may be omitted when only one timer exists. Pass all=true to clear every timer.",
inputSchema: {
type: "object",
properties: {
timer: { type: "number", description: "1-based timer number, as shown in the timer list." },
all: { type: "boolean", description: "Clear all timers instead of a single one." },
},
additionalProperties: false,
},
availability: "open",
},
];
const windows = new Map<string, TimerWindow>();
const timers: CountdownTimer[] = [];
let screenOn = true;
let stopwatchAccumulatedMs = 0;
let stopwatchRunningSinceMs: number | null = null;
let nextTimerSerial = 1;
function post(message: WorkerAppReply): void {
global.postMessage(message);
}
// The host queues messages until this arrives: posts to a worker whose bundle
// is still evaluating can be silently dropped (see WorkerAppHost). Top-level
// evaluation is synchronous, so the handler below is installed before any
// queued message can be delivered.
post({ type: "worker-ready" });
global.onmessage = (event: { data: WorkerAppMessage }) => {
const message = event.data;
switch (message.type) {
case "open-window":
windows.set(message.windowId, {
windowId: message.windowId,
surfaceId: message.surfaceId,
title: message.title,
viewportWidth: message.viewport.width,
viewportHeight: message.viewport.height,
foreground: false,
focused: false,
menu: null,
view: "stopwatch",
stopwatchAction: 0,
timerSelection: 0,
editorField: 0,
editorHours: 0,
editorMinutes: 5,
editorSeconds: 0,
editorMessage: "",
renderTimer: null,
lastSubmittedFingerprint: "",
});
post({ type: "set-tools", windowId: message.windowId, tools: TIMER_TOOLS });
syncExpiredTimers();
break;
case "close-window": {
const window = windows.get(message.windowId);
if (window?.renderTimer) clearInterval(window.renderTimer);
windows.delete(message.windowId);
break;
}
case "input": {
const window = windows.get(message.windowId);
if (!window) {
frameTimings.finishFrame(message.frameId, "discarded: unknown timer window");
break;
}
window.focused = message.focused;
// Marks the main-thread -> worker hop, which is otherwise an
// unexplained gap inside the shell's handle-input span.
frameTimings.logFrame(message.frameId, `input received in ${message.windowId} worker`);
handleInput(window, message.event as InputEvent, message.frameId);
break;
}
case "render": {
const window = windows.get(message.windowId);
if (!window) break;
window.focused = message.focused;
renderAndSubmit(window, 0);
break;
}
case "foreground": {
const window = windows.get(message.windowId);
if (!window) break;
window.foreground = message.foreground;
window.focused = message.focused;
updateRenderTimer(window);
if (window.foreground) renderAndSubmit(window, 0);
break;
}
case "screen":
screenOn = message.on;
for (const window of windows.values()) updateRenderTimer(window);
break;
case "tool-call": {
let result: ToolResult;
try {
result = handleTimerTool(message.name, message.args);
} catch (error) {
result = { ok: false, error: String((error as Error)?.message ?? error) };
}
post({ type: "tool-result", callId: message.callId, result });
break;
}
}
};
// ---------------------------------------------------------------------------
// Tools
function handleTimerTool(name: string, args: any): ToolResult {
syncExpiredTimers();
switch (name) {
case "set_timer": {
const hours = toolDurationField(args?.hours, "hours");
const minutes = toolDurationField(args?.minutes, "minutes");
const seconds = toolDurationField(args?.seconds, "seconds");
const durationMs = Math.round(((hours * 60 + minutes) * 60 + seconds) * 1000);
if (durationMs <= 0) return { ok: false, error: "set_timer requires a duration longer than zero" };
addTimer(durationMs);
const timer = timers[timers.length - 1]!;
refreshWindowsAfterToolChange();
return {
ok: true,
content:
`Started a ${formatDuration(durationMs)} timer (timer ${timers.length}), ` +
`finishing at ${formatClock(timer.endAtMs)}.`,
};
}
case "list_timers": {
if (timers.length === 0) return { ok: true, content: "No timers are set." };
return { ok: true, content: timers.map(describeTimer).join("\n") };
}
case "cancel_timer": {
if (args?.all === true) {
if (timers.length === 0) return { ok: true, content: "No timers are set." };
const count = timers.length;
for (const timer of [...timers]) removeTimer(timer);
refreshWindowsAfterToolChange();
return { ok: true, content: count === 1 ? "Cleared the timer." : `Cleared ${count} timers.` };
}
if (timers.length === 0) return { ok: true, content: "No timers are set." };
let timer: CountdownTimer;
if (args?.timer === undefined || args?.timer === null) {
if (timers.length > 1) {
return {
ok: false,
error: `There are ${timers.length} timers; give the timer number.\n${timers.map(describeTimer).join("\n")}`,
};
}
timer = timers[0]!;
} else {
const index = Math.floor(Number(args.timer));
if (!Number.isFinite(index) || index < 1 || index > timers.length) {
return { ok: false, error: `No timer ${args.timer}; there are ${timers.length} timers.` };
}
timer = timers[index - 1]!;
}
const description = describeTimer(timer);
removeTimer(timer);
refreshWindowsAfterToolChange();
return { ok: true, content: `${timer.expired ? "Dismissed" : "Canceled"}: ${description}` };
}
default:
return { ok: false, error: `Unknown timer tool: ${name}` };
}
}
function toolDurationField(value: unknown, label: string): number {
if (value === undefined || value === null) return 0;
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
throw new Error(`Invalid ${label} value: ${value}`);
}
return parsed;
}
function describeTimer(timer: CountdownTimer): string {
const number = timers.indexOf(timer) + 1;
const duration = formatDuration(timer.durationMs);
if (timer.expired) return `Timer ${number}: ${duration} timer, finished.`;
return (
`Timer ${number}: ${duration} timer, ${formatCountdown(timer.endAtMs - Date.now())} remaining ` +
`(finishes at ${formatClock(timer.endAtMs)}).`
);
}
/** Repaint and re-gate every window after a tool call changed the timer list. */
function refreshWindowsAfterToolChange(): void {
for (const window of windows.values()) {
window.timerSelection = clamp(window.timerSelection, 0, timers.length + 1);
updateRenderTimer(window);
if (window.foreground && screenOn) renderAndSubmit(window, 0);
}
}
/**
* The window's context menu, created lazily. The timer has no entries of
* its own, so tap-then-hold opens the shell's system menu in its place.
*/
function windowMenu(window: TimerWindow): WindowMenu {
if (!window.menu) {
window.menu = new WindowMenu({
windowId: window.windowId,
post,
title: () => window.title,
items: () => [],
size: { width: window.viewportWidth, height: window.viewportHeight },
paintBase: () => paintContent(window),
isFocused: () => window.focused,
});
}
return window.menu;
}
function handleInput(window: TimerWindow, event: InputEvent, frameId: number): void {
// An open window menu owns all input (it closes itself via pop).
if (window.menu?.isOpen()) {
window.menu
.handleInput(event)
.catch((error) => console.error(`timer menu input failed: ${error}`))
.then(() => renderAndSubmit(window, frameId));
return;
}
if (event.type === "short-then-long-press") {
windowMenu(window).open();
renderAndSubmit(window, frameId);
return;
}
if (event.type === "double-click") {
if (window.view === "editor") {
window.view = "timers";
window.editorMessage = "";
updateRenderTimer(window);
renderAndSubmit(window, frameId);
} else {
frameTimings.finishFrame(frameId, "discarded: timer yielded focus");
post({ type: "yield-focus", windowId: window.windowId });
}
return;
}
if (window.view === "stopwatch") {
handleStopwatchInput(window, event, frameId);
} else if (window.view === "timers") {
handleTimersInput(window, event, frameId);
} else {
handleEditorInput(window, event, frameId);
}
}
function handleStopwatchInput(window: TimerWindow, event: InputEvent, frameId: number): void {
if (event.type === "scroll-up" || event.type === "scroll-down") {
const delta = event.type === "scroll-down" ? 1 : -1;
window.stopwatchAction = clamp(window.stopwatchAction + delta, 0, 2);
renderAndSubmit(window, frameId);
return;
}
if (event.type !== "click") {
frameTimings.finishFrame(frameId, "discarded: timer stopwatch ignored input");
return;
}
if (window.stopwatchAction === 0) {
if (stopwatchRunningSinceMs === null) {
stopwatchRunningSinceMs = Date.now();
} else {
stopwatchAccumulatedMs += Date.now() - stopwatchRunningSinceMs;
stopwatchRunningSinceMs = null;
}
} else if (window.stopwatchAction === 1) {
stopwatchAccumulatedMs = 0;
stopwatchRunningSinceMs = null;
} else {
window.view = "timers";
window.timerSelection = 0;
}
updateRenderTimer(window);
renderAndSubmit(window, frameId);
}
function handleTimersInput(window: TimerWindow, event: InputEvent, frameId: number): void {
syncExpiredTimers();
const itemCount = timers.length + 2; // Stopwatch navigation + New timer + timers.
if (event.type === "scroll-up" || event.type === "scroll-down") {
const delta = event.type === "scroll-down" ? 1 : -1;
window.timerSelection = clamp(window.timerSelection + delta, 0, itemCount - 1);
renderAndSubmit(window, frameId);
return;
}
if (event.type !== "click") {
frameTimings.finishFrame(frameId, "discarded: timer list ignored input");
return;
}
if (window.timerSelection === 0) {
window.view = "stopwatch";
} else if (window.timerSelection === 1) {
openEditor(window);
} else {
const timer = timers[window.timerSelection - 2];
if (timer) removeTimer(timer);
window.timerSelection = clamp(window.timerSelection, 0, Math.max(0, timers.length + 1));
}
updateRenderTimer(window);
renderAndSubmit(window, frameId);
}
function handleEditorInput(window: TimerWindow, event: InputEvent, frameId: number): void {
if (event.type === "scroll-up" || event.type === "scroll-down") {
const delta = event.type === "scroll-up" ? 1 : -1;
if (window.editorField === 0) {
window.editorHours = clamp(window.editorHours + delta, 0, 23);
} else if (window.editorField === 1) {
window.editorMinutes = clamp(window.editorMinutes + delta, 0, 59);
} else if (window.editorField === 2) {
window.editorSeconds = clamp(window.editorSeconds + delta, 0, 59);
} else {
window.editorField = delta > 0 ? 2 : 3;
}
window.editorMessage = "";
renderAndSubmit(window, frameId);
return;
}
if (event.type !== "click") {
frameTimings.finishFrame(frameId, "discarded: timer editor ignored input");
return;
}
if (window.editorField < 3) {
window.editorField += 1;
} else {
const durationMs =
((window.editorHours * 60 + window.editorMinutes) * 60 + window.editorSeconds) * 1000;
if (durationMs <= 0) {
window.editorMessage = "Choose a duration";
window.editorField = 0;
} else {
addTimer(durationMs);
window.view = "timers";
window.timerSelection = timers.length + 1;
window.editorMessage = "";
}
}
updateRenderTimer(window);
renderAndSubmit(window, frameId);
}
function openEditor(window: TimerWindow): void {
window.view = "editor";
window.editorField = 0;
window.editorHours = 0;
window.editorMinutes = 5;
window.editorSeconds = 0;
window.editorMessage = "";
}
function addTimer(durationMs: number): void {
// Millisecond epoch plus a small serial is unique across worker restarts and
// still safely representable as a JavaScript/Java long bridge value.
const id = Date.now() * 100 + (nextTimerSerial++ % 100);
const endAtMs = Date.now() + durationMs;
const timer: CountdownTimer = {
id,
durationMs,
endAtMs,
expired: false,
expiryTimeout: null,
};
timers.push(timer);
const durationLabel = formatDuration(durationMs);
scheduleTimerNotification(id, endAtMs, durationLabel);
timer.expiryTimeout = setTimeout(() => expireTimer(timer), Math.max(0, endAtMs - Date.now()));
}
function expireTimer(timer: CountdownTimer, renderWindows = true): void {
if (timer.expired) return;
timer.expired = true;
timer.expiryTimeout = null;
fireTimerNotification(timer.id, formatDuration(timer.durationMs));
for (const window of windows.values()) {
post({ type: "set-attention", windowId: window.windowId, attention: true });
updateRenderTimer(window);
if (renderWindows && window.foreground && screenOn) renderAndSubmit(window, 0);
}
}
function removeTimer(timer: CountdownTimer): void {
if (timer.expiryTimeout) clearTimeout(timer.expiryTimeout);
cancelTimerNotification(timer.id);
const index = timers.indexOf(timer);
if (index >= 0) timers.splice(index, 1);
}
function syncExpiredTimers(): void {
const now = Date.now();
for (const timer of timers) {
// The caller is already about to paint, so avoid a nested render when a
// sleeping/backgrounded timer is first observed as finished.
if (!timer.expired && timer.endAtMs <= now) expireTimer(timer, false);
}
}
function updateRenderTimer(window: TimerWindow): void {
const activeCountdowns = timers.some((timer) => !timer.expired);
const dynamic =
(window.view === "stopwatch" && stopwatchRunningSinceMs !== null) ||
(window.view === "timers" && activeCountdowns);
const shouldRun = dynamic && window.foreground && screenOn;
if (shouldRun && window.renderTimer === null) {
window.renderTimer = setInterval(() => {
syncExpiredTimers();
renderAndSubmit(window, 0);
}, RENDER_INTERVAL_MS);
} else if (!shouldRun && window.renderTimer !== null) {
clearInterval(window.renderTimer);
window.renderTimer = null;
}
}
function paint(window: TimerWindow): Plane[] {
return windowMenu(window).paint();
}
function paintContent(window: TimerWindow): GrayImage {
syncExpiredTimers();
const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0);
if (window.view === "stopwatch") {
paintStopwatch(image, window);
} else if (window.view === "timers") {
paintTimers(image, window);
} else {
paintEditor(image, window);
}
return image;
}
function paintStopwatch(image: GrayImage, window: TimerWindow): void {
drawTabs(image, "stopwatch");
const elapsed = stopwatchElapsedMs();
const timeLabel = formatStopwatchElapsed(elapsed);
const timeX = Math.max(0, Math.round((window.viewportWidth - largeFont.measureText(timeLabel)) / 2));
image.drawText(largeFont, timeX, 66, timeLabel, 245);
const state = stopwatchRunningSinceMs === null ? (elapsed > 0 ? "Paused" : "Ready") : "Running";
drawCenteredText(image, smallFont(), 112, state, 145);
const labels = [stopwatchRunningSinceMs === null ? "Start" : "Pause", "Reset", `Timers (${timers.length})`];
drawButtonRow(image, labels, window.stopwatchAction, 154);
drawFooter(image, `${GESTURE_SCROLL} action ${GESTURE_CLICK} select ${GESTURE_DOUBLE_CLICK} back`);
}
function paintTimers(image: GrayImage, window: TimerWindow): void {
drawTabs(image, "timers");
const items = ["< Stopwatch", "+ New timer", ...timers.map(timerRowLabel)];
const listBottom = image.height - FOOTER_HEIGHT;
const visibleRows = Math.max(1, Math.floor((listBottom - TIMER_LIST_TOP) / TIMER_ROW_HEIGHT));
const first = clamp(window.timerSelection - visibleRows + 1, 0, Math.max(0, items.length - visibleRows));
for (let row = 0; row < visibleRows; row++) {
const index = first + row;
if (index >= items.length) break;
const y = TIMER_LIST_TOP + row * TIMER_ROW_HEIGHT;
const selected = index === window.timerSelection;
if (selected) {
image.fillRoundedRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 34, 5);
image.drawRect(18, y, image.width - 36, TIMER_ROW_HEIGHT - 4, 105);
}
image.drawText(index >= 2 ? mediumFont : smallFont(), 32, y + (index >= 2 ? 2 : 7), items[index]!, selected ? 245 : 180);
}
const selectedTimer = window.timerSelection >= 2 ? timers[window.timerSelection - 2] : null;
const action = selectedTimer ? (selectedTimer.expired ? "dismiss" : "cancel") : "select";
drawFooter(image, `${GESTURE_SCROLL} timer ${GESTURE_CLICK} ${action} ${GESTURE_DOUBLE_CLICK} back`);
}
function paintEditor(image: GrayImage, window: TimerWindow): void {
image.drawText(smallFont(), 24, 14, "New timer", 190);
const fields = [pad2(window.editorHours), pad2(window.editorMinutes), pad2(window.editorSeconds)];
const labels = ["hours", "minutes", "seconds"];
const fieldWidth = 118;
const gap = 22;
const totalWidth = fieldWidth * 3 + gap * 2;
const startX = Math.round((image.width - totalWidth) / 2);
for (let index = 0; index < 3; index++) {
const x = startX + index * (fieldWidth + gap);
if (window.editorField === index) {
image.fillRoundedRect(x, 57, fieldWidth, 68, 35, 6);
image.drawRect(x, 57, fieldWidth, 68, 120);
}
drawCenteredIn(image, largeFont, x, fieldWidth, 65, fields[index]!, window.editorField === index ? 250 : 180);
drawCenteredIn(image, smallFont(), x, fieldWidth, 105, labels[index]!, 125);
if (index < 2) image.drawText(mediumFont, x + fieldWidth + 5, 71, ":", 130);
}
const startSelected = window.editorField === 3;
const buttonWidth = 160;
const buttonX = Math.round((image.width - buttonWidth) / 2);
if (startSelected) {
image.fillRoundedRect(buttonX, 151, buttonWidth, 38, 40, 6);
image.drawRect(buttonX, 151, buttonWidth, 38, 120);
}
drawCenteredIn(image, smallFont(), buttonX, buttonWidth, 162, "Start timer", startSelected ? 250 : 175);
if (window.editorMessage) drawCenteredText(image, smallFont(), 202, window.editorMessage, 190);
drawFooter(image, `${GESTURE_SCROLL} adjust ${GESTURE_CLICK} next ${GESTURE_DOUBLE_CLICK} cancel`);
}
function drawTabs(image: GrayImage, active: "stopwatch" | "timers"): void {
const stopwatch = "Stopwatch";
const timerLabel = `Timers (${timers.length})`;
const left = 24;
const dividerX = left + smallFont().measureText(stopwatch) + 18;
image.drawText(smallFont(), left, 15, stopwatch, active === "stopwatch" ? 245 : 105);
image.drawLine(left, 35, dividerX - 12, 35, active === "stopwatch" ? 200 : 30);
image.drawText(smallFont(), dividerX, 15, timerLabel, active === "timers" ? 245 : 105);
image.drawLine(dividerX, 35, dividerX + smallFont().measureText(timerLabel), 35, active === "timers" ? 200 : 30);
}
function drawButtonRow(image: GrayImage, labels: string[], selected: number, y: number): void {
const gap = 12;
const margin = 24;
const width = Math.floor((image.width - margin * 2 - gap * (labels.length - 1)) / labels.length);
for (let index = 0; index < labels.length; index++) {
const x = margin + index * (width + gap);
if (index === selected) {
image.fillRoundedRect(x, y, width, 40, 38, 6);
image.drawRect(x, y, width, 40, 115);
}
drawCenteredIn(image, smallFont(), x, width, y + 12, labels[index]!, index === selected ? 245 : 155);
}
}
function drawFooter(image: GrayImage, text: string): void {
image.drawLine(16, image.height - FOOTER_HEIGHT, image.width - 16, image.height - FOOTER_HEIGHT, 35);
drawCenteredText(image, smallFont(), image.height - 22, text, 115);
}
function drawCenteredText(image: GrayImage, font: UiFont, y: number, text: string, value: number): void {
image.drawText(font, Math.round((image.width - font.measureText(text)) / 2), y, text, value);
}
function drawCenteredIn(
image: GrayImage,
font: UiFont,
x: number,
width: number,
y: number,
text: string,
value: number,
): void {
image.drawText(font, Math.round(x + (width - font.measureText(text)) / 2), y, text, value);
}
function timerRowLabel(timer: CountdownTimer): string {
const number = timers.indexOf(timer) + 1;
if (timer.expired) return `${number}. 00:00 Finished`;
return `${number}. ${formatCountdown(timer.endAtMs - Date.now())} Running`;
}
function renderAndSubmit(window: TimerWindow, inputFrameId: number): void {
const frameId = inputFrameId > 0 ? inputFrameId : frameTimings.startFrame(`render:${window.windowId}`);
try {
const paintStartedAtMs = Date.now();
const planes = frameTimings.span(frameId, "paint", () =>
frameTimings.runWithFrame(frameId, () => paint(window)),
);
const paintMs = Date.now() - paintStartedAtMs;
const fingerprint = planesFingerprint(planes);
if (fingerprint === window.lastSubmittedFingerprint) {
frameTimings.finishFrame(frameId, "discarded: timer content unchanged");
return;
}
const communicator = getActiveDisplay();
if (!communicator) {
frameTimings.finishFrame(frameId, "discarded: no active display");
return;
}
const { image, draws } = frameTimings.span(frameId, "flatten", () => flattenPlanesWithDraws(planes));
const buffer = frameTimings.span(frameId, "to8bpp", () => image.to8bppBuffer());
communicator.submitSurfaceFrame(
buffer.buffer,
window.surfaceId,
0,
0,
image.width,
image.height,
fingerprint,
paintMs,
frameId,
frameTimings.span(frameId, "prepareFrameDraws", () => prepareFrameDraws(draws)),
);
window.lastSubmittedFingerprint = fingerprint;
} catch (error) {
frameTimings.finishFrame(frameId, "discarded: timer render failed");
console.error(`timer worker render failed: ${error}`);
}
}
function stopwatchElapsedMs(): number {
const runningMs = stopwatchRunningSinceMs === null ? 0 : Date.now() - stopwatchRunningSinceMs;
return stopwatchAccumulatedMs + runningMs;
}
function pad2(value: number): string {
return String(value).padStart(2, "0");
}
function formatStopwatchElapsed(totalMs: number): string {
const totalTenths = Math.floor(totalMs / 100);
const tenths = totalTenths % 10;
const totalSeconds = Math.floor(totalTenths / 10);
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return hours > 0
? `${hours}:${pad2(minutes)}:${pad2(seconds)}.${tenths}`
: `${pad2(minutes)}:${pad2(seconds)}.${tenths}`;
}
function formatCountdown(remainingMs: number): string {
const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${pad2(minutes)}:${pad2(seconds)}`;
}
function formatClock(timestampMs: number): string {
const date = new Date(timestampMs);
let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, "0");
const meridiem = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
if (hours === 0) hours = 12;
return `${hours}:${minutes} ${meridiem}`;
}
function formatDuration(durationMs: number): string {
const totalSeconds = Math.round(durationMs / 1000);
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
if (minutes > 0) return `${minutes}m ${seconds}s`;
return `${seconds}s`;
}
+557
View File
@@ -0,0 +1,557 @@
/**
* The Timers app's clock engine: a main-thread singleton that owns the
* timers / stopwatch / alarms state, persists it, schedules the durable
* Android alarms behind every expiry, rings the glasses buzzer, and tells
* listeners (the window, the tray icon, the assistant tools) when anything
* changes. It is booted at shell start, so everything here works with the
* window closed; the window is only a view on it.
*
* Two expiry paths run side by side, as before: a JS deadline for prompt
* on-glasses ringing while the process is awake, and an AlarmManager alarm
* (see FaceclawTimerNotifications.java) that posts the phone notification
* at the right moment even if the process is asleep or dead. The Java side
* deduplicates the two.
*/
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import {
cancelTimerNotification,
fireTimerNotification,
scheduleTimerNotification,
} from "../../native/timer-notifications";
import { buildSoundSequencePayload, findSoundEffect, effectPhrases } from "../../ui/sound-effects";
import { timeFormatSetting } from "../../ui/dashboard-settings";
import {
alarmNextRingMs,
createAlarm,
createTimer,
emptyTimersState,
formatDurationWords,
formatTimeOfDay,
parseTimersState,
pushRecentDuration,
serializeTimersState,
stopwatchElapsedMs,
timerRemainingMs,
type Alarm,
type CountdownTimer,
type TimersState,
} from "./timer-model";
const STATE_KEY = "timers.state";
/**
* An expiry that passed longer ago than this while the process was down
* (phone off, app killed) is marked rung silently rather than blaring on
* the glasses hours late; the phone notification already fired on time.
*/
const RING_GRACE_MS = 5 * 60_000;
/** How often the buzzer repeats while something is ringing. */
const RING_REPEAT_MS = 3_000;
/** Stop buzzing an item this long after it started ringing (it stays "rung"). */
const RING_MAX_MS = 2 * 60_000;
/**
* Upper bound between deadline checks even with nothing due, so a JS timer
* delayed by Doze or a clock jump can't leave a due item unnoticed for long.
*/
const MAX_ARM_MS = 30_000;
export const timersSoundSetting = new ConfigSettingBoolean({
id: "timersSound",
label: "Sound on glasses",
storageKey: "timers.soundOnGlasses",
defaultValue: true,
description: "Play the glasses buzzer while a timer or alarm is ringing.",
});
export const timersWakeSetting = new ConfigSettingBoolean({
id: "timersWake",
label: "Wake glasses when ringing",
storageKey: "timers.wakeGlasses",
defaultValue: true,
description: "Turn the display on and show the Timers app when a timer or alarm goes off.",
});
export type SnoozeMinutes = "5" | "10" | "15";
export const timersSnoozeSetting = new ConfigSettingEnum<SnoozeMinutes>({
id: "timersSnooze",
label: "Snooze length",
storageKey: "timers.snoozeMinutes",
defaultValue: "10",
values: ["5", "10", "15"],
formatValue: (value) => `${value} min`,
});
export type RingingItem = { kind: "timer"; timer: CountdownTimer } | { kind: "alarm"; alarm: Alarm };
export type TimerEngineHooks = {
/** Play one buzzer sequencer payload on the glasses (no-op when disconnected). */
playBuzzer: (payload: Uint8Array) => Promise<void> | void;
/** Something started ringing audibly: bring the app forward, wake the glasses. */
onRing: (item: RingingItem) => void;
};
const noopHooks: TimerEngineHooks = { playBuzzer: () => {}, onRing: () => {} };
export class TimerEngine {
state: TimersState;
private hooks: TimerEngineHooks = noopHooks;
private readonly listeners = new Set<() => void>();
private deadlineTimer: ReturnType<typeof setTimeout> | null = null;
private ringTimer: ReturnType<typeof setInterval> | null = null;
private booted = false;
constructor(private readonly now: () => number = () => Date.now()) {
this.state = emptyTimersState();
}
/**
* Install the side-effect hooks and reconcile persisted state against the
* clock: anything that came due while the process was down rings (or is
* marked rung silently past the grace window), and the Android alarms are
* re-armed for what is still pending.
*/
boot(hooks: TimerEngineHooks): void {
this.hooks = hooks;
if (this.booted) return;
this.booted = true;
// Loaded here rather than at module evaluation, so the settings store is
// certainly up before the first read.
this.state = parseTimersState(getStringSetting(STATE_KEY, ""));
this.check();
for (const timer of this.state.timers) {
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
}
for (const alarm of this.state.alarms) this.schedulePhoneAlarm(alarm);
this.save();
}
onChange(listener: () => void): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
/** True while anything on screen changes by itself once a second. */
isDynamic(): boolean {
return (
this.state.stopwatch.runningSinceMs !== null ||
this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null) ||
this.ringingItems().length > 0
);
}
ringingItems(): RingingItem[] {
const items: RingingItem[] = [];
for (const timer of this.state.timers) {
if (timer.rungAtMs !== null) items.push({ kind: "timer", timer });
}
for (const alarm of this.state.alarms) {
if (alarm.ringingSinceMs !== null) items.push({ kind: "alarm", alarm });
}
return items;
}
// -------------------------------------------------------------------------
// Timers
findTimer(id: number): CountdownTimer | undefined {
return this.state.timers.find((timer) => timer.id === id);
}
startTimer(durationMs: number, label = ""): CountdownTimer {
const timer = createTimer(durationMs, label, this.now());
this.state.timers.push(timer);
this.state.recentDurationsMs = pushRecentDuration(this.state.recentDurationsMs, durationMs);
this.schedulePhoneNotification(timer);
this.commit();
return timer;
}
pauseTimer(id: number): void {
const timer = this.findTimer(id);
if (!timer || timer.endsAtMs === null || timer.rungAtMs !== null) return;
timer.pausedRemainingMs = Math.max(0, timer.endsAtMs - this.now());
timer.endsAtMs = null;
cancelTimerNotification(timer.id);
this.commit();
}
resumeTimer(id: number): void {
const timer = this.findTimer(id);
if (!timer || timer.pausedRemainingMs === null) return;
timer.endsAtMs = this.now() + timer.pausedRemainingMs;
timer.pausedRemainingMs = null;
this.schedulePhoneNotification(timer);
this.commit();
}
/** Add time to a timer; a rung timer becomes a running one with just the added time. */
addTimerTime(id: number, deltaMs: number): void {
const timer = this.findTimer(id);
if (!timer) return;
if (timer.rungAtMs !== null) {
timer.rungAtMs = null;
timer.durationMs = deltaMs;
timer.endsAtMs = this.now() + deltaMs;
cancelTimerNotification(timer.id);
this.schedulePhoneNotification(timer);
} else if (timer.pausedRemainingMs !== null) {
timer.pausedRemainingMs += deltaMs;
timer.durationMs += deltaMs;
} else if (timer.endsAtMs !== null) {
timer.endsAtMs += deltaMs;
timer.durationMs += deltaMs;
this.schedulePhoneNotification(timer);
}
this.commit();
}
/** Start the timer over at its set duration ("Again" on a rung timer). */
restartTimer(id: number): void {
const timer = this.findTimer(id);
if (!timer) return;
timer.rungAtMs = null;
timer.pausedRemainingMs = null;
timer.endsAtMs = this.now() + timer.durationMs;
cancelTimerNotification(timer.id);
this.schedulePhoneNotification(timer);
this.commit();
}
setTimerLabel(id: number, label: string): void {
const timer = this.findTimer(id);
if (!timer) return;
timer.label = label.trim();
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
this.commit();
}
/** Cancel a timer, or dismiss a rung one. */
removeTimer(id: number): void {
const index = this.state.timers.findIndex((timer) => timer.id === id);
if (index < 0) return;
cancelTimerNotification(id);
this.state.timers.splice(index, 1);
this.commit();
}
// -------------------------------------------------------------------------
// Stopwatch
stopwatchToggle(): void {
const stopwatch = this.state.stopwatch;
const now = this.now();
if (stopwatch.runningSinceMs === null) {
stopwatch.runningSinceMs = now;
} else {
stopwatch.accumulatedMs += Math.max(0, now - stopwatch.runningSinceMs);
stopwatch.runningSinceMs = null;
}
this.commit();
}
stopwatchStart(): void {
if (this.state.stopwatch.runningSinceMs === null) this.stopwatchToggle();
}
stopwatchStop(): void {
if (this.state.stopwatch.runningSinceMs !== null) this.stopwatchToggle();
}
stopwatchLap(): void {
const stopwatch = this.state.stopwatch;
if (stopwatch.runningSinceMs === null) return;
stopwatch.lapsMs.push(stopwatchElapsedMs(stopwatch, this.now()));
this.commit();
}
stopwatchReset(): void {
this.state.stopwatch = { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] };
this.commit();
}
// -------------------------------------------------------------------------
// Alarms
findAlarm(id: number): Alarm | undefined {
return this.state.alarms.find((alarm) => alarm.id === id);
}
addAlarm(hour: number, minute: number, days: number, label = ""): Alarm {
const alarm = createAlarm(hour, minute, days, label, this.now());
this.state.alarms.push(alarm);
this.schedulePhoneAlarm(alarm);
this.commit();
return alarm;
}
setAlarmTime(id: number, hour: number, minute: number): void {
const alarm = this.findAlarm(id);
if (!alarm) return;
alarm.hour = hour;
alarm.minute = minute;
alarm.enabled = true;
alarm.snoozedUntilMs = null;
alarm.ringingSinceMs = null;
alarm.lastFiredAtMs = null;
this.schedulePhoneAlarm(alarm);
this.commit();
}
setAlarmDays(id: number, days: number): void {
const alarm = this.findAlarm(id);
if (!alarm) return;
alarm.days = days;
this.schedulePhoneAlarm(alarm);
this.commit();
}
setAlarmEnabled(id: number, enabled: boolean): void {
const alarm = this.findAlarm(id);
if (!alarm) return;
alarm.enabled = enabled;
alarm.snoozedUntilMs = null;
alarm.ringingSinceMs = null;
if (enabled) alarm.lastFiredAtMs = null;
this.schedulePhoneAlarm(alarm);
this.commit();
}
setAlarmLabel(id: number, label: string): void {
const alarm = this.findAlarm(id);
if (!alarm) return;
alarm.label = label.trim();
this.schedulePhoneAlarm(alarm);
this.commit();
}
deleteAlarm(id: number): void {
const index = this.state.alarms.findIndex((alarm) => alarm.id === id);
if (index < 0) return;
cancelTimerNotification(id);
this.state.alarms.splice(index, 1);
this.commit();
}
snoozeAlarm(id: number, minutes = Number(timersSnoozeSetting.get())): void {
const alarm = this.findAlarm(id);
if (!alarm || alarm.ringingSinceMs === null) return;
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = this.now() + minutes * 60_000;
this.schedulePhoneAlarm(alarm);
this.commit();
}
/** Stop a ringing alarm; a one-off alarm switches itself off. */
dismissAlarm(id: number): void {
const alarm = this.findAlarm(id);
if (!alarm || alarm.ringingSinceMs === null) return;
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = null;
if (alarm.days === 0) alarm.enabled = false;
this.schedulePhoneAlarm(alarm);
this.commit();
}
/** Dismiss whatever is ringing (timers and alarms alike). Returns how many. */
dismissAllRinging(): number {
const items = this.ringingItems();
for (const item of items) {
if (item.kind === "timer") this.removeTimer(item.timer.id);
else this.dismissAlarm(item.alarm.id);
}
return items.length;
}
// -------------------------------------------------------------------------
// Deadlines and ringing
/**
* Fire anything due and re-arm for the next deadline. Called on every
* change, on the deadline timer, and by the window before it paints, so a
* timer never shows 0:00 without also being rung.
*/
check(): void {
const now = this.now();
let changed = false;
for (const timer of this.state.timers) {
if (timer.endsAtMs === null || timer.rungAtMs !== null || timer.endsAtMs > now) continue;
timer.rungAtMs = timer.endsAtMs;
timer.endsAtMs = null;
changed = true;
const late = now - timer.rungAtMs > RING_GRACE_MS;
fireTimerNotification(timer.id, "Timer finished", timerNotificationText(timer));
if (!late) this.startRinging({ kind: "timer", timer });
}
for (const alarm of this.state.alarms) {
if (alarm.ringingSinceMs !== null) continue;
const due = this.alarmDueMs(alarm, now);
if (due === null || due > now) continue;
alarm.ringingSinceMs = now;
alarm.snoozedUntilMs = null;
alarm.lastFiredAtMs = due;
changed = true;
const late = now - due > RING_GRACE_MS;
fireTimerNotification(alarm.id, "Alarm", alarmNotificationText(alarm));
if (late) {
// Missed by too much to ring now: fall through to the next occurrence.
alarm.ringingSinceMs = null;
if (alarm.days === 0) alarm.enabled = false;
this.schedulePhoneAlarm(alarm);
} else {
this.startRinging({ kind: "alarm", alarm });
}
}
this.arm(now);
this.syncRingLoop(now);
if (changed) this.commit();
}
/**
* The occurrence an alarm should ring for next: the pending snooze, or the
* first occurrence after (now - grace) that it has not already rung for.
* Inside the grace window this returns a time in the past, which check()
* fires; beyond it the missed occurrence is skipped.
*/
private alarmDueMs(alarm: Alarm, now: number): number | null {
return alarmNextRingMs(alarm, now - RING_GRACE_MS);
}
private startRinging(item: RingingItem): void {
try {
this.hooks.onRing(item);
} catch (error) {
console.warn(`timers onRing hook failed: ${error}`);
}
}
/** Re-arm the single deadline timer for the soonest pending expiry. */
private arm(now: number): void {
if (this.deadlineTimer !== null) {
clearTimeout(this.deadlineTimer);
this.deadlineTimer = null;
}
const deadlines: number[] = [];
for (const timer of this.state.timers) {
if (timer.rungAtMs === null && timer.endsAtMs !== null) deadlines.push(timer.endsAtMs);
}
for (const alarm of this.state.alarms) {
if (alarm.ringingSinceMs !== null) continue;
const due = this.alarmDueMs(alarm, now);
if (due !== null) deadlines.push(due);
}
if (deadlines.length === 0) return;
const delay = Math.min(MAX_ARM_MS, Math.max(0, Math.min(...deadlines) - now));
this.deadlineTimer = setTimeout(() => {
this.deadlineTimer = null;
this.check();
}, delay);
}
/** Run the buzzer repeat loop while anything is (still audibly) ringing. */
private syncRingLoop(now: number): void {
const audible = this.ringingItems().some((item) => this.ringAgeMs(item, now) < RING_MAX_MS);
if (audible && this.ringTimer === null) {
this.playRingSound();
this.ringTimer = setInterval(() => {
const at = this.now();
if (!this.ringingItems().some((item) => this.ringAgeMs(item, at) < RING_MAX_MS)) {
this.syncRingLoop(at);
return;
}
this.playRingSound();
}, RING_REPEAT_MS);
} else if (!audible && this.ringTimer !== null) {
clearInterval(this.ringTimer);
this.ringTimer = null;
}
}
private ringAgeMs(item: RingingItem, now: number): number {
const since = item.kind === "timer" ? item.timer.rungAtMs : item.alarm.ringingSinceMs;
return since === null ? Infinity : Math.max(0, now - since);
}
private playRingSound(): void {
if (!timersSoundSetting.get()) return;
const effect = findSoundEffect("alarm");
if (!effect) return;
const phrase = effectPhrases(effect.make())[0];
if (!phrase) return;
try {
void this.hooks.playBuzzer(buildSoundSequencePayload(phrase));
} catch (error) {
console.warn(`timers buzzer failed: ${error}`);
}
}
// -------------------------------------------------------------------------
// Phone notifications
private schedulePhoneNotification(timer: CountdownTimer): void {
if (timer.endsAtMs === null) return;
scheduleTimerNotification(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer));
}
/** (Re)arm or cancel the phone alarm for an alarm's next occurrence. */
private schedulePhoneAlarm(alarm: Alarm): void {
const due = alarm.ringingSinceMs === null ? this.alarmDueMs(alarm, this.now()) : null;
if (due === null) {
cancelTimerNotification(alarm.id);
return;
}
scheduleTimerNotification(alarm.id, due, "Alarm", alarmNotificationText(alarm));
}
// -------------------------------------------------------------------------
// Change plumbing
private commit(): void {
this.save();
this.check();
this.notify();
}
private save(): void {
try {
setStringSetting(STATE_KEY, serializeTimersState(this.state));
} catch (error) {
console.warn(`timers state save failed: ${error}`);
}
}
private notify(): void {
for (const listener of Array.from(this.listeners)) {
try {
listener();
} catch (error) {
console.warn(`timers listener failed: ${error}`);
}
}
}
}
function timerNotificationText(timer: CountdownTimer): string {
const duration = formatDurationWords(timer.durationMs);
return timer.label ? `${timer.label} (${duration}) is up` : `${duration} timer is up`;
}
function alarmNotificationText(alarm: Alarm): string {
const time = formatTimeOfDay(alarm.hour, alarm.minute, timeFormatSetting.get() === "12h");
return alarm.label ? `${time} · ${alarm.label}` : time;
}
/** Remaining time of the timer that ends soonest, for the tray icon; null when none runs. */
export function soonestRunningTimerRemainingMs(engine: TimerEngine, now = Date.now()): number | null {
let soonest: number | null = null;
for (const timer of engine.state.timers) {
if (timer.endsAtMs === null || timer.rungAtMs !== null) continue;
const remaining = timerRemainingMs(timer, now);
if (soonest === null || remaining < soonest) soonest = remaining;
}
return soonest;
}
export const timerEngine = new TimerEngine();
+460
View File
@@ -0,0 +1,460 @@
/**
* Pure data model for the Timers app: countdown timers, the stopwatch, and
* alarms, plus the formatting and scheduling arithmetic they need. No
* NativeScript imports, so tests/timer-model.test.cjs can run it under plain
* node. Side effects (persistence, Android alarms, the buzzer, waking the
* glasses) live in timer-engine.ts; drawing lives in timer-app.ts.
*/
// ---------------------------------------------------------------------------
// Types
/**
* A countdown timer. Exactly one of the three phases holds at a time:
* running (endsAtMs set), paused (pausedRemainingMs set), or rung
* (rungAtMs set). A rung timer stays until dismissed so a missed one still
* reads "Time's up".
*/
export type CountdownTimer = {
/** Unique across restarts and safe as a Java long (see newItemId). */
id: number;
/** Wearer-given name; "" for an unlabelled timer (shown by duration). */
label: string;
durationMs: number;
endsAtMs: number | null;
pausedRemainingMs: number | null;
rungAtMs: number | null;
createdAtMs: number;
};
export type StopwatchState = {
/** Time accumulated over previous running stretches. */
accumulatedMs: number;
/** Start of the current running stretch, or null while stopped. */
runningSinceMs: number | null;
/** Cumulative elapsed time at each lap mark, oldest first. */
lapsMs: number[];
};
/** Day-of-week bits for Alarm.days, Monday first (Mon = bit 0 ... Sun = bit 6). */
export const DAY_BITS = [1, 2, 4, 8, 16, 32, 64] as const;
export const DAY_LETTERS = ["M", "T", "W", "T", "F", "S", "S"] as const;
export const DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as const;
export const DAY_FULL_NAMES = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] as const;
export const WEEKDAYS_MASK = 1 | 2 | 4 | 8 | 16;
export const WEEKEND_MASK = 32 | 64;
export const EVERY_DAY_MASK = 127;
export type Alarm = {
id: number;
hour: number;
minute: number;
/** Repeat days as DAY_BITS; 0 means a one-off alarm (disabled after it rings). */
days: number;
label: string;
enabled: boolean;
/** Set while a snooze is pending; the alarm rings again at this time. */
snoozedUntilMs: number | null;
/** Set while ringing; cleared by dismiss or snooze. */
ringingSinceMs: number | null;
/**
* For a repeating alarm: the occurrence most recently rung (or dismissed
* from ringing), so the same occurrence does not ring twice after a
* dismiss that lands before the minute is over.
*/
lastFiredAtMs: number | null;
};
export type TimersState = {
timers: CountdownTimer[];
stopwatch: StopwatchState;
alarms: Alarm[];
/** Durations the wearer started most recently, newest first. */
recentDurationsMs: number[];
};
export function emptyTimersState(): TimersState {
return {
timers: [],
stopwatch: { accumulatedMs: 0, runningSinceMs: null, lapsMs: [] },
alarms: [],
recentDurationsMs: [],
};
}
/** How many recent durations to keep for the "New timer" menu. */
export const RECENT_DURATION_COUNT = 3;
// ---------------------------------------------------------------------------
// Ids
let idSerial = 1;
/**
* Millisecond epoch plus a small serial: unique across restarts, ordered by
* creation, and still exactly representable through the JS -> Java long
* bridge.
*/
export function newItemId(nowMs: number): number {
return nowMs * 100 + (idSerial++ % 100);
}
// ---------------------------------------------------------------------------
// Duration ladder (the "New timer" dial)
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
/**
* The durations the dial scrolls through: fine steps where timers are
* usually short, coarser steps as they get long, so anything from ten
* seconds to a day is a few dozen scroll clicks away at most.
*/
export const DURATION_LADDER_MS: readonly number[] = (() => {
const ladder: number[] = [10 * SECOND, 15 * SECOND, 20 * SECOND, 30 * SECOND, 45 * SECOND, MINUTE, 90 * SECOND];
for (let minutes = 2; minutes <= 20; minutes++) ladder.push(minutes * MINUTE);
for (let minutes = 25; minutes <= 60; minutes += 5) ladder.push(minutes * MINUTE);
for (let minutes = 75; minutes <= 180; minutes += 15) ladder.push(minutes * MINUTE);
for (let minutes = 210; minutes <= 360; minutes += 30) ladder.push(minutes * MINUTE);
for (let hours = 7; hours <= 12; hours++) ladder.push(hours * HOUR);
ladder.push(18 * HOUR, 24 * HOUR);
return ladder;
})();
/** Index of the ladder rung closest to a duration (ties go to the shorter). */
export function nearestLadderIndex(durationMs: number): number {
let best = 0;
let bestDistance = Infinity;
for (let index = 0; index < DURATION_LADDER_MS.length; index++) {
const distance = Math.abs(DURATION_LADDER_MS[index]! - durationMs);
if (distance < bestDistance) {
best = index;
bestDistance = distance;
}
}
return best;
}
export const DEFAULT_TIMER_DURATION_MS = 10 * MINUTE;
export const MAX_TIMER_DURATION_MS = 24 * HOUR;
// ---------------------------------------------------------------------------
// Timers
export function timerRemainingMs(timer: CountdownTimer, nowMs: number): number {
if (timer.pausedRemainingMs !== null) return timer.pausedRemainingMs;
if (timer.endsAtMs !== null) return Math.max(0, timer.endsAtMs - nowMs);
return 0;
}
export type TimerPhase = "running" | "paused" | "rung";
export function timerPhase(timer: CountdownTimer): TimerPhase {
if (timer.rungAtMs !== null) return "rung";
if (timer.pausedRemainingMs !== null) return "paused";
return "running";
}
/** 0..1 progress toward the end (1 once rung). */
export function timerProgress(timer: CountdownTimer, nowMs: number): number {
if (timer.rungAtMs !== null || timer.durationMs <= 0) return 1;
return Math.min(1, Math.max(0, 1 - timerRemainingMs(timer, nowMs) / timer.durationMs));
}
export function createTimer(durationMs: number, label: string, nowMs: number): CountdownTimer {
return {
id: newItemId(nowMs),
label,
durationMs,
endsAtMs: nowMs + durationMs,
pausedRemainingMs: null,
rungAtMs: null,
createdAtMs: nowMs,
};
}
/** Running timers soonest first, then paused, then rung (oldest ring first). */
export function sortTimers(timers: readonly CountdownTimer[], nowMs: number): CountdownTimer[] {
const rank = (timer: CountdownTimer) => (timer.rungAtMs !== null ? 0 : timer.pausedRemainingMs !== null ? 2 : 1);
return [...timers].sort((a, b) => {
const rankDelta = rank(a) - rank(b);
if (rankDelta !== 0) return rankDelta;
if (a.rungAtMs !== null && b.rungAtMs !== null) return a.rungAtMs - b.rungAtMs;
return timerRemainingMs(a, nowMs) - timerRemainingMs(b, nowMs) || a.createdAtMs - b.createdAtMs;
});
}
export function pushRecentDuration(recent: readonly number[], durationMs: number): number[] {
return [durationMs, ...recent.filter((value) => value !== durationMs)].slice(0, RECENT_DURATION_COUNT);
}
// ---------------------------------------------------------------------------
// Stopwatch
export function stopwatchElapsedMs(stopwatch: StopwatchState, nowMs: number): number {
const running = stopwatch.runningSinceMs === null ? 0 : Math.max(0, nowMs - stopwatch.runningSinceMs);
return stopwatch.accumulatedMs + running;
}
export function stopwatchIsRunning(stopwatch: StopwatchState): boolean {
return stopwatch.runningSinceMs !== null;
}
// ---------------------------------------------------------------------------
// Alarms
export function createAlarm(hour: number, minute: number, days: number, label: string, nowMs: number): Alarm {
return {
id: newItemId(nowMs),
hour,
minute,
days,
label,
enabled: true,
snoozedUntilMs: null,
ringingSinceMs: null,
lastFiredAtMs: null,
};
}
/** Monday-first weekday index (0..6) of a Date, from JS's Sunday-first getDay. */
export function mondayFirstDay(date: Date): number {
return (date.getDay() + 6) % 7;
}
/**
* When the alarm next goes off, given the current time: the pending snooze
* if there is one, otherwise the next wall-clock occurrence of hour:minute
* on an enabled day (any day for a one-off), strictly after `nowMs` and
* after the occurrence it last rang for. Null when the alarm is disabled.
* Wall-clock arithmetic runs in the local zone via Date, so DST changes
* land on the right local time.
*/
export function alarmNextRingMs(alarm: Alarm, nowMs: number): number | null {
if (!alarm.enabled) return null;
if (alarm.snoozedUntilMs !== null) return alarm.snoozedUntilMs;
const floor = Math.max(nowMs, alarm.lastFiredAtMs ?? 0);
const start = new Date(nowMs);
for (let dayOffset = 0; dayOffset <= 7; dayOffset++) {
const candidate = new Date(start.getFullYear(), start.getMonth(), start.getDate() + dayOffset, alarm.hour, alarm.minute, 0, 0);
if (candidate.getTime() <= floor) continue;
if (alarm.days !== 0 && !(alarm.days & DAY_BITS[mondayFirstDay(candidate)]!)) continue;
return candidate.getTime();
}
return null;
}
/** Alarms by time of day, then by creation. */
export function sortAlarms(alarms: readonly Alarm[]): Alarm[] {
return [...alarms].sort((a, b) => a.hour * 60 + a.minute - (b.hour * 60 + b.minute) || a.id - b.id);
}
export function formatDays(days: number): string {
if (days === 0) return "Once";
if (days === EVERY_DAY_MASK) return "Every day";
if (days === WEEKDAYS_MASK) return "Weekdays";
if (days === WEEKEND_MASK) return "Weekends";
return DAY_NAMES.filter((_, index) => days & DAY_BITS[index]!).join(" ");
}
// ---------------------------------------------------------------------------
// Formatting
function pad2(value: number): string {
return String(value).padStart(2, "0");
}
/** Countdown / elapsed digits: m:ss below an hour, h:mm:ss above. */
export function formatClockDigits(totalSeconds: number): string {
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
return hours > 0 ? `${hours}:${pad2(minutes)}:${pad2(seconds)}` : `${minutes}:${pad2(seconds)}`;
}
/** Remaining time as a countdown reads it: rounds up, so 0:00 means done. */
export function formatCountdown(remainingMs: number): string {
return formatClockDigits(Math.max(0, Math.ceil(remainingMs / 1000)));
}
/** Elapsed time as a stopwatch reads it: rounds down, plus optional tenths. */
export function formatElapsed(elapsedMs: number, tenths: boolean): string {
const clamped = Math.max(0, elapsedMs);
const digits = formatClockDigits(Math.floor(clamped / 1000));
return tenths ? `${digits}.${Math.floor(clamped / 100) % 10}` : digits;
}
/** A set duration in words: "20 min", "1h 30m", "45s", "2m 30s". */
export function formatDurationWords(durationMs: number): string {
const totalSeconds = Math.round(durationMs / 1000);
const seconds = totalSeconds % 60;
const totalMinutes = Math.floor(totalSeconds / 60);
const minutes = totalMinutes % 60;
const hours = Math.floor(totalMinutes / 60);
if (hours > 0) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
if (minutes > 0) return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes} min`;
return `${seconds}s`;
}
/** A span until something: "9h 12m", "12m", "45s". Coarse on purpose. */
export function formatSpanWords(spanMs: number): string {
const totalSeconds = Math.max(0, Math.round(spanMs / 1000));
if (totalSeconds < 60) return `${totalSeconds}s`;
const totalMinutes = Math.floor(totalSeconds / 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (hours === 0) return `${minutes}m`;
if (hours < 24) return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
const days = Math.floor(hours / 24);
const restHours = hours % 24;
return restHours > 0 ? `${days}d ${restHours}h` : `${days}d`;
}
/** Wall-clock time of day in the wearer's chosen format. */
export function formatTimeOfDay(hour24: number, minute: number, twelveHour: boolean): string {
const minutes = pad2(minute);
if (!twelveHour) return `${hour24}:${minutes}`;
const hour12 = ((hour24 + 11) % 12) + 1;
return `${hour12}:${minutes} ${hour24 < 12 ? "AM" : "PM"}`;
}
export function formatClockAt(timestampMs: number, twelveHour: boolean): string {
const date = new Date(timestampMs);
return formatTimeOfDay(date.getHours(), date.getMinutes(), twelveHour);
}
/** Row/stage label for a timer: its label, else its set duration. */
export function timerDisplayName(timer: CountdownTimer): string {
return timer.label || formatDurationWords(timer.durationMs);
}
// ---------------------------------------------------------------------------
// Persistence shape
/**
* Parse a persisted state blob defensively: anything malformed falls back to
* a field default rather than failing the whole load, so a bad record loses
* itself and nothing else.
*/
export function parseTimersState(raw: string | null | undefined): TimersState {
const state = emptyTimersState();
if (!raw) return state;
let parsed: any;
try {
parsed = JSON.parse(raw);
} catch {
return state;
}
if (!parsed || typeof parsed !== "object") return state;
if (Array.isArray(parsed.timers)) {
for (const item of parsed.timers) {
if (!item || typeof item !== "object" || !isFiniteNumber(item.id) || !isFiniteNumber(item.durationMs)) continue;
state.timers.push({
id: item.id,
label: typeof item.label === "string" ? item.label : "",
durationMs: item.durationMs,
endsAtMs: isFiniteNumber(item.endsAtMs) ? item.endsAtMs : null,
pausedRemainingMs: isFiniteNumber(item.pausedRemainingMs) ? item.pausedRemainingMs : null,
rungAtMs: isFiniteNumber(item.rungAtMs) ? item.rungAtMs : null,
createdAtMs: isFiniteNumber(item.createdAtMs) ? item.createdAtMs : 0,
});
}
}
const stopwatch = parsed.stopwatch;
if (stopwatch && typeof stopwatch === "object") {
state.stopwatch = {
accumulatedMs: isFiniteNumber(stopwatch.accumulatedMs) ? Math.max(0, stopwatch.accumulatedMs) : 0,
runningSinceMs: isFiniteNumber(stopwatch.runningSinceMs) ? stopwatch.runningSinceMs : null,
lapsMs: Array.isArray(stopwatch.lapsMs) ? stopwatch.lapsMs.filter(isFiniteNumber) : [],
};
}
if (Array.isArray(parsed.alarms)) {
for (const item of parsed.alarms) {
if (!item || typeof item !== "object" || !isFiniteNumber(item.id)) continue;
if (!isFiniteNumber(item.hour) || !isFiniteNumber(item.minute)) continue;
state.alarms.push({
id: item.id,
hour: Math.min(23, Math.max(0, Math.floor(item.hour))),
minute: Math.min(59, Math.max(0, Math.floor(item.minute))),
days: isFiniteNumber(item.days) ? item.days & EVERY_DAY_MASK : 0,
label: typeof item.label === "string" ? item.label : "",
enabled: item.enabled !== false,
snoozedUntilMs: isFiniteNumber(item.snoozedUntilMs) ? item.snoozedUntilMs : null,
ringingSinceMs: isFiniteNumber(item.ringingSinceMs) ? item.ringingSinceMs : null,
lastFiredAtMs: isFiniteNumber(item.lastFiredAtMs) ? item.lastFiredAtMs : null,
});
}
}
if (Array.isArray(parsed.recentDurationsMs)) {
state.recentDurationsMs = parsed.recentDurationsMs.filter(isFiniteNumber).slice(0, RECENT_DURATION_COUNT);
}
return state;
}
export function serializeTimersState(state: TimersState): string {
return JSON.stringify(state);
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
// ---------------------------------------------------------------------------
// Tool-argument parsing (shared by the assistant tools)
/**
* Parse a time of day from the forms an assistant is likely to pass:
* "7:30", "07:30", "7:30 am", "7pm", "19:30", "noon", "midnight".
* Returns null when unparseable.
*/
export function parseTimeOfDay(text: string): { hour: number; minute: number } | null {
const trimmed = text.trim().toLowerCase();
if (trimmed === "noon") return { hour: 12, minute: 0 };
if (trimmed === "midnight") return { hour: 0, minute: 0 };
const match = /^(\d{1,2})(?::(\d{2}))?\s*(a\.?m\.?|p\.?m\.?)?$/.exec(trimmed);
if (!match) return null;
let hour = parseInt(match[1]!, 10);
const minute = match[2] ? parseInt(match[2], 10) : 0;
const meridiem = match[3]?.replace(/\./g, "");
if (minute > 59) return null;
if (meridiem) {
if (hour < 1 || hour > 12) return null;
hour = hour % 12;
if (meridiem === "pm") hour += 12;
} else if (hour > 23) {
return null;
}
return { hour, minute };
}
/** Parse repeat days from names ("mon", "tuesday"), "weekdays", "weekends", "daily"/"every day", "once". */
export function parseRepeatDays(values: readonly string[] | string | null | undefined): number | null {
if (values === null || values === undefined) return 0;
const list =
typeof values === "string"
? values.toLowerCase().replace(/every\s*day/g, "daily").split(/[,\s]+/)
: values.map((value) => String(value).toLowerCase().replace(/every\s*day/g, "daily"));
let mask = 0;
for (const raw of list) {
const value = String(raw).trim().toLowerCase();
if (!value || value === "once" || value === "none") continue;
if (value === "weekdays") {
mask |= WEEKDAYS_MASK;
continue;
}
if (value === "weekends" || value === "weekend") {
mask |= WEEKEND_MASK;
continue;
}
if (value === "daily" || value === "every day" || value === "everyday" || value === "all") {
mask |= EVERY_DAY_MASK;
continue;
}
const index = DAY_FULL_NAMES.findIndex((name) => name.toLowerCase().startsWith(value.slice(0, 3)));
if (index < 0 || value.length < 2) return null;
mask |= DAY_BITS[index]!;
}
return mask;
}
+383 -26
View File
@@ -1,76 +1,433 @@
/**
* Shell-side timer.* assistant tools. The Timer app's own tools are
* window-scoped ("open" tier), but "start a 5 minute timer" must work with no
* Timer window open — so these always-available wrappers launch the app,
* wait for its tools to register, and forward the call. Timer state lives in
* the app's worker, which outlives its window, so list/cancel also route
* through the app rather than answering "no timers" from the shell.
* The assistant's timer.* / stopwatch.* / alarm.* tools. They talk to the
* Timers app's engine directly (it boots with the shell), so every one works
* with no Timers window open; timer.set and alarm.set also bring the window
* forward so the wearer sees what was set.
*/
import { toolRegistry, type ToolRegistry } from "./tool-registry";
import { callAppToolWithLaunch } from "./launch-on-call";
import {
alarmNextRingMs,
formatClockAt,
formatCountdown,
formatDays,
formatDurationWords,
formatElapsed,
formatSpanWords,
formatTimeOfDay,
MAX_TIMER_DURATION_MS,
parseRepeatDays,
parseTimeOfDay,
sortAlarms,
sortTimers,
stopwatchElapsedMs,
stopwatchIsRunning,
timerDisplayName,
timerPhase,
timerRemainingMs,
type Alarm,
type CountdownTimer,
} from "../apps/timer/timer-model";
import { timerEngine } from "../apps/timer/timer-engine";
import { timeFormatSetting } from "../ui/dashboard-settings";
import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
let registered = false;
// Wrapper timeout: covers a first-launch worker spawn (up to the 5 s
// tool-appear wait in callAppToolWithLaunch) plus the forwarded call's own
// 10 s default budget.
const TIMER_WRAPPER_TIMEOUT_MS = 20_000;
function twelveHour(): boolean {
return timeFormatSetting.get() === "12h";
}
export function registerTimerTools(
launchApp: (appId: string) => Promise<void>,
registry: ToolRegistry = toolRegistry,
): void {
/** Timers in the order the app lists them, so "timer 2" means the same thing in both places. */
function listedTimers(): CountdownTimer[] {
return sortTimers(timerEngine.state.timers, Date.now());
}
function listedAlarms(): Alarm[] {
return sortAlarms(timerEngine.state.alarms);
}
function describeTimer(timer: CountdownTimer, number: number, now: number): string {
const name = timerDisplayName(timer);
switch (timerPhase(timer)) {
case "rung":
return `Timer ${number} (${name}): finished ${formatSpanWords(now - timer.rungAtMs!)} ago, still ringing until dismissed.`;
case "paused":
return `Timer ${number} (${name}): paused with ${formatCountdown(timerRemainingMs(timer, now))} left.`;
default:
return `Timer ${number} (${name}): ${formatCountdown(timerRemainingMs(timer, now))} left, ends at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`;
}
}
function describeAlarm(alarm: Alarm, number: number, now: number): string {
const time = formatTimeOfDay(alarm.hour, alarm.minute, twelveHour());
const name = alarm.label ? ` (${alarm.label})` : "";
if (alarm.ringingSinceMs !== null) return `Alarm ${number}: ${time}${name}, ringing now.`;
if (!alarm.enabled) return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}, off.`;
const next = alarmNextRingMs(alarm, now);
const when = next === null ? "" : `, rings in ${formatSpanWords(next - now)}`;
const snoozed = alarm.snoozedUntilMs !== null ? " (snoozed)" : "";
return `Alarm ${number}: ${time}${name}, ${formatDays(alarm.days).toLowerCase()}${when}${snoozed}.`;
}
/** Resolve a 1-based "timer"/"alarm" argument, or the only item when omitted. */
function pickItem<T>(items: T[], raw: unknown, noun: string, describe: (item: T, number: number) => string): T | ToolResult {
if (items.length === 0) return { ok: false, error: `No ${noun}s are set.` };
if (raw === undefined || raw === null) {
if (items.length === 1) return items[0]!;
return {
ok: false,
error: `There are ${items.length} ${noun}s; give the ${noun} number.\n${items.map(describe).join("\n")}`,
};
}
const index = Math.floor(Number(raw));
if (!Number.isFinite(index) || index < 1 || index > items.length) {
return { ok: false, error: `No ${noun} ${raw}; there are ${items.length} ${noun}s.` };
}
return items[index - 1]!;
}
function isResult(value: unknown): value is ToolResult {
return !!value && typeof value === "object" && "ok" in (value as object) && !("id" in (value as object));
}
function durationField(value: unknown, label: string): number {
if (value === undefined || value === null || value === "") return 0;
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`Invalid ${label} value: ${value}`);
return parsed;
}
const NUMBER_ARG = (noun: string, listTool: string) => ({
type: "number",
description: `1-based ${noun} number, as shown by ${listTool}. May be omitted when only one ${noun} exists.`,
});
export function registerTimerTools(launchApp: (appId: string) => Promise<void>, registry: ToolRegistry = toolRegistry): void {
if (registered) return;
registered = true;
const showApp = () => {
void launchApp("timer").catch((error) => console.warn(`timer tool launch failed: ${error}`));
};
// --- timers ---
registry.registerSystemTool(
{
name: "timer.set",
description:
"Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds; at least one must be nonzero. Opens the Timer app if it isn't already open. Returns the timer's number and when it will finish.",
"Start a countdown timer on the glasses. Give the duration as hours/minutes/seconds (at least one nonzero) and optionally a label such as \"pasta\". Returns the timer's number and when it will finish.",
inputSchema: {
type: "object",
properties: {
hours: { type: "number", description: "Hours component of the duration (default 0)." },
minutes: { type: "number", description: "Minutes component of the duration (default 0)." },
seconds: { type: "number", description: "Seconds component of the duration (default 0)." },
label: { type: "string", description: "Optional short name for the timer." },
},
additionalProperties: false,
},
timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
(args) => callAppToolWithLaunch(registry, launchApp, "timer", "set_timer", args ?? {}),
(args) => {
const durationMs = Math.round(
((durationField(args?.hours, "hours") * 60 + durationField(args?.minutes, "minutes")) * 60 +
durationField(args?.seconds, "seconds")) *
1000,
);
if (durationMs <= 0) return { ok: false, error: "timer.set requires a duration longer than zero." };
if (durationMs > MAX_TIMER_DURATION_MS) return { ok: false, error: "Timers can run for at most 24 hours." };
const label = typeof args?.label === "string" ? args.label.trim() : "";
const timer = timerEngine.startTimer(durationMs, label);
showApp();
const number = listedTimers().indexOf(timer) + 1;
return {
ok: true,
content: `Started a ${formatDurationWords(durationMs)} timer${label ? ` "${label}"` : ""} (timer ${number}), finishing at ${formatClockAt(timer.endsAtMs!, twelveHour())}.`,
};
},
);
registry.registerSystemTool(
{
name: "timer.list",
description:
"List the countdown timers on the glasses: each timer's number, its original duration, and the time remaining (or that it has finished). Opens the Timer app if it isn't already open — timers keep running while its window is closed.",
"List the countdown timers on the glasses: each timer's number, name, time remaining (or paused / finished), and end time.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
() => callAppToolWithLaunch(registry, launchApp, "timer", "list_timers", {}),
() => {
const timers = listedTimers();
if (timers.length === 0) return { ok: true, content: "No timers are set." };
const now = Date.now();
return { ok: true, content: timers.map((timer, index) => describeTimer(timer, index + 1, now)).join("\n") };
},
);
registry.registerSystemTool(
{
name: "timer.cancel",
description:
"Cancel a running countdown timer on the glasses, or dismiss a finished one. Give the timer number from timer.list; it may be omitted when only one timer exists. Pass all=true to clear every timer. Opens the Timer app if it isn't already open.",
"Cancel a countdown timer, or dismiss a finished one. Give the timer number from timer.list (omit it when only one exists), or all=true to clear every timer.",
inputSchema: {
type: "object",
properties: {
timer: { type: "number", description: "1-based timer number, as shown by timer.list." },
timer: NUMBER_ARG("timer", "timer.list"),
all: { type: "boolean", description: "Clear all timers instead of a single one." },
},
additionalProperties: false,
},
timeoutMs: TIMER_WRAPPER_TIMEOUT_MS,
proactive: true,
},
(args) => callAppToolWithLaunch(registry, launchApp, "timer", "cancel_timer", args ?? {}),
(args) => {
const timers = listedTimers();
if (args?.all === true) {
if (timers.length === 0) return { ok: true, content: "No timers are set." };
for (const timer of timers) timerEngine.removeTimer(timer.id);
return { ok: true, content: timers.length === 1 ? "Cleared the timer." : `Cleared ${timers.length} timers.` };
}
const now = Date.now();
const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
if (isResult(picked)) return picked;
const description = describeTimer(picked, timers.indexOf(picked) + 1, now);
timerEngine.removeTimer(picked.id);
return { ok: true, content: `${timerPhase(picked) === "rung" ? "Dismissed" : "Canceled"}: ${description}` };
},
);
registry.registerSystemTool(
{
name: "timer.pause",
description: "Pause a running countdown timer, or resume a paused one. Give the timer number from timer.list (omit it when only one exists).",
inputSchema: {
type: "object",
properties: {
timer: NUMBER_ARG("timer", "timer.list"),
resume: { type: "boolean", description: "true to resume a paused timer instead of pausing." },
},
additionalProperties: false,
},
proactive: true,
},
(args) => {
const timers = listedTimers();
const now = Date.now();
const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
if (isResult(picked)) return picked;
const phase = timerPhase(picked);
if (phase === "rung") return { ok: false, error: "That timer has already finished; dismiss it with timer.cancel." };
const resume = args?.resume === true || phase === "paused";
if (resume) timerEngine.resumeTimer(picked.id);
else timerEngine.pauseTimer(picked.id);
const updated = timerEngine.findTimer(picked.id)!;
return { ok: true, content: `${resume ? "Resumed" : "Paused"} ${describeTimer(updated, timers.indexOf(picked) + 1, Date.now())}` };
},
);
registry.registerSystemTool(
{
name: "timer.add_time",
description: "Add minutes to a countdown timer (a finished one restarts with just the added time). Give the timer number from timer.list (omit it when only one exists).",
inputSchema: {
type: "object",
properties: {
timer: NUMBER_ARG("timer", "timer.list"),
minutes: { type: "number", description: "Minutes to add (default 1)." },
},
additionalProperties: false,
},
proactive: true,
},
(args) => {
const timers = listedTimers();
const now = Date.now();
const picked = pickItem(timers, args?.timer, "timer", (timer, number) => describeTimer(timer, number, now));
if (isResult(picked)) return picked;
const minutes = args?.minutes === undefined ? 1 : Number(args.minutes);
if (!Number.isFinite(minutes) || minutes <= 0) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` };
timerEngine.addTimerTime(picked.id, Math.round(minutes * 60_000));
const updated = timerEngine.findTimer(picked.id)!;
return { ok: true, content: `Added ${formatDurationWords(minutes * 60_000)}. ${describeTimer(updated, listedTimers().indexOf(updated) + 1, Date.now())}` };
},
);
registry.registerSystemTool(
{
name: "timer.dismiss",
description: "Stop whatever is ringing on the glasses right now: finished timers are cleared and ringing alarms dismissed.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
proactive: true,
},
() => {
const count = timerEngine.dismissAllRinging();
return { ok: true, content: count === 0 ? "Nothing is ringing." : `Dismissed ${count === 1 ? "it" : `${count} items`}.` };
},
);
// --- stopwatch ---
registry.registerSystemTool(
{
name: "stopwatch.control",
description:
"Control the stopwatch on the glasses: action start, stop, lap, reset, or read (report the elapsed time and laps without changing anything).",
inputSchema: {
type: "object",
properties: {
action: { type: "string", enum: ["start", "stop", "lap", "reset", "read"], description: "What to do." },
},
required: ["action"],
additionalProperties: false,
},
proactive: true,
},
(args) => {
const action = String(args?.action ?? "read");
switch (action) {
case "start":
timerEngine.stopwatchStart();
showApp();
break;
case "stop":
timerEngine.stopwatchStop();
break;
case "lap":
if (!stopwatchIsRunning(timerEngine.state.stopwatch)) return { ok: false, error: "The stopwatch is not running." };
timerEngine.stopwatchLap();
break;
case "reset":
timerEngine.stopwatchReset();
break;
case "read":
break;
default:
return { ok: false, error: `Unknown stopwatch action: ${action}` };
}
const stopwatch = timerEngine.state.stopwatch;
const elapsed = formatElapsed(stopwatchElapsedMs(stopwatch, Date.now()), true);
const state = stopwatchIsRunning(stopwatch) ? "running" : "stopped";
const laps = stopwatch.lapsMs.length > 0 ? ` Laps: ${stopwatch.lapsMs.map((lap) => formatElapsed(lap, true)).join(", ")}.` : "";
return { ok: true, content: `Stopwatch ${state} at ${elapsed}.${laps}` };
},
);
// --- alarms ---
registry.registerSystemTool(
{
name: "alarm.set",
description:
"Set an alarm on the glasses. Give the time of day (e.g. \"7:30\", \"7:30 am\", \"19:30\"), optional repeat days (day names, \"weekdays\", \"weekends\", \"every day\"; default once), and an optional label.",
inputSchema: {
type: "object",
properties: {
time: { type: "string", description: "Time of day, 12- or 24-hour." },
days: {
type: "array",
items: { type: "string" },
description: "Repeat days: day names or weekdays / weekends / every day. Omit for a one-off alarm.",
},
label: { type: "string", description: "Optional short name for the alarm." },
},
required: ["time"],
additionalProperties: false,
},
proactive: true,
},
(args) => {
const time = parseTimeOfDay(String(args?.time ?? ""));
if (!time) return { ok: false, error: `Could not understand the time "${args?.time}". Use a form like 7:30 am or 19:30.` };
const days = parseRepeatDays(args?.days);
if (days === null) return { ok: false, error: `Could not understand the repeat days ${JSON.stringify(args?.days)}.` };
const label = typeof args?.label === "string" ? args.label.trim() : "";
const alarm = timerEngine.addAlarm(time.hour, time.minute, days, label);
showApp();
const now = Date.now();
return { ok: true, content: `Set. ${describeAlarm(alarm, listedAlarms().indexOf(alarm) + 1, now)}` };
},
);
registry.registerSystemTool(
{
name: "alarm.list",
description: "List the alarms on the glasses: each alarm's number, time, repeat days, label, and whether it is on.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
proactive: true,
},
() => {
const alarms = listedAlarms();
if (alarms.length === 0) return { ok: true, content: "No alarms are set." };
const now = Date.now();
return { ok: true, content: alarms.map((alarm, index) => describeAlarm(alarm, index + 1, now)).join("\n") };
},
);
registry.registerSystemTool(
{
name: "alarm.enable",
description: "Turn an alarm on or off without deleting it. Give the alarm number from alarm.list (omit it when only one exists).",
inputSchema: {
type: "object",
properties: {
alarm: NUMBER_ARG("alarm", "alarm.list"),
enabled: { type: "boolean", description: "true to turn the alarm on, false to turn it off." },
},
required: ["enabled"],
additionalProperties: false,
},
proactive: true,
},
(args) => {
const alarms = listedAlarms();
const now = Date.now();
const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now));
if (isResult(picked)) return picked;
timerEngine.setAlarmEnabled(picked.id, args?.enabled !== false);
const updated = timerEngine.findAlarm(picked.id)!;
return { ok: true, content: describeAlarm(updated, alarms.indexOf(picked) + 1, Date.now()) };
},
);
registry.registerSystemTool(
{
name: "alarm.delete",
description: "Delete an alarm. Give the alarm number from alarm.list (omit it when only one exists).",
inputSchema: {
type: "object",
properties: { alarm: NUMBER_ARG("alarm", "alarm.list") },
additionalProperties: false,
},
proactive: true,
},
(args) => {
const alarms = listedAlarms();
const now = Date.now();
const picked = pickItem(alarms, args?.alarm, "alarm", (alarm, number) => describeAlarm(alarm, number, now));
if (isResult(picked)) return picked;
const description = describeAlarm(picked, alarms.indexOf(picked) + 1, now);
timerEngine.deleteAlarm(picked.id);
return { ok: true, content: `Deleted: ${description}` };
},
);
registry.registerSystemTool(
{
name: "alarm.snooze",
description: "Snooze the alarm that is ringing now. Optionally give the snooze length in minutes (default: the Timers app's snooze setting).",
inputSchema: {
type: "object",
properties: { minutes: { type: "number", description: "Snooze length in minutes." } },
additionalProperties: false,
},
proactive: true,
},
(args) => {
const ringing = timerEngine.state.alarms.filter((alarm) => alarm.ringingSinceMs !== null);
if (ringing.length === 0) return { ok: false, error: "No alarm is ringing." };
const minutes = args?.minutes === undefined ? undefined : Number(args.minutes);
if (minutes !== undefined && (!Number.isFinite(minutes) || minutes <= 0)) return { ok: false, error: `Invalid minutes value: ${args?.minutes}` };
for (const alarm of ringing) timerEngine.snoozeAlarm(alarm.id, minutes);
const updated = timerEngine.findAlarm(ringing[0]!.id)!;
return { ok: true, content: `Snoozed until ${formatClockAt(updated.snoozedUntilMs!, twelveHour())}.` };
},
);
}
-3
View File
@@ -56,7 +56,6 @@ import { registerNavigateTools } from "../assistant/navigate-tools";
import { registerRoamTools } from "../assistant/roam-tools";
import { assistantBridge } from "../assistant/bridge-client";
import { registerWindowTools } from "../assistant/window-tools";
import { registerTimerTools } from "../assistant/timer-tools";
import { WorkerAppHost } from "../ui/shell/worker-window";
import { ALL_APPS } from "../apps/all-apps";
import { type AppContext, type AppDefinition, type AppLaunchParams, type TextEditorHost } from "../apps/app-definition";
@@ -326,8 +325,6 @@ class DashboardController {
registerNavigateTools((appId) => this.launchApp(appId));
// roam.* tools launch the Roam app on demand likewise.
registerRoamTools((appId) => this.launchApp(appId));
// timer.* tools launch the Timer app on demand likewise.
registerTimerTools((appId) => this.launchApp(appId));
// apps.* tools mirror the launcher grid and sidebar (launch, focus, close).
registerWindowTools({
apps: LAUNCHABLE_APPS,
+15 -8
View File
@@ -2,28 +2,35 @@ import { Utils } from "@nativescript/core";
declare const com: any;
/**
* Bridge to FaceclawTimerNotifications.java: the durable Android alarm and
* phone notification behind every Timers-app expiry (countdown timers and
* alarms alike, keyed by the item's id). The phone posts the notification at
* `triggerAtMs` even if the app process is asleep or gone.
*/
function getContext(): android.content.Context | null {
if (!global.isAndroid) return null;
return Utils.android.getApplicationContext() ?? null;
}
/** Schedule the durable Android alarm backing one on-glasses timer. */
export function scheduleTimerNotification(timerId: number, triggerAtMs: number, durationLabel: string): void {
/** Schedule (or move) the Android alarm that posts `title` / `text` at triggerAtMs. */
export function scheduleTimerNotification(itemId: number, triggerAtMs: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.schedule(context, timerId, triggerAtMs, durationLabel);
com.faceclaw.app.FaceclawTimerNotifications.schedule(context, itemId, triggerAtMs, title, text);
}
/** Cancel both a pending alarm and any already-posted notification. */
export function cancelTimerNotification(timerId: number): void {
export function cancelTimerNotification(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.cancel(context, timerId);
com.faceclaw.app.FaceclawTimerNotifications.cancel(context, itemId);
}
/** Prompt worker-side expiry path; Java deduplicates it against the alarm. */
export function fireTimerNotification(timerId: number, durationLabel: string): void {
/** The engine's own expiry path; Java deduplicates it against the alarm's. */
export function fireTimerNotification(itemId: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, timerId, durationLabel);
com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, itemId, title, text);
}
+151
View File
@@ -0,0 +1,151 @@
// Pins the Timers app's clock arithmetic: the duration dial's ladder, the
// countdown / stopwatch / span formatting the stage shows, alarm scheduling
// across days and repeat masks, and the argument parsing the assistant
// tools rely on.
const test = require("node:test");
const assert = require("node:assert/strict");
const model = require("../.test-build/app/apps/timer/timer-model.js");
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
test("the duration ladder is strictly increasing and spans 10s to 24h", () => {
const ladder = model.DURATION_LADDER_MS;
assert.equal(ladder[0], 10_000);
assert.equal(ladder[ladder.length - 1], 24 * HOUR);
for (let index = 1; index < ladder.length; index++) {
assert.ok(ladder[index] > ladder[index - 1], `rung ${index} not increasing`);
}
assert.ok(ladder.includes(10 * MINUTE));
assert.ok(ladder.includes(25 * MINUTE));
assert.ok(ladder.includes(90 * MINUTE));
});
test("nearestLadderIndex snaps to the closest rung", () => {
assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(10 * MINUTE)], 10 * MINUTE);
assert.equal(model.DURATION_LADDER_MS[model.nearestLadderIndex(11 * MINUTE + 20_000)], 11 * MINUTE);
assert.equal(model.nearestLadderIndex(0), 0);
assert.equal(model.nearestLadderIndex(1000 * HOUR), model.DURATION_LADDER_MS.length - 1);
});
test("countdown rounds up so 0:00 means finished; elapsed rounds down", () => {
assert.equal(model.formatCountdown(59_001), "1:00");
assert.equal(model.formatCountdown(59_000), "0:59");
assert.equal(model.formatCountdown(0), "0:00");
assert.equal(model.formatCountdown(HOUR + 5 * MINUTE + 3000), "1:05:03");
assert.equal(model.formatElapsed(59_950, false), "0:59");
assert.equal(model.formatElapsed(59_950, true), "0:59.9");
assert.equal(model.formatElapsed(HOUR, true), "1:00:00.0");
});
test("durations and spans read naturally", () => {
assert.equal(model.formatDurationWords(20 * MINUTE), "20 min");
assert.equal(model.formatDurationWords(90 * MINUTE), "1h 30m");
assert.equal(model.formatDurationWords(45_000), "45s");
assert.equal(model.formatDurationWords(2 * MINUTE + 30_000), "2m 30s");
assert.equal(model.formatSpanWords(9 * HOUR + 12 * MINUTE), "9h 12m");
assert.equal(model.formatSpanWords(12 * MINUTE), "12m");
assert.equal(model.formatSpanWords(30 * HOUR), "1d 6h");
});
test("time of day honours the 12/24-hour choice", () => {
assert.equal(model.formatTimeOfDay(7, 5, false), "7:05");
assert.equal(model.formatTimeOfDay(19, 30, false), "19:30");
assert.equal(model.formatTimeOfDay(0, 0, true), "12:00 AM");
assert.equal(model.formatTimeOfDay(12, 0, true), "12:00 PM");
assert.equal(model.formatTimeOfDay(19, 30, true), "7:30 PM");
});
function alarm(hour, minute, days, extra = {}) {
return { id: 1, hour, minute, days, label: "", enabled: true, snoozedUntilMs: null, ringingSinceMs: null, lastFiredAtMs: null, ...extra };
}
/** Local-time constructor: Wednesday 2026-09-02 at hh:mm. */
function wednesday(hour, minute) {
return new Date(2026, 8, 2, hour, minute, 0, 0).getTime();
}
test("a one-off alarm rings later today, else tomorrow", () => {
const now = wednesday(8, 0);
assert.equal(model.alarmNextRingMs(alarm(9, 30, 0), now), wednesday(9, 30));
assert.equal(model.alarmNextRingMs(alarm(7, 0, 0), now), new Date(2026, 8, 3, 7, 0).getTime());
// Exactly now counts as passed.
assert.equal(model.alarmNextRingMs(alarm(8, 0, 0), now), new Date(2026, 8, 3, 8, 0).getTime());
});
test("a repeating alarm skips to its next enabled day", () => {
const now = wednesday(8, 0);
// Weekends only: Wednesday -> Saturday.
assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKEND_MASK), now), new Date(2026, 8, 5, 7, 0).getTime());
// Weekdays, time already passed today: Thursday.
assert.equal(model.alarmNextRingMs(alarm(7, 0, model.WEEKDAYS_MASK), now), new Date(2026, 8, 3, 7, 0).getTime());
// Only Wednesdays, time passed: a week from now.
assert.equal(model.alarmNextRingMs(alarm(7, 0, model.DAY_BITS[2]), now), new Date(2026, 8, 9, 7, 0).getTime());
});
test("an alarm does not ring twice for the occurrence it last fired for", () => {
const now = wednesday(7, 0) + 20_000;
const fired = alarm(7, 0, model.EVERY_DAY_MASK, { lastFiredAtMs: wednesday(7, 0) });
assert.equal(model.alarmNextRingMs(fired, now - 5 * MINUTE), new Date(2026, 8, 3, 7, 0).getTime());
});
test("snooze and disabled override the schedule", () => {
const now = wednesday(8, 0);
assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { snoozedUntilMs: now + 10 * MINUTE }), now), now + 10 * MINUTE);
assert.equal(model.alarmNextRingMs(alarm(7, 0, 0, { enabled: false }), now), null);
});
test("repeat masks have readable names", () => {
assert.equal(model.formatDays(0), "Once");
assert.equal(model.formatDays(model.WEEKDAYS_MASK), "Weekdays");
assert.equal(model.formatDays(model.WEEKEND_MASK), "Weekends");
assert.equal(model.formatDays(model.EVERY_DAY_MASK), "Every day");
assert.equal(model.formatDays(model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]), "Mon Wed Fri");
});
test("timers sort ringing first, then soonest running, then paused", () => {
const now = 1_000_000;
const running = { id: 1, label: "", durationMs: 600_000, endsAtMs: now + 300_000, pausedRemainingMs: null, rungAtMs: null, createdAtMs: 1 };
const sooner = { ...running, id: 2, endsAtMs: now + 60_000 };
const paused = { ...running, id: 3, endsAtMs: null, pausedRemainingMs: 10_000 };
const rung = { ...running, id: 4, endsAtMs: null, rungAtMs: now - 5000 };
assert.deepEqual(model.sortTimers([running, paused, rung, sooner], now).map((timer) => timer.id), [4, 2, 1, 3]);
});
test("tool arguments: times of day", () => {
assert.deepEqual(model.parseTimeOfDay("7:30"), { hour: 7, minute: 30 });
assert.deepEqual(model.parseTimeOfDay("7:30 pm"), { hour: 19, minute: 30 });
assert.deepEqual(model.parseTimeOfDay("12 am"), { hour: 0, minute: 0 });
assert.deepEqual(model.parseTimeOfDay("12:15PM"), { hour: 12, minute: 15 });
assert.deepEqual(model.parseTimeOfDay("19:30"), { hour: 19, minute: 30 });
assert.deepEqual(model.parseTimeOfDay("noon"), { hour: 12, minute: 0 });
assert.equal(model.parseTimeOfDay("25:00"), null);
assert.equal(model.parseTimeOfDay("13 pm"), null);
assert.equal(model.parseTimeOfDay("soon"), null);
});
test("tool arguments: repeat days", () => {
assert.equal(model.parseRepeatDays(undefined), 0);
assert.equal(model.parseRepeatDays(["weekdays"]), model.WEEKDAYS_MASK);
assert.equal(model.parseRepeatDays("every day"), model.EVERY_DAY_MASK);
assert.equal(model.parseRepeatDays(["mon", "Wednesday", "fri"]), model.DAY_BITS[0] | model.DAY_BITS[2] | model.DAY_BITS[4]);
assert.equal(model.parseRepeatDays(["someday"]), null);
});
test("persisted state survives a round trip and shrugs off junk", () => {
const state = model.emptyTimersState();
state.timers.push(model.createTimer(5 * MINUTE, "tea", 1000));
state.alarms.push(model.createAlarm(7, 30, model.WEEKDAYS_MASK, "work", 1000));
state.stopwatch = { accumulatedMs: 1234, runningSinceMs: null, lapsMs: [500, 1000] };
state.recentDurationsMs = [5 * MINUTE];
const restored = model.parseTimersState(model.serializeTimersState(state));
assert.deepEqual(restored, state);
assert.deepEqual(model.parseTimersState("not json"), model.emptyTimersState());
assert.deepEqual(model.parseTimersState(JSON.stringify({ timers: [{ id: "x" }], alarms: [null] })), model.emptyTimersState());
});
test("recent durations stay short and deduplicated", () => {
assert.deepEqual(model.pushRecentDuration([1, 2, 3], 2), [2, 1, 3]);
assert.deepEqual(model.pushRecentDuration([1, 2, 3], 4), [4, 1, 2]);
});
+2 -1
View File
@@ -24,6 +24,7 @@
"../app/apps/microphones/dsp.ts",
"../app/apps/microphones/radar-dots.ts",
"../app/apps/microphones/name-guess.ts",
"../app/apps/evenhub/containers.ts"
"../app/apps/evenhub/containers.ts",
"../app/apps/timer/timer-model.ts"
]
}