);
}
+
+// The panel's side of the reminder to commit (useGitSession.ts): one line above the commit message once the work has
+// stayed uncommitted for the chosen interval, and a clock beside "Commit to" for the interval. The line never
+// interrupts: no toast, no dialog, no button. It stays until a commit; Off on the clock is the way to silence it.
+
+/** The line, or nothing while the reminder is quiet. It says what the branch chip's tooltip says. */
+export function CommitReminderNote({ reminder }: { readonly reminder: CommitReminder }) {
+ const translate = useTranslate();
+ const format = useFormat();
+ if (reminder.state.kind === 'quiet') {
+ return undefined;
+ }
+ const duration = commitReminderDuration(reminder.nowMs - reminder.state.sinceMs, format);
+ return (
+
+ );
+}
+
+/**
+ * The interval, kept for this project on this computer: the app's dropdown with a clock for its trigger, and the app's
+ * tooltip naming what the clock is for and the interval chosen. The clock dims while the reminder is off.
+ */
+export function CommitReminderInterval({ reminder, disabled }: { readonly reminder: CommitReminder; readonly disabled: boolean }) {
+ const translate = useTranslate();
+ const format = useFormat();
+ const label = (setting: CommitReminderSetting) => (setting === 'off' ? translate('git.reminder.off') : commitReminderDuration(setting * 60_000, format));
+ const settings: readonly CommitReminderSetting[] = ['off', ...COMMIT_REMINDER_MINUTES];
+ const options = settings.map((value) => ({ value, label: label(value), icon: }));
+ return (
+
+
+ className={`git-commit-reminder-interval ${reminder.setting === 'off' ? 'is-off' : ''}`}
+ menuClassName="git-commit-reminder-menu"
+ menuWidthMin={120}
+ ariaLabel={translate('git.reminder.setting')}
+ disabled={disabled}
+ value={reminder.setting}
+ options={options}
+ onChange={reminder.choose}
+ />
+
+ );
+}
diff --git a/src/features/git/branchIndicator.css b/src/features/git/branchIndicator.css
index 6ed6945ab..e2aaca63f 100644
--- a/src/features/git/branchIndicator.css
+++ b/src/features/git/branchIndicator.css
@@ -33,6 +33,15 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+/* The reminder to commit is due (features/git/useGitSession.ts): a small accent dot after the name, never a badge
+ or a number, so the chip keeps its width and the dot reads as "something to do", not as an alarm. */
+.stacki-branch-reminder {
+ flex: none;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent);
+}
.stacki-branch-chip[data-state='warning'] {
background: rgba(255, 214, 10, 0.16);
color: var(--amber);
diff --git a/src/features/git/useGitSession.ts b/src/features/git/useGitSession.ts
index 5bffa1bcd..2415db0df 100644
--- a/src/features/git/useGitSession.ts
+++ b/src/features/git/useGitSession.ts
@@ -1,15 +1,22 @@
// The one git session behind the History panel's controls and the title bar's pull button: one lock, one pull path and
// one pending merge review. Why one: the top bar and the shortcut pull while the panel is closed, so the lock that stops
-// two git actions at once, the toasts and the conflict review cannot belong to the panel.
+// two git actions at once, the toasts and the conflict review cannot belong to the panel. The reminder to commit lives
+// here for the same reason: the panel, the branch chip and the rail's Git tab all show it (see its section below).
import type React from 'react';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { assert } from '../../../shared/core/assert';
+import type { Formatters } from '../../../shared/core/i18n/format';
import type { IpcResults } from '../../../shared/ipc/ipcResults';
import { withReferencedMessage } from '../../../shared/core/i18n/referencedMessage';
import { useTranslate } from '../../lib/i18n/useTranslate';
import type { Translator } from '../../lib/i18n/localeContext';
import { cleanErrorKeepingReference, type Failure } from '../../lib/cleanError';
import { translateErrorText } from '../../lib/i18n/translateErrorText';
+import { forgetProjectPreference, loadProjectPreference, saveProjectPreference, type ProjectPreferenceSpec } from '../../lib/projectPreference';
+import { parseCommitHash } from '../../../shared/ipc/commitAvatars';
import { windowHeld } from '../../ui/busyLock';
+// The commit type's key, so both Git preferences tell projects apart the same way (Studio's included).
+import { COMMIT_TYPE_PROJECTS_MAX, commitTypeProjectKey } from './commitTypePreference';
import { pullGitBranch } from './gitChipBridge';
import type { Conflict } from './gitConflictModel';
@@ -57,6 +64,8 @@ export interface GitSession {
readonly conflict: PendingConflict | undefined;
readonly setConflict: React.Dispatch>;
readonly pull: (commits: number | undefined) => void;
+ /** The reminder to commit, shared by the panel's note, the title bar's branch chip and the rail's Git tab. */
+ readonly reminder: CommitReminder;
}
export function useGitSession(host: GitHost): GitSession {
@@ -65,6 +74,7 @@ export function useGitSession(host: GitHost): GitSession {
const [conflict, setConflict] = useState(undefined);
const settled = useCallback(() => setPulling(undefined), []);
const action = useActionRunner(host, translate, settled);
+ const reminder = useCommitReminder(host.info, host.project);
const busy = action.busy ?? host.busy;
const pull = (commits: number | undefined): void => {
const info = host.info;
@@ -95,6 +105,7 @@ export function useGitSession(host: GitHost): GitSession {
conflict,
setConflict,
pull,
+ reminder,
};
}
@@ -159,3 +170,251 @@ function useActionRunner({ flushSave, refresh, onWorktreeChanged, showToast, bus
);
return { busy, error, setError, runAction } as const;
}
+
+/*
+ * The reminder to commit: once a project has held uncommitted changes for a while, the Git panel, the branch chip and
+ * the rail's Git tab say so (GitChipView.tsx, BranchIndicator.tsx, DesktopGitPull.tsx).
+ *
+ * Why a reminder and not automatic backups: a commit is the step people come back to, share and publish. A safety net
+ * that saves work on its own teaches people new to Git that committing is optional; a reminder teaches the habit.
+ *
+ * What is measured is how long the work has stayed uncommitted, never how old the last commit is: a project last
+ * committed weeks ago and opened today has nothing to commit until something changes, and an hour with no changes is
+ * no reason to remind anyone. The clock starts the first time Stacki sees uncommitted changes on a commit and stops
+ * as soon as there are none; a new commit under remaining changes starts it again, since a commit is what it asks for.
+ * When it started, and on which commit, is kept per project on this computer: reopened on that same commit with
+ * changes, the project is the same uncommitted work, so the clock goes on from then and a reminder already due shows
+ * at once. On any other commit (one made elsewhere, an amend, another branch) the changes are newer, and it starts at
+ * opening.
+ *
+ * Both that start and the person's choice of interval are kept per project on this computer
+ * (src/lib/projectPreference.ts), never in the project; on by default at one hour, because the habit is the point and
+ * the reminder writes nothing in the project.
+ */
+
+export const COMMIT_REMINDER_MINUTES = [30, 60, 120, 240] as const;
+export type CommitReminderMinutes = (typeof COMMIT_REMINDER_MINUTES)[number];
+export type CommitReminderSetting = 'off' | CommitReminderMinutes;
+export const COMMIT_REMINDER_DEFAULT: CommitReminderSetting = 60;
+
+/** How long the work has been uncommitted, and on which commit (undefined in a repository with none yet). */
+export type CommitReminderClock = { readonly kind: 'clean' } | { readonly kind: 'dirty'; readonly sinceMs: number; readonly head: string | undefined };
+
+/** What a git read says: nothing to commit, or changes on a commit. */
+export type CommitReminderRead = { readonly kind: 'clean' } | { readonly kind: 'dirty'; readonly head: string | undefined };
+
+/** When the uncommitted work began and on which commit, as kept on this computer between openings. */
+export interface CommitReminderStart {
+ readonly sinceMs: number;
+ readonly head: string;
+}
+
+/** What the panel and the chip show. `dueAtMs` is when a quiet reminder becomes due, if one is on its way. */
+export type CommitReminderState = { readonly kind: 'quiet'; readonly dueAtMs: number | undefined } | { readonly kind: 'due'; readonly sinceMs: number };
+
+export const CLEAN_CLOCK: CommitReminderClock = { kind: 'clean' };
+
+/**
+ * The clock after a git read: kept while the changes stay on the same commit, stopped when there are none, and
+ * otherwise started, from the kept start when it was on this very commit (the same work, left uncommitted while the
+ * project was closed), or from now.
+ */
+export function nextCommitReminderClock(
+ clock: CommitReminderClock,
+ read: CommitReminderRead,
+ nowMs: number,
+ kept: CommitReminderStart | undefined,
+): CommitReminderClock {
+ assert(Number.isFinite(nowMs), 'Commit reminder: the time is a number');
+ if (read.kind === 'clean') {
+ return CLEAN_CLOCK;
+ }
+ if (clock.kind === 'dirty' && clock.head === read.head) {
+ return clock;
+ }
+ if (kept !== undefined && kept.head === read.head) {
+ // A start ahead of now means this computer's clock went back: the work is counted from now instead.
+ if (kept.sinceMs <= nowMs) {
+ return { kind: 'dirty', sinceMs: kept.sinceMs, head: read.head };
+ }
+ }
+ return { kind: 'dirty', sinceMs: nowMs, head: read.head };
+}
+
+/** A kept start, or undefined for anything an earlier build or another hand may have left there. */
+export function parseCommitReminderStart(raw: unknown): CommitReminderStart | undefined {
+ if (typeof raw !== 'object' || raw === null) {
+ return undefined;
+ }
+ const value: Readonly> = { ...raw };
+ const sinceMs = value['sinceMs'];
+ if (typeof sinceMs !== 'number' || !Number.isSafeInteger(sinceMs) || sinceMs < 0) {
+ return undefined;
+ }
+ try {
+ return { sinceMs, head: parseCommitHash(value['head']) };
+ } catch {
+ // Not a full commit hash: an unreadable start is no start, never a reason to stop.
+ return undefined;
+ }
+}
+
+/** Due once the work has stayed uncommitted for the interval, and until a commit or Off: nothing snoozes it. */
+export function commitReminderState(clock: CommitReminderClock, setting: CommitReminderSetting, nowMs: number): CommitReminderState {
+ assert(Number.isFinite(nowMs), 'Commit reminder: the time is a number');
+ if (setting === 'off') {
+ return { kind: 'quiet', dueAtMs: undefined };
+ }
+ if (clock.kind === 'clean') {
+ return { kind: 'quiet', dueAtMs: undefined };
+ }
+ const dueAtMs = clock.sinceMs + minutesMs(setting);
+ assert(dueAtMs > clock.sinceMs, 'Commit reminder: a reminder is due after the work became uncommitted');
+ if (nowMs < dueAtMs) {
+ return { kind: 'quiet', dueAtMs };
+ }
+ return { kind: 'due', sinceMs: clock.sinceMs };
+}
+
+/**
+ * When a due reminder's shown time next changes, as commitReminderDuration words it: the next whole minute under an
+ * hour, the next whole hour from there.
+ */
+export function nextCommitReminderRefreshMs(sinceMs: number, nowMs: number): number {
+ assert(Number.isFinite(sinceMs), 'Commit reminder: the time is a number');
+ assert(nowMs >= sinceMs, 'Commit reminder: the work became uncommitted before now');
+ const minutes = Math.floor((nowMs - sinceMs) / 60_000);
+ const minutesNext = minutes < 60 ? minutes + 1 : (Math.floor(minutes / 60) + 1) * 60;
+ const refreshMs = sinceMs + minutesNext * 60_000;
+ assert(refreshMs > nowMs, 'Commit reminder: the next refresh is ahead');
+ return refreshMs;
+}
+
+/** A stored interval, or undefined for anything an earlier build or another hand may have left there. */
+export function parseCommitReminderSetting(raw: unknown): CommitReminderSetting | undefined {
+ if (raw === 'off') {
+ return 'off';
+ }
+ return COMMIT_REMINDER_MINUTES.find((minutes) => minutes === raw);
+}
+
+/** A span of time in the locale's own words, in whole minutes under an hour and whole hours from there ("30 minutes", "2 hours"). */
+export function commitReminderDuration(durationMs: number, format: Pick): string {
+ assert(Number.isFinite(durationMs), 'Commit reminder: a duration is a number');
+ assert(durationMs >= 0, 'Commit reminder: a duration is not negative');
+ const minutes = Math.floor(durationMs / 60_000);
+ if (minutes < 60) {
+ return format.formatNumber(minutes, { style: 'unit', unit: 'minute', unitDisplay: 'long' });
+ }
+ return format.formatNumber(Math.floor(minutes / 60), { style: 'unit', unit: 'hour', unitDisplay: 'long' });
+}
+
+export const COMMIT_REMINDER_SPEC: ProjectPreferenceSpec = {
+ storageKey: 'stacki.git.commitReminders',
+ // The interval is kept beside the commit type, per project and on this computer, so both remember as many projects;
+ // past the bound the oldest choice falls back to the default.
+ projectsMax: COMMIT_TYPE_PROJECTS_MAX,
+ parseValue: parseCommitReminderSetting,
+};
+
+export const COMMIT_REMINDER_START_SPEC: ProjectPreferenceSpec = {
+ storageKey: 'stacki.git.uncommittedSince',
+ // Kept beside the interval, for as many projects; a project past the bound counts again from its next opening.
+ projectsMax: COMMIT_TYPE_PROJECTS_MAX,
+ parseValue: parseCommitReminderStart,
+};
+
+export interface CommitReminder {
+ readonly setting: CommitReminderSetting;
+ readonly state: CommitReminderState;
+ /** The time the state was computed at, so the elapsed time shown agrees with it. */
+ readonly nowMs: number;
+ readonly choose: (setting: CommitReminderSetting) => void;
+}
+
+type Repository = IpcResults['git:info'] | undefined;
+
+/** The reminder for the project on screen, driven by the git info the editor already keeps current. */
+export function useCommitReminder(info: Repository, project: GitProject): CommitReminder {
+ const projectKey = commitTypeProjectKey(project);
+ const setting = useReminderSetting(projectKey);
+ const [tracked, setTracked] = useState(() => ({ projectKey, clock: CLEAN_CLOCK }));
+ const [nowMs, setNowMs] = useState(() => Date.now());
+ // Another project's clock is never carried over.
+ const clock = tracked.projectKey === projectKey ? tracked.clock : CLEAN_CLOCK;
+ const worktree = worktreeOf(info);
+ const head = info?.isRepo ? info.head : undefined;
+ useEffect(() => {
+ // Until git answers, the clock keeps what it knew.
+ if (worktree === 'unknown') {
+ return;
+ }
+ const read: CommitReminderRead = worktree === 'dirty' ? { kind: 'dirty', head } : { kind: 'clean' };
+ const kept = loadProjectPreference(COMMIT_REMINDER_START_SPEC, projectKey);
+ setTracked((previous) => {
+ const base = previous.projectKey === projectKey ? previous.clock : CLEAN_CLOCK;
+ const next = nextCommitReminderClock(base, read, Date.now(), kept);
+ return next === previous.clock ? previous : { projectKey, clock: next };
+ });
+ }, [worktree, head, projectKey]);
+ useEffect(() => {
+ // Written only once the clock agrees with git's last answer: before the clock catches up, or before git answers
+ // at all, what is kept is left as it was.
+ if (worktree === 'clean' && clock.kind === 'clean') {
+ forgetProjectPreference(COMMIT_REMINDER_START_SPEC, projectKey);
+ }
+ if (worktree === 'dirty' && clock.kind === 'dirty' && clock.head !== undefined) {
+ saveProjectPreference(COMMIT_REMINDER_START_SPEC, projectKey, { sinceMs: clock.sinceMs, head: clock.head });
+ }
+ }, [worktree, clock, projectKey]);
+ const state = commitReminderState(clock, setting.value, nowMs);
+ // Quiet: wake when it becomes due. Due: wake when the time it shows next changes, since nothing else moves it.
+ const wakeAtMs = state.kind === 'quiet' ? state.dueAtMs : nextCommitReminderRefreshMs(state.sinceMs, nowMs);
+ useEffect(() => {
+ if (wakeAtMs === undefined) {
+ return undefined;
+ }
+ // The longest wait is the longest interval, well under what a browser timer holds (about 24 days).
+ const delayMs = Math.max(wakeAtMs - Date.now(), 0);
+ assert(delayMs <= minutesMs(240), 'Commit reminder: the wait is at most the longest interval');
+ const timer = setTimeout(() => setNowMs(Date.now()), delayMs);
+ return () => clearTimeout(timer);
+ }, [wakeAtMs]);
+ return {
+ setting: setting.value,
+ state,
+ nowMs,
+ choose: setting.choose,
+ };
+}
+
+/** The interval chosen for the project on screen, or the default, and how to change it. */
+function useReminderSetting(projectKey: string): { readonly value: CommitReminderSetting; readonly choose: (value: CommitReminderSetting) => void } {
+ const [choice, setChoice] = useState(() => ({ projectKey, value: loadProjectPreference(COMMIT_REMINDER_SPEC, projectKey) }));
+ // Another project's choice is never carried over: the stored one is read again.
+ const stored = choice.projectKey === projectKey ? choice.value : loadProjectPreference(COMMIT_REMINDER_SPEC, projectKey);
+ if (choice.projectKey !== projectKey) {
+ setChoice({ projectKey, value: stored });
+ }
+ return {
+ value: stored ?? COMMIT_REMINDER_DEFAULT,
+ choose: (value) => {
+ setChoice({ projectKey, value });
+ saveProjectPreference(COMMIT_REMINDER_SPEC, projectKey, value);
+ },
+ };
+}
+
+function worktreeOf(info: Repository): 'dirty' | 'clean' | 'unknown' {
+ if (info === undefined) {
+ return 'unknown';
+ }
+ if (info.isRepo) {
+ return info.dirty ? 'dirty' : 'clean';
+ }
+ return 'clean';
+}
+
+function minutesMs(minutes: CommitReminderMinutes): number {
+ return minutes * 60_000;
+}
diff --git a/src/lib/projectPreference.ts b/src/lib/projectPreference.ts
index 3ae8c7e2a..89d352c28 100644
--- a/src/lib/projectPreference.ts
+++ b/src/lib/projectPreference.ts
@@ -1,7 +1,7 @@
/*
* A person's remembered choice, kept per project in this app's local storage: the Assets panel's view
- * and sort, the Style selectors panel's tab. They are a way of looking at the project, not part of the
- * site, so they never go in a tracked `.stacki/` file.
+ * and sort, the Style selectors panel's tab, the reminder to commit's interval and when its uncommitted work began.
+ * They are a way of looking at the project, not part of the site, so they never go in a tracked `.stacki/` file.
*
* One storage key holds one short list of [project, value] pairs, newest first. Opening many projects
* forgets the least recently changed first; that bounds the list, never a project's content. Storage is
@@ -96,3 +96,18 @@ export function saveProjectPreference(spec: ProjectPreferenceSpec,
/* noop: an unsaved choice lasts until the panel closes */
}
}
+
+/** Forgets the project's value, so it reads as absent again. Storage is written only when there was one. */
+export function forgetProjectPreference(spec: ProjectPreferenceSpec, project: string, storage?: PreferenceStorage): void {
+ assert(project.length > 0, 'A remembered choice belongs to a project');
+ try {
+ const target = storage ?? localStorage;
+ const stored = parseStoredPreferences(target.getItem(spec.storageKey), spec);
+ const others = stored.filter(([kept]) => kept !== project);
+ if (others.length < stored.length) {
+ target.setItem(spec.storageKey, JSON.stringify(others));
+ }
+ } catch {
+ /* noop: a value that cannot be forgotten is read again, and the reader decides what it still means */
+ }
+}
diff --git a/test/renderer/apps/appsPanel.test.js b/test/renderer/apps/appsPanel.test.js
index 68717d698..af4bbe9ec 100644
--- a/test/renderer/apps/appsPanel.test.js
+++ b/test/renderer/apps/appsPanel.test.js
@@ -910,13 +910,13 @@ test('a waiting update reads on its row and dots the rail; auto-update starts of
const updates = bundle('src/features/apps/appUpdates.tsx', 'updates');
updates.noteInstalledApps([waiting]);
const dot = await mount(React.createElement(updates.AppsRailBadge, { admin: true }));
- assert.ok(dot.container.querySelector('.apps-rail-badge'), 'an admin sees that an update waits');
+ assert.ok(dot.container.querySelector('.rail-badge'), 'an admin sees that an update waits');
await act(async () => updates.noteUpdateOutcomes([{ kind: 'updated', id: 'heat-map', version: '1.1.0' }]));
- assert.equal(dot.container.querySelector('.apps-rail-badge') ?? undefined, undefined, 'an installed update no longer waits');
+ assert.equal(dot.container.querySelector('.rail-badge') ?? undefined, undefined, 'an installed update no longer waits');
await act(async () => dot.root.unmount());
updates.noteInstalledApps([waiting]);
const nonAdmin = await mount(React.createElement(updates.AppsRailBadge, { admin: false }));
- assert.equal(nonAdmin.container.querySelector('.apps-rail-badge') ?? undefined, undefined, 'only an admin can act on it');
+ assert.equal(nonAdmin.container.querySelector('.rail-badge') ?? undefined, undefined, 'only an admin can act on it');
await act(async () => nonAdmin.root.unmount());
});
diff --git a/test/renderer/git/commitReminder.test.js b/test/renderer/git/commitReminder.test.js
new file mode 100644
index 000000000..78293bb86
--- /dev/null
+++ b/test/renderer/git/commitReminder.test.js
@@ -0,0 +1,355 @@
+// Goal: the reminder to commit (src/features/git/useGitSession.ts) speaks only about work that has stayed
+// uncommitted for the chosen interval: never about an open project with nothing to commit, never when it is off,
+// until a commit once due (nothing snoozes it), and its interval and when the work began (on which commit) are kept
+// per project on this computer, nowhere else.
+// Methodology: first the pure pieces through the app's bundler — the clock's transitions, the state for every
+// setting, the stored-preference parser on malformed storage and at its bound, the duration wording, and the pinned
+// assertion messages. Then the real hook, the one-line note, the clock that picks the interval and the branch chip
+// mounted in jsdom under node:test's mocked clock, so an hour passes in a tick: the reminder appears at the interval
+// and not a minute before, with no button, and stays until a commit quiets it; reopened on the same commit after hours
+// closed it shows at once with the whole time, and on another commit it starts afresh; the clock's tooltip says what it is for
+// and names the interval, it dims for Off, Off silences it and is remembered, and another project starts from its own state. Last, Desktop's
+// Git tab: its dot shows only while the reminder is due, and stays away while the Git panel is open or for a role
+// without it.
+const assert = require('node:assert/strict');
+const { test, mock } = require('node:test');
+const fs = require('node:fs');
+const path = require('node:path');
+const esbuild = require('esbuild');
+const { JSDOM } = require('jsdom');
+const loadRenderer = require('../../helpers/rendererModule');
+const { repoPath, sourceSpecifier } = require('../../helpers/sources');
+
+const {
+ CLEAN_CLOCK,
+ COMMIT_REMINDER_DEFAULT,
+ commitReminderDuration,
+ COMMIT_REMINDER_SPEC,
+ COMMIT_REMINDER_START_SPEC,
+ commitReminderState,
+ nextCommitReminderClock,
+ nextCommitReminderRefreshMs,
+ parseCommitReminderSetting,
+ parseCommitReminderStart,
+} = loadRenderer('src/features/git/useGitSession.ts');
+const { createFormatters } = loadRenderer('shared/core/i18n/format.ts');
+const { parseStoredPreferences } = loadRenderer('src/lib/projectPreference.ts');
+const { COMMIT_TYPE_PROJECTS_MAX } = loadRenderer('src/features/git/commitTypePreference.ts');
+
+const MINUTE_MS = 60_000;
+const HOUR_MS = 60 * MINUTE_MS;
+
+const HEAD = 'a'.repeat(40);
+const NEXT_HEAD = 'b'.repeat(40);
+const CLEAN = { kind: 'clean' };
+const dirtyOn = (head) => ({ kind: 'dirty', head });
+
+test('the clock counts only time with uncommitted changes', () => {
+ assert.equal(COMMIT_REMINDER_DEFAULT, 60, 'on by default, at one hour');
+ // Clean stays clean, however long: an open project with nothing to commit is never reminded of anything.
+ assert.equal(nextCommitReminderClock(CLEAN_CLOCK, CLEAN, 5 * HOUR_MS, undefined), CLEAN_CLOCK);
+ assert.deepEqual(commitReminderState(CLEAN_CLOCK, 60, 5 * HOUR_MS), { kind: 'quiet', dueAtMs: undefined });
+ // The first change starts it; later reads on the same commit keep its start; none left stops it.
+ const started = nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(HEAD), 1_000, undefined);
+ assert.deepEqual(started, { kind: 'dirty', sinceMs: 1_000, head: HEAD });
+ assert.equal(nextCommitReminderClock(started, dirtyOn(HEAD), 50 * MINUTE_MS, undefined), started, 'a later read keeps the start');
+ assert.equal(nextCommitReminderClock(started, CLEAN, 2 * HOUR_MS, undefined), CLEAN_CLOCK);
+ // A commit that leaves changes behind is still a commit: the remaining work counts from it.
+ assert.deepEqual(nextCommitReminderClock(started, dirtyOn(NEXT_HEAD), 2 * HOUR_MS, undefined), { kind: 'dirty', sinceMs: 2 * HOUR_MS, head: NEXT_HEAD });
+ // A repository with no commit yet still counts, from now.
+ assert.deepEqual(nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(undefined), 7, undefined), { kind: 'dirty', sinceMs: 7, head: undefined });
+});
+
+test('reopened on the same commit, the clock goes on from the kept start; on another commit, from now', () => {
+ const kept = { sinceMs: 1_000, head: HEAD };
+ // The same work, left uncommitted while the project was closed: due at once when the interval has passed.
+ const resumed = nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(HEAD), 6 * HOUR_MS, kept);
+ assert.deepEqual(resumed, { kind: 'dirty', sinceMs: 1_000, head: HEAD });
+ assert.deepEqual(commitReminderState(resumed, 60, 6 * HOUR_MS), { kind: 'due', sinceMs: 1_000 });
+ // A commit made elsewhere, an amend or another branch: the changes are newer than the kept start.
+ assert.deepEqual(nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(NEXT_HEAD), 6 * HOUR_MS, kept), { kind: 'dirty', sinceMs: 6 * HOUR_MS, head: NEXT_HEAD });
+ assert.deepEqual(nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(undefined), 6 * HOUR_MS, kept), { kind: 'dirty', sinceMs: 6 * HOUR_MS, head: undefined });
+ // Nothing to commit: the kept start means nothing any more.
+ assert.equal(nextCommitReminderClock(CLEAN_CLOCK, CLEAN, 6 * HOUR_MS, kept), CLEAN_CLOCK);
+ // A start ahead of now (this computer's clock went back) counts from now instead of a negative time.
+ assert.deepEqual(nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(HEAD), 500, kept), { kind: 'dirty', sinceMs: 500, head: HEAD });
+});
+
+test('a kept start is parsed like any input, and stays bounded', () => {
+ assert.deepEqual(parseCommitReminderStart({ sinceMs: 1_000, head: HEAD }), { sinceMs: 1_000, head: HEAD });
+ assert.deepEqual(parseCommitReminderStart({ sinceMs: 0, head: 'c'.repeat(64) }), { sinceMs: 0, head: 'c'.repeat(64) }, 'a SHA-256 repository');
+ for (const bad of [
+ undefined,
+ 'start',
+ [1_000, HEAD],
+ { sinceMs: -1, head: HEAD },
+ { sinceMs: 1.5, head: HEAD },
+ { sinceMs: Number.MAX_SAFE_INTEGER + 1, head: HEAD },
+ { sinceMs: '1000', head: HEAD },
+ { sinceMs: 1_000 },
+ { sinceMs: 1_000, head: 'a'.repeat(39) },
+ { sinceMs: 1_000, head: 'A'.repeat(40) },
+ { sinceMs: 1_000, head: 'main' },
+ ]) {
+ assert.equal(parseCommitReminderStart(bad), undefined, `refuses ${JSON.stringify(bad)}`);
+ }
+ assert.equal(COMMIT_REMINDER_START_SPEC.projectsMax, COMMIT_TYPE_PROJECTS_MAX, 'as many projects as the interval beside it');
+ const many = JSON.stringify(
+ Array.from({ length: COMMIT_REMINDER_START_SPEC.projectsMax + 5 }, (_, index) => [`project-${index}`, { sinceMs: index, head: HEAD }]),
+ );
+ assert.equal(parseStoredPreferences(many, COMMIT_REMINDER_START_SPEC).length, COMMIT_REMINDER_START_SPEC.projectsMax);
+});
+
+test('the reminder is due at the interval, not a moment before, and stays due', () => {
+ const clock = nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(HEAD), 0, undefined);
+ assert.deepEqual(commitReminderState(clock, 60, HOUR_MS - 1), { kind: 'quiet', dueAtMs: HOUR_MS });
+ assert.deepEqual(commitReminderState(clock, 60, HOUR_MS), { kind: 'due', sinceMs: 0 });
+ assert.deepEqual(commitReminderState(clock, 30, 30 * MINUTE_MS), { kind: 'due', sinceMs: 0 });
+ assert.deepEqual(commitReminderState(clock, 240, 3 * HOUR_MS), { kind: 'quiet', dueAtMs: 4 * HOUR_MS });
+ assert.deepEqual(commitReminderState(clock, 'off', 100 * HOUR_MS), { kind: 'quiet', dueAtMs: undefined }, 'off is never due');
+ assert.deepEqual(commitReminderState(clock, 60, 10 * HOUR_MS), { kind: 'due', sinceMs: 0 }, 'still due hours later, counting from the first change');
+});
+
+test('a due reminder wakes when the time it shows next changes', () => {
+ // Under an hour the wording moves each minute; from an hour on, each hour.
+ assert.equal(nextCommitReminderRefreshMs(0, 30 * MINUTE_MS), 31 * MINUTE_MS);
+ assert.equal(nextCommitReminderRefreshMs(0, 59 * MINUTE_MS + 30_000), HOUR_MS);
+ assert.equal(nextCommitReminderRefreshMs(0, HOUR_MS), 2 * HOUR_MS);
+ assert.equal(nextCommitReminderRefreshMs(0, 2 * HOUR_MS - 1), 2 * HOUR_MS);
+ assert.equal(nextCommitReminderRefreshMs(5_000, 5_000 + 3 * HOUR_MS), 5_000 + 4 * HOUR_MS, 'counted from the first change');
+});
+
+test('the reminder refuses what cannot happen, loudly', () => {
+ assert.throws(() => nextCommitReminderClock(CLEAN_CLOCK, dirtyOn(HEAD), Number.NaN, undefined), /Commit reminder: the time is a number/);
+ assert.throws(() => nextCommitReminderRefreshMs(HOUR_MS, 0), /Commit reminder: the work became uncommitted before now/);
+ const format = createFormatters('en');
+ assert.throws(() => commitReminderDuration(-1, format), /Commit reminder: a duration is not negative/);
+});
+
+test('the stored interval is parsed like any input, and stays bounded', () => {
+ assert.equal(parseCommitReminderSetting('off'), 'off');
+ assert.equal(parseCommitReminderSetting(120), 120);
+ // JSON's null is one of the shapes storage can hold.
+ for (const bad of [0, 45, '60', -30, 1e9, JSON.parse('null'), undefined, 'OFF', {}]) {
+ assert.equal(parseCommitReminderSetting(bad), undefined, `refuses ${JSON.stringify(bad)}`);
+ }
+ // The store itself is the shared per-project preference (src/lib/projectPreference.ts, tested on its own); here,
+ // only that the reminder's spec drops what it refuses and keeps its project bound.
+ const stored = JSON.stringify([
+ ['a', 'off'],
+ ['b', 45],
+ ['c', 240],
+ ]);
+ assert.deepEqual(parseStoredPreferences(stored, COMMIT_REMINDER_SPEC), [
+ ['a', 'off'],
+ ['c', 240],
+ ]);
+ assert.equal(COMMIT_REMINDER_SPEC.projectsMax, COMMIT_TYPE_PROJECTS_MAX, 'as many projects as the commit type it is kept beside');
+ const many = JSON.stringify(Array.from({ length: COMMIT_REMINDER_SPEC.projectsMax + 5 }, (_, index) => [`project-${index}`, 30]));
+ assert.equal(parseStoredPreferences(many, COMMIT_REMINDER_SPEC).length, COMMIT_REMINDER_SPEC.projectsMax);
+});
+
+test('a duration reads in whole minutes under an hour and whole hours from there', () => {
+ const format = createFormatters('en');
+ assert.equal(commitReminderDuration(30 * MINUTE_MS, format), '30 minutes');
+ assert.equal(commitReminderDuration(59 * MINUTE_MS + 59_000, format), '59 minutes');
+ assert.equal(commitReminderDuration(HOUR_MS, format), '1 hour');
+ assert.equal(commitReminderDuration(2 * HOUR_MS + 59 * MINUTE_MS, format), '2 hours');
+ // French puts a no-break space between the number and the unit; any space is accepted here.
+ assert.match(commitReminderDuration(2 * HOUR_MS, createFormatters('fr')), /^2\sheures$/);
+});
+
+test('in the panel, the reminder appears after an hour of uncommitted work and only then', async (context) => {
+ const directory = repoPath('node_modules/.stacki-test/commit-reminder');
+ fs.mkdirSync(directory, { recursive: true });
+ const outfile = path.join(directory, 'reminder.cjs');
+ await esbuild.build({
+ stdin: {
+ contents: [
+ `export { useCommitReminder } from ${sourceSpecifier('src/features/git/useGitSession.ts')};`,
+ `export { CommitReminderNote, CommitReminderInterval } from ${sourceSpecifier('src/features/git/GitChipView.tsx')};`,
+ `export { BranchIndicator } from ${sourceSpecifier('src/features/git/BranchIndicator.tsx')};`,
+ ].join('\n'),
+ resolveDir: repoPath('src'),
+ loader: 'tsx',
+ },
+ outfile,
+ bundle: true,
+ format: 'cjs',
+ platform: 'node',
+ external: ['react', 'react-dom', 'react/jsx-runtime'],
+ loader: { '.css': 'empty' },
+ logLevel: 'silent',
+ });
+ const dom = new JSDOM('', { pretendToBeVisual: true, url: 'http://localhost/' });
+ for (const key of ['window', 'document', 'HTMLElement', 'Element', 'Node', 'localStorage']) {
+ global[key] = key === 'window' ? dom.window : dom.window[key];
+ }
+ window.matchMedia = () => ({ matches: true });
+ global.IS_REACT_ACT_ENVIRONMENT = true;
+ // React schedules its own work with setImmediate, which stays real; only the reminder's clock and timer are mocked.
+ mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1_764_000_000_000 });
+ context.after(() => mock.timers.reset());
+ const React = require('react');
+ const { act } = React;
+ const { createRoot } = require('react-dom/client');
+ const { useCommitReminder, CommitReminderNote, CommitReminderInterval, BranchIndicator } = require(outfile);
+
+ function Harness({ info, project }) {
+ const reminder = useCommitReminder(info, project);
+ return React.createElement(
+ React.Fragment,
+ undefined,
+ React.createElement(CommitReminderNote, { reminder }),
+ React.createElement(CommitReminderInterval, { reminder, disabled: false }),
+ );
+ }
+ const repository = (dirty, head = HEAD) => ({ isRepo: true, branch: 'main', branches: ['main'], parked: [], head, dirty, ahead: 0, trunk: 'main' });
+ const site = { path: '/site', name: 'Site' };
+ let root = createRoot(document.getElementById('root'));
+ // Closing and opening the project again: the window's memory is gone, only what this computer kept remains.
+ const reopen = async (info) => {
+ await act(async () => root.unmount());
+ root = createRoot(document.getElementById('root'));
+ await render(info);
+ };
+ const keptStart = (project) => JSON.parse(localStorage.getItem('stacki.git.uncommittedSince') ?? '[]').find(([stored]) => stored === project)?.[1];
+ const render = (info, project = site) => act(async () => root.render(React.createElement(Harness, { info, project })));
+ const pass = (milliseconds) => act(async () => mock.timers.tick(milliseconds));
+ const note = () => document.querySelector('.git-commit-reminder')?.textContent;
+ const storedChoice = (project) => JSON.parse(localStorage.getItem('stacki.git.commitReminders')).find(([stored]) => stored === project)?.[1];
+ const clock = () => document.querySelector('[aria-label="Remind me to commit"]');
+ // The app's tooltip keeps its text in the description the wrapper points to, read by screen readers and shown on hover.
+ const tip = () => document.getElementById(clock().closest('.git-commit-reminder-tip').getAttribute('aria-describedby')).textContent;
+ const choose = async (label) => {
+ await act(async () => document.querySelector('[aria-label="Remind me to commit"]').click());
+ const row = [...document.querySelectorAll('.dd-option')].find((option) => option.textContent.includes(label));
+ assert.ok(row, `the interval menu lists ${label}`);
+ await act(async () => row.click());
+ };
+ try {
+ // Open for two hours with nothing to commit: no reminder at all, and nothing kept.
+ await render(repository(false));
+ await pass(2 * HOUR_MS);
+ assert.equal(note(), undefined, 'nothing to commit, nothing to say');
+ assert.equal(keptStart('/site\nSite'), undefined);
+ // The clock's tooltip says what it is for and the interval; no native title doubles it; not dimmed while on.
+ assert.equal(tip(), 'Remind me to commit: 1 hour');
+ assert.equal(clock().hasAttribute('title'), false, 'one tooltip, the app’s');
+ assert.equal(clock().classList.contains('is-off'), false);
+
+ // The first change starts the clock; a minute short of the hour, still quiet; at the hour, the note.
+ await render(repository(true));
+ await pass(59 * MINUTE_MS);
+ assert.equal(note(), undefined);
+ await pass(MINUTE_MS);
+ assert.equal(note(), 'Uncommitted changes for 1 hour', 'the sentence the branch chip shows');
+ assert.equal(document.querySelectorAll('.git-commit-reminder button').length, 0, 'no button: Off on the clock silences it');
+
+ // Nothing snoozes it: it stays, and its time moves on by itself, counting from the first change.
+ await pass(HOUR_MS - 1);
+ assert.equal(note(), 'Uncommitted changes for 1 hour');
+ await pass(1);
+ assert.equal(note(), 'Uncommitted changes for 2 hours', 'the time shown keeps up without a git read');
+ assert.deepEqual(keptStart('/site\nSite'), { sinceMs: 1_764_000_000_000 + 2 * HOUR_MS, head: HEAD }, 'the start and its commit are kept');
+
+ // Closed for three hours and opened on the same commit: the same work, so the reminder shows at once.
+ await act(async () => root.unmount());
+ await pass(3 * HOUR_MS);
+ root = createRoot(document.getElementById('root'));
+ await render(repository(true));
+ assert.equal(note(), 'Uncommitted changes for 5 hours', 'counted from the first change, across the closed hours');
+
+ // Opened on another commit (made elsewhere, amended, another branch): newer changes, a fresh hour.
+ await reopen(repository(true, NEXT_HEAD));
+ assert.equal(note(), undefined, 'a commit since the kept start');
+ assert.equal(keptStart('/site\nSite').head, NEXT_HEAD, 'the new start is kept on the new commit');
+
+ // A commit (nothing left) quiets it, forgets the start, and the next change starts a fresh hour.
+ await render(repository(false, NEXT_HEAD));
+ assert.equal(note(), undefined);
+ assert.equal(keptStart('/site\nSite'), undefined, 'nothing to commit, nothing kept');
+ await render(repository(true));
+ await pass(30 * MINUTE_MS);
+ assert.equal(note(), undefined, 'a fresh clock after the commit');
+
+ // Off: never, however long, and remembered for this project on this computer.
+ await choose('Off');
+ await pass(10 * HOUR_MS);
+ assert.equal(note(), undefined, 'off is silent');
+ assert.equal(storedChoice('/site\nSite'), 'off');
+ assert.equal(tip(), 'Remind me to commit: Off');
+ assert.equal(clock().classList.contains('is-off'), true, 'the clock dims while off');
+ // Back to one hour: remembered like any other choice.
+ await choose('1 hour');
+ assert.equal(storedChoice('/site\nSite'), 60);
+
+ // Another project starts from its own clock and its own choice.
+ await render(repository(true), { path: '/other', name: 'Other' });
+ assert.equal(note(), undefined, 'no carried-over clock');
+ assert.equal(clock().textContent, '1 hour');
+ } finally {
+ await act(async () => root.unmount());
+ }
+
+ // The branch chip: a dot and the sentence once due, nothing otherwise.
+ const chipRoot = createRoot(document.getElementById('root'));
+ const chip = (reminder) =>
+ act(async () => chipRoot.render(React.createElement(BranchIndicator, { projectPath: '/site', info: repository(true), onOpen: () => {}, reminder })));
+ try {
+ await chip(undefined);
+ assert.equal(document.querySelector('.stacki-branch-reminder') === null, true, 'quiet: no dot');
+ await chip('Uncommitted changes for 1 hour');
+ assert.ok(document.querySelector('.stacki-branch-reminder'), 'due: a dot');
+ assert.match(document.querySelector('.stacki-branch-chip').getAttribute('aria-label'), /Uncommitted changes for 1 hour/);
+ } finally {
+ await act(async () => chipRoot.unmount());
+ }
+});
+
+test('on Desktop, the Git tab carries a dot while the reminder is due, and none while its panel is open', async () => {
+ const directory = repoPath('node_modules/.stacki-test/commit-reminder');
+ fs.mkdirSync(directory, { recursive: true });
+ const outfile = path.join(directory, 'railBadge.cjs');
+ await esbuild.build({
+ stdin: {
+ contents: [
+ `export { DesktopGitContext } from ${sourceSpecifier('src/app/shell/DesktopGitPull.tsx')};`,
+ `export { railBadge } from ${sourceSpecifier('src/app/LeftRail.tsx')};`,
+ ].join('\n'),
+ resolveDir: repoPath('src'),
+ loader: 'tsx',
+ },
+ outfile,
+ bundle: true,
+ format: 'cjs',
+ platform: 'node',
+ external: ['react', 'react-dom', 'react/jsx-runtime', 'electron'],
+ loader: { '.css': 'empty', '.svg': 'text', '.png': 'empty', '.woff2': 'empty' },
+ logLevel: 'silent',
+ });
+ const React = require('react');
+ const { act } = React;
+ const { createRoot } = require('react-dom/client');
+ const { DesktopGitContext, railBadge } = require(outfile);
+ const reminder = (state) => ({ setting: 60, state, nowMs: HOUR_MS, choose: () => {} });
+ const git = (value, access = 'allowed') => ({ session: { reminder: value }, incoming: 0, access, shortcut: undefined });
+ const root = createRoot(document.getElementById('root'));
+ const render = (value, { pressed = false, access = 'allowed' } = {}) =>
+ act(async () =>
+ root.render(React.createElement(DesktopGitContext.Provider, { value: git(value, access) }, railBadge('history', { admin: false, pressed }))),
+ );
+ const dot = () => document.querySelector('.rail-badge') ?? undefined;
+ try {
+ await render(reminder({ kind: 'quiet', dueAtMs: HOUR_MS }));
+ assert.equal(dot(), undefined, 'quiet: no dot');
+ await render(reminder({ kind: 'due', sinceMs: 0 }));
+ assert.equal(dot().getAttribute('aria-label'), 'Uncommitted changes for 1 hour');
+ await render(reminder({ kind: 'due', sinceMs: 0 }), { pressed: true });
+ assert.equal(dot(), undefined, 'the open panel shows the note instead');
+ await render(reminder({ kind: 'due', sinceMs: 0 }), { access: 'denied' });
+ assert.equal(dot(), undefined, 'a role without the Git panel has nowhere to commit from');
+ } finally {
+ await act(async () => root.unmount());
+ }
+});
diff --git a/test/renderer/git/commitReminderChromium.test.js b/test/renderer/git/commitReminderChromium.test.js
new file mode 100644
index 000000000..3e9254ef2
--- /dev/null
+++ b/test/renderer/git/commitReminderChromium.test.js
@@ -0,0 +1,246 @@
+// Goal: the reminder to commit stays whole in the Git panel at every width the left panel can take (260px to 600px),
+// in every language and for every time it can show: its line never reaches past the panel's edge, the panel never
+// scrolls sideways, the sentence wraps under itself and never under its dot, it takes at most two lines, and the
+// interval's clock stays at the end of the "Commit to" heading, centred on it, whatever the branch name's length.
+//
+// node test/renderer/git/commitReminderChromium.test.js
+//
+// Method: run under the Electron binary, because only Chromium lays out grids, wrapping and scroll widths. A harness
+// bundles the real GitChipView and styles.css into the History panel's own markup (`.panel.left` > `.panel-section` >
+// `.panel-body.history-body`, as src/features/history/HistoryPanel.tsx draws it) at the width under test, inside the
+// real LocaleProvider, with a reminder that is due. Each of the 18 languages is drawn at 260, 340 and 600px with the
+// longest times it can word (59 minutes, then 1, 23 and 9999 hours) under a short and a long branch name. The probe
+// counts the sentence's lines from its text's line boxes and reads every box against the panel's. Every wait is for a
+// condition (the document language the provider sets once a catalog arrives), polled once per animation frame and
+// bounded. Screenshots of the narrowest drawing per language are written to
+// node_modules/.stacki-test/commit-reminder-chromium/.
+const fs = require('node:fs');
+const path = require('node:path');
+const { buildSync } = require('esbuild');
+const { runElectronProbe } = require('../../helpers/electronProbe.js');
+const { repoPath } = require('../../helpers/sources.js');
+
+const WIDTHS_PX = [260, 340, 600];
+const LOCALES = ['en', 'es', 'fr', 'de', 'pt-BR', 'it', 'nl', 'pl', 'tr', 'ru', 'id', 'hi', 'ar', 'he', 'ja', 'ko', 'zh-CN', 'zh-TW'];
+const MINUTE_MS = 60_000;
+const DURATIONS_MS = [59 * MINUTE_MS, 60 * MINUTE_MS, 23 * 60 * MINUTE_MS, 9999 * 60 * MINUTE_MS];
+const BRANCHES = ['main', 'feature/a-branch-name-long-enough-to-wrap-the-heading'];
+const LINES_MAX = 2;
+const PANE_HEIGHT_PX = 400;
+// Sub-pixel layout rounds; an element this far past an edge is not overflowing.
+const EDGE_TOLERANCE_PX = 0.5;
+// The clock is centred on the heading when the two centres are this close.
+const CENTRE_TOLERANCE_PX = 1.5;
+
+const HARNESS = `
+import ${JSON.stringify(repoPath('src/app/styles.css'))};
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { LocaleProvider } from ${JSON.stringify(repoPath('src/lib/i18n/LocaleProvider.tsx'))};
+import GitChipView from ${JSON.stringify(repoPath('src/features/git/GitChipView.tsx'))};
+import { useCommitType } from ${JSON.stringify(repoPath('src/features/git/CommitTypePicker.tsx'))};
+
+const noop = () => {};
+function Harness({ branch, durationMs }) {
+ const commitType = useCommitType({ path: '/fixture', name: 'fixture' });
+ const info = { isRepo: true, branch, branches: [branch], parked: [], head: 'a'.repeat(40), dirty: true, ahead: 0, trunk: branch };
+ return React.createElement(GitChipView, {
+ changes: { projectPath: '/fixture', info: { dirty: false }, showToast: noop },
+ info, busy: undefined, error: undefined, commitMessage: '', commitType, commitSubject: undefined, newBranch: '',
+ picking: false, picked: undefined, changed: [], onDismissError: noop, onSwitch: noop, onMerge: noop, onDelete: noop,
+ onNewBranch: noop, onCreateBranch: noop, onCommitMessage: noop, onRefreshFiles: noop, onTogglePicking: noop, onPick: noop,
+ onCommit: noop, onPull: noop, incoming: { kind: 'ready', commits: 0 }, pullAccess: 'allowed', pullShortcut: undefined,
+ reminder: { setting: 60, state: { kind: 'due', sinceMs: 0 }, nowMs: durationMs, choose: noop },
+ });
+}
+window.mount = (locale, widthPx, branch, durationMs) => {
+ window.root?.unmount();
+ document.documentElement.lang = '';
+ const host = document.getElementById('host');
+ host.innerHTML = '