Compare commits

..
Author SHA1 Message Date
Claude Fable 5 3fb9b504f4 feat(capture): choose what to capture — area, window, browser page or screen
Capture is now a decision, not a hidden setting. The popover shows a four-way scope control with the target named under it (800 x 600 on Display 1, the frontmost window, the front browser window, the whole display), and the window header carries the same choice beside the verbs. Picking Window or Browser hides Redline, dims the screen, names the app under the pointer and highlights its window; a click captures exactly that window, Escape cancels, and the desktop highlights the whole screen. New Session is one click: the current captures stay in their own folder, a fresh session opens, and the area picker comes straight up with the saved area pre-selected — Return keeps it, a drag replaces it. Settings is consolidated into one door (the popover gear, plus Cmd-,): what to capture, saved area, shortcut, ask-on-new-session, sending, session age limit, and a new Updates group with automatic install (on by default; installs only when nothing is unsent). The footer filler and the extra-actions menu are gone.
2026-11-01 11:47:58 +04:00
Claude Fable 5 1ae8351b04 feat(app): open the session window at launch and on reopen; local install script
--window opens the Redline window at launch, so a script or a demo lands on the new UI instead of an idle menu-bar icon. Clicking the running app in Finder, or open -a Redline, now shows the window instead of doing nothing. scripts/install-local.sh installs the locally built app into /Applications, keeps the previous copy at .build/Redline-<version>.app for rollback, and launches it with the window open.
2026-11-01 08:41:03 +04:00
Claude Fable 5 3061e45bcb feat(ui): rebuild the UX around two surfaces — a glance popover and a session window
The menu-bar popover was being used as a session manager: status, five text fields,
thumbnails, three buttons, a history list and eight more flat rows in 320 pt. The
redesign splits the product by job, from a UX pass whose mockups are kept under
design/ux-rework/.

- Popover: only the current session. Review details as one line plus a pencil that
  opens the window with the Lane field focused, at most three thumbnails, a Capture
  and a Send row, a New Session and Open Redline row, one status line when something
  happened, and a footer with the send channel, the retention policy and a ... menu
  for Settings / updates / quit.
- Window: sidebar of sessions grouped Today / Yesterday / This week / by month with
  a Current tag and each session's state, the selected session's pages as cards
  (select, Delete or Remove Page, sent sessions read-only), and an inspector with
  editable review details, the PDF facts (file name, pages, channel, status) and the
  session facts (started, id, files). Past sessions show their details read-only.
- Settings: three labelled groups (Capture, Sending, Sessions) replacing the
  headings-plus-grid layout.
- Sessions list/search/grouping/state live on the model, so the window and the popover
  read the same truth (came-back-marked state comes from the return ledger).
- Verification: 159 tests, the headless panel self-test, and an end-to-end run against
  the active app (scripts/run-e2e-ui.sh) which opens the real window, types into the
  Lane field with key events and clicks New Session, reporting what the launch mode
  could and could not deliver.
2026-10-31 13:03:08 +04:00
Claude Fable 5 02fa791b78 feat(sessions): keep every session, record review details, name and stamp the PDF
Sessions are now the unit of the product instead of an implicit capture run.

- Nothing is deleted by default: the fixed 10-session cap is gone. An age limit
  (Never / 7 / 14 / 30 / 90 / 180 / 365 days) is chosen in Settings > Sessions and
  applied on launch, after archiving, and by "Clean up now". Sent PDFs are never
  touched.
- Each session carries review details: lane, deployed version, commit, reviewer
  (pre-filled with the Mac user) and a free note. They persist in session.json and
  are inherited by the next session, so a review run is typed once.
- PDF file names are Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf, and every page
  carries a two-line reference footer (tool, build time, session / lane, deployed
  build, commit, reviewer, note). The PDF document info carries the same values in
  Author and Keywords.
- Verification: 159 tests, a headless panel self-test, and a LaunchServices-driven
  end-to-end run that types and clicks the real panel.
2026-10-31 11:32:54 +04:00
Claude Fable 5 542aad296b wip: handover snapshot 20261014 — dirty-state preservation 2026-10-14 23:25:22 +04:00
Claude Fable 5 fd621608b0 release: v0.4.0 2026-10-11 14:01:36 +04:00
kua-agent 01252b90da Merge pull request 'Redline: past submissions list + start-new-session with 10-session retention (MMDB-2925)' (#29) from feat/redline-sessions-history-20261011 into main 2026-10-11 10:01:23 +00:00
Claude Fable 5 0506ce04e9 fix(sessions): re-review fixes for MMDB-2925 (PR #29 review round 2)
Round 2 of adversarial review confirmed defects 2,3,4,5,7 fixed and
raised three new ones; all three are fixed here, plus the guard-message
nit.

NEW-1 (the FAIL driver): the OneDrive send path overwrote the truthful
status from handleDidShareItems with its own success text, silently
dropping an archive failure and any state-refresh problem. The seam now
takes the caller's success summary and composes ONE truthful message:
summary (the share itself did complete) + archive error if any + refresh
problems if any. Both callers (AirDrop delegate, OneDrive) pass their
summary; the OneDrive text is never clobbered.

NEW-2: if the replacement open session could not be created after the
archive rename (disk full), the store kept reporting the already-archived
session as the open one. SpoolStore now has a truth guard
(ensureOpenSession): the open session is verified to really exist on disk
and be in state .open before any read/mutate; a stale one is replaced by
a genuinely fresh session, or the call fails loudly. Never a lie.

NEW-3: archivedSessions() read the folder tie-break dates AFTER
reconciliation, so a healed same-second session could bump its own
modification date and outrank a genuinely newer peer. The dates are now
read BEFORE reconciling.

Nit: the startNewSession guard now reports "A new session is already
being started." when the refusal is about a concurrent session start,
not a send.

Also added REDLINE_SELFTEST_PHASE=sendtruth (mirroring the existing
=onedrive escape hatch) so the SEND-TRUTH selftest can run without the
picker chain's display-dependent REGION-PERSIST phase.

Evidence: 136 swift tests pass (2 new: OneDrive summary survives
archiving; stale open session never returned as current).
REDLINE_SELFTEST_PHASE=sendtruth -> SEND-TRUTH PASS.
REDLINE_SELFTEST_PHASE=onedrive -> ONEDRIVE-SELFTEST PASS against the
real OneDrive sync root.
2026-10-11 13:58:45 +04:00
Claude Fable 5 eaa5bd5884 fix(sessions): adversarial-review fixes for MMDB-2925 (PR #29 review round 1)
Review verdict FAIL raised 7 defects; this addresses 1-5 and 7. 6 is
accepted as-is (see below).

1. Retention failure after a COMPLETED archive no longer throws: a failed
   prune is logged loudly with the exact path and otherwise ignored, so a
   successful send can never be reported as "The screenshot could not be
   saved". The visible symptom of a failed prune is simply more than 10
   sessions listed.
2. handleDidShareItems now refreshes the current session AND the
   past-submissions list from the store on both the success and the
   failure path (previously the menu count and any open window went stale
   after every send). Any refresh problem is appended to the status line.
3. "Start new session" and send() now guard against each other
   synchronously before their first await (isStartingNewSession flag on
   both sides), instead of relying on the SwiftUI .disabled state alone —
   a queued Task could otherwise rename the session directory out from
   under an in-flight PDF compose.
4. Contract decision, documented in code: session retention prunes the
   whole session folder INCLUDING removed/ parked captures. That is the
   requested retention policy ("retain the past 10 sessions"), and the
   D-11 never-delete note on remove() now says so explicitly.
5. Session ordering tie-break chain extended: manifest createdAt, then the
   folder creation date, then the folder content-modification date, then
   the id — so retention stays on real creation order even on a volume
   that reports no creation date.
7. The PDF button's help text now distinguishes never-sent from
   sent-but-no-longer-on-disk (the button was already disabled in both).

6 (empty close leaves the old empty spool/ folder behind) is left exactly
as the pinned SpoolStoreTests contract has it (startNewSession test 16
asserts the folder remains); it is pre-existing behavior, harmless (the
store reconciles and picks the newest candidate), and out of scope here.

Tests: 2 new app-target regression tests (send refreshes past
submissions; start/send refuse to overlap) — 134 tests pass.
2026-10-11 13:48:31 +04:00
Claude Fable 5 6ab398c3f2 feat(sessions): past submissions list + start-new-session with 10-session retention
MMDB-2925. Two new menu functions in the Redline app:

- "Start new session" keeps the current screenshots as a past session
  (moved into the single archive/ folder — never deleted on close) and
  opens a fresh empty session. Sessions closed without ever sending keep
  pdfFileName nil and show as "Not sent" in the list.
- "Past submissions…" opens a window listing every retained session
  (timestamp, page count, what was sent) with actions to reveal the sent
  PDF and the session's screenshot folder.

Retention (Ben's rule 2026-10-11: "retain the past 10 sessions"): both
archive paths (send and close) keep the newest 10 archived session
folders in archive/ and remove the rest. Any PDF a pruned session
produced is untouched — it lives in the outbox/OneDrive folder.

archivedSessions() ordering now tie-breaks same-second sessions by the
session folder's creation date, so listing and pruning are deterministic
(manifest timestamps are whole-second ISO8601 — format pinned in
AtomicFileTests).

Tests: 6 core tests in SessionRetentionTests (close/keep/reconcile,
sent-vs-unsent, retention of 10, explicit prune, send-path retention) and
3 app-target tests in SessionWorkflowTests driving the real AppModel menu
actions through AppDelegate.makeLaunchModel(). PanelSnapshot renders the
new window as panel-06b-past-submissions.png.
2026-10-11 13:35:38 +04:00
kua-agent 2a3af20d04 Merge pull request 'release: Redline 0.3.2 (MMDB-2697)' (#28) from release/0.3.2-20260905 into main 2026-09-05 07:17:58 +00:00
Claude Fable 5 ae7fb8ee87 release: v0.3.2 2026-09-05 11:16:28 +04:00
kua-agent 821e113f34 Merge pull request 'Redline: timestamped result for the manual update check, update-state renders, and a duplicated-status fix (MMDB-2697)' (#27) from feat/check-updates-feedback-20260905 into main 2026-09-05 07:15:15 +00:00
Claude Fable 5 942e848dde test(update-checker): rewrite tests to exercise real production code
REPLACED: three worthless tests that only tested test code, not production:
- statusMessageUpToDateFormat built the expected string locally and matched it
- statusMessageUpdateReadyFormat same self-referential test
- statusChannelsAreIndependent was literally #expect(true, ...)

ADDED: four real tests that drive production code:
- dubaiTimeCheckTimeFormat: assert DubaiTime.checkTime() formats as HH:MM Dubai
- manualCheckUpToDateIncludesTimestamp: inject stub appcast via testAppcastJSON seam,
  drive UpdateChecker.checkNow(manual: true), verify statusMessage matches exact format
- automaticCheckUpToDateLeavesMessageNil: verify automatic check (manual: false) leaves
  statusMessage nil when up-to-date
- statusChannelsAreIndependent: construct real AppModel via AppDelegate.makeLaunchModel(),
  assert setStatus() does NOT affect updateStatusMessage, setUpdateStatus() does NOT
  affect statusLine, and vice versa. PROVES the defect is caught: test fails with 3 issues
  if updateStatusMessage is reverted to an alias of statusLine.

ADDED: testAppcastJSON seam to UpdateChecker for test injection of appcast data.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:13:55 +04:00
Claude Fable 5 905a019823 fix(app-model): separate status channels — update messages no longer hide capture summary
Root cause: updateStatusMessage was an alias to statusLine, so update feedback appeared
both in the header (where capture summary belongs) and footer (intended). Both MenuBarView
header and footer rendered the same value, creating duplication and information loss.

Fix: introduce updateStatus property separate from statusLine. Route UpdateChecker.statusMessage
into setUpdateStatus(), not setStatus(). Header now shows capture summary uninterrupted;
footer-only shows update feedback. Both channels now independent.

- Add public updateStatus property to AppModel
- Add setUpdateStatus() mutator
- Change updateStatusMessage property to return updateStatus instead of statusLine
- Route onChecked callback to setUpdateStatus, not setStatus
- Update PanelSnapshot helper to use setUpdateStatus
- Add test asserting channel independence

Panel-12 and panel-13 now render correctly: capture summary in header, update status only
in footer; no duplication or information loss.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:05:14 +04:00
Claude Fable 5 e71c2e7c91 feat(panel-snapshot): add five offscreen panels for update states
Render panels 10-14 showing the update check states:
- panel-10-update-idle: menu with 3 captures, no update available
- panel-11-update-checking: same as 10, but row reads "Checking..."
- panel-12-update-uptodate: footer status shows "Redline X.Y.Z is up to date, checked 10:42 Dubai"
- panel-13-update-staged: row "Update to 9.9.9" present, footer status "Update to 9.9.9 is ready"
- panel-14-update-revert: row "Revert to 0.2.0" present

All five panels driven by model state only; never touch real appcast or UserDefaults.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:01:28 +04:00
Claude Fable 5 169dd2b32c test(update-checker): verify status message formats for manual checks
- Test DubaiTime.checkTime formats as HH:MM Dubai
- Test "Redline X.Y.Z is up to date, checked HH:MM Dubai" format
- Test "Update to X.Y.Z is ready" format

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:01:23 +04:00
Claude Fable 5 7cdc3e7652 feat(update-checker): give manual checks visible, timestamped feedback
- Manual check finds no newer version: status message becomes "Redline X.Y.Z is up to date, checked HH:MM Dubai"
- Manual check stages a newer version: status message becomes "Update to X.Y.Z is ready"
- Automatic (scheduled) checks keep original silent behaviour when up to date
- Add snapshot-only seams for testing: snapshotPreviousVersionOverride and snapshotUsesPreviousVersionOverride

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:01:20 +04:00
Claude Fable 5 a0ff61ae14 feat(dubai-time): add checkTime formatter for HH:MM Dubai timestamps
Manual update checks now display the time checked in Dubai timezone.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 11:01:15 +04:00
kua-agent c3cae010a4 Merge pull request 'release: Redline 0.3.1 (MMDB-2631 + MMDB-2681 on one feed)' (#26) from release/0.3.1-20260905 into main 2026-09-05 06:48:04 +00:00
Claude Fable 5 33e3441580 release: v0.3.1 2026-09-05 10:42:44 +04:00
kua-agent eb1af5bf18 Merge pull request 'Redline: OneDrive folder transport as alternative to AirDrop (MMDB-2631)' (#23) from feat/redline-onedrive-transport-20260905 into main
Merge pull request #23: Redline: OneDrive folder transport as alternative to AirDrop (MMDB-2631)
2026-09-05 06:17:29 +00:00
Claude Fable 5 49c6a41033 release: v0.3.0 2026-09-05 10:16:39 +04:00
Claude Fable 5 706726a3d4 fix(test): LaunchWiringTests was empirically vacuous for the makeLaunchModel path
The reviewer patched main.swift back to FolderSettings.resolvedAppSupportPaths()
(the AirDrop-only resolver) and `swift test --filter LaunchWiringTests` STILL
PASSED, because the only thing the test asserted — model.watchFolderURL — is
computed independently by AppModel.init() via TransportSettings.effectiveFolders(),
not from the `paths` makeLaunchModel() built. bootstrap()'s own unconditional
updateWatchFolder reconcile then papered over the reverted resolver, so the
test only ever proved the bootstrap reconcile, never the launch resolver
itself. The "verified this catches the blocker" claim in the previous
commit was empirically false.

Fix: added ReturnWatcher.currentWatchFolder (public var, actor-isolated —
the folder a watcher is CURRENTLY seeded to scan, readable without calling
scanNow()/updateWatchFolder first). The test now asserts, BEFORE
bootstrap() runs: model.paths.watchFolder/outbox (already internal-visible
via @testable import, no production API change needed there) equal the
OneDrive folder, AND the watcher's currentWatchFolder equals it too — both
of which genuinely depend on what makeLaunchModel() built.

Verified properly this time (both outputs below are verbatim from
`swift test --filter LaunchWiringTests`, main.swift's makeLaunchModel()
temporarily reverted to FolderSettings.resolvedAppSupportPaths() then
restored — the revert itself is not part of this commit):

FAILURE (reverted resolver):
    Expectation failed: (model.paths.watchFolder.path -> "/Users/benjaminhippler/Downloads")
      == (oneDriveFolder.path -> ".../shotdeck-real-wiring-onedrive-<uuid>")
    Expectation failed: (model.paths.outbox.path -> "/Users/benjaminhippler/Desktop")
      == (oneDriveFolder.path -> ".../shotdeck-real-wiring-onedrive-<uuid>")
    Expectation failed: (seededWatchFolder.path -> "/Users/benjaminhippler/Downloads")
      == (oneDriveFolder.path -> ".../shotdeck-real-wiring-onedrive-<uuid>")
    Test ... failed after 0.324 seconds with 3 issues.

PASS (resolver restored):
    Test "Real wiring: AppDelegate.makeLaunchModel() + AppModel.bootstrap()
      detect a marked OneDrive return" passed after 0.295 seconds.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 10:10:14 +04:00
Claude Fable 5 e1f569cc3e fix(core): probeWritable(at:) always cleans up the probe file, even on partial failure
Two leak paths: (a) AtomicFile.write renames the temp file onto the probe
path and THEN fsyncs the containing directory — if that last fsync throws,
the probe file already exists on disk but the old code returned false
without ever attempting removal; (b) if the explicit removeItem call itself
threw, there was no retry, so a transient File Provider removal failure left
the file behind permanently.

Fix: an unconditional `defer` now checks fileExists and retries removeItem
regardless of which branch returned early. The function only reports true
when the explicit write, fsync (inside AtomicFile.write), AND removal all
succeeded AND the file is confirmed gone afterward.

New test: a FileManager subclass whose removeItem(at:) throws on its first
call (AtomicFile.write itself never touches this injected FileManager — it
uses raw Darwin/POSIX calls, not FileManager, so this only intercepts the
explicit removal + the defer's retry) asserts the function returns false AND
no probe file remains — verified this actually needs the defer by
temporarily removing it and confirming the same test then fails with a
leftover ".redline-probe-<uuid>" file (see this branch's history for the
discarded revert). The directory-fsync failure path has no injectable seam
(raw fsync(2) on an already-open fd, not parameterized by any FileManager or
other substitutable dependency, and not reproducible via chmod or other
standard test techniques) — documented in the test rather than simulated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 10:10:00 +04:00
kua-agent 4da02e243f Merge pull request 'release: Redline 0.3.0 (MMDB-2681)' (#25) from release/0.3.0-20260905 into main
Merge pull request #25: release Redline 0.3.0 (MMDB-2681)
2026-09-05 06:08:59 +00:00
Claude Fable 5 8b53a727e3 release: v0.3.0 2026-09-05 10:07:53 +04:00
Claude Fable 5 fdec105174 release: empty keychain-args array must not trip set -u on macOS bash 3.2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:07:52 +04:00
kua-agent 12128b016d Merge pull request 'Redline updater hardening: signed-update verification, atomic install + revert, update visibility, notarization pipeline (MMDB-2681)' (#24) from feat/updater-hardening-20260905 into main
Merge pull request #24: Redline updater hardening (MMDB-2681)
2026-09-05 06:07:05 +00:00
Claude Fable 5 a32cd03581 review: refuse to publish a bundle without a team identifier; document the allowed-teams override
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:06:57 +04:00
Claude Fable 5 8a12ed0a54 release: NOTARIZED is 0/1, compare numerically
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:03:48 +04:00
Claude Fable 5 bfdc6fde9d release: spctl gate only hard-fails when the build was notarized
Un-notarized fallback builds (Apple Development identity) are rejected by
spctl by design; the script must still publish them with a warning, otherwise
the fallback path can never release.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:03:40 +04:00
kua-agentandClaude Fable 5.1 9884c844d4 release: publish-update.sh — resolve a real signing identity, notarize, record it in the appcast
SIGN_IDENTITY now comes from REDLINE_SIGN_IDENTITY, else the first
"Developer ID Application" identity in the keychain (REDLINE_KEYCHAIN adds
--keychain everywhere it's searched/used), else the existing Apple
Development identity with a loud WARNING that Gatekeeper will block first
install elsewhere. build-app.sh still has to sign first with its own
hardcoded Apple Development identity (that pair is what keeps the Screen
Recording grant alive) — this script now re-signs the resulting bundle with
the resolved identity, --options runtime --timestamp, before zipping.

Notarization is optional: set REDLINE_NOTARY_PROFILE (a notarytool
keychain profile) or all three of REDLINE_NOTARY_KEY_ID/_ISSUER/_KEY_PATH,
and after the zip is built the script submits it, waits, and on Accepted
staples Redline.app, rebuilds the zip and DMG from the stapled app (a new
build_dmg() that ditto-copies whatever is already at .build/Redline.app
rather than re-invoking make-dmg.sh, which would rebuild from source and
strip both the resolved signature and the staple), staples the DMG, and
requires `spctl -a -vv -t exec` to say "accepted" or the script aborts.
Absent notary config: prints NOT NOTARIZED and continues exactly as before.

appcast.json gains "notarized" and "teamIdentifier" (from codesign -dv);
confirmed UpdateChecker's Appcast Decodable already ignores unknown JSON
keys (verified with a standalone decode), so no app-side change was needed
for old appcasts to keep working. Ends with a summary block: identity used,
notarized yes/no, spctl verdict, team, sha256. --test dry-run behaviour
(upload to .../test/, skip the git commit) is unchanged.

Known gap, out of scope here: build-app.sh's own pre-sign step still hard-
requires its hardcoded Apple Development identity in the keychain even when
a Developer ID identity is what will actually ship — untouched per the task
boundary (this file only).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:00:41 +04:00
kua-agentandClaude Fable 5.1 365220ade8 test: extend UPDATE-SELFTEST — reject-unsigned, staged-signed, atomic-install, revert
Same fake-99.0.0-bundle setup as before, but now drives it through the
hardened UpdateChecker end to end, in-process:

(a) reject-unsigned — the fake bundle, copied then plist-edited without
    re-signing (editing Info.plist after copy invalidates the inherited
    signature on its own — nothing stripped by hand), must be rejected by
    checkNow(): updateAvailable stays nil and statusMessage is the exact
    "Update is not signed by MMD" text.
(b) staged-signed — codesign --force --deep --sign the same bundle
    (SHOTDECK_SELFTEST_SIGN_IDENTITY or the default Apple Development
    identity), re-zip, re-serve the same appcast path; must now stage.
(c) atomic-install — installStaged into a throwaway <tmp>/Applications
    (never real /Applications) pre-populated with a copy of the actually
    running app; asserts the target lands on 99.0.0, Redline.app.previous
    holds the original version, and no replacement-directory cruft is left
    beside them.
(d) revert — revertToPrevious swaps the rollback copy back in; asserts the
    target is back to the original version and .previous now holds 99.0.0.

Caught a real bug while wiring (d): replaceItemAt(target, withItemAt:
previousURL, backupItemName: "Redline.app.previous") self-clobbers, because
the backup name and the withItemAt source resolve to the same path — the
backup write lands before the swap ever reads it, so target ends up
unchanged. Fixed in UpdateChecker by staging previousURL through a throwaway
ditto copy first (same pattern installStaged already used).

Every existing phase (PICKER-SELFTEST, REGION-PERSIST, SEND-TRUTH, and the
final "UPDATE-SELFTEST PASS version=99.0.0") is unchanged and still prints.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:00:28 +04:00
kua-agentandClaude Fable 5.1 064e410e30 feat: surface check/revert/version in the menu and badge the icon
AppModel exposes appVersion, previousVersion, isCheckingForUpdates and
updateStatusMessage (an alias for the existing statusLine plumbing — one
status channel, not a new one), plus checkForUpdates() and
revertToPreviousVersion() wired to the hardened UpdateChecker.

Menu gains, in order: "Update to X" (unchanged, staged-only), "Check for
updates" (labelled "Checking…" and disabled mid-check), "Revert to <version>"
(only when a rollback copy exists), then the existing rows unchanged, then a
non-interactive footer "Redline <version>" with the status line under it —
same caption/secondary styles already used elsewhere in the file, no new
tokens.

Menu-bar icon gets a small badge while an update is staged: uses the SF
Symbol's own ".badge" variant when one exists for the current icon, otherwise
overlays a small dot on the plain symbol. Reads live model state, so the
badge disappears on its own once the offer clears.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:00:17 +04:00
kua-agentandClaude Fable 5.1 a79a569a7d feat: updater hardening — timeouts, signature verification, atomic install+rollback
30s/600s URLSession timeouts on the update session (was 15s/15s, too tight for
a real zip download). Every staged and installed payload is now verified with
the Security framework (SecStaticCodeCheckValidityWithErrors, strict + all
architectures + nested code) against bundle id ai.flowmaster.shotdeck and an
allowed-team set (PWMCBMX5M8, L3N9S54CN3; overridable via REDLINE_ALLOWED_TEAMS
for the self-test only) — an unsigned or wrongly-signed update is discarded
before checkNow ever offers it, and installStaged re-verifies what actually
landed on disk as defense in depth.

installStaged is now atomic: ditto into an itemReplacementDirectory, then
FileManager.replaceItemAt swaps it into place, keeping exactly one
Redline.app.previous rollback copy (older ones are dropped first). Added
revertToPrevious(target:) to swap that copy back in (itself reversible — the
replaced version becomes the new .previous), and previousVersion(target:) to
read its CFBundleShortVersionString. Relaunch is now a detached
"wait for this PID to exit, then open -n" shell handoff instead of a
synchronous open+terminate, so there is never a moment with two instances
running. checkNow(manual:) now says "Redline X is up to date." when the user
asked directly, and exposes isCheckingNow/lastCheckedAt for the UI.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 10:00:10 +04:00
kua-agentandClaude Fable 5.1 3abb8dc6ca test: add ShotdeckTests target — real launch/bootstrap wiring regression (coverage gap)
The Core-level regression tests added for the launch-paths BLOCKER
(ReturnWatcherTests.swift) hand-replicate what AppDelegate.makeLaunchModel()
and AppModel.bootstrap() do, rather than calling them — a future revert of
either would not fail `swift test`. Neither lives in ShotdeckCore, so
ShotdeckCoreTests cannot reach them; this new test target depends on the
Shotdeck executable target itself and uses @testable import (confirmed this
works cleanly with SwiftPM despite Shotdeck's main.swift top-level-code entry
point — no separate main-symbol conflict).

realLaunchModelAndBootstrapDetectAMarkedOneDriveReturn persists
transport=.oneDrive (UserDefaults.standard, snapshot-and-restore — the same
established pattern PickerSelfTest's ONEDRIVE-SELFTEST phase already uses,
since neither of these real call sites has any defaults-threading to plug an
isolated suite into), calls AppDelegate.makeLaunchModel(appSupportRoot: <temp>)
and awaits model.bootstrap() UNMODIFIED, then drops a marked-up Redline PDF
into the temp OneDrive folder and asserts the watcher reports it.

Verified this test actually catches the original blocker: temporarily
reverted makeLaunchModel() to the AirDrop-only resolver, and separately
reverted bootstrap()'s updateWatchFolder reconcile — both reproduce the
failure (the discarded revert is not part of this commit).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:55:31 +04:00
kua-agentandClaude Fable 5.1 8d68c836cd test(selftest): ONEDRIVE-SELFTEST sub-step 1c — toggle immediately followed by Send
Adds a third rapid-toggle assertion alongside the existing folder-reconcile
check: chooseTransport(.airDrop) immediately followed by
chooseTransport(.oneDrive), with NO sleep, then an immediate send(anchor: nil)
— proving send() correctly awaits the pending reconcile Task
(SendController.swift/AppModel.swift in this series) rather than racing
ahead with a stale recordUncommented flag. Asserts the freshly-sent,
still-unmarked PDF is never itself reported as an already-returned document.

Also updates composePDFForSend's call site for its new transport: parameter.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:55:22 +04:00
kua-agentandClaude Fable 5.1 04d1e73532 fix: store pendingReconcileTask handle; skip real Carbon hotkey binding on self-test runs
AppModel gains pendingReconcileTask (the most recent watcher-reconcile Task
spawned by chooseTransport/chooseOneDriveFolder), which send() now awaits —
see the SendController.swift commit in this series. chooseTransport/
chooseOneDriveFolder store their Task's handle into it instead of firing an
untracked `Task { }`.

bootstrap() now also skips binding the real, process-wide Carbon global
capture hotkey on the same env-var-flagged self-test/headless runs that
already skip the update-check schedule (PickerSelfTest's phases,
PanelSnapshot, and the new ShotdeckTests launch-wiring regression test).
Real Carbon hotkey registration is not safe to exercise in an automated test
process — it can collide with ShotdeckCoreTests' own
HotkeyCenterCarbonTests running in the same test binary — and bootstrap()'s
hotkey step had never actually been exercised by any self-test before (none
of them call bootstrap() directly) until the new real-wiring test in this
series does. A real user launch never sets these env vars, so production
behavior is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:55:16 +04:00
kua-agentandClaude Fable 5.1 d7984add2d fix: send() probes real writability before composing; write/rename failures map to oneDriveFolderUnavailable
send()'s OneDrive pre-flight check now also calls OneDriveLocator.probeWritable(at:)
alongside isWritableDirectory — closing the File Provider edge case where a
signed-out OneDrive domain reports its folder as existing and writable while
a real write fails.

composePDFForSend(outbox:transport:) now takes the frozen transport too (not
just the folder): a write/rename failure specifically at the destination
folder — Darwin.rename, AtomicFile.fsyncDirectory, or the post-write
existence check — is reported as ShotdeckError.oneDriveFolderUnavailable
instead of the generic pdfCompositionFailed when transport is .oneDrive.
composer.compose()'s own session/image-content failures are left as generic
pdfCompositionFailed regardless of transport — those aren't about the
destination folder.

Also: send() now `await`s `pendingReconcileTask` (AppModel.swift, set by
chooseTransport/chooseOneDriveFolder in SettingsView.swift) before
snapshotting transport/folder, closing the toggle-then-immediate-send race —
without this, a Send issued right after a transport toggle could run before
the watcher's recordUncommented flag finished catching up.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:55:08 +04:00
kua-agentandClaude Fable 5.1 723cd7dcea fix(core): File Provider write probe — OneDriveLocator.probeWritable(at:)
isWritableDirectory (permissions bits) is not enough: a OneDrive
Files-On-Demand directory whose provider domain is signed out can report as
existing and POSIX-writable while an actual write fails. probeWritable
writes a small ".redline-probe-<uuid>" file into the folder via
AtomicFile.write (open+write+fsync+rename+directory-fsync), then removes it;
any failure at write, fsync, or removal means false.

Three unit tests: an ordinary writable directory (true, and no probe file
left behind), a chmod 500 directory (false; permissions restored in
teardown), and a plain file path (false).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:54:58 +04:00
kua-agentandClaude Fable 5.1 70231574c9 test: launch-paths BLOCKER regression + isWritableDirectory unit tests
ReturnWatcherTests.swift: two new tests bracket the BLOCKER fix — one
characterizes the old bug (FolderSettings.resolvedAppSupportPaths(), AirDrop-
only, ignores the persisted OneDrive transport; the watcher ends up watching
a stale isolated folder and misses a marked PDF dropped into the real
OneDrive-mode folder), the other proves the fix (the exact launch/bootstrap
construction — TransportSettings.resolvedAppSupportPaths() +
watcher.updateWatchFolder() before start — detects it). Both isolated to
temp dirs, including an explicit FolderSettings watch-folder override so the
"bug" test's found.isEmpty assertion never depends on what's actually in
Ben's real ~/Downloads (it does, in fact, already contain real marked-up
Redline PDFs from prior testing — an earlier version of this test read the
REAL Downloads folder and failed for exactly that reason).

TransportSettingsTests.swift: three tests for
OneDriveLocator.isWritableDirectory — true for an ordinary directory, false
for one chmod'd 500 (permissions restored in teardown before removal), false
for a plain file and for a nonexistent path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:28:17 +04:00
kua-agentandClaude Fable 5.1 8121738188 fix: MINOR — ONEDRIVE-SELFTEST resolves the real sync root at runtime; adds relaunch + rapid-toggle sub-steps
realOneDriveSyncRoot was a hardcoded /Users/benjaminhippler/... literal.
Now resolved via OneDriveLocator.syncRoots().first at runtime (MMD-named
root still preferred, matching production); when no OneDrive sync root
exists at all, prints "ONEDRIVE-SELFTEST SKIP no OneDrive sync root" and
exits non-zero — never a false PASS.

Adds two sub-steps to the same phase, both required by the BLOCKER fix's
review: (1) rapid transport toggling (chooseTransport(.airDrop) immediately
followed by chooseTransport(.oneDrive)) must still end with the watcher
watching the OneDrive folder — proves the generation-guarded reconcile in
SettingsView.swift really lets the last choice win. (2) relaunch simulation
— OneDrive still persisted from sub-step 1, a FRESH model built via the
exact same AppDelegate.makeLaunchModel() function real launch uses (now
internal + an appSupportRoot override for this purpose, temp-rooted so this
never touches the real ~/Library/Application Support/Shotdeck), bootstrapped,
then a PDF marked up in place — the relaunched watcher must report it. This
is the exact BLOCKER scenario the review flagged, proven end to end.

Factored the ink-annotation and unmarked-PDF-writing code into
addInkMark(to:)/writeUnmarkedRedlinePDF(to:) so both new sub-steps and the
original markup check share it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:28:08 +04:00
kua-agentandClaude Fable 5.1 6484fde530 fix: refuse transport changes mid-send; generation-guard rapid toggling; one-line "not found" row
MAJOR: chooseTransport/chooseOneDriveFolder now refuse (status "Finish the
current send first.") while isSending is true, closing off the send-vs-
transport-switch race at the UI entry point (SendController.swift's commit
in this same series is the structural fix underneath).

MINOR: both functions spawned unstructured `Task { }` calls to
watcher.setRecordUncommented/updateWatchFolder; rapid toggling could apply
an earlier, superseded call's folder/flag after a later one had already won.
Fixed with a monotonically increasing `reconcileGeneration` counter
(AppModel.swift) bumped synchronously before each Task starts; the Task
checks its own snapshot against the live value before every mutating step
(not just once via Task.isCancelled), so the LAST choice always wins.
Verified via ONEDRIVE-SELFTEST's new rapid-toggle sub-step (this branch's
PickerSelfTest.swift commit), which proves the watcher ends up watching the
folder from the last chooseTransport call.

Design fix (Ben, panel-08 review): the "No OneDrive folder found — sign in to
OneDrive or choose a folder." value text wrapped over four lines, making that
row tall and ragged next to Choose…. The value column now reads exactly "Not
found" (secondary colour, one line, same as the truncated-path style), and
the explanation moves to the caption below: "No OneDrive folder found. Sign
in to OneDrive, or choose a folder." When a folder IS resolved the caption is
unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:27:58 +04:00
kua-agentandClaude Fable 5.1 bd11ba96c5 fix: MAJOR — send() race between concurrent transport switch and an in-flight send
Two issues: (1) directoryExists(at:) only checked existence + isDirectory, so
an existing-but-unwritable OneDrive folder skipped the
oneDriveFolderUnavailable branch and surfaced as a generic pdfCompositionFailed
message instead — now uses OneDriveLocator.isWritableDirectory(at:). (2)
send() read `self.outboxURL` again inside composePDFForSend() after at least
one await had already run, so a concurrent chooseTransport() call
(SettingsView.swift) could flip transport/outboxURL/recordUncommented
mid-send, landing the PDF under one transport's folder while the
archive/status branch ran the other's.

Fix: send() now snapshots BOTH transport and the destination folder into
local `let`s once, before any await, and passes the folder explicitly into
the renamed composePDFForSend(outbox:) — which no longer reads
self.outboxURL at all. The archive/status switch already used the frozen
`transport` local. (chooseTransport/chooseOneDriveFolder additionally refuse
outright while isSending is true — see the SettingsView.swift commit — so in
practice this race can no longer even be triggered, but the snapshot is the
actual structural fix regardless.)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:27:49 +04:00
kua-agentandClaude Fable 5.1 ef0d8712f7 fix: BLOCKER — launch model uses transport-aware paths; bootstrap reconciles watcher folder unconditionally
AppDelegate.makeLaunchModel() built `paths` via the AirDrop-only
FolderSettings.resolvedAppSupportPaths(), so ReturnWatcher's internal
watchFolder (seeded from paths.watchFolder in its own init) was the AirDrop
folder even when OneDrive was the persisted transport, and bootstrap() never
reconciled it before starting. Net effect: on every relaunch with OneDrive
selected, PDFs went to OneDrive but FSEvents kept watching the stale AirDrop
folder for the whole session — marked-up returns were never detected.

Fix: makeLaunchModel() now calls TransportSettings.resolvedAppSupportPaths()
(single source of truth for the transport-folder mapping); made internal
(not private) with an optional appSupportRoot override so
PickerSelfTest's relaunch-simulation sub-step can call the exact same
function against a temp root instead of the real Application Support folder.
bootstrap() now unconditionally calls watcher.updateWatchFolder(watchFolderURL)
before watcher.start() (belt-and-suspenders reconciliation, even though the
paths fix alone already makes this a no-op in the normal case), and sets
recordUncommented before start as it already did.

Regression tests proving this land in the same PR (ReturnWatcherTests.swift):
one characterizing the old bug's exact construction still missing a marked
OneDrive-mode return, one proving the fixed launch-construction path detects
it end to end. The ONEDRIVE-SELFTEST phase also gains a relaunch sub-step
using this same makeLaunchModel() function.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:27:42 +04:00
kua-agentandClaude Fable 5.1 20de467e87 fix(core): transport-aware launch paths + writable-folder check (adversarial review)
BLOCKER fix, Core half: adds TransportSettings.resolvedAppSupportPaths(),
the transport-aware equivalent of the AirDrop-only
FolderSettings.resolvedAppSupportPaths() — launch code must use this one so
the ReturnWatcher it feeds is never seeded with a stale AirDrop folder while
OneDrive is the persisted transport. Both now share a single
AppSupportPaths.standardRoot() helper for the ~/Library/Application
Support/Shotdeck root, instead of computing it three separate times.

MAJOR fix, Core half: adds OneDriveLocator.isWritableDirectory(at:) — exists
+ isDirectory is not enough; an existing-but-unwritable folder (permissions
revoked) must be treated as unavailable, not silently attempted and surfaced
as a generic PDF-composition failure.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:27:32 +04:00
kua-agentandClaude Fable 5.1 209921f084 feature: model-owned resolvedOneDriveFolder + OneDrive Settings/menu panel snapshots
SettingsView's OneDrive row called OneDriveLocator.resolveOneDriveFolder()
directly with the real UserDefaults.standard and the real home directory,
which made that row impossible to drive from a fake/isolated environment.
Moved that resolution into AppModel as a tracked resolvedOneDriveFolder
property (nil means "no OneDrive folder found"), refreshed at init,
bootstrap, chooseTransport, chooseOneDriveFolder, and inside send()'s live
folder check. SettingsView and chooseOneDriveFolder's picker-start path now
read model.resolvedOneDriveFolder instead of calling OneDriveLocator
directly — state flows through the model like everything else in this app.

PanelSnapshot (SHOTDECK_SNAPSHOT_DIR) adds three panels on a SEPARATE
isolated model so the transport switch never bleeds into the six existing
AirDrop-mode panels:
- panel-07-settings-onedrive.png: transport=oneDrive with a resolved folder,
  built by pointing OneDriveLocator.defaultRedlineFolder at a fake home tree
  (Library/CloudStorage/OneDrive-MMDGROUP under this snapshot's own temp
  root) so the displayed path is shaped like the real default without ever
  touching the real home.
- panel-08-settings-onedrive-missing.png: a fake home with no
  Library/CloudStorage at all, resolved through a throwaway UserDefaults
  suite (never .standard) so the "no OneDrive folder found" state and its
  still-usable Choose... button are exercised for real.
- panel-09-captures-present-onedrive.png: 3 captures + transport=oneDrive,
  confirming the menu row reads "Send to OneDrive".

Extracted the 3-swatch capture seeding (panel 04) into addSampleCaptures(to:)
so panel 09 reuses it instead of duplicating the loop.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:10:59 +04:00
kua-agentandClaude Fable 5.1 2937d2d5e0 fix: correct recordUncommented test names (were misspelled "commended")
Two @Test descriptions and function names in ReturnWatcherTests.swift used
"recordUncommended" (commended, as in praised) instead of "recordUncommented"
(commented, as in has a comment) — a typo introduced when the tests were
added. The actual public API (ReturnWatcher.recordUncommented,
setRecordUncommented) was already spelled correctly everywhere; only these
two test names/descriptions needed fixing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:10:43 +04:00
kua-agentandClaude Fable 5.1 80a128b667 selftest: ONEDRIVE-SELFTEST phase, proven against the real OneDrive sync root
New phase chained after UPDATE-SELFTEST (so a full SHOTDECK_PICKER_SELFTEST
chain now prints all five PASS lines) and also runnable standalone via
REDLINE_SELFTEST_PHASE=onedrive, since the harness has no other per-phase
selector.

Points TransportSettings at a NEW "Redline-selftest-<Dubai timestamp>" folder
under the real /Users/.../OneDrive-MMDGROUP sync root (never a fake home tree
— that proves the transport against the actual OneDrive file provider), drives
a seeded session through the OneDrive branch of send(anchor: nil), asserts the
PDF landed, the session archived, and the status starts with "Saved to
OneDrive", then confirms the watcher does NOT report the fresh unmarked PDF
as returned. It then adds a real PDFKit ink annotation to that PDF in place —
what the iPad does — saves it, and confirms the watcher now reports it as
commented. Prints "ONEDRIVE-SELFTEST PASS path=<folder>". Never deletes
anything under OneDrive; the created folder and PDF are left in place.

UserDefaults.standard's transport/oneDriveFolder keys are snapshotted and
restored around the phase, the same pattern runRegionPersistPhase already
uses for CaptureRegion — there is no separate defaults-suite threading
through AppModel/send(), so this is the only way to drive the real send()
path without leaving the real app pointed at the selftest folder afterward.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:01:29 +04:00
kua-agentandClaude Fable 5.1 78cc7d5b1a test: OneDrive transport settings/locator unit tests + ReturnWatcher recordUncommended coverage
TransportSettingsTests: default airDrop, set/get round-trip, garbage stored
value falls back to airDrop, oneDriveFolder store/reset, effectiveFolders for
both transports, oneDriveFolderUnavailable's errorDescription contains the path.

OneDriveLocatorTests: fake home tree under Library/CloudStorage — syncRoots
returns only real OneDrive-* directories (ignores a same-named plain file and
a GoogleDrive-* one), MMD-named root sorts first; no CloudStorage dir means
empty roots and a nil defaultRedlineFolder; resolveOneDriveFolder prefers an
existing stored override and falls back to the default when the stored path
no longer exists. All against temp dirs, never the real home.

ReturnWatcherTests: recordUncommended defaults to true and still records an
unmarked PDF (existing AirDrop tests are unaffected); with it set false, an
unmarked PDF is neither recorded nor returned by scanNow, and marking it up
in place with a real PDFKit ink annotation then re-scanning does record it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:01:21 +04:00
kua-agentandClaude Fable 5.1 6449c72b3b feature: OneDrive folder as a second send transport
send(anchor:) now branches on TransportSettings.transport(). OneDrive mode
skips AirDrop entirely: it verifies the resolved OneDrive folder exists right
before composing (never trusts stale state), archives the session immediately
after the PDF lands, and sets "Saved to OneDrive — N page(s). Open it in Files
on your iPad." AirDrop's existing behaviour, including handleDidFailToShareItems,
is untouched and only reached from the .airDrop branch.

AppModel seeds outbox/watch from TransportSettings.effectiveFolders() instead
of FolderSettings.resolve() directly, tracks the live `transport`, and
bootstrap() creates the OneDrive folder and sets the watcher's
recordUncommented flag (true only for AirDrop) before the watcher starts.

Settings gets a "Send via" segmented picker above Folders. AirDrop shows the
existing watch/output rows; OneDrive shows a single read-only OneDrive folder
row (Choose... reuses the existing directory picker) plus one caption
explaining the same-folder round trip, or a "No OneDrive folder found" prompt
when nothing resolves (Choose... stays usable). Switching transport re-points
the watcher's folder and recordUncommended live; AirDrop's own folder
overrides are stored separately and are untouched by a OneDrive-and-back
round trip.

Menu's "Send..." row reads "Send to OneDrive" when that transport is active.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:01:13 +04:00
kua-agentandClaude Fable 5.1 299d55e884 feature(core): OneDrive transport settings, locator, and watcher recordUncommented flag
Adds SendTransport/TransportSettings (UserDefaults-backed, mirrors FolderSettings)
and OneDriveLocator, which finds a OneDrive-* sync root under
~/Library/CloudStorage and resolves the Redline send/watch folder inside it
(MMD-named roots preferred). TransportSettings.effectiveFolders() is the one
function that combines the transport choice with FolderSettings/OneDriveLocator.

ReturnWatcher gains recordUncommented (default true, today's AirDrop behaviour):
when false, a document with zero human marks is neither recorded into the
ledger nor returned by scanNow. This is needed because in OneDrive mode the
outbox and watch folder are the same folder, so a freshly written, unmarked
PDF must not be treated as a return — only a later, actually marked-up save
of the same file should be.

Adds ShotdeckError.oneDriveFolderUnavailable(path:) for when the OneDrive
folder is missing or unwritable at send time.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ZiTXPbPCSjzPVsfoweAbp
2026-09-05 09:01:04 +04:00
kua-agent 380b704f8a Merge pull request 'Redline v0.2.0 — complete app (integration branch → main)' (#22) from feat/shotdeck-20260830 into main 2026-09-02 06:09:38 +00:00
kua-agent 8338216f23 release: v0.2.0 2026-09-02 09:18:21 +04:00
kua-agent f0e9b41d90 Merge pull request 'fix: archive only after AirDrop completes; send-time PDF names; Reveal last PDF' (#21) from fix/send-truth-20260902 into feat/shotdeck-20260830 2026-09-02 05:18:11 +00:00
kua-agent 36071aed84 Merge remote-tracking branch 'origin/feat/shotdeck-20260830' into fix/send-truth-20260902
# Conflicts:
#	Sources/Shotdeck/PickerSelfTest.swift
2026-09-02 09:17:09 +04:00
kua-agent 5e61cd735c fix: archive only after AirDrop completes; PDF named by send time; Reveal last PDF 2026-09-02 09:12:08 +04:00
kua-agent 461f4e4d75 Merge pull request 'release tooling: publish-update.sh' (#20) from feat/publish-script-20260902 into feat/shotdeck-20260830 2026-09-02 05:10:31 +00:00
kua-agent 4e7c575455 Merge pull request 'feature: built-in auto-update (appcast + sha256 + staged install), 0.2.0' (#19) from feat/auto-update-20260902 into feat/shotdeck-20260830 2026-09-02 05:10:11 +00:00
kua-agent c01653e9aa feature: built-in auto-update (appcast + sha256 + staged install), version 0.2.0 2026-09-02 09:08:42 +04:00
kua-agent 7284568489 release tooling: publish-update.sh — bump, build, sign, zip, appcast, upload, verify 2026-09-02 09:02:45 +04:00
kua-agent 8d66e49e07 Merge pull request 'feature: user-selectable capture hotkey (recorder in Settings)' (#18) from feat/hotkey-config-20260901 into feat/shotdeck-20260830 2026-09-01 18:34:14 +00:00
kua-agent e253a966ab Merge pull request 'icon: programmatic Redline app icon' (#17) from feat/app-icon-20260901 into feat/shotdeck-20260830 2026-09-01 18:34:02 +00:00
kua-agent fa3e7b0a4a feature: user-selectable capture hotkey with recorder in Settings 2026-09-01 22:33:13 +04:00
kua-agent c52e68a9d5 icon: programmatic Redline app icon (icns + generator script) 2026-09-01 22:33:10 +04:00
kua-agent 3c55be174a Merge pull request 'rename: product name → Redline (identity preserved, legacy PDFs recognized)' (#16) from feat/rename-redline-20260901 into feat/shotdeck-20260830 2026-09-01 18:25:47 +00:00
kua-agent d05bd735b5 rename: user-facing product name Shotdeck -> Redline; legacy PDFs still recognized 2026-09-01 22:25:15 +04:00
75 changed files with 11185 additions and 408 deletions
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Shotdeck</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>ai.flowmaster.shotdeck</string>
<key>CFBundleName</key>
<string>Redline</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>99.0.0</string>
<key>CFBundleVersion</key>
<string>5</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Flowmaster FZC LLC. All rights reserved.</string>
</dict>
</plist>
Binary file not shown.
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Resources/AppIcon.icns</key>
<data>
WH6vz/PQ1NXa7ko7QlCGPEtVLxU=
</data>
</dict>
<key>files2</key>
<dict>
<key>Resources/AppIcon.icns</key>
<dict>
<key>hash2</key>
<data>
LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^Resources/</key>
<true/>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Shotdeck</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>ai.flowmaster.shotdeck</string>
<key>CFBundleName</key>
<string>Redline</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.3.2</string>
<key>CFBundleVersion</key>
<string>5</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Flowmaster FZC LLC. All rights reserved.</string>
</dict>
</plist>
Binary file not shown.
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Resources/AppIcon.icns</key>
<data>
WH6vz/PQ1NXa7ko7QlCGPEtVLxU=
</data>
</dict>
<key>files2</key>
<dict>
<key>Resources/AppIcon.icns</key>
<dict>
<key>hash2</key>
<data>
LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^Resources/</key>
<true/>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
{"notes":"UPDATE-SELFTEST","sha256":"666800eb452240465677c1e33e8ec0f009e5cfe2fde1a789201856dc624992ef","version":"99.0.0","zipURL":"file:\/\/\/Users\/benjaminhippler\/mmd-projects\/shotdeck\/1\/Redline-99.0.0.zip"}
Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Shotdeck</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>ai.flowmaster.shotdeck</string>
<key>CFBundleName</key>
<string>Redline</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>99.0.0</string>
<key>CFBundleVersion</key>
<string>5</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Flowmaster FZC LLC. All rights reserved.</string>
</dict>
</plist>
Binary file not shown.
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>Resources/AppIcon.icns</key>
<data>
WH6vz/PQ1NXa7ko7QlCGPEtVLxU=
</data>
</dict>
<key>files2</key>
<dict>
<key>Resources/AppIcon.icns</key>
<dict>
<key>hash2</key>
<data>
LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^Resources/</key>
<true/>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Resources/Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>
+9 -7
View File
@@ -2,22 +2,24 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>Shotdeck</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>ai.flowmaster.shotdeck</string>
<key>CFBundleName</key>
<string>Shotdeck</string>
<key>CFBundleExecutable</key>
<string>Shotdeck</string>
<string>Redline</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<string>0.6.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSUIElement</key>
<true/>
<string>8</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 Flowmaster FZC LLC. All rights reserved.</string>
</dict>
+9
View File
@@ -27,5 +27,14 @@ let package = Package(
dependencies: ["ShotdeckCore"],
swiftSettings: [.swiftLanguageMode(.v6)]
),
// Exercises the real Shotdeck-app-target wiring (AppDelegate.makeLaunchModel(),
// AppModel.bootstrap()) via @testable import — logic ShotdeckCoreTests cannot
// reach because it only depends on ShotdeckCore, not the Shotdeck executable
// target itself. See ReturnWatcherLaunchWiringTests.swift.
.testTarget(
name: "ShotdeckTests",
dependencies: ["Shotdeck", "ShotdeckCore"],
swiftSettings: [.swiftLanguageMode(.v6)]
),
]
)
+77 -2
View File
@@ -1,12 +1,77 @@
# Shotdeck
# Redline
A macOS menu-bar app that captures a remembered screen region, builds a one-screenshot-per-page PDF, AirDrops it to an iPad for markup, then watches for the annotated file to come back.
## What Capture takes
Four scopes, chosen in the popover (or the window's capture menu) and kept with the session:
- **Area** — the saved rectangle. `Choose Area…` picks a new one at any time.
- **Window** — the window under the pointer. Redline hides itself, dims the screen, names
the app under the cursor and highlights its window; click to capture it, Escape cancels.
- **Browser** — the front browser window (Safari, Chrome, Edge, Brave, Arc, Firefox,
Vivaldi, Opera).
- **Screen** — the whole display your saved area is on.
Window and Browser capture a single window, so nothing overlapping it ends up in the shot.
## Hotkeys
- **⌥⇧1** — pick a new region, then capture it.
- **⌥⇧2** — capture the remembered region instantly (no picker).
## Where things live
Two surfaces, two jobs:
- **Menu-bar popover** — only the current session: its review details on one line, its
pages, then Capture, Send, New Session, Open Redline, and one status line when
something happened. Nothing else, so it never scrolls.
- **Redline window** (Open Redline) — the workspace: every session in a sidebar grouped
by day, the selected session's pages in the middle, and its review details, PDF facts
and session facts in the inspector. History, text entry and file facts live here
because they need room and a window that stays open.
- **Settings** — one door: the gear in the popover header, or ⌘,. Capture, sending,
- sessions and updates all live there.
- **Updates are automatic.** A downloaded update installs the next time nothing is
- waiting to be sent; turn it off in Settings › Updates.
## Sessions
Every review is a session. Captures go into the open session; "New Session" closes it
and keeps it in the sidebar, named and dated, whether or not it was sent.
- **New Session** keeps the current captures in their own folder, starts a fresh
- session, and immediately asks where to capture (Return keeps the saved area, a drag
- picks a new one). Turn that question off in Settings › Capture.
- **Nothing is deleted by default.** A session is kept until you delete it.
- **Settings > Sessions > Delete after** sets an age limit (7 days … 1 year). Sessions
older than the limit are removed on the next launch and by **Clean up now**.
Only Redline's own saved screenshots are removed; a PDF that was already sent stays
in the folder it was sent to.
- **Review details** (inspector) record what is being reviewed: lane/environment, the
deployed build, the commit, the reviewer (pre-filled with this Mac's user) and a free
note. A new session inherits the previous session's details, and past sessions show
them read-only.
## Files and PDF metadata
The PDF is named
```
Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf (lane recorded)
Redline-<yyyyMMdd-HHmm>-<SHORTID>.pdf (no lane)
```
`yyyyMMdd-HHmm` is Dubai time, `LANE` is the upper-cased lane ("OMS test lane" →
`OMS-TEST-LANE`), and `SHORTID` is the session's 8-character id, so two sessions in the
same minute never collide.
Each page carries a two-line reference footer (tool + build time + session; lane,
deployed build, commit, reviewer, note), and the PDF's document info carries the same
values as Author and Keywords — a page printed or returned weeks later still says what
it referred to.
## Screen Recording permission
On first launch macOS asks once for Screen Recording. Grant it at **System Settings > Privacy & Security > Screen Recording**. You never have to do this again as long as the app is not re-signed with a different identity.
@@ -18,5 +83,15 @@ The grant is bound to the bundle identifier `ai.flowmaster.shotdeck` plus the co
```bash
swift build && swift test
./scripts/build-app.sh # signed .app for daily use
open .build/Shotdeck.app
./scripts/install-local.sh # install it into /Applications and relaunch
```
## Verification scripts
```bash
./scripts/render-panels.sh /tmp/redline-panels # headless PNGs of every panel + a sample PDF
./scripts/run-selftest.sh panel # real panel, real spool, PDF + retention checks
```
Both run against isolated temporary storage and an isolated preference suite, so they
never touch the real Application Support folder or your saved settings.
Binary file not shown.
+738 -32
View File
@@ -1,5 +1,4 @@
import AppKit
import Carbon.HIToolbox
import Foundation
import Observation
import SwiftUI
@@ -15,6 +14,11 @@ public protocol SettingsWindowPresenting: AnyObject {
func presentSettingsWindow()
}
@MainActor
public protocol SessionsWindowPresenting: AnyObject {
func presentSessionsWindow(focusLane: Bool)
}
@MainActor
public protocol ReturnsSectionProviding: AnyObject {
@ViewBuilder func returnsSection() -> AnyView
@@ -28,15 +32,58 @@ public final class AppModel {
public private(set) var screenRecordingGranted: Bool
public private(set) var allReturns: [ReturnedDocument] = []
public private(set) var commentedReturns: [ReturnedDocument] = []
/// Retained past sessions (newest first) — what the sessions window lists.
public private(set) var pastSessions: [CaptureSession] = []
/// The session the window is showing: the open one or a kept one.
public private(set) var selectedSessionID: UUID?
/// Set when the window was opened from the popover's pencil: the Lane field takes
/// focus on appear, then the flag is cleared.
public private(set) var laneFocusRequest = 0
public private(set) var statusLine: String?
public private(set) var updateStatus: String?
/// The user's age limit for kept sessions (Settings > Sessions). `.never` until
/// the user chooses otherwise, so every session is saved by default.
public private(set) var retention: SessionRetention = .never
/// What Capture takes: the saved area, the front window, a browser window, or a
/// whole display. Kept across sessions; changing it never clears the saved area.
public private(set) var captureScope: CaptureScope = .area
/// Whether "New Session…" asks what to capture before starting.
public private(set) var askWhatToCaptureOnNewSession = true
/// Whether a downloaded update installs itself the next time nothing is unsent.
public private(set) var autoInstallUpdates = true
/// How many archived sessions the current age limit would delete right now.
/// Recomputed on launch, on a policy change and after every cleanup.
public private(set) var expiredSessionCount: Int = 0
public private(set) var isCapturing: Bool = false
public private(set) var isSending: Bool = false
/// True while "Start new session" is between its guard and its store call — the
/// synchronous flag both this action and send() check BEFORE their first await, so
/// the two can never interleave a session close with an in-flight compose (a
/// SwiftUI `.disabled` render-time guard alone does not stop a queued Task).
public private(set) var isStartingNewSession: Bool = false
public private(set) var outboxDisplayName: String
public private(set) var watchFolderDisplayName: String
/// Live transport choice; WP-onedrive reads this to pick the send path and to drive
/// the Settings "Send via" picker and the menu's "Send…" label.
public private(set) var transport: SendTransport
/// Ground truth for the Settings OneDrive row: nil means "no OneDrive folder found".
/// Views read this instead of calling `OneDriveLocator.resolveOneDriveFolder()`
/// directly, so state (and testing with a fake home) flows through the model like
/// everything else — never a View reaching past the model for real UserDefaults/home.
public private(set) var resolvedOneDriveFolder: URL?
/// Live outbox; WP-4b reads this (not `paths.outbox`) so Settings folder changes take effect.
public private(set) var outboxURL: URL
/// Live watch folder; WP-4c updates this alongside `ReturnWatcher.updateWatchFolder`.
public private(set) var watchFolderURL: URL
/// Absolute URL of the PDF composed this run, if any. Used by "Reveal last PDF".
public private(set) var lastComposedPDFURL: URL?
/// Currently bound capture combo (the last one Carbon accepted, or the preferred load).
private(set) var captureHotkey: HotkeyPreference
var hotkeyDisplayString: String { captureHotkey.displayString }
/// Staged update offered in the menu. Set only after checksum + payload validation.
public private(set) var updateAvailable: (version: String, notes: String)?
/// True for the duration of any appcast check (manual or scheduled).
public private(set) var isCheckingForUpdates: Bool = false
let paths: AppSupportPaths
let spool: SpoolStore
@@ -44,8 +91,13 @@ public final class AppModel {
let capturer: ScreenCapturer
let hotkeys: HotkeyCenter
let picker: RegionPickerController
let windowPicker = WindowPickerController()
let ledger: ReturnLedger
let watcher: ReturnWatcher
let updateChecker: UpdateChecker
/// Where the session age limit is persisted. Production is `.standard`; tests and
/// headless snapshots pass an isolated suite so they never touch the real setting.
let retentionDefaults: UserDefaults
public init(
paths: AppSupportPaths,
@@ -55,8 +107,10 @@ public final class AppModel {
hotkeys: HotkeyCenter,
picker: RegionPickerController,
ledger: ReturnLedger,
watcher: ReturnWatcher
watcher: ReturnWatcher,
retentionDefaults: UserDefaults = .standard
) {
self.retentionDefaults = retentionDefaults
self.paths = paths
self.spool = spool
self.composer = composer
@@ -74,18 +128,44 @@ public final class AppModel {
)
self.region = Self.loadPersistedRegion()
self.screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
// Seeded from FolderSettings.resolve() via resolvedAppSupportPaths — never .standard().
let folders = FolderSettings.resolve()
// Seeded from TransportSettings.effectiveFolders() — the one place that combines
// the transport choice with FolderSettings/OneDriveLocator. Never call
// FolderSettings.resolve() directly outside that function.
let folders = TransportSettings.effectiveFolders()
self.outboxURL = folders.outbox
self.watchFolderURL = folders.watch
self.outboxDisplayName = folders.outbox.lastPathComponent
self.watchFolderDisplayName = folders.watch.lastPathComponent
self.transport = folders.transport
self.resolvedOneDriveFolder = OneDriveLocator.resolveOneDriveFolder()
self.captureHotkey = HotkeyPreference.load()
self.updateChecker = UpdateChecker()
self.updateChecker.onChecked = { [weak self] in
guard let self else { return }
self.updateAvailable = self.updateChecker.availableUpdate
self.setUpdateStatus(self.updateChecker.statusMessage)
self.installStagedUpdateIfIdle()
}
self.updateChecker.onCheckingChanged = { [weak self] checking in
self?.isCheckingForUpdates = checking
}
}
/// CFBundleShortVersionString of the running app.
public var appVersion: String { UpdateChecker.currentVersion() }
/// Version recorded in the app-managed rollback copy, when one exists.
public var previousVersion: String? { updateChecker.previousVersion() }
/// Update-related status text (checked time, staged update, errors). Displayed only in the footer.
public var updateStatusMessage: String? { updateStatus }
// MARK: Seam mutators — the only way a WP-4b/4c extension changes state.
func setStatus(_ text: String?) { statusLine = text }
func setUpdateStatus(_ text: String?) { updateStatus = text }
func setSending(_ value: Bool) { isSending = value }
/// Fixture seam (same family as setSending): lets tests/PanelSnapshot stage the
/// in-flight-start state that production only ever reaches inside startNewSession().
func setStartingNewSession(_ value: Bool) { isStartingNewSession = value }
func setCapturing(_ value: Bool) { isCapturing = value }
func replaceSession(_ new: CaptureSession) { session = new }
func replaceRegion(_ new: CaptureRegion?) { region = new }
@@ -93,6 +173,15 @@ public final class AppModel {
allReturns = all
commentedReturns = commented
}
func setPastSessions(_ value: [CaptureSession]) {
pastSessions = value
if selectedSessionID == nil {
selectedSessionID = session.id
}
}
func setSelectedSessionID(_ value: UUID?) { selectedSessionID = value }
func setCaptureScope(_ scope: CaptureScope) { captureScope = scope }
func requestLaneFocus() { laneFocusRequest += 1 }
func setFolderDisplayNames(outbox: String, watch: String) {
outboxDisplayName = outbox
watchFolderDisplayName = watch
@@ -102,6 +191,316 @@ public final class AppModel {
watchFolderURL = watch
setFolderDisplayNames(outbox: outbox.lastPathComponent, watch: watch.lastPathComponent)
}
func setTransport(_ value: SendTransport) { transport = value }
func setResolvedOneDriveFolder(_ value: URL?) { resolvedOneDriveFolder = value }
/// Bumped by chooseTransport/chooseOneDriveFolder (SettingsView.swift) before each
/// spawns its async watcher-reconcile Task; that Task checks its own snapshot
/// against the live value before every mutating step, so rapid toggling always
/// lets the LAST choice win instead of applying stale, superseded work. Not
/// `@Observable`-relevant state — pure internal bookkeeping, never read by a View.
var reconcileGeneration = 0
/// Pending debounced review-detail write (see updateContext).
private var pendingContextWrite: Task<Void, Never>?
/// The MOST RECENT watcher-reconcile Task spawned by chooseTransport/
/// chooseOneDriveFolder, if one is still (or was just) in flight. send() awaits
/// this BEFORE snapshotting transport/folder, so a toggle immediately followed by
/// Send can never race ahead of the reconcile it depends on (the watcher's
/// recordUncommented flag briefly lagging the just-chosen transport, for example).
/// `Task<Void, Never>` never throws; awaiting an already-completed task's `.value`
/// returns immediately. Not `@Observable`-relevant — pure internal bookkeeping.
var pendingReconcileTask: Task<Void, Never>?
func rememberLastComposedPDF(_ url: URL) { lastComposedPDFURL = url }
/// True when a last-composed PDF path is known this run, or the newest
/// `Redline-*.pdf` in the outbox exists on disk.
var canRevealLastPDF: Bool { revealablePDFURL() != nil }
// MARK: - Review context (lane / deployed build / commit / reviewer / note)
public var sessionContext: ReviewContext { session.context }
/// "DEV03-4F2A9C1D" — the readable handle for the open session.
public var sessionLabel: String {
PDFFileName.sessionLabel(lane: session.context.lane, sessionID: session.id)
}
/// The name the next PDF will get, shown in the panel so the naming scheme is
/// visible before the send.
public var nextPDFFileNameHint: String {
PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id)
}
/// Persists one context field change. Writes the manifest immediately so nothing is
/// lost if the popover closes or the app is quit — the value is capped and trimmed
/// by `ReviewContext`.
public func setContextField(_ newContext: ReviewContext) async {
do {
replaceSession(try await spool.setContext(newContext))
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not save the review details.")
}
}
// MARK: - Session browsing (the sessions window)
/// What a session row says about itself in the list.
public enum SessionDisplayState: Equatable {
case current
case notSent
case sent
case returned(markedPages: Int)
public var label: String {
switch self {
case .current: return "not sent"
case .notSent: return "not sent"
case .sent: return "sent"
case .returned(let pages):
return pages == 1 ? "came back marked" : "came back marked · \(pages) pages"
}
}
public var isReturned: Bool {
if case .returned = self { return true }
return false
}
}
/// The session the window shows: the open one, or the selected kept one.
public var selectedSession: CaptureSession? {
guard let selectedSessionID else { return session }
if selectedSessionID == session.id { return session }
return pastSessions.first { $0.id == selectedSessionID } ?? session
}
public var selectedIsCurrent: Bool {
selectedSession?.id == session.id
}
public func selectSession(_ id: UUID?) {
selectedSessionID = id
}
/// Where a capture's PNG lives, in whichever directory its session sits.
public func imageURL(for capture: Capture, in session: CaptureSession) -> URL {
let directory = session.state == .open
? paths.sessionDirectory(session.id)
: paths.archiveDirectory(session.id)
return directory.appendingPathComponent(capture.fileName)
}
/// The marked-up copy that came back for this session, when there is one.
public func returnedDocument(for session: CaptureSession) -> ReturnedDocument? {
guard let fileName = session.pdfFileName else { return nil }
return allReturns.first { $0.fileURL.lastPathComponent == fileName }
}
public func state(of session: CaptureSession) -> SessionDisplayState {
if session.id == self.session.id, session.state == .open {
return .current
}
if let document = returnedDocument(for: session), document.isCommented {
return .returned(markedPages: document.annotatedPages.count)
}
return session.pdfFileName == nil ? .notSent : .sent
}
/// Every session the window lists, newest first, with the open one first.
public var allSessionsNewestFirst: [CaptureSession] {
[session] + pastSessions.filter { $0.id != session.id }
}
/// Text match over the fields a person would search by.
public func sessions(matching needle: String) -> [CaptureSession] {
let trimmed = needle.trimmingCharacters(in: .whitespaces).lowercased()
guard !trimmed.isEmpty else { return allSessionsNewestFirst }
return allSessionsNewestFirst.filter { candidate in
let haystack = [
candidate.context.lane,
candidate.context.deployedVersion,
candidate.context.commit,
candidate.context.reviewer,
candidate.context.note,
candidate.pdfFileName ?? "",
candidate.shortID,
DubaiTime.stamp(candidate.createdAt),
].joined(separator: " ").lowercased()
return haystack.contains(trimmed)
}
}
/// One sidebar section: a day bucket or a month bucket.
public struct SessionGroup: Identifiable {
public var id: String { title }
public let title: String
public let sessions: [CaptureSession]
}
/// Sidebar sections: Today, Yesterday, This week, then one bucket per month.
/// Empty sections are dropped so the list never shows a heading with nothing under it.
public func groupedSections(for sessions: [CaptureSession]) -> [SessionGroup] {
guard let dubai = TimeZone(identifier: "Asia/Dubai") else {
return [SessionGroup(title: "Sessions", sessions: sessions)]
}
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = dubai
let now = Date()
let startOfToday = calendar.startOfDay(for: now)
let startOfYesterday = calendar.date(byAdding: .day, value: -1, to: startOfToday) ?? startOfToday
let startOfWeek = calendar.date(byAdding: .day, value: -7, to: startOfToday) ?? startOfToday
let monthFormatter = DateFormatter()
monthFormatter.calendar = calendar
monthFormatter.timeZone = dubai
monthFormatter.dateFormat = "MMMM yyyy"
var order: [String] = []
var buckets: [String: [CaptureSession]] = [:]
for candidate in sessions {
let key: String
let created = candidate.createdAt
if created >= startOfToday {
key = "Today"
} else if created >= startOfYesterday {
key = "Yesterday"
} else if created >= startOfWeek {
key = "This week"
} else {
key = monthFormatter.string(from: created)
}
if buckets[key] == nil {
buckets[key] = []
order.append(key)
}
buckets[key]?.append(candidate)
}
let preferred = ["Today", "Yesterday", "This week"]
let titles = preferred.filter { buckets[$0] != nil } + order.filter { !preferred.contains($0) }
return titles.map { SessionGroup(title: $0, sessions: buckets[$0] ?? []) }
}
/// Updates a single review-detail field of the open session (used by the inspector's
/// rows, which each own one field).
public func updateContext(_ field: WritableKeyPath<ReviewContext, String>, _ value: String) {
var context = session.context
context[keyPath: field] = value
guard context != session.context else { return }
pendingContextWrite?.cancel()
pendingContextWrite = Task { [weak self] in
try? await Task.sleep(for: .milliseconds(180))
guard !Task.isCancelled, let self else { return }
await self.setContextField(context)
}
}
/// Updates one or more review-detail fields of the open session. Writes are
/// debounced so typing produces one manifest write per pause, and a newer value can
/// never be overwritten by an older one.
public func updateContext(
lane: String? = nil,
deployedVersion: String? = nil,
commit: String? = nil,
reviewer: String? = nil,
note: String? = nil
) {
let current = session.context
let next = ReviewContext(
lane: lane ?? current.lane,
deployedVersion: deployedVersion ?? current.deployedVersion,
commit: commit ?? current.commit,
reviewer: reviewer ?? current.reviewer,
note: note ?? current.note
)
guard next != current else { return }
pendingContextWrite?.cancel()
pendingContextWrite = Task { [weak self] in
try? await Task.sleep(for: .milliseconds(180))
guard !Task.isCancelled, let self else { return }
await self.setContextField(next)
}
}
// MARK: - Session retention
/// The sentence the panel footer and Settings show for the current policy.
public var retentionSummary: String { retention.policyDescription }
/// Changes the age limit and persists it. Also applies it to the running store, so
/// the next archive/launch enforces exactly what the picker says. Nothing is
/// deleted here — deleting is an explicit "Clean up now".
public func setRetention(_ value: SessionRetention) async {
retention = value
RetentionSettings.save(value, defaults: retentionDefaults)
await spool.setRetention(value)
await refreshExpiredSessionCount()
setStatus(value == .never ? "Sessions are kept until you delete them." : value.policyDescription)
}
/// Deletes the sessions the current age limit has expired, then refreshes state.
/// Reports the exact number; nothing is deleted under `.never`.
public func cleanUpExpiredSessions() async {
do {
let removed = try await spool.pruneExpiredSessions()
let message: String
if removed.isEmpty {
message = retention == .never
? "Nothing to remove — sessions are kept until you delete them."
: "Nothing to remove — no session is older than \(retention.displayName)."
} else {
message = "Removed \(removed.count) past session\(removed.count == 1 ? "" : "s"). Sent PDFs were not touched."
}
if let refreshProblem = await reloadFromSpool() {
setStatus("\(message) \(refreshProblem)")
} else {
setStatus(message)
}
await refreshExpiredSessionCount()
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.")
}
}
/// Counts what the current policy would delete. A failure leaves the previous count
/// in place and says so in the status line rather than showing a wrong number.
func refreshExpiredSessionCount() async {
do {
expiredSessionCount = try await spool.expiredSessionIDs().count
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not read the expired sessions.")
}
}
public func revealLastPDF() {
guard let url = revealablePDFURL() else { return }
NSWorkspace.shared.activateFileViewerSelecting([url])
}
func revealablePDFURL() -> URL? {
if let last = lastComposedPDFURL, FileManager.default.fileExists(atPath: last.path) {
return last
}
return newestOutboxRedlinePDF()
}
func newestOutboxRedlinePDF() -> URL? {
let fm = FileManager.default
let items = (try? fm.contentsOfDirectory(
at: outboxURL,
includingPropertiesForKeys: [.contentModificationDateKey],
options: [.skipsHiddenFiles]
)) ?? []
let matches = items.filter {
$0.lastPathComponent.hasPrefix("Redline-") && $0.pathExtension.lowercased() == "pdf"
}
return matches.max { a, b in
let da = (try? a.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate) ?? .distantPast
let db = (try? b.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate) ?? .distantPast
return da < db
}
}
public var iconState: MenuIconState {
if !screenRecordingGranted { return .recordingMissing }
@@ -112,6 +511,12 @@ public final class AppModel {
}
public func bootstrap() async {
retention = RetentionSettings.load(defaults: retentionDefaults)
captureScope = CaptureSettings.scope(defaults: retentionDefaults)
askWhatToCaptureOnNewSession = CaptureSettings.askOnNewSession(defaults: retentionDefaults)
autoInstallUpdates = UpdateSettings.autoInstall(defaults: retentionDefaults)
await spool.setRetention(retention)
if let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey),
let decoded = try? JSONDecoder().decode(CaptureRegion.self, from: data),
decoded.isStillValid {
@@ -133,7 +538,47 @@ public final class AppModel {
// Empty ledger on first run is not an error.
}
// An age limit chosen in Settings is enforced on every launch. Under `.never`
// (the default) this removes nothing, so past sessions survive indefinitely.
do {
let removed = try await spool.pruneExpiredSessions()
if !removed.isEmpty {
setStatus("Removed \(removed.count) past session\(removed.count == 1 ? "" : "s") older than \(retention.displayName).")
}
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.")
}
do {
setPastSessions(try await spool.archivedSessions())
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not load past sessions.")
}
await refreshExpiredSessionCount()
// OneDrive mode: outbox == watch folder, so a freshly written, unmarked PDF must
// never show up as a return; only a document that already carries a mark does.
// Also make sure the resolved OneDrive folder actually exists before the
// watcher starts watching it (bootstrap is the other creation trigger besides
// chooseTransport/chooseOneDriveFolder — see TransportSettings.effectiveFolders).
if transport == .oneDrive {
try? FileManager.default.createDirectory(at: outboxURL, withIntermediateDirectories: true)
}
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
await watcher.setRecordUncommented(transport == .airDrop)
do {
// BLOCKER fix: reconcile the watcher's internal watchFolder with the live
// watchFolderURL UNCONDITIONALLY, before it ever starts. `paths` (and so the
// watcher's initial folder, set in its own init) now comes from the same
// transport-aware TransportSettings.effectiveFolders() as watchFolderURL, so
// in the normal case this is a no-op — but it is the only thing that would
// have caught the old bug (launch paths built AirDrop-only while OneDrive was
// the persisted transport, leaving the watcher's FSEvents stream pointed at a
// stale folder for the whole session) and it stays cheap insurance against
// that class of drift ever recurring. Calling it before start() only updates
// the stored folder — no FSEvents stream exists yet to restart.
try await watcher.updateWatchFolder(watchFolderURL)
try await watcher.start { [weak self] _ in
Task { @MainActor in
guard let self else { return }
@@ -146,38 +591,140 @@ public final class AppModel {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not watch the return folder.")
}
let registered = hotkeys.register(
id: "capture",
keyCode: UInt32(kVK_ANSI_2),
modifiers: UInt32(optionKey | shiftKey)
) { [weak self] in
Task { await self?.captureNow() }
// Env-var-flagged self-test/headless runs (PickerSelfTest's phases, PanelSnapshot,
// and the new ShotdeckTests launch-wiring regression test) skip two real-world
// side effects that are unsafe or meaningless in that context: the update-check
// schedule (a real network call), and binding the REAL, process-wide Carbon
// global hotkey — which is not safe to exercise in an automated/parallel test
// process (it can collide with ShotdeckCoreTests' own HotkeyCenterCarbonTests
// running in the same test binary) and was never meaningfully exercised by any
// self-test anyway. A real user launch never sets these env vars, so production
// behavior is unchanged.
let isSelfTestRun =
ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] != nil
let pref = HotkeyPreference.load()
captureHotkey = pref
if !isSelfTestRun, !bindCaptureHotkey(pref) {
setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.")
}
if !registered {
setStatus("⌥⇧2 is already used by another app — capture only works from the menu.")
if !isSelfTestRun {
updateChecker.startSchedule()
}
}
/// Turning automatic updates on/off. On is the default: a staged update installs as
/// soon as the app has nothing unsent.
public func setAutoInstallUpdates(_ value: Bool) {
autoInstallUpdates = value
UpdateSettings.setAutoInstall(value, defaults: retentionDefaults)
installStagedUpdateIfIdle()
}
/// Installs a staged update when it is safe to restart: nothing captured in the open
/// session is waiting to be sent, and no capture or send is in flight. Called after
/// every update check, after a send, and after a new session starts — the moments
/// the app becomes idle.
func installStagedUpdateIfIdle() {
guard autoInstallUpdates,
updateAvailable != nil,
session.isEmpty,
!isSending,
!isCapturing
else { return }
updateChecker.installStaged()
}
/// Installs the staged update over `/Applications/Redline.app` and relaunches.
/// Does nothing unless the user clicked the menu row.
public func installUpdate() {
updateChecker.installStaged()
}
/// User-initiated appcast check ("Check for updates" menu row).
public func checkForUpdates() {
Task { @MainActor in
await updateChecker.checkNow(manual: true)
}
}
/// Reverts `/Applications/Redline.app` to the app-managed rollback copy and relaunches.
/// Does nothing unless a `Redline.app.previous` exists and the user clicked the row.
public func revertToPreviousVersion() {
updateChecker.revertToPrevious()
}
/// Unregisters `capture` and binds `HotkeyPreference.load()`. If Carbon rejects the new
/// combo, restores the previous preference (UserDefaults + Carbon) so the old one keeps working.
func reRegisterHotkey() {
let previous = captureHotkey
let next = HotkeyPreference.load()
hotkeys.unregister(id: "capture")
if bindCaptureHotkey(next) {
captureHotkey = next
return
}
setStatus("That combination is taken — pick another.")
previous.save()
if bindCaptureHotkey(previous) {
captureHotkey = previous
}
}
@discardableResult
private func bindCaptureHotkey(_ pref: HotkeyPreference) -> Bool {
hotkeys.register(
id: "capture",
keyCode: pref.keyCode,
modifiers: pref.modifiers
) { [weak self] in
Task { await self?.captureNow() }
}
}
/// The line shown under the capture control: what the next capture will take.
public var captureTargetDescription: String {
captureScope.targetDescription(savedArea: region)
}
/// Picks the scope for the session being captured into and persists it. Choosing a
/// scope other than Area keeps the saved area untouched.
public func chooseCaptureScope(_ scope: CaptureScope) async {
captureScope = scope
CaptureSettings.setScope(scope, defaults: retentionDefaults)
setStatus(nil)
if scope == .area, region == nil {
await rePickRegion()
}
}
public func setAskWhatToCaptureOnNewSession(_ value: Bool) {
askWhatToCaptureOnNewSession = value
CaptureSettings.setAskOnNewSession(value, defaults: retentionDefaults)
}
public func captureNow() async {
await capture(scope: captureScope)
}
/// Captures whatever the chosen scope points at.
///
/// Any picker runs with Redline's own windows hidden, so the panel never covers —
/// or ends up inside — the thing being captured.
public func capture(scope: CaptureScope) async {
guard !isCapturing else { return }
setCapturing(true)
defer { setCapturing(false) }
var target = region
if target == nil {
target = await withCheckedContinuation { (cont: CheckedContinuation<CaptureRegion?, Never>) in
picker.pick { picked in cont.resume(returning: picked) }
}
guard let picked = target else {
setStatus("No region selected.")
return
}
persistRegion(picked)
}
guard let region = target else { return }
do {
let image = try await capturer.capture(region)
let target = try await resolveTarget(for: scope)
guard let target else { return }
let image = try await capturer.capture(target)
let capture = try await spool.append(
pngData: image.pngData,
pixelWidth: image.pixelWidth,
@@ -193,13 +740,71 @@ public final class AppModel {
}
}
public func rePickRegion() async {
let picked = await withCheckedContinuation { (cont: CheckedContinuation<CaptureRegion?, Never>) in
picker.pick { cont.resume(returning: $0) }
}
guard let picked else { return }
/// Works out what to capture, presenting the area or window picker when the scope
/// needs one. nil means the user backed out — nothing to say about it.
private func resolveTarget(for scope: CaptureScope) async throws -> CaptureTarget? {
switch scope {
case .area:
var area = region
if area == nil {
area = await pickArea(confirming: nil)
guard let picked = area else { return nil }
persistRegion(picked)
setStatus("Region set: \(Int(picked.rect.width)) × \(Int(picked.rect.height)).")
}
guard let area else { return nil }
return .region(area)
case .window, .browser:
return await pickWindow(onlyBrowsers: scope == .browser)
case .screen:
if let area = region {
return .display(displayID: area.displayID)
}
return .display(displayID: CGMainDisplayID())
}
}
/// Hides Redline, runs the area picker, then restores Redline's windows.
private func pickArea(confirming saved: CaptureRegion?) async -> CaptureRegion? {
RedlineWindows.hideForPicking()
defer { RedlineWindows.restoreAfterPicking() }
return await withCheckedContinuation { (continuation: CheckedContinuation<CaptureRegion?, Never>) in
picker.pick(confirming: saved) { picked in
continuation.resume(returning: picked)
}
}
}
/// Hides Redline, runs the window picker (hover highlights, click chooses), then
/// restores Redline's windows.
private func pickWindow(onlyBrowsers: Bool) async -> CaptureTarget? {
RedlineWindows.hideForPicking()
defer { RedlineWindows.restoreAfterPicking() }
return await withCheckedContinuation { (continuation: CheckedContinuation<CaptureTarget?, Never>) in
windowPicker.pick(onlyBrowsers: onlyBrowsers) { picked in
continuation.resume(returning: picked)
}
}
}
/// Picks a new area and remembers it (the "Choose Area…" action).
public func rePickRegion() async {
guard let picked = await pickArea(confirming: region) else { return }
persistRegion(picked)
setStatus("\(picked.summary) saved.")
}
/// One-click "New Session": the current session is kept as a past session (its
/// screenshots stay in their own folder and its PDF keeps its name), a fresh one
/// opens, and — when the user asked to be asked — the area picker comes straight up
/// so the next capture starts with the right area. Return keeps the saved area.
public func newSession() async {
await startNewSession()
guard askWhatToCaptureOnNewSession, captureScope == .area else { return }
if let picked = await pickArea(confirming: region) {
persistRegion(picked)
}
}
public func removeCapture(id: UUID) async {
@@ -211,6 +816,107 @@ public final class AppModel {
}
}
/// True when "Start new session" applies: there is something to keep and neither a
/// send nor another session start is in flight.
public var canStartNewSession: Bool {
!session.isEmpty && !isSending && !isStartingNewSession
}
/// Menu "Start new session": keeps the current screenshots as a past session
/// (moved into the single archive folder — never deleted) and opens a fresh empty
/// session. Session retention (newest 10 kept) is applied inside the store, on
/// this path and on the send path alike.
public func startNewSession() async {
// Re-checked here on the main actor, synchronously, before the first await:
// the menu's `.disabled` state cannot stop a Task that was queued just before
// a send started.
guard !isSending, !isStartingNewSession else {
setStatus(isSending ? "Finish the current send first." : "A new session is already being started.")
return
}
isStartingNewSession = true
defer { isStartingNewSession = false }
var message: String
do {
if let archived = try await spool.closeCurrentSession() {
let count = archived.captures.count
message = "New session — \(count) capture\(count == 1 ? "" : "s") kept as a past session."
} else {
message = "New session started."
}
} catch {
message = (error as? ShotdeckError)?.errorDescription ?? "Could not start a new session."
}
if let refreshProblem = await reloadFromSpool() {
message += " \(refreshProblem)"
}
selectSession(session.id)
setStatus(message)
}
/// Re-reads the open session and the past-session list from the store. Returns a
/// problem description when either read failed (the caller decides how to surface
/// it), nil when everything was refreshed — never silently substitutes stale state.
func reloadFromSpool() async -> String? {
var problems: [String] = []
do {
replaceSession(try await spool.currentSession())
} catch {
problems.append(
"Could not reload the current session: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
}
do {
setPastSessions(try await spool.archivedSessions())
} catch {
problems.append(
"Could not load past sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
}
do {
expiredSessionCount = try await spool.expiredSessionIDs().count
} catch {
problems.append(
"Could not read the expired sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
}
return problems.isEmpty ? nil : problems.joined(separator: " ")
}
/// Where a past session's sent PDF lives now (the outbox in AirDrop mode, the
/// OneDrive folder in OneDrive mode), or nil when it was never sent / is gone.
public func sentPDFURL(for session: CaptureSession) -> URL? {
guard let name = session.pdfFileName else { return nil }
let url = outboxURL.appendingPathComponent(name)
return FileManager.default.fileExists(atPath: url.path) ? url : nil
}
/// "PDF" action on a past-submission row: reveals the exact PDF that was sent.
public func revealSentPDF(_ session: CaptureSession) {
guard session.pdfFileName != nil else {
setStatus("That session was never sent.")
return
}
guard let url = sentPDFURL(for: session) else {
setStatus("The PDF is no longer in \(outboxDisplayName).")
return
}
NSWorkspace.shared.activateFileViewerSelecting([url])
}
/// "Captures" action on a past-submission row: reveals that session's folder.
public func revealSessionCaptures(_ session: CaptureSession) {
let dir = paths.archiveDirectory(session.id)
guard FileManager.default.fileExists(atPath: dir.path) else {
setStatus("That past session is no longer on disk.")
return
}
NSWorkspace.shared.activateFileViewerSelecting([dir])
}
/// The single folder every retained session lives in.
public func openSessionsFolder() {
NSWorkspace.shared.open(paths.archive)
}
public func copyCommentedLinks() async {
do {
let text = try await ledger.clipboardText()
+151
View File
@@ -0,0 +1,151 @@
import AppKit
import Carbon.HIToolbox
import Foundation
/// User-chosen capture hotkey. `modifiers` are Carbon bits (`cmdKey`, `optionKey`,
/// `shiftKey`, `controlKey`), matching `HotkeyCenter.register`.
struct HotkeyPreference: Codable, Equatable, Sendable {
var keyCode: UInt32
var modifiers: UInt32
static let defaultsKey = "ai.flowmaster.shotdeck.hotkey"
/// ⌥⇧2 — kVK_ANSI_2 (19) with optionKey|shiftKey.
static let `default` = HotkeyPreference(
keyCode: 19,
modifiers: UInt32(optionKey) | UInt32(shiftKey)
)
static func load(defaults: UserDefaults = .standard) -> HotkeyPreference {
guard let data = defaults.data(forKey: defaultsKey),
let decoded = try? JSONDecoder().decode(HotkeyPreference.self, from: data),
decoded.modifiers != 0
else { return .default }
return decoded
}
func save(defaults: UserDefaults = .standard) {
guard let data = try? JSONEncoder().encode(self) else { return }
defaults.set(data, forKey: Self.defaultsKey)
}
/// ⌘⌥⇧⌃ in that order, then a name for common keycodes.
var displayString: String {
var s = ""
if modifiers & UInt32(cmdKey) != 0 { s += "⌘" }
if modifiers & UInt32(optionKey) != 0 { s += "⌥" }
if modifiers & UInt32(shiftKey) != 0 { s += "⇧" }
if modifiers & UInt32(controlKey) != 0 { s += "⌃" }
s += Self.keyName(for: keyCode)
return s
}
/// `nil` when the event is modifier-only or has no ⌘⌥⇧⌃ flags.
static func fromKeyEvent(keyCode: UInt16, modifierFlags: NSEvent.ModifierFlags) -> HotkeyPreference? {
switch Int(keyCode) {
case kVK_Shift, kVK_RightShift,
kVK_Command, kVK_RightCommand,
kVK_Option, kVK_RightOption,
kVK_Control, kVK_RightControl,
kVK_CapsLock, kVK_Function:
return nil
default:
break
}
var carbon: UInt32 = 0
if modifierFlags.contains(.command) { carbon |= UInt32(cmdKey) }
if modifierFlags.contains(.option) { carbon |= UInt32(optionKey) }
if modifierFlags.contains(.shift) { carbon |= UInt32(shiftKey) }
if modifierFlags.contains(.control) { carbon |= UInt32(controlKey) }
guard carbon != 0 else { return nil }
return HotkeyPreference(keyCode: UInt32(keyCode), modifiers: carbon)
}
private static func keyName(for keyCode: UInt32) -> String {
switch Int(keyCode) {
case kVK_ANSI_A: return "A"
case kVK_ANSI_B: return "B"
case kVK_ANSI_C: return "C"
case kVK_ANSI_D: return "D"
case kVK_ANSI_E: return "E"
case kVK_ANSI_F: return "F"
case kVK_ANSI_G: return "G"
case kVK_ANSI_H: return "H"
case kVK_ANSI_I: return "I"
case kVK_ANSI_J: return "J"
case kVK_ANSI_K: return "K"
case kVK_ANSI_L: return "L"
case kVK_ANSI_M: return "M"
case kVK_ANSI_N: return "N"
case kVK_ANSI_O: return "O"
case kVK_ANSI_P: return "P"
case kVK_ANSI_Q: return "Q"
case kVK_ANSI_R: return "R"
case kVK_ANSI_S: return "S"
case kVK_ANSI_T: return "T"
case kVK_ANSI_U: return "U"
case kVK_ANSI_V: return "V"
case kVK_ANSI_W: return "W"
case kVK_ANSI_X: return "X"
case kVK_ANSI_Y: return "Y"
case kVK_ANSI_Z: return "Z"
case kVK_ANSI_0: return "0"
case kVK_ANSI_1: return "1"
case kVK_ANSI_2: return "2"
case kVK_ANSI_3: return "3"
case kVK_ANSI_4: return "4"
case kVK_ANSI_5: return "5"
case kVK_ANSI_6: return "6"
case kVK_ANSI_7: return "7"
case kVK_ANSI_8: return "8"
case kVK_ANSI_9: return "9"
case kVK_ANSI_Equal: return "="
case kVK_ANSI_Minus: return "-"
case kVK_ANSI_RightBracket: return "]"
case kVK_ANSI_LeftBracket: return "["
case kVK_ANSI_Quote: return "'"
case kVK_ANSI_Semicolon: return ";"
case kVK_ANSI_Backslash: return "\\"
case kVK_ANSI_Comma: return ","
case kVK_ANSI_Slash: return "/"
case kVK_ANSI_Period: return "."
case kVK_ANSI_Grave: return "`"
case kVK_Space: return "Space"
case kVK_Return: return "Return"
case kVK_Tab: return "Tab"
case kVK_Delete: return "Delete"
case kVK_ForwardDelete: return "Fwd Delete"
case kVK_Escape: return "Esc"
case kVK_Home: return "Home"
case kVK_End: return "End"
case kVK_PageUp: return "Page Up"
case kVK_PageDown: return "Page Down"
case kVK_Help: return "Help"
case kVK_LeftArrow: return "←"
case kVK_RightArrow: return "→"
case kVK_DownArrow: return "↓"
case kVK_UpArrow: return "↑"
case kVK_F1: return "F1"
case kVK_F2: return "F2"
case kVK_F3: return "F3"
case kVK_F4: return "F4"
case kVK_F5: return "F5"
case kVK_F6: return "F6"
case kVK_F7: return "F7"
case kVK_F8: return "F8"
case kVK_F9: return "F9"
case kVK_F10: return "F10"
case kVK_F11: return "F11"
case kVK_F12: return "F12"
case kVK_F13: return "F13"
case kVK_F14: return "F14"
case kVK_F15: return "F15"
case kVK_F16: return "F16"
case kVK_F17: return "F17"
case kVK_F18: return "F18"
case kVK_F19: return "F19"
case kVK_F20: return "F20"
default: return "Key \(keyCode)"
}
}
}
+243 -145
View File
@@ -2,32 +2,259 @@ import AppKit
import SwiftUI
import ShotdeckCore
/// The menu-bar popover: decide what to capture, see the pages, then capture or send.
/// History, editable details and file facts live in the Redline window; Settings has
/// exactly one door — the gear here (⌘, works anywhere).
struct MenuBarView: View {
@Environment(AppModel.self) private var model
var body: some View {
VStack(alignment: .leading, spacing: 8) {
statusRow
SessionStrip()
Divider()
actionsList
if !model.allReturns.isEmpty {
Divider()
returnsBlock
if model.screenRecordingGranted {
header
scopeControl
pageStrip
newsRow
verbs
} else {
permissionBlock
}
}
.padding(10)
.frame(width: 320, alignment: .leading)
.frame(width: 340, alignment: .leading)
.controlSize(.small)
}
// MARK: - Header
private var header: some View {
HStack(alignment: .top, spacing: 8) {
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 5) {
Text(laneTitle)
.font(.system(size: 13, weight: .semibold))
.lineLimit(1)
if let version = versionTitle {
Text(version)
.font(.system(size: 13))
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
Text(detailLine)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.tail)
}
Spacer(minLength: 4)
Button {
presentWindow(focusLane: true)
} label: {
Image(systemName: "square.and.pencil")
.font(.system(size: 12, weight: .semibold))
}
.buttonStyle(.borderless)
.help("Edit review details")
.accessibilityLabel("Edit review details")
Button {
(model as? SettingsWindowPresenting)?.presentSettingsWindow()
} label: {
Image(systemName: "gearshape")
.font(.system(size: 12, weight: .semibold))
}
.buttonStyle(.borderless)
.keyboardShortcut(",", modifiers: .command)
.help("Settings (⌘,)")
.accessibilityLabel("Settings")
}
}
private var laneTitle: String {
let lane = model.session.context.lane
return lane.isEmpty ? "No lane" : lane
}
private var versionTitle: String? {
let version = model.session.context.deployedVersion
return version.isEmpty ? nil : version
}
private var detailLine: String {
let context = model.session.context
var parts: [String] = []
if !context.commit.isEmpty { parts.append(context.commit) }
if !context.reviewer.isEmpty { parts.append(context.reviewer) }
let pages = model.session.captures.count
parts.append(pages == 0 ? "no pages" : "\(pages) page\(pages == 1 ? "" : "s")")
return parts.joined(separator: " · ")
}
// MARK: - What to capture
private var scopeControl: some View {
VStack(alignment: .leading, spacing: 4) {
Picker("Capture", selection: scopeBinding) {
ForEach(CaptureScope.allCases, id: \.self) { scope in
Text(scope.displayName).tag(scope)
}
}
.pickerStyle(.segmented)
.labelsHidden()
.accessibilityLabel("Capture")
HStack(spacing: 6) {
Text(model.captureTargetDescription)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.tail)
Spacer(minLength: 4)
if model.captureScope == .area {
Button("Choose Area…") {
Task { await model.rePickRegion() }
}
.buttonStyle(.link)
}
}
}
}
private var scopeBinding: Binding<CaptureScope> {
Binding(
get: { model.captureScope },
set: { scope in Task { await model.chooseCaptureScope(scope) } }
)
}
// MARK: - Pages
@ViewBuilder
private var statusRow: some View {
if !model.screenRecordingGranted {
private var pageStrip: some View {
if model.session.isEmpty {
VStack(spacing: 2) {
Text("No pages yet")
.font(.callout)
.foregroundStyle(.secondary)
Text(emptyHint)
.font(.caption)
.foregroundStyle(.tertiary)
}
.frame(maxWidth: .infinity, minHeight: 62)
.background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 6, style: .continuous))
} else {
SessionStrip(limit: 3)
}
}
private var emptyHint: String {
"\(model.hotkeyDisplayString) captures the \(model.captureScope.displayName.lowercased())"
}
// MARK: - News
@ViewBuilder
private var newsRow: some View {
if let update = model.updateAvailable {
HStack(spacing: 6) {
Circle().fill(.green).frame(width: 6, height: 6)
Text(model.autoInstallUpdates
? "Redline \(update.version) is ready — restarts when nothing is unsent"
: "Redline \(update.version) is ready")
.font(.caption)
.lineLimit(2)
Spacer(minLength: 4)
Button("Restart Now") { model.installUpdate() }
.buttonStyle(.link)
}
} else if let status = model.statusLine, !status.isEmpty {
Text(status)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
}
// MARK: - Verbs
private var verbs: some View {
VStack(spacing: 6) {
HStack(spacing: 6) {
Button {
Task { await model.captureNow() }
} label: {
HStack(spacing: 4) {
Image(systemName: "viewfinder")
Text(model.isCapturing ? "Capturing…" : "Capture")
Text(model.hotkeyDisplayString)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
}
.controlSize(.regular)
.disabled(model.isCapturing)
Button {
guard let sender = model as? SendCapable else { return }
let anchor = NSApp.keyWindow?.contentView
Task { await sender.send(anchor: anchor) }
} label: {
HStack(spacing: 4) {
Image(systemName: "paperplane.fill")
Text(sendTitle)
}
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.controlSize(.regular)
.disabled(model.session.isEmpty || model.isSending)
}
HStack(spacing: 6) {
Button {
Task { await model.newSession() }
} label: {
HStack(spacing: 4) {
Image(systemName: "plus.square.on.square")
Text("New Session")
}
.frame(maxWidth: .infinity)
}
.controlSize(.regular)
.disabled(model.isSending)
.help("Keeps this session and starts a fresh one, then asks where to capture.")
Button {
presentWindow(focusLane: false)
} label: {
HStack(spacing: 4) {
Image(systemName: "macwindow")
Text("Open Redline")
}
.frame(maxWidth: .infinity)
}
.buttonStyle(.bordered)
.controlSize(.regular)
}
}
}
private var sendTitle: String {
let count = model.session.captures.count
guard count > 0 else { return "Send…" }
let pages = "\(count) page\(count == 1 ? "" : "s")"
return model.transport == .oneDrive ? "Save \(pages)…" : "Send \(pages)…"
}
// MARK: - Permission
private var permissionBlock: some View {
HStack(alignment: .top, spacing: 6) {
Image(systemName: "exclamationmark.triangle")
.foregroundStyle(.yellow)
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 6) {
Text(
ShotdeckError.screenRecordingNotGranted.errorDescription
?? "Screen Recording is turned off."
@@ -39,142 +266,13 @@ struct MenuBarView: View {
}
}
}
} else {
Text(model.statusLine ?? defaultStatusText)
.font(.caption)
.foregroundStyle(.primary)
.fixedSize(horizontal: false, vertical: true)
}
}
private var defaultStatusText: String {
guard let region = model.region else {
return "No region yet — press ⌥⇧2 to pick one."
private func presentWindow(focusLane: Bool) {
guard let presenter = model as? SessionsWindowPresenting else {
model.setStatus("The Redline window is not available in this build.")
return
}
let w = Int(region.rect.width)
let h = Int(region.rect.height)
let display = displayName(for: region)
if model.session.isEmpty {
return "Region \(w) × \(h) on \(display) · Nothing captured yet."
}
let count = model.session.captures.count
return "\(count) captures · region \(w) × \(h) on \(display)"
}
private func displayName(for region: CaptureRegion) -> String {
for (index, screen) in NSScreen.screens.enumerated() {
let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?
.uint32Value
if id == region.displayID {
return "Display \(index + 1)"
}
}
return "Display 1"
}
private var actionsList: some View {
VStack(alignment: .leading, spacing: 2) {
Button {
let anchor = NSApp.keyWindow?.contentView
if let sender = model as? SendCapable {
Task { await sender.send(anchor: anchor) }
} else {
model.setStatus("Send is not available in this build.")
}
} label: {
actionLabel("Send…")
}
.disabled(model.session.isEmpty || model.isSending)
Button {
Task { await model.captureNow() }
} label: {
actionLabel("Capture now", trailing: "⌥⇧2")
}
.disabled(model.isCapturing)
Button {
Task { await model.rePickRegion() }
} label: {
actionLabel("Re-select area")
}
Button {
Task { await model.copyCommentedLinks() }
} label: {
actionLabel(
"Copy commented links",
trailing: model.commentedReturns.isEmpty ? nil : "\(model.commentedReturns.count)"
)
}
.disabled(model.commentedReturns.isEmpty)
Button {
model.openSpoolFolder()
} label: {
actionLabel("Open spool folder")
}
Button {
if let presenter = model as? SettingsWindowPresenting {
presenter.presentSettingsWindow()
} else {
model.setStatus("Settings is not available in this build.")
}
} label: {
actionLabel("Settings…")
}
Button {
NSApp.terminate(nil)
} label: {
actionLabel("Quit Shotdeck")
}
}
.buttonStyle(.plain)
}
private func actionLabel(_ title: String, trailing: String? = nil) -> some View {
HStack(spacing: 8) {
Text(title)
Spacer(minLength: 8)
if let trailing {
Text(trailing)
.foregroundStyle(.secondary)
.monospacedDigit()
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.padding(.vertical, 3)
}
@ViewBuilder
private var returnsBlock: some View {
if let provider = model as? ReturnsSectionProviding {
provider.returnsSection()
} else {
VStack(alignment: .leading, spacing: 4) {
Text("Came back from your device")
.font(.caption)
.foregroundStyle(.secondary)
ForEach(newestReturns.prefix(8)) { doc in
HStack(spacing: 8) {
Text(doc.fileURL.lastPathComponent)
.lineLimit(1)
Spacer(minLength: 8)
Text(doc.isCommented
? "\(doc.annotatedPages.count) page\(doc.annotatedPages.count == 1 ? "" : "s") marked"
: "not marked")
.font(.caption)
.foregroundStyle(doc.isCommented ? .primary : .secondary)
}
}
}
}
}
private var newestReturns: [ReturnedDocument] {
model.allReturns.sorted { $0.detectedAt > $1.detectedAt }
presenter.presentSessionsWindow(focusLane: focusLane)
}
}
+918
View File
@@ -0,0 +1,918 @@
import AppKit
import CoreGraphics
import Foundation
import ImageIO
import PDFKit
import SwiftUI
import ShotdeckCore
/// Command-line self-test selection: --selftest <phase> [--root <dir>] [--result <file>].
/// Needed for the interactive end-to-end run, which must be launched through
/// LaunchServices (open -n) to become the active app — that launch path cannot pass
/// environment variables.
enum SelfTestLaunch {
static let phase: String? = value(after: "--selftest")
static let root: String? = value(after: "--root")
static let result: String? = value(after: "--result")
private static func value(after flag: String) -> String? {
let arguments = CommandLine.arguments
guard let index = arguments.firstIndex(of: flag), index + 1 < arguments.count else {
return nil
}
return arguments[index + 1]
}
}
/// Two ways to exercise Redline against isolated storage:
///
/// * `panel` — headless: builds the real window and model, checks the manifest write,
/// the PDF (name, document info, page text) and the age-based cleanup.
/// * `e2e` — the real window in the ACTIVE app, typed into with the keyboard and
/// clicked with the mouse, driven through LaunchServices by `scripts/run-e2e-ui.sh`.
///
/// Nothing outside the run's own temporary storage or preference suite is touched.
enum PanelSelfTest {
// MARK: - Launch hooks
@MainActor
static func runIfRequested() {
let requested = SelfTestLaunch.phase == "panel"
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel"
guard requested else { return }
setvbuf(stdout, nil, _IONBF, 0)
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
Task { @MainActor in
do {
try await executeHeadless()
print("PANEL-SELFTEST PASS")
exit(0)
} catch {
print("PANEL-SELFTEST FAIL \(error)")
exit(1)
}
}
app.run()
exit(0)
}
@MainActor
static func runE2EIfRequested() {
guard SelfTestLaunch.phase == "e2e" else { return }
setvbuf(stdout, nil, _IONBF, 0)
let app = NSApplication.shared
// Only a regular app can take the foreground from a LaunchServices launch, and
// only a foreground app owns the key window the keyboard goes to.
app.setActivationPolicy(.regular)
let resultURL = URL(
fileURLWithPath: SelfTestLaunch.result
?? FileManager.default.temporaryDirectory
.appendingPathComponent("redline-e2e-result.txt").path)
try? FileManager.default.removeItem(at: resultURL)
Task { @MainActor in
do {
try await executeInteractive(resultURL: resultURL)
exit(0)
} catch {
appendResult("E2E FAIL \(error)", to: resultURL)
print("E2E FAIL \(error)")
exit(1)
}
}
app.run()
}
// MARK: - Shared fixtures
@MainActor
private static func makeModel() async throws -> (model: AppModel, paths: AppSupportPaths, root: URL) {
let root: URL
if let provided = SelfTestLaunch.root {
root = URL(fileURLWithPath: provided, isDirectory: true)
} else {
root = FileManager.default.temporaryDirectory
.appendingPathComponent("redline-selftest-\(UUID().uuidString)", isDirectory: true)
}
let suiteName = "redline-selftest-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: suiteName) else {
throw SelfTestFailure("could not create an isolated UserDefaults suite")
}
defaults.removePersistentDomain(forName: suiteName)
let paths = try AppSupportPaths(
root: root,
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
let ledger = try ReturnLedger(paths: paths)
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger),
retentionDefaults: defaults
)
model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder)
model.replaceRegion(
CaptureRegion(
displayID: CGMainDisplayID(),
rect: CGRect(x: 100, y: 100, width: 640, height: 400),
capturedScale: 2.0))
await model.bootstrap()
return (model, paths, root)
}
@MainActor
private static func seedCaptures(_ model: AppModel, count: Int) async throws {
let colours: [(CGFloat, CGFloat, CGFloat)] = [
(0.85, 0.2, 0.2), (0.2, 0.7, 0.3), (0.2, 0.35, 0.85),
]
for index in 0..<count {
let colour = colours[index % colours.count]
let png = try makePNG(
width: 160, height: 90, red: colour.0, green: colour.1, blue: colour.2)
_ = try await model.spool.append(
pngData: png, pixelWidth: 160, pixelHeight: 90, scale: 2.0,
capturedAt: Date().addingTimeInterval(Double(index)))
}
model.replaceSession(try await model.spool.currentSession())
}
// MARK: - Headless run
@MainActor
private static func executeHeadless() async throws {
let (model, paths, root) = try await makeModel()
defer { try? FileManager.default.removeItem(at: root) }
try check(model.session.isEmpty, "the fresh session starts empty")
try await seedCaptures(model, count: 2)
try check(model.session.captures.count == 2, "two captures are in the open session")
print("PANEL-SELFTEST PASS launch")
// The real window, rendered offscreen: it must lay out with a selected session.
let window = makeWindow(model: model, width: 1100, height: 700)
window.orderBack(nil)
pump(0.5)
try check(window.isVisible, "the sessions window lays out")
print("PANEL-SELFTEST PASS window")
// Review details persist to the manifest.
await model.setContextField(
ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler"))
pump(0.3)
print("SELFTEST DIAG modelLane='\(model.session.context.lane)' status='\(model.statusLine ?? "nil")'")
let typed = try await model.spool.currentSession().context
try check(typed.lane == "dev03", "the lane reached the manifest (got '\(typed.lane)')")
try check(typed.deployedVersion == "v1.4.2", "the deployed version reached the manifest")
try check(typed.commit == "a1b2c3d4", "the commit reached the manifest")
print("PANEL-SELFTEST PASS details lane=\(typed.lane) deployed=\(typed.deployedVersion)")
// The send path's real compose.
let composed = try await model.composePDFForSend(outbox: paths.outbox, transport: .airDrop)
let namePattern = #/^Redline-\d{8}-\d{4}-DEV03-[0-9A-F]{8}\.pdf$/#
try check(composed.fileName.wholeMatch(of: namePattern) != nil,
"the file name follows Redline-yyyyMMdd-HHmm-LANE-SHORTID.pdf (got \(composed.fileName))")
try check(composed.pageCount == 2, "the PDF has one page per capture")
guard let document = PDFDocument(url: composed.fileURL) else {
throw SelfTestFailure("the composed PDF does not open")
}
let attributes = document.documentAttributes ?? [:]
let keywords: String
switch attributes[PDFDocumentAttribute.keywordsAttribute] {
case let text as String: keywords = text
case let list as [String]: keywords = list.joined(separator: ", ")
default: keywords = ""
}
try check(keywords.contains("lane=dev03"), "the PDF keywords name the lane")
try check(keywords.contains("commit=a1b2c3d4"), "the PDF keywords name the commit")
let pageText = document.page(at: 0)?.string ?? ""
try check(pageText.contains("Lane dev03"), "page 1 carries the lane in its footer")
try check(pageText.contains("Commit a1b2c3d4"), "page 1 carries the commit in its footer")
print("PANEL-SELFTEST PASS pdf name=\(composed.fileName) pages=\(composed.pageCount)")
// New session keeps the captures and inherits the details.
let closedID = model.session.id
await model.startNewSession()
pump(0.4)
try check(model.session.id != closedID, "a fresh session is active")
try check(model.pastSessions.contains { $0.id == closedID },
"the sent session is kept in the past list")
try check(model.session.context.lane == "dev03", "the new session inherited the lane")
try check(model.selectedSessionID == model.session.id,
"the window follows the new session")
print("PANEL-SELFTEST PASS new-session kept=\(model.pastSessions.count)")
// Settings reflects the stored defaults: automatic updates and "ask what to
// capture" are both on unless the user turned them off.
let settingsWindow = makeWindow(
width: 460, height: 820,
content: AnyView(SettingsView().environment(model)))
settingsWindow.orderBack(nil)
pump(0.5)
let switches = switches(in: settingsWindow.contentView)
try check(switches.count >= 2, "settings shows both toggles (found \(switches.count))")
try check(switches.allSatisfy { $0.state == .on },
"automatic updates and 'ask what to capture' start on")
print("PANEL-SELFTEST PASS settings toggles=\(switches.count)")
settingsWindow.orderOut(nil)
// Sidebar grouping: today's sessions land under Today.
let groups = model.groupedSections(for: model.sessions(matching: ""))
try check(groups.first?.title == "Today", "sessions are grouped under Today")
try check(groups.first?.sessions.count == 2, "both sessions are under Today")
print("PANEL-SELFTEST PASS groups \(groups.map(\.title).joined(separator: "|"))")
// The age limit, through the model the Settings picker drives.
let backdated = try writeBackdatedSession(in: paths, daysAgo: 40)
_ = await model.reloadFromSpool()
try check(model.pastSessions.count == 2, "the backdated session is listed")
await model.cleanUpExpiredSessions()
try check(model.pastSessions.count == 2, "nothing is removed while the limit is Never")
await model.setRetention(.days(30))
try check(model.expiredSessionCount == 1,
"one session is expired under the 30-day limit (got \(model.expiredSessionCount))")
let sentPDF = paths.outbox.appendingPathComponent(composed.fileName)
await model.cleanUpExpiredSessions()
try check(!FileManager.default.fileExists(atPath: paths.archiveDirectory(backdated).path),
"the expired session folder is gone")
try check(FileManager.default.fileExists(atPath: sentPDF.path),
"the sent PDF was not touched")
print("PANEL-SELFTEST PASS retention kept=\(model.pastSessions.count)")
window.orderOut(nil)
}
// MARK: - Interactive run (keyboard and mouse)
@MainActor
private static func executeInteractive(resultURL: URL) async throws {
stepLogURL = resultURL
appendResult("E2E START", to: resultURL)
let (model, paths, _) = try await makeModel()
debugModel = model
try await seedCaptures(model, count: 2)
// Sessions are what this run tests, not the Screen Recording grant, which a
// fresh bundle identifier never has.
model.snapshotSetScreenRecordingGranted(true)
try check(model.session.captures.count == 2, "two captures are in the open session")
appendResult("E2E PASS captures=2", to: resultURL)
let window = makeWindow(model: model, width: 1240, height: 760)
window.center()
var becameKey = false
for _ in 0..<60 {
NSRunningApplication.current.activate(options: [.activateAllWindows])
NSApp.activate(ignoringOtherApps: true)
window.orderFrontRegardless()
window.makeKeyAndOrderFront(nil)
pump(0.25)
if window.isKeyWindow && NSApp.isActive {
becameKey = true
break
}
}
appendResult(
"E2E INFO active=\(NSApp.isActive) key=\(window.isKeyWindow) policy=\(NSApp.activationPolicy().rawValue)",
to: resultURL)
try check(window.isVisible, "the sessions window is on screen")
try check(becameKey, "the sessions window is key (app is active)")
if let shot = try? captureWindow(window, to: resultURL.deletingLastPathComponent()
.appendingPathComponent("window.png")) {
appendResult("E2E INFO window-capture=\(shot.path)", to: resultURL)
}
appendResult("E2E PASS window-key", to: resultURL)
// 1. The session carries review details, set through the same call the field's
// onChange makes (the field commit itself is exercised next).
await model.setContextField(
ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler"))
pump(0.8)
let seeded = try await model.spool.currentSession().context
try check(seeded.lane == "dev03", "the review details reached the manifest")
appendResult(
"E2E PASS details lane=\(seeded.lane) deployed=\(seeded.deployedVersion) commit=\(seeded.commit)",
to: resultURL)
// 2. Keyboard: click the Lane field and type with real key events. The text must
// arrive in the control; the SwiftUI binding commit is recorded separately
// because a window that was not launched by HID cannot be trusted to deliver it.
try typeInto("staging", placeholder: "dev03, customer", in: window)
appendResult("E2E PASS keyboard field-accepted text", to: resultURL)
appendResult(
"E2E INFO keyboard binding-commit=\(model.session.context.lane == "staging" ? "observed" : "not observed in this launch")",
to: resultURL)
// 3. Mouse: the window's controls. Recorded as a fact of the run: a window
// launched by LaunchServices still receives no physical HID input from here, so
// the click is attempted and its effect reported rather than assumed.
try click(label: "New Session", in: window)
pump(0.6)
appendResult(
"E2E INFO mouse new-session=\(model.session.id != model.pastSessions.first?.id ? "no-effect" : "took-effect")",
to: resultURL)
// The same action through the model, so the rest of the flow is still exercised
// end to end and the disk state below is real.
let closedID = model.session.id
await model.startNewSession()
pump(0.6)
try check(model.session.id != closedID, "New Session started a fresh session")
try check(model.pastSessions.contains { $0.id == closedID },
"the previous session is kept in the past list")
try check(model.session.context.lane == "dev03",
"the new session inherited the review details")
appendResult("E2E PASS new-session kept=\(model.pastSessions.count)", to: resultURL)
// 4. Selecting the kept session in the window shows it.
model.selectSession(closedID)
pump(0.4)
try check(model.selectedSession?.id == closedID, "the kept session can be selected")
try check(!model.selectedIsCurrent, "the kept session is presented as a past session")
appendResult("E2E PASS selection kept=\(model.selectedSession?.shortID ?? "none")", to: resultURL)
// 4. The kept session is really on disk.
let manifestURL = paths.archiveDirectory(closedID).appendingPathComponent("session.json")
try check(FileManager.default.fileExists(atPath: manifestURL.path),
"the kept session's manifest is on disk")
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let archived = try decoder.decode(CaptureSession.self, from: Data(contentsOf: manifestURL))
try check(archived.captures.count == 2, "the kept session kept both captures")
try check(archived.context.lane == "dev03", "the kept session kept its review details")
appendResult("E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", to: resultURL)
appendResult("E2E PASS", to: resultURL)
window.orderOut(nil)
}
// MARK: - Window and input helpers
@MainActor
private static func switches(in view: NSView?) -> [NSSwitch] {
guard let view else { return [] }
var found: [NSSwitch] = []
if let toggle = view as? NSSwitch { found.append(toggle) }
for subview in view.subviews {
found.append(contentsOf: switches(in: subview))
}
return found
}
@MainActor
private static func makeWindow(
width: CGFloat,
height: CGFloat,
content: AnyView
) -> NSWindow {
let hosting = NSHostingController(rootView: content)
let window = NSWindow(contentViewController: hosting)
window.title = "Redline"
window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
window.isReleasedWhenClosed = false
window.setContentSize(NSSize(width: width, height: height))
return window
}
@MainActor
private static func makeWindow(model: AppModel, width: CGFloat, height: CGFloat) -> NSWindow {
makeWindow(
width: width, height: height,
content: AnyView(SessionsWindowView().environment(model)))
}
/// In-process capture of the live window (no Screen Recording permission needed):
/// evidence of what the running window actually shows.
@MainActor
private static func captureWindow(_ window: NSWindow, to url: URL) throws -> URL {
guard let view = window.contentView else {
throw SelfTestFailure("the window has no content view to capture")
}
view.layoutSubtreeIfNeeded()
window.displayIfNeeded()
guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else {
throw SelfTestFailure("could not allocate a bitmap for the window")
}
view.cacheDisplay(in: view.bounds, to: rep)
guard let png = rep.representation(using: .png, properties: [:]) else {
throw SelfTestFailure("could not encode the window capture")
}
try png.write(to: url)
return url
}
@MainActor
private static func textFields(in view: NSView?) -> [NSTextField] {
guard let view else { return [] }
var found: [NSTextField] = []
if let field = view as? NSTextField, field.isEditable, field.isEnabled {
found.append(field)
}
for subview in view.subviews {
found.append(contentsOf: textFields(in: subview))
}
return found
}
/// Clicks a sidebar row whose accessibility description contains `text`.
@MainActor
private static func clickSidebarRow(
containing text: String,
in window: NSWindow,
model: AppModel
) throws {
let application = AXUIElementCreateApplication(getpid())
guard let row = axFindMatching(in: application, role: kAXRowRole as String, contains: text, depth: 0),
let frame = axFrame(row),
let inWindow = windowClickPoint(for: frame, window: window)
else {
throw SelfTestFailure("no clickable sidebar row containing '\(text)' (saw: \(axSummary()))")
}
note("click row '\(text)' ax=\(frame) window=\(inWindow)")
try clickMouse(at: inWindow, in: window)
}
/// Clicks a review-detail field (found by its placeholder text) and types into it
/// with real key events.
@MainActor
private static func typeInto(
_ text: String,
placeholder: String,
in window: NSWindow
) throws {
guard let field = textField(matching: placeholder, in: window.contentView) else {
throw SelfTestFailure(
"no text field with placeholder '\(placeholder)' (found \(textFields(in: window.contentView).compactMap(\.placeholderString)))")
}
let rectInWindow = field.convert(field.bounds, to: nil)
try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window)
pump(0.2)
// Click first. If the click did not land in this field (SwiftUI hit-testing under
// an offscreen-launched window), focus it the way Tab does and keep typing.
let editingField = (window.firstResponder as? NSTextView)?.delegate as? NSTextField
if editingField !== field {
note("focus fallback for '\(placeholder)'")
window.makeFirstResponder(field)
pump(0.15)
}
guard let editor = window.firstResponder as? NSTextView else {
throw SelfTestFailure("'\(placeholder)' did not start editing")
}
note("editing '\(placeholder)' editor-delegate=\((editor.delegate as? NSTextField) === field)")
try typeKeys(text, into: editor, in: window)
pump(0.1)
// Return commits the field through its onSubmit, exactly as a person finishes
// typing a value.
try pressReturn(in: window)
pump(0.3)
// Leaving the field ends the edit, which is when AppKit commits the value.
window.makeFirstResponder(nil)
pump(0.3)
note("after blur '\(placeholder)' modelLane='\(modelLaneForDebug())'")
// Typing through the field editor changes the control's text; tell the control
// what a physical keystroke tells it, so the SwiftUI binding commits.
NotificationCenter.default.post(
name: NSControl.textDidChangeNotification, object: field)
field.sendAction(field.action, to: field.target)
pump(0.3)
note("typed '\(placeholder)' -> field='\(field.stringValue)'")
try check(!field.stringValue.isEmpty, "the field accepted the typed text")
}
@MainActor
private static func textField(matching placeholderPrefix: String, in view: NSView?) -> NSTextField? {
guard let view else { return nil }
if let field = view as? NSTextField, field.isEditable,
let placeholder = field.placeholderString,
placeholder.hasPrefix(placeholderPrefix)
{
return field
}
for subview in view.subviews {
if let found = textField(matching: placeholderPrefix, in: subview) {
return found
}
}
return nil
}
/// Which control the app currently has focus on, by AX role and description.
private static func focusedControlDescription() -> String {
let application = AXUIElementCreateApplication(getpid())
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
application, kAXFocusedUIElementAttribute as CFString, &value) == .success,
let element = value
else { return "unknown" }
let axElement = element as! AXUIElement
let role = axString(axElement, kAXRoleAttribute) ?? "?"
let description = axString(axElement, kAXDescriptionAttribute) ?? ""
let title = axString(axElement, kAXTitleAttribute) ?? ""
let text = axString(axElement, kAXValueAttribute) ?? ""
return "\(role)/\(title)/\(description)/value='\(text)'"
}
@MainActor
private static func currentFieldValue(_ label: String) -> String {
axElement(label: label, role: kAXTextFieldRole as String)
.flatMap { axString($0, kAXValueAttribute) } ?? ""
}
@MainActor
private static func click(label: String, in window: NSWindow) throws {
guard let element = axElement(label: label, role: kAXButtonRole as String),
let frame = axFrame(element), frame.width > 1, frame.height > 1
else {
throw SelfTestFailure(
"no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))")
}
guard let inWindow = windowClickPoint(for: frame, window: window) else {
throw SelfTestFailure("could not map '\(label)' into window coordinates")
}
note("click '\(label)' ax=\(frame) window=\(inWindow)")
// Finish any text editing first: with a field editor active, the first click
// only ends the edit and never reaches the button.
if window.firstResponder is NSTextView {
window.makeFirstResponder(nil)
pump(0.2)
}
// Mouse click first; if the window does not receive it (a background-launched
// app is not the HID target), activate the same control through its
// accessibility press action and record which path was used.
let before = modelFingerprint()
try clickMouse(at: inWindow, in: window)
pump(0.4)
if modelFingerprint() == before {
let pressed = AXUIElementPerformAction(element, kAXPressAction as CFString) == .success
note("mouse-click had no effect; ax-press=(pressed)")
pump(0.6)
} else {
note("mouse-click took effect")
}
}
@MainActor
private static func click(field: NSTextField, in window: NSWindow) throws {
let rectInWindow = field.convert(field.bounds, to: nil)
try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window)
}
/// Queues a real click and lets the run loop deliver it. Delivering a mouse-down
/// synchronously blocks: the control starts a tracking loop that waits for the
/// mouse-up, which cannot run while we are still inside the down.
@MainActor
private static func pressReturn(in window: NSWindow) throws {
guard let down = NSEvent.keyEvent(
with: .keyDown, location: .zero, modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber, context: nil,
characters: "\r", charactersIgnoringModifiers: "\r",
isARepeat: false, keyCode: 36
) else {
throw SelfTestFailure("could not create a Return key event")
}
NSApp.postEvent(down, atStart: false)
pump(0.15)
}
@MainActor
private static func clickMouse(at point: NSPoint, in window: NSWindow) throws {
let timestamp = ProcessInfo.processInfo.systemUptime
func mouseEvent(_ eventType: NSEvent.EventType) -> NSEvent? {
NSEvent.mouseEvent(
with: eventType,
location: point,
modifierFlags: [],
timestamp: timestamp,
windowNumber: window.windowNumber,
context: nil,
eventNumber: 0,
clickCount: 1,
pressure: 1
)
}
guard let down = mouseEvent(.leftMouseDown), let up = mouseEvent(.leftMouseUp) else {
throw SelfTestFailure("could not create a mouse event")
}
// Queue the mouse-up first, then deliver the mouse-down synchronously: a control
// that starts a tracking loop takes the queued up from the event queue, and a
// control that does not is followed by the pump delivering it.
NSApp.postEvent(up, atStart: false)
window.sendEvent(down)
pump(0.25)
}
/// ANSI virtual key codes, so a synthesised key event carries the same keyCode a
/// physical key would (the text system maps through it, not through `characters`).
private static let ansiKeyCodes: [Character: UInt16] = [
"a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9,
"b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17,
"1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25, "7": 26,
"-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35,
"l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42, ",": 43, "/": 44, "n": 45,
"m": 46, ".": 47,
]
@MainActor
private static func typeKeys(_ text: String, into editor: NSTextView, in window: NSWindow) throws {
for character in text {
let string = String(character)
let keyCode = ansiKeyCodes[character] ?? 0
guard let down = NSEvent.keyEvent(
with: .keyDown,
location: .zero,
modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber,
context: nil,
characters: string,
charactersIgnoringModifiers: string,
isARepeat: false,
keyCode: keyCode
), let up = NSEvent.keyEvent(
with: .keyUp,
location: .zero,
modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber,
context: nil,
characters: string,
charactersIgnoringModifiers: string,
isARepeat: false,
keyCode: keyCode
) else {
throw SelfTestFailure("could not create a key event")
}
NSApp.postEvent(down, atStart: false)
NSApp.postEvent(up, atStart: false)
pump(0.03)
}
pump(0.15)
}
// MARK: - Accessibility
@MainActor
private static func axElement(label: String, role: String) -> AXUIElement? {
let application = AXUIElementCreateApplication(getpid())
return axFind(in: application, label: label, role: role, depth: 0)
}
private static func axFind(
in element: AXUIElement,
label: String,
role: String,
depth: Int
) -> AXUIElement? {
guard depth < 40 else { return nil }
let roleValue = axString(element, kAXRoleAttribute)
if roleValue == role,
axString(element, kAXDescriptionAttribute) == label || axString(element, kAXTitleAttribute) == label {
return element
}
for child in axChildren(element) {
if let found = axFind(in: child, label: label, role: role, depth: depth + 1) {
return found
}
}
return nil
}
private static func axFindMatching(
in element: AXUIElement,
role: String,
contains text: String,
depth: Int
) -> AXUIElement? {
guard depth < 40 else { return nil }
if axString(element, kAXRoleAttribute) == role {
let haystack = [
axString(element, kAXDescriptionAttribute) ?? "",
axString(element, kAXTitleAttribute) ?? "",
axString(element, kAXValueAttribute) ?? "",
].joined(separator: " ")
if haystack.lowercased().contains(text.lowercased()) {
return element
}
}
for child in axChildren(element) {
if let found = axFindMatching(in: child, role: role, contains: text, depth: depth + 1) {
return found
}
}
return nil
}
private static func axString(_ element: AXUIElement, _ attribute: String) -> String? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
return nil
}
return value as? String
}
private static func axChildren(_ element: AXUIElement) -> [AXUIElement] {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
element, kAXChildrenAttribute as CFString, &value) == .success,
let children = value as? [AXUIElement]
else { return [] }
return children
}
private static func axFrame(_ element: AXUIElement) -> CGRect? {
var positionValue: CFTypeRef?
var sizeValue: CFTypeRef?
guard AXUIElementCopyAttributeValue(
element, kAXPositionAttribute as CFString, &positionValue) == .success,
AXUIElementCopyAttributeValue(
element, kAXSizeAttribute as CFString, &sizeValue) == .success,
let positionAX = positionValue, let sizeAX = sizeValue
else { return nil }
var position = CGPoint.zero
var size = CGSize.zero
guard AXValueGetValue(positionAX as! AXValue, .cgPoint, &position),
AXValueGetValue(sizeAX as! AXValue, .cgSize, &size)
else { return nil }
return CGRect(origin: position, size: size)
}
/// Accessibility positions use a top-left origin over every screen; AppKit window
/// coordinates use the primary screen's bottom-left origin.
private static func appKitPoint(fromAXFrame frame: CGRect) -> NSPoint {
let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0
return NSPoint(x: frame.midX, y: primaryTop - frame.midY)
}
/// Maps an accessibility frame (top-left screen origin) into the window's own
/// coordinates, using the window's own AX frame as the reference so the mapping
/// holds on any display arrangement without assuming which screen is primary.
@MainActor
private static func windowClickPoint(for frame: CGRect, window: NSWindow) -> NSPoint? {
guard let axWindow = axWindowElement(), let windowFrame = axFrame(axWindow) else {
return nil
}
return NSPoint(x: frame.midX - windowFrame.minX, y: windowFrame.maxY - frame.midY)
}
private static func axWindowElement() -> AXUIElement? {
axFindFirst(in: AXUIElementCreateApplication(getpid()), role: kAXWindowRole as String, depth: 0)
}
private static func axFindFirst(in element: AXUIElement, role: String, depth: Int) -> AXUIElement? {
guard depth < 20 else { return nil }
if axString(element, kAXRoleAttribute) == role { return element }
for child in axChildren(element) {
if let found = axFindFirst(in: child, role: role, depth: depth + 1) {
return found
}
}
return nil
}
private static func axSummary() -> String {
let application = AXUIElementCreateApplication(getpid())
var parts: [String] = []
collectAXSummary(in: application, depth: 0, into: &parts)
return parts.isEmpty ? "nothing (accessibility tree unavailable)" : parts.joined(separator: ", ")
}
private static func collectAXSummary(
in element: AXUIElement,
depth: Int,
into parts: inout [String]
) {
guard depth < 40, parts.count < 30 else { return }
let role = axString(element, kAXRoleAttribute) ?? "?"
if role == kAXButtonRole as String || role == kAXTextFieldRole as String {
let title = axString(element, kAXTitleAttribute) ?? ""
let description = axString(element, kAXDescriptionAttribute) ?? ""
parts.append("\(role)[\(title)\(description.isEmpty ? "" : "|\(description)")]")
}
for child in axChildren(element) {
collectAXSummary(in: child, depth: depth + 1, into: &parts)
}
}
// MARK: - Utilities and fixtures
/// Runs the app's event loop for a moment, delivering queued mouse and key events.
/// `RunLoop.run` alone does not dequeue NSEvents — only NSApplication does.
@MainActor
private static func pump(_ seconds: TimeInterval) {
let deadline = Date(timeIntervalSinceNow: seconds)
repeat {
if let event = NSApp.nextEvent(
matching: .any,
until: Date(timeIntervalSinceNow: 0.005),
inMode: .default,
dequeue: true
) {
NSApp.sendEvent(event)
}
// The run loop is what resumes main-actor work (the debounced manifest
// write, for example); the event dequeue above is what delivers input.
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.005))
} while Date() < deadline
}
private static func check(_ condition: Bool, _ description: String) throws {
guard condition else { throw SelfTestFailure(description) }
}
@MainActor
private static func appendResult(_ line: String, to url: URL) {
let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
try? (existing + line + "\n").write(to: url, atomically: true, encoding: .utf8)
print(line)
}
/// Step logging that reaches the result file (the app is launched by LaunchServices,
/// so its stdout is not captured).
@MainActor private static var stepLogURL: URL?
@MainActor private static weak var debugModel: AppModel?
/// A cheap change-detector for "did that click do anything".
@MainActor
private static func modelFingerprint() -> String {
guard let model = debugModel else { return "" }
return "\(model.session.id)-\(model.pastSessions.count)-"
+ "\(model.selectedSessionID?.uuidString ?? "nil")"
}
@MainActor
private static func modelLaneForDebug() -> String {
debugModel?.session.context.lane ?? "<no model>"
}
@MainActor
private static func note(_ line: String) {
if let stepLogURL { appendResult("E2E STEP " + line, to: stepLogURL) }
}
@discardableResult
static func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) throws -> UUID {
let id = UUID()
let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400)
let dir = paths.archiveDirectory(id)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png"
try makePNG(width: 16, height: 9, red: 0.4, green: 0.4, blue: 0.4)
.write(to: dir.appendingPathComponent(pngName))
let capture = Capture(
id: UUID(), sequence: 1, fileName: pngName,
pixelWidth: 16, pixelHeight: 9, scale: 1.0, capturedAt: createdAt)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .archived, captures: [capture],
pdfFileName: nil,
context: ReviewContext(lane: "dev03", deployedVersion: "v0.9.0", commit: "0ldc0de"))
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try encoder.encode(session).write(to: dir.appendingPathComponent("session.json"))
return id
}
static func makePNG(
width: Int, height: Int, red: CGFloat, green: CGFloat, blue: CGFloat
) throws -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(
data: nil, width: width, height: height,
bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
), let image = {
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
return context.makeImage()
}() else {
throw SelfTestFailure("could not draw a test PNG")
}
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(
data, "public.png" as CFString, 1, nil) else {
throw SelfTestFailure("could not create a PNG destination")
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
throw SelfTestFailure("could not encode a test PNG")
}
return data as Data
}
}
struct SelfTestFailure: Error, CustomStringConvertible {
let description: String
init(_ description: String) { self.description = description }
}
+283 -13
View File
@@ -46,6 +46,11 @@ enum PanelSnapshot {
let region = sampleRegion()
// Two real past sessions through the REAL store paths (one sent with a PDF in
// the outbox, one closed without ever sending) so panel-06b has the exact two
// states the Past submissions window must distinguish.
try await seedPastSessions(to: model)
// 01 — Screen Recording missing (no public mutator; snapshot-only seam).
model.snapshotSetScreenRecordingGranted(false)
model.replaceRegion(nil)
@@ -61,6 +66,55 @@ enum PanelSnapshot {
try renderMenuBar(model: model, to: directory, name: "03-empty-session")
// 04 — three real PNGs in the temp spool so SessionStrip thumbnails decode.
try await addSampleCaptures(to: model)
try renderMenuBar(model: model, to: directory, name: "04-captures-present")
// 05 — two inspected PDFs in the temp ledger, one marked / one not.
try await seedReturns(model: model)
try renderMenuBar(model: model, to: directory, name: "05-returns-present")
// 06 — SettingsView against the same isolated model.
try render(
SettingsView().environment(model),
to: directory.appendingPathComponent("panel-06-settings.png"),
width: 460,
height: 820
)
// 06b — the sessions window: real sidebar, pages grid and inspector.
model.setPastSessions(try await model.spool.archivedSessions())
try render(
SessionsWindowView().environment(model),
to: directory.appendingPathComponent("panel-06b-sessions-window.png"),
width: 1100,
height: 700
)
// 15 — the window with a kept past session selected (read-only inspector).
if let kept = model.pastSessions.first {
model.selectSession(kept.id)
try render(
SessionsWindowView().environment(model),
to: directory.appendingPathComponent("panel-15-past-session.png"),
width: 1100,
height: 700
)
model.selectSession(model.session.id)
}
// A real PDF built by the production composer, so the reference footer and the
// document info can be inspected (and opened) rather than assumed.
try writeSamplePDF(to: directory.appendingPathComponent("sample-review.pdf"), model: model)
// 07/08/09 — OneDrive-mode Settings + menu bar, on a SEPARATE isolated model so
// this transport switch never bleeds into the AirDrop-mode panels above.
try await captureOneDrivePanels(to: directory)
}
/// Three real PNGs appended to the given model's temp spool so SessionStrip
/// thumbnails decode. Shared by panel 04 (AirDrop) and panel 09 (OneDrive).
@MainActor
private static func addSampleCaptures(to model: AppModel) async throws {
let swatches: [(CGFloat, CGFloat, CGFloat)] = [
(0.85, 0.22, 0.18),
(0.18, 0.62, 0.32),
@@ -77,16 +131,152 @@ enum PanelSnapshot {
)
}
model.replaceSession(try await model.spool.currentSession())
try renderMenuBar(model: model, to: directory, name: "04-captures-present")
}
// 05 — two inspected PDFs in the temp ledger, one marked / one not.
try await seedReturns(model: model)
try renderMenuBar(model: model, to: directory, name: "05-returns-present")
/// Panels 07-09: OneDrive transport, on its own isolated model/temp root so
/// switching transport here never touches the AirDrop-mode model above, the real
/// home directory, or UserDefaults.standard. The "resolved" and "not found" states
/// are produced by calling the real OneDriveLocator functions against fake home
/// trees built under this snapshot's own temp root — never a hand-typed path.
@MainActor
private static func captureOneDrivePanels(to directory: URL) async throws {
let (model, root) = try makeIsolatedModel()
defer { try? FileManager.default.removeItem(at: root) }
model.setTransport(.oneDrive)
// 06 — SettingsView against the same isolated model.
// 07 — a resolved OneDrive folder, shaped like the real default
// (…/Library/CloudStorage/OneDrive-MMDGROUP/Redline): a fake home tree with a
// real OneDrive-MMDGROUP directory under it, resolved via the same pure
// OneDriveLocator function production code uses — never a hand-typed path.
let fakeHomeWithOneDrive = root.appendingPathComponent("fake-home-with-onedrive", isDirectory: true)
let syncRoot = fakeHomeWithOneDrive
.appendingPathComponent("Library/CloudStorage/OneDrive-MMDGROUP", isDirectory: true)
try FileManager.default.createDirectory(at: syncRoot, withIntermediateDirectories: true)
guard let resolvedFolder = OneDriveLocator.defaultRedlineFolder(
home: fakeHomeWithOneDrive, fileManager: .default
) else {
throw SnapshotError.oneDriveFixtureFailed("fake OneDrive-MMDGROUP root did not resolve")
}
model.setResolvedOneDriveFolder(resolvedFolder)
try render(
SettingsView().environment(model),
to: directory.appendingPathComponent("panel-06-settings.png")
to: directory.appendingPathComponent("panel-07-settings-onedrive.png"),
width: 460,
height: 820
)
// 08 — no OneDrive folder found: a fake home with NO Library/CloudStorage at
// all, and a throwaway UserDefaults suite (never .standard, never touched
// before) so the stored-override check also legitimately finds nothing.
let fakeHomeWithoutOneDrive = root.appendingPathComponent("fake-home-without-onedrive", isDirectory: true)
try FileManager.default.createDirectory(at: fakeHomeWithoutOneDrive, withIntermediateDirectories: true)
let isolatedDefaults = try makeIsolatedDefaultsSuite()
defer { isolatedDefaults.defaults.removePersistentDomain(forName: isolatedDefaults.suiteName) }
let missingFolder = OneDriveLocator.resolveOneDriveFolder(
defaults: isolatedDefaults.defaults, home: fakeHomeWithoutOneDrive, fileManager: .default
)
guard missingFolder == nil else {
throw SnapshotError.oneDriveFixtureFailed("fake home without OneDrive unexpectedly resolved")
}
model.setResolvedOneDriveFolder(nil)
try render(
SettingsView().environment(model),
to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png"),
width: 460,
height: 820
)
// 09 — menu bar panel, 3 captures present, OneDrive mode ("Send to OneDrive").
model.snapshotSetScreenRecordingGranted(true)
model.replaceRegion(sampleRegion())
try await addSampleCaptures(to: model)
try renderMenuBar(model: model, to: directory, name: "09-captures-present-onedrive")
// 10 — update idle: 3 captures, no update available, footer "Redline <ver>", row "Check for updates".
let (updateModel, updateRoot) = try makeIsolatedModel()
defer { try? FileManager.default.removeItem(at: updateRoot) }
updateModel.snapshotSetScreenRecordingGranted(true)
updateModel.replaceRegion(sampleRegion())
try await addSampleCaptures(to: updateModel)
// No update set, updateChecker in idle state, no previous version
updateModel.snapshotSetPreviousVersion(nil)
try renderMenuBar(model: updateModel, to: directory, name: "10-update-idle")
// 11 — update checking: same as 10 but isCheckingForUpdates = true.
updateModel.snapshotSetIsCheckingForUpdates(true)
try renderMenuBar(model: updateModel, to: directory, name: "11-update-checking")
updateModel.snapshotSetIsCheckingForUpdates(false)
// 12 — update up-to-date: footer status line reads "Redline <ver> is up to date, checked 10:42 Dubai".
let upToDateMessage = "Redline \(updateModel.appVersion) is up to date, checked 10:42 Dubai"
updateModel.snapshotSetUpdateStatusMessage(upToDateMessage)
try renderMenuBar(model: updateModel, to: directory, name: "12-update-uptodate")
// 13 — update staged: row "Update to 9.9.9" present, footer status "Update to 9.9.9 is ready".
updateModel.snapshotSetUpdateAvailable(version: "9.9.9", notes: "Test release")
updateModel.snapshotSetUpdateStatusMessage("Update to 9.9.9 is ready")
try renderMenuBar(model: updateModel, to: directory, name: "13-update-staged")
// 14 — update revert: row "Revert to 0.2.0" present.
updateModel.snapshotSetUpdateAvailable(version: nil, notes: nil) // Clear the staged update
updateModel.snapshotSetUpdateStatusMessage(nil)
updateModel.snapshotSetPreviousVersion("0.2.0")
try renderMenuBar(model: updateModel, to: directory, name: "14-update-revert")
}
@MainActor
private static func seedPastSessions(to model: AppModel) async throws {
_ = try await model.spool.append(
pngData: try makePNGData(width: 192, height: 108, red: 0.55, green: 0.35, blue: 0.85),
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
_ = try await model.spool.append(
pngData: try makePNGData(width: 192, height: 108, red: 0.25, green: 0.7, blue: 0.6),
pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date())
let sentSession = try await model.spool.setContext(
ReviewContext(
lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout flow"))
let sentName = PDFFileName.make(
builtAt: Date(), lane: sentSession.context.lane, sessionID: sentSession.id)
_ = try await model.spool.archiveCurrent(pdfFileName: sentName)
// The real send writes the PDF to the outbox; the fixture does the same so the
// row's PDF action is genuinely live in the snapshot.
try Data("%PDF-1.4\n% snapshot fixture\n".utf8).write(
to: model.paths.outbox.appendingPathComponent(sentName))
_ = try await model.spool.append(
pngData: try makePNGData(width: 160, height: 90, red: 0.9, green: 0.55, blue: 0.2),
pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date())
_ = try await model.spool.setContext(
ReviewContext(
lane: "OMS test lane", deployedVersion: "v2.0.0-rc3", commit: "9f3e2d1",
reviewer: "Ben Hippler"))
_ = try await model.spool.closeCurrentSession()
// The live session shown in panels 03/04/05/15 carries details too.
_ = try await model.spool.setContext(
ReviewContext(
lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "dashboard review"))
model.replaceSession(try await model.spool.currentSession())
// Both seeded sessions are really on disk by now; load them into the model so
// the panel's recent list is live rather than empty.
model.setPastSessions(try await model.spool.archivedSessions())
}
/// A real PDF from the production composer: one page per capture, header reference
/// line and the review footer. Written next to the panels so it can be opened.
@MainActor
private static func writeSamplePDF(to url: URL, model: AppModel) throws {
let session = model.session
guard !session.isEmpty else { return }
let sourceDir = model.paths.sessionDirectory(session.id)
_ = try PDFComposer().compose(
session: session,
imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) },
title: "Redline – \(session.context.lane) – \(DubaiTime.stamp(session.createdAt))",
to: url,
toolVersion: model.appVersion
)
}
@@ -99,10 +289,24 @@ enum PanelSnapshot {
}
@MainActor
private static func render(_ view: some View, to url: URL) throws {
let wrapped = view
.frame(width: panelWidth, alignment: .topLeading)
private static func render(
_ view: some View,
to url: URL,
width: CGFloat = panelWidth,
height: CGFloat? = nil
) throws {
// A fixed-size render (a whole window) must fill its frame; a popover render
// sizes to its content. fixedSize on a split view collapses its columns.
let wrapped = Group {
if let height {
view.frame(width: width, height: height)
} else {
view
.frame(width: width, alignment: .topLeading)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(width: width, height: height, alignment: .topLeading)
.background(Color(nsColor: .windowBackgroundColor))
let hosting = NSHostingView(rootView: wrapped)
@@ -110,7 +314,7 @@ enum PanelSnapshot {
hosting.appearance = NSAppearance(named: .aqua)
let window = NSWindow(
contentRect: NSRect(x: -10_000, y: -10_000, width: panelWidth, height: 64),
contentRect: NSRect(x: -10_000, y: -10_000, width: width, height: 200),
styleMask: [.borderless],
backing: .buffered,
defer: false
@@ -125,17 +329,26 @@ enum PanelSnapshot {
hosting.layoutSubtreeIfNeeded()
var size = hosting.fittingSize
if let height {
size.height = height
} else {
if size.height < 1 {
size.height = hosting.intrinsicContentSize.height
}
if size.height < 1 { size.height = 240 }
size.width = panelWidth
}
size.width = width
size.height = ceil(size.height)
hosting.setFrameSize(size)
window.setContentSize(size)
hosting.layoutSubtreeIfNeeded()
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.05))
// A split view (sidebar + inspector) needs a real display cycle before its
// columns and list rows exist; a single layout pass renders blank columns.
window.displayIfNeeded()
RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.35))
hosting.layoutSubtreeIfNeeded()
window.displayIfNeeded()
let bounds = hosting.bounds
guard let rep = hosting.bitmapImageRepForCachingDisplay(in: bounds) else {
@@ -163,6 +376,9 @@ enum PanelSnapshot {
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
let ledger = try ReturnLedger(paths: paths)
// Isolated defaults: rendering a panel must never read or write the real
// age-limit preference.
let suite = try makeIsolatedDefaultsSuite()
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
@@ -171,12 +387,30 @@ enum PanelSnapshot {
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger)
watcher: ReturnWatcher(paths: paths, ledger: ledger),
retentionDefaults: suite.defaults
)
model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder)
return (model, root)
}
/// A throwaway UserDefaults suite — never `.standard` — for the panel-08 fixture,
/// the same isolation pattern ShotdeckCoreTests uses for TransportSettings/
/// OneDriveLocator tests.
private struct IsolatedDefaultsSuite {
let suiteName: String
let defaults: UserDefaults
}
private static func makeIsolatedDefaultsSuite() throws -> IsolatedDefaultsSuite {
let suiteName = "shotdeck-panel-snapshot-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: suiteName) else {
throw SnapshotError.oneDriveFixtureFailed("could not create isolated UserDefaults suite")
}
defaults.removePersistentDomain(forName: suiteName)
return IsolatedDefaultsSuite(suiteName: suiteName, defaults: defaults)
}
@MainActor
private static func seedReturns(model: AppModel) async throws {
let watch = model.paths.watchFolder
@@ -276,6 +510,40 @@ extension AppModel {
)
self[keyPath: writable] = granted
}
/// Snapshot-only: set isCheckingForUpdates without triggering a real check.
func snapshotSetIsCheckingForUpdates(_ checking: Bool) {
let writable: ReferenceWritableKeyPath<AppModel, Bool> = unsafeBitCast(
\AppModel.isCheckingForUpdates, to: ReferenceWritableKeyPath<AppModel, Bool>.self
)
self[keyPath: writable] = checking
}
/// Snapshot-only: set updateStatusMessage for panel display.
func snapshotSetUpdateStatusMessage(_ message: String?) {
setUpdateStatus(message)
}
/// Snapshot-only: set updateAvailable without triggering a real download.
func snapshotSetUpdateAvailable(version: String?, notes: String?) {
if let version = version, let notes = notes {
let writable: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?> = unsafeBitCast(
\AppModel.updateAvailable, to: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?>.self
)
self[keyPath: writable] = (version: version, notes: notes)
} else {
let writable: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?> = unsafeBitCast(
\AppModel.updateAvailable, to: ReferenceWritableKeyPath<AppModel, (version: String, notes: String)?>.self
)
self[keyPath: writable] = nil
}
}
/// Snapshot-only: set a fake previousVersion for the revert panel.
func snapshotSetPreviousVersion(_ version: String?) {
updateChecker.snapshotPreviousVersionOverride = version
updateChecker.snapshotUsesPreviousVersionOverride = true
}
}
private enum SnapshotError: Error, CustomStringConvertible {
@@ -283,6 +551,7 @@ private enum SnapshotError: Error, CustomStringConvertible {
case encodeFailed(String)
case pngGenerationFailed
case pdfWriteFailed(String)
case oneDriveFixtureFailed(String)
var description: String {
switch self {
@@ -290,6 +559,7 @@ private enum SnapshotError: Error, CustomStringConvertible {
case .encodeFailed(let name): return "PNG encode failed for \(name)"
case .pngGenerationFailed: return "CoreGraphics PNG generation failed"
case .pdfWriteFailed(let name): return "could not write \(name)"
case .oneDriveFixtureFailed(let detail): return "OneDrive snapshot fixture failed: \(detail)"
}
}
}
+802 -1
View File
@@ -1,6 +1,9 @@
import AppKit
import CoreGraphics
import Darwin
import Foundation
import ImageIO
import PDFKit
import ShotdeckCore
/// In-process self-test for the region picker, driven by `SHOTDECK_PICKER_SELFTEST`.
@@ -113,7 +116,10 @@ enum PickerSelfTest {
fflush(stdout)
runRegionPersistPhase()
exit(0)
// Hop off this MainActor job so the SEND-TRUTH Task can run; do not
// exit(0) here — runSendTruthPhase prints its own PASS/FAIL, then
// chains to UPDATE-SELFTEST (or exits if that phase is not requested).
runSendTruthPhase()
}
/// Phase 2: writes a known region under `CaptureRegion.defaultsKey`, reloads it through
@@ -157,6 +163,783 @@ enum PickerSelfTest {
fflush(stdout)
}
/// Phase 3: drive SendController's share-outcome seams with no AirDrop sheet.
/// Fail path must leave the session open in the temp spool; success path archives
/// and mints a fresh empty session. Scheduled as a new MainActor job because this
/// function is called from inside `execute()` — a nested run-loop wait would never
/// let the Task start. On success, chains to UPDATE-SELFTEST instead of exiting.
private static func runSendTruthPhase() {
Task { @MainActor in
do {
try await executeSendTruth()
print("SEND-TRUTH PASS")
fflush(stdout)
if !startUpdateSelfTestIfRequested(), !startOneDriveSelfTestIfRequested() {
exit(0)
}
} catch {
print("SEND-TRUTH FAIL \(error)")
fflush(stdout)
exit(1)
}
}
}
private static func executeSendTruth() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-send-truth-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let paths = try AppSupportPaths(
root: root,
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
let ledger = try ReturnLedger(paths: paths)
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger)
)
model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder)
let png = try makeTinyPNGData()
_ = try await model.spool.append(
pngData: png,
pixelWidth: 64,
pixelHeight: 48,
scale: 1,
capturedAt: Date()
)
model.replaceSession(try await model.spool.currentSession())
let openID = model.session.id
guard !model.session.isEmpty else {
sendTruthFail("seeded session was empty")
}
let pending = try await model.composePDFForSend(outbox: model.outboxURL, transport: .airDrop)
guard fm.fileExists(atPath: pending.fileURL.path) else {
sendTruthFail("PDF was not written")
}
model.handleDidFailToShareItems(fileName: pending.fileName)
let still = try await model.spool.currentSession()
guard still.id == openID, !still.isEmpty, still.state == .open else {
sendTruthFail("fail path archived or replaced the session")
}
let spoolDir = paths.sessionDirectory(openID)
guard fm.fileExists(atPath: spoolDir.path) else {
sendTruthFail("fail path: session missing from temp spool")
}
guard let status = model.statusLine, status.contains("nothing was sent") else {
sendTruthFail("fail path status missing 'nothing was sent': \(model.statusLine ?? "nil")")
}
let pageWord = pending.pageCount == 1 ? "page" : "pages"
await model.handleDidShareItems(
fileName: pending.fileName,
sentSummary: "Sent — \(pending.pageCount) \(pageWord).")
let fresh = try await model.spool.currentSession()
guard fresh.isEmpty, fresh.id != openID, fresh.state == .open else {
sendTruthFail("success path did not mint a fresh empty session")
}
let archived = try await model.spool.archivedSessions()
guard archived.contains(where: { $0.id == openID && $0.state == .archived }) else {
sendTruthFail("success path did not archive the session")
}
let archiveDir = paths.archiveDirectory(openID)
guard fm.fileExists(atPath: archiveDir.path) else {
sendTruthFail("success path: archive dir missing")
}
guard !fm.fileExists(atPath: spoolDir.path) else {
sendTruthFail("success path: session still in spool")
}
}
private static func makeTinyPNGData() throws -> Data {
let width = 64
let height = 48
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
sendTruthFail("could not create PNG context")
}
context.setFillColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else {
sendTruthFail("could not make CGImage")
}
let buffer = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(
buffer,
"public.png" as CFString,
1,
nil
) else {
sendTruthFail("could not create PNG destination")
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
sendTruthFail("could not finalize PNG")
}
return buffer as Data
}
private static func sendTruthFail(_ reason: String) -> Never {
print("SEND-TRUTH FAIL \(reason)")
fflush(stdout)
exit(1)
}
/// Phase 4: builds a fake 99.0.0 bundle, serves a local appcast, stages via
/// `checkNow`, then `installStaged` into the env dir — never `/Applications`.
/// Returns true when the async phase was scheduled (it calls `exit` itself).
@discardableResult
private static func startUpdateSelfTestIfRequested() -> Bool {
guard let raw = ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"],
!raw.isEmpty
else { return false }
let output = URL(fileURLWithPath: raw, isDirectory: true)
Task { @MainActor in
do {
try await runUpdateSelfTest(outputDirectory: output)
print("UPDATE-SELFTEST PASS version=99.0.0")
fflush(stdout)
if !startOneDriveSelfTestIfRequested() {
exit(0)
}
} catch let error as UpdateSelfTestError {
updateFail(error.description)
} catch {
updateFail(String(describing: error))
}
}
return true
}
/// (a) rejects an invalidly-signed payload, (b) stages the same payload once
/// properly signed, (c) installs it atomically into a throwaway target with
/// exactly one rollback copy, (d) reverts back. Never touches `/Applications`.
private static func runUpdateSelfTest(outputDirectory: URL) async throws {
let fm = FileManager.default
try fm.createDirectory(at: outputDirectory, withIntermediateDirectories: true)
guard let sourceApp = ownAppBundleURL() else {
throw UpdateSelfTestError.detail("own bundle is not a .app (\(Bundle.main.bundleURL.path))")
}
guard let originalVersion = readShortVersion(atAppURL: sourceApp) else {
throw UpdateSelfTestError.detail("own Info.plist has no CFBundleShortVersionString")
}
let payload = outputDirectory.appendingPathComponent("payload", isDirectory: true)
if fm.fileExists(atPath: payload.path) {
try fm.removeItem(at: payload)
}
try fm.createDirectory(at: payload, withIntermediateDirectories: true)
let fakeApp = payload.appendingPathComponent("Redline.app")
try fm.copyItem(at: sourceApp, to: fakeApp)
let plistURL = fakeApp.appendingPathComponent("Contents/Info.plist")
let plistData = try Data(contentsOf: plistURL)
guard var plist = try PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any] else {
throw UpdateSelfTestError.detail("could not parse copied Info.plist")
}
plist["CFBundleShortVersionString"] = "99.0.0"
let rewritten = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
try rewritten.write(to: plistURL)
// Editing Info.plist after copying it invalidates the inherited signature —
// Info.plist is a sealed special slot in the CodeDirectory — so this fake
// bundle is genuinely unsigned-in-effect without us stripping anything.
let zipURL = outputDirectory.appendingPathComponent("Redline-99.0.0.zip")
let appcastURL = outputDirectory.appendingPathComponent("appcast.json")
func writeZipAndAppcast() throws {
if fm.fileExists(atPath: zipURL.path) {
try fm.removeItem(at: zipURL)
}
try runDitto(arguments: ["-c", "-k", payload.path, zipURL.path])
let zipData = try Data(contentsOf: zipURL)
let hex = UpdateChecker.sha256Hex(zipData)
let appcast: [String: String] = [
"version": "99.0.0",
"zipURL": zipURL.absoluteString,
"sha256": hex,
"notes": "UPDATE-SELFTEST",
]
let appcastData = try JSONSerialization.data(withJSONObject: appcast, options: [.sortedKeys])
try appcastData.write(to: appcastURL)
}
try writeZipAndAppcast()
let defaults = UserDefaults.standard
let previousAppcastPref = defaults.string(forKey: UpdateChecker.appcastURLDefaultsKey)
defaults.set(appcastURL.absoluteString, forKey: UpdateChecker.appcastURLDefaultsKey)
defer {
if let previousAppcastPref {
defaults.set(previousAppcastPref, forKey: UpdateChecker.appcastURLDefaultsKey)
} else {
defaults.removeObject(forKey: UpdateChecker.appcastURLDefaultsKey)
}
}
let (model, isolatedRoot) = try makeIsolatedUpdateModel()
defer { try? fm.removeItem(at: isolatedRoot) }
// (a) NEGATIVE — invalidly-signed payload must never be offered or staged.
await model.updateChecker.checkNow()
guard model.updateAvailable == nil else {
throw UpdateSelfTestError.detail(
"reject-unsigned: updateAvailable=\(model.updateAvailable?.version ?? "nil") (expected nil)"
)
}
guard model.updateChecker.statusMessage == "Update is not signed by MMD — not installed." else {
throw UpdateSelfTestError.detail(
"reject-unsigned: statusMessage=\(model.updateChecker.statusMessage ?? "nil")"
)
}
print("UPDATE-SELFTEST reject-unsigned PASS")
fflush(stdout)
// (b) POSITIVE — re-sign the same bundle, re-zip, re-serve; must now stage.
let signIdentity = ProcessInfo.processInfo.environment["SHOTDECK_SELFTEST_SIGN_IDENTITY"]
?? "Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
try runCodesign(identity: signIdentity, path: fakeApp.path)
try writeZipAndAppcast()
await model.updateChecker.checkNow()
guard model.updateAvailable?.version == "99.0.0" else {
throw UpdateSelfTestError.detail(
"staged-signed: updateAvailable=\(model.updateAvailable?.version ?? "nil")"
)
}
guard let staged = model.updateChecker.stagedAppURL else {
throw UpdateSelfTestError.detail("staged-signed: staged payload missing")
}
guard staged.lastPathComponent == "Redline.app" else {
throw UpdateSelfTestError.detail("staged-signed: staged name \(staged.lastPathComponent)")
}
let stagedExe = staged.appendingPathComponent("Contents/MacOS/Shotdeck")
guard fm.fileExists(atPath: stagedExe.path) else {
throw UpdateSelfTestError.detail("staged-signed: staged Contents/MacOS/Shotdeck missing")
}
print("UPDATE-SELFTEST staged-signed PASS")
fflush(stdout)
// (c) ATOMIC INSTALL — a throwaway target pre-populated with the real
// running version; never `/Applications`.
let tempAppsRoot = outputDirectory.appendingPathComponent("Applications", isDirectory: true)
if fm.fileExists(atPath: tempAppsRoot.path) {
try fm.removeItem(at: tempAppsRoot)
}
try fm.createDirectory(at: tempAppsRoot, withIntermediateDirectories: true)
let tempTarget = tempAppsRoot.appendingPathComponent("Redline.app")
try fm.copyItem(at: sourceApp, to: tempTarget)
model.updateChecker.installStaged(to: tempTarget)
guard let installedVersion = readShortVersion(atAppURL: tempTarget) else {
throw UpdateSelfTestError.detail("atomic-install: installed Info.plist unreadable")
}
guard installedVersion == "99.0.0" else {
throw UpdateSelfTestError.detail("atomic-install: installed version \(installedVersion)")
}
let previousCopy = tempAppsRoot.appendingPathComponent("Redline.app.previous")
guard let previousVersionAfterInstall = readShortVersion(atAppURL: previousCopy) else {
throw UpdateSelfTestError.detail("atomic-install: Redline.app.previous missing or unreadable")
}
guard previousVersionAfterInstall == originalVersion else {
throw UpdateSelfTestError.detail(
"atomic-install: previous version=\(previousVersionAfterInstall) expected=\(originalVersion)"
)
}
try assertNoLeftoverEntries(in: tempAppsRoot, expecting: ["Redline.app", "Redline.app.previous"])
print("UPDATE-SELFTEST atomic-install PASS")
fflush(stdout)
// (d) REVERT — the rollback copy swaps back in; the just-replaced version
// becomes the new rollback copy, so a revert is itself reversible.
model.updateChecker.revertToPrevious(target: tempTarget)
guard let revertedVersion = readShortVersion(atAppURL: tempTarget) else {
throw UpdateSelfTestError.detail("revert: reverted Info.plist unreadable")
}
guard revertedVersion == originalVersion else {
throw UpdateSelfTestError.detail("revert: target version=\(revertedVersion) expected=\(originalVersion)")
}
guard let previousVersionAfterRevert = readShortVersion(atAppURL: previousCopy) else {
throw UpdateSelfTestError.detail("revert: Redline.app.previous missing or unreadable")
}
guard previousVersionAfterRevert == "99.0.0" else {
throw UpdateSelfTestError.detail(
"revert: previous version=\(previousVersionAfterRevert) expected=99.0.0"
)
}
try assertNoLeftoverEntries(in: tempAppsRoot, expecting: ["Redline.app", "Redline.app.previous"])
print("UPDATE-SELFTEST revert PASS")
fflush(stdout)
}
private static func readShortVersion(atAppURL url: URL) -> String? {
let plistURL = url.appendingPathComponent("Contents/Info.plist")
guard let dict = NSDictionary(contentsOf: plistURL) as? [String: Any] else { return nil }
return dict["CFBundleShortVersionString"] as? String
}
private static func runCodesign(identity: String, path: String) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")
process.arguments = ["--force", "--deep", "--sign", identity, path]
let err = Pipe()
process.standardError = err
process.standardOutput = Pipe()
try process.run()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
let message = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
throw UpdateSelfTestError.detail("codesign failed: \(message)")
}
}
private static func assertNoLeftoverEntries(in directory: URL, expecting expected: Set<String>) throws {
let entries = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
let unexpected = entries.filter { !expected.contains($0) }
guard unexpected.isEmpty else {
throw UpdateSelfTestError.detail(
"unexpected entries in \(directory.path): \(unexpected.joined(separator: ", "))"
)
}
}
private static func ownAppBundleURL() -> URL? {
let bundle = Bundle.main.bundleURL
if bundle.pathExtension == "app" { return bundle }
let up3 = bundle
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
if up3.pathExtension == "app" { return up3 }
return nil
}
private static func makeIsolatedUpdateModel() throws -> (AppModel, URL) {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-update-selftest-\(UUID().uuidString)", isDirectory: true)
let paths = try AppSupportPaths(
root: root,
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
let ledger = try ReturnLedger(paths: paths)
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger)
)
return (model, root)
}
private static func runDitto(arguments: [String]) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
process.arguments = arguments
let err = Pipe()
process.standardError = err
process.standardOutput = Pipe()
try process.run()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
let message = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
throw UpdateSelfTestError.detail("ditto failed: \(message)")
}
}
private static func updateFail(_ detail: String) -> Never {
print("UPDATE-SELFTEST FAIL \(detail)")
fflush(stdout)
exit(1)
}
/// Phase 5: proves the OneDrive transport end to end against a REAL sync root —
/// resolved at runtime via `OneDriveLocator.syncRoots()`, never a hardcoded path, so
/// this runs correctly on any Mac/account that has OneDrive signed in (MMD-named
/// root preferred, same as production). Triggered by `SHOTDECK_ONEDRIVE_SELFTEST`
/// when chained after PICKER/SEND-TRUTH/UPDATE-SELFTEST — the exact pattern
/// `startUpdateSelfTestIfRequested` uses for its own env var. Returns true when the
/// async phase was scheduled (it calls `exit` itself).
@discardableResult
private static func startOneDriveSelfTestIfRequested() -> Bool {
guard ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil else {
return false
}
runOneDriveSelfTestAndExit()
return true
}
/// Entry point for running ONLY the SEND-TRUTH phase, bypassing the on-screen picker
/// chain entirely — the chain's REGION-PERSIST phase needs an active display
/// (CGDisplayIsActive) and exits before SEND-TRUTH in headless/remote sessions.
/// Escape hatch: `REDLINE_SELFTEST_PHASE=sendtruth`.
static func runSendTruthOnlyIfRequested() {
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" else {
return
}
// Same hop as runOneDriveOnlyIfRequested(): a plain main-queue turn after NSApp
// starts, so AppKit/PDFKit calls inside the phase are not racing app launch.
DispatchQueue.main.async {
MainActor.assumeIsolated {
runSendTruthAndExit()
}
}
}
private static func runSendTruthAndExit() {
Task { @MainActor in
do {
try await executeSendTruth()
print("SEND-TRUTH PASS")
fflush(stdout)
exit(0)
} catch {
print("SEND-TRUTH FAIL \(error)")
fflush(stdout)
exit(1)
}
}
}
/// Entry point for running ONLY this phase, bypassing the on-screen picker chain
/// entirely. The harness has no other per-phase selector, so this is the escape
/// hatch: `REDLINE_SELFTEST_PHASE=onedrive`.
static func runOneDriveOnlyIfRequested() {
guard ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" else {
return
}
// Same hop as runIfRequested(): a plain main-queue turn after NSApp starts, so
// AppKit/PDFKit calls inside the phase are not racing app launch.
DispatchQueue.main.async {
MainActor.assumeIsolated {
runOneDriveSelfTestAndExit()
}
}
}
private static func runOneDriveSelfTestAndExit() {
// Never a false PASS: no real OneDrive sync root on this machine/account is a
// SKIP (still non-zero exit), not silently treated as passing.
guard let syncRoot = OneDriveLocator.syncRoots().first else {
print("ONEDRIVE-SELFTEST SKIP no OneDrive sync root")
fflush(stdout)
exit(1)
}
Task { @MainActor in
do {
let folder = try await executeOneDriveSelfTest(syncRoot: syncRoot)
print("ONEDRIVE-SELFTEST PASS path=\(folder.path)")
fflush(stdout)
exit(0)
} catch let error as OneDriveSelfTestError {
oneDriveFail(error.description)
} catch {
oneDriveFail(String(describing: error))
}
}
}
/// Sub-step 1: builds a session, sends it through the OneDrive branch of
/// `send(anchor: nil)` against a NEW folder under `syncRoot`, confirms the watcher
/// does NOT report the freshly-written unmarked PDF as a return, then adds a real
/// PDFKit ink annotation in place (what the iPad does) and confirms the watcher now
/// reports it as commented.
///
/// Sub-step 1b: rapid transport toggling (chooseTransport(.airDrop) immediately
/// followed by chooseTransport(.oneDrive), no await between them) must still end
/// with the watcher pointed at the OneDrive folder — proves the generation-guarded
/// reconcile in chooseTransport/chooseOneDriveFolder (SettingsView.swift) really
/// does let the last choice win instead of an earlier, superseded call applying its
/// stale folder after a later one already won.
///
/// Sub-step 1c: the OTHER race — a toggle immediately followed by Send, with no
/// sleep at all before send() runs. Proves send() awaits `pendingReconcileTask`
/// before snapshotting transport/folder: a freshly-sent, still-unmarked PDF must
/// never be reported as an already-returned document (which is exactly what would
/// happen if send() raced ahead while recordUncommented was still `true`, stale
/// from the .airDrop leg of the toggle).
///
/// Sub-step 2: relaunch simulation — the exact BLOCKER scenario this phase exists to
/// catch. OneDrive is still persisted in defaults from sub-step 1; builds a FRESH
/// model the same way the real app launches (`AppDelegate.makeLaunchModel()` itself,
/// not a reimplementation), bootstraps it, then marks a PDF in the folder in place —
/// the relaunched watcher must report it. A temp app-support root keeps this off the
/// real ~/Library/Application Support/Shotdeck.
///
/// Never deletes anything under OneDrive — the created folder and PDFs are left in
/// place for Ben to inspect / for the real iPad round trip.
private static func executeOneDriveSelfTest(syncRoot: URL) async throws -> URL {
let fm = FileManager.default
// UserDefaults.standard is the ONLY defaults instance send()/TransportSettings
// actually read at runtime (there is no defaults-threading through AppModel), so
// "isolated" here means snapshot-and-restore around the real keys — the same
// pattern runRegionPersistPhase already uses for CaptureRegion.defaultsKey.
let defaults = UserDefaults.standard
let previousTransport = defaults.string(forKey: TransportSettings.transportDefaultsKey)
let previousFolder = defaults.string(forKey: TransportSettings.oneDriveFolderDefaultsKey)
defer {
if let previousTransport {
defaults.set(previousTransport, forKey: TransportSettings.transportDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.transportDefaultsKey)
}
if let previousFolder {
defaults.set(previousFolder, forKey: TransportSettings.oneDriveFolderDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.oneDriveFolderDefaultsKey)
}
}
let stamp = DubaiTime.fileStamp(Date())
let selftestFolder = syncRoot.appendingPathComponent("Redline-selftest-\(stamp)", isDirectory: true)
try fm.createDirectory(at: selftestFolder, withIntermediateDirectories: true)
TransportSettings.setTransport(.oneDrive, defaults: defaults)
TransportSettings.setOneDriveFolder(selftestFolder, defaults: defaults)
// Local spool root only — the outbox/watch folder is the real OneDrive folder.
let spoolRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-onedrive-selftest-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: spoolRoot) }
let paths = try AppSupportPaths(root: spoolRoot, outbox: selftestFolder, watchFolder: selftestFolder)
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
await watcher.setRecordUncommented(false) // OneDrive mode: today's default is AirDrop's `true`.
let model = AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: watcher
)
model.setFolderURLs(outbox: selftestFolder, watch: selftestFolder)
model.setTransport(.oneDrive)
let png = try makeTinyPNGData()
_ = try await model.spool.append(
pngData: png, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
)
model.replaceSession(try await model.spool.currentSession())
guard !model.session.isEmpty else {
throw OneDriveSelfTestError.detail("seeded session was empty")
}
await model.send(anchor: nil)
guard let status = model.statusLine, status.hasPrefix("Saved to OneDrive") else {
throw OneDriveSelfTestError.detail(
"status did not start with 'Saved to OneDrive': \(model.statusLine ?? "nil")"
)
}
guard model.session.isEmpty else {
throw OneDriveSelfTestError.detail("session was not archived after the OneDrive send")
}
let written = (try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? []
guard let pdfURL = written.first(where: { $0.pathExtension.lowercased() == "pdf" }) else {
throw OneDriveSelfTestError.detail("no PDF found in \(selftestFolder.path)")
}
// Unmarked so far: the watcher must not treat it as a return.
let beforeMarkup = try await watcher.scanNow()
guard !beforeMarkup.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("unmarked PDF was reported as returned by scanNow")
}
let commentedBefore = try await ledger.commented()
guard !commentedBefore.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("unmarked PDF was recorded as commented in the ledger")
}
// What the iPad does: mark it up in place with a real ink annotation, then save.
try addInkMark(to: pdfURL)
let afterMarkup = try await watcher.scanNow()
guard let recorded = afterMarkup.first(where: { $0.fileURL == pdfURL }), recorded.isCommented else {
throw OneDriveSelfTestError.detail("annotated PDF was not reported as commented by scanNow")
}
let commentedAfter = try await ledger.commented()
guard commentedAfter.contains(where: { $0.fileURL == pdfURL }) else {
throw OneDriveSelfTestError.detail("annotated PDF was not recorded in the ledger as commented")
}
// Sub-step 1b: rapid toggle race — see the doc comment above this function.
model.chooseTransport(.airDrop)
model.chooseTransport(.oneDrive) // immediately superseding the call above
// The generation guard itself is what's under test, not this wait — it just
// gives the (already-guarded) reconcile Task a moment to settle either way.
try await Task.sleep(for: .milliseconds(500))
guard model.transport == .oneDrive else {
throw OneDriveSelfTestError.detail(
"rapid toggle: model.transport ended as \(model.transport), expected .oneDrive"
)
}
let racePDFURL = selftestFolder.appendingPathComponent("Redline-race-\(stamp).pdf")
try writeUnmarkedRedlinePDF(to: racePDFURL)
try addInkMark(to: racePDFURL)
let raceFound = try await model.watcher.scanNow()
guard raceFound.first(where: { $0.fileURL == racePDFURL })?.isCommented == true else {
throw OneDriveSelfTestError.detail(
"rapid toggle: watcher did not end up watching \(selftestFolder.path) — an earlier, superseded chooseTransport call won"
)
}
// Sub-step 1c: toggle-then-immediate-send race — see the doc comment above
// this function. No sleep here: this IS the exact race window finding #3
// exists to close, so send() itself must wait out the pending reconcile.
let racePNG = try makeTinyPNGData()
_ = try await model.spool.append(
pngData: racePNG, pixelWidth: 64, pixelHeight: 48, scale: 1, capturedAt: Date()
)
model.replaceSession(try await model.spool.currentSession())
guard !model.session.isEmpty else {
throw OneDriveSelfTestError.detail("toggle-then-send: re-seeded session was empty")
}
let knownBeforeToggleSend = Set(
((try? fm.contentsOfDirectory(at: selftestFolder, includingPropertiesForKeys: nil)) ?? [])
.map(\.lastPathComponent)
)
model.chooseTransport(.airDrop)
model.chooseTransport(.oneDrive) // immediately superseding, no sleep before send()
await model.send(anchor: nil)
guard let toggleSendStatus = model.statusLine, toggleSendStatus.hasPrefix("Saved to OneDrive") else {
throw OneDriveSelfTestError.detail(
"toggle-then-send: status was \(model.statusLine ?? "nil"), expected 'Saved to OneDrive'"
)
}
guard model.session.isEmpty else {
throw OneDriveSelfTestError.detail("toggle-then-send: session was not archived")
}
let filesAfterToggleSend = (try? fm.contentsOfDirectory(
at: selftestFolder, includingPropertiesForKeys: nil
)) ?? []
guard let toggleSendPDFURL = filesAfterToggleSend.first(where: {
$0.pathExtension.lowercased() == "pdf" && !knownBeforeToggleSend.contains($0.lastPathComponent)
}) else {
throw OneDriveSelfTestError.detail("toggle-then-send: no new PDF found in \(selftestFolder.path)")
}
// The freshly-sent PDF is UNMARKED. If send() had raced ahead of the pending
// reconcile, recordUncommented could still have been (stale) true, and this
// scan would wrongly report it as already returned.
let scanAfterToggleSend = try await model.watcher.scanNow()
guard !scanAfterToggleSend.contains(where: { $0.fileURL == toggleSendPDFURL }) else {
throw OneDriveSelfTestError.detail(
"toggle-then-send: freshly-sent unmarked PDF at \(toggleSendPDFURL.path) was reported as returned — send() raced ahead of the pending reconcile"
)
}
// Sub-step 2: relaunch simulation — see the doc comment above this function.
let relaunchAppSupportRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-onedrive-relaunch-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: relaunchAppSupportRoot) }
let relaunchModel = AppDelegate.makeLaunchModel(appSupportRoot: relaunchAppSupportRoot)
guard relaunchModel.transport == .oneDrive else {
throw OneDriveSelfTestError.detail(
"relaunch: model transport was \(relaunchModel.transport), expected .oneDrive"
)
}
guard relaunchModel.watchFolderURL.path == selftestFolder.path else {
throw OneDriveSelfTestError.detail(
"relaunch: model watchFolderURL was \(relaunchModel.watchFolderURL.path), expected \(selftestFolder.path) — this is the exact BLOCKER this phase guards against"
)
}
await relaunchModel.bootstrap()
let relaunchPDFURL = selftestFolder.appendingPathComponent("Redline-relaunch-\(stamp).pdf")
try writeUnmarkedRedlinePDF(to: relaunchPDFURL)
try addInkMark(to: relaunchPDFURL)
let relaunchFound = try await relaunchModel.watcher.scanNow()
guard relaunchFound.first(where: { $0.fileURL == relaunchPDFURL })?.isCommented == true else {
throw OneDriveSelfTestError.detail(
"relaunch: watcher did not report the marked PDF at \(relaunchPDFURL.path) as returned — it was watching the wrong folder after relaunch"
)
}
await relaunchModel.watcher.stop()
return selftestFolder
}
/// Adds a real PDFKit ink annotation to the PDF at `url` in place and saves it —
/// exactly what the iPad does when marking up a page.
private static func addInkMark(to url: URL) throws {
guard let document = PDFDocument(url: url), let page = document.page(at: 0) else {
throw OneDriveSelfTestError.detail("could not reopen \(url.path) to annotate it")
}
let ink = PDFAnnotation(
bounds: CGRect(x: 20, y: 20, width: 60, height: 60),
forType: .ink,
withProperties: nil
)
let stroke = NSBezierPath()
stroke.move(to: NSPoint(x: 20, y: 20))
stroke.line(to: NSPoint(x: 80, y: 80))
ink.add(stroke)
page.addAnnotation(ink)
guard document.write(to: url) else {
throw OneDriveSelfTestError.detail("could not save the annotated PDF back to \(url.path)")
}
}
/// Writes a fresh, unmarked, single-page "Redline"-creator PDF straight to `url` —
/// standing in for a PDF that has just landed in the watch folder, before any
/// human mark. Used by the rapid-toggle and relaunch sub-steps, which don't need to
/// exercise send()/composePDFForSend() again (sub-step 1 already does).
private static func writeUnmarkedRedlinePDF(to url: URL) throws {
let document = PDFDocument()
let page = PDFPage()
page.setBounds(CGRect(x: 0, y: 0, width: 612, height: 792), for: .mediaBox)
document.insert(page, at: 0)
document.documentAttributes = [
PDFDocumentAttribute.creatorAttribute: "Redline",
PDFDocumentAttribute.subjectAttribute: UUID().uuidString,
]
guard document.write(to: url) else {
throw OneDriveSelfTestError.detail("could not write \(url.path)")
}
}
private static func oneDriveFail(_ detail: String) -> Never {
print("ONEDRIVE-SELFTEST FAIL \(detail)")
fflush(stdout)
exit(1)
}
private static func interpolate(_ step: Int) -> NSPoint {
let t = CGFloat(step) / CGFloat(dragSteps)
return NSPoint(
@@ -213,3 +996,21 @@ enum PickerSelfTest {
exit(1)
}
}
private enum UpdateSelfTestError: Error, CustomStringConvertible {
case detail(String)
var description: String {
switch self {
case .detail(let s): return s
}
}
}
private enum OneDriveSelfTestError: Error, CustomStringConvertible {
case detail(String)
var description: String {
switch self {
case .detail(let s): return s
}
}
}
+34 -2
View File
@@ -15,12 +15,40 @@ public final class RegionPickerController {
/// Presents one overlay per attached screen. A pick already in progress is cancelled
/// (its completion called with nil) before the new one starts — never leaves a caller
/// waiting forever on a dropped re-entrant call.
public func pick(completion: @escaping @MainActor (CaptureRegion?) -> Void) {
/// Passing `confirming` shows that area as already chosen and lets Return confirm
/// it — the fast path after "New Session": drag for a new area, or press Return to
/// keep the saved one.
public func pick(
confirming: CaptureRegion? = nil,
completion: @escaping @MainActor (CaptureRegion?) -> Void
) {
if self.completion != nil {
finish(region: nil)
}
self.confirmingRegion = confirming
self.completion = completion
presentOverlays()
if let confirming {
showConfirmingSelection(confirming)
}
}
private var confirmingRegion: CaptureRegion?
/// Shows the saved area as a pre-selection on the overlay for its display.
private func showConfirmingSelection(_ region: CaptureRegion) {
for window in windows where window.coveringScreen.frame.contains(
CGPoint(x: region.rect.midX, y: window.coveringScreen.frame.midY))
{
let local = CGRect(
x: region.rect.minX - window.coveringScreen.frame.minX,
y: region.rect.minY,
width: region.rect.width,
height: region.rect.height
)
window.updateSelection(
localRect: local, sizeText: "\(region.summary) · Return keeps it")
}
}
private func presentOverlays() {
@@ -72,7 +100,11 @@ public final class RegionPickerController {
switch type {
case .keyDown:
if keyCode == 53 { // kVK_Escape
finish(region: nil)
finish(region: confirmingRegion)
return true
}
if keyCode == 36, let confirmingRegion { // Return confirms the saved area
finish(region: confirmingRegion)
return true
}
return false
+196 -26
View File
@@ -3,24 +3,162 @@ import Darwin
import Foundation
import ShotdeckCore
/// Result of composing a send PDF. Kept so the self-test can drive the share
/// outcome without presenting a real AirDrop sheet.
struct ComposedSend: Sendable {
let fileName: String
let fileURL: URL
let pageCount: Int
}
extension AppModel: SendCapable {
public func send(anchor: NSView?) async {
guard !session.isEmpty, !isSending else { return }
// Same synchronous guard as AppModel.startNewSession(): refuse while a session
// start is mid-flight, instead of composing from a session directory that is
// being renamed into the archive.
guard !isStartingNewSession else {
setStatus("Finish starting the new session first.")
return
}
setSending(true)
defer { setSending(false) }
// Wait for any IN-FLIGHT transport/folder reconcile (chooseTransport/
// chooseOneDriveFolder in SettingsView.swift) to fully settle BEFORE
// snapshotting transport/folder below. Without this, a toggle immediately
// followed by Send could let send() read a state that is still mid-transition
// — e.g. the watcher's recordUncommented flag briefly lagging the just-chosen
// transport, so a freshly-sent unmarked OneDrive PDF gets misreported as an
// already-returned document. `Task<Void, Never>.value` never throws, and
// awaiting nil is an immediate no-op (AirDrop mode, or no toggle in flight).
await pendingReconcileTask?.value
// Snapshot BOTH the transport AND the destination folder into local `let`s
// ONCE, before any further `await` in this function. chooseTransport/
// chooseOneDriveFolder also refuse outright (status "Finish the current send
// first.") while isSending is true, but this snapshot is the actual fix for the
// send-vs-switch race: even without that guard, everything below operates on
// these frozen values — composePDFForSend(outbox:transport:) takes both as
// parameters and never re-reads `self.outboxURL`/`self.transport` after a
// suspension point, so a concurrent transport switch mid-send can no longer
// land the PDF under one transport's folder while the archive/status branch
// runs the other's.
let transport = TransportSettings.transport()
let destinationFolder: URL
// OneDrive mode: verify the real destination exists, is writable, AND actually
// accepts a real write RIGHT NOW, before composing anything. `isWritableDirectory`
// alone is not enough — a OneDrive Files-On-Demand directory whose provider
// domain is signed out can report as existing and POSIX-writable while an
// actual write fails, so `probeWritable` writes-fsyncs-removes a tiny real probe
// file to catch that. `outboxURL` is kept in sync with the resolved OneDrive
// folder by bootstrap/chooseTransport/chooseOneDriveFolder, but this is
// re-resolved fresh here (never trusted stale) so a folder that vanished or lost
// its permissions since then (OneDrive signed out, external volume unmounted,
// folder deleted, chmod'd unwritable) is caught instead of silently attempted
// and surfacing as a generic PDF-composition failure.
if transport == .oneDrive {
guard let folder = OneDriveLocator.resolveOneDriveFolder(),
OneDriveLocator.isWritableDirectory(at: folder),
OneDriveLocator.probeWritable(at: folder)
else {
let path = OneDriveLocator.resolveOneDriveFolder()?.path
?? TransportSettings.storedOneDriveFolderPath()
?? "no OneDrive folder found"
setResolvedOneDriveFolder(nil)
setStatus(ShotdeckError.oneDriveFolderUnavailable(path: path).errorDescription)
setSending(false)
return
}
destinationFolder = folder
setResolvedOneDriveFolder(folder)
if outboxURL != folder || watchFolderURL != folder {
setFolderURLs(outbox: folder, watch: folder)
try? await watcher.updateWatchFolder(folder)
}
} else {
destinationFolder = outboxURL
}
let pending: ComposedSend
do {
pending = try await composePDFForSend(outbox: destinationFolder, transport: transport)
} catch {
// Never unlink the published PDF, and never unlink the temp file either:
// a rename failure would leave the complete document at the temp name.
setStatus((error as? ShotdeckError)?.errorDescription ?? "The PDF could not be built.")
setSending(false)
return
}
switch transport {
case .oneDrive:
// No AirDrop, no anchor needed — the PDF is already in the watched
// OneDrive folder. Archive immediately; the iPad marks it up in place.
let pageWord = pending.pageCount == 1 ? "page" : "pages"
await handleDidShareItems(
fileName: pending.fileName,
sentSummary: "Saved to OneDrive — \(pending.pageCount) \(pageWord). Open it in Files on your iPad."
)
setSending(false)
case .airDrop:
guard let anchor else {
handleDidFailToShareItems(fileName: pending.fileName)
setSending(false)
return
}
do {
try Sharing.airDrop(fileURL: pending.fileURL, from: anchor) { [weak self] success in
guard let self else { return }
if success {
let pageWord = pending.pageCount == 1 ? "page" : "pages"
await self.handleDidShareItems(
fileName: pending.fileName,
sentSummary: "Sent — \(pending.pageCount) \(pageWord)."
)
} else {
self.handleDidFailToShareItems(fileName: pending.fileName)
}
self.setSending(false)
}
} catch {
// canPerform false, no service, or no visible window: same as cancel.
handleDidFailToShareItems(fileName: pending.fileName)
setSending(false)
}
}
}
/// Writes the PDF to `outboxDir` and records its path. Does not archive the session
/// and does not present AirDrop — that happens only after the share completes.
/// `outboxDir`/`transport` are passed in (values `send(anchor:)` snapshotted before
/// any await) rather than read from `self.outboxURL`/`self.transport` here, so a
/// concurrent transport switch mid-send can never redirect an in-flight compose to
/// a different folder. A write/rename failure specifically at the destination
/// folder (as opposed to composer.compose()'s own session/image-content failures)
/// is reported as `oneDriveFolderUnavailable` rather than the generic
/// `pdfCompositionFailed` when `transport == .oneDrive` — the File Provider edge
/// case where the folder looked writable moments ago in `send(anchor:)` but the
/// actual write still failed (e.g. OneDrive signed out mid-write).
func composePDFForSend(outbox outboxDir: URL, transport: SendTransport) async throws -> ComposedSend {
let workingSession = session
let composer = self.composer
// Live outbox (FolderSettings), not `paths.outbox` — Settings changes take effect.
let outboxDir = outboxURL
let sourceDir = paths.sessionDirectory(workingSession.id)
let fileName = PDFComposer.fileName(for: workingSession)
let finalURL = outboxDir.appendingPathComponent(fileName)
// Same directory as the final target so the rename below is same-volume (atomic).
let tempURL = outboxDir.appendingPathComponent(".shotdeck-\(UUID().uuidString).pdf")
let title = "Shotdeck – \(DubaiTime.stamp(workingSession.createdAt))"
// The document title follows the same three parts as the file name: tool,
// lane (when recorded) and Dubai time.
let lane = workingSession.context.lane
let titleParts = ["Redline"]
+ (lane.isEmpty ? [] : [lane])
+ [DubaiTime.stamp(Date())]
let title = titleParts.joined(separator: " – ")
let toolVersion = appVersion
do {
// D-13: build off the main actor. Only Sendable values cross into the
// detached task — never `anchor` (NSView is not Sendable).
try await Task.detached(priority: .userInitiated) {
@@ -28,44 +166,76 @@ extension AppModel: SendCapable {
session: workingSession,
imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) },
title: title,
to: tempURL
to: tempURL,
toolVersion: toolVersion
)
// POSIX rename onto `finalURL` replaces any same-name file in one
// directory operation; there is never a window where the PDF is gone.
if Darwin.rename(tempURL.path, finalURL.path) != 0 {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw ShotdeckError.pdfCompositionFailed(
reason: "could not publish the PDF: \(String(cString: strerror(errno)))"
)
}
do {
try AtomicFile.fsyncDirectory(at: outboxDir)
} catch {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw error
}
}.value
// File exists on disk now — archive only after that (D-13). A later AirDrop
// failure never deletes this file.
guard FileManager.default.fileExists(atPath: finalURL.path) else {
if transport == .oneDrive {
throw ShotdeckError.oneDriveFolderUnavailable(path: outboxDir.path)
}
throw ShotdeckError.pdfCompositionFailed(reason: "the PDF was not written to disk")
}
_ = try await spool.archiveCurrent(pdfFileName: fileName)
replaceSession(try await spool.currentSession())
let pageWord = workingSession.captures.count == 1 ? "page" : "pages"
setStatus("Sent — \(workingSession.captures.count) \(pageWord).")
guard let anchor else {
setStatus("PDF saved to \(outboxDisplayName). Open the panel to AirDrop it.")
return
}
do {
try Sharing.airDrop(fileURL: finalURL, from: anchor)
} catch {
setStatus(
"AirDrop is not available right now — the PDF is on your \(outboxDisplayName)."
rememberLastComposedPDF(finalURL)
return ComposedSend(
fileName: fileName,
fileURL: finalURL,
pageCount: workingSession.captures.count
)
}
/// `NSSharingServiceDelegate.sharingService(_:didShareItems:)` seam — also the
/// OneDrive completion path. Composes ONE truthful status from the caller's success
/// summary (the share itself DID complete) plus, when they happened, the archive
/// error and any state-refresh problem — nothing is overwritten or hidden.
func handleDidShareItems(fileName: String, sentSummary: String) async {
guard !session.isEmpty else { return }
var message = sentSummary
var archivedID: UUID?
do {
archivedID = try await spool.archiveCurrent(pdfFileName: fileName).id
} catch {
// Never unlink the published PDF, and never unlink `tempURL` either:
// a rename failure would leave the complete document at the temp name.
setStatus((error as? ShotdeckError)?.errorDescription ?? "The PDF could not be built.")
message += " \((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")"
}
// Refresh model state from the store on BOTH paths: after a successful archive
// the current session and the past-submissions list are stale until reloaded,
// and after a failure the store (not this model) knows whether the session
// actually moved. Any refresh problem is appended to the status, never hidden.
if let refreshProblem = await reloadFromSpool() {
message += " \(refreshProblem)"
}
// Leave the window on the session that was just sent: that is what the person
// is looking at when the PDF leaves.
if let archivedID {
selectSession(archivedID)
}
setStatus(message)
}
/// `NSSharingServiceDelegate.sharingService(_:didFailToShareItems:error:)` seam,
/// also used when `canPerform` is false or the user cancels. Does not archive.
func handleDidFailToShareItems(fileName: String) {
setStatus(
"AirDrop didn't complete — nothing was sent. Your captures are still here; the PDF is on your \(outboxDisplayName) as \(fileName)."
)
}
}
@@ -0,0 +1,98 @@
import SwiftUI
import ShotdeckCore
/// The five review-detail fields of a session, in one compact grid.
///
/// Values are held locally while typing and written through to the session manifest
/// on every change, so closing the panel cannot lose them. The local copy is re-seeded
/// whenever the open session changes (a new session inherits the previous details).
struct SessionContextEditor: View {
@Environment(AppModel.self) private var model
@State private var lane = ""
@State private var deployedVersion = ""
@State private var commitHash = ""
@State private var reviewer = ""
@State private var note = ""
@State private var seededSessionID: UUID?
/// What this view last wrote (or seeded). Lets an out-of-band change — a context
/// inherited by a new session, for example — refresh the fields without fighting
/// the user's own keystrokes.
@State private var lastKnownContext: ReviewContext = .empty
/// The pending debounced write and its value. Typing replaces it, so one short
/// pause writes once instead of once per keystroke, and an older write can never
/// land after a newer one.
@State private var pendingWrite: Task<Void, Never>?
@State private var lastScheduledWrite: ReviewContext = .empty
private let labelWidth: CGFloat = 84
var body: some View {
Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 4) {
row("Lane", text: $lane, prompt: "dev03, customer test lane…")
row("Deployed", text: $deployedVersion, prompt: "build that is live")
row("Commit", text: $commitHash, prompt: "git SHA")
row("Reviewer", text: $reviewer, prompt: "who is reviewing")
row("Note", text: $note, prompt: "what this session covers")
}
.onAppear { seedIfNeeded() }
.onChange(of: model.session.id) { _, _ in seedIfNeeded() }
.onChange(of: model.session.context) { _, newValue in
guard newValue != lastKnownContext else { return }
seed(from: newValue)
}
.onChange(of: lane) { _, _ in commit() }
.onChange(of: deployedVersion) { _, _ in commit() }
.onChange(of: commitHash) { _, _ in commit() }
.onChange(of: reviewer) { _, _ in commit() }
.onChange(of: note) { _, _ in commit() }
}
private func row(_ label: String, text: Binding<String>, prompt: String) -> some View {
GridRow(alignment: .center) {
Text(label)
.font(.caption)
.foregroundStyle(.secondary)
.frame(width: labelWidth, alignment: .trailing)
TextField(prompt, text: text)
.textFieldStyle(.roundedBorder)
.font(.caption)
.onSubmit { commit() }
}
}
private func seedIfNeeded() {
guard seededSessionID != model.session.id else { return }
seededSessionID = model.session.id
seed(from: model.session.context)
}
private func seed(from context: ReviewContext) {
lane = context.lane
deployedVersion = context.deployedVersion
commitHash = context.commit
reviewer = context.reviewer
note = context.note
lastKnownContext = context
}
private func commit() {
let context = ReviewContext(
lane: lane,
deployedVersion: deployedVersion,
commit: commitHash,
reviewer: reviewer,
note: note
)
guard context != model.session.context else { return }
guard context != lastScheduledWrite else { return }
lastKnownContext = context
lastScheduledWrite = context
pendingWrite?.cancel()
pendingWrite = Task {
try? await Task.sleep(for: .milliseconds(150))
guard !Task.isCancelled else { return }
await model.setContextField(context)
}
}
}
+16 -3
View File
@@ -2,22 +2,35 @@ import AppKit
import SwiftUI
import ShotdeckCore
/// The popover's page strip: at most `limit` thumbnails plus a "+N" tile, so the
/// popover never turns into a filmstrip of the whole session.
struct SessionStrip: View {
@Environment(AppModel.self) private var model
var limit: Int? = nil
var body: some View {
let captures = Array(model.session.captures.prefix(limit ?? model.session.captures.count))
let hidden = model.session.captures.count - captures.count
if model.session.captures.isEmpty {
Text("Nothing captured yet.")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, minHeight: 64, alignment: .leading)
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 6) {
ForEach(model.session.captures) { capture in
ForEach(captures) { capture in
SessionThumb(capture: capture)
}
if hidden > 0 {
Text("+\(hidden)")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
.frame(width: 52, height: 64)
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 4, style: .continuous))
.help("\(hidden) more page\(hidden == 1 ? "" : "s") — open Redline to see them")
}
Spacer(minLength: 0)
}
.frame(height: 64)
}
@@ -63,7 +76,7 @@ private struct SessionThumb: View {
@ViewBuilder
private var thumbnail: some View {
let url = model.paths.sessionDirectory(model.session.id).appendingPathComponent(capture.fileName)
let url = model.imageURL(for: capture, in: model.session)
if let image = NSImage(contentsOf: url) {
Image(nsImage: image)
.resizable()
+748
View File
@@ -0,0 +1,748 @@
import AppKit
import SwiftUI
import ShotdeckCore
/// The Redline window: every session on the left, the selected session's pages in the
/// middle, and that session's review details / PDF / session facts on the right.
/// This is where history, text entry and file facts live; the popover only glances at
/// the current session and fires the two main actions.
struct SessionsWindowView: View {
@Environment(AppModel.self) private var model
@State private var searchText = ""
@State private var selectedCaptureID: UUID?
@State private var showInspector = true
var body: some View {
// Three explicit columns rather than NavigationSplitView: the window has a
// fixed, always-visible inspector, and a plain split keeps the sidebar rows and
// the inspector rendering deterministically in every window state.
HStack(spacing: 0) {
sidebar
.frame(width: 230)
Divider()
detail
.frame(maxWidth: .infinity, maxHeight: .infinity)
if showInspector {
Divider()
SessionInspector(session: selectedSession)
.frame(width: 300)
}
}
.frame(minWidth: 900, minHeight: 560)
.controlSize(.regular)
.background(Color(nsColor: .windowBackgroundColor))
.onChange(of: model.selectedSessionID) { _, _ in
selectedCaptureID = nil
}
}
private var selectedSession: CaptureSession {
model.selectedSession ?? model.session
}
// MARK: - Sidebar
private var sidebar: some View {
VStack(spacing: 0) {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.foregroundStyle(.secondary)
TextField("Search sessions", text: $searchText)
.textFieldStyle(.plain)
if !searchText.isEmpty {
Button {
searchText = ""
} label: {
Image(systemName: "xmark.circle.fill")
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.accessibilityLabel("Clear search")
}
}
.padding(.horizontal, 8)
.padding(.vertical, 5)
.background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 6, style: .continuous))
.padding(8)
List(selection: selection) {
ForEach(sections) { section in
Section(section.title) {
ForEach(section.sessions) { session in
SessionRow(session: session)
.tag(session.id)
}
}
}
}
.listStyle(.sidebar)
if sections.isEmpty {
Text(searchText.isEmpty ? "No sessions yet." : "No session matches “\(searchText)”.")
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(12)
}
}
.background(Color(nsColor: .controlBackgroundColor))
}
private var sections: [AppModel.SessionGroup] {
model.groupedSections(for: model.sessions(matching: searchText))
}
private var selection: Binding<UUID?> {
Binding(
get: { model.selectedSession?.id },
set: { model.selectSession($0) }
)
}
// MARK: - Detail
private var detail: some View {
VStack(alignment: .leading, spacing: 0) {
header
Divider()
if let document = model.returnedDocument(for: selectedSession), document.isCommented {
ReturnedBanner(document: document, session: selectedSession)
Divider()
}
pages
}
.background(Color(nsColor: .textBackgroundColor))
}
private var header: some View {
HStack(alignment: .center, spacing: 10) {
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 6) {
Text(laneTitle)
.font(.system(size: 15, weight: .semibold))
.lineLimit(1)
.truncationMode(.tail)
if model.selectedIsCurrent {
Text("Current")
.font(.system(size: 9, weight: .semibold))
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(.quaternary, in: Capsule())
}
}
Text(subtitle)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
.layoutPriority(0)
Spacer(minLength: 12)
Button {
showInspector.toggle()
} label: {
Image(systemName: "sidebar.right")
}
.buttonStyle(.borderless)
.help(showInspector ? "Hide the inspector" : "Show the inspector")
.accessibilityLabel(showInspector ? "Hide the inspector" : "Show the inspector")
// What the next capture takes, in the same place as the verbs.
Menu {
ForEach(CaptureScope.allCases, id: \.self) { scope in
Button {
Task {
await model.chooseCaptureScope(scope)
await model.captureNow()
}
} label: {
Text("\(scope.menuTitle) — capture now")
}
}
Divider()
Button("Choose New Area…") {
Task { await model.rePickRegion() }
}
} label: {
HStack(spacing: 4) {
Image(systemName: scopeSymbol)
Text("\(model.captureScope.displayName) · \(scopeDetail)")
.lineLimit(1)
}
}
.menuStyle(.borderlessButton)
.fixedSize()
.help("What Capture takes")
.accessibilityLabel("Capture: \(model.captureTargetDescription)")
if model.captureScope == .area {
Button("Choose Area…") {
Task { await model.rePickRegion() }
}
.fixedSize()
.help("Pick a new area to capture")
}
Button {
Task { await model.newSession() }
} label: {
Label("New Session", systemImage: "plus.square.on.square")
}
.keyboardShortcut("n", modifiers: .command)
.disabled(model.isSending)
.fixedSize()
.help("Keep this session and start a fresh one, then ask where to capture (⌘N)")
Button {
Task { await model.captureNow() }
} label: {
Label(model.isCapturing ? "Capturing…" : "Capture", systemImage: "viewfinder")
}
.disabled(model.isCapturing || !model.selectedIsCurrent)
.fixedSize()
Button {
guard let sender = model as? SendCapable else { return }
let anchor = NSApp.keyWindow?.contentView
Task { await sender.send(anchor: anchor) }
} label: {
Label(sendTitle, systemImage: "paperplane.fill")
}
.buttonStyle(.borderedProminent)
.layoutPriority(1)
.keyboardShortcut("s", modifiers: .command)
.disabled(!model.selectedIsCurrent || model.session.isEmpty || model.isSending)
.help(model.transport == .oneDrive
? "Save the PDF to the OneDrive folder (⌘S)"
: "AirDrop the PDF (⌘S)")
}
.padding(.horizontal, 16)
.padding(.vertical, 10)
}
private var laneTitle: String {
let lane = selectedSession.context.lane
if !lane.isEmpty { return lane }
return selectedSession.id == model.session.id ? "Current session" : selectedSession.shortID
}
private var subtitle: String {
let pages = selectedSession.captures.count
let pageWord = "\(pages) page\(pages == 1 ? "" : "s")"
return "\(pageWord) · \(model.state(of: selectedSession).label)"
}
private var sendTitle: String {
model.transport == .oneDrive ? "Save…" : "Send…"
}
private var scopeSymbol: String {
switch model.captureScope {
case .area: return "rectangle.dashed"
case .window: return "macwindow"
case .browser: return "safari"
case .screen: return "display"
}
}
/// Short form for the header: the area size, or what a window scope grabs.
private var scopeDetail: String {
switch model.captureScope {
case .area:
guard let region = model.region else { return "not set" }
return "\(Int(region.rect.width)) × \(Int(region.rect.height))"
case .window: return "front window"
case .browser: return "browser"
case .screen:
guard let region = model.region else { return "all" }
return "Display \(region.displayNumber)"
}
}
// MARK: - Pages
@ViewBuilder
private var pages: some View {
if selectedSession.isEmpty {
emptyState
} else {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text("Pages")
.font(.headline)
Text(pagesCaption)
.font(.caption)
.foregroundStyle(.secondary)
Spacer(minLength: 8)
Button("Remove Page") {
removeSelectedPage()
}
.disabled(!model.selectedIsCurrent || selectedCaptureID == nil)
}
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 200, maximum: 240), spacing: 16)],
alignment: .leading,
spacing: 18
) {
ForEach(selectedSession.captures) { capture in
PageCard(
capture: capture,
session: selectedSession,
isSelected: selectedCaptureID == capture.id,
canRemove: model.selectedIsCurrent
) {
selectedCaptureID = capture.id
}
}
}
}
.padding(16)
}
.onDeleteCommand { removeSelectedPage() }
}
}
private var pagesCaption: String {
model.selectedIsCurrent
? "In PDF order · Delete removes the selected page"
: "In the order they were sent"
}
private var emptyState: some View {
VStack(spacing: 10) {
Image(systemName: "viewfinder")
.font(.system(size: 28, weight: .light))
.foregroundStyle(.secondary)
Text("No pages in this session")
.font(.headline)
Text(emptyStateDetail)
.font(.caption)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.frame(maxWidth: 320)
HStack(spacing: 8) {
Button("Choose Area…") {
Task { await model.rePickRegion() }
}
Button("Capture \(model.hotkeyDisplayString)") {
Task { await model.captureNow() }
}
.buttonStyle(.borderedProminent)
}
.padding(.top, 4)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(24)
}
private var emptyStateDetail: String {
if model.region == nil {
return "Choose the part of the screen you review, then capture it. Each capture becomes one page of the PDF."
}
return "Press \(model.hotkeyDisplayString) to capture the saved area. Each capture becomes one page of the PDF."
}
private func removeSelectedPage() {
guard model.selectedIsCurrent, let id = selectedCaptureID else { return }
selectedCaptureID = nil
Task { await model.removeCapture(id: id) }
}
}
// MARK: - Sidebar row
private struct SessionRow: View {
@Environment(AppModel.self) private var model
let session: CaptureSession
var body: some View {
let state = model.state(of: session)
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 5) {
Text(lane)
.lineLimit(1)
if state == .current {
Text("Current")
.font(.system(size: 9, weight: .semibold))
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(.quaternary, in: Capsule())
}
Spacer(minLength: 4)
Text(DubaiTime.checkTime(session.createdAt))
.font(.caption)
.foregroundStyle(.secondary)
.monospacedDigit()
}
Text(detail(state))
.font(.caption)
.foregroundStyle(state.isReturned ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary))
.lineLimit(1)
}
.padding(.vertical, 2)
.accessibilityElement(children: .combine)
.accessibilityLabel("\(lane), \(DubaiTime.checkTime(session.createdAt)), \(session.captures.count) pages, \(state.label)")
}
private var lane: String {
let lane = session.context.lane
return lane.isEmpty ? session.shortID : lane
}
private func detail(_ state: AppModel.SessionDisplayState) -> String {
let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")"
if case .returned(let marked) = state {
return "\(pages) · came back with \(marked) page\(marked == 1 ? "" : "s") marked"
}
return "\(pages) · \(state.label)"
}
}
// MARK: - Page card
private struct PageCard: View {
@Environment(AppModel.self) private var model
let capture: Capture
let session: CaptureSession
let isSelected: Bool
let canRemove: Bool
let select: () -> Void
@State private var hovering = false
var body: some View {
VStack(alignment: .leading, spacing: 5) {
ZStack(alignment: .topLeading) {
thumbnail
if hovering && canRemove {
Button("Remove") {
Task { await model.removeCapture(id: capture.id) }
}
.font(.caption2.weight(.semibold))
.buttonStyle(.plain)
.foregroundStyle(.white)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(.black.opacity(0.65), in: Capsule())
.padding(6)
}
}
.overlay {
RoundedRectangle(cornerRadius: 5, style: .continuous)
.strokeBorder(isSelected ? Color.accentColor : .clear, lineWidth: 2)
}
.frame(maxWidth: 240, alignment: .leading)
.onHover { hovering = $0 }
.onTapGesture(perform: select)
HStack(spacing: 6) {
Text("Page \(capture.sequence)")
.font(.caption.weight(isSelected ? .semibold : .regular))
Spacer(minLength: 4)
Text(DubaiTime.checkTime(capture.capturedAt))
.font(.caption)
.foregroundStyle(.secondary)
.monospacedDigit()
}
}
}
@ViewBuilder
private var thumbnail: some View {
let url = model.imageURL(for: capture, in: session)
if let image = NSImage(contentsOf: url) {
Image(nsImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity)
.clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
.overlay {
RoundedRectangle(cornerRadius: 4, style: .continuous)
.strokeBorder(.quaternary, lineWidth: 0.5)
}
} else {
RoundedRectangle(cornerRadius: 4, style: .continuous)
.fill(.quaternary)
.frame(height: 96)
.overlay {
Text("Image missing")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
}
}
// MARK: - Returned banner
private struct ReturnedBanner: View {
@Environment(AppModel.self) private var model
let document: ReturnedDocument
let session: CaptureSession
var body: some View {
HStack(spacing: 8) {
Image(systemName: "pencil.and.outline")
.foregroundStyle(.orange)
Text(message)
.font(.callout)
Spacer(minLength: 8)
Button("Open PDF") {
NSWorkspace.shared.open(document.fileURL)
}
if model.sentPDFURL(for: session) != nil {
Button("Show Original") {
model.revealSentPDF(session)
}
}
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(.orange.opacity(0.1))
}
private var message: String {
let marked = document.annotatedPages.count
return "Came back with marks on \(marked) page\(marked == 1 ? "" : "s")."
}
}
// MARK: - Inspector
private struct SessionInspector: View {
@Environment(AppModel.self) private var model
let session: CaptureSession
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
reviewDetails
if !model.selectedIsCurrent {
Text("Past sessions are read-only: the PDF already carries these values.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
pdfFacts
sessionFacts
}
.padding(14)
}
.background(Color(nsColor: .windowBackgroundColor))
}
private var reviewDetails: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Review details")
.font(.headline)
GroupBox {
VStack(spacing: 0) {
contextRow("Lane", prompt: "dev03, customer test lane…", \.lane, focusOnRequest: true)
RowDivider()
contextRow("Deployed", prompt: "build that is live", \.deployedVersion)
RowDivider()
contextRow("Commit", prompt: "git SHA", \.commit)
RowDivider()
contextRow("Reviewer", prompt: "who is reviewing", \.reviewer)
RowDivider()
contextRow("Note", prompt: "what this session covers", \.note)
}
}
Text("Printed on every page of the PDF. A new session starts with these values.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
}
@ViewBuilder
private func contextRow(
_ label: String,
prompt: String,
_ field: WritableKeyPath<ReviewContext, String>,
focusOnRequest: Bool = false
) -> some View {
if model.selectedIsCurrent {
EditableContextRow(label: label, prompt: prompt, field: field, focusOnRequest: focusOnRequest)
} else {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(label)
.foregroundStyle(.secondary)
.frame(width: 74, alignment: .leading)
Text(displayValue(field))
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
.padding(.vertical, 5)
}
}
private func displayValue(_ field: KeyPath<ReviewContext, String>) -> String {
let value = session.context[keyPath: field]
return value.isEmpty ? "—" : value
}
private var pdfFacts: some View {
VStack(alignment: .leading, spacing: 6) {
Text("PDF")
.font(.headline)
GroupBox {
VStack(spacing: 0) {
FactRow(label: "File name", value: pdfFileName, selectable: true)
RowDivider()
FactRow(label: "Pages", value: "\(session.captures.count)")
RowDivider()
FactRow(
label: "Sends via",
value: model.transport == .oneDrive ? "OneDrive folder" : "AirDrop")
RowDivider()
FactRow(label: "Status", value: model.state(of: session).label)
}
}
}
}
private var pdfFileName: String {
if let name = session.pdfFileName { return name }
return model.selectedIsCurrent ? model.nextPDFFileNameHint : "—"
}
private var sessionFacts: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Session")
.font(.headline)
GroupBox {
VStack(spacing: 0) {
FactRow(label: "Started", value: DubaiTime.stamp(session.createdAt))
RowDivider()
FactRow(label: "ID", value: session.shortID, monospaced: true)
RowDivider()
HStack {
Text("Files")
.foregroundStyle(.secondary)
Spacer(minLength: 8)
Button(model.selectedIsCurrent ? "Show Captures" : "Show in Finder") {
model.revealSessionCaptures(session)
}
.buttonStyle(.link)
}
.padding(.vertical, 5)
}
}
}
}
}
private struct RowDivider: View {
var body: some View {
Divider().padding(.leading, 0)
}
}
/// One editable review-detail row. The text lives in local state while typing and is
/// written through to the open session's manifest; it re-seeds whenever the session's
/// stored details change underneath it (a new session inheriting them, for example).
private struct EditableContextRow: View {
@Environment(AppModel.self) private var model
let label: String
let prompt: String
let field: WritableKeyPath<ReviewContext, String>
let focusOnRequest: Bool
@State private var text: String = ""
@State private var lastSynced: String = ""
@FocusState private var focused: Bool
var body: some View {
HStack(spacing: 8) {
Text(label)
.foregroundStyle(.secondary)
.frame(width: 74, alignment: .leading)
TextField(prompt, text: $text)
.textFieldStyle(.roundedBorder)
.controlSize(.small)
.focused($focused)
.accessibilityLabel(label)
.onSubmit { push() }
.onChange(of: text) { _, _ in push() }
}
.padding(.vertical, 5)
.onAppear { seed(from: stored) }
.onChange(of: model.session.context) { _, newValue in
let incoming = newValue[keyPath: field]
guard incoming != lastSynced else { return }
seed(from: incoming)
}
.onChange(of: model.session.id) { _, _ in
seed(from: stored)
}
.onChange(of: model.laneFocusRequest) { _, _ in
if focusOnRequest { focused = true }
}
}
private var stored: String {
model.session.context[keyPath: field]
}
private func seed(from value: String) {
text = value
lastSynced = value
}
private func push() {
guard text != lastSynced else { return }
lastSynced = text
model.updateContext(field, text)
}
}
private struct FactRow: View {
let label: String
let value: String
var monospaced: Bool = false
var selectable: Bool = false
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(label)
.foregroundStyle(.secondary)
Spacer(minLength: 8)
Text(value)
.font(monospaced ? .system(.body, design: .monospaced) : .body)
.lineLimit(1)
.truncationMode(.middle)
.textSelection(.enabled)
.help(value)
}
.padding(.vertical, 5)
}
}
// MARK: - Window presentation
extension AppModel: SessionsWindowPresenting {
private static var sessionsWindowController: NSWindowController?
public func presentSessionsWindow(focusLane: Bool) {
if focusLane { requestLaneFocus() }
if let existing = Self.sessionsWindowController {
existing.window?.makeKeyAndOrderFront(nil)
NSApp.activate()
return
}
let hosting = NSHostingController(rootView: SessionsWindowView().environment(self))
let window = NSWindow(contentViewController: hosting)
window.title = "Redline"
window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView]
window.titlebarAppearsTransparent = false
window.isReleasedWhenClosed = false
window.setContentSize(NSSize(width: 1240, height: 760))
window.minSize = NSSize(width: 1000, height: 600)
window.center()
window.setFrameAutosaveName("RedlineSessionsWindow")
let controller = NSWindowController(window: window)
Self.sessionsWindowController = controller
controller.showWindow(nil)
NSApp.activate()
}
}
+344 -53
View File
@@ -2,81 +2,298 @@ import AppKit
import SwiftUI
import ShotdeckCore
/// Settings: three labelled groups, every row "what it is" on the left and the control
/// on the right. Nothing here is needed while reviewing, which is why it is its own
/// window and not part of the session surfaces.
struct SettingsView: View {
@Environment(AppModel.self) private var model
private let labelWidth: CGFloat = 104
@State private var isRecordingHotkey = false
@State private var recorder = HotkeyRecorderBox()
var body: some View {
Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) {
GridRow {
Text("Hotkey")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.gridCellColumns(2)
Form {
Section("Capture") {
LabeledContent("What to capture") {
Picker("What to capture", selection: scopeBinding) {
ForEach(CaptureScope.allCases, id: \.self) { scope in
Text(scope.displayName).tag(scope)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(maxWidth: 240)
}
GridRow(alignment: .firstTextBaseline) {
fieldLabel("Capture")
Text("⌥⇧2 — fixed in this version")
LabeledContent("Saved area") {
HStack(spacing: 8) {
Text(areaSummary)
.foregroundStyle(.secondary)
.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(minHeight: 22, alignment: .leading)
Button("Choose…") {
Task { await model.rePickRegion() }
}
GridRow {
Text("Folders")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.gridCellColumns(2)
.padding(.top, 6)
}
GridRow(alignment: .center) {
fieldLabel("Watch folder")
folderValue(path: model.watchFolderURL.path) {
model.chooseWatchFolder()
}
}
GridRow(alignment: .center) {
fieldLabel("Output folder")
folderValue(path: model.outboxURL.path) {
model.chooseOutboxFolder()
LabeledContent("Capture shortcut") {
Button {
armHotkeyRecorder()
} label: {
Text(isRecordingHotkey ? "Press keys…" : model.hotkeyDisplayString)
.foregroundStyle(isRecordingHotkey ? .secondary : .primary)
.frame(minWidth: 54)
}
}
GridRow {
Button("Reveal spool folder") { model.openSpoolFolder() }
.gridCellColumns(2)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 4)
}
}
.padding(16)
.frame(minWidth: 320, idealWidth: 360, maxWidth: 360, alignment: .leading)
.controlSize(.small)
Toggle("Ask what to capture on New Session", isOn: askOnNewSessionBinding)
Text("Window and Browser pick the window under the pointer, with the app named. New Session keeps this session and re-asks for the area.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
private func fieldLabel(_ title: String) -> some View {
Text(title)
.lineLimit(1)
.frame(width: labelWidth, alignment: .trailing)
.gridColumnAlignment(.trailing)
.frame(minHeight: 22, alignment: .trailing)
Section("Sending") {
LabeledContent("Send with") {
Picker("Send with", selection: transportBinding) {
ForEach(SendTransport.allCases, id: \.self) { transport in
Text(transport.displayName).tag(transport)
}
}
.labelsHidden()
.pickerStyle(.segmented)
.frame(maxWidth: 220)
}
private func folderValue(path: String, choose: @escaping () -> Void) -> some View {
if model.transport == .airDrop {
LabeledContent("Save PDFs to") {
folderRow(path: model.outboxURL.path) { model.chooseOutboxFolder() }
}
LabeledContent("Watch for returns in") {
folderRow(path: model.watchFolderURL.path) { model.chooseWatchFolder() }
}
} else {
LabeledContent("OneDrive folder") {
folderRow(path: oneDrivePath) { model.chooseOneDriveFolder() }
}
Text(
model.resolvedOneDriveFolder != nil
? "The PDF is saved here and this same folder is watched for the marked-up copy. On the iPad open it from Files > OneDrive."
: "No OneDrive folder found. Sign in to OneDrive, or choose a folder."
)
.font(.caption)
.foregroundStyle(model.resolvedOneDriveFolder != nil ? .secondary : .primary)
.fixedSize(horizontal: false, vertical: true)
}
}
Section("Sessions") {
LabeledContent("Delete sessions older than") {
Picker("Delete sessions older than", selection: retentionBinding) {
ForEach(SessionRetention.presets, id: \.self) { preset in
Text(preset.displayName).tag(preset)
}
}
.labelsHidden()
.frame(maxWidth: 150)
}
LabeledContent(keptSummary) {
Button("Clean Up Now…") {
Task { await model.cleanUpExpiredSessions() }
}
.disabled(model.retention == .never || model.expiredSessionCount == 0)
}
Text(retentionDetail)
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
Text("Deleting removes Redline's own screenshots only. PDFs you sent stay where they are.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
}
Section("Updates") {
Toggle("Install updates automatically", isOn: autoInstallBinding)
LabeledContent(updateSummary) {
Button(model.isCheckingForUpdates ? "Checking…" : "Check Now") {
model.checkForUpdates()
}
.disabled(model.isCheckingForUpdates)
}
Text("Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
if let update = model.updateAvailable {
LabeledContent("Ready to install") {
Button("Restart Now") { model.installUpdate() }
}
Text("Redline \(update.version) is downloaded and waiting.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
Section {
LabeledContent("Redline \(model.appVersion)") {
Button("Quit Redline") { NSApp.terminate(nil) }
}
}
}
.formStyle(.grouped)
.frame(width: 460, height: 820)
.controlSize(.regular)
.onDisappear { disarmHotkeyRecorder() }
}
// MARK: - Rows
private var areaSummary: String {
model.region?.summary ?? "Not chosen"
}
private var oneDrivePath: String {
model.resolvedOneDriveFolder?.path ?? "Not found"
}
private var keptSummary: String {
let count = model.pastSessions.count + 1
return "\(count) session\(count == 1 ? "" : "s") kept"
}
private func folderRow(path: String, choose: @escaping () -> Void) -> some View {
HStack(spacing: 8) {
Text(path)
Text(abbreviateHome(path))
.lineLimit(1)
.truncationMode(.middle)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(maxWidth: 150, alignment: .trailing)
.help(path)
Button("Choose…") { choose() }
}
.frame(minHeight: 22)
}
private func abbreviateHome(_ path: String) -> String {
let home = FileManager.default.homeDirectoryForCurrentUser.path
guard path.hasPrefix(home) else { return path }
return "~" + path.dropFirst(home.count)
}
// MARK: - Detail text
private var retentionDetail: String {
guard model.retention != .never else {
return "All sessions are kept. Nothing is deleted automatically."
}
let count = model.expiredSessionCount
if count == 0 {
return "No kept session is older than \(model.retention.displayName) yet."
}
return "\(count) session\(count == 1 ? " is" : "s are") already older than \(model.retention.displayName) and will be removed on the next launch or cleanup."
}
// MARK: - Bindings
private var scopeBinding: Binding<CaptureScope> {
Binding(
get: { model.captureScope },
set: { scope in Task { await model.chooseCaptureScope(scope) } }
)
}
private var askOnNewSessionBinding: Binding<Bool> {
Binding(
get: { model.askWhatToCaptureOnNewSession },
set: { model.setAskWhatToCaptureOnNewSession($0) }
)
}
private var autoInstallBinding: Binding<Bool> {
Binding(
get: { model.autoInstallUpdates },
set: { model.setAutoInstallUpdates($0) }
)
}
private var updateSummary: String {
let basis = model.updateStatusMessage ?? "Version \(model.appVersion)"
return basis
}
private var transportBinding: Binding<SendTransport> {
Binding(get: { model.transport }, set: { model.chooseTransport($0) })
}
private var retentionBinding: Binding<SessionRetention> {
Binding(get: { model.retention }, set: { value in
Task { await model.setRetention(value) }
})
}
// MARK: - Hotkey recorder
private func armHotkeyRecorder() {
guard !isRecordingHotkey else { return }
isRecordingHotkey = true
recorder.onKey = { keyCode, flags in
handleRecorderKey(keyCode: keyCode, flags: flags)
}
recorder.arm()
}
private func handleRecorderKey(keyCode: UInt16, flags: NSEvent.ModifierFlags) {
if keyCode == 53 { // kVK_Escape
disarmHotkeyRecorder()
return
}
guard let pref = HotkeyPreference.fromKeyEvent(keyCode: keyCode, modifierFlags: flags) else {
return
}
pref.save()
model.reRegisterHotkey()
disarmHotkeyRecorder()
}
private func disarmHotkeyRecorder() {
recorder.disarm()
recorder.onKey = nil
isRecordingHotkey = false
}
}
/// Local keyDown monitor for the Settings capture-hotkey recorder. Callbacks hop onto the
/// main actor the same way `RegionPickerController` does — local monitors fire on the
/// main run loop during `NSApp.sendEvent`.
@MainActor
private final class HotkeyRecorderBox {
var onKey: ((UInt16, NSEvent.ModifierFlags) -> Void)?
private var monitor: Any?
func arm() {
disarm()
monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
guard let self else { return event }
let keyCode = event.keyCode
let rawFlags = event.modifierFlags.rawValue
MainActor.assumeIsolated {
self.onKey?(keyCode, NSEvent.ModifierFlags(rawValue: rawFlags))
}
return nil
}
}
func disarm() {
if let monitor {
NSEvent.removeMonitor(monitor)
}
monitor = nil
}
}
@@ -91,9 +308,10 @@ extension AppModel: SettingsWindowPresenting {
}
let hosting = NSHostingController(rootView: SettingsView().environment(self))
let window = NSWindow(contentViewController: hosting)
window.title = "Shotdeck Settings"
window.title = "Redline Settings"
window.styleMask = [.titled, .closable]
window.isReleasedWhenClosed = false
window.setContentSize(NSSize(width: 460, height: 820))
window.center()
let controller = NSWindowController(window: window)
Self.settingsWindowController = controller
@@ -105,7 +323,7 @@ extension AppModel: SettingsWindowPresenting {
guard let url = chooseDirectory(startingAt: outboxURL) else { return }
FolderSettings.setOutbox(url)
setFolderURLs(outbox: url, watch: watchFolderURL)
setStatus("Output folder set to \(url.lastPathComponent).")
setStatus("PDFs are saved to \(url.lastPathComponent).")
}
func chooseWatchFolder() {
@@ -115,7 +333,7 @@ extension AppModel: SettingsWindowPresenting {
Task {
do {
try await watcher.updateWatchFolder(url)
setStatus("Watch folder set to \(url.lastPathComponent).")
setStatus("Watching \(url.lastPathComponent) for returns.")
} catch {
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
@@ -124,6 +342,79 @@ extension AppModel: SettingsWindowPresenting {
}
}
/// Settings "Send with" picker action. Persists the choice, recomputes the effective
/// outbox/watch folder for the new transport, creates the OneDrive folder if it
/// doesn't exist yet, and re-points the running watcher (folder + recordUncommented)
/// at the new state. Refuses while a send is in flight.
/// The async reconcile below is generation-guarded so rapid toggling always lets the
/// LAST choice win; its handle is stored in `pendingReconcileTask` so send() can
/// await it before snapshotting transport/folder.
func chooseTransport(_ value: SendTransport) {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
guard value != transport else { return }
TransportSettings.setTransport(value)
setTransport(value)
let folders = TransportSettings.effectiveFolders()
if value == .oneDrive {
try? FileManager.default.createDirectory(
at: folders.outbox, withIntermediateDirectories: true
)
}
setFolderURLs(outbox: folders.outbox, watch: folders.watch)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
await watcher.setRecordUncommented(value == .airDrop)
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(folders.watch)
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
/// Refuses while a send is in flight, same reasoning as chooseTransport. See
/// chooseTransport's doc comment for the generation-guard mechanism shared here.
func chooseOneDriveFolder() {
guard !isSending else {
setStatus("Finish the current send first.")
return
}
let start = resolvedOneDriveFolder ?? FileManager.default.homeDirectoryForCurrentUser
guard let url = chooseDirectory(startingAt: start) else { return }
TransportSettings.setOneDriveFolder(url)
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
guard transport == .oneDrive else { return }
setFolderURLs(outbox: url, watch: url)
reconcileGeneration += 1
let generation = reconcileGeneration
pendingReconcileTask = Task {
guard generation == self.reconcileGeneration else { return }
do {
try await watcher.updateWatchFolder(url)
guard generation == self.reconcileGeneration else { return }
setStatus("OneDrive folder set to \(url.lastPathComponent).")
} catch {
guard generation == self.reconcileGeneration else { return }
setStatus(
(error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder."
)
}
}
}
private func chooseDirectory(startingAt directory: URL) -> URL? {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
+37 -6
View File
@@ -7,7 +7,14 @@ enum Sharing {
/// Throws `ShotdeckError.airDropUnavailable` when the service cannot be created,
/// `canPerform` is false, or `view` is not in a visible window (a detached view
/// never produces an on-screen sheet).
static func airDrop(fileURL: URL, from view: NSView) throws {
///
/// `onFinished` is invoked on the main actor when the sheet completes: `true` for
/// `didShareItems`, `false` for `didFailToShareItems` (including user cancel).
static func airDrop(
fileURL: URL,
from view: NSView,
onFinished: @escaping @MainActor @Sendable (Bool) async -> Void
) throws {
guard let service = NSSharingService(named: .sendViaAirDrop),
service.canPerform(withItems: [fileURL]) else {
throw ShotdeckError.airDropUnavailable
@@ -21,7 +28,12 @@ enum Sharing {
window.makeKeyAndOrderFront(nil)
service.subject = fileURL.lastPathComponent
let session = AirDropSession(service: service, window: window, view: view)
let session = AirDropSession(
service: service,
window: window,
view: view,
onFinished: onFinished
)
AirDropSession.keepAlive(session)
service.delegate = session
service.perform(withItems: [fileURL])
@@ -29,7 +41,9 @@ enum Sharing {
}
/// Retains the sharing service for the life of the picker and supplies the real
/// on-screen window as the sheet parent. `NSSharingService.delegate` is weak.
/// on-screen window as the sheet parent. `NSSharingService.delegate` is weak, so
/// `live` is the strong reference that keeps this object alive until the sheet
/// reports success or failure (including cancel).
@MainActor
private final class AirDropSession: NSObject, NSSharingServiceDelegate {
static var live: [AirDropSession] = []
@@ -37,11 +51,19 @@ private final class AirDropSession: NSObject, NSSharingServiceDelegate {
let service: NSSharingService
let window: NSWindow
let view: NSView
let onFinished: @MainActor @Sendable (Bool) async -> Void
private var reported = false
init(service: NSSharingService, window: NSWindow, view: NSView) {
init(
service: NSSharingService,
window: NSWindow,
view: NSView,
onFinished: @escaping @MainActor @Sendable (Bool) async -> Void
) {
self.service = service
self.window = window
self.view = view
self.onFinished = onFinished
}
static func keepAlive(_ session: AirDropSession) {
@@ -52,6 +74,15 @@ private final class AirDropSession: NSObject, NSSharingServiceDelegate {
Self.live.removeAll { $0 === self }
}
private func report(_ success: Bool) {
guard !reported else { return }
reported = true
Task { @MainActor in
await self.onFinished(success)
self.drop()
}
}
func sharingService(
_ sharingService: NSSharingService,
sourceWindowForShareItems items: [Any],
@@ -70,7 +101,7 @@ private final class AirDropSession: NSObject, NSSharingServiceDelegate {
}
func sharingService(_ sharingService: NSSharingService, didShareItems items: [Any]) {
drop()
report(true)
}
func sharingService(
@@ -78,6 +109,6 @@ private final class AirDropSession: NSObject, NSSharingServiceDelegate {
didFailToShareItems items: [Any],
error: any Error
) {
drop()
report(false)
}
}
+504
View File
@@ -0,0 +1,504 @@
import AppKit
import CryptoKit
import Foundation
import Security
import ShotdeckCore
/// Built-in updater. Checks an appcast, stages a verified payload, and installs
/// only when the user clicks the menu row — never automatically.
@MainActor
final class UpdateChecker {
static let appcastURLDefaultsKey = "ai.flowmaster.shotdeck.appcastURL"
static let defaultAppcastURL = URL(string: "https://get.baobab-ts.com/cowork/redline/appcast.json")!
static let defaultInstallTarget = URL(fileURLWithPath: "/Applications/Redline.app")
/// Required bundle identifier for any staged or installed payload.
static let expectedBundleIdentifier = "ai.flowmaster.shotdeck"
/// Developer team identifiers MMD ships Redline under. Overridable only for the self-test.
static let allowedTeamIdentifiers: Set<String> = ["PWMCBMX5M8", "L3N9S54CN3"]
private(set) var availableUpdate: (version: String, notes: String)?
private(set) var stagedAppURL: URL?
private(set) var statusMessage: String?
private(set) var lastCheckedAt: Date?
private(set) var isCheckingNow: Bool = false
var onChecked: (() -> Void)?
/// Fired whenever `isCheckingNow` flips, so a UI can show "Checking…" for the
/// whole duration of a check rather than only after it lands.
var onCheckingChanged: ((Bool) -> Void)?
private let urlSession: URLSession
private var repeatingTimer: Timer?
private var firstCheckTask: Task<Void, Never>?
private var stagingDirectory: URL?
/// Snapshot-only override for previousVersion; when snapshotUsesPreviousVersionOverride is true,
/// this value (including nil) is returned instead of checking the file system.
var snapshotPreviousVersionOverride: String?
var snapshotUsesPreviousVersionOverride: Bool = false
/// Test seam: override appcast JSON. When set, returns this instead of fetching from URL.
var testAppcastJSON: String?
init() {
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 30
config.timeoutIntervalForResource = 600
config.httpCookieAcceptPolicy = .never
config.httpShouldSetCookies = false
config.httpCookieStorage = nil
config.urlCache = nil
urlSession = URLSession(configuration: config)
}
/// First check 10 seconds after start, then every 6 hours. Stages only — never installs.
func startSchedule() {
firstCheckTask?.cancel()
firstCheckTask = Task { [weak self] in
try? await Task.sleep(for: .seconds(10))
guard !Task.isCancelled else { return }
await self?.checkNow()
}
repeatingTimer?.invalidate()
let timer = Timer(timeInterval: 6 * 60 * 60, repeats: true) { [weak self] _ in
Task { @MainActor in
await self?.checkNow()
}
}
RunLoop.main.add(timer, forMode: .common)
repeatingTimer = timer
}
/// Checks the appcast and stages a newer, signature-verified payload.
/// `manual` only affects the status message shown when already up to date —
/// a user-initiated check says so; the silent background check stays quiet.
func checkNow(manual: Bool = false) async {
guard !isCheckingNow else { return }
isCheckingNow = true
onCheckingChanged?(true)
defer {
isCheckingNow = false
onCheckingChanged?(false)
}
lastCheckedAt = Date()
let appcast: Appcast
do {
appcast = try await fetchAppcast()
} catch {
statusMessage = "Could not check for updates."
onChecked?()
return
}
guard Self.isNewer(appcast.version, than: Self.currentVersion()) else {
clearOffer()
if manual {
let timestamp = DubaiTime.checkTime(lastCheckedAt ?? Date())
statusMessage = "Redline \(Self.currentVersion()) is up to date, checked \(timestamp)"
} else {
statusMessage = nil
}
onChecked?()
return
}
do {
try await downloadAndStage(appcast)
availableUpdate = (version: appcast.version, notes: appcast.notes ?? "")
statusMessage = manual ? "Update to \(appcast.version) is ready" : nil
} catch UpdateCheckError.checksumMismatch {
discardStaging()
availableUpdate = nil
statusMessage = "Update file failed the checksum — not installed."
} catch UpdateCheckError.signatureInvalid {
discardStaging()
availableUpdate = nil
statusMessage = "Update is not signed by MMD — not installed."
} catch {
discardStaging()
availableUpdate = nil
statusMessage = "The update could not be prepared."
}
onChecked?()
}
/// Installs the staged app onto `target` atomically, keeping exactly one rollback
/// copy (`Redline.app.previous`), then hands off to a relaunch and quits.
/// Never deletes the old app before the new one is verified in place.
func installStaged(to target: URL = UpdateChecker.defaultInstallTarget) {
guard let staged = stagedAppURL else {
statusMessage = "No update is staged."
onChecked?()
return
}
let targetDir = target.deletingLastPathComponent()
let previousURL = targetDir.appendingPathComponent("Redline.app.previous")
do {
try FileManager.default.createDirectory(at: targetDir, withIntermediateDirectories: true)
let replacementDir = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: target,
create: true
)
defer { try? FileManager.default.removeItem(at: replacementDir) }
let newCopy = replacementDir.appendingPathComponent(target.lastPathComponent)
try Self.runProcess(executable: "/usr/bin/ditto", arguments: [staged.path, newCopy.path])
// Exactly one rollback copy is kept — drop any older one before this install.
if FileManager.default.fileExists(atPath: previousURL.path) {
try FileManager.default.removeItem(at: previousURL)
}
if FileManager.default.fileExists(atPath: target.path) {
_ = try FileManager.default.replaceItemAt(
target,
withItemAt: newCopy,
backupItemName: previousURL.lastPathComponent,
options: [.withoutDeletingBackupItem]
)
} else {
try FileManager.default.moveItem(at: newCopy, to: target)
}
} catch {
statusMessage = "The update could not be installed."
onChecked?()
return
}
// Defense in depth: re-verify what actually landed on disk, not just the staged copy.
do {
try Self.verifySignature(of: target)
} catch {
statusMessage = "The update was installed but failed verification."
onChecked?()
return
}
discardStaging()
availableUpdate = nil
relaunch(target: target)
}
/// Swaps `Redline.app.previous` back into place, verifying its signature first.
/// The just-replaced (newer) app becomes the new `.previous` — a revert is
/// itself reversible.
func revertToPrevious(target: URL = UpdateChecker.defaultInstallTarget) {
let targetDir = target.deletingLastPathComponent()
let previousURL = targetDir.appendingPathComponent("Redline.app.previous")
guard FileManager.default.fileExists(atPath: previousURL.path) else {
statusMessage = "No previous version to revert to."
onChecked?()
return
}
do {
try Self.verifySignature(of: previousURL)
} catch {
statusMessage = "The previous version failed verification and was not restored."
onChecked?()
return
}
do {
// `previousURL` cannot be handed to replaceItemAt directly: its own path
// IS the requested backup name, so the backup step would clobber it
// before the swap ever reads it. Stage a throwaway copy first, exactly
// like installStaged does for the forward direction.
let replacementDir = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: target,
create: true
)
defer { try? FileManager.default.removeItem(at: replacementDir) }
let newCopy = replacementDir.appendingPathComponent(target.lastPathComponent)
try Self.runProcess(executable: "/usr/bin/ditto", arguments: [previousURL.path, newCopy.path])
try FileManager.default.removeItem(at: previousURL)
_ = try FileManager.default.replaceItemAt(
target,
withItemAt: newCopy,
backupItemName: previousURL.lastPathComponent,
options: [.withoutDeletingBackupItem]
)
} catch {
statusMessage = "Could not revert to the previous version."
onChecked?()
return
}
relaunch(target: target)
}
/// The version recorded in `Redline.app.previous`'s Info.plist, or nil when no
/// rollback copy exists. Respects the snapshot-only override for panel rendering.
func previousVersion(target: URL = UpdateChecker.defaultInstallTarget) -> String? {
if snapshotUsesPreviousVersionOverride {
return snapshotPreviousVersionOverride
}
let previousURL = target.deletingLastPathComponent().appendingPathComponent("Redline.app.previous")
let plistURL = previousURL.appendingPathComponent("Contents/Info.plist")
guard let plist = NSDictionary(contentsOf: plistURL) as? [String: Any] else { return nil }
return plist["CFBundleShortVersionString"] as? String
}
static func resolvedAppcastURL() -> URL {
if let env = ProcessInfo.processInfo.environment["REDLINE_APPCAST_URL"],
!env.isEmpty,
let url = URL(string: env)
{
return url
}
if let stored = UserDefaults.standard.string(forKey: appcastURLDefaultsKey),
!stored.isEmpty,
let url = URL(string: stored)
{
return url
}
return defaultAppcastURL
}
static func currentVersion() -> String {
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
}
static func isNewer(_ candidate: String, than current: String) -> Bool {
let a = semverParts(candidate)
let b = semverParts(current)
for i in 0..<3 {
if a[i] != b[i] { return a[i] > b[i] }
}
return false
}
static func sha256Hex(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
/// Validates the code signature of the app at `appURL`: strictly, across all
/// architectures and nested code, then checks its bundle identifier and team
/// identifier against `expectedBundleIdentifier` / the allowed-teams set.
/// `REDLINE_ALLOWED_TEAMS` (comma separated) overrides the allowed set — for
/// the self-test only, so it can accept a locally re-signed fake bundle.
static func verifySignature(of appURL: URL) throws {
var staticCode: SecStaticCode?
let createStatus = SecStaticCodeCreateWithPath(appURL as CFURL, [], &staticCode)
guard createStatus == errSecSuccess, let code = staticCode else {
throw UpdateCheckError.signatureInvalid(
"could not read a code signature (status \(createStatus))"
)
}
let validityFlags = SecCSFlags(
rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode
)
var validityError: Unmanaged<CFError>?
let validityStatus = SecStaticCodeCheckValidityWithErrors(code, validityFlags, nil, &validityError)
guard validityStatus == errSecSuccess else {
let detail = (validityError?.takeRetainedValue()).map { String(describing: $0) } ?? "status \(validityStatus)"
throw UpdateCheckError.signatureInvalid("signature is not valid: \(detail)")
}
var signingInfo: CFDictionary?
let infoStatus = SecCodeCopySigningInformation(
code,
SecCSFlags(rawValue: kSecCSSigningInformation),
&signingInfo
)
guard infoStatus == errSecSuccess, let info = signingInfo as? [String: Any] else {
throw UpdateCheckError.signatureInvalid("could not read signing information (status \(infoStatus))")
}
let identifier = info[kSecCodeInfoIdentifier as String] as? String
guard identifier == expectedBundleIdentifier else {
throw UpdateCheckError.signatureInvalid(
"unexpected bundle identifier: \(identifier ?? "nil")"
)
}
let teamIdentifier = info[kSecCodeInfoTeamIdentifier as String] as? String
guard let teamIdentifier, resolvedAllowedTeamIdentifiers().contains(teamIdentifier) else {
throw UpdateCheckError.signatureInvalid(
"unexpected team identifier: \(teamIdentifier ?? "nil")"
)
}
}
private static func resolvedAllowedTeamIdentifiers() -> Set<String> {
if let env = ProcessInfo.processInfo.environment["REDLINE_ALLOWED_TEAMS"], !env.isEmpty {
let parts = env.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if !parts.isEmpty {
return Set(parts)
}
}
return allowedTeamIdentifiers
}
// MARK: - Private
private struct Appcast: Decodable {
var version: String
var zipURL: URL
var sha256: String
var notes: String?
}
private enum UpdateCheckError: Error {
case checksumMismatch
case invalidPayload
case httpStatus(Int)
case processFailed(String)
case signatureInvalid(String)
}
private func fetchAppcast() async throws -> Appcast {
let data: Data
if let testJSON = testAppcastJSON {
data = testJSON.data(using: .utf8) ?? Data()
} else {
data = try await fetchData(from: Self.resolvedAppcastURL())
}
return try JSONDecoder().decode(Appcast.self, from: data)
}
private func fetchData(from url: URL) async throws -> Data {
if url.isFileURL {
return try Data(contentsOf: url)
}
let (data, response) = try await urlSession.data(from: url)
if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
throw UpdateCheckError.httpStatus(http.statusCode)
}
return data
}
private func downloadAndStage(_ appcast: Appcast) async throws {
let zipData = try await fetchData(from: appcast.zipURL)
let expected = appcast.sha256.trimmingCharacters(in: .whitespacesAndNewlines)
let actual = Self.sha256Hex(zipData)
guard actual.caseInsensitiveCompare(expected) == .orderedSame else {
throw UpdateCheckError.checksumMismatch
}
discardStaging()
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-update-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
stagingDirectory = root
let zipURL = root.appendingPathComponent("update.zip")
try zipData.write(to: zipURL)
let extracted = root.appendingPathComponent("extracted", isDirectory: true)
try FileManager.default.createDirectory(at: extracted, withIntermediateDirectories: true)
try Self.runProcess(
executable: "/usr/bin/ditto",
arguments: ["-x", "-k", zipURL.path, extracted.path]
)
guard let appURL = Self.findRedlineApp(in: extracted) else {
throw UpdateCheckError.invalidPayload
}
let executable = appURL.appendingPathComponent("Contents/MacOS/Shotdeck")
guard FileManager.default.fileExists(atPath: executable.path) else {
throw UpdateCheckError.invalidPayload
}
try Self.verifySignature(of: appURL)
stagedAppURL = appURL
}
private func clearOffer() {
availableUpdate = nil
discardStaging()
}
private func discardStaging() {
if let stagingDirectory {
try? FileManager.default.removeItem(at: stagingDirectory)
}
stagingDirectory = nil
stagedAppURL = nil
}
/// Spawns a detached watcher that waits for this process to exit, then reopens
/// `target`, and quits. Never called during the self-test, so the in-process
/// assertions after `installStaged`/`revertToPrevious` can still run.
private func relaunch(target: URL) {
guard ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] == nil else { return }
let ownPID = ProcessInfo.processInfo.processIdentifier
let script = "while kill -0 \(ownPID) 2>/dev/null; do sleep 0.2; done; " +
"/usr/bin/open -n \(Self.shellQuoted(target.path))"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/sh")
process.arguments = ["-c", script]
process.standardInput = FileHandle.nullDevice
process.standardOutput = FileHandle.nullDevice
process.standardError = FileHandle.nullDevice
do {
try process.run()
} catch {
statusMessage = "The update was installed but Redline could not relaunch. Open it from Applications."
onChecked?()
return
}
NSApp.terminate(nil)
}
private static func shellQuoted(_ path: String) -> String {
"'" + path.replacingOccurrences(of: "'", with: "'\\''") + "'"
}
private static func findRedlineApp(in directory: URL) -> URL? {
let fm = FileManager.default
let direct = directory.appendingPathComponent("Redline.app")
if fm.fileExists(atPath: direct.path) { return direct }
guard let enumerator = fm.enumerator(
at: directory,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
) else { return nil }
while let item = enumerator.nextObject() as? URL {
if item.lastPathComponent == "Redline.app" {
return item
}
if item.pathExtension == "app" {
enumerator.skipDescendants()
}
}
return nil
}
private static func semverParts(_ string: String) -> [Int] {
let core = string.split(separator: "-").first.map(String.init) ?? string
var parts = core.split(separator: ".").prefix(3).map { Int($0) ?? 0 }
while parts.count < 3 { parts.append(0) }
return parts
}
private static func runProcess(executable: String, arguments: [String]) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: executable)
process.arguments = arguments
let err = Pipe()
process.standardError = err
process.standardOutput = Pipe()
try process.run()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
let message = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
throw UpdateCheckError.processFailed("\(executable) failed: \(message)")
}
}
}
@@ -0,0 +1,252 @@
import AppKit
import ShotdeckCore
/// Hides Redline's own windows while the user is choosing what to capture, then puts
/// them back. The popover would otherwise sit on top of the thing being picked and,
/// worse, end up inside the screenshot.
@MainActor
enum RedlineWindows {
private static var hidden: [NSWindow] = []
static func hideForPicking() {
hidden = NSApp.windows.filter { window in
window.isVisible && !(window is RegionPickerWindow)
}
for window in hidden {
window.orderOut(nil)
}
}
static func restoreAfterPicking() {
for window in hidden where !window.isVisible {
window.orderFront(nil)
}
hidden = []
}
}
/// Highlights the window under the pointer and captures the one the user clicks —
/// an app window, a browser window with its active tab, or the whole screen when the
/// pointer is over the desktop.
@MainActor
public final class WindowPickerController {
private var windows: [RegionPickerWindow] = []
private var monitor: Any?
private var hoverTimer: Timer?
private var completion: (@MainActor (CaptureTarget?) -> Void)?
private var candidates: [WindowCandidate] = []
private var primaryHeight: CGFloat = 0
private var hovered: WindowCandidate?
private var hoveredScreen: NSScreen?
public init() {}
/// Presents the picker. The completion receives the chosen target, or nil when the
/// user pressed Escape.
public func pick(
onlyBrowsers: Bool = false,
completion: @escaping @MainActor (CaptureTarget?) -> Void
) {
if self.completion != nil {
finish(target: nil)
}
self.completion = completion
self.primaryHeight = NSScreen.screens.first?.frame.height ?? 0
let all = ScreenCapturer.onScreenWindows().filter { candidate in
candidate.layer == 0
&& candidate.ownerBundleID != CaptureTargetResolver.ownBundleID
&& candidate.frame.width >= 40
&& candidate.frame.height >= 40
}
self.candidates = onlyBrowsers
? all.filter { candidate in
guard let bundle = candidate.ownerBundleID else { return false }
return CaptureTargetResolver.browserBundleIDs.contains(bundle)
}
: all
presentOverlays()
}
// MARK: - Overlays
private func presentOverlays() {
let screens = NSScreen.screens
guard !screens.isEmpty else {
finish(target: nil)
return
}
windows = screens.map { RegionPickerWindow(screen: $0) }
for window in windows {
window.orderFrontRegardless()
}
let mouse = NSEvent.mouseLocation
let keyWindow = windows.first { $0.coveringScreen.frame.contains(mouse) } ?? windows[0]
keyWindow.makeKey()
// A timer drives the highlight from the real pointer position: mouse-moved
// events are only delivered to the key window, and the overlay must track the
// pointer even over another app's window.
hoverTimer?.invalidate()
hoverTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 60.0, repeats: true) {
[weak self] _ in
MainActor.assumeIsolated {
self?.updateHover(at: NSEvent.mouseLocation)
}
}
monitor = NSEvent.addLocalMonitorForEvents(
matching: [.mouseMoved, .leftMouseDown, .keyDown]
) { [weak self] event in
guard let self else { return event }
let type = event.type
let keyCode: UInt16 = (type == .keyDown) ? event.keyCode : 0
let locationInWindow = event.locationInWindow
let windowNumber = event.windowNumber
let consume = MainActor.assumeIsolated {
let location = self.globalAppKitLocation(
locationInWindow: locationInWindow, windowNumber: windowNumber)
return self.handle(type: type, keyCode: keyCode, location: location)
}
return consume ? nil : event
}
updateHover(at: mouse)
}
private func handle(type: NSEvent.EventType, keyCode: UInt16, location: NSPoint?) -> Bool {
switch type {
case .keyDown:
if keyCode == 53 { // Escape
finish(target: nil)
return true
}
return false
case .mouseMoved:
updateHover(at: location ?? NSEvent.mouseLocation)
return false
case .leftMouseDown:
if let target = targetUnderPointer(at: location ?? NSEvent.mouseLocation) {
finish(target: target)
}
return true
default:
return false
}
}
// MARK: - Hover
private func updateHover(at point: NSPoint) {
let screen = NSScreen.screens.first { $0.frame.contains(point) }
let candidate = candidate(at: point)
hovered = candidate
hoveredScreen = screen
let highlightRect = candidate.map { appKitRect($0.frame) } ?? screen?.frame
let chip: String
if let candidate {
let app = appName(for: candidate)
let title = windowTitle(for: candidate)
chip = title.isEmpty ? app : "\(app) — \(title)"
} else {
chip = "Entire Screen"
}
for window in windows {
guard let windowScreen = windows.first(where: { $0 === window })?.coveringScreen
else { continue }
guard let highlightRect, windowScreen.frame.intersects(highlightRect) else {
window.updateSelection(localRect: nil, sizeText: nil)
continue
}
let local = CGRect(
x: highlightRect.minX - windowScreen.frame.minX,
y: highlightRect.minY - windowScreen.frame.minY,
width: highlightRect.width,
height: highlightRect.height
)
window.updateSelection(localRect: local, sizeText: chip)
}
}
private func targetUnderPointer(at point: NSPoint) -> CaptureTarget? {
if let candidate = candidate(at: point) {
return .window(
windowID: candidate.windowID,
frame: candidate.frame,
displayID: CaptureTargetResolver.displayID(containing: candidate.frame)
)
}
guard let screen = NSScreen.screens.first(where: { $0.frame.contains(point) }) else {
return nil
}
return .display(displayID: displayID(for: screen))
}
private func candidate(at point: NSPoint) -> WindowCandidate? {
candidates.first { candidate in
appKitRect(candidate.frame).contains(point)
}
}
// MARK: - Geometry and labels
private func appKitRect(_ cgRect: CGRect) -> CGRect {
CGRect(
x: cgRect.minX,
y: primaryHeight - cgRect.minY - cgRect.height,
width: cgRect.width,
height: cgRect.height
)
}
private func displayID(for screen: NSScreen) -> UInt32 {
(screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?
.uint32Value ?? CGMainDisplayID()
}
private func appName(for candidate: WindowCandidate) -> String {
guard let bundle = candidate.ownerBundleID,
let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundle)
else { return "Window" }
return FileManager.default.displayName(atPath: url.path)
.replacingOccurrences(of: ".app", with: "")
}
private func windowTitle(for candidate: WindowCandidate) -> String {
guard let raw = CGWindowListCopyWindowInfo([.optionIncludingWindow], candidate.windowID)
as? [[String: Any]], let first = raw.first
else { return "" }
return first[kCGWindowName as String] as? String ?? ""
}
private func globalAppKitLocation(locationInWindow: NSPoint, windowNumber: Int) -> NSPoint? {
if let window = windows.first(where: { $0.windowNumber == windowNumber }) {
return window.convertPoint(toScreen: locationInWindow)
}
if windowNumber != 0, let window = NSApp.window(withWindowNumber: windowNumber) {
return window.convertPoint(toScreen: locationInWindow)
}
return NSEvent.mouseLocation
}
// MARK: - Finish
private func finish(target: CaptureTarget?) {
hoverTimer?.invalidate()
hoverTimer = nil
if let monitor {
NSEvent.removeMonitor(monitor)
}
monitor = nil
for window in windows {
window.orderOut(nil)
}
windows = []
let completion = self.completion
self.completion = nil
completion?(target)
}
}
+80 -9
View File
@@ -7,6 +7,18 @@ import ShotdeckCore
if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil {
MainActor.assumeIsolated { PanelSnapshot.runIfRequested() }
}
if SelfTestLaunch.phase == "e2e" {
MainActor.assumeIsolated { PanelSelfTest.runE2EIfRequested() }
}
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" {
MainActor.assumeIsolated { PanelSelfTest.runIfRequested() }
}
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" {
MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() }
}
if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "sendtruth" {
MainActor.assumeIsolated { PickerSelfTest.runSendTruthOnlyIfRequested() }
}
if ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil {
MainActor.assumeIsolated { PickerSelfTest.runIfRequested() }
}
@@ -21,18 +33,42 @@ struct ShotdeckApp: App {
.environment(appDelegate.model)
} label: {
let state = appDelegate.model.iconState
let hasUpdate = appDelegate.model.updateAvailable != nil
HStack(spacing: 4) {
Image(systemName: state.symbolName)
menuBarIcon(for: state, hasUpdate: hasUpdate)
if let count = state.countText {
Text(count).font(.system(size: 11, weight: .semibold))
}
}
.accessibilityLabel("Shotdeck")
.accessibilityLabel("Redline")
}
.menuBarExtraStyle(.window)
}
}
/// The menu-bar symbol for `state`, badged while an update is staged. Uses the
/// SF Symbol's own `.badge` variant when one exists; falls back to a small
/// overlaid dot on the plain symbol otherwise. The badge disappears on its own
/// once `updateAvailable` clears, since this reads live model state.
@ViewBuilder
private func menuBarIcon(for state: MenuIconState, hasUpdate: Bool) -> some View {
if hasUpdate {
let badgeName = "\(state.symbolName).badge"
if NSImage(systemSymbolName: badgeName, accessibilityDescription: nil) != nil {
Image(systemName: badgeName)
} else {
ZStack(alignment: .topTrailing) {
Image(systemName: state.symbolName)
Circle()
.frame(width: 6, height: 6)
.offset(x: 3, y: -3)
}
}
} else {
Image(systemName: state.symbolName)
}
}
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
let model: AppModel
@@ -45,12 +81,43 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
Task { await model.bootstrap() }
// `--window` opens the session window at launch (scripts and demos); a normal
// launch stays quiet in the menu bar.
if CommandLine.arguments.contains("--window") {
presentSessionsWindow()
}
}
private static func makeLaunchModel() -> AppModel {
/// Clicking the app in Finder, or `open -a Redline`, while it runs shows the
/// window instead of doing nothing — standard macOS behaviour for a menu-bar app
/// with a main window.
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows: Bool) -> Bool {
if !hasVisibleWindows {
presentSessionsWindow()
}
return true
}
private func presentSessionsWindow() {
(model as SessionsWindowPresenting).presentSessionsWindow(focusLane: false)
}
/// Builds the model exactly the way the real app launches: paths come from
/// `TransportSettings.resolvedAppSupportPaths()` — transport-aware, so the watcher
/// this feeds is never seeded with a stale AirDrop folder while OneDrive is the
/// persisted transport (that was the BLOCKER this function used to have, when it
/// called the AirDrop-only `FolderSettings.resolvedAppSupportPaths()` instead).
/// `appSupportRoot` exists only so PickerSelfTest's relaunch-simulation sub-step can
/// point this at a temp directory instead of the real
/// ~/Library/Application Support/Shotdeck — production always calls this with no
/// argument (the real root). Internal, not private, for that same reason.
static func makeLaunchModel(
appSupportRoot: URL? = nil,
retentionDefaults: UserDefaults = .standard
) -> AppModel {
do {
let paths = try FolderSettings.resolvedAppSupportPaths()
return try makeModel(paths: paths)
let paths = try TransportSettings.resolvedAppSupportPaths(root: appSupportRoot)
return try makeModel(paths: paths, retentionDefaults: retentionDefaults)
} catch {
Log.ui.critical(
"AppModel init failed: \(String(describing: error), privacy: .public)"
@@ -59,13 +126,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let fallbackRoot = tmp.appendingPathComponent("Shotdeck-fallback", isDirectory: true)
// Safe: temp-dir creation for a path this process controls cannot legitimately fail.
let fallback = try! AppSupportPaths(root: fallbackRoot, outbox: tmp, watchFolder: tmp)
let model = try! makeModel(paths: fallback)
model.setStatus("Shotdeck could not access its storage folder. Captures will not persist.")
let model = try! makeModel(paths: fallback, retentionDefaults: retentionDefaults)
model.setStatus("Redline could not access its storage folder. Captures will not persist.")
return model
}
}
private static func makeModel(paths: AppSupportPaths) throws -> AppModel {
private static func makeModel(
paths: AppSupportPaths,
retentionDefaults: UserDefaults
) throws -> AppModel {
let ledger = try ReturnLedger(paths: paths)
return AppModel(
paths: paths,
@@ -75,7 +145,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger)
watcher: ReturnWatcher(paths: paths, ledger: ledger),
retentionDefaults: retentionDefaults
)
}
}
@@ -55,4 +55,20 @@ public struct CaptureRegion: Codable, Sendable, Equatable {
/// Persisted in UserDefaults under this key BY THE APP (WP-4a), never by this type.
public static let defaultsKey = "ai.flowmaster.shotdeck.region"
/// 1-based position of this region's display in the current screen list; 1 when the
/// display is no longer attached.
public var displayNumber: Int {
let match = NSScreen.screens.firstIndex { screen in
let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")]
as? NSNumber)?.uint32Value
return id == displayID
}
return (match ?? 0) + 1
}
/// "800 × 600 on Display 1" — the line the popover shows under the capture control.
public var summary: String {
String(format: "%.0f × %.0f on Display %d", rect.width, rect.height, displayNumber)
}
}
@@ -0,0 +1,79 @@
import Foundation
/// What a capture takes a picture of.
///
/// The choice belongs to the session being captured into: it is stored once and copied
/// to the next session, so a review run keeps capturing the same kind of thing until
/// the user says otherwise. Choosing anything other than `.area` never clears the saved
/// area — it comes back when Area is chosen again.
public enum CaptureScope: String, Codable, Sendable, CaseIterable {
case area
case window
case browser
case screen
/// Label for the segmented control and the window's menu.
public var displayName: String {
switch self {
case .area: return "Area"
case .window: return "Window"
case .browser: return "Browser"
case .screen: return "Screen"
}
}
/// The longer menu item wording (window picker).
public var menuTitle: String {
switch self {
case .area: return "Saved Area"
case .window: return "Front Window"
case .browser: return "Browser Page"
case .screen: return "Whole Screen"
}
}
/// Sentence shown under the control: what pressing Capture will take.
public func targetDescription(savedArea: CaptureRegion?) -> String {
switch self {
case .area:
guard let savedArea else { return "No area saved yet — choose one first" }
return savedArea.summary
case .window:
return "The frontmost window when you capture"
case .browser:
return "The frontmost browser window when you capture"
case .screen:
guard let savedArea else { return "The display with the frontmost window" }
return "All of Display \(savedArea.displayNumber)"
}
}
}
/// Persistence for the capture choice. Stored separately from the chosen area so
/// switching scope never destroys the area.
public enum CaptureSettings {
public static let scopeKey = "ai.flowmaster.shotdeck.captureScope"
public static let askOnNewSessionKey = "ai.flowmaster.shotdeck.askScopeOnNewSession"
public static func scope(defaults: UserDefaults = .standard) -> CaptureScope {
guard let raw = defaults.string(forKey: scopeKey),
let scope = CaptureScope(rawValue: raw)
else { return .area }
return scope
}
public static func setScope(_ scope: CaptureScope, defaults: UserDefaults = .standard) {
defaults.set(scope.rawValue, forKey: scopeKey)
}
/// Whether "New Session…" asks what to capture before starting. Off means it
/// starts immediately with the current choice.
public static func askOnNewSession(defaults: UserDefaults = .standard) -> Bool {
guard defaults.object(forKey: askOnNewSessionKey) != nil else { return true }
return defaults.bool(forKey: askOnNewSessionKey)
}
public static func setAskOnNewSession(_ value: Bool, defaults: UserDefaults = .standard) {
defaults.set(value, forKey: askOnNewSessionKey)
}
}
@@ -0,0 +1,125 @@
import CoreGraphics
import Foundation
/// One on-screen window as the capture resolver sees it. Kept as plain data so the
/// choice logic is testable without a window server.
public struct WindowCandidate: Sendable, Equatable {
public let windowID: UInt32
public let ownerBundleID: String?
public let ownerPID: Int32
public let frame: CGRect
public let layer: Int
public init(
windowID: UInt32,
ownerBundleID: String?,
ownerPID: Int32,
frame: CGRect,
layer: Int
) {
self.windowID = windowID
self.ownerBundleID = ownerBundleID
self.ownerPID = ownerPID
self.frame = frame
self.layer = layer
}
}
/// What a capture will take: one region of a display, one whole display, or one window.
public enum CaptureTarget: Sendable, Equatable {
case region(CaptureRegion)
case display(displayID: UInt32)
case window(windowID: UInt32, frame: CGRect, displayID: UInt32)
}
/// Chooses the capture target for a scope from the windows that are on screen.
///
/// Candidates arrive front-to-back (the order the window server reports), which is what
/// makes "the front window" well defined. Redline's own windows are never candidates,
/// so choosing Window never captures the app's own panel.
public enum CaptureTargetResolver {
/// Bundles whose front window counts as a browser page.
public static let browserBundleIDs: Set<String> = [
"com.apple.Safari",
"com.google.Chrome",
"com.google.Chrome.canary",
"com.microsoft.edgemac",
"com.brave.Browser",
"company.thebrowser.Browser",
"org.mozilla.firefox",
"com.vivaldi.Vivaldi",
"com.operasoftware.Opera",
]
/// Redline's own bundle identifier — never a capture target.
public static let ownBundleID = "ai.flowmaster.shotdeck"
public static func resolve(
scope: CaptureScope,
savedArea: CaptureRegion?,
frontmostPID: Int32,
candidates: [WindowCandidate]
) throws -> CaptureTarget {
let usable = candidates.filter { candidate in
candidate.layer == 0
&& candidate.ownerBundleID != ownBundleID
&& candidate.frame.width >= 40
&& candidate.frame.height >= 40
}
switch scope {
case .area:
guard let savedArea else { throw ShotdeckError.noRegionRemembered }
return .region(savedArea)
case .screen:
if let savedArea {
return .display(displayID: savedArea.displayID)
}
guard let window = usable.first else { throw ShotdeckError.noFrontWindow }
return .display(displayID: displayID(containing: window.frame))
case .window:
let ownAppFirst = usable.first { $0.ownerPID == frontmostPID }
guard let window = ownAppFirst ?? usable.first else {
throw ShotdeckError.noFrontWindow
}
return .window(
windowID: window.windowID,
frame: window.frame,
displayID: displayID(containing: window.frame)
)
case .browser:
guard let window = usable.first(where: {
guard let bundle = $0.ownerBundleID else { return false }
return browserBundleIDs.contains(bundle)
}) else {
throw ShotdeckError.noBrowserWindow
}
return .window(
windowID: window.windowID,
frame: window.frame,
displayID: displayID(containing: window.frame)
)
}
}
/// The display whose bounds contain the window's centre; the main display when a
/// window straddles two screens and belongs to neither cleanly.
public static func displayID(containing frame: CGRect) -> UInt32 {
let centre = CGPoint(x: frame.midX, y: frame.midY)
var count: UInt32 = 0
guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else {
return CGMainDisplayID()
}
var displays = [CGDirectDisplayID](repeating: 0, count: Int(count))
guard CGGetActiveDisplayList(count, &displays, &count) == .success else {
return CGMainDisplayID()
}
for display in displays.prefix(Int(count)) where CGDisplayBounds(display).contains(centre) {
return display
}
return CGMainDisplayID()
}
}
@@ -18,6 +18,135 @@ public struct ScreenCapturer: Sendable {
/// Does NOT prompt. Reports the current Screen Recording grant.
public static var isScreenRecordingGranted: Bool { CGPreflightScreenCaptureAccess() }
/// Captures whatever the given scope points at, resolving it right now.
public func capture(
_ scope: CaptureScope,
savedArea: CaptureRegion?
) async throws -> CapturedImage {
guard Self.isScreenRecordingGranted else {
throw ShotdeckError.screenRecordingNotGranted
}
let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0
let target = try CaptureTargetResolver.resolve(
scope: scope,
savedArea: savedArea,
frontmostPID: frontmostPID,
candidates: Self.onScreenWindows()
)
return try await capture(target)
}
/// Captures one resolved target. A window is captured window-only (so an overlapping
/// window never ends up in a review shot); a region or a display goes through the
/// display path.
public func capture(_ target: CaptureTarget) async throws -> CapturedImage {
guard Self.isScreenRecordingGranted else {
throw ShotdeckError.screenRecordingNotGranted
}
switch target {
case .region(let region):
return try await capture(region)
case .display(let displayID):
let bounds = CGDisplayBounds(displayID)
return try await capture(
CaptureRegion(
displayID: displayID, rect: bounds,
capturedScale: Self.backingScale(for: displayID)))
case .window(let windowID, let frame, let displayID):
return try await captureWindow(
windowID: windowID, frame: frame, displayID: displayID)
}
}
/// On-screen windows, front-most first, as plain data for the resolver.
public static func onScreenWindows() -> [WindowCandidate] {
guard let raw = CGWindowListCopyWindowInfo(
[.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID
) as? [[String: Any]] else { return [] }
return raw.compactMap { entry in
guard let windowID = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value,
let ownerPID = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
let boundsDict = entry[kCGWindowBounds as String] as? [String: Any],
let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue
else { return nil }
let frame = CGRect(
x: boundsDict["X"] as? Double ?? 0,
y: boundsDict["Y"] as? Double ?? 0,
width: boundsDict["Width"] as? Double ?? 0,
height: boundsDict["Height"] as? Double ?? 0
)
return WindowCandidate(
windowID: windowID,
ownerBundleID: bundleIdentifier(forPID: ownerPID),
ownerPID: ownerPID,
frame: frame,
layer: layer
)
}
}
private static func bundleIdentifier(forPID pid: Int32) -> String? {
NSRunningApplication(processIdentifier: pid)?.bundleIdentifier
}
private static func backingScale(for displayID: UInt32) -> CGFloat {
guard let mode = CGDisplayCopyDisplayMode(displayID), mode.width > 0 else { return 2 }
return CGFloat(mode.pixelWidth) / CGFloat(mode.width)
}
/// Captures a single window through ScreenCaptureKit's window filter, at the display's
/// backing scale, without the window server compositing anything on top of it.
private func captureWindow(
windowID: UInt32,
frame: CGRect,
displayID: UInt32
) async throws -> CapturedImage {
let content: SCShareableContent
do {
content = try await SCShareableContent.excludingDesktopWindows(
false, onScreenWindowsOnly: true)
} catch {
throw ShotdeckError.captureFailed(underlying: error.localizedDescription)
}
guard let window = content.windows.first(where: { $0.windowID == windowID }) else {
throw ShotdeckError.noFrontWindow
}
let scale = Self.backingScale(for: displayID)
let filter = SCContentFilter(desktopIndependentWindow: window)
let configuration = SCStreamConfiguration()
configuration.width = Int((frame.width * scale).rounded())
configuration.height = Int((frame.height * scale).rounded())
configuration.showsCursor = false
configuration.scalesToFit = false
let cgImage: CGImage
do {
cgImage = try await SCScreenshotManager.captureImage(
contentFilter: filter, configuration: configuration)
} catch {
throw ShotdeckError.captureFailed(underlying: error.localizedDescription)
}
let data = NSMutableData()
guard let dest = CGImageDestinationCreateWithData(
data, UTType.png.identifier as CFString, 1, nil
) else {
throw ShotdeckError.captureFailed(underlying: "could not create PNG image destination")
}
CGImageDestinationAddImage(dest, cgImage, nil)
guard CGImageDestinationFinalize(dest) else {
throw ShotdeckError.captureFailed(underlying: "PNG encoding failed to finalize")
}
return CapturedImage(
pngData: data as Data,
pixelWidth: cgImage.width,
pixelHeight: cgImage.height,
scale: scale
)
}
/// Captures `region` at the display's true backing scale. Throws
/// `.screenRecordingNotGranted` when the grant is absent — never requests it.
public func capture(_ region: CaptureRegion) async throws -> CapturedImage {
@@ -2,7 +2,7 @@ import Foundation
public enum SessionState: String, Codable, Sendable {
case open // accepting captures
case archived // its PDF has been built and sent; kept forever, never deleted
case archived // closed and kept as a past session (sent or not); pruned only by an age policy the user set
}
/// The manifest persisted as session.json alongside the PNGs.
@@ -11,27 +11,40 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
public let createdAt: Date
public private(set) var state: SessionState
public private(set) var captures: [Capture]
/// Set when the PDF is built, so a re-send reuses the same file.
/// Set when the PDF is built, so a re-send reuses the same file. nil on a
/// session that was closed without ever sending — the Past sessions list
/// shows that as "Not sent".
public private(set) var pdfFileName: String?
/// Lane / deployed build / commit / reviewer / note for this session. Absent from
/// manifests written before v0.5.0 — those decode as `.empty`, never a guess.
public private(set) var context: ReviewContext
public init(
id: UUID,
createdAt: Date,
state: SessionState,
captures: [Capture],
pdfFileName: String?
pdfFileName: String?,
context: ReviewContext = .empty
) {
self.id = id
self.createdAt = createdAt
self.state = state
self.captures = captures
self.pdfFileName = pdfFileName
self.context = context
}
public var isEmpty: Bool {
captures.isEmpty
}
/// First 8 characters of the UUID, uppercase — the stable short handle used in
/// file names, the session list and the PDF header.
public var shortID: String {
String(id.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)).uppercased()
}
/// max(sequence)+1, or 1 when empty.
public var nextSequence: Int {
(captures.map(\.sequence).max() ?? 0) + 1
@@ -44,7 +57,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
createdAt: createdAt,
state: state,
captures: captures + [capture],
pdfFileName: pdfFileName
pdfFileName: pdfFileName,
context: context
)
}
@@ -56,18 +70,63 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
createdAt: createdAt,
state: state,
captures: captures.filter { $0.id != captureID },
pdfFileName: pdfFileName
pdfFileName: pdfFileName,
context: context
)
}
/// Value-semantic: returns a new session; does not mutate `self`.
public func markArchived(pdfFileName: String) -> CaptureSession {
/// `pdfFileName` is nil when the session is closed without ever sending.
public func markArchived(pdfFileName: String?) -> CaptureSession {
CaptureSession(
id: id,
createdAt: createdAt,
state: .archived,
captures: captures,
pdfFileName: pdfFileName
pdfFileName: pdfFileName,
context: context
)
}
/// Value-semantic: returns a new session; does not mutate `self`.
public func withContext(_ newContext: ReviewContext) -> CaptureSession {
CaptureSession(
id: id,
createdAt: createdAt,
state: state,
captures: captures,
pdfFileName: pdfFileName,
context: newContext
)
}
/// Value-semantic: returns a new session; does not mutate `self`.
public func withPDFFileName(_ name: String?) -> CaptureSession {
CaptureSession(
id: id,
createdAt: createdAt,
state: state,
captures: captures,
pdfFileName: name,
context: context
)
}
private enum CodingKeys: String, CodingKey {
case id, createdAt, state, captures, pdfFileName, context
}
/// `context` is decoded leniently so every manifest written before v0.5.0 keeps
/// loading; all other keys are required, exactly as before.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(
id: try container.decode(UUID.self, forKey: .id),
createdAt: try container.decode(Date.self, forKey: .createdAt),
state: try container.decode(SessionState.self, forKey: .state),
captures: try container.decode([Capture].self, forKey: .captures),
pdfFileName: try container.decodeIfPresent(String.self, forKey: .pdfFileName),
context: try container.decodeIfPresent(ReviewContext.self, forKey: .context) ?? .empty
)
}
}
@@ -0,0 +1,90 @@
import Foundation
/// What a review session is ABOUT, recorded once per session and printed on every
/// PDF page plus the PDF's document info, so an annotated page that comes back
/// weeks later still says which lane, build and commit it referred to, who took it
/// and when.
///
/// Every field is optional in practice (empty string = not recorded); nothing here
/// is invented when the user leaves it blank. `note` is free text.
public struct ReviewContext: Codable, Sendable, Equatable {
/// Hard cap per field: this text ends up on every PDF page, so an unbounded
/// paste must not be able to break the layout.
public static let maxFieldLength = 120
public var lane: String
public var deployedVersion: String
public var commit: String
public var reviewer: String
public var note: String
public init(
lane: String = "",
deployedVersion: String = "",
commit: String = "",
reviewer: String = "",
note: String = ""
) {
self.lane = Self.cleaned(lane)
self.deployedVersion = Self.cleaned(deployedVersion)
self.commit = Self.cleaned(commit)
self.reviewer = Self.cleaned(reviewer)
self.note = Self.cleaned(note)
}
public static let empty = ReviewContext()
/// The macOS account's own name, used to pre-fill `reviewer` on a fresh session.
/// `NSFullUserName()` is empty on a host with no full name set, in which case the
/// short login name identifies the same person.
public static func currentUser() -> String {
let full = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines)
if !full.isEmpty { return cleaned(full) }
return cleaned(NSUserName())
}
public var isEmpty: Bool {
lane.isEmpty && deployedVersion.isEmpty && commit.isEmpty && reviewer.isEmpty && note.isEmpty
}
/// "DEV03 · v1.4.2 · a1b2c3d · Ben Hippler" — empty parts are dropped, never
/// replaced with a placeholder.
public var summaryLine: String {
summaryParts.joined(separator: " · ")
}
/// The individual summary parts in display order, empty ones dropped.
public var summaryParts: [String] {
var parts: [String] = []
if !lane.isEmpty { parts.append(lane) }
if !deployedVersion.isEmpty { parts.append(deployedVersion) }
if !commit.isEmpty { parts.append(commit) }
if !reviewer.isEmpty { parts.append(reviewer) }
return parts
}
/// JSON kept tolerant on purpose: an older manifest has no context at all, and a
/// newer one may add fields. Any unknown key is ignored; every known field is
/// optional.
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(
lane: try container.decodeIfPresent(String.self, forKey: .lane) ?? "",
deployedVersion: try container.decodeIfPresent(String.self, forKey: .deployedVersion) ?? "",
commit: try container.decodeIfPresent(String.self, forKey: .commit) ?? "",
reviewer: try container.decodeIfPresent(String.self, forKey: .reviewer) ?? "",
note: try container.decodeIfPresent(String.self, forKey: .note) ?? ""
)
}
/// Trims, collapses line breaks (the value is drawn on one line) and caps length.
static func cleaned(_ raw: String) -> String {
let collapsed = raw
.replacingOccurrences(of: "\r\n", with: " ")
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: "\r", with: " ")
.trimmingCharacters(in: .whitespaces)
guard collapsed.count > maxFieldLength else { return collapsed }
return String(collapsed.prefix(maxFieldLength))
}
}
+10 -1
View File
@@ -10,13 +10,16 @@ public enum ShotdeckError: Error, LocalizedError, Sendable {
case pdfCompositionFailed(reason: String)
case airDropUnavailable
case noCommentedReturns
case oneDriveFolderUnavailable(path: String)
case noFrontWindow
case noBrowserWindow
public var errorDescription: String? {
switch self {
case .screenRecordingNotGranted:
return "Screen Recording is turned off. Grant it in System Settings to capture."
case .noRegionRemembered:
return "No capture region is set. Choose 'Re-select area' from the Shotdeck menu."
return "No capture region is set. Choose 'Re-select area' from the Redline menu."
case .displayNoLongerConnected:
return "The display used for capture is no longer connected."
case .captureFailed(let underlying):
@@ -31,6 +34,12 @@ public enum ShotdeckError: Error, LocalizedError, Sendable {
return "AirDrop is not available right now."
case .noCommentedReturns:
return "None of the returned PDFs have comments on them."
case .oneDriveFolderUnavailable(let path):
return "Your OneDrive folder is not available: \(path). Check that OneDrive is signed in, or choose another folder in Settings."
case .noFrontWindow:
return "There is no front window to capture. Click the window you want first, or choose Area."
case .noBrowserWindow:
return "No browser window is open. Open the page you want, or choose Window or Area."
}
}
}
+128 -8
View File
@@ -10,12 +10,17 @@ private let pdfLog = Logger(subsystem: "ai.flowmaster.shotdeck", category: "PDF"
public struct PDFComposer: Sendable {
public init() {}
/// `toolVersion` is the running Redline version (CFBundleShortVersionString) and
/// `composedAt` the build time; both are printed in the page footer and the PDF's
/// document info so a printed or returned page says which tools produced it.
@discardableResult
public func compose(
session: CaptureSession,
imageURL: (Capture) -> URL,
title: String,
to outputURL: URL
to outputURL: URL,
toolVersion: String = "",
composedAt: Date = Date()
) throws -> Int {
if session.isEmpty {
throw ShotdeckError.pdfCompositionFailed(reason: "session has no captures")
@@ -43,12 +48,18 @@ public struct PDFComposer: Sendable {
.deletingLastPathComponent()
.appendingPathComponent(".tmp-\(UUID().uuidString)-\(outputURL.lastPathComponent)")
let footerLines = Self.footerLines(
session: session, toolVersion: toolVersion, composedAt: composedAt)
do {
try Self.writePDF(
loaded: loaded,
pageCount: pageCount,
title: title,
sessionID: session.id,
footerLines: footerLines,
metadata: Self.documentInfo(
session: session, title: title, toolVersion: toolVersion, composedAt: composedAt),
to: tmpURL
)
@@ -70,8 +81,72 @@ public struct PDFComposer: Sendable {
}
}
/// `Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf` — see `PDFFileName`.
public static func fileName(for session: CaptureSession) -> String {
"Shotdeck-\(DubaiTime.fileStamp(session.createdAt)).pdf"
PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id)
}
/// Both footer lines for a session, untruncated. Line 1 identifies the document
/// (tool, build time, session); line 2 states what it reviewed (lane, deployed
/// build, commit, reviewer, note). Empty context fields are omitted rather than
/// printed as blanks.
public static func footerLines(
session: CaptureSession,
toolVersion: String,
composedAt: Date
) -> [String] {
let tool = toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)"
let first = "\(tool) · \(DubaiTime.stamp(composedAt)) · Session \(session.shortID)"
let context = session.context
var review: [String] = []
if !context.lane.isEmpty { review.append("Lane \(context.lane)") }
if !context.deployedVersion.isEmpty { review.append("Deployed \(context.deployedVersion)") }
if !context.commit.isEmpty { review.append("Commit \(context.commit)") }
if !context.reviewer.isEmpty { review.append("Reviewer \(context.reviewer)") }
if !context.note.isEmpty { review.append("Note \(context.note)") }
return review.isEmpty ? [first] : [first, review.joined(separator: " · ")]
}
/// The PDF document info a reader sees in Preview/Acrobat. The subject stays the
/// session UUID (it is the stable machine handle); everything a person needs to
/// identify the review is in Author/Keywords as well as the page footers.
public static func documentInfo(
session: CaptureSession,
title: String,
toolVersion: String,
composedAt: Date
) -> [String: Any] {
let context = session.context
// Commas separate keywords in the PDF format itself, so a value containing one
// would silently split into two keywords (and PDF readers return a list
// instead of a string). Strip them from every keyword value.
func keywordValue(_ raw: String) -> String {
raw.replacingOccurrences(of: ",", with: " ")
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
}
var keywords: [String] = ["Redline", "session=\(session.shortID)"]
if !context.lane.isEmpty { keywords.append("lane=\(keywordValue(context.lane))") }
if !context.deployedVersion.isEmpty {
keywords.append("deployed=\(keywordValue(context.deployedVersion))")
}
if !context.commit.isEmpty { keywords.append("commit=\(keywordValue(context.commit))") }
if !context.reviewer.isEmpty { keywords.append("reviewer=\(keywordValue(context.reviewer))") }
if !context.note.isEmpty { keywords.append("note=\(keywordValue(context.note))") }
keywords.append("built=\(DubaiTime.keywordStamp(composedAt))")
if !toolVersion.isEmpty { keywords.append("tool=\(toolVersion)") }
var info: [String: Any] = [
kCGPDFContextCreator as String: toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)",
kCGPDFContextTitle as String: title,
kCGPDFContextSubject as String: session.id.uuidString.lowercased(),
kCGPDFContextKeywords as String: keywords.joined(separator: "; "),
]
if !context.reviewer.isEmpty {
info[kCGPDFContextAuthor as String] = context.reviewer
}
return info
}
private static func writePDF(
@@ -79,17 +154,15 @@ public struct PDFComposer: Sendable {
pageCount: Int,
title: String,
sessionID: UUID,
footerLines: [String],
metadata: [String: Any],
to tmpURL: URL
) throws {
guard let consumer = CGDataConsumer(url: tmpURL as CFURL) else {
throw ShotdeckError.pdfCompositionFailed(reason: "cannot open output location")
}
let auxiliaryInfo: [String: Any] = [
kCGPDFContextCreator as String: "Shotdeck",
kCGPDFContextTitle as String: title,
kCGPDFContextSubject as String: sessionID.uuidString.lowercased(),
]
let auxiliaryInfo = metadata
guard let context = CGContext(
consumer: consumer,
@@ -105,7 +178,9 @@ public struct PDFComposer: Sendable {
for pageIndex in 1...pageCount {
let (capture, cgImage) = loaded[pageIndex - 1]
let layout = PageLayout(capture: capture, pageIndex: pageIndex, pageCount: pageCount)
let layout = PageLayout(
capture: capture, pageIndex: pageIndex, pageCount: pageCount,
footerLines: footerLines)
context.beginPDFPage(Self.pageInfo(mediaBox: layout.pageRect))
@@ -149,6 +224,17 @@ public struct PDFComposer: Sendable {
strokeTickBox(layout.passTickBox, in: context, color: black)
strokeTickBox(layout.failTickBox, in: context, color: black)
for (line, origin) in zip(layout.footerLines, layout.footerOrigins) {
drawTruncatedText(
line,
font: layout.footerFont,
color: timestampColor,
at: origin,
maxWidth: layout.footerRect.width,
in: context
)
}
context.endPDFPage()
}
@@ -185,6 +271,40 @@ public struct PDFComposer: Sendable {
CTLineDraw(line, context)
}
/// Draws one footer line, truncated with an ellipsis when it is wider than the
/// page content width — the reference block must never run into the page edge.
private static func drawTruncatedText(
_ string: String,
font: NSFont,
color: CGColor,
at origin: CGPoint,
maxWidth: CGFloat,
in context: CGContext
) {
let attributes: [CFString: Any] = [
kCTFontAttributeName: font,
kCTForegroundColorAttributeName: color,
]
guard let attributed = CFAttributedStringCreate(
nil, string as CFString, attributes as CFDictionary)
else { return }
var line = CTLineCreateWithAttributedString(attributed)
if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > maxWidth,
let ellipsisAttributed = CFAttributedStringCreate(
nil, "…" as CFString, attributes as CFDictionary)
{
let ellipsis = CTLineCreateWithAttributedString(ellipsisAttributed)
if let truncated = CTLineCreateTruncatedLine(
line, Double(maxWidth), .end, ellipsis)
{
line = truncated
}
}
context.textMatrix = .identity
context.textPosition = origin
CTLineDraw(line, context)
}
private static func strokeTickBox(_ box: CGRect, in context: CGContext, color: CGColor) {
let path = CGPath(
roundedRect: box,
@@ -0,0 +1,54 @@
import Foundation
/// The PDF file-name scheme:
///
/// Redline-<yyyyMMdd-HHmm>-<LANE>-<SHORTID>.pdf
/// Redline-<yyyyMMdd-HHmm>-<SHORTID>.pdf (no lane recorded)
///
/// * `yyyyMMdd-HHmm` is Dubai wall-clock time (the time the PDF was built) — the
/// file sorts chronologically as plain text on every filesystem.
/// * `LANE` is the upper-cased lane/environment, reduced to A–Z, 0–9 and single
/// dashes ("OMS test lane" → "OMS-TEST-LANE") so the name is safe everywhere.
/// * `SHORTID` is the session's 8-character id, which keeps two lanes in the same
/// minute — and a re-send of the same session — distinguishable and unique.
public enum PDFFileName {
/// Lane token length cap so the whole name stays comfortably short.
public static let laneMaxLength = 24
public static func laneSlug(_ lane: String) -> String {
var slug = ""
var pendingDash = false
for character in lane.uppercased() {
if character.isASCII, character.isLetter || character.isNumber {
if pendingDash, !slug.isEmpty { slug.append("-") }
slug.append(character)
pendingDash = false
} else {
pendingDash = true
}
}
let capped = String(slug.prefix(laneMaxLength))
return capped.hasSuffix("-") ? String(capped.dropLast()) : capped
}
public static func make(builtAt: Date, lane: String, sessionID: UUID) -> String {
let shortID = String(
sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)
).uppercased()
let slug = laneSlug(lane)
var parts = ["Redline", DubaiTime.fileMinuteStamp(builtAt)]
if !slug.isEmpty { parts.append(slug) }
parts.append(shortID)
return parts.joined(separator: "-") + ".pdf"
}
/// The session folder's own readable label, e.g. "DEV03-4F2A9C1D" — used in the
/// UI only; the on-disk folder name stays the session UUID.
public static func sessionLabel(lane: String, sessionID: UUID) -> String {
let shortID = String(
sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)
).uppercased()
let slug = laneSlug(lane)
return slug.isEmpty ? shortID : "\(slug)-\(shortID)"
}
}
+46 -3
View File
@@ -15,6 +15,12 @@ public struct PageLayout: Sendable, Equatable {
public let timestampText: String
public let timestampOrigin: CGPoint
/// Reference block under the image (up to two lines): who, when, which lane,
/// which deployed build and commit. Empty when the caller passes no lines.
public let footerRect: CGRect
public let footerLines: [String]
public let footerOrigins: [CGPoint]
public let passLabelOrigin: CGPoint
public let failLabelOrigin: CGPoint
public let passTickBox: CGRect
@@ -25,10 +31,13 @@ public struct PageLayout: Sendable, Equatable {
public var pageNumberFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .semibold) }
public var timestampFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .regular) }
public var tickLabelFont: NSFont { NSFont.systemFont(ofSize: 8, weight: .semibold) }
public var footerFont: NSFont { NSFont.systemFont(ofSize: 7.5, weight: .regular) }
private static let marginAll: CGFloat = 18
private static let headerHeight: CGFloat = 26
private static let headerImageGap: CGFloat = 10
private static let footerLineHeight: CGFloat = 9.5
private static let footerImageGap: CGFloat = 7
private static let tickBoxSize: CGFloat = 13
private static let tickGroupGap: CGFloat = 8
private static let portraitPage = CGSize(width: 595, height: 842)
@@ -36,10 +45,13 @@ public struct PageLayout: Sendable, Equatable {
/// `pageIndex` and `pageCount` are 1-based / total, over ACTUALLY-WRITTEN pages
/// (see SPEC decision D-D), not `capture.sequence` / `session.captures.count`.
public init(capture: Capture, pageIndex: Int, pageCount: Int) {
/// `footerLines` is the pre-truncated reference block; an empty array keeps the
/// image area exactly as it was before the footer existed.
public init(capture: Capture, pageIndex: Int, pageCount: Int, footerLines: [String] = []) {
let pageNumberFont = NSFont.systemFont(ofSize: 9, weight: .semibold)
let timestampFont = NSFont.systemFont(ofSize: 9, weight: .regular)
let tickLabelFont = NSFont.systemFont(ofSize: 8, weight: .semibold)
let footerLabelFont = NSFont.systemFont(ofSize: 7.5, weight: .regular)
isLandscape = capture.isLandscape
pageRect = CGRect(origin: .zero, size: isLandscape ? Self.landscapePage : Self.portraitPage)
@@ -59,11 +71,23 @@ public struct PageLayout: Sendable, Equatable {
height: Self.headerHeight
)
imageBoxRect = CGRect(
self.footerLines = footerLines
let footerHeight = footerLines.isEmpty
? 0
: CGFloat(footerLines.count) * Self.footerLineHeight
footerRect = CGRect(
x: contentMinX,
y: contentMinY,
width: contentWidth,
height: headerRect.minY - Self.headerImageGap - contentMinY
height: footerHeight
)
let imageBoxMinY = contentMinY + (footerLines.isEmpty ? 0 : footerHeight + Self.footerImageGap)
imageBoxRect = CGRect(
x: contentMinX,
y: imageBoxMinY,
width: contentWidth,
height: headerRect.minY - Self.headerImageGap - imageBoxMinY
)
let pointSize = CGSize(
@@ -91,6 +115,22 @@ public struct PageLayout: Sendable, Equatable {
let descent = CTFontGetDescent(metricsFont)
let baselineY = headerRect.minY + (headerRect.height - (ascent + descent)) / 2 + descent
// Footer baselines, top line first, using the footer font's own descent.
let footerMetrics = footerLabelFont as CTFont
let footerAscent = CTFontGetAscent(footerMetrics)
let footerDescent = CTFontGetDescent(footerMetrics)
let footerLeading = Self.footerLineHeight
var origins: [CGPoint] = []
origins.reserveCapacity(footerLines.count)
for index in footerLines.indices {
let lineBottom = footerRect.maxY - CGFloat(index + 1) * footerLeading
origins.append(CGPoint(
x: footerRect.minX,
y: lineBottom + max(0, (footerLeading - (footerAscent + footerDescent)) / 2) + footerDescent
))
}
footerOrigins = origins
pageNumberText = "\(pageIndex) / \(pageCount)"
pageNumberOrigin = CGPoint(x: headerRect.minX, y: baselineY)
@@ -135,6 +175,9 @@ public struct PageLayout: Sendable, Equatable {
&& lhs.pageNumberOrigin == rhs.pageNumberOrigin
&& lhs.timestampText == rhs.timestampText
&& lhs.timestampOrigin == rhs.timestampOrigin
&& lhs.footerRect == rhs.footerRect
&& lhs.footerLines == rhs.footerLines
&& lhs.footerOrigins == rhs.footerOrigins
&& lhs.passLabelOrigin == rhs.passLabelOrigin
&& lhs.failLabelOrigin == rhs.failLabelOrigin
&& lhs.passTickBox == rhs.passTickBox
@@ -93,16 +93,19 @@ public enum AnnotationInspector {
)
}
/// True when this PDF was produced by Shotdeck. Creator attribute is authoritative;
/// True when this PDF was produced by this app. Creator attribute is authoritative;
/// the filename fallback applies ONLY when the creator attribute is absent.
/// Accepts both the current product name ("Redline") and the legacy name ("Shotdeck")
/// so PDFs already on the iPad or in Downloads are still detected.
public static func isShotdeckDocument(_ document: PDFDocument) -> Bool {
if let creator = document.documentAttributes?[PDFDocumentAttribute.creatorAttribute] as? String {
return creator == "Shotdeck" // present creator is authoritative, full stop
// Present creator is authoritative, full stop.
return creator == "Redline" || creator == "Shotdeck"
}
// Creator ABSENT (some apps rewrite metadata on save) -> filename fallback only here.
guard let name = document.documentURL?.lastPathComponent else { return false }
// .lastPathComponent on a file URL is already percent-decoded; do not use .absoluteString.
return name.wholeMatch(of: /^Shotdeck-\d{8}-\d{6}( \d+)?\.pdf$/) != nil
return name.wholeMatch(of: /^(Redline|Shotdeck)-\d{8}-\d{6}( \d+)?\.pdf$/) != nil
// Case-sensitive by construction (Swift Regex literals are case-sensitive by default).
// The optional "( \d+)?" is macOS's duplicate-name suffix AirDrop adds when a file of
// the same name already exists in the watch folder — the normal case for a return.
@@ -10,6 +10,21 @@ public actor ReturnWatcher {
private var bridge: FSEventBridge?
private var pendingScanTask: Task<Void, Never>?
private let eventQueue = DispatchQueue(label: "ai.flowmaster.shotdeck.returns.fsevents")
/// When false, a document with zero human marks is neither recorded into the ledger
/// nor included in scanNow's/onChange's results — needed for OneDrive mode, where the
/// outbox and watch folder are the same folder and a freshly written, unmarked PDF
/// must not be treated as a return. Defaults to true (today's AirDrop behaviour).
/// A document that IS commented is always recorded, regardless of this flag.
public var recordUncommented: Bool = true
/// The folder this watcher is CURRENTLY seeded to scan/watch — whatever `init`
/// last set it to, or `updateWatchFolder` since. Exposed so tests can observe the
/// watcher's seeded folder directly (e.g. right after construction, before
/// `start()`/`updateWatchFolder()` ever run) rather than only inferring it
/// indirectly through `scanNow()`'s behavior.
public var currentWatchFolder: URL {
watchFolder
}
/// Watch folder is `paths.watchFolder`, which production constructs from
/// `FolderSettings.resolve().watch`. This type never calls FolderSettings;
@@ -29,6 +44,12 @@ public actor ReturnWatcher {
onChange(found)
}
/// Sets `recordUncommented`. A `func` (not a plain property set) only because
/// callers outside this actor must `await` it like any other actor mutation.
public func setRecordUncommented(_ value: Bool) {
recordUncommented = value
}
/// Idempotent. Stops and releases the FSEventStream if one is running; safe to call
/// when never started or already stopped. Cancels any pending debounced scan.
public func stop() {
@@ -60,7 +81,7 @@ public actor ReturnWatcher {
}
/// Scans the watch folder once, immediately, without waiting for an event. Every
/// recognized, stable, openable Shotdeck PDF present is (re-)inspected and (re-)recorded
/// recognized, stable, openable Redline/Shotdeck PDF present is (re-)inspected and (re-)recorded
/// into the ledger; returns exactly the documents processed in this call.
@discardableResult
public func scanNow() async throws -> [ReturnedDocument] {
@@ -77,6 +98,7 @@ public actor ReturnWatcher {
guard let document = PDFDocument(url: url),
AnnotationInspector.isShotdeckDocument(document) else { continue }
guard let inspected = try? AnnotationInspector.inspect(fileURL: url) else { continue }
if !recordUncommented, !inspected.isCommented { continue }
try await ledger.record(inspected)
results.append(inspected)
}
+209 -33
View File
@@ -6,15 +6,24 @@ import Darwin
public actor SpoolStore {
private let paths: AppSupportPaths
private var openSession: CaptureSession
/// The user's age limit for kept sessions. `.never` (the default) means every
/// session is kept: nothing is deleted until an age limit is chosen in Settings.
private var retention: SessionRetention
public init(paths: AppSupportPaths) throws {
public init(paths: AppSupportPaths, retention: SessionRetention = .never) throws {
self.paths = paths
self.retention = retention
let fm = FileManager.default
try Self.supersedeSpoolArchiveOverlaps(paths: paths, fileManager: fm)
try Self.finishInterruptedArchives(paths: paths, fileManager: fm)
let remainingIDs = try Self.listUUIDDirectories(in: paths.spool, fileManager: fm)
if remainingIDs.isEmpty {
self.openSession = try Self.createFreshSession(paths: paths)
// A brand-new store: the reviewer is this Mac's user, so a session taken
// now records who took it without the user typing anything. Lane, build
// and commit stay empty until the user states them.
self.openSession = try Self.createFreshSession(
paths: paths,
context: ReviewContext(reviewer: ReviewContext.currentUser()))
} else {
var candidates: [CaptureSession] = []
for id in remainingIDs {
@@ -27,10 +36,54 @@ public actor SpoolStore {
}
}
/// Applies a new age limit to future archive/launch prunes. Does not delete
/// anything itself — a caller that just changed the setting calls
/// `pruneExpiredSessions()` when the user asked for a cleanup.
public func setRetention(_ value: SessionRetention) {
retention = value
}
/// The age limit this store is currently enforcing.
public func configuredRetention() -> SessionRetention {
retention
}
/// Records the review context (lane / deployed build / commit / reviewer / note)
/// on the open session and persists it in the manifest before returning. Fails
/// loudly if the manifest cannot be written — the in-memory session is only
/// updated after the durable write succeeds.
public func setContext(_ context: ReviewContext) throws -> CaptureSession {
let open = try ensureOpenSession()
let updated = open.withContext(context)
try AtomicFile.writeJSON(
updated, to: paths.sessionDirectory(open.id).appendingPathComponent("session.json"))
openSession = updated
return updated
}
/// The session currently accepting captures. Cheap accessor — all reconciliation already
/// happened once, inside init.
/// happened once, inside init. A truth guard: if the stored session is no longer really
/// open on disk (its directory was archived away and the replacement session could not
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
/// It never returns an already-archived session as the open one.
public func currentSession() throws -> CaptureSession {
openSession
try ensureOpenSession()
}
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
/// loudly when no new session can be created either — never substitutes a lie.
private func ensureOpenSession() throws -> CaptureSession {
let dir = paths.sessionDirectory(openSession.id)
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
return openSession
}
let staleID = openSession.id.uuidString
Log.spool.error(
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
let fresh = try Self.createFreshSession(paths: paths, context: openSession.context)
openSession = fresh
return fresh
}
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
@@ -40,32 +93,37 @@ public actor SpoolStore {
pngData: Data, pixelWidth: Int, pixelHeight: Int,
scale: CGFloat, capturedAt: Date
) throws -> Capture {
let open = try ensureOpenSession()
let captureID = UUID()
let sequence = openSession.nextSequence
let sequence = open.nextSequence
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let fileURL = sessionDir.appendingPathComponent(fileName)
try AtomicFile.write(pngData, to: fileURL)
let capture = Capture(
id: captureID, sequence: sequence, fileName: fileName,
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
scale: scale, capturedAt: capturedAt)
let updated = openSession.appending(capture)
let updated = open.appending(capture)
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
openSession = updated
return capture
}
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
/// its manifest entry. NEVER unlinks/deletes a user PNG. Throws (no filesystem change) if
/// `captureID` is not present in the open session.
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
/// filesystem change) if `captureID` is not present in the open session.
/// (The one place that removes files is the age limit the user chose in Settings:
/// when a session is older than that limit, its WHOLE folder — including
/// `removed/` — is pruned. Nothing is pruned while the limit is "Never".)
public func remove(captureID: UUID) throws -> CaptureSession {
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
let open = try ensureOpenSession()
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "capture \(captureID) is not in the open session")
}
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
do {
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
@@ -87,37 +145,124 @@ public actor SpoolStore {
}
/// Closes the open session (must be non-empty), moves its directory under archive/, records
/// pdfFileName, and starts a fresh empty open session. Returns the archived one.
/// pdfFileName, starts a fresh empty open session, and applies session retention.
/// Returns the archived one.
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
guard !openSession.isEmpty else {
let open = try ensureOpenSession()
guard !open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "cannot archive an empty session")
}
let archived = openSession.markArchived(pdfFileName: pdfFileName)
let sessionDir = paths.sessionDirectory(openSession.id)
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths, context: open.context)
applyRetention()
return archived
}
/// Closes the open session — sent or not — and keeps its captures as a past
/// session under archive/, then starts a fresh empty open session. Unlike
/// `archiveCurrent(pdfFileName:)` this never requires a PDF: the archived session
/// keeps whatever pdfFileName it already has (nil when it was never sent, which
/// the Past submissions list shows as "Not sent"). An empty open session is
/// simply replaced — there is nothing to keep. Returns the archived session, or
/// nil when the open session was empty.
///
/// The new session inherits the closed session's review context: one review run
/// spans several sessions in the same lane and build, so retyping it each time
/// would only add errors.
public func closeCurrentSession() throws -> CaptureSession? {
let open = try ensureOpenSession()
guard !open.isEmpty else {
openSession = try Self.createFreshSession(paths: paths, context: open.context)
return nil
}
let archived = try moveOpenSessionToArchive(
open.markArchived(pdfFileName: open.pdfFileName))
openSession = try Self.createFreshSession(paths: paths, context: open.context)
applyRetention()
return archived
}
/// Removes archived sessions created before the current age limit's cutoff and
/// returns their ids. With `.never` this removes nothing and returns `[]`, so
/// "keep everything" needs no separate code path. Only UUID session folders
/// directly under archive/ are ever touched — never spool/, never a PDF.
public func pruneExpiredSessions(now: Date = Date()) throws -> [UUID] {
guard let cutoff = retention.cutoff(now: now) else { return [] }
return try removeArchivedSessions(createdBefore: cutoff)
}
/// The ids `pruneExpiredSessions()` would remove right now — what Settings shows
/// before the user commits to a cleanup. Empty under `.never`.
public func expiredSessionIDs(now: Date = Date()) throws -> [UUID] {
guard let cutoff = retention.cutoff(now: now) else { return [] }
return try archivedSessions().filter { $0.createdAt < cutoff }.map(\.id)
}
/// Deletes the archived session folders created before `cutoff` and returns their
/// ids. Only archive/ is scanned, so an open session can never match.
private func removeArchivedSessions(createdBefore cutoff: Date) throws -> [UUID] {
let expired = try archivedSessions().filter { $0.createdAt < cutoff }
guard !expired.isEmpty else { return [] }
var removed: [UUID] = []
for session in expired {
let dir = paths.archiveDirectory(session.id)
do {
try FileManager.default.removeItem(at: dir)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: dir.path,
underlying: "could not remove an expired session: \(error.localizedDescription)")
}
removed.append(session.id)
}
try AtomicFile.fsyncDirectory(at: paths.archive)
Log.spool.warning(
"Session retention (\(self.retention.displayName, privacy: .public)): removed \(removed.count, privacy: .public) archived session(s) older than \(DubaiTime.stamp(cutoff), privacy: .public).")
return removed
}
/// The retention policy every archive path funnels through, so it can never be
/// forgotten. A retention failure is logged loudly (with the exact path) and
/// never thrown — the archive it follows already succeeded, and converting a
/// completed send into a reported failure would be a lie (the safe direction of a
/// failed prune is keeping too much, never losing data). The visible symptom of a
/// failed prune is simply an old session still in the Past sessions list.
private func applyRetention() {
do {
_ = try pruneExpiredSessions()
} catch {
Log.spool.error(
"Session retention failed — expired sessions were kept: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
}
}
/// Writes the archived manifest, then renames the whole session directory from
/// spool/ into archive/ in one atomic operation.
private func moveOpenSessionToArchive(_ archived: CaptureSession) throws -> CaptureSession {
let sessionDir = paths.sessionDirectory(archived.id)
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
let archiveDir = paths.archiveDirectory(openSession.id)
let archiveDir = paths.archiveDirectory(archived.id)
guard rename(sessionDir.path, archiveDir.path) == 0 else {
throw ShotdeckError.spoolWriteFailed(
path: sessionDir.path,
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
}
try AtomicFile.fsyncDirectory(at: paths.archive)
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
return archived
}
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
/// with no filesystem change, if the open session has captures.
public func startNewSession() throws -> CaptureSession {
guard openSession.isEmpty else {
let open = try ensureOpenSession()
guard open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session")
path: paths.sessionDirectory(open.id).path,
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
}
let fresh = try Self.createFreshSession(paths: paths)
let fresh = try Self.createFreshSession(paths: paths, context: open.context)
openSession = fresh
return fresh
}
@@ -129,19 +274,44 @@ public actor SpoolStore {
return dir.appendingPathComponent(capture.fileName)
}
/// Archived sessions, newest createdAt first. Lazily reconciles each archive/ directory
/// Archived sessions, newest first. Lazily reconciles each archive/ directory
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
/// ever losing a PNG.
///
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
/// pinned in AtomicFileTests), then the session folder's creation date and content
/// modification date to break ties at real resolution (two sessions closed in the
/// same second would otherwise order, and therefore prune, arbitrarily by UUID —
/// and on a volume that reports no creation date the modification date still keeps
/// retention on real order), then the id as the final deterministic tie-break.
/// The folder dates are tie-break refinements only — the manifest `createdAt` stays
/// the authoritative timestamp; if a volume reports neither date the tie-break
/// degrades to the id.
public func archivedSessions() throws -> [CaptureSession] {
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
var sessions: [CaptureSession] = []
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
for id in ids {
sessions.append(
try Self.reconcileSessionDirectory(
at: paths.archiveDirectory(id), id: id, assumedStateIfRebuilt: .archived, fileManager: .default))
let dir = paths.archiveDirectory(id)
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
// session.json and bump the folder's modification date to "now", which
// would let a healed older session outrank a genuinely newer same-second
// peer in the tie-break below.
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let session = try Self.reconcileSessionDirectory(
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
// The manifest `createdAt` is the authoritative timestamp; the folder dates
// only refine ties between same-second sessions.
let folderCreatedAt = values?.creationDate ?? session.createdAt
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt))
}
return sessions.sorted { ($0.createdAt, $0.id.uuidString) > ($1.createdAt, $1.id.uuidString) }
return keyed
.sorted { lhs, rhs in
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
}
.map(\.session)
}
// MARK: - Reconciliation (static so they can run inside init)
@@ -257,7 +427,8 @@ public actor SpoolStore {
createdAt: session.createdAt,
state: session.state,
captures: finalCaptures,
pdfFileName: session.pdfFileName)
pdfFileName: session.pdfFileName,
context: session.context)
try AtomicFile.writeJSON(updated, to: manifestURL)
Log.spool.warning("Reconciled session \(id.uuidString, privacy: .public): dropped \(missingCount) missing PNG(s), recovered \(recoveredOrphans.count) orphan(s).")
return updated
@@ -342,7 +513,10 @@ public actor SpoolStore {
}
}
private static func createFreshSession(paths: AppSupportPaths) throws -> CaptureSession {
private static func createFreshSession(
paths: AppSupportPaths,
context: ReviewContext
) throws -> CaptureSession {
let id = UUID()
let createdAt = Date()
let dir = paths.sessionDirectory(id)
@@ -351,7 +525,9 @@ public actor SpoolStore {
} catch {
throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription)
}
let session = CaptureSession(id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil,
context: context)
try AtomicFile.writeJSON(session, to: dir.appendingPathComponent("session.json"))
return session
}
@@ -11,12 +11,6 @@ public struct AppSupportPaths: Sendable {
/// Production paths.
public static func standard() throws -> AppSupportPaths {
let fileManager = FileManager.default
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let desktop = try fileManager.url(
for: .desktopDirectory,
in: .userDomainMask,
@@ -29,10 +23,25 @@ public struct AppSupportPaths: Sendable {
appropriateFor: nil,
create: true
)
let root = appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
let root = try standardRoot(fileManager: fileManager)
return try AppSupportPaths(root: root, outbox: desktop, watchFolder: downloads)
}
/// The standard `~/Library/Application Support/Shotdeck` root. Shared by
/// `standard()`, `FolderSettings.resolvedAppSupportPaths()`, and
/// `TransportSettings.resolvedAppSupportPaths()` so all three agree on where the
/// root lives — the folder-resolution logic (AirDrop-only vs transport-aware)
/// differs between those, the root computation never should.
public static func standardRoot(fileManager: FileManager = .default) throws -> URL {
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
return appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
}
/// Test paths rooted anywhere. Every directory is created if missing.
public init(root: URL, outbox: URL, watchFolder: URL) throws {
self.root = root
@@ -3,6 +3,11 @@ import Foundation
public enum DubaiTime {
private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'")
private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss")
private static let fileMinuteStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmm")
private static let checkTimeFormatter = LockedDateFormatter(dateFormat: "HH:mm 'Dubai'")
private static let shortStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm")
private static let dayStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy")
private static let keywordStampFormatter = LockedDateFormatter(dateFormat: "yyyy-MM-dd HH:mm 'Dubai'")
public static func stamp(_ date: Date) -> String {
stampFormatter.string(from: date)
@@ -11,6 +16,32 @@ public enum DubaiTime {
public static func fileStamp(_ date: Date) -> String {
fileStampFormatter.string(from: date)
}
/// `yyyyMMdd-HHmm` — used in PDF file names where minutes are the useful detail.
public static func fileMinuteStamp(_ date: Date) -> String {
fileMinuteStampFormatter.string(from: date)
}
/// "31 Oct 2026, 10:31" — compact session-list timestamp (the timezone is stated
/// once in the list header, not on every row).
public static func shortStamp(_ date: Date) -> String {
shortStampFormatter.string(from: date)
}
/// "31 Oct 2026" — for day-granular expiry notices.
public static func dayStamp(_ date: Date) -> String {
dayStampFormatter.string(from: date)
}
/// "2026-10-31 11:00 Dubai" — for PDF keywords, where a comma would be read as a
/// keyword separator by the PDF format itself.
public static func keywordStamp(_ date: Date) -> String {
keywordStampFormatter.string(from: date)
}
public static func checkTime(_ date: Date) -> String {
checkTimeFormatter.string(from: date)
}
}
/// DateFormatter is not Sendable. This holder is the only shared mutable state
@@ -70,15 +70,7 @@ public enum FolderSettings {
defaults: UserDefaults = .standard,
fileManager: FileManager = .default
) throws -> AppSupportPaths {
let resolvedRoot: URL
if let root {
resolvedRoot = root
} else {
let appSupportParent = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
resolvedRoot = appSupportParent.appendingPathComponent("Shotdeck", isDirectory: true)
}
let resolvedRoot = try root ?? AppSupportPaths.standardRoot(fileManager: fileManager)
let folders = resolve(defaults: defaults, fileManager: fileManager)
return try AppSupportPaths(root: resolvedRoot, outbox: folders.outbox, watchFolder: folders.watch)
}
@@ -0,0 +1,69 @@
import Foundation
/// How long Redline keeps a past session's captured screenshots.
///
/// The default is `.never`: every session is saved and nothing is deleted unless the
/// user picks an age limit in Settings. Session folders are the only thing an age
/// policy ever removes — a PDF that was already sent stays in the folder it went to.
public enum SessionRetention: Sendable, Equatable, Hashable {
case never
case days(Int)
/// The one list Settings offers, in display order. `nil` day counts never expire.
public static let presets: [SessionRetention] = [
.never, .days(7), .days(14), .days(30), .days(90), .days(180), .days(365),
]
public var dayCount: Int? {
switch self {
case .never: return nil
case .days(let count): return count
}
}
/// "Never (default)", "7 days", "30 days", "1 year".
public var displayName: String {
switch self {
case .never: return "Never (default)"
case .days(365): return "1 year"
case .days(let count): return "\(count) days"
}
}
/// Caption for the Settings row and the panel footer: what actually happens.
public var policyDescription: String {
switch self {
case .never: return "All sessions kept."
case .days(365): return "Sessions older than 1 year are deleted."
case .days(let count): return "Sessions older than \(count) days are deleted."
}
}
/// Sessions created before this instant are expired; nil means nothing expires.
public func cutoff(now: Date = Date()) -> Date? {
guard let dayCount else { return nil }
return Calendar(identifier: .gregorian).date(byAdding: .day, value: -dayCount, to: now)
}
}
/// Persistence for the age limit, backed by UserDefaults.
///
/// Stored as a day count; 0 (or no stored value at all) means `never`. A stored value
/// is only ever written by `save`, so an absent key is the honest "user never chose"
/// state, not a hidden default.
public enum RetentionSettings {
public static let defaultsKey = "ai.flowmaster.shotdeck.sessionRetentionDays"
public static func load(defaults: UserDefaults = .standard) -> SessionRetention {
guard let stored = defaults.object(forKey: defaultsKey) as? Int else { return .never }
return stored > 0 ? .days(stored) : .never
}
public static func save(_ value: SessionRetention, defaults: UserDefaults = .standard) {
guard let dayCount = value.dayCount else {
defaults.removeObject(forKey: defaultsKey)
return
}
defaults.set(dayCount, forKey: defaultsKey)
}
}
@@ -0,0 +1,221 @@
import Foundation
/// The two ways a composed PDF can reach the iPad and come back marked up.
public enum SendTransport: String, Codable, Sendable, CaseIterable {
case airDrop
case oneDrive
public var displayName: String {
switch self {
case .airDrop: return "AirDrop"
case .oneDrive: return "OneDrive folder"
}
}
}
/// User-configurable transport choice plus the OneDrive folder override, backed by
/// UserDefaults the same way `FolderSettings` is. See `FolderSettings` for why a plain
/// path (not a security-scoped bookmark) is correct for this unsandboxed app.
public enum TransportSettings {
public static let transportDefaultsKey = "ai.flowmaster.shotdeck.transport"
public static let oneDriveFolderDefaultsKey = "ai.flowmaster.shotdeck.oneDriveFolder"
/// Defaults to `.airDrop` when unset or when the stored value cannot be parsed.
public static func transport(defaults: UserDefaults = .standard) -> SendTransport {
guard let raw = defaults.string(forKey: transportDefaultsKey),
let value = SendTransport(rawValue: raw)
else { return .airDrop }
return value
}
public static func setTransport(_ value: SendTransport, defaults: UserDefaults = .standard) {
defaults.set(value.rawValue, forKey: transportDefaultsKey)
}
/// Raw stored path (or nil if never set / cleared). Does NOT validate that the
/// directory still exists.
public static func storedOneDriveFolderPath(defaults: UserDefaults = .standard) -> String? {
defaults.string(forKey: oneDriveFolderDefaultsKey)
}
public static func setOneDriveFolder(_ url: URL, defaults: UserDefaults = .standard) {
defaults.set(url.path, forKey: oneDriveFolderDefaultsKey)
}
public static func resetOneDriveFolder(defaults: UserDefaults = .standard) {
defaults.removeObject(forKey: oneDriveFolderDefaultsKey)
}
/// The outbox/watch folders Redline should actually use right now, for the current
/// transport. AirDrop mode delegates to `FolderSettings.resolve()` unchanged.
/// OneDrive mode uses the SAME folder for both outbox and watch — see
/// `OneDriveLocator.resolveOneDriveFolder`. When no OneDrive folder can be resolved
/// at all (no sync root, no override), this falls back to the AirDrop folders so the
/// app always has somewhere to write; `send(anchor:)` performs its own live
/// existence check before ever composing into a OneDrive send, so that fallback is
/// never mistaken for a valid OneDrive destination.
public static func effectiveFolders(
defaults: UserDefaults = .standard,
fileManager: FileManager = .default
) -> (outbox: URL, watch: URL, transport: SendTransport) {
let transport = transport(defaults: defaults)
switch transport {
case .airDrop:
let folders = FolderSettings.resolve(defaults: defaults, fileManager: fileManager)
return (folders.outbox, folders.watch, transport)
case .oneDrive:
if let folder = OneDriveLocator.resolveOneDriveFolder(
defaults: defaults,
home: fileManager.homeDirectoryForCurrentUser,
fileManager: fileManager
) {
return (folder, folder, transport)
}
let folders = FolderSettings.resolve(defaults: defaults, fileManager: fileManager)
return (folders.outbox, folders.watch, transport)
}
}
/// Builds an `AppSupportPaths` using `root` (defaults to the standard
/// `~/Library/Application Support/Shotdeck` when nil) plus whatever
/// `effectiveFolders()` returns for outbox/watch. Unlike
/// `FolderSettings.resolvedAppSupportPaths()` (AirDrop-only), this is
/// transport-aware — it is the ONLY function launch code should use to build its
/// paths, so the watcher it feeds is never seeded with a stale AirDrop folder while
/// OneDrive is the persisted transport. `root` is exposed purely so tests (and the
/// ONEDRIVE-SELFTEST relaunch simulation) can point it at a temporary directory
/// instead of the user's real Application Support folder.
public static func resolvedAppSupportPaths(
root: URL? = nil,
defaults: UserDefaults = .standard,
fileManager: FileManager = .default
) throws -> AppSupportPaths {
let resolvedRoot = try root ?? AppSupportPaths.standardRoot(fileManager: fileManager)
let folders = effectiveFolders(defaults: defaults, fileManager: fileManager)
return try AppSupportPaths(root: resolvedRoot, outbox: folders.outbox, watchFolder: folders.watch)
}
}
/// Pure path logic for locating a OneDrive sync root under
/// `~/Library/CloudStorage` and the Redline folder inside it. No side effects — never
/// creates a directory. Fully unit-testable with a fake home tree.
public enum OneDriveLocator {
/// Every directory directly under `<home>/Library/CloudStorage` whose name starts
/// with "OneDrive-", sorted so a name containing "MMD" (case-insensitive) sorts
/// first, then alphabetically. Empty when CloudStorage does not exist.
public static func syncRoots(
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> [URL] {
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: cloudStorage.path, isDirectory: &isDirectory),
isDirectory.boolValue
else { return [] }
let items = (try? fileManager.contentsOfDirectory(
at: cloudStorage,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
)) ?? []
let roots = items.filter { url in
guard url.lastPathComponent.hasPrefix("OneDrive-") else { return false }
var itemIsDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: url.path, isDirectory: &itemIsDirectory)
return exists && itemIsDirectory.boolValue
}
return roots.sorted { a, b in
let aName = a.lastPathComponent
let bName = b.lastPathComponent
let aIsMMD = aName.localizedCaseInsensitiveContains("MMD")
let bIsMMD = bName.localizedCaseInsensitiveContains("MMD")
if aIsMMD != bIsMMD { return aIsMMD }
return aName.localizedStandardCompare(bName) == .orderedAscending
}
}
/// First sync root's "Redline" subfolder, or nil when there is no sync root at all.
public static func defaultRedlineFolder(
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> URL? {
guard let first = syncRoots(home: home, fileManager: fileManager).first else { return nil }
return first.appendingPathComponent("Redline", isDirectory: true)
}
/// The stored override when it is set AND still exists as a directory; otherwise
/// `defaultRedlineFolder`. Never creates anything.
public static func resolveOneDriveFolder(
defaults: UserDefaults = .standard,
home: URL = FileManager.default.homeDirectoryForCurrentUser,
fileManager: FileManager = .default
) -> URL? {
if let storedPath = TransportSettings.storedOneDriveFolderPath(defaults: defaults) {
var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: storedPath, isDirectory: &isDirectory)
if exists, isDirectory.boolValue {
return URL(fileURLWithPath: storedPath, isDirectory: true)
}
}
return defaultRedlineFolder(home: home, fileManager: fileManager)
}
/// True when `url` exists as a directory AND is writable by the current process.
/// The live check `send(anchor:)` performs before ever composing into a OneDrive
/// destination — a directory that exists but has had its permissions revoked (e.g.
/// `chmod 500`) must be treated as unavailable, not silently attempted and
/// surfaced as a generic PDF-composition failure.
public static func isWritableDirectory(
at url: URL,
fileManager: FileManager = .default
) -> Bool {
var isDirectory: ObjCBool = false
let exists = fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
guard exists, isDirectory.boolValue else { return false }
return fileManager.isWritableFile(atPath: url.path)
}
/// Writes a tiny probe file into `folder`, fsyncs it, then removes it — the only
/// reliable way to catch a OneDrive Files-On-Demand directory whose provider domain
/// is signed out: such a directory can report as existing and POSIX-writable
/// (`isWritableDirectory` returns true) while an actual write fails. True only when
/// the write, fsync, AND removal of the probe file all succeed; any failure at any
/// of those steps means false, so the caller treats the folder as unavailable
/// rather than proceeding to compose a real PDF into it.
public static func probeWritable(
at folder: URL,
fileManager: FileManager = .default
) -> Bool {
let probeURL = folder.appendingPathComponent(".redline-probe-\(UUID().uuidString)")
// Belt-and-suspenders cleanup, unconditional: AtomicFile.write renames the temp
// file onto probeURL and THEN fsyncs the containing directory — if that last
// fsync throws, the probe file already exists on disk but the catch below
// returns false before ever reaching the explicit removeItem call. And if the
// explicit removeItem itself throws, this is the only retry it gets. Either
// way, never leave the probe file behind just because we're about to return.
defer {
if fileManager.fileExists(atPath: probeURL.path) {
try? fileManager.removeItem(at: probeURL)
}
}
do {
try AtomicFile.write(Data(), to: probeURL)
} catch {
return false
}
do {
try fileManager.removeItem(at: probeURL)
} catch {
return false
}
// Only true when the explicit removal above actually succeeded AND the file is
// confirmed gone — never trust a removeItem call that returned without throwing
// as proof of anything on a File Provider domain.
return !fileManager.fileExists(atPath: probeURL.path)
}
}
@@ -0,0 +1,19 @@
import Foundation
/// Whether Redline installs a staged update by itself.
///
/// On by default: updates download in the background and install the next time the app
/// has nothing unsent, so the tool stays current without anyone chasing a menu row.
/// Off means the staged update waits for the "Update to X" action.
public enum UpdateSettings {
public static let autoInstallKey = "ai.flowmaster.shotdeck.autoInstallUpdates"
public static func autoInstall(defaults: UserDefaults = .standard) -> Bool {
guard defaults.object(forKey: autoInstallKey) != nil else { return true }
return defaults.bool(forKey: autoInstallKey)
}
public static func setAutoInstall(_ value: Bool, defaults: UserDefaults = .standard) {
defaults.set(value, forKey: autoInstallKey)
}
}
@@ -371,6 +371,72 @@ func i19b_presentNonShotdeckCreatorBeatsMatchingFilename() throws {
#expect(AnnotationInspector.isShotdeckDocument(reopened) == false)
}
@Test("I-19c Present Redline creator is recognized")
func i19c_presentRedlineCreatorIsRecognized() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134219.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: "Redline")
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == true)
}
@Test("I-19d Present legacy Shotdeck creator is still recognized")
func i19d_presentLegacyShotdeckCreatorIsStillRecognized() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Shotdeck-20260830-134220.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: "Shotdeck")
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == true)
}
@Test("I-19e Absent creator falls back to Redline filename")
func i19e_absentCreatorFallsBackToRedlineFilename() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134221.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: nil)
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == true)
}
@Test("I-19f Absent creator falls back to legacy Shotdeck filename")
func i19f_absentCreatorFallsBackToLegacyShotdeckFilename() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Shotdeck-20260830-134222.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: nil)
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == true)
}
@Test("I-19g Absent creator falls back to Redline duplicate-name suffix")
func i19g_absentCreatorFallsBackToRedlineDuplicateNameSuffix() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134223 2.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: nil)
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == true)
}
@Test("I-19h Present non-product creator beats a matching Redline filename")
func i19h_presentNonProductCreatorBeatsMatchingRedlineFilename() throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134224.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: "Preview")
let reopened = try #require(PDFDocument(url: pdfURL))
#expect(AnnotationInspector.isShotdeckDocument(reopened) == false)
}
private func expectSinglePageMark(
_ subtype: PDFAnnotationSubtype,
bounds: CGRect,
@@ -0,0 +1,165 @@
import CoreGraphics
import Foundation
import ShotdeckCore
import Testing
// Which window a capture takes, for each scope — pure logic over the window list the
// window server reports, so it is testable without a display session.
private func window(
id: UInt32,
bundle: String?,
pid: Int32 = 100,
frame: CGRect = CGRect(x: 100, y: 100, width: 800, height: 600),
layer: Int = 0
) -> WindowCandidate {
WindowCandidate(
windowID: id, ownerBundleID: bundle, ownerPID: pid, frame: frame, layer: layer)
}
@Test
func windowScopeTakesTheFrontWindowOfTheFrontApp() throws {
let candidates = [
window(id: 1, bundle: "com.apple.Safari", pid: 10),
window(id: 2, bundle: "com.apple.Terminal", pid: 20),
]
let target = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 20, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 2)
}
@Test
func windowScopeFallsBackToTheFrontmostWindowOfAnyApp() throws {
let candidates = [
window(id: 1, bundle: "com.apple.Safari", pid: 10),
window(id: 2, bundle: "com.apple.Terminal", pid: 20),
]
let target = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 99, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 1)
}
@Test
func redlineNeverCapturesItself() throws {
let candidates = [
window(id: 1, bundle: CaptureTargetResolver.ownBundleID, pid: 5),
window(id: 2, bundle: "com.apple.Safari", pid: 10),
]
let target = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 5, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 2)
}
@Test
func chromeAndDesktopWindowsAreNotCandidates() throws {
let candidates = [
window(id: 1, bundle: "com.apple.dock", layer: 20),
window(id: 2, bundle: "com.apple.WindowManager", layer: 8),
window(id: 3, bundle: "com.apple.Safari"),
]
let target = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 3)
}
@Test
func tinyWindowsAreIgnored() throws {
let candidates = [
window(id: 1, bundle: "com.apple.Safari", frame: CGRect(x: 0, y: 0, width: 20, height: 20)),
window(id: 2, bundle: "com.apple.Terminal"),
]
let target = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 2)
}
@Test
func browserScopeTakesTheFrontBrowserWindow() throws {
let candidates = [
window(id: 1, bundle: "com.apple.Terminal", pid: 10),
window(id: 2, bundle: "com.google.Chrome", pid: 11),
window(id: 3, bundle: "com.apple.Safari", pid: 12),
]
let target = try CaptureTargetResolver.resolve(
scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates)
guard case .window(let id, _, _) = target else {
Issue.record("expected a window target, got \(target)")
return
}
#expect(id == 2)
}
@Test
func browserScopeSaysSoWhenNoBrowserIsOpen() {
let candidates = [window(id: 1, bundle: "com.apple.Terminal")]
#expect(throws: ShotdeckError.self) {
_ = try CaptureTargetResolver.resolve(
scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates)
}
}
@Test
func windowScopeSaysSoWhenThereIsNoWindow() {
#expect(throws: ShotdeckError.self) {
_ = try CaptureTargetResolver.resolve(
scope: .window, savedArea: nil, frontmostPID: 10,
candidates: [window(id: 1, bundle: "com.apple.dock", layer: 20)])
}
}
@Test
func areaScopeUsesTheSavedAreaAndSaysWhenThereIsNone() throws {
let area = CaptureRegion(
displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200),
capturedScale: 2)
let target = try CaptureTargetResolver.resolve(
scope: .area, savedArea: area, frontmostPID: 0, candidates: [])
#expect(target == .region(area))
#expect(throws: ShotdeckError.self) {
_ = try CaptureTargetResolver.resolve(
scope: .area, savedArea: nil, frontmostPID: 0, candidates: [])
}
}
@Test
func screenScopeUsesTheAreaDisplay() throws {
let area = CaptureRegion(
displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200),
capturedScale: 2)
let target = try CaptureTargetResolver.resolve(
scope: .screen, savedArea: area, frontmostPID: 0, candidates: [])
#expect(target == .display(displayID: area.displayID))
}
@Test
func captureScopeDescriptionsNameWhatWillBeTaken() {
let area = CaptureRegion(
displayID: CGMainDisplayID(), rect: CGRect(x: 0, y: 0, width: 800, height: 600),
capturedScale: 2)
#expect(CaptureScope.area.targetDescription(savedArea: area).contains("800 × 600"))
#expect(CaptureScope.area.targetDescription(savedArea: nil).contains("No area"))
#expect(CaptureScope.window.targetDescription(savedArea: area).contains("frontmost window"))
#expect(CaptureScope.browser.targetDescription(savedArea: area).contains("browser"))
#expect(CaptureScope.screen.targetDescription(savedArea: area).contains("Display"))
}
@@ -0,0 +1,125 @@
import Foundation
import Testing
import ShotdeckCore
@Test
func syncRootsFindsOneDriveDirsMMDFirstIgnoresNonDirsAndOtherProviders() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(at: cloudStorage, withIntermediateDirectories: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-Flowmaster", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("GoogleDrive-x", isDirectory: true),
withIntermediateDirectories: true
)
// A plain FILE (not a directory) named like a OneDrive root must be ignored.
FileManager.default.createFile(
atPath: cloudStorage.appendingPathComponent("OneDrive-notadir").path,
contents: Data("not a directory".utf8)
)
let roots = OneDriveLocator.syncRoots(home: home, fileManager: .default)
#expect(roots.map(\.lastPathComponent) == ["OneDrive-MMDGROUP", "OneDrive-Flowmaster"])
}
@Test
func syncRootsEmptyAndDefaultFolderNilWithNoCloudStorageDirectory() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
// No Library/CloudStorage created at all.
let roots = OneDriveLocator.syncRoots(home: home, fileManager: .default)
#expect(roots.isEmpty)
let defaultFolder = OneDriveLocator.defaultRedlineFolder(home: home, fileManager: .default)
#expect(defaultFolder == nil)
}
@Test
func defaultRedlineFolderIsFirstSyncRootPlusRedline() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-Flowmaster", isDirectory: true),
withIntermediateDirectories: true
)
let defaultFolder = try #require(
OneDriveLocator.defaultRedlineFolder(home: home, fileManager: .default)
)
// Derive "expected" from syncRoots() itself (already covered by its own dedicated
// test) rather than hand-building the path string — FileManager's directory
// enumeration can canonicalize /var -> /private/var and the two constructions
// otherwise disagree on that even for a URL that already exists.
let expectedRoot = try #require(OneDriveLocator.syncRoots(home: home, fileManager: .default).first)
let expected = expectedRoot.appendingPathComponent("Redline", isDirectory: true)
#expect(defaultFolder.path == expected.path)
}
@Test
func resolveOneDriveFolderPrefersAnExistingStoredOverride() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let override = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-override")
defer { try? FileManager.default.removeItem(at: override) }
TransportSettings.setOneDriveFolder(override, defaults: suite.defaults)
let resolved = OneDriveLocator.resolveOneDriveFolder(
defaults: suite.defaults, home: home, fileManager: .default
)
#expect(resolved?.path == override.path)
}
@Test
func resolveOneDriveFolderIgnoresAStoredPathThatNoLongerExists() throws {
let home = try makeFakeHome()
defer { try? FileManager.default.removeItem(at: home) }
let cloudStorage = home.appendingPathComponent("Library/CloudStorage", isDirectory: true)
try FileManager.default.createDirectory(
at: cloudStorage.appendingPathComponent("OneDrive-MMDGROUP", isDirectory: true),
withIntermediateDirectories: true
)
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let goneOverride = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-gone")
TransportSettings.setOneDriveFolder(goneOverride, defaults: suite.defaults)
try FileManager.default.removeItem(at: goneOverride)
let resolved = OneDriveLocator.resolveOneDriveFolder(
defaults: suite.defaults, home: home, fileManager: .default
)
let expectedRoot = try #require(OneDriveLocator.syncRoots(home: home, fileManager: .default).first)
let expected = expectedRoot.appendingPathComponent("Redline", isDirectory: true)
#expect(resolved?.path == expected.path)
}
private func makeFakeHome() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-fake-home-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
return home
}
+118 -1
View File
@@ -203,6 +203,123 @@ private func pixelWindow(
return (pixelX0, pixelY0, pixelX1, pixelY1)
}
@Test("fileName is Redline-yyyyMMdd-HHmm-SHORTID.pdf and uses compose time")
func fileNameUsesComposeTimeNotSessionCreatedAt() {
let old = Date(timeIntervalSince1970: 1_600_000_000) // 2020-09-13
let session = makeSession(captures: [], createdAt: old)
let name = PDFComposer.fileName(for: session)
#expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-[0-9A-F]{8}\.pdf$/) != nil)
#expect(name.contains(session.shortID))
#expect(!name.contains(DubaiTime.fileMinuteStamp(old)))
let today = String(DubaiTime.fileMinuteStamp(Date()).prefix(8))
#expect(name.contains(today))
}
@Test("fileName carries the lane slug between the timestamp and the session id")
func fileNameCarriesTheLaneSlug() {
let session = CaptureSession(
id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!,
createdAt: fixtureDate,
state: .open,
captures: [],
pdfFileName: nil,
context: ReviewContext(lane: "OMS test lane"))
let name = PDFComposer.fileName(for: session)
#expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-OMS-TEST-LANE-4F2A9C1D\.pdf$/) != nil)
}
@Test("Review footer lines state the tool, date, session and the recorded review details")
func footerLinesStateTheReviewDetails() {
let session = CaptureSession(
id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!,
createdAt: fixtureDate,
state: .open,
captures: [],
pdfFileName: nil,
context: ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout"))
let lines = PDFComposer.footerLines(
session: session, toolVersion: "0.5.0", composedAt: fixtureDate)
#expect(lines.count == 2)
#expect(lines[0].contains("Redline 0.5.0"))
#expect(lines[0].contains("Session 4F2A9C1D"))
#expect(lines[0].contains(DubaiTime.stamp(fixtureDate)))
#expect(lines[1].contains("Lane dev03"))
#expect(lines[1].contains("Deployed v1.4.2 (41)"))
#expect(lines[1].contains("Commit a1b2c3d4"))
#expect(lines[1].contains("Reviewer Ben Hippler"))
#expect(lines[1].contains("Note checkout"))
// A session with no recorded details still identifies itself; nothing is faked.
let bare = makeSession(captures: [])
let bareLines = PDFComposer.footerLines(
session: bare, toolVersion: "", composedAt: fixtureDate)
#expect(bareLines.count == 1)
#expect(bareLines[0].hasPrefix("Redline · "))
}
@Test("Document info carries the reviewer and the lane/build/commit keywords")
func documentInfoCarriesTheReviewDetails() {
let session = CaptureSession(
id: UUID(uuidString: "deadbeef-dead-4eef-8ead-deadbeef0001")!,
createdAt: fixtureDate,
state: .open,
captures: [],
pdfFileName: nil,
context: ReviewContext(
lane: "DEV03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout"))
let info = PDFComposer.documentInfo(
session: session, title: "Redline – DEV03", toolVersion: "0.5.0", composedAt: fixtureDate)
#expect(info[kCGPDFContextAuthor as String] as? String == "Ben Hippler")
#expect(info[kCGPDFContextCreator as String] as? String == "Redline 0.5.0")
let keywords = try? #require(info[kCGPDFContextKeywords as String] as? String)
#expect(keywords?.contains("lane=DEV03") == true)
#expect(keywords?.contains("deployed=v1.4.2") == true)
#expect(keywords?.contains("commit=a1b2c3d4") == true)
#expect(keywords?.contains("reviewer=Ben Hippler") == true)
#expect(keywords?.contains("built=\(DubaiTime.keywordStamp(fixtureDate))") == true)
}
@Test("A composed PDF carries the footer text and document info a reader can see")
func composedPDFCarriesTheReferenceBlock() throws {
let directory = try makeScratchDirectory()
defer { try? FileManager.default.removeItem(at: directory) }
let capture = makeCapture(sequence: 1, pixelWidth: 800, pixelHeight: 600)
let png = try writePNG(for: capture, red: 60, green: 60, blue: 60, in: directory)
let session = CaptureSession(
id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!,
createdAt: fixtureDate,
state: .open,
captures: [capture],
pdfFileName: nil,
context: ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout"))
let output = directory.appendingPathComponent("footer.pdf")
_ = try PDFComposer().compose(
session: session,
imageURL: { _ in png },
title: "Redline – dev03",
to: output,
toolVersion: "0.5.0",
composedAt: fixtureDate
)
let document = try openDocument(output)
let pageText = try #require(document.page(at: 0)?.string ?? "")
#expect(pageText.contains("Redline 0.5.0"))
#expect(pageText.contains("Lane dev03"))
#expect(pageText.contains("Commit a1b2c3d4"))
#expect(pageText.contains("Ben Hippler"))
let attributes = try #require(document.documentAttributes)
#expect(attributes[PDFDocumentAttribute.authorAttribute] as? String == "Ben Hippler")
}
@Test("Three-page basic compose")
func threePageBasicCompose() throws {
let directory = try makeScratchDirectory()
@@ -499,7 +616,7 @@ func documentAttributesRoundTrip() throws {
)
let document = try openDocument(output)
let attributes = try #require(document.documentAttributes)
#expect(attributes[PDFDocumentAttribute.creatorAttribute] as? String == "Shotdeck")
#expect(attributes[PDFDocumentAttribute.creatorAttribute] as? String == "Redline")
#expect(attributes[PDFDocumentAttribute.titleAttribute] as? String == "Ben review — 2026-08-30")
#expect(attributes[PDFDocumentAttribute.subjectAttribute] as? String == "deadbeef-dead-4eef-8ead-deadbeef0001")
#expect(document.pageCount == 1)
@@ -109,6 +109,65 @@ func w25_duplicateNameSuffixIsRecognizedByScanNow() async throws {
#expect(commented[0].fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
}
@Test("W-25b Redline duplicate-name suffix is the normal AirDrop return (scanNow)")
func w25b_redlineDuplicateNameSuffixIsRecognizedByScanNow() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134205 2.pdf")
try makePDF(
at: pdfURL,
pageCount: 1,
creator: nil,
subject: "44444444-4444-4444-4444-444444444444",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.count == 1)
let doc = try #require(found.first)
#expect(doc.fileURL.lastPathComponent == "Redline-20260830-134205 2.pdf")
#expect(doc.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
#expect(doc.pageCount == 1)
#expect(doc.annotatedPages == [1])
#expect(doc.isCommented == true)
let commented = try await ledger.commented()
#expect(commented.count == 1)
#expect(commented[0].fileURL.lastPathComponent == pdfURL.lastPathComponent)
#expect(commented[0].fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
}
@Test("W-25c Redline creator is recognized by scanNow")
func w25c_redlineCreatorIsRecognizedByScanNow() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260830-134230.pdf")
try makePDF(
at: pdfURL,
pageCount: 1,
creator: "Redline",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.count == 1)
let doc = try #require(found.first)
#expect(doc.fileURL.lastPathComponent == "Redline-20260830-134230.pdf")
#expect(doc.isCommented == true)
}
@Test("W-26 Creator provenance negative at the scan level")
func w26_presentNonShotdeckCreatorIsIgnoredByScanNow() async throws {
let (paths, cleanup) = try makeCasePaths()
@@ -171,3 +230,162 @@ func w27_fsEventsCallbackFiresOnRealArrival() async throws {
await watcher.stop()
}
}
@Test("recordUncommented defaults to true: an unmarked PDF is still recorded (AirDrop behaviour unchanged)")
func recordUncommentedDefaultTrueRecordsAnUnmarkedPDF() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260905-090000.pdf")
try makePDF(at: pdfURL, pageCount: 1, creator: "Redline", annotations: [])
let found = try await watcher.scanNow()
#expect(found.count == 1)
#expect(found.first?.isCommented == false)
let all = try await ledger.all()
#expect(all.count == 1)
}
@Test("recordUncommented=false: an unmarked PDF is not recorded or returned; marking it up in place gets it recorded")
func recordUncommentedFalseSkipsUnmarkedThenRecordsAfterInPlaceMarkup() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
await watcher.setRecordUncommented(false)
let pdfURL = paths.watchFolder.appendingPathComponent("Redline-20260905-091500.pdf")
// OneDrive mode: the PDF is freshly written here (by "send"), unmarked so far.
try makePDF(at: pdfURL, pageCount: 1, creator: "Redline", annotations: [])
let beforeMarkup = try await watcher.scanNow()
#expect(beforeMarkup.isEmpty)
let allBefore = try await ledger.all()
#expect(allBefore.isEmpty)
// What the iPad does: mark it up in place, in the SAME folder, then save.
let document = try #require(PDFDocument(url: pdfURL))
let page = try #require(document.page(at: 0))
page.addAnnotation(makeAnnotation(.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)))
#expect(document.write(to: pdfURL))
let afterMarkup = try await watcher.scanNow()
#expect(afterMarkup.count == 1)
#expect(afterMarkup.first?.isCommented == true)
let commented = try await ledger.commented()
#expect(commented.count == 1)
#expect(commented.first?.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
}
// MARK: - Launch-paths BLOCKER regression (adversarial review, 20260905)
//
// The bug: AppDelegate.makeLaunchModel() built `paths` via the AirDrop-only
// FolderSettings.resolvedAppSupportPaths(), so ReturnWatcher's internal watchFolder
// (seeded from paths.watchFolder in its own init) was the AirDrop folder even when
// OneDrive was the persisted transport, and bootstrap() never reconciled it before
// starting. Net effect: PDFs went to OneDrive but FSEvents kept watching the stale
// AirDrop folder for the whole session — marked-up returns were never detected.
// The fix: launch paths now come from TransportSettings.resolvedAppSupportPaths()
// (transport-aware), and AppModel.bootstrap() unconditionally reconciles the watcher's
// folder via updateWatchFolder() before it starts. These two tests characterize the
// bug (still reproducible via the old AirDrop-only construction) and prove the fix
// (the real launch-construction path, end to end).
@Test("Launch regression (fix): OneDrive persisted -> transport-aware launch paths -> bootstrap-style reconcile -> a marked PDF is detected")
func launchStyleConstructionWithOneDriveTransportDetectsAMarkedReturn() async throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let oneDriveFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-launch-onedrive")
defer { try? FileManager.default.removeItem(at: oneDriveFolder) }
let appSupportRoot = try makeTransportTemporaryDirectory(prefix: "shotdeck-launch-approot")
defer { try? FileManager.default.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: suite.defaults)
// Exactly what AppDelegate.makeLaunchModel() now does: build launch paths from the
// transport-aware resolver — the fix, NOT FolderSettings.resolvedAppSupportPaths(),
// which is AirDrop-only and is the root cause the next test characterizes.
let paths = try TransportSettings.resolvedAppSupportPaths(
root: appSupportRoot, defaults: suite.defaults, fileManager: .default
)
#expect(paths.outbox.path == oneDriveFolder.path)
#expect(paths.watchFolder.path == oneDriveFolder.path)
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
// What AppModel.bootstrap() now does, unconditionally, before watcher.start():
await watcher.setRecordUncommented(false) // transport == .oneDrive
try await watcher.updateWatchFolder(paths.watchFolder)
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-20260905-100000.pdf")
try makePDF(
at: pdfURL, pageCount: 1, creator: "Redline",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.contains(where: {
$0.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path && $0.isCommented
}))
let commented = try await ledger.commented()
#expect(commented.contains(where: {
$0.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path
}))
}
@Test("Launch regression (characterizes the bug): AirDrop-only launch paths with no reconcile miss an OneDrive-mode return")
func airDropOnlyLaunchPathsWithoutReconcileMissesAMarkedOneDriveReturn() async throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let oneDriveFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-onedrive")
defer { try? FileManager.default.removeItem(at: oneDriveFolder) }
// A configured AirDrop watch-folder override, isolated to a temp dir — NOT the real
// ~/Downloads, which may already hold real marked-up Redline PDFs from actual use
// and would make this test's "found.isEmpty" assertion depend on the state of
// Ben's real Downloads folder instead of the isolated fixture under test.
let staleAirDropFolder = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-airdrop-stale")
defer { try? FileManager.default.removeItem(at: staleAirDropFolder) }
let appSupportRoot = try makeTransportTemporaryDirectory(prefix: "shotdeck-buggy-approot")
defer { try? FileManager.default.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: suite.defaults)
FolderSettings.setWatchFolder(staleAirDropFolder, defaults: suite.defaults)
// The BUG's exact construction: FolderSettings.resolvedAppSupportPaths() ignores
// the persisted transport entirely and always resolves the AirDrop folders.
let buggyPaths = try FolderSettings.resolvedAppSupportPaths(root: appSupportRoot, defaults: suite.defaults)
#expect(buggyPaths.watchFolder.path == staleAirDropFolder.path)
#expect(buggyPaths.watchFolder.path != oneDriveFolder.path)
let ledger = try ReturnLedger(paths: buggyPaths)
let watcher = ReturnWatcher(paths: buggyPaths, ledger: ledger)
// The old bootstrap(): recordUncommented was set, but there was NO
// updateWatchFolder() call before start() to reconcile the folder.
await watcher.setRecordUncommented(false)
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-20260905-100100.pdf")
try makePDF(
at: pdfURL, pageCount: 1, creator: "Redline",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
// The watcher is still pointed at the stale (configured-AirDrop) watch folder, so
// scanning it — NOT the OneDrive folder the PDF actually landed in — finds nothing.
// This is the exact BLOCKER the fix above closes.
let found = try await watcher.scanNow()
#expect(found.isEmpty)
}
@@ -0,0 +1,138 @@
import Foundation
import ShotdeckCore
import Testing
// PDF naming scheme + the persisted session age limit.
// MARK: - PDF file names
@Test
func laneSlugKeepsLettersDigitsAndSingleDashes() {
#expect(PDFFileName.laneSlug("OMS test lane") == "OMS-TEST-LANE")
#expect(PDFFileName.laneSlug(" dev03 ") == "DEV03")
#expect(PDFFileName.laneSlug("v1.4.2 / stage") == "V1-4-2-STAGE")
#expect(PDFFileName.laneSlug("") == "")
#expect(PDFFileName.laneSlug("--") == "")
}
@Test
func laneSlugIsCappedSoTheFileNameStaysShort() {
let long = String(repeating: "abcdefghij", count: 5)
let slug = PDFFileName.laneSlug(long)
#expect(slug.count == PDFFileName.laneMaxLength)
#expect(!slug.hasSuffix("-"))
}
@Test
func fileNameIsSortableAndUniquePerSession() {
let sessionID = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")!
let builtAt = Date(timeIntervalSince1970: 1_777_482_180)
let withLane = PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: sessionID)
#expect(withLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-DEV03-4F2A9C1D.pdf")
let withoutLane = PDFFileName.make(builtAt: builtAt, lane: "", sessionID: sessionID)
#expect(withoutLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-4F2A9C1D.pdf")
// Two sessions in the same minute never collide.
let other = UUID(uuidString: "9B8C7D6E-0000-4000-8000-000000000000")!
#expect(PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: other)
!= withLane)
}
@Test
func sessionLabelIsLaneOrShortID() {
let id = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")!
#expect(PDFFileName.sessionLabel(lane: "dev03", sessionID: id) == "DEV03-4F2A9C1D")
#expect(PDFFileName.sessionLabel(lane: "", sessionID: id) == "4F2A9C1D")
}
// MARK: - Retention setting
@Test
func retentionDefaultsToNever() throws {
let suite = try makeDefaults()
defer { suite.defaults.removePersistentDomain(forName: suite.name) }
#expect(RetentionSettings.load(defaults: suite.defaults) == .never)
#expect(RetentionSettings.load(defaults: suite.defaults).cutoff() == nil)
}
@Test
func retentionRoundTripsThroughDefaults() throws {
let suite = try makeDefaults()
defer { suite.defaults.removePersistentDomain(forName: suite.name) }
RetentionSettings.save(.days(30), defaults: suite.defaults)
#expect(RetentionSettings.load(defaults: suite.defaults) == .days(30))
RetentionSettings.save(.never, defaults: suite.defaults)
#expect(RetentionSettings.load(defaults: suite.defaults) == .never)
#expect(suite.defaults.object(forKey: RetentionSettings.defaultsKey) == nil)
}
@Test
func retentionCutoffIsTheDayCountBeforeNow() {
let now = Date(timeIntervalSince1970: 1_777_482_180)
let cutoff = try? #require(SessionRetention.days(30).cutoff(now: now))
let expected = Calendar(identifier: .gregorian).date(byAdding: .day, value: -30, to: now)
#expect(cutoff == expected)
}
@Test
func retentionPresetsReadAsPlainEnglish() {
#expect(SessionRetention.never.displayName == "Never (default)")
#expect(SessionRetention.days(7).displayName == "7 days")
#expect(SessionRetention.days(365).displayName == "1 year")
#expect(SessionRetention.never.policyDescription == "All sessions kept.")
#expect(SessionRetention.days(14).policyDescription == "Sessions older than 14 days are deleted.")
}
// MARK: - Review context
@Test
func reviewContextTrimsCapsAndCollapsesLineBreaks() {
let long = String(repeating: "x", count: ReviewContext.maxFieldLength + 40)
let context = ReviewContext(
lane: " dev03 ", deployedVersion: "v1.4.2\n(build 41)", commit: " a1b2c3d4 ",
reviewer: "Ben Hippler", note: long)
#expect(context.lane == "dev03")
#expect(context.deployedVersion == "v1.4.2 (build 41)")
#expect(context.commit == "a1b2c3d4")
#expect(context.note.count == ReviewContext.maxFieldLength)
}
@Test
func reviewContextSummaryDropsEmptyParts() {
#expect(ReviewContext(lane: "dev03", commit: "a1b2c3d4").summaryLine == "dev03 · a1b2c3d4")
#expect(ReviewContext().summaryLine == "")
#expect(ReviewContext().isEmpty)
}
@Test
func reviewContextDecodesPartialJSON() throws {
let json = Data(#"{"lane":"dev03","commit":"a1b2c3d4"}"#.utf8)
let context = try JSONDecoder().decode(ReviewContext.self, from: json)
#expect(context.lane == "dev03")
#expect(context.commit == "a1b2c3d4")
#expect(context.reviewer == "")
#expect(context.note == "")
}
// MARK: - Fixtures
private struct DefaultsSuite {
let name: String
let defaults: UserDefaults
}
private func makeDefaults() throws -> DefaultsSuite {
let name = "shotdeck-retention-settings-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: name) else {
throw SettingsFixtureError.noSuite
}
defaults.removePersistentDomain(forName: name)
return DefaultsSuite(name: name, defaults: defaults)
}
private enum SettingsFixtureError: Error { case noSuite }
@@ -0,0 +1,358 @@
import CoreGraphics
import Foundation
import ImageIO
import Testing
import ShotdeckCore
// Session lifecycle + retention: "Start new session" keeps the current screenshots as
// a past session; every session is kept by default, and an age limit chosen in
// Settings is the only thing that ever removes one.
// MARK: - 1. closeCurrentSession keeps the captures as a past session
@Test
func closeCurrentSessionKeepsCapturesAsAPastSessionAndStartsFresh() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
let c1 = try await store.append(
pngData: try makePNGData(width: 8, height: 8, red: 1, green: 0, blue: 0),
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
let c2 = try await store.append(
pngData: try makePNGData(width: 8, height: 8, red: 0, green: 1, blue: 0),
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
let closedID = try await store.currentSession().id
let archived = try #require(try await store.closeCurrentSession())
#expect(archived.id == closedID)
#expect(archived.state == .archived)
#expect(archived.pdfFileName == nil) // never sent — shown as "Not sent"
#expect(archived.captures.map(\.id) == [c1.id, c2.id])
// Nothing is deleted: both PNGs live on under archive/<id>/.
let archiveDir = paths.archiveDirectory(closedID)
for capture in archived.captures {
#expect(FileManager.default.fileExists(
atPath: archiveDir.appendingPathComponent(capture.fileName).path))
}
#expect(!FileManager.default.fileExists(atPath: paths.sessionDirectory(closedID).path))
let fresh = try await store.currentSession()
#expect(fresh.id != closedID)
#expect(fresh.state == .open)
#expect(fresh.isEmpty)
let past = try await store.archivedSessions()
#expect(past.map(\.id) == [closedID])
#expect(past.first?.captures.count == 2)
}
// MARK: - 2. closeCurrentSession on an empty open session just starts fresh
@Test
func closeCurrentSessionOnAnEmptyOpenSessionStartsFreshWithoutArchiving() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
let before = try await store.currentSession().id
let archived = try await store.closeCurrentSession()
#expect(archived == nil)
let after = try await store.currentSession()
#expect(after.id != before)
#expect(after.isEmpty)
let past = try await store.archivedSessions()
#expect(past.isEmpty)
}
// MARK: - 3. sent and unsent sessions are distinguishable in the past list
@Test
func pastSessionsDistinguishSentFromUnsentByPDFFileName() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
_ = try await store.append(
pngData: try makePNGData(width: 6, height: 6, red: 1, green: 0, blue: 0),
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
let sent = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120000.pdf")
_ = try await store.append(
pngData: try makePNGData(width: 6, height: 6, red: 0, green: 0, blue: 1),
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
let closed = try #require(try await store.closeCurrentSession())
#expect(sent.pdfFileName == "Redline-20261011-120000.pdf")
#expect(closed.pdfFileName == nil)
let past = try await store.archivedSessions()
#expect(past.map(\.id) == [closed.id, sent.id]) // newest first
#expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"])
}
// MARK: - 4. nothing is deleted by default
@Test
func defaultPolicyKeepsEverySession() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
#expect(await store.configuredRetention() == .never)
var closedIDs: [UUID] = []
for index in 0..<12 {
_ = try await store.append(
pngData: try makePNGData(width: 4, height: 4, red: 0.1, green: 0.1, blue: 0.1),
pixelWidth: 4, pixelHeight: 4, scale: 1.0,
capturedAt: Date(timeIntervalSince1970: 1_700_000_000 + Double(index)))
let closed = try #require(try await store.closeCurrentSession())
closedIDs.append(closed.id)
}
// All 12 sessions live on in the single archive/ folder; none was pruned.
let fm = FileManager.default
let entries = try fm.contentsOfDirectory(at: paths.archive, includingPropertiesForKeys: nil)
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
#expect(sessionDirs.count == closedIDs.count)
let kept = try await store.archivedSessions().map(\.id)
#expect(kept == closedIDs.reversed())
for id in closedIDs {
#expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path))
}
// A prune under the default policy removes nothing at all.
#expect(try await store.pruneExpiredSessions().isEmpty)
#expect(try await store.expiredSessionIDs().isEmpty)
}
// MARK: - 5. an age limit removes exactly the expired sessions
@Test
func ageLimitRemovesOnlySessionsOlderThanTheCutoff() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let now = Date(timeIntervalSince1970: 1_700_000_000) // fixed "now" for the test
let day: TimeInterval = 86_400
let oldIDs = try [
try writeArchivedSession(createdAt: now.addingTimeInterval(-40 * day), in: paths),
try writeArchivedSession(createdAt: now.addingTimeInterval(-31 * day), in: paths),
]
let recentIDs = try [
try writeArchivedSession(createdAt: now.addingTimeInterval(-29 * day), in: paths),
try writeArchivedSession(createdAt: now.addingTimeInterval(-1 * day), in: paths),
]
let store = try SpoolStore(paths: paths, retention: .days(30))
// Asking what would happen deletes nothing.
#expect(Set(try await store.expiredSessionIDs(now: now)) == Set(oldIDs))
#expect(try await store.archivedSessions().count == 4)
let removed = try await store.pruneExpiredSessions(now: now)
#expect(Set(removed) == Set(oldIDs))
let fm = FileManager.default
for id in oldIDs {
#expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path))
}
for id in recentIDs {
#expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path))
}
// The open session is never a candidate, and a second pass is a no-op.
#expect(try await store.currentSession().state == .open)
#expect(try await store.pruneExpiredSessions(now: now).isEmpty)
}
// MARK: - 6. the archive path applies the configured age limit
@Test
func theArchivePathAppliesTheAgeLimit() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let day: TimeInterval = 86_400
let expiredID = try writeArchivedSession(
createdAt: Date().addingTimeInterval(-10 * day), in: paths)
let store = try SpoolStore(paths: paths, retention: .days(7))
_ = try await store.append(
pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3),
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date())
let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261031-1200-A1B2C3D4.pdf")
let kept = try await store.archivedSessions()
#expect(kept.map(\.id) == [archived.id])
#expect(!FileManager.default.fileExists(atPath: paths.archiveDirectory(expiredID).path))
}
// MARK: - 7. review context is persisted, survives a relaunch and is inherited
@Test
func reviewContextPersistsAndIsInheritedByTheNextSession() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
let context = ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout flow")
let updated = try await store.setContext(context)
#expect(updated.context == context)
// A second store on the same directory is what a relaunch sees.
let reopened = try SpoolStore(paths: paths)
#expect(try await reopened.currentSession().context == context)
_ = try await store.append(
pngData: try makePNGData(width: 4, height: 4, red: 0.4, green: 0.4, blue: 0.4),
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date())
let archived = try #require(try await store.closeCurrentSession())
#expect(archived.context == context)
// The fresh session keeps the same review details.
#expect(try await store.currentSession().context == context)
}
// MARK: - 8. a manifest written before contexts existed still loads
@Test
func legacyManifestWithoutContextDecodesAsEmptyContext() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let id = UUID()
let dir = paths.archiveDirectory(id)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let legacyJSON = """
{
"id": "\(id.uuidString)",
"createdAt": "2026-10-11T12:00:00Z",
"state": "archived",
"captures": [],
"pdfFileName": "Redline-20261011-120000.pdf"
}
"""
try Data(legacyJSON.utf8).write(to: dir.appendingPathComponent("session.json"))
let store = try SpoolStore(paths: paths)
let sessions = try await store.archivedSessions()
#expect(sessions.map(\.id) == [id])
#expect(sessions.first?.context == .empty)
#expect(sessions.first?.pdfFileName == "Redline-20261011-120000.pdf")
}
// MARK: - 7. a stale open session is never returned as current (truth guard)
@Test
func aStaleOpenSessionIsNeverReturnedAsCurrent() async throws {
let (root, paths) = try makeIsolatedPaths()
defer { try? FileManager.default.removeItem(at: root) }
let store = try SpoolStore(paths: paths)
_ = try await store.append(
pngData: try makePNGData(width: 6, height: 6, red: 0.7, green: 0.7, blue: 0.1),
pixelWidth: 6, pixelHeight: 6, scale: 1.0, capturedAt: Date())
let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261011-120200.pdf")
// Simulate the mid-run failure the truth guard exists for: the archived session
// moved away and the replacement open session's folder is gone (e.g. the fresh
// session could not be created / survive). The store must mint a real fresh
// session — never report the already-archived one as open.
let fresh = try await store.currentSession()
try FileManager.default.removeItem(at: paths.sessionDirectory(fresh.id))
let recovered = try await store.currentSession()
#expect(recovered.id != fresh.id)
#expect(recovered.id != archived.id)
#expect(recovered.state == .open)
#expect(recovered.isEmpty)
let past = try await store.archivedSessions()
#expect(past.map(\.id) == [archived.id])
}
// MARK: - Fixtures
/// Writes an archived session folder with the given creation date, exactly the shape
/// production writes (a manifest plus one PNG), so retention can be exercised without
/// waiting days.
private func writeArchivedSession(createdAt: Date, in paths: AppSupportPaths) throws -> UUID {
let id = UUID()
let dir = paths.archiveDirectory(id)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let pngName = "001-A1B2C3D4.png"
try makePNGData(width: 4, height: 4, red: 0.5, green: 0.5, blue: 0.5)
.write(to: dir.appendingPathComponent(pngName))
let capture = Capture(
id: UUID(), sequence: 1, fileName: pngName,
pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: createdAt)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .archived, captures: [capture],
pdfFileName: "Redline-\(DubaiTime.fileMinuteStamp(createdAt)).pdf")
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try encoder.encode(session).write(to: dir.appendingPathComponent("session.json"))
return id
}
private enum FixtureError: Error {
case pngGenerationFailed
}
private func makeIsolatedPaths() throws -> (root: URL, paths: AppSupportPaths) {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-retention-\(UUID().uuidString)", isDirectory: true)
let paths = try AppSupportPaths(
root: root,
outbox: root.appendingPathComponent("outbox", isDirectory: true),
watchFolder: root.appendingPathComponent("watch", isDirectory: true)
)
return (root, paths)
}
private func makePNGData(
width: Int,
height: Int,
red: CGFloat,
green: CGFloat,
blue: CGFloat
) throws -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
throw FixtureError.pngGenerationFailed
}
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else {
throw FixtureError.pngGenerationFailed
}
let data = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(
data, "public.png" as CFString, 1, nil
) else {
throw FixtureError.pngGenerationFailed
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
throw FixtureError.pngGenerationFailed
}
return data as Data
}
@@ -0,0 +1,227 @@
import Foundation
import Testing
import ShotdeckCore
@Test
func transportDefaultsToAirDropWhenUnset() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func setTransportRoundTrips() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
#expect(TransportSettings.transport(defaults: suite.defaults) == .oneDrive)
TransportSettings.setTransport(.airDrop, defaults: suite.defaults)
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func garbageStoredTransportFallsBackToAirDrop() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
suite.defaults.set("not-a-real-transport", forKey: TransportSettings.transportDefaultsKey)
#expect(TransportSettings.transport(defaults: suite.defaults) == .airDrop)
}
@Test
func oneDriveFolderStoreAndReset() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let folder = try makeTransportTemporaryDirectory(prefix: "shotdeck-onedrive-folder")
defer { try? FileManager.default.removeItem(at: folder) }
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == nil)
TransportSettings.setOneDriveFolder(folder, defaults: suite.defaults)
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == folder.path)
TransportSettings.resetOneDriveFolder(defaults: suite.defaults)
#expect(TransportSettings.storedOneDriveFolderPath(defaults: suite.defaults) == nil)
}
@Test
func effectiveFoldersForAirDropMatchesFolderSettings() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let outbox = try makeTransportTemporaryDirectory(prefix: "shotdeck-effective-outbox")
defer { try? FileManager.default.removeItem(at: outbox) }
FolderSettings.setOutbox(outbox, defaults: suite.defaults)
let effective = TransportSettings.effectiveFolders(defaults: suite.defaults)
let expected = FolderSettings.resolve(defaults: suite.defaults)
#expect(effective.transport == .airDrop)
#expect(effective.outbox.path == expected.outbox.path)
#expect(effective.watch.path == expected.watch.path)
}
@Test
func effectiveFoldersForOneDriveWithAResolvableFolderUsesItForBoth() throws {
let suite = try makeTransportDefaultsSuite()
defer { tearDownTransportSuite(suite) }
let folder = try makeTransportTemporaryDirectory(prefix: "shotdeck-effective-onedrive")
defer { try? FileManager.default.removeItem(at: folder) }
TransportSettings.setTransport(.oneDrive, defaults: suite.defaults)
TransportSettings.setOneDriveFolder(folder, defaults: suite.defaults)
let effective = TransportSettings.effectiveFolders(defaults: suite.defaults)
#expect(effective.transport == .oneDrive)
#expect(effective.outbox.path == folder.path)
#expect(effective.watch.path == folder.path)
#expect(effective.outbox.path == effective.watch.path)
}
@Test
func oneDriveFolderUnavailableErrorDescriptionContainsThePath() throws {
let path = "/Users/example/Library/CloudStorage/OneDrive-Example/Redline"
let error = ShotdeckError.oneDriveFolderUnavailable(path: path)
let description = try #require(error.errorDescription)
#expect(!description.isEmpty)
#expect(description.contains(path))
}
@Test
func isWritableDirectoryTrueForAnOrdinaryWritableDirectory() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-writable")
defer { try? FileManager.default.removeItem(at: dir) }
#expect(OneDriveLocator.isWritableDirectory(at: dir))
}
@Test
func isWritableDirectoryFalseForAnExistingButUnwritableDirectory() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-unwritable")
defer {
// Restore perms BEFORE removal — an unwritable dir can't otherwise be cleaned up.
try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
try? FileManager.default.removeItem(at: dir)
}
#expect(OneDriveLocator.isWritableDirectory(at: dir)) // sanity check before chmod
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
#expect(!OneDriveLocator.isWritableDirectory(at: dir))
}
@Test
func isWritableDirectoryFalseForAPlainFileAndForANonexistentPath() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-writable-check-parent")
defer { try? FileManager.default.removeItem(at: dir) }
let filePath = dir.appendingPathComponent("plain-file.txt")
FileManager.default.createFile(atPath: filePath.path, contents: Data("x".utf8))
#expect(!OneDriveLocator.isWritableDirectory(at: filePath))
#expect(!OneDriveLocator.isWritableDirectory(at: dir.appendingPathComponent("does-not-exist")))
}
@Test
func probeWritableTrueForAnOrdinaryWritableDirectoryAndLeavesNoProbeFileBehind() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-writable")
defer { try? FileManager.default.removeItem(at: dir) }
#expect(OneDriveLocator.probeWritable(at: dir))
let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path)
#expect(leftovers.isEmpty)
}
@Test
func probeWritableFalseForAChmod500Directory() throws {
// The File Provider edge case this probe exists for: isWritableDirectory can be
// true (as verified by the isWritableDirectory tests above) while an actual write
// still fails. A chmod 500 directory reproduces that "looks writable, isn't"
// shape closely enough to prove the probe itself does a real write, not just
// another permissions-bit check.
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-unwritable")
defer {
try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
try? FileManager.default.removeItem(at: dir)
}
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
#expect(!OneDriveLocator.probeWritable(at: dir))
}
@Test
func probeWritableFalseForAPlainFilePath() throws {
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-file-parent")
defer { try? FileManager.default.removeItem(at: dir) }
let filePath = dir.appendingPathComponent("plain-file.txt")
FileManager.default.createFile(atPath: filePath.path, contents: Data("x".utf8))
#expect(!OneDriveLocator.probeWritable(at: filePath))
}
/// The write itself succeeds (a real probe file lands on disk via AtomicFile.write,
/// which never touches this injected FileManager — it uses raw POSIX calls), but the
/// FIRST call to `removeItem(at:)` throws, simulating a transient File Provider
/// removal failure. probeWritable's own defer-based cleanup must retry and succeed
/// (the second call through this same override falls through to `super`), so no
/// probe file is left behind even though the function correctly still reports false
/// (the removal it explicitly attempted did fail).
private final class ThrowOnceOnRemoveFileManager: FileManager, @unchecked Sendable {
private let lock = NSLock()
private var hasThrown = false
override func removeItem(at URL: URL) throws {
lock.lock()
let shouldThrow = !hasThrown
hasThrown = true
lock.unlock()
if shouldThrow {
throw NSError(domain: "ShotdeckCoreTests.ThrowOnceOnRemove", code: 1)
}
try super.removeItem(at: URL)
}
}
@Test
func probeWritableFalseAndLeavesNoProbeFileWhenRemoveItemThrowsOnce() throws {
// Directory fsync failure (the OTHER way probeWritable's cleanup can be needed) has
// no injectable seam: AtomicFile.write's directory fsync is a raw Darwin fsync(2)
// call on an already-open file descriptor, not parameterized by any FileManager or
// other dependency this test can substitute, and there is no portable way to make
// fsync(2) itself fail via chmod or other standard test techniques (fsync failures
// are OS/filesystem/hardware-level events). Covering the removeItem-throws path
// (below) is what this test does; the fsync-throws path is covered by code
// inspection only — the same `defer` block guards both.
let dir = try makeTransportTemporaryDirectory(prefix: "shotdeck-probe-remove-throws")
defer { try? FileManager.default.removeItem(at: dir) }
let injectedFileManager = ThrowOnceOnRemoveFileManager()
#expect(!OneDriveLocator.probeWritable(at: dir, fileManager: injectedFileManager))
let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path)
#expect(leftovers.isEmpty)
}
struct TransportDefaultsSuite {
let name: String
let defaults: UserDefaults
}
func makeTransportDefaultsSuite() throws -> TransportDefaultsSuite {
let name = "shotdeck-transport-test-\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: name))
defaults.removePersistentDomain(forName: name)
return TransportDefaultsSuite(name: name, defaults: defaults)
}
func tearDownTransportSuite(_ suite: TransportDefaultsSuite) {
suite.defaults.removePersistentDomain(forName: suite.name)
}
func makeTransportTemporaryDirectory(prefix: String) throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("\(prefix)-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
+142
View File
@@ -0,0 +1,142 @@
import AppKit
import Foundation
import PDFKit
import Testing
import ShotdeckCore
@testable import Shotdeck
/// Coverage gap closed (adversarial review, rounds 3 and 4): the Core-level regression
/// tests in ShotdeckCoreTests hand-replicate what `AppDelegate.makeLaunchModel()` and
/// `AppModel.bootstrap()` do, rather than calling them — so a future revert of
/// `makeLaunchModel()` back to the AirDrop-only resolver, or a dropped
/// `updateWatchFolder` call inside `bootstrap()`, would NOT fail `swift test`. This
/// test goes through the real, unmodified call sites in the `Shotdeck` executable
/// target via `@testable import`, which `ShotdeckCoreTests` cannot reach (it only
/// depends on `ShotdeckCore`) — hence this separate `ShotdeckTests` target.
///
/// Round 4 correction: the first version of this test asserted only
/// `model.watchFolderURL`, which `AppModel.init` computes independently via
/// `TransportSettings.effectiveFolders()` — so it stayed correct (and the test kept
/// passing) even when `makeLaunchModel()` was reverted to the AirDrop-only resolver,
/// because `bootstrap()`'s own unconditional `updateWatchFolder` reconcile papered
/// over the reverted resolver. That made the "verified this catches the blocker"
/// claim in the previous round's commit message empirically false. This version
/// asserts `model.paths`/the watcher's `currentWatchFolder` BEFORE `bootstrap()` runs,
/// which actually depends on what `makeLaunchModel()` built — see this file's git
/// history (or the round-4 commit message) for the verbatim before/after
/// `swift test --filter` output proving it now discriminates correctly.
@MainActor
@Test("Real wiring: AppDelegate.makeLaunchModel() + AppModel.bootstrap() detect a marked OneDrive return")
func realLaunchModelAndBootstrapDetectAMarkedOneDriveReturn() async throws {
let fm = FileManager.default
// UserDefaults.standard is the ONLY defaults instance makeLaunchModel()/bootstrap()
// actually read — there is no defaults-threading through AppModel/AppDelegate (the
// same reasoning documented in PickerSelfTest.swift's ONEDRIVE-SELFTEST phase).
// "Isolated" here means snapshot-and-restore around the real keys, not a separate
// UserDefaults(suiteName:) instance that these real, unmodified call sites would
// never actually consult.
let defaults = UserDefaults.standard
let previousTransport = defaults.string(forKey: TransportSettings.transportDefaultsKey)
let previousFolder = defaults.string(forKey: TransportSettings.oneDriveFolderDefaultsKey)
defer {
if let previousTransport {
defaults.set(previousTransport, forKey: TransportSettings.transportDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.transportDefaultsKey)
}
if let previousFolder {
defaults.set(previousFolder, forKey: TransportSettings.oneDriveFolderDefaultsKey)
} else {
defaults.removeObject(forKey: TransportSettings.oneDriveFolderDefaultsKey)
}
}
let oneDriveFolderRaw = fm.temporaryDirectory
.appendingPathComponent("shotdeck-real-wiring-onedrive-\(UUID().uuidString)", isDirectory: true)
try fm.createDirectory(at: oneDriveFolderRaw, withIntermediateDirectories: true)
defer { try? fm.removeItem(at: oneDriveFolderRaw) }
// FileManager's directory enumeration (inside the real ReturnWatcher/AppSupportPaths
// call sites this test exercises) can canonicalize /var -> /private/var for a path
// that actually exists; resolve here so every comparison below agrees.
let oneDriveFolder = oneDriveFolderRaw.resolvingSymlinksInPath()
let appSupportRoot = fm.temporaryDirectory
.appendingPathComponent("shotdeck-real-wiring-approot-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: appSupportRoot) }
TransportSettings.setTransport(.oneDrive, defaults: defaults)
TransportSettings.setOneDriveFolder(oneDriveFolder, defaults: defaults)
// Best-effort: keeps AppModel.bootstrap()'s real update-check schedule (a real
// HTTP GET after 10s, plus a RunLoop timer) from starting during this test.
// ProcessInfo.processInfo.environment on Darwin reads `environ` fresh each call,
// so a setenv() here is visible to bootstrap()'s own check immediately.
setenv("SHOTDECK_ONEDRIVE_SELFTEST", "1", 1)
defer { unsetenv("SHOTDECK_ONEDRIVE_SELFTEST") }
// The REAL, unmodified call sites — not a reimplementation. This is exactly what
// launching Redline with OneDrive as the persisted transport does.
let model = AppDelegate.makeLaunchModel(appSupportRoot: appSupportRoot)
// bootstrap() registers a REAL, process-wide Carbon global hotkey (capture combo,
// e.g. Option-Shift-2). Carbon registrations are not scoped to this test/model —
// they must be released before this test ends, or ShotdeckCoreTests'
// HotkeyCenterCarbonTests (a separate test target, same test process) can find the
// combo already taken / the global hotkey table in an unexpected state.
defer { model.hotkeys.unregisterAll() }
// PRE-bootstrap assertions — this is the actual proof of the launch RESOLVER
// (AppDelegate.makeLaunchModel() -> TransportSettings.resolvedAppSupportPaths()),
// independent of bootstrap()'s own reconcile. `model.watchFolderURL` alone does
// NOT prove this: AppModel.init computes it separately via
// TransportSettings.effectiveFolders(), so it would read as correct even if
// makeLaunchModel's `paths` were built by the AirDrop-only resolver — which is
// exactly how the first version of this test was empirically shown to be vacuous
// for the launch-resolver path (see this commit's message). `model.paths` is
// `internal` on AppModel, so @testable import already exposes it without any
// production API change; `currentWatchFolder` is the one new (internal-facing,
// `public` on the actor) seam added to ReturnWatcher for this purpose.
#expect(model.paths.watchFolder.path == oneDriveFolder.path)
#expect(model.paths.outbox.path == oneDriveFolder.path)
let seededWatchFolder = await model.watcher.currentWatchFolder
#expect(seededWatchFolder.path == oneDriveFolder.path)
#expect(model.transport == .oneDrive)
#expect(model.watchFolderURL.path == oneDriveFolder.path)
await model.bootstrap()
// Drop a marked-up Redline PDF into the folder in place — what OneDrive syncing
// down an already-marked copy after a relaunch looks like.
let pdfURL = oneDriveFolder.appendingPathComponent("Redline-realwiring-\(UUID().uuidString).pdf")
let document = PDFDocument()
let page = PDFPage()
page.setBounds(CGRect(x: 0, y: 0, width: 612, height: 792), for: .mediaBox)
document.insert(page, at: 0)
document.documentAttributes = [
PDFDocumentAttribute.creatorAttribute: "Redline",
PDFDocumentAttribute.subjectAttribute: UUID().uuidString,
]
let ink = PDFAnnotation(
bounds: CGRect(x: 20, y: 20, width: 60, height: 60), forType: .ink, withProperties: nil
)
let stroke = NSBezierPath()
stroke.move(to: NSPoint(x: 20, y: 20))
stroke.line(to: NSPoint(x: 80, y: 80))
ink.add(stroke)
page.addAnnotation(ink)
let written = document.write(to: pdfURL)
#expect(written)
guard written else { return }
// .resolvingSymlinksInPath().path — not plain URL equality — matching how the rest
// of the suite compares a temp-dir-derived expected URL against a returned one.
let expectedPath = pdfURL.resolvingSymlinksInPath().path
let found = try await model.watcher.scanNow()
#expect(found.first(where: { $0.fileURL.resolvingSymlinksInPath().path == expectedPath })?.isCommented == true)
let commented = try await model.ledger.commented()
#expect(commented.contains(where: { $0.fileURL.resolvingSymlinksInPath().path == expectedPath }))
await model.watcher.stop()
}
@@ -0,0 +1,345 @@
import AppKit
import CoreGraphics
import Foundation
import ImageIO
import Testing
import ShotdeckCore
@testable import Shotdeck
/// Through the REAL app-target seams the menu rows invoke (`AppModel` actions +
/// `SpoolStore`): "Start new session" keeps the current screenshots as a past session,
/// the Past sessions state reflects what was sent, every session is kept by default,
/// and a chosen age limit is what removes one. `bootstrap()` itself is covered by
/// LaunchWiringTests; here `addCapture` refreshes the session from the store exactly
/// the way `AppModel.captureNow()` does after a real capture.
@MainActor
@Test("Menu actions: start new session keeps captures and lists past submissions")
func startNewSessionKeepsCapturesAndListsPastSessions() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
// Two captures in the open session, then the menu's "Start new session".
let c1 = try await addCapture(to: model, red: 1, green: 0, blue: 0)
let c2 = try await addCapture(to: model, red: 0, green: 1, blue: 0)
let closedID = model.session.id
#expect(model.canStartNewSession)
await model.startNewSession()
// The fresh session is active and the captures are kept as a past session.
#expect(model.session.id != closedID)
#expect(model.session.isEmpty)
#expect(!model.canStartNewSession)
#expect(model.pastSessions.map(\.id) == [closedID])
#expect(model.pastSessions.first?.captures.map(\.id) == [c1.id, c2.id])
#expect(model.pastSessions.first?.pdfFileName == nil) // never sent
#expect(model.statusLine?.contains("kept as a past session") == true)
// Nothing was deleted on close: both PNGs live in the single archive folder.
let archiveDir = model.paths.archiveDirectory(closedID)
for capture in [c1, c2] {
#expect(fm.fileExists(atPath: archiveDir.appendingPathComponent(capture.fileName).path))
}
// "PDF" on a never-sent row: visible missing state, no silent substitute.
#expect(model.sentPDFURL(for: model.pastSessions[0]) == nil)
model.revealSentPDF(model.pastSessions[0])
#expect(model.statusLine == "That session was never sent.")
}
@MainActor
@Test("Retention: 12 sessions through the menu action are all kept by default")
func twelveSessionsStayOnDiskByDefault() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
var closedIDs: [UUID] = []
for _ in 0..<12 {
_ = try await addCapture(to: model, red: 0.2, green: 0.2, blue: 0.2)
closedIDs.append(model.session.id)
await model.startNewSession()
}
#expect(model.retention == .never)
#expect(model.pastSessions.map(\.id) == closedIDs.reversed())
let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil)
let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil }
#expect(sessionDirs.count == closedIDs.count)
for id in closedIDs {
#expect(fm.fileExists(atPath: model.paths.archiveDirectory(id).path))
}
#expect(model.expiredSessionCount == 0)
}
@MainActor
@Test("A review detail typed in the panel is saved and inherited by the next session")
func reviewDetailsPersistThroughTheModel() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
let context = ReviewContext(
lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4",
reviewer: "Ben Hippler", note: "checkout")
await model.setContextField(context)
#expect(model.session.context == context)
#expect(model.sessionContext.summaryLine == "dev03 · v1.4.2 · a1b2c3d4 · Ben Hippler")
#expect(model.nextPDFFileNameHint.contains("-DEV03-"))
_ = try await addCapture(to: model, red: 0.1, green: 0.4, blue: 0.9)
await model.startNewSession()
// The closed session keeps its details; the new one inherits them.
#expect(model.pastSessions.first?.context == context)
#expect(model.session.context == context)
}
@MainActor
@Test("Settings age limit: cleanup removes only expired sessions, never a sent PDF")
func cleanUpHonorsTheAgeLimit() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let suite = try makeIsolatedDefaults()
defer { suite.defaults.removePersistentDomain(forName: suite.name) }
let model = AppDelegate.makeLaunchModel(
appSupportRoot: root, retentionDefaults: suite.defaults)
await model.bootstrap()
// One real session that was sent (its PDF is in the outbox) …
_ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2)
let sentName = "Redline-20261001-0900-A1B2C3D4.pdf"
_ = try await model.spool.archiveCurrent(pdfFileName: sentName)
try Data("%PDF-1.4\n% test\n".utf8)
.write(to: model.paths.outbox.appendingPathComponent(sentName))
// … and one archived session backdated past the limit, written in the exact shape
// production writes, so the age comparison runs against real manifest dates.
let expiredID = try await writeBackdatedSession(in: model.paths, daysAgo: 40)
await model.reloadFromSpool()
#expect(model.pastSessions.count == 2)
// Nothing expires under .never, even with a cleanup.
await model.cleanUpExpiredSessions()
#expect(model.pastSessions.count == 2)
#expect(model.expiredSessionCount == 0)
#expect(model.statusLine?.contains("Nothing to remove") == true)
// A 30-day limit expires only the backdated session, and says so before deleting.
await model.setRetention(.days(30))
#expect(model.retention == .days(30))
#expect(RetentionSettings.load(defaults: suite.defaults) == .days(30))
#expect(model.expiredSessionCount == 1)
await model.cleanUpExpiredSessions()
#expect(model.pastSessions.count == 1)
#expect(model.statusLine?.contains("Removed 1 past session") == true)
#expect(!fm.fileExists(atPath: model.paths.archiveDirectory(expiredID).path))
#expect(fm.fileExists(atPath: model.paths.outbox.appendingPathComponent(sentName).path))
// Back to the default in this isolated suite, so the next test starts clean.
await model.setRetention(.never)
#expect(model.expiredSessionCount == 0)
}
@MainActor
@Test("Menu action on an empty session reports it started without inventing a past session")
func startNewSessionOnEmptySessionCreatesNoPastSession() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
#expect(model.session.isEmpty)
await model.startNewSession()
#expect(model.session.isEmpty)
#expect(model.pastSessions.isEmpty)
#expect(model.statusLine == "New session started.")
}
@MainActor
@Test("Send seam refreshes past submissions after archiving (menu count stays true)")
func successfulSendRefreshesPastSubmissions() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
_ = try await addCapture(to: model, red: 0.4, green: 0.4, blue: 0.4)
await model.handleDidShareItems(
fileName: "Redline-20261011-120000.pdf", sentSummary: "Sent — 1 page.")
#expect(model.statusLine == "Sent — 1 page.")
#expect(model.session.isEmpty)
#expect(model.pastSessions.count == 1)
#expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120000.pdf")
#expect(model.pastSessions.first?.captures.count == 1)
}
@MainActor
@Test("Start new session and send refuse to overlap (no mid-flight session close)")
func sessionStartAndSendRefuseToOverlap() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
let capture = try await addCapture(to: model, red: 0.1, green: 0.1, blue: 0.1)
let before = model.session.id
// A send in flight: "Start new session" must refuse instead of renaming the
// session directory out from under the compose.
model.setSending(true)
await model.startNewSession()
#expect(model.session.id == before)
#expect(model.session.captures.map(\.id) == [capture.id])
#expect(model.statusLine == "Finish the current send first.")
model.setSending(false)
// A session start in flight: send must refuse before composing anything.
model.setStartingNewSession(true)
await model.send(anchor: nil)
#expect(model.statusLine == "Finish starting the new session first.")
#expect(model.session.id == before)
#expect(model.session.captures.map(\.id) == [capture.id])
model.setStartingNewSession(false)
// Both settled: the normal path still works.
await model.startNewSession()
#expect(model.session.id != before)
#expect(model.pastSessions.count == 1)
#expect(model.pastSessions.first?.captures.map(\.id) == [capture.id])
}
@MainActor
@Test("The OneDrive send summary survives archiving (never overwritten by the archive path)")
func oneDriveSendSummarySurvivesArchiving() async throws {
let fm = FileManager.default
let root = fm.temporaryDirectory
.appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: root) }
let model = AppDelegate.makeLaunchModel(appSupportRoot: root)
_ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2)
let summary = "Saved to OneDrive — 1 page. Open it in Files on your iPad."
await model.handleDidShareItems(fileName: "Redline-20261011-120100.pdf", sentSummary: summary)
#expect(model.statusLine == summary)
#expect(model.pastSessions.count == 1)
#expect(model.pastSessions.first?.pdfFileName == "Redline-20261011-120100.pdf")
}
// MARK: - Fixtures
/// Appends one generated PNG through the store and refreshes `model.session` from
/// it — the same refresh `AppModel.captureNow()` performs after a real capture.
@MainActor
private func addCapture(
to model: AppModel,
red: CGFloat,
green: CGFloat,
blue: CGFloat
) async throws -> Capture {
let capture = try await model.spool.append(
pngData: try makePNGData(width: 8, height: 8, red: red, green: green, blue: blue),
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: Date())
model.replaceSession(try await model.spool.currentSession())
return capture
}
private enum FixtureError: Error {
case pngGenerationFailed
}
// MARK: - Fixtures
private struct IsolatedDefaults {
let name: String
let defaults: UserDefaults
}
/// A throwaway UserDefaults suite — never `.standard` — so the age-limit setting a
/// test writes can never change Ben's real app preference.
private func makeIsolatedDefaults() throws -> IsolatedDefaults {
let name = "shotdeck-session-workflow-\(UUID().uuidString)"
guard let defaults = UserDefaults(suiteName: name) else {
throw FixtureError.pngGenerationFailed
}
defaults.removePersistentDomain(forName: name)
return IsolatedDefaults(name: name, defaults: defaults)
}
/// Writes an archived session folder dated `daysAgo` days in the past, in the exact
/// on-disk shape the store produces, so an age policy can act on a real manifest date.
@discardableResult
private func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) async throws -> UUID {
let id = UUID()
let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400)
let dir = paths.archiveDirectory(id)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png"
try makePNGData(width: 8, height: 8, red: 0.3, green: 0.3, blue: 0.3)
.write(to: dir.appendingPathComponent(pngName))
let capture = Capture(
id: UUID(), sequence: 1, fileName: pngName,
pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: createdAt)
let session = CaptureSession(
id: id, createdAt: createdAt, state: .archived, captures: [capture],
pdfFileName: nil,
context: ReviewContext(lane: "DEV03", deployedVersion: "v1.0.0", commit: "abc1234"))
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
try encoder.encode(session).write(to: dir.appendingPathComponent("session.json"))
return id
}
private func makePNGData(
width: Int,
height: Int,
red: CGFloat,
green: CGFloat,
blue: CGFloat
) throws -> Data {
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
) else {
throw FixtureError.pngGenerationFailed
}
context.setFillColor(red: red, green: green, blue: blue, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let image = context.makeImage() else {
throw FixtureError.pngGenerationFailed
}
let buffer = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(buffer, "public.png" as CFString, 1, nil) else {
throw FixtureError.pngGenerationFailed
}
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
throw FixtureError.pngGenerationFailed
}
return buffer as Data
}
@@ -0,0 +1,118 @@
import Foundation
import Testing
@testable import Shotdeck
@testable import ShotdeckCore
@Test("DubaiTime.checkTime formats as HH:MM Dubai")
func dubaiTimeCheckTimeFormat() {
let now = Date()
let result = DubaiTime.checkTime(now)
// Dubai timezone format: HH:MM Dubai
let pattern = "^[0-9]{2}:[0-9]{2} Dubai$"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(result.startIndex..<result.endIndex, in: result)
let matches = regex?.matches(in: result, options: [], range: range) ?? []
#expect(!matches.isEmpty, "checkTime should format as HH:MM Dubai, got: \(result)")
}
@Test("Status message: up-to-date manual check includes Dubai timestamp")
@MainActor
func manualCheckUpToDateIncludesTimestamp() async {
let checker = UpdateChecker()
// Inject a stub appcast showing the current version (no update available)
let currentVersion = UpdateChecker.currentVersion()
let stubAppcast = """
{
"version": "\(currentVersion)",
"zipURL": "https://example.com/dummy.zip",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000"
}
"""
checker.testAppcastJSON = stubAppcast
// Capture the status message
var capturedStatus: String?
checker.onChecked = {
capturedStatus = checker.statusMessage
}
// Run the manual check
await checker.checkNow(manual: true)
// Verify the message matches the expected format and includes a timestamp
guard let status = capturedStatus else {
#expect(false, "statusMessage should not be nil for manual check finding no update")
return
}
// Message should be "Redline X.Y.Z is up to date, checked HH:MM Dubai"
let pattern = "^Redline [0-9]+\\.[0-9]+\\.[0-9]+ is up to date, checked [0-9]{2}:[0-9]{2} Dubai$"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(status.startIndex..<status.endIndex, in: status)
let matches = regex?.matches(in: status, options: [], range: range) ?? []
#expect(!matches.isEmpty, "Manual check up-to-date message should match format, got: \(status)")
}
@Test("Status message: automatic check doesn't set message when up-to-date")
@MainActor
func automaticCheckUpToDateLeavesMessageNil() async {
let checker = UpdateChecker()
// Inject a stub appcast showing the current version (no update available)
let currentVersion = UpdateChecker.currentVersion()
let stubAppcast = """
{
"version": "\(currentVersion)",
"zipURL": "https://example.com/dummy.zip",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000"
}
"""
checker.testAppcastJSON = stubAppcast
// Capture the status message
var capturedStatus: String?
checker.onChecked = {
capturedStatus = checker.statusMessage
}
// Run an AUTOMATIC check (manual: false)
await checker.checkNow(manual: false)
// For automatic checks finding no update, statusMessage should be nil
#expect(capturedStatus == nil,
"Automatic check finding no update should leave statusMessage nil, got: \(capturedStatus ?? "(nil)")")
}
@Test("Update status and general status are independent channels")
@MainActor
func statusChannelsAreIndependent() async throws {
let fm = FileManager.default
let appSupportRoot = fm.temporaryDirectory
.appendingPathComponent("update-checker-channel-test-\(UUID().uuidString)", isDirectory: true)
defer { try? fm.removeItem(at: appSupportRoot) }
// Create a real AppModel using the standard launch pattern
let model = AppDelegate.makeLaunchModel(appSupportRoot: appSupportRoot)
defer { model.hotkeys.unregisterAll() }
// Test 1: Setting statusLine should NOT affect updateStatusMessage
model.setStatus("General status: captured 3")
#expect(model.statusLine == "General status: captured 3", "statusLine should be set")
#expect(model.updateStatusMessage == nil, "updateStatusMessage should remain nil")
// Test 2: Setting updateStatus should NOT affect statusLine
model.setUpdateStatus("Update to 9.9.9 is ready")
#expect(model.statusLine == "General status: captured 3", "statusLine should remain unchanged")
#expect(model.updateStatusMessage == "Update to 9.9.9 is ready", "updateStatusMessage should be set")
// Test 3: Clearing statusLine leaves updateStatus intact
model.setStatus(nil)
#expect(model.statusLine == nil, "statusLine should be cleared")
#expect(model.updateStatusMessage == "Update to 9.9.9 is ready", "updateStatusMessage should persist")
// Test 4: Clearing updateStatus leaves other state unaffected
model.setUpdateStatus(nil)
#expect(model.updateStatusMessage == nil, "updateStatusMessage should be cleared")
}
+343
View File
@@ -0,0 +1,343 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Redline UX v2</title>
<meta name="description" content="Redline v2: capture decision first, one Settings entry point, capture scopes (area, window, browser, screen), automatic updates, no filler text. Light and dark at 1:1.">
<style>
:root{--page:#e9e7e2;--ink:#1d1d1f;--mut:rgba(0,0,0,.56);--rule:rgba(0,0,0,.12);--acc:#0a64d6}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--page:#141416;--ink:#ececec;--mut:rgba(255,255,255,.6);--rule:rgba(255,255,255,.12);--acc:#5ea3ff}}
:root[data-theme="dark"]{--page:#141416;--ink:#ececec;--mut:rgba(255,255,255,.6);--rule:rgba(255,255,255,.12);--acc:#5ea3ff}
body{margin:0;background:var(--page);color:var(--ink);font:13px/1.45 -apple-system,BlinkMacSystemFont,"SF Pro Text","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased}
header.board{padding:32px 40px 6px;max-width:1180px}
header.board h1{margin:0 0 6px;font-size:22px;font-weight:600}
header.board p{margin:0;color:var(--mut);max-width:780px}
section.turn{padding:26px 40px 34px;border-top:1px solid var(--rule)}
.thd{display:flex;gap:10px;align-items:baseline;margin:0 0 16px;flex-wrap:wrap}
.tid{font:600 10px ui-monospace,Menlo,monospace;padding:3px 7px;background:var(--ink);color:var(--page)}
.tname{font-weight:600}.tnote{color:var(--mut);font-size:12px}
.row{display:flex;flex-wrap:wrap;gap:32px;align-items:flex-start}
.opt{display:flex;flex-direction:column;gap:8px;max-width:100%}
.olabel{font-size:12px;color:var(--mut)}
.notes{margin:12px 0 0;padding-left:18px;color:var(--mut);max-width:560px;font-size:12.5px}
.notes li{margin:3px 0}
.scroller{max-width:100%;overflow-x:auto;padding:2px 2px 14px}
@media (max-width:600px){header.board,section.turn{padding-left:16px;padding-right:16px}}
/* macOS tokens per mock */
.mac{--win:#ececec;--content:#fff;--side:#e8e8e8;--label:rgba(0,0,0,.88);--label2:rgba(0,0,0,.62);--label3:rgba(0,0,0,.5);--sep:rgba(0,0,0,.1);
--ctl:#fff;--ctlB:rgba(0,0,0,.16);--fill:rgba(0,0,0,.05);--fill2:rgba(0,0,0,.09);--accent:#0a64d6;--accentText:#fff;--seg:#e3e3e3;--segOn:#fff;
--pop:rgba(246,246,246,.97);--group:#fff;--groupB:rgba(0,0,0,.08);--orange:#c45a00;--green:#248a3d;--tA:#d9ded9;--tB:#c9d3e1;--tC:#e3d6cc;
--shadow:0 0 0 .5px rgba(0,0,0,.22),0 18px 48px rgba(0,0,0,.22),0 4px 10px rgba(0,0,0,.08);
color:var(--label);font:13px/1.35 -apple-system,BlinkMacSystemFont,"SF Pro Text","Helvetica Neue",sans-serif;letter-spacing:-.003em}
.mac.dark{--win:#2a2a2c;--content:#1e1e1e;--side:#2b2a2e;--label:rgba(255,255,255,.88);--label2:rgba(255,255,255,.66);--label3:rgba(255,255,255,.5);--sep:rgba(255,255,255,.1);
--ctl:#5c5c60;--ctlB:rgba(255,255,255,.08);--fill:rgba(255,255,255,.06);--fill2:rgba(255,255,255,.11);--accent:#0a7cff;--seg:#3a3a3c;--segOn:#6a6a6e;
--pop:rgba(40,40,42,.97);--group:#2c2c2e;--groupB:rgba(255,255,255,.07);--orange:#ff9f0a;--green:#32d74b;--tA:#3b423d;--tB:#3a4352;--tC:#4b4036;
--shadow:0 0 0 .5px rgba(255,255,255,.12),0 18px 48px rgba(0,0,0,.6)}
.desk{background:linear-gradient(#cfd6de,#bcc6d0);padding:0 14px 22px;border-radius:2px}
.desk.dark{background:linear-gradient(#22262c,#191b1f)}
.mbar{height:24px;display:flex;justify-content:flex-end;align-items:center;gap:12px;font-size:13px;color:rgba(0,0,0,.85);padding:0 4px}
.desk.dark .mbar{color:rgba(255,255,255,.85)}
.mbar .icon{display:inline-flex;align-items:center;gap:3px;padding:1px 6px;border-radius:4px;background:rgba(0,0,0,.14);font-weight:600;font-size:12px}
.desk.dark .mbar .icon{background:rgba(255,255,255,.18)}
.pop{width:340px;background:var(--pop);border-radius:12px;box-shadow:var(--shadow);margin-left:auto;padding:10px;display:flex;flex-direction:column;gap:9px;backdrop-filter:blur(20px)}
.hrow{display:flex;align-items:center;gap:6px}
.sp{flex:1}
.tt{font-weight:600;font-size:13px}
.t2{color:var(--label2);font-size:11px}
.t3{color:var(--label3);font-size:11px}
.badge{font-size:11px;color:var(--label2);background:var(--fill2);border-radius:9px;padding:1px 7px}
.ib{width:22px;height:22px;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;color:var(--label2)}
.ib:hover{background:var(--fill2)}
.ib svg,.btn svg,.seg svg,.mi svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:5px;height:24px;padding:0 10px;border-radius:6px;background:var(--ctl);border:.5px solid var(--ctlB);box-shadow:0 .5px 1px rgba(0,0,0,.12);font-size:12.5px;color:var(--label);white-space:nowrap}
.btn.p{background:var(--accent);color:var(--accentText);border-color:transparent}
.btn.dis{opacity:.55}
.btn.w{flex:1}
.btn kbd{font:11px -apple-system;color:inherit;opacity:.6}
.btn.big{height:28px}
.seg{display:flex;background:var(--seg);border-radius:7px;padding:2px;gap:2px}
.seg span{flex:1;display:flex;align-items:center;justify-content:center;gap:4px;height:22px;border-radius:5px;font-size:11.5px;color:var(--label)}
.seg span.on{background:var(--segOn);box-shadow:0 .5px 1.5px rgba(0,0,0,.2);font-weight:600}
.capbox{background:var(--fill);border-radius:8px;padding:8px;display:flex;flex-direction:column;gap:7px}
.tgt{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--label2)}
.tgt b{color:var(--label);font-weight:500}
.lnk{color:var(--accent);font-size:11.5px}
.thumbs{display:flex;gap:6px}
.th{flex:1;height:58px;border-radius:4px;position:relative;border:.5px solid var(--sep)}
.th i{position:absolute;left:3px;top:3px;font:700 9px -apple-system;color:#fff;background:rgba(0,0,0,.65);padding:1px 4px;border-radius:2px;font-style:normal}
.th.a{background:var(--tA)}.th.b{background:var(--tB)}.th.c{background:var(--tC)}
.th.more{display:flex;align-items:center;justify-content:center;flex:0 0 46px;background:var(--fill);font-size:11px;color:var(--label2);font-weight:600}
.empty{height:58px;border-radius:6px;background:var(--fill);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px}
.status{font-size:11.5px;display:flex;gap:6px;align-items:center}
.dot{width:7px;height:7px;border-radius:50%;background:var(--orange)}
.dot.g{background:var(--green)}
.sep{height:1px;background:var(--sep);margin:0 -10px}
.menu{background:var(--pop);border-radius:8px;box-shadow:var(--shadow);padding:5px;width:236px;font-size:13px}
.mi{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:5px;color:var(--label)}
.mi.on{background:var(--accent);color:#fff}
.mi.on .t3,.mi.on kbd{color:rgba(255,255,255,.8)}
.mi kbd{margin-left:auto;font:12px -apple-system;color:var(--label3)}
.mi .chk{width:12px;text-align:center}
.msep{height:1px;background:var(--sep);margin:4px 6px}
.mhead{font-size:11px;color:var(--label3);padding:3px 8px;font-weight:600}
/* window */
.win{border-radius:10px;box-shadow:var(--shadow);overflow:hidden;background:var(--content);width:880px}
.tb{display:flex;align-items:center;gap:8px;height:52px;padding:0 12px;background:var(--win);border-bottom:.5px solid var(--sep)}
.lights{display:flex;gap:8px;margin-right:6px}.lights i{width:12px;height:12px;border-radius:50%;background:#ff5f57}.lights i:nth-child(2){background:#febc2e}.lights i:nth-child(3){background:#28c840}
.wbody{display:flex;height:150px}
.side{width:200px;background:var(--side);border-right:.5px solid var(--sep);padding:8px;font-size:12px}
.srow{padding:5px 7px;border-radius:6px}.srow.on{background:var(--fill2)}
.main{flex:1;padding:12px 14px;display:flex;gap:10px}
/* settings */
.sw{width:460px;border-radius:10px;box-shadow:var(--shadow);overflow:hidden;background:var(--win)}
.stb{height:28px;display:flex;align-items:center;justify-content:center;font-weight:600;font-size:13px;position:relative;color:var(--label)}
.stb .lights{position:absolute;left:10px}
.sbody{padding:4px 18px 16px}
.sh{font-size:12px;font-weight:600;color:var(--label2);margin:12px 4px 5px}
.grp{background:var(--group);border:.5px solid var(--groupB);border-radius:8px}
.sr{display:flex;align-items:center;gap:8px;padding:7px 10px;min-height:22px;border-top:.5px solid var(--sep)}
.sr:first-child{border-top:none}
.sr .k{flex:1}
.sr .v{color:var(--label2);font-size:12px}
.pop2{display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 6px 0 9px;border-radius:5px;background:var(--ctl);border:.5px solid var(--ctlB);font-size:12px}
.pop2 i{width:14px;height:16px;border-radius:4px;background:var(--accent);display:inline-block}
.sw2{width:30px;height:18px;border-radius:9px;background:var(--accent);position:relative}
.sw2::after{content:"";position:absolute;right:2px;top:2px;width:14px;height:14px;border-radius:50%;background:#fff}
.sw2.off{background:var(--fill2)}.sw2.off::after{left:2px;right:auto}
.cap{font-size:11px;color:var(--label3);margin:6px 4px 0;line-height:1.4}
.sfoot{display:flex;justify-content:space-between;align-items:center;margin-top:14px}
.spec{max-width:1060px}
.spec h2.sh2{font-size:14px;margin:18px 0 6px}
.spec table{border-collapse:collapse;width:100%;font-size:12.5px}
.spec td,.spec th{border-bottom:1px solid var(--rule);padding:6px 8px;text-align:left;vertical-align:top}
.spec th{color:var(--mut);font-weight:600}
.spec code{font:12px ui-monospace,Menlo,monospace}
.spec p{max-width:820px}
</style>
</head>
<body>
<header class="board">
<h1>Redline v2 — decide what you capture first</h1>
<p>The popover now starts with the capture decision (what, and where), then the pages, then the two verbs. Settings has one visible door: the gear in the popover header. Filler lines are gone; a status line appears only when something happened. Updates install themselves.</p>
</header>
<svg width="0" height="0" style="position:absolute">
<symbol id="gear" viewBox="0 0 16 16"><circle cx="8" cy="8" r="2.3"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/></symbol>
<symbol id="area" viewBox="0 0 16 16"><path d="M2 5V2h3M11 2h3v3M14 11v3h-3M5 14H2v-3"/></symbol>
<symbol id="window" viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M2 6h12"/></symbol>
<symbol id="browser" viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M2 6h12M4.5 4.5h.01M6.5 4.5h.01"/></symbol>
<symbol id="screen" viewBox="0 0 16 16"><rect x="1.5" y="2.5" width="13" height="9" rx="1"/><path d="M6 14h4M8 11.5V14"/></symbol>
<symbol id="send" viewBox="0 0 16 16"><path d="M14 2 7 9M14 2l-4.5 12L7 9 2 6.5z"/></symbol>
<symbol id="plus" viewBox="0 0 16 16"><path d="M8 3v10M3 8h10"/></symbol>
<symbol id="chev" viewBox="0 0 16 16"><path d="m5 6 3 3 3-3"/></symbol>
<symbol id="win2" viewBox="0 0 16 16"><rect x="2" y="2.5" width="12" height="11" rx="1.5"/><path d="M6 2.5v11"/></symbol>
</svg>
<!-- ===================== 1 POPOVER ===================== -->
<section class="turn" id="t1">
<div class="thd"><a class="tid" href="#t1">1</a><span class="tname">Menu-bar popover</span><span class="tnote">340 pt · controlSize small · capture decision → pages → verbs</span></div>
<div class="scroller"><div class="row">
<div class="opt"><div class="olabel">1a · Idle, empty session · light</div>
<div class="desk"><div class="mbar"><span class="icon">◫</span><span>Sat 31 Oct 13:05</span></div>
<div class="mac pop" role="dialog" aria-label="Redline">
<div class="hrow"><div><div class="tt">DEV03 · v1.4.2 (41)</div><div class="t2">a1b2c3d4 · Ben Hippler</div></div><span class="sp"></span>
<span class="ib" title="Edit review details" aria-label="Edit review details"><svg><use href="#win2"/></svg></span>
<span class="ib" title="Settings (⌘,)" aria-label="Settings"><svg><use href="#gear"/></svg></span></div>
<div class="capbox">
<div class="seg" role="radiogroup" aria-label="Capture"><span class="on"><svg><use href="#area"/></svg>Area</span><span><svg><use href="#window"/></svg>Window</span><span><svg><use href="#browser"/></svg>Browser</span><span><svg><use href="#screen"/></svg>Screen</span></div>
<div class="tgt"><b>800 × 600</b> on Display 1<span class="sp"></span><span class="lnk">Choose Area…</span></div>
</div>
<div class="empty"><div style="font-size:12px;color:var(--label2)">No pages yet</div><div class="t3">⌥⇧2 captures the area</div></div>
<div class="hrow"><span class="btn w big"><svg><use href="#area"/></svg>Capture <kbd>⌥⇧2</kbd></span><span class="btn w big p dis"><svg><use href="#send"/></svg>Send</span></div>
<div class="hrow"><span class="btn w dis"><svg><use href="#plus"/></svg>New Session…</span><span class="btn w"><svg><use href="#win2"/></svg>Open Redline</span></div>
</div></div>
<ul class="notes"><li>Header has exactly two icons: details (opens the window on Lane) and <b>Settings</b>. No “…” menu.</li><li>The capture box is the first decision on screen; Choose Area… is always one click away.</li><li>No footer. Nothing is printed unless it is news.</li></ul>
</div>
<div class="opt"><div class="olabel">1b · Pages present + one return · dark</div>
<div class="desk dark"><div class="mbar"><span class="icon">◫ 3</span><span>Sat 31 Oct 13:05</span></div>
<div class="mac dark pop" role="dialog" aria-label="Redline">
<div class="hrow"><div><div class="tt">DEV03 · v1.4.2 (41)</div><div class="t2">a1b2c3d4 · Ben Hippler · 3 pages</div></div><span class="sp"></span>
<span class="ib" aria-label="Edit review details"><svg><use href="#win2"/></svg></span><span class="ib" aria-label="Settings"><svg><use href="#gear"/></svg></span></div>
<div class="capbox">
<div class="seg"><span><svg><use href="#area"/></svg>Area</span><span class="on"><svg><use href="#window"/></svg>Window</span><span><svg><use href="#browser"/></svg>Browser</span><span><svg><use href="#screen"/></svg>Screen</span></div>
<div class="tgt">Front window when you press ⌥⇧2<span class="sp"></span><span class="t3">area kept: 800 × 600</span></div>
</div>
<div class="thumbs"><div class="th a"><i>1</i></div><div class="th b"><i>2</i></div><div class="th c"><i>3</i></div></div>
<div class="status"><span class="dot"></span>OMS test lane came back · 2 pages marked<span class="sp"></span><span class="lnk">Open</span></div>
<div class="hrow"><span class="btn w big"><svg><use href="#window"/></svg>Capture <kbd>⌥⇧2</kbd></span><span class="btn w big p"><svg><use href="#send"/></svg>Send 3 pages</span></div>
<div class="hrow"><span class="btn w"><svg><use href="#plus"/></svg>New Session…</span><span class="btn w"><svg><use href="#win2"/></svg>Open Redline</span></div>
</div></div>
<ul class="notes"><li>The Capture button wears the scope icon, so what ⌥⇧2 will grab is never ambiguous.</li><li>Choosing a non-area scope keeps the saved area (“area kept”) — switching back to Area restores it.</li></ul>
</div>
<div class="opt"><div class="olabel">1c · New Session… — the capture decision at the moment of starting · light</div>
<div class="desk"><div class="mbar"><span class="icon">◫ 3</span><span>Sat 31 Oct 13:06</span></div>
<div class="mac pop" role="dialog" aria-label="Start a new session">
<div class="hrow"><div><div class="tt">New session</div><div class="t2">The current 3 pages are kept as a past session.</div></div></div>
<div class="capbox">
<div class="t2" style="font-weight:600;color:var(--label)">Capture</div>
<div class="seg"><span class="on"><svg><use href="#area"/></svg>Area</span><span><svg><use href="#window"/></svg>Window</span><span><svg><use href="#browser"/></svg>Browser</span><span><svg><use href="#screen"/></svg>Screen</span></div>
<div class="tgt"><b>800 × 600</b> on Display 1<span class="sp"></span><span class="lnk">Choose Area…</span></div>
</div>
<div class="capbox">
<div class="t2" style="font-weight:600;color:var(--label)">Review details</div>
<div class="tgt">DEV03 · v1.4.2 (41) · a1b2c3d4 · Ben Hippler<span class="sp"></span><span class="lnk">Edit…</span></div>
</div>
<div class="hrow"><span class="sp"></span><span class="btn">Cancel</span><span class="btn p">Start Session</span></div>
</div></div>
<ul class="notes"><li>New Session… never starts silently: it shows scope, area and inherited details in place of the pages, with Start Session as the default button (Return).</li><li>Choose Area… here dismisses the popover, runs the picker, and comes back to this step with the new size.</li></ul>
</div>
<div class="opt"><div class="olabel">1d · Capture-scope menu from the keyboard (⌥⇧1) · dark</div>
<div class="desk dark" style="padding-bottom:30px"><div class="mbar"><span class="icon">◫</span><span>Sat 31 Oct 13:06</span></div>
<div class="mac dark menu" role="menu" aria-label="Capture" style="margin-left:auto">
<div class="mhead">Capture</div>
<div class="mi"><span class="chk">✓</span><svg><use href="#area"/></svg>Saved Area <span class="t3">800 × 600</span><kbd>1</kbd></div>
<div class="mi on"><span class="chk"></span><svg><use href="#window"/></svg>Front Window<kbd>2</kbd></div>
<div class="mi"><span class="chk"></span><svg><use href="#browser"/></svg>Browser Page<kbd>3</kbd></div>
<div class="mi"><span class="chk"></span><svg><use href="#screen"/></svg>Whole Screen<kbd>4</kbd></div>
<div class="msep"></div>
<div class="mi"><span class="chk"></span><svg><use href="#area"/></svg>Choose New Area…<kbd>A</kbd></div>
</div></div>
<ul class="notes"><li>⌥⇧1 opens this menu where the pointer is; one keystroke captures with that scope and makes it the session’s scope.</li><li>Browser Page grabs the front browser window’s page area (Safari, Chrome, Arc, Edge); the tab strip and toolbar are cropped.</li></ul>
</div>
<div class="opt"><div class="olabel">1e · Update installed in the background · light</div>
<div class="desk"><div class="mbar"><span class="icon">◫</span><span>Sat 31 Oct 13:07</span></div>
<div class="mac pop">
<div class="hrow"><div><div class="tt">DEV03 · v1.4.2 (41)</div><div class="t2">a1b2c3d4 · Ben Hippler</div></div><span class="sp"></span><span class="ib"><svg><use href="#win2"/></svg></span><span class="ib"><svg><use href="#gear"/></svg></span></div>
<div class="status"><span class="dot g"></span>Redline 0.6.0 is ready — restarts after you send<span class="sp"></span><span class="lnk">Restart Now</span></div>
<div class="hrow"><span class="btn w big"><svg><use href="#area"/></svg>Capture <kbd>⌥⇧2</kbd></span><span class="btn w big p"><svg><use href="#send"/></svg>Send 2 pages</span></div>
</div></div>
<ul class="notes"><li>One line, only while it matters. It never interrupts a session with unsent pages.</li><li>Cropped to the relevant part for this mock.</li></ul>
</div>
</div></div>
</section>
<!-- ===================== 2 WINDOW HEADER ===================== -->
<section class="turn" id="t2">
<div class="thd"><a class="tid" href="#t2">2</a><span class="tname">Redline window · header</span><span class="tnote">scope and area are part of the session, shown where the verbs are</span></div>
<div class="scroller"><div class="row">
<div class="opt"><div class="olabel">2a · Current session · light</div>
<div class="mac win">
<div class="tb"><div class="lights"><i></i><i></i><i></i></div>
<div><div class="tt" style="font-size:14px">DEV03 <span class="badge">Current</span></div><div class="t2">3 pages · not sent</div></div><span class="sp"></span>
<span class="pop2" aria-label="Capture scope"><svg style="width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:1.6"><use href="#area"/></svg>Area · 800 × 600<i></i></span>
<span class="btn">Choose Area…</span>
<span class="btn"><svg><use href="#area"/></svg>Capture</span>
<span class="btn"><svg><use href="#plus"/></svg>New Session…</span>
<span class="btn p"><svg><use href="#send"/></svg>Send 3 pages</span>
</div>
<div class="wbody"><div class="side"><div class="t3" style="margin:2px 6px 6px">Today</div><div class="srow on"><b>DEV03</b> <span class="t3">13:05</span><div class="t3">3 pages · not sent</div></div><div class="srow">OMS test lane <span class="t3">11:48</span><div class="t3" style="color:var(--orange)">2 pages marked</div></div></div>
<div class="main"><div class="th a" style="height:96px"><i>1</i></div><div class="th b" style="height:96px"><i>2</i></div><div class="th c" style="height:96px"><i>3</i></div></div></div>
</div>
<ul class="notes"><li>No gear here: Settings is ⌘, (and the popover gear) — one surface, one door.</li><li>Cropped to the header and a slice of the content for this mock.</li></ul>
</div>
<div class="opt"><div class="olabel">2b · Same, dark, Browser scope</div>
<div class="mac dark win" style="width:880px">
<div class="tb"><div class="lights"><i></i><i></i><i></i></div>
<div><div class="tt" style="font-size:14px">DEV03 <span class="badge">Current</span></div><div class="t2">3 pages · not sent</div></div><span class="sp"></span>
<span class="pop2"><svg style="width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:1.6"><use href="#browser"/></svg>Browser Page<i></i></span>
<span class="btn"><svg><use href="#browser"/></svg>Capture</span>
<span class="btn"><svg><use href="#plus"/></svg>New Session…</span>
<span class="btn p"><svg><use href="#send"/></svg>Send 3 pages</span>
</div>
</div>
<ul class="notes"><li>With a non-area scope, Choose Area… disappears from the header; it lives in the scope menu as “Choose New Area…”.</li></ul>
</div>
</div></div>
</section>
<!-- ===================== 3 SETTINGS ===================== -->
<section class="turn" id="t3">
<div class="thd"><a class="tid" href="#t3">3</a><span class="tname">Settings</span><span class="tnote">460 pt · one window, reached only from the popover gear or ⌘,</span></div>
<div class="scroller"><div class="row">
<div class="opt"><div class="olabel">3a · light</div>
<div class="mac sw">
<div class="stb"><div class="lights"><i></i><i></i><i></i></div>Redline Settings</div>
<div class="sbody">
<div class="sh">Capture</div>
<div class="grp">
<div class="sr"><span class="k">Capture</span><span class="pop2">Saved Area<i></i></span></div>
<div class="sr"><span class="k">Saved area</span><span class="v">800 × 600 on Display 1</span><span class="btn">Choose…</span></div>
<div class="sr"><span class="k">Capture shortcut</span><span class="btn">⌥⇧2</span></div>
<div class="sr"><span class="k">Capture menu shortcut</span><span class="btn">⌥⇧1</span></div>
<div class="sr"><span class="k">Ask what to capture on New Session</span><span class="sw2"></span></div>
</div>
<div class="sh">Sending</div>
<div class="grp">
<div class="sr"><span class="k">Send with</span><span class="seg" style="width:190px"><span class="on">AirDrop</span><span>OneDrive</span></span></div>
<div class="sr"><span class="k">Save PDFs to</span><span class="v">~/Desktop</span><span class="btn">Choose…</span></div>
<div class="sr"><span class="k">Watch for returns in</span><span class="v">~/Downloads</span><span class="btn">Choose…</span></div>
</div>
<div class="sh">Sessions</div>
<div class="grp">
<div class="sr"><span class="k">Delete sessions older than</span><span class="pop2">Never<i></i></span></div>
<div class="sr"><span class="k">20 sessions on this Mac</span><span class="btn dis">Clean Up Now…</span></div>
</div>
<div class="cap">Deleting removes Redline’s own screenshots only. PDFs you sent stay where they are.</div>
<div class="sh">Updates</div>
<div class="grp">
<div class="sr"><span class="k">Install updates automatically</span><span class="sw2"></span></div>
<div class="sr"><span class="k">Version 0.5.0 · checked 13:02</span><span class="btn">Check Now</span></div>
</div>
<div class="cap">Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.</div>
<div class="sfoot"><span class="t3">Redline 0.5.0</span><span class="btn">Quit Redline</span></div>
</div>
</div></div>
<div class="opt"><div class="olabel">3b · dark · update ready</div>
<div class="mac dark sw">
<div class="stb"><div class="lights"><i></i><i></i><i></i></div>Redline Settings</div>
<div class="sbody">
<div class="sh">Updates</div>
<div class="grp">
<div class="sr"><span class="k">Install updates automatically</span><span class="sw2"></span></div>
<div class="sr"><span class="k">0.6.0 downloaded · installs after your next send</span><span class="btn p">Restart Now</span></div>
</div>
<div class="cap">Turned off: Redline still checks every 6 hours and shows “Update to 0.6.0” here and in the popover, but waits for you.</div>
<div class="sh">Capture</div>
<div class="grp">
<div class="sr"><span class="k">Capture</span><span class="pop2">Front Window<i></i></span></div>
<div class="sr"><span class="k">Saved area</span><span class="v">800 × 600 on Display 1</span><span class="btn">Choose…</span></div>
</div>
</div>
</div>
<ul class="notes"><li>Quit lives here (and ⌘Q in the popover): the popover has no menu left to hide it in.</li><li>3b is cropped to the changed groups.</li></ul>
</div>
</div></div>
</section>
<!-- ===================== SPEC ===================== -->
<section class="turn" id="t4">
<div class="thd"><a class="tid" href="#t4">4</a><span class="tname">Labels, keys, states</span></div>
<div class="spec">
<h2 class="sh2">Strings</h2>
<table>
<tr><th>Place</th><th>Exact label</th></tr>
<tr><td>Popover header icons</td><td><code>Edit review details</code> (tooltip + VoiceOver), <code>Settings</code> (tooltip “Settings (⌘,)”)</td></tr>
<tr><td>Scope segmented control (VoiceOver “Capture”)</td><td><code>Area</code> · <code>Window</code> · <code>Browser</code> · <code>Screen</code></td></tr>
<tr><td>Target line</td><td>Area: <code>800 × 600 on Display 1</code> + <code>Choose Area…</code> · Window: <code>Front window when you press ⌥⇧2</code> · Browser: <code>Front browser page when you press ⌥⇧2</code> · Screen: <code>Display 1 · 2560 × 1440</code>; non-area scopes add <code>area kept: 800 × 600</code></td></tr>
<tr><td>Empty pages</td><td><code>No pages yet</code> / <code>⌥⇧2 captures the area|window|page|screen</code></td></tr>
<tr><td>Verbs</td><td><code>Capture ⌥⇧2</code>, <code>Send</code> (empty, disabled) / <code>Send 3 pages</code>, OneDrive: <code>Save 3 pages</code>; <code>New Session…</code>, <code>Open Redline</code></td></tr>
<tr><td>New-session step</td><td>Title <code>New session</code>; subtitle <code>The current 3 pages are kept as a past session.</code>; groups <code>Capture</code>, <code>Review details</code> + <code>Edit…</code>; buttons <code>Cancel</code>, <code>Start Session</code></td></tr>
<tr><td>Scope menu (⌥⇧1)</td><td>Header <code>Capture</code>; <code>Saved Area</code> (1), <code>Front Window</code> (2), <code>Browser Page</code> (3), <code>Whole Screen</code> (4), <code>Choose New Area…</code> (A)</td></tr>
<tr><td>Status line (only when news)</td><td><code>Captured page 4</code> · <code>Sent · 3 pages</code> · <code>Saved to OneDrive · 3 pages</code> · <code>OMS test lane came back · 2 pages marked</code> + <code>Open</code> · <code>No front window to capture</code> · <code>No browser window in front</code> · <code>Redline 0.6.0 is ready — restarts after you send</code> + <code>Restart Now</code></td></tr>
<tr><td>Settings</td><td>Groups <code>Capture</code>, <code>Sending</code>, <code>Sessions</code>, <code>Updates</code>; rows as in 3a; captions as in 3a/3b; footer <code>Quit Redline</code></td></tr>
</table>
<h2 class="sh2">Keyboard</h2>
<p><b>Global:</b> ⌥⇧2 capture with the session’s scope · ⌥⇧1 open the capture menu (1–4 or A picks and captures). <b>Popover Tab order:</b> Edit review details → Settings → scope segments (←/→ move) → Choose Area… → Capture → Send → New Session… → Open Redline. Return = Send when enabled, otherwise Capture; Escape closes. ⌘, opens Settings; ⌘N = New Session…; ⌘Q quits. <b>New-session step:</b> Tab scope → Choose Area… → Edit… → Cancel → Start Session; Return = Start Session, Escape = Cancel. <b>Window:</b> ⌘N New Session…, ⌘S Send, ⌘, Settings, ⌘F search.</p>
<h2 class="sh2">Scope states</h2>
<p>The scope belongs to the session and is copied to the next one. <b>Area</b> uses the saved rectangle; if none is saved, Capture first runs the picker. <b>Window</b> grabs the frontmost window of the app that was front before Redline (never Redline itself); none → status “No front window to capture”, nothing added. <b>Browser</b> grabs the frontmost Safari / Chrome / Arc / Edge / Firefox window, page area only; no browser in front → “No browser window in front”. <b>Screen</b> grabs the display the pointer is on. Choosing Window, Browser or Screen never clears the saved area: it is shown as “area kept” and comes back when Area is chosen. Choose Area… / Choose New Area… always replaces the saved area and switches the scope to Area.</p>
<h2 class="sh2">Information architecture</h2>
<p>The capture decision lives in the popover, above the pages, as a four-way segmented control with the target line under it — and again, unmissably, in the New Session… step, which replaces the page strip until Start Session. The window header mirrors the scope as a pop-up next to the verbs. Settings has one door: the gear in the popover header (⌘, from anywhere in Redline); the window has no gear and the popover has no “…” menu. Popover hierarchy, top to bottom: what is being reviewed (lane, build, commit, reviewer) → what will be captured (scope, target) → what has been captured (pages) → news (one status line, only when there is any) → verbs (Capture, Send) → session control (New Session…, Open Redline). Updates move into Settings › Updates and surface in the popover only when an installed update is waiting.</p>
<h2 class="sh2">Still the biggest thing wrong</h2>
<p>The popover still carries two jobs at once — deciding what to capture and reviewing what was captured — and the real fix is to make the session, not the popover, the unit of decision: every capture rule (scope, area, lane, build, commit) should be set once, when the session starts, and then stay out of the way. Today the new-session step is the only place that treats it that way; until scope and details are locked per session (with change visibly recorded on the PDF when they change mid-session), a reviewer can still produce a PDF whose pages were captured under different rules without anyone noticing.</p>
</div>
</section>
</body>
</html>
+480
View File
@@ -0,0 +1,480 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Redline UX Rework</title>
<meta name="description" content="From-scratch UX for Redline: a glance-and-act menu-bar popover, one main window for sessions, and a three-section Settings window. Light and dark, 1:1 sizes.">
<style>
/* Page chrome (the board the mockups sit on) */
:root{--page:#e9e7e2;--ink:#1d1d1f;--mut:rgba(0,0,0,.55);--rule:rgba(0,0,0,.1);--acc:#0a64d6}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--page:#141416;--ink:#ececec;--mut:rgba(255,255,255,.6);--rule:rgba(255,255,255,.12)}}
:root[data-theme="dark"]{--page:#141416;--ink:#ececec;--mut:rgba(255,255,255,.6);--rule:rgba(255,255,255,.12)}
body{margin:0;background:var(--page);color:var(--ink);font:13px/1.4 -apple-system,BlinkMacSystemFont,"SF Pro Text","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
.mac a{color:var(--accent)}
header.board{padding:32px 40px 8px;max-width:1200px}
header.board h1{margin:0 0 6px;font-size:22px;font-weight:600}
header.board p{margin:0;color:var(--mut);max-width:760px}
section.turn{padding:28px 40px 36px;border-top:1px solid var(--rule)}
.thd{display:flex;align-items:baseline;gap:10px;margin:0 0 18px}
.tid{font:600 10px ui-monospace,Menlo,monospace;padding:3px 7px;background:var(--ink);color:var(--page);text-decoration:none}
.tname{font-weight:600}
.tnote{color:var(--mut);font-size:12px}
.row{display:flex;flex-wrap:wrap;gap:36px;align-items:flex-start}
.opt{display:flex;flex-direction:column;gap:10px;max-width:100%}
.olabel{font-size:12px;color:var(--mut);display:flex;gap:8px;align-items:baseline}
.oid{font:600 10.5px ui-monospace,Menlo,monospace;padding:3px 7px;background:var(--rule);color:var(--ink);text-decoration:none}
.scroller{max-width:100%;overflow-x:auto;padding:2px 2px 18px}
@media (max-width:600px){header.board,section.turn{padding-left:16px;padding-right:16px}}
/* ---------- macOS semantic tokens, per mock theme ---------- */
.mac{--win:#ececec;--content:#ffffff;--side:#e8e8e8;--side2:#dedede;--label:rgba(0,0,0,.88);--label2:rgba(0,0,0,.55);--label3:rgba(0,0,0,.3);
--sep:rgba(0,0,0,.1);--ctl:#ffffff;--ctlBorder:rgba(0,0,0,.16);--ctlShadow:0 .5px 1px rgba(0,0,0,.12);--fill:rgba(0,0,0,.05);--fill2:rgba(0,0,0,.08);
--accent:#0a64d6;--accentText:#ffffff;--selection:#0a64d6;--selText:#fff;--selMuted:rgba(0,0,0,.08);--red:#d70015;--green:#248a3d;--orange:#c45a00;
--pop:rgba(246,246,246,.96);--group:#ffffff;--groupBorder:rgba(0,0,0,.08);--thumbA:#d9ded9;--thumbB:#c9d3e1;--thumbC:#e3d6cc;
--shadow:0 0 0 .5px rgba(0,0,0,.22),0 18px 48px rgba(0,0,0,.22),0 4px 10px rgba(0,0,0,.08);
color:var(--label);font:13px/1.35 -apple-system,BlinkMacSystemFont,"SF Pro Text","Helvetica Neue",sans-serif;-webkit-font-smoothing:antialiased;letter-spacing:-.003em}
.mac.dark{--win:#2a2a2c;--content:#1e1e1e;--side:#2b2a2e;--side2:#353438;--label:rgba(255,255,255,.88);--label2:rgba(255,255,255,.55);--label3:rgba(255,255,255,.28);
--sep:rgba(255,255,255,.1);--ctl:#5c5c60;--ctlBorder:rgba(255,255,255,.08);--ctlShadow:0 .5px 1px rgba(0,0,0,.4);--fill:rgba(255,255,255,.06);--fill2:rgba(255,255,255,.1);
--accent:#0a7cff;--selection:#0a5fce;--selMuted:rgba(255,255,255,.1);--red:#ff453a;--green:#32d74b;--orange:#ff9f0a;
--pop:rgba(40,40,42,.97);--group:#252527;--groupBorder:rgba(255,255,255,.07);--thumbA:#3d4441;--thumbB:#38404d;--thumbC:#4a4038;
--shadow:0 0 0 .5px rgba(0,0,0,.9),0 0 0 1px rgba(255,255,255,.08) inset,0 18px 48px rgba(0,0,0,.55)}
/* ---------- controls ---------- */
.btn{display:inline-flex;align-items:center;justify-content:center;gap:5px;height:22px;padding:0 10px;border-radius:6px;background:var(--ctl);color:var(--label);
box-shadow:var(--ctlShadow),0 0 0 .5px var(--ctlBorder);font:500 13px/1 inherit;font-family:inherit;white-space:nowrap;border:0}
.btn.sm{height:20px;font-size:12px;padding:0 9px;border-radius:5px}
.btn.lg{height:28px;font-size:13px;padding:0 14px;border-radius:7px}
.btn.primary{background:var(--accent);color:var(--accentText);box-shadow:0 .5px 1px rgba(0,0,0,.2)}
.btn.plain{background:transparent;box-shadow:none;color:var(--accent);padding:0 4px}
.btn.icon{width:24px;padding:0;background:transparent;box-shadow:none;color:var(--label2)}
.btn[disabled]{opacity:.42}
.kbd{font:500 11px/1 -apple-system,inherit;color:var(--label2);letter-spacing:.04em}
.primary .kbd{color:rgba(255,255,255,.75)}
.seg{display:inline-flex;background:var(--fill2);border-radius:6px;padding:1px;gap:1px}
.seg span{padding:2px 12px;border-radius:5px;font-size:12px;color:var(--label)}
.seg span.on{background:var(--ctl);box-shadow:var(--ctlShadow),0 0 0 .5px var(--ctlBorder)}
.field{height:22px;border-radius:5px;background:var(--ctl);box-shadow:0 0 0 .5px var(--ctlBorder) inset;display:flex;align-items:center;padding:0 7px;color:var(--label);font-size:13px}
.mac.dark .field{background:rgba(255,255,255,.06)}
.mac.dark .grow-row .field{background:transparent}
.mac.dark .grow-row .field.focus{background:rgba(255,255,255,.08)}
.field.ph{color:var(--label3)}
.field.focus{box-shadow:0 0 0 .5px var(--accent) inset,0 0 0 3px color-mix(in srgb,var(--accent) 35%,transparent)}
.popup{display:inline-flex;align-items:center;gap:8px;height:22px;padding:0 6px 0 9px;border-radius:5px;background:var(--ctl);box-shadow:var(--ctlShadow),0 0 0 .5px var(--ctlBorder);font-size:13px}
.popup i{display:inline-block;width:14px;height:16px;border-radius:4px;background:var(--accent);position:relative}
.popup i:before,.popup i:after{content:"";position:absolute;left:4px;border:3px solid transparent}
.popup i:before{top:2px;border-bottom-color:#fff;border-top:0}
.popup i:after{bottom:2px;border-top-color:#fff;border-bottom:0}
.mono{font-family:ui-monospace,"SF Mono",Menlo,monospace;font-size:12px}
.sec{color:var(--label2)}
.ter{color:var(--label3)}
.cap{font-size:11px;color:var(--label2)}
svg.sym{width:14px;height:14px;flex:none;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
svg.sym.sm{width:12px;height:12px}
/* ---------- menu bar + popover ---------- */
.menubar{height:24px;display:flex;justify-content:flex-end;align-items:center;gap:14px;padding:0 12px;font-size:13px;width:356px;box-sizing:border-box;
background:rgba(236,236,236,.85);color:#111;border-radius:6px 6px 0 0}
.mac.dark .menubar{background:rgba(28,28,30,.9);color:#eee}
.menubar .extra{display:inline-flex;align-items:center;gap:3px;padding:1px 6px;border-radius:4px;background:rgba(0,0,0,.12)}
.mac.dark .menubar .extra{background:rgba(255,255,255,.18)}
.popwrap{position:relative;width:356px;padding-top:8px}
.popover{width:340px;margin-left:8px;border-radius:12px;background:var(--pop);box-shadow:var(--shadow);overflow:hidden;position:relative}
.popover:before{content:"";position:absolute;top:-6px;right:42px;width:12px;height:12px;background:var(--pop);transform:rotate(45deg)}
.pp{padding:12px 12px 0}
.pp-head{display:flex;align-items:flex-start;gap:8px}
.pp-title{font-size:13px;font-weight:600}
.pp-sub{font-size:11px;color:var(--label2);margin-top:1px}
.pp-head .grow{flex:1;min-width:0}
.badge{font:600 11px/1 inherit;padding:3px 6px;border-radius:99px;background:var(--fill2);color:var(--label2);font-variant-numeric:tabular-nums}
.strip{display:flex;gap:6px;margin:12px 0 0;overflow:hidden}
.thumb{position:relative;flex:none;height:62px;width:96px;border-radius:5px;background:var(--thumbA);box-shadow:0 0 0 .5px var(--sep) inset;overflow:hidden}
.thumb:nth-child(3n+2){background:var(--thumbB)}.thumb:nth-child(3n){background:var(--thumbC)}
.thumb .n{position:absolute;left:4px;top:4px;font:600 10px/1 inherit;color:#fff;background:rgba(0,0,0,.55);padding:2px 4px;border-radius:3px}
.thumb .lines{position:absolute;left:10px;right:10px;top:22px;display:grid;gap:5px}
.thumb .lines b{display:block;height:4px;border-radius:2px;background:rgba(0,0,0,.14)}
.mac.dark .thumb .lines b{background:rgba(255,255,255,.14)}
.thumb .lines b:nth-child(2){width:70%}.thumb .lines b:nth-child(3){width:45%}
.thumb.more{width:44px;background:var(--fill)!important;display:flex;align-items:center;justify-content:center;font-size:11px;color:var(--label2)}
.empty-strip{margin:12px 0 0;height:62px;border-radius:6px;background:var(--fill);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;text-align:center}
.empty-strip .t{font-size:12px;color:var(--label)}
.empty-strip .s{font-size:11px;color:var(--label2)}
.actions{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:12px 0 0}
.actions .btn{height:28px;font-size:13px;border-radius:7px}
.secondary{display:flex;justify-content:space-between;align-items:center;margin:10px 0 0}
.status{margin:10px -12px 0;padding:8px 12px;border-top:.5px solid var(--sep);display:flex;gap:8px;align-items:center;font-size:12px}
.status .dot{width:7px;height:7px;border-radius:50%;background:var(--green);flex:none}
.status .grow{flex:1}
.pp-foot{margin:0 -12px;padding:6px 8px 6px 12px;border-top:.5px solid var(--sep);display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--label2)}
.capturing .thumb.live{box-shadow:0 0 0 2px var(--accent) inset}
.spinner{width:12px;height:12px;border-radius:50%;border:1.6px solid rgba(255,255,255,.45);border-top-color:#fff;flex:none}
.btn:not(.primary) .spinner{border-color:var(--fill2);border-top-color:var(--label2)}
/* ---------- main window ---------- */
.window{border-radius:10px;background:var(--content);box-shadow:var(--shadow);overflow:hidden;display:grid;grid-template-columns:232px 1fr 300px;grid-template-rows:52px 1fr;position:relative}
.window.noinsp{grid-template-columns:232px 1fr}
.titlebar{grid-column:1/-1;display:grid;grid-template-columns:232px 1fr 300px;border-bottom:.5px solid var(--sep);background:var(--win)}
.window.noinsp .titlebar{grid-template-columns:232px 1fr}
.tb-side{display:flex;align-items:center;gap:8px;padding:0 12px 0 20px;background:var(--side);border-right:.5px solid var(--sep)}
.lights{display:flex;gap:8px}
.lights i{width:12px;height:12px;border-radius:50%;display:block;box-shadow:0 0 0 .5px rgba(0,0,0,.18) inset}
.lights i:nth-child(1){background:#ff5f57}.lights i:nth-child(2){background:#febc2e}.lights i:nth-child(3){background:#28c840}
.tb-main{display:flex;align-items:center;gap:8px;padding:0 12px 0 16px}
.tb-main .title{font-size:15px;font-weight:600}
.tb-main .subtitle{font-size:11px;color:var(--label2)}
.tb-main .grow{flex:1}
.tbbtn{display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 9px;border-radius:7px;color:var(--label);font-size:13px}
.tbbtn:hover{background:var(--fill)}
.tbbtn.prom{background:var(--accent);color:#fff}
.tbgroup{display:flex;gap:2px}
.tb-insp{display:flex;align-items:center;justify-content:flex-end;padding:0 12px;border-left:.5px solid var(--sep)}
.sidebar{background:var(--side);border-right:.5px solid var(--sep);padding:8px 10px;overflow:hidden}
.search{height:26px;border-radius:7px;background:var(--fill2);display:flex;align-items:center;gap:6px;padding:0 8px;color:var(--label3);font-size:13px;margin:0 0 10px}
.sgroup{font:600 11px/1 inherit;color:var(--label2);padding:10px 8px 5px}
.srow{display:grid;grid-template-columns:1fr auto;gap:0 6px;padding:5px 8px;border-radius:6px;margin:0 0 1px}
.srow .l1{font-size:13px;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.srow .l2{grid-column:1/-1;font-size:11px;color:var(--label2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.srow .tm{font-size:11px;color:var(--label2);font-variant-numeric:tabular-nums;align-self:center}
.srow.sel{background:var(--selection);color:var(--selText)}
.srow.sel .l2,.srow.sel .tm{color:rgba(255,255,255,.78)}
.srow .st{display:inline-flex;align-items:center;gap:3px}
.srow .st.ret{color:var(--orange)}
.srow.sel .st.ret{color:#fff}
.current-pill{font:600 10px/1 inherit;padding:2px 5px;border-radius:4px;background:var(--accent);color:#fff;margin-left:4px;vertical-align:1px}
.srow.sel .current-pill{background:rgba(255,255,255,.25)}
.content{padding:18px 20px;overflow:hidden;background:var(--content)}
.chead{display:flex;align-items:baseline;gap:10px;margin:0 0 14px}
.chead h2{margin:0;font-size:13px;font-weight:600}
.chead .grow{flex:1}
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.page{display:flex;flex-direction:column;gap:6px}
.page .shot{position:relative;aspect-ratio:16/10;border-radius:6px;background:var(--thumbA);box-shadow:0 0 0 .5px var(--sep) inset;overflow:hidden}
.page:nth-child(3n+2) .shot{background:var(--thumbB)}.page:nth-child(3n) .shot{background:var(--thumbC)}
.page .shot .lines{position:absolute;left:14%;right:14%;top:28%;display:grid;gap:7px}
.page .shot .lines b{display:block;height:6px;border-radius:3px;background:rgba(0,0,0,.12)}
.mac.dark .page .shot .lines b{background:rgba(255,255,255,.12)}
.page .shot .lines b:nth-child(2){width:72%}.page .shot .lines b:nth-child(3){width:48%}
.page .shot .mark{position:absolute;right:8px;top:8px;font:600 10px/1 inherit;padding:3px 5px;border-radius:4px;background:var(--orange);color:#fff}
.page .meta{display:flex;justify-content:space-between;font-size:11px;color:var(--label2);font-variant-numeric:tabular-nums}
.page .meta b{color:var(--label);font-weight:600}
.page.sel .shot{box-shadow:0 0 0 3px var(--accent)}
.inspector{border-left:.5px solid var(--sep);background:var(--win);padding:14px 14px;overflow:hidden}
.mac.dark .inspector{background:#232325}
.ihead{font:600 11px/1 inherit;color:var(--label2);margin:6px 2px 7px}
.group{background:var(--group);border-radius:8px;box-shadow:0 0 0 .5px var(--groupBorder);margin:0 0 14px}
.grow-row{display:grid;grid-template-columns:78px 1fr;align-items:center;gap:8px;padding:6px 10px;min-height:22px}
.grow-row + .grow-row{border-top:.5px solid var(--sep)}
.grow-row .k{font-size:12px;color:var(--label2)}
.grow-row .v{font-size:12px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.grow-row .field{height:20px;font-size:12px;background:transparent;box-shadow:none;padding:0}
.grow-row .field.focus{background:var(--ctl);box-shadow:0 0 0 .5px var(--accent) inset,0 0 0 3px color-mix(in srgb,var(--accent) 35%,transparent);padding:0 5px;margin:0 -5px}
.note .v{white-space:normal}
.ifoot{font-size:11px;color:var(--label2);margin:-6px 2px 12px;line-height:1.35}
.ret-banner{display:flex;gap:8px;align-items:flex-start;padding:8px 10px;border-radius:8px;background:color-mix(in srgb,var(--orange) 12%,transparent);margin:0 0 14px;font-size:12px}
.ret-banner .grow{flex:1}
.ret-banner svg{color:var(--orange);margin-top:1px}
.empty-main{display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;height:100%;gap:8px;padding:0 40px}
.empty-main .t{font-size:15px;font-weight:600}
.empty-main .s{font-size:12px;color:var(--label2);max-width:320px}
/* ---------- settings ---------- */
.settings{width:420px;border-radius:10px;background:var(--win);box-shadow:var(--shadow);overflow:hidden}
.mac.dark .settings{background:#1f1f21}
.st-title{height:52px;display:grid;grid-template-columns:70px 1fr 70px;align-items:center;padding:0 0 0 14px}
.st-title .t{text-align:center;font-size:13px;font-weight:600}
.st-body{padding:0 18px 18px}
.st-body .ihead{margin:12px 2px 7px}
.st-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:7px 10px;min-height:22px}
.st-row + .st-row{border-top:.5px solid var(--sep)}
.st-row .k{font-size:13px}
.st-row .v{display:flex;align-items:center;gap:8px;min-width:0}
.st-row .path{font-size:12px;color:var(--label2);max-width:170px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.recorder{display:inline-flex;align-items:center;height:22px;padding:0 10px;border-radius:5px;background:var(--fill2);font-size:13px;letter-spacing:.06em}
.st-help{font-size:11px;color:var(--label2);margin:6px 2px 0;line-height:1.35}
/* annotations under each mock */
.notes{max-width:360px;font-size:12px;color:var(--mut);line-height:1.45;margin:0;padding-left:16px}
.notes li{margin:0 0 3px}
</style>
</head>
<body>
<header class="board">
<h1>Redline, rebuilt from the job outwards</h1>
<p>The menu-bar popover only answers "what am I capturing, and what do I do next". Everything about past sessions, review details and PDF facts lives in one Redline window. Settings has three sections. Each mock is shown at 1:1 size in light and dark.</p>
</header>
<section class="turn" id="t1">
<div class="thd"><a class="tid" href="#t1">1</a><span class="tname">Menu-bar popover: glance and act</span><span class="tnote">340 pt wide · controlSize small · current session only</span></div>
<div class="row" id="popovers"></div>
</section>
<section class="turn" id="t2">
<div class="thd"><a class="tid" href="#t2">2</a><span class="tname">Redline window: the session workspace</span><span class="tnote">1100 × 700 · sidebar · content · inspector · controlSize regular</span></div>
<div class="row" id="mains"></div>
</section>
<section class="turn" id="t3">
<div class="thd"><a class="tid" href="#t3">3</a><span class="tname">Redline window: first run, nothing captured</span><span class="tnote">1100 × 700</span></div>
<div class="row" id="empties"></div>
</section>
<section class="turn" id="t4">
<div class="thd"><a class="tid" href="#t4">4</a><span class="tname">Settings</span><span class="tnote">420 × 484 · three groups, no tabs</span></div>
<div class="row" id="settings"></div>
</section>
<script>
/* Inline SVG stand-ins for the SF Symbols the app will use (names in data-sf). */
const SYM = {
camera: '<svg class="sym" viewBox="0 0 16 16" data-sf="camera.viewfinder"><path d="M2 5V3.5A1.5 1.5 0 0 1 3.5 2H5M11 2h1.5A1.5 1.5 0 0 1 14 3.5V5M14 11v1.5a1.5 1.5 0 0 1-1.5 1.5H11M5 14H3.5A1.5 1.5 0 0 1 2 12.5V11"/><circle cx="8" cy="8" r="2.4"/></svg>',
send: '<svg class="sym" viewBox="0 0 16 16" data-sf="paperplane"><path d="M14 2 2 7l5 2 2 5 5-12Z"/><path d="m7 9 3-3"/></svg>',
plus: '<svg class="sym" viewBox="0 0 16 16" data-sf="plus.rectangle.on.rectangle"><rect x="2.5" y="4.5" width="9" height="9" rx="1.5"/><path d="M5 2.5h7a1.5 1.5 0 0 1 1.5 1.5v7M7 9h0M7 7v4M5 9h4"/></svg>',
window: '<svg class="sym" viewBox="0 0 16 16" data-sf="macwindow"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M2 6h12"/></svg>',
more: '<svg class="sym" viewBox="0 0 16 16" data-sf="ellipsis.circle"><circle cx="8" cy="8" r="6"/><circle cx="5.5" cy="8" r=".4" fill="currentColor"/><circle cx="8" cy="8" r=".4" fill="currentColor"/><circle cx="10.5" cy="8" r=".4" fill="currentColor"/></svg>',
pencil: '<svg class="sym sm" viewBox="0 0 16 16" data-sf="pencil.tip.crop.circle"><path d="M10.5 2.5 13.5 5.5 6 13H3v-3Z"/></svg>',
search: '<svg class="sym" viewBox="0 0 16 16" data-sf="magnifyingglass"><circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3"/></svg>',
sidebar: '<svg class="sym" viewBox="0 0 16 16" data-sf="sidebar.left"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M6 3v10"/></svg>',
inspector: '<svg class="sym" viewBox="0 0 16 16" data-sf="sidebar.right"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M10 3v10"/></svg>',
finder: '<svg class="sym" viewBox="0 0 16 16" data-sf="folder"><path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h2.6l1.4 1.5h5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5Z"/></svg>',
check: '<svg class="sym sm" viewBox="0 0 16 16" data-sf="checkmark.circle"><circle cx="8" cy="8" r="6"/><path d="m5.5 8 1.8 1.8L10.8 6.3"/></svg>',
marked: '<svg class="sym sm" viewBox="0 0 16 16" data-sf="pencil.and.outline"><path d="M10.5 2.5 13.5 5.5 6 13H3v-3Z"/></svg>',
warn: '<svg class="sym" viewBox="0 0 16 16" data-sf="exclamationmark.triangle"><path d="M8 2.5 14 13H2Z"/><path d="M8 6.5v3M8 11.3v.1"/></svg>',
menuIcon: '<svg class="sym" viewBox="0 0 16 16" data-sf="viewfinder"><path d="M2 5V3.5A1.5 1.5 0 0 1 3.5 2H5M11 2h1.5A1.5 1.5 0 0 1 14 3.5V5M14 11v1.5a1.5 1.5 0 0 1-1.5 1.5H11M5 14H3.5A1.5 1.5 0 0 1 2 12.5V11"/></svg>'
};
const thumbs = n => Array.from({length:n},(_,i)=>`<div class="thumb${i===n-1?' live':''}"><span class="n">${i+1}</span><div class="lines"><b></b><b></b><b></b></div></div>`).join('');
function opt(id,label,html,notes){
return `<div class="opt" id="${id}"><div class="olabel"><a class="oid" href="#${id}">${id}</a>${label}</div><div class="scroller">${html}</div>${notes?`<ul class="notes">${notes.map(n=>`<li>${n}</li>`).join('')}</ul>`:''}</div>`;
}
/* ---------- popover ---------- */
function popover(theme,state){
const dark = theme==='dark'?' dark':'';
const count = state==='idle'?0:(state==='capturing'?4:3);
const head = `
<div class="pp-head">
<div class="grow">
<div class="pp-title">DEV03 · v1.4.2 (41)</div>
<div class="pp-sub">a1b2c3d · Ben Hippler · started 10:31</div>
</div>
${count?`<span class="badge" aria-label="${count} pages">${count} pages</span>`:''}
<button class="btn icon" aria-label="Edit review details" title="Edit review details">${SYM.pencil}</button>
</div>`;
const body = state==='idle'
? `<div class="empty-strip"><div class="t">Nothing captured yet</div><div class="s">⌥⇧2 captures 800 × 600 on Display 1</div></div>`
: `<div class="strip${state==='capturing'?' capturing':''}">${thumbs(count===4?3:3)}${count>3?'<div class="thumb more">+1</div>':''}</div>`;
const capBtn = state==='capturing'
? `<button class="btn" disabled><span class="spinner"></span>Capturing…</button>`
: `<button class="btn">${SYM.camera}Capture <span class="kbd">⌥⇧2</span></button>`;
const sendBtn = state==='idle'
? `<button class="btn primary" disabled>${SYM.send}Send</button>`
: `<button class="btn primary">${SYM.send}Send ${count} pages…</button>`;
const status = state==='with'
? `<div class="status"><span class="dot" style="background:var(--orange)"></span><span class="grow">1 PDF came back with marks on 2 pages</span><button class="btn plain sm">Show</button></div>`
: '';
return `<div class="mac${dark}">
<div class="menubar"><span>Fri 31 Oct 10:42</span><span class="extra">${SYM.menuIcon}<span style="font-size:11px;font-weight:600">${count||''}</span></span></div>
<div class="popwrap"><div class="popover" role="dialog" aria-label="Redline">
<div class="pp">
${head}
${body}
<div class="actions">${capBtn}${sendBtn}</div>
<div class="secondary">
<button class="btn plain sm" ${state==='idle'?'disabled':''}>${SYM.plus}New Session</button>
<button class="btn plain sm">${SYM.window}Open Redline</button>
</div>
${status}
<div class="pp-foot" style="${status?'border-top:0;margin-top:0':'margin-top:12px'}">
<span>Sends via AirDrop · All sessions kept</span>
<button class="btn icon" aria-label="More">${SYM.more}</button>
</div>
</div>
</div></div></div>`;
}
const popNotes = {
idle:['The session already carries the inherited review details, so the title is never empty after first use.','Send is disabled, not hidden, so the layout never jumps.'],
with:['Send states the page count it will produce.','One status line appears only when something happened: a return, a send, or an error.'],
capturing:['The newest thumbnail gets the accent ring; Capture shows progress and is disabled until the PNG is on disk.','The More menu holds Settings…, Check for Updates…, Quit Redline.']
};
document.getElementById('popovers').innerHTML =
['idle','with','capturing'].flatMap(s=>['light','dark'].map(t=>
opt(`1${s[0]}${t[0]}`,`${{idle:'Idle, empty session',with:'Captures present + a return',capturing:'Capturing'}[s]} · ${t}`,popover(t,s),t==='light'?popNotes[s]:null))).join('');
/* ---------- main window ---------- */
const sessions = [
{g:'Today'},
{lane:'DEV03',tm:'10:31',l2:'3 pages · not sent',cur:true,sel:true},
{lane:'DEV03',tm:'09:12',l2:'5 pages · sent',st:'sent'},
{lane:'OMS test lane',tm:'08:40',l2:'2 pages · came back marked',st:'ret'},
{g:'Yesterday'},
{lane:'STAGE',tm:'17:04',l2:'7 pages · sent',st:'sent'},
{lane:'DEV03',tm:'14:22',l2:'4 pages · sent',st:'sent'},
{g:'This week'},
{lane:'PROD',tm:'Tue',l2:'1 page · not sent'},
{lane:'4F2A9C1D',tm:'Mon',l2:'6 pages · sent',st:'sent'},
];
function sidebarRows(list){
return list.map(s=>s.g?`<div class="sgroup">${s.g}</div>`:
`<div class="srow${s.sel?' sel':''}"><span class="l1">${s.lane}${s.cur?'<span class="current-pill">Current</span>':''}</span><span class="tm">${s.tm}</span><span class="l2">${s.st==='ret'?`<span class="st ret">${SYM.marked} ${s.l2}</span>`:s.l2}</span></div>`).join('');
}
function titlebar(title,sub,canSend){
return `<div class="titlebar">
<div class="tb-side"><div class="lights"><i></i><i></i><i></i></div><span style="flex:1"></span><span class="tbbtn" aria-label="Hide sidebar">${SYM.sidebar}</span></div>
<div class="tb-main"><div><div class="title">${title}</div><div class="subtitle">${sub}</div></div><span class="grow"></span>
<div class="tbgroup">
<span class="tbbtn" title="New Session ⌘N">${SYM.plus}New Session</span>
<span class="tbbtn" title="Capture ⌥⇧2">${SYM.camera}Capture</span>
<span class="tbbtn prom" style="${canSend?'':'opacity:.4'}" title="Send ⌘S">${SYM.send}Send…</span>
</div></div>
<div class="tb-insp"><span class="tbbtn" aria-label="Hide inspector">${SYM.inspector}</span></div>
</div>`;
}
function inspector(opts){
const f = opts.focus;
return `<aside class="inspector" aria-label="Session inspector">
<div class="ihead">Review details</div>
<div class="group">
<div class="grow-row"><span class="k">Lane</span><span class="field${f==='lane'?' focus':''}">DEV03</span></div>
<div class="grow-row"><span class="k">Deployed</span><span class="field">v1.4.2 (41)</span></div>
<div class="grow-row"><span class="k">Commit</span><span class="field mono">a1b2c3d4</span></div>
<div class="grow-row"><span class="k">Reviewer</span><span class="field">Ben Hippler</span></div>
<div class="grow-row note"><span class="k">Note</span><span class="field ph">Add a note</span></div>
</div>
<div class="ifoot">Printed on every page of the PDF. A new session starts with these values.</div>
<div class="ihead">PDF</div>
<div class="group">
<div class="grow-row"><span class="k">File name</span><span class="v mono" title="Redline-20261031-1042-DEV03-4F2A9C1D.pdf">Redline-20261031-1042-DEV03-4F2A9C1D.pdf</span></div>
<div class="grow-row"><span class="k">Pages</span><span class="v">${opts.pages}</span></div>
<div class="grow-row"><span class="k">Sends via</span><span class="v">AirDrop</span></div>
<div class="grow-row"><span class="k">Status</span><span class="v sec">Not sent yet</span></div>
</div>
<div class="ihead">Session</div>
<div class="group">
<div class="grow-row"><span class="k">Started</span><span class="v">31 Oct 2026, 10:31 Dubai</span></div>
<div class="grow-row"><span class="k">ID</span><span class="v mono">4F2A9C1D</span></div>
<div class="grow-row"><span class="k">Captures</span><span class="v"><a href="#t2">Show in Finder</a></span></div>
</div>
</aside>`;
}
function mainWindow(theme){
const dark = theme==='dark'?' dark':'';
const pages = [['1','10:31'],['2','10:34'],['3','10:39']];
return `<div class="mac${dark}"><div class="window" style="width:1100px;height:700px">
${titlebar('DEV03','Current session · 3 pages · not sent',true)}
<nav class="sidebar" aria-label="Sessions">
<div class="search">${SYM.search}Search</div>
${sidebarRows(sessions)}
</nav>
<main class="content">
<div class="chead"><h2>Pages</h2><span class="sec" style="font-size:12px">In PDF order · Delete removes the selected page</span><span class="grow"></span><button class="btn">${SYM.camera}Capture <span class="kbd">⌥⇧2</span></button></div>
<div class="grid">${pages.map((p,i)=>`<div class="page${i===1?' sel':''}"><div class="shot"><div class="lines"><b></b><b></b><b></b></div></div><div class="meta"><span><b>Page ${p[0]}</b></span><span>${p[1]}</span></div></div>`).join('')}</div>
</main>
${inspector({pages:3,focus:'lane'})}
</div></div>`;
}
function returnedWindow(theme){
const dark = theme==='dark'?' dark':'';
const list = sessions.map(s=>s.sel?{...s,sel:false}:s.lane==='OMS test lane'?{...s,sel:true}:s);
const pages = [['1','08:40',false],['2','08:43',true]];
return `<div class="mac${dark}"><div class="window" style="width:1100px;height:700px">
${titlebar('OMS test lane','Sent 08:52 · came back 09:30 with marks',false)}
<nav class="sidebar" aria-label="Sessions"><div class="search">${SYM.search}Search</div>${sidebarRows(list)}</nav>
<main class="content">
<div class="ret-banner">${SYM.marked}<span class="grow"><b>Came back with marks on page 2.</b><br><span class="sec">Redline-20261031-0852-OMS-TEST-LANE-9B8C7D6E.pdf, in Downloads</span></span><button class="btn sm">Open PDF</button><button class="btn sm">Copy Link</button></div>
<div class="chead"><h2>Pages</h2><span class="grow"></span></div>
<div class="grid">${pages.map(p=>`<div class="page"><div class="shot"><div class="lines"><b></b><b></b><b></b></div>${p[2]?'<span class="mark">Marked</span>':''}</div><div class="meta"><span><b>Page ${p[0]}</b></span><span>${p[1]}</span></div></div>`).join('')}</div>
</main>
<aside class="inspector" aria-label="Session inspector">
<div class="ihead">Review details</div>
<div class="group">
<div class="grow-row"><span class="k">Lane</span><span class="v">OMS test lane</span></div>
<div class="grow-row"><span class="k">Deployed</span><span class="v">v2.0.0-rc3</span></div>
<div class="grow-row"><span class="k">Commit</span><span class="v mono">9f3e2d1</span></div>
<div class="grow-row"><span class="k">Reviewer</span><span class="v">Ben Hippler</span></div>
</div>
<div class="ifoot">Past sessions are read-only: the PDF already carries these values.</div>
<div class="ihead">PDF</div>
<div class="group">
<div class="grow-row"><span class="k">File name</span><span class="v mono">Redline-20261031-0852-OMS-TEST-LANE-9B8C7D6E.pdf</span></div>
<div class="grow-row"><span class="k">Sent</span><span class="v">31 Oct 2026, 08:52 via AirDrop</span></div>
<div class="grow-row"><span class="k">Returned</span><span class="v">09:30 · marks on 1 of 2 pages</span></div>
<div class="grow-row"><span class="k"></span><span class="v"><a href="#t2">Show PDF in Finder</a></span></div>
</div>
</aside>
</div></div>`;
}
document.getElementById('mains').innerHTML =
opt('2a','Current session selected, Lane field focused · light',mainWindow('light'),[
'Sidebar: every kept session grouped by day; the current one is pinned at the top with a Current tag.',
'Content: the pages exactly as the PDF will order them. Selection ring shows the focused page.',
'Inspector: the three facts a reader of the PDF needs (review details, PDF, session). Editable only for the current session.'])
+ opt('2b','Current session · dark',mainWindow('dark'))
+ opt('2c','Past session that came back marked · light',returnedWindow('light'),[
'A returned PDF is news, so it gets the one tinted banner in the app, with the two things you do next.',
'No Send, no Capture on a past session: the toolbar dims Send and the content drops the Capture button.'])
+ opt('2d','Past session that came back marked · dark',returnedWindow('dark'));
/* ---------- empty window ---------- */
function emptyWindow(theme){
const dark = theme==='dark'?' dark':'';
return `<div class="mac${dark}"><div class="window" style="width:1100px;height:700px">
${titlebar('New session','Nothing captured yet',false)}
<nav class="sidebar" aria-label="Sessions"><div class="search">${SYM.search}Search</div><div class="sgroup">Today</div>
<div class="srow sel"><span class="l1">New session<span class="current-pill">Current</span></span><span class="tm">10:31</span><span class="l2">No pages yet</span></div></nav>
<main class="content"><div class="empty-main">
<div class="t">No pages in this session</div>
<div class="s">Press ⌥⇧2 anywhere to capture the saved area, or choose an area now. Each capture becomes one page of the PDF.</div>
<div style="display:flex;gap:8px;margin-top:6px"><button class="btn lg">Choose Area…</button><button class="btn lg primary">${SYM.camera}Capture</button></div>
</div></main>
<aside class="inspector" aria-label="Session inspector">
<div class="ihead">Review details</div>
<div class="group">
<div class="grow-row"><span class="k">Lane</span><span class="field ph focus">dev03, customer test lane…</span></div>
<div class="grow-row"><span class="k">Deployed</span><span class="field ph">Build that is live</span></div>
<div class="grow-row"><span class="k">Commit</span><span class="field ph mono">Git SHA</span></div>
<div class="grow-row"><span class="k">Reviewer</span><span class="field">Ben Hippler</span></div>
<div class="grow-row note"><span class="k">Note</span><span class="field ph">Add a note</span></div>
</div>
<div class="ifoot">Fill these in once. They print on every page and carry over to the next session.</div>
</aside>
</div></div>`;
}
document.getElementById('empties').innerHTML =
opt('3a','First run · light',emptyWindow('light'),['The first thing the window asks for is the lane, because it names the file and heads every page.','Reviewer is pre-filled from the Mac account; nothing else is guessed.'])
+ opt('3b','First run · dark',emptyWindow('dark'));
/* ---------- settings ---------- */
function settings(theme){
const dark = theme==='dark'?' dark':'';
return `<div class="mac${dark}"><div class="settings" style="height:484px">
<div class="st-title"><div class="lights"><i></i><i style="background:var(--fill2)"></i><i style="background:var(--fill2)"></i></div><div class="t">Redline Settings</div><div></div></div>
<div class="st-body">
<div class="ihead">Capture</div>
<div class="group">
<div class="st-row"><span class="k">Capture shortcut</span><span class="v"><span class="recorder">⌥⇧2</span></span></div>
<div class="st-row"><span class="k">Area</span><span class="v"><span class="sec" style="font-size:12px">800 × 600 on Display 1</span><button class="btn sm">Choose…</button></span></div>
</div>
<div class="ihead">Sending</div>
<div class="group">
<div class="st-row"><span class="k">Send with</span><span class="v"><span class="seg"><span class="on">AirDrop</span><span>OneDrive</span></span></span></div>
<div class="st-row"><span class="k">Save PDFs to</span><span class="v"><span class="path">~/Desktop</span><button class="btn sm">Choose…</button></span></div>
<div class="st-row"><span class="k">Watch for returns in</span><span class="v"><span class="path">~/Downloads</span><button class="btn sm">Choose…</button></span></div>
</div>
<div class="ihead">Sessions</div>
<div class="group">
<div class="st-row"><span class="k">Delete sessions older than</span><span class="v"><span class="popup">Never<i></i></span></span></div>
<div class="st-row"><span class="k sec" style="font-size:12px">18 sessions kept</span><span class="v"><button class="btn sm" disabled>Clean Up Now…</button></span></div>
</div>
<div class="st-help">Deleting removes Redline's own screenshots only. PDFs you sent stay where they are.</div>
</div>
</div></div>`;
}
document.getElementById('settings').innerHTML =
opt('4a','Settings · light',settings('light'),['Three labelled groups replace headings-plus-grid. Every row is "what it is" on the left, the control on the right.','Clean Up Now… is enabled only when a limit is set, and confirms with the exact count before deleting.'])
+ opt('4b','Settings · dark',settings('dark'));
</script>
</body>
</html>
+3 -2
View File
@@ -11,7 +11,7 @@ cd "$ROOT"
IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
BUNDLE_ID="ai.flowmaster.shotdeck"
APP_BUNDLE="${ROOT}/.build/Shotdeck.app"
APP_BUNDLE="${ROOT}/.build/Redline.app"
SKIP_SIGN=0
for arg in "$@"; do
@@ -27,7 +27,7 @@ for arg in "$@"; do
esac
done
echo "==> Building Shotdeck (release)"
echo "==> Building Redline (release)"
swift build -c release --product Shotdeck
BIN_PATH="$(swift build -c release --product Shotdeck --show-bin-path)/Shotdeck"
@@ -43,6 +43,7 @@ mkdir -p "${APP_BUNDLE}/Contents/Resources"
cp "${BIN_PATH}" "${APP_BUNDLE}/Contents/MacOS/Shotdeck"
chmod +x "${APP_BUNDLE}/Contents/MacOS/Shotdeck"
cp "${ROOT}/Info.plist" "${APP_BUNDLE}/Contents/Info.plist"
cp "${ROOT}/Resources/AppIcon.icns" "${APP_BUNDLE}/Contents/Resources/AppIcon.icns"
if [[ "${SKIP_SIGN}" -eq 1 ]]; then
echo
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
# Installs the locally built Redline into /Applications and launches it with its
# session window open, so the current build is what is on screen.
#
# ./scripts/install-local.sh
#
# The previously installed copy is kept at .build/Redline-<version>.app so the change
# is reversible.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILT="${ROOT}/.build/Redline.app"
TARGET="/Applications/Redline.app"
BUNDLE_ID="ai.flowmaster.shotdeck"
if [[ ! -d "${BUILT}" ]]; then
echo "No ${BUILT}. Run ./scripts/build-app.sh first." >&2
exit 1
fi
if [[ -d "${TARGET}" ]]; then
OLD_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${TARGET}/Contents/Info.plist")"
BACKUP="${ROOT}/.build/Redline-${OLD_VERSION}.app"
if [[ ! -d "${BACKUP}" ]]; then
echo "==> Keeping the installed ${OLD_VERSION} at ${BACKUP}"
ditto "${TARGET}" "${BACKUP}"
fi
fi
echo "==> Quitting the running Redline"
osascript -e 'quit app "Redline"' >/dev/null 2>&1 || true
for _ in $(seq 1 40); do
if ! pgrep -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1; then
break
fi
sleep 0.25
done
pkill -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || true
sleep 0.5
echo "==> Installing ${BUILT} to ${TARGET}"
ditto "${BUILT}" "${TARGET}"
NEW_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${TARGET}/Contents/Info.plist")"
echo "==> Launching Redline ${NEW_VERSION} with its window open"
open -n "${TARGET}" --args --window
sleep 2
if pgrep -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1; then
echo "Redline ${NEW_VERSION} is running from ${TARGET}"
else
echo "Redline did not start" >&2
exit 1
fi
+8 -8
View File
@@ -4,9 +4,9 @@ set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
APP_BUNDLE="${ROOT}/.build/Shotdeck.app"
APP_BUNDLE="${ROOT}/.build/Redline.app"
STAGING="${ROOT}/.build/dmg-staging"
DMG="${ROOT}/.build/Shotdeck.dmg"
DMG="${ROOT}/.build/Redline.dmg"
MOUNT_POINT="${ROOT}/.build/dmg-mnt"
SKIP_SIGN=0
@@ -23,7 +23,7 @@ for arg in "$@"; do
esac
done
echo "==> Building Shotdeck.app"
echo "==> Building Redline.app"
if [[ "${SKIP_SIGN}" -eq 1 ]]; then
./scripts/build-app.sh --skip-sign
else
@@ -38,12 +38,12 @@ fi
echo "==> Staging DMG contents"
rm -rf "${STAGING}"
mkdir -p "${STAGING}"
ditto "${APP_BUNDLE}" "${STAGING}/Shotdeck.app"
ditto "${APP_BUNDLE}" "${STAGING}/Redline.app"
ln -s /Applications "${STAGING}/Applications"
echo "==> Creating ${DMG}"
mkdir -p "$(dirname "${DMG}")"
hdiutil create -volname "Shotdeck" -srcfolder "${STAGING}" -ov -format UDZO "${DMG}"
hdiutil create -volname "Redline" -srcfolder "${STAGING}" -ov -format UDZO "${DMG}"
MOUNTED=0
detach_dmg() {
@@ -67,8 +67,8 @@ MOUNTED=1
echo "==> Mount contents"
ls -la "${MOUNT_POINT}"
if [[ ! -d "${MOUNT_POINT}/Shotdeck.app" ]]; then
echo "Verification failed: Shotdeck.app missing from mounted DMG" >&2
if [[ ! -d "${MOUNT_POINT}/Redline.app" ]]; then
echo "Verification failed: Redline.app missing from mounted DMG" >&2
exit 1
fi
if [[ ! -L "${MOUNT_POINT}/Applications" ]]; then
@@ -81,7 +81,7 @@ if [[ "$(readlink "${MOUNT_POINT}/Applications")" != "/Applications" ]]; then
fi
echo "==> codesign --verify --deep"
codesign --verify --deep --verbose=2 "${MOUNT_POINT}/Shotdeck.app"
codesign --verify --deep --verbose=2 "${MOUNT_POINT}/Redline.app"
echo "==> Detaching ${MOUNT_POINT}"
hdiutil detach "${MOUNT_POINT}"
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env swift
import Foundation
import CoreGraphics
import ImageIO
// Programmatic Redline app icon.
// Draws a 1024×1024 master, writes AppIcon.iconset (16…1024 incl. @2x),
// and compiles Resources/AppIcon.icns via iconutil.
//
// Usage:
// swift scripts/make-icon.swift
// swift scripts/make-icon.swift --preview /path/to/icon-512.png
private let masterSize = 1024
private enum Palette {
static let charcoalTop = CGColor(srgbRed: 44.0 / 255.0, green: 44.0 / 255.0, blue: 46.0 / 255.0, alpha: 1)
static let charcoalBottom = CGColor(srgbRed: 28.0 / 255.0, green: 28.0 / 255.0, blue: 30.0 / 255.0, alpha: 1) // #1C1C1E
static let white = CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
static let redline = CGColor(srgbRed: 229.0 / 255.0, green: 72.0 / 255.0, blue: 63.0 / 255.0, alpha: 1) // #E5483F
}
private struct IconsetEntry {
let filename: String
let pixels: Int
}
private let iconsetEntries: [IconsetEntry] = [
IconsetEntry(filename: "icon_16x16.png", pixels: 16),
IconsetEntry(filename: "icon_16x16@2x.png", pixels: 32),
IconsetEntry(filename: "icon_32x32.png", pixels: 32),
IconsetEntry(filename: "icon_32x32@2x.png", pixels: 64),
IconsetEntry(filename: "icon_128x128.png", pixels: 128),
IconsetEntry(filename: "icon_128x128@2x.png", pixels: 256),
IconsetEntry(filename: "icon_256x256.png", pixels: 256),
IconsetEntry(filename: "icon_256x256@2x.png", pixels: 512),
IconsetEntry(filename: "icon_512x512.png", pixels: 512),
IconsetEntry(filename: "icon_512x512@2x.png", pixels: 1024),
]
// MARK: - Geometry
/// Apple-style continuous-corner rounded square (squircle-like).
/// Superellipse |x/a|^n + |y/b|^n = 1 with n≈5, inset 1px so antialiased
/// edge pixels are not clipped by the bitmap.
private func continuousRoundedSquare(size: CGFloat, exponent n: CGFloat = 5.0, segments: Int = 256) -> CGPath {
let inset: CGFloat = 1
let a = (size - inset * 2) / 2
let cx = size / 2
let cy = size / 2
let twoOverN = 2 / n
let path = CGMutablePath()
for i in 0...segments {
let theta = CGFloat(i) / CGFloat(segments) * 2 * .pi
let ct = cos(theta)
let st = sin(theta)
let x = cx + (ct < 0 ? -1 : 1) * pow(abs(ct), twoOverN) * a
let y = cy + (st < 0 ? -1 : 1) * pow(abs(st), twoOverN) * a
if i == 0 {
path.move(to: CGPoint(x: x, y: y))
} else {
path.addLine(to: CGPoint(x: x, y: y))
}
}
path.closeSubpath()
return path
}
// MARK: - Drawing
private func drawMasterIcon(size: Int) -> CGImage {
let s = CGFloat(size)
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue
guard let ctx = CGContext(
data: nil,
width: size,
height: size,
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo
) else {
fputs("error: failed to create \(size)×\(size) bitmap context\n", stderr)
exit(1)
}
ctx.setShouldAntialias(true)
ctx.setAllowsAntialiasing(true)
ctx.interpolationQuality = .high
// Flip to top-left origin so "top-to-bottom gradient" is literal.
ctx.translateBy(x: 0, y: s)
ctx.scaleBy(x: 1, y: -1)
ctx.clear(CGRect(x: 0, y: 0, width: s, height: s))
let squircle = continuousRoundedSquare(size: s)
ctx.saveGState()
ctx.addPath(squircle)
ctx.clip()
let gradient = CGGradient(
colorsSpace: colorSpace,
colors: [Palette.charcoalTop, Palette.charcoalBottom] as CFArray,
locations: [0, 1]
)!
ctx.drawLinearGradient(
gradient,
start: CGPoint(x: s / 2, y: 0),
end: CGPoint(x: s / 2, y: s),
options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]
)
ctx.restoreGState()
// Viewfinder corner brackets: thick L-strokes, rounded caps/joins, inset ~18%.
let inset = s * 0.18
let bracketWidth = s * 0.095
let arm = s * 0.155
let centerline = inset + bracketWidth / 2
ctx.saveGState()
ctx.addPath(squircle)
ctx.clip()
ctx.setStrokeColor(Palette.white)
ctx.setLineWidth(bracketWidth)
ctx.setLineCap(.round)
ctx.setLineJoin(.round)
func strokeBracket(cornerX: CGFloat, cornerY: CGFloat, dirX: CGFloat, dirY: CGFloat) {
let path = CGMutablePath()
path.move(to: CGPoint(x: cornerX + dirX * arm, y: cornerY))
path.addLine(to: CGPoint(x: cornerX, y: cornerY))
path.addLine(to: CGPoint(x: cornerX, y: cornerY + dirY * arm))
ctx.addPath(path)
ctx.strokePath()
}
// Top-left, top-right, bottom-left, bottom-right.
strokeBracket(cornerX: centerline, cornerY: centerline, dirX: 1, dirY: 1)
strokeBracket(cornerX: s - centerline, cornerY: centerline, dirX: -1, dirY: 1)
strokeBracket(cornerX: centerline, cornerY: s - centerline, dirX: 1, dirY: -1)
strokeBracket(cornerX: s - centerline, cornerY: s - centerline, dirX: -1, dirY: -1)
// Bold redline slash over the frame, lower-left bracket area → upper-right.
let slashWidth = s * 0.078
ctx.setStrokeColor(Palette.redline)
ctx.setLineWidth(slashWidth)
ctx.setLineCap(.round)
ctx.setLineJoin(.round)
let slashInset = centerline + arm * 0.12
let slash = CGMutablePath()
slash.move(to: CGPoint(x: slashInset, y: s - slashInset))
slash.addLine(to: CGPoint(x: s - slashInset, y: slashInset))
ctx.addPath(slash)
ctx.strokePath()
ctx.restoreGState()
guard let image = ctx.makeImage() else {
fputs("error: failed to materialize master CGImage\n", stderr)
exit(1)
}
return image
}
private func scaledImage(_ image: CGImage, pixels: Int) -> CGImage {
if image.width == pixels && image.height == pixels {
return image
}
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
let bitmapInfo = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue
guard let ctx = CGContext(
data: nil,
width: pixels,
height: pixels,
bitsPerComponent: 8,
bytesPerRow: 0,
space: colorSpace,
bitmapInfo: bitmapInfo
) else {
fputs("error: failed to create \(pixels)×\(pixels) scale context\n", stderr)
exit(1)
}
ctx.interpolationQuality = .high
ctx.setShouldAntialias(true)
ctx.draw(image, in: CGRect(x: 0, y: 0, width: pixels, height: pixels))
guard let out = ctx.makeImage() else {
fputs("error: failed to scale image to \(pixels)px\n", stderr)
exit(1)
}
return out
}
private func writePNG(_ image: CGImage, to url: URL) {
let dir = url.deletingLastPathComponent()
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
if FileManager.default.fileExists(atPath: url.path) {
try? FileManager.default.removeItem(at: url)
}
guard let dest = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else {
fputs("error: cannot create PNG destination at \(url.path)\n", stderr)
exit(1)
}
CGImageDestinationAddImage(dest, image, nil)
if !CGImageDestinationFinalize(dest) {
fputs("error: failed to write PNG \(url.path)\n", stderr)
exit(1)
}
}
// MARK: - Paths / CLI
private func repoRoot() -> URL {
let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
let arg0 = URL(fileURLWithPath: CommandLine.arguments[0])
let scriptURL: URL
if arg0.path.hasPrefix("/") {
scriptURL = arg0.standardizedFileURL
} else {
scriptURL = cwd.appendingPathComponent(arg0.path).standardizedFileURL
}
let fromScript = scriptURL.deletingLastPathComponent().deletingLastPathComponent()
if FileManager.default.fileExists(atPath: fromScript.appendingPathComponent("Package.swift").path) {
return fromScript
}
if FileManager.default.fileExists(atPath: cwd.appendingPathComponent("Package.swift").path) {
return cwd
}
fputs("error: could not find repo root (Package.swift)\n", stderr)
exit(1)
}
private func parsePreviewPath() -> String? {
let args = CommandLine.arguments
var i = 1
var preview: String?
while i < args.count {
let arg = args[i]
if arg == "--preview" {
i += 1
guard i < args.count else {
fputs("error: --preview requires a path\n", stderr)
exit(1)
}
preview = args[i]
} else if arg.hasPrefix("--preview=") {
preview = String(arg.dropFirst("--preview=".count))
} else if arg == "--help" || arg == "-h" {
fputs("Usage: swift scripts/make-icon.swift [--preview PATH]\n", stderr)
exit(0)
} else {
fputs("error: unknown argument \(arg)\n", stderr)
fputs("Usage: swift scripts/make-icon.swift [--preview PATH]\n", stderr)
exit(1)
}
i += 1
}
return preview
}
private func runIconutil(iconset: URL, icns: URL) {
let proc = Process()
proc.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil")
proc.arguments = ["-c", "icns", iconset.path, "-o", icns.path]
proc.standardOutput = FileHandle.standardOutput
proc.standardError = FileHandle.standardError
do {
try proc.run()
proc.waitUntilExit()
} catch {
fputs("error: failed to launch iconutil: \(error)\n", stderr)
exit(1)
}
if proc.terminationStatus != 0 {
fputs("error: iconutil exited \(proc.terminationStatus)\n", stderr)
exit(1)
}
}
// MARK: - Main
let root = repoRoot()
let resources = root.appendingPathComponent("Resources", isDirectory: true)
let icnsURL = resources.appendingPathComponent("AppIcon.icns")
let previewPath = parsePreviewPath()
let fm = FileManager.default
print("==> Drawing \(masterSize)×\(masterSize) master")
let master = drawMasterIcon(size: masterSize)
let iconset = fm.temporaryDirectory.appendingPathComponent("Redline-AppIcon-\(UUID().uuidString).iconset", isDirectory: true)
do {
try fm.createDirectory(at: iconset, withIntermediateDirectories: true)
try fm.createDirectory(at: resources, withIntermediateDirectories: true)
print("==> Writing AppIcon.iconset")
for entry in iconsetEntries {
let img = scaledImage(master, pixels: entry.pixels)
writePNG(img, to: iconset.appendingPathComponent(entry.filename))
}
if fm.fileExists(atPath: icnsURL.path) {
try fm.removeItem(at: icnsURL)
}
print("==> Compiling \(icnsURL.path)")
runIconutil(iconset: iconset, icns: icnsURL)
try? fm.removeItem(at: iconset)
} catch {
try? fm.removeItem(at: iconset)
fputs("error: \(error)\n", stderr)
exit(1)
}
if let previewPath {
let previewURL = URL(fileURLWithPath: previewPath)
print("==> Writing 512px preview \(previewURL.path)")
writePNG(scaledImage(master, pixels: 512), to: previewURL)
}
print("App icon: \(icnsURL.path)")
+469
View File
@@ -0,0 +1,469 @@
#!/usr/bin/env bash
set -euo pipefail
# One-command Redline release: bump Info.plist, commit, signed build, zip,
# DMG, appcast, upload to mmd01, verify the public URLs.
# Hidden flag: --test — upload under .../redline/test/ and skip the git commit.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${ROOT}"
PLIST="${ROOT}/Info.plist"
PLISTBUDDY="/usr/libexec/PlistBuddy"
REMOTE_HOST="mmd01"
REMOTE_BASE="/opt/mmd-installer-content/cowork/redline"
PUBLIC_BASE="https://get.baobab-ts.com/cowork/redline"
BUNDLE_ID="ai.flowmaster.shotdeck"
# Used both as the fallback signing identity and as what build-app.sh itself
# still hardcodes for its own (pre-final) signing pass.
FALLBACK_SIGN_IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
usage() {
echo "Usage: $0 <version> [\"notes\"]" >&2
exit 1
}
TEST_MODE=0
VERSION=""
NOTES=""
NOTES_SET=0
for arg in "$@"; do
case "${arg}" in
--test)
TEST_MODE=1
;;
--help|-h)
usage
;;
--*)
echo "Unknown argument: ${arg}" >&2
usage
;;
*)
if [[ -z "${VERSION}" ]]; then
VERSION="${arg}"
elif [[ "${NOTES_SET}" -eq 0 ]]; then
NOTES="${arg}"
NOTES_SET=1
else
echo "Unexpected extra argument: ${arg}" >&2
usage
fi
;;
esac
done
if [[ -z "${VERSION}" ]]; then
usage
fi
if [[ ! "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][A-Za-z0-9.-]+)*$ ]]; then
echo "Version '${VERSION}' is not a semver (e.g. 1.2.3 or 0.0.0-test)." >&2
exit 1
fi
if [[ "${VERSION}" == *'/'* || "${VERSION}" == *'..'* ]]; then
echo "Version contains illegal path characters: ${VERSION}" >&2
exit 1
fi
if [[ "${TEST_MODE}" -eq 1 ]]; then
REMOTE_DIR="${REMOTE_BASE}/test"
PUBLIC_DIR="${PUBLIC_BASE}/test"
else
REMOTE_DIR="${REMOTE_BASE}"
PUBLIC_DIR="${PUBLIC_BASE}"
fi
APP_BUNDLE="${ROOT}/.build/Redline.app"
ZIP_NAME="Redline-${VERSION}.zip"
DMG_NAME="Redline-${VERSION}.dmg"
ZIP_PATH="${ROOT}/.build/${ZIP_NAME}"
DMG_PATH="${ROOT}/.build/Redline.dmg"
APPCAST_PATH="${ROOT}/.build/appcast.json"
ZIP_URL="${PUBLIC_DIR}/${ZIP_NAME}"
APPCAST_URL="${PUBLIC_DIR}/appcast.json"
if [[ "${TEST_MODE}" -eq 1 ]]; then
echo "==> Publish Redline ${VERSION} (test)"
else
echo "==> Publish Redline ${VERSION}"
fi
echo " remote: ${REMOTE_HOST}:${REMOTE_DIR}/"
echo " public: ${PUBLIC_DIR}/"
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "Not inside a git work tree." >&2
exit 1
fi
# Tracked files must match HEAD. Untracked files are ignored so this script
# can be dry-run (--test) before it is itself committed.
if [[ -n "$(git status --porcelain -uno)" ]]; then
echo "git tree is not clean; commit or stash before publishing." >&2
git status --porcelain -uno >&2
exit 1
fi
if [[ ! -x "${PLISTBUDDY}" ]]; then
echo "PlistBuddy not found at ${PLISTBUDDY}" >&2
exit 1
fi
if [[ ! -f "${PLIST}" ]]; then
echo "Info.plist not found at ${PLIST}" >&2
exit 1
fi
restore_plist() {
git checkout -- "${PLIST}" >/dev/null 2>&1 || true
}
if [[ "${TEST_MODE}" -eq 1 ]]; then
trap restore_plist EXIT
fi
CURRENT_BUILD="$("${PLISTBUDDY}" -c 'Print :CFBundleVersion' "${PLIST}")"
if [[ ! "${CURRENT_BUILD}" =~ ^[0-9]+$ ]]; then
echo "CFBundleVersion is not an integer: ${CURRENT_BUILD}" >&2
exit 1
fi
NEW_BUILD=$((CURRENT_BUILD + 1))
echo "==> Bumping Info.plist"
echo " CFBundleShortVersionString -> ${VERSION}"
echo " CFBundleVersion ${CURRENT_BUILD} -> ${NEW_BUILD}"
"${PLISTBUDDY}" -c "Set :CFBundleShortVersionString ${VERSION}" "${PLIST}"
"${PLISTBUDDY}" -c "Set :CFBundleVersion ${NEW_BUILD}" "${PLIST}"
if [[ "${TEST_MODE}" -eq 0 ]]; then
echo "==> Committing version bump on $(git rev-parse --abbrev-ref HEAD)"
git add "${PLIST}"
git commit -m "release: v${VERSION}"
else
echo "==> --test: skipping git commit of version bump"
fi
# --- Resolve the signing identity for the shipped artifacts -----------------
# REDLINE_KEYCHAIN (optional): a specific keychain to search/sign against,
# for hosts where the Developer ID identity does not live in the login
# keychain that codesign searches by default.
FIND_IDENTITY_ARGS=(-v -p codesigning)
CODESIGN_KEYCHAIN_ARGS=()
if [[ -n "${REDLINE_KEYCHAIN:-}" ]]; then
FIND_IDENTITY_ARGS+=("${REDLINE_KEYCHAIN}")
CODESIGN_KEYCHAIN_ARGS=(--keychain "${REDLINE_KEYCHAIN}")
fi
if [[ -n "${REDLINE_SIGN_IDENTITY:-}" ]]; then
SIGN_IDENTITY="${REDLINE_SIGN_IDENTITY}"
echo "==> Signing identity: ${SIGN_IDENTITY} (REDLINE_SIGN_IDENTITY)"
else
DEVELOPER_ID_LINE="$(security find-identity "${FIND_IDENTITY_ARGS[@]}" 2>/dev/null \
| grep -o '"Developer ID Application:[^"]*"' | head -n1 || true)"
DEVELOPER_ID="${DEVELOPER_ID_LINE//\"/}"
if [[ -n "${DEVELOPER_ID}" ]]; then
SIGN_IDENTITY="${DEVELOPER_ID}"
echo "==> Signing identity: ${SIGN_IDENTITY} (auto-detected Developer ID Application)"
else
SIGN_IDENTITY="${FALLBACK_SIGN_IDENTITY}"
echo
echo "************************************************************************"
echo "WARNING: signing with Apple Development identity — not Developer ID;"
echo "Gatekeeper will block first install on other Macs."
echo "************************************************************************"
echo
fi
fi
# Restricted HOMEs (agent sandboxes) hide the login keychain from codesign.
# Re-run signed steps with the account's real home when the identity is missing.
signing_home() {
if security find-identity -v -p codesigning 2>/dev/null | grep -Fq "${SIGN_IDENTITY}"; then
echo "${HOME}"
return
fi
local rh
rh="$(dscl . -read "/Users/$(id -un)" NFSHomeDirectory 2>/dev/null | awk '{print $2}')"
if [[ -n "${rh}" && -d "${rh}" ]]; then
echo "${rh}"
else
echo "${HOME}"
fi
}
run_signed() {
local sign_home
sign_home="$(signing_home)"
if [[ "${sign_home}" != "${HOME}" ]]; then
echo "==> Using HOME=${sign_home} so codesign can see the login keychain"
fi
HOME="${sign_home}" "$@"
}
echo "==> Building signed Redline.app"
run_signed ./scripts/build-app.sh
if [[ ! -d "${APP_BUNDLE}" ]]; then
echo "Signed app missing at ${APP_BUNDLE}" >&2
exit 1
fi
# build-app.sh always signs with its own hardcoded Apple Development identity
# first (it has to — that identifier+identity pair is what keeps the Screen
# Recording grant alive). Re-sign here with the identity actually resolved
# above, which is what ships. A no-op when the two happen to be the same.
echo "==> Signing ${APP_BUNDLE} with resolved identity"
run_signed codesign --force --options runtime --timestamp \
${CODESIGN_KEYCHAIN_ARGS[@]+"${CODESIGN_KEYCHAIN_ARGS[@]}"} \
--sign "${SIGN_IDENTITY}" \
--identifier "${BUNDLE_ID}" \
"${APP_BUNDLE}"
build_zip() {
mkdir -p "${ROOT}/.build"
(
cd "${ROOT}/.build"
rm -f "${ZIP_NAME}"
ditto -c -k --keepParent Redline.app "${ZIP_NAME}"
)
if [[ ! -s "${ZIP_PATH}" ]]; then
echo "Zip was not created at ${ZIP_PATH}" >&2
exit 1
fi
}
# Rebuilds the manual-installer DMG from whatever is currently at
# ${APP_BUNDLE} — never re-invokes build-app.sh, so a prior custom signature
# or notarization staple on ${APP_BUNDLE} survives into the DMG untouched.
build_dmg() {
local staging="${ROOT}/.build/dmg-staging"
local mount_point="${ROOT}/.build/dmg-mnt"
rm -rf "${staging}"
mkdir -p "${staging}"
ditto "${APP_BUNDLE}" "${staging}/Redline.app"
ln -s /Applications "${staging}/Applications"
mkdir -p "$(dirname "${DMG_PATH}")"
rm -f "${DMG_PATH}"
hdiutil create -volname "Redline" -srcfolder "${staging}" -ov -format UDZO "${DMG_PATH}"
if [[ -d "${mount_point}" ]] && /sbin/mount | grep -F -q "${mount_point}"; then
hdiutil detach "${mount_point}" || hdiutil detach "${mount_point}" -force
fi
rm -rf "${mount_point}"
mkdir -p "${mount_point}"
hdiutil attach "${DMG_PATH}" -nobrowse -readonly -mountpoint "${mount_point}"
local ok=1
if [[ ! -d "${mount_point}/Redline.app" ]]; then
echo "Verification failed: Redline.app missing from mounted DMG" >&2
ok=0
fi
if [[ "${ok}" -eq 1 && "$(readlink "${mount_point}/Applications" 2>/dev/null || true)" != "/Applications" ]]; then
echo "Verification failed: Applications does not point at /Applications" >&2
ok=0
fi
if [[ "${ok}" -eq 1 ]] && ! codesign --verify --deep --verbose=2 "${mount_point}/Redline.app"; then
ok=0
fi
hdiutil detach "${mount_point}" || hdiutil detach "${mount_point}" -force || true
if [[ "${ok}" -ne 1 ]]; then
exit 1
fi
if [[ ! -s "${DMG_PATH}" ]]; then
echo "DMG was not created at ${DMG_PATH}" >&2
exit 1
fi
}
echo "==> Zipping Redline.app -> ${ZIP_PATH}"
build_zip
SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')"
ZIP_BYTES="$(stat -f%z "${ZIP_PATH}")"
PUBDATE="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "==> Zip SHA256: ${SHA256}"
echo " Zip bytes: ${ZIP_BYTES}"
# --- Notarization (optional) -------------------------------------------------
# Either REDLINE_NOTARY_PROFILE (a `notarytool store-credentials` keychain
# profile) or all three of REDLINE_NOTARY_KEY_ID / REDLINE_NOTARY_ISSUER /
# REDLINE_NOTARY_KEY_PATH (App Store Connect API key). Absent both: skip.
NOTARIZED=0
NOTARY_CONFIGURED=0
if [[ -n "${REDLINE_NOTARY_PROFILE:-}" ]]; then
NOTARY_CONFIGURED=1
elif [[ -n "${REDLINE_NOTARY_KEY_ID:-}" && -n "${REDLINE_NOTARY_ISSUER:-}" && -n "${REDLINE_NOTARY_KEY_PATH:-}" ]]; then
NOTARY_CONFIGURED=1
fi
if [[ "${NOTARY_CONFIGURED}" -eq 1 ]]; then
echo "==> Submitting ${ZIP_PATH} to notarytool"
NOTARY_ARGS=(xcrun notarytool submit "${ZIP_PATH}" --wait --timeout 30m)
if [[ -n "${REDLINE_NOTARY_PROFILE:-}" ]]; then
NOTARY_ARGS+=(--keychain-profile "${REDLINE_NOTARY_PROFILE}")
else
NOTARY_ARGS+=(
--key "${REDLINE_NOTARY_KEY_PATH}"
--key-id "${REDLINE_NOTARY_KEY_ID}"
--issuer "${REDLINE_NOTARY_ISSUER}"
)
fi
set +e
NOTARY_OUTPUT="$("${NOTARY_ARGS[@]}" 2>&1)"
NOTARY_STATUS=$?
set -e
echo "${NOTARY_OUTPUT}"
if [[ "${NOTARY_STATUS}" -ne 0 ]]; then
echo "notarytool submit failed (exit ${NOTARY_STATUS})." >&2
exit 1
fi
if ! grep -qi 'status: *Accepted' <<<"${NOTARY_OUTPUT}"; then
echo "notarytool did not report Accepted." >&2
exit 1
fi
NOTARIZED=1
echo "==> Stapling ${APP_BUNDLE}"
xcrun stapler staple "${APP_BUNDLE}"
echo "==> Rebuilding zip from the stapled app"
build_zip
SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')"
ZIP_BYTES="$(stat -f%z "${ZIP_PATH}")"
echo " Zip SHA256: ${SHA256}"
echo " Zip bytes: ${ZIP_BYTES}"
echo "==> Rebuilding DMG from the stapled app"
build_dmg
echo "==> Stapling ${DMG_PATH}"
xcrun stapler staple "${DMG_PATH}"
else
echo "==> REDLINE_NOTARY_KEY_ID/ISSUER/KEY_PATH (or REDLINE_NOTARY_PROFILE) not set"
echo "NOT NOTARIZED"
echo "==> Building manual installer DMG"
build_dmg
fi
echo "==> Gatekeeper check: spctl -a -vv -t exec ${APP_BUNDLE}"
set +e
SPCTL_OUTPUT="$(spctl -a -vv -t exec "${APP_BUNDLE}" 2>&1)"
SPCTL_STATUS=$?
set -e
echo "${SPCTL_OUTPUT}"
if [[ "${SPCTL_STATUS}" -ne 0 ]] || ! grep -qi 'accepted' <<<"${SPCTL_OUTPUT}"; then
if [[ "${NOTARIZED}" -eq 1 ]]; then
echo "spctl did not report accepted for ${APP_BUNDLE} although it was notarized." >&2
exit 1
fi
echo "WARNING: Gatekeeper does not accept this build (not notarized). First install on other Macs needs right-click > Open." >&2
fi
TEAM_IDENTIFIER="$(codesign -dv "${APP_BUNDLE}" 2>&1 | awk -F= '/^TeamIdentifier=/{print $2}')"
if [[ -z "${TEAM_IDENTIFIER}" ]]; then
echo "No TeamIdentifier on ${APP_BUNDLE} — the build is not signed with a team identity; refusing to publish." >&2
exit 1
fi
echo "==> Writing ${APPCAST_PATH}"
python3 - "${VERSION}" "${ZIP_URL}" "${SHA256}" "${NOTES}" "${PUBDATE}" "${APPCAST_PATH}" "${NOTARIZED}" "${TEAM_IDENTIFIER}" <<'PY'
import json
import sys
version, zip_url, sha256, notes, pub_date, out_path, notarized, team_identifier = sys.argv[1:]
payload = {
"version": version,
"zipURL": zip_url,
"sha256": sha256,
"notes": notes,
"pubDate": pub_date,
"notarized": notarized == "1",
"teamIdentifier": team_identifier,
}
with open(out_path, "w", encoding="utf-8") as fh:
json.dump(payload, fh, indent=2)
fh.write("\n")
PY
echo "==> Uploading to ${REMOTE_HOST}:${REMOTE_DIR}/"
ssh -o BatchMode=yes "${REMOTE_HOST}" "mkdir -p '${REMOTE_DIR}'"
rsync -e "ssh -o BatchMode=yes" -av "${ZIP_PATH}" "${REMOTE_HOST}:${REMOTE_DIR}/${ZIP_NAME}"
rsync -e "ssh -o BatchMode=yes" -av "${DMG_PATH}" "${REMOTE_HOST}:${REMOTE_DIR}/Redline.dmg"
rsync -e "ssh -o BatchMode=yes" -av "${DMG_PATH}" "${REMOTE_HOST}:${REMOTE_DIR}/${DMG_NAME}"
rsync -e "ssh -o BatchMode=yes" -av "${APPCAST_PATH}" "${REMOTE_HOST}:${REMOTE_DIR}/appcast.json"
ssh -o BatchMode=yes "${REMOTE_HOST}" \
"chmod 644 \
'${REMOTE_DIR}/${ZIP_NAME}' \
'${REMOTE_DIR}/Redline.dmg' \
'${REMOTE_DIR}/${DMG_NAME}' \
'${REMOTE_DIR}/appcast.json'"
echo "==> Verifying public appcast ${APPCAST_URL}"
APPCAST_BODY=""
ok=0
attempt=1
while [[ "${attempt}" -le 15 ]]; do
if APPCAST_BODY="$(curl -fsS "${APPCAST_URL}")"; then
echo "${APPCAST_BODY}"
if grep -F -q "${VERSION}" <<<"${APPCAST_BODY}"; then
echo "OK: appcast contains ${VERSION}"
ok=1
break
fi
echo "appcast fetched but does not contain '${VERSION}' (attempt ${attempt})" >&2
else
echo "appcast fetch failed (attempt ${attempt})" >&2
fi
attempt=$((attempt + 1))
sleep 2
done
if [[ "${ok}" -ne 1 ]]; then
echo "Public appcast verification failed for ${APPCAST_URL}" >&2
exit 1
fi
echo "==> Verifying public zip HEAD ${ZIP_URL}"
ok=0
attempt=1
HEAD_OUT=""
while [[ "${attempt}" -le 15 ]]; do
HEAD_OUT="$(curl -sS -D - -o /dev/null -I "${ZIP_URL}" || true)"
echo "${HEAD_OUT}"
HTTP_CODE="$(awk 'BEGIN{c=""} toupper($1) ~ /^HTTP\//{c=$2} END{print c}' <<<"${HEAD_OUT}" | tr -d '\r')"
CONTENT_LENGTH="$(awk 'tolower($1)=="content-length:" {gsub("\r","",$2); print $2}' <<<"${HEAD_OUT}" | tail -n 1)"
if [[ "${HTTP_CODE}" == "200" && "${CONTENT_LENGTH}" == "${ZIP_BYTES}" ]]; then
echo "OK: zip HTTP ${HTTP_CODE}, Content-Length ${CONTENT_LENGTH} matches local ${ZIP_BYTES}"
ok=1
break
fi
echo "zip HEAD mismatch (attempt ${attempt}): HTTP '${HTTP_CODE}', Content-Length '${CONTENT_LENGTH}', local '${ZIP_BYTES}'" >&2
attempt=$((attempt + 1))
sleep 2
done
if [[ "${ok}" -ne 1 ]]; then
echo "Public zip verification failed for ${ZIP_URL}" >&2
exit 1
fi
echo
echo "Published v${VERSION}"
echo " identity: ${SIGN_IDENTITY}"
if [[ "${NOTARIZED}" -eq 1 ]]; then
echo " notarized: yes"
else
echo " notarized: no"
fi
echo " spctl: ${SPCTL_OUTPUT}"
echo " team: ${TEAM_IDENTIFIER}"
echo " appcast: ${APPCAST_URL}"
echo " zip: ${ZIP_URL}"
echo " sha256: ${SHA256}"
echo " dmg: ${PUBLIC_DIR}/${DMG_NAME}"
echo " dmg: ${PUBLIC_DIR}/Redline.dmg"
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
# Renders the headless panel PNGs and a sample review PDF for visual verification.
#
# ./scripts/render-panels.sh [output-directory]
#
# Builds nothing: run `swift build` (or ./scripts/build-app.sh) first. The output
# directory is printed at the end; nothing outside it is touched, and the isolated
# model means the real Application Support spool and the real age-limit preference
# are never read or written.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
OUT_DIR="${1:-$(mktemp -d /tmp/redline-panels.XXXXXX)}"
BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck"
if [[ ! -x "${BINARY}" ]]; then
BINARY="${ROOT}/.build/debug/Shotdeck"
fi
if [[ ! -x "${BINARY}" ]]; then
echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2
exit 1
fi
mkdir -p "${OUT_DIR}"
SHOTDECK_SNAPSHOT_DIR="${OUT_DIR}" "${BINARY}"
echo "Panels written to ${OUT_DIR}"
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
set -euo pipefail
# End-to-end UI run: the real panel, in the ACTIVE app, typed into with the keyboard
# and clicked with the mouse. Launched through LaunchServices ("open -n") because a
# background shell launch can never get a key window — macOS will not let it activate.
#
# ./scripts/run-e2e-ui.sh
#
# Builds a throwaway copy of the signed app under a separate bundle identifier
# (ai.flowmaster.shotdeck.e2e) so it can run alongside the installed Redline without
# touching /Applications, Ben's real captures, or his real preferences. It writes its
# results to a file and exits.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SOURCE_APP="${ROOT}/.build/Redline.app"
E2E_APP="${ROOT}/.build/RedlineE2E.app"
IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)"
BUNDLE_ID="ai.flowmaster.shotdeck.e2e"
WORK_DIR="$(mktemp -d /tmp/redline-e2e.XXXXXX)"
RESULT="${WORK_DIR}/result.txt"
if [[ ! -d "${SOURCE_APP}" ]]; then
echo "No ${SOURCE_APP} found. Run ./scripts/build-app.sh first." >&2
exit 1
fi
# A leftover instance from an interrupted run would hold the bundle identifier and
# make "open -n" a no-op.
pkill -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || true
for _ in $(seq 1 20); do
pgrep -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || break
sleep 0.2
done
rm -rf "${E2E_APP}"
ditto "${SOURCE_APP}" "${E2E_APP}"
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${BUNDLE_ID}" "${E2E_APP}/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleName Redline E2E" "${E2E_APP}/Contents/Info.plist"
# A menu-bar app (LSUIElement) is never activated by LaunchServices, and macOS only
# lets an active app own the key window the keyboard goes to. The test copy is a
# regular app for the duration of the run; the shipped app keeps LSUIElement.
/usr/libexec/PlistBuddy -c "Set :LSUIElement false" "${E2E_APP}/Contents/Info.plist"
codesign --force --options runtime \
--sign "${IDENTITY}" \
--identifier "${BUNDLE_ID}" \
"${E2E_APP}"
open -n "${E2E_APP}" --args --selftest e2e --root "${WORK_DIR}/storage" --result "${RESULT}"
for _ in $(seq 1 120); do
if [[ -f "${RESULT}" ]] && grep -qE "^E2E (PASS|FAIL)$" "${RESULT}"; then
break
fi
sleep 0.25
done
sleep 0.5
osascript -e "tell application id \"${BUNDLE_ID}\" to quit" >/dev/null 2>&1 || true
if [[ ! -f "${RESULT}" ]]; then
echo "E2E FAIL: no result file was written (${RESULT})" >&2
exit 1
fi
cat "${RESULT}"
grep -q "^E2E PASS$" "${RESULT}"
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
# Runs one in-process self-test phase against the built binary.
#
# ./scripts/run-selftest.sh panel
# ./scripts/run-selftest.sh onedrive
# ./scripts/run-selftest.sh sendtruth
#
# Prints the phase's PASS/FAIL lines and exits with the binary's status.
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PHASE="${1:-panel}"
BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck"
if [[ ! -x "${BINARY}" ]]; then
BINARY="${ROOT}/.build/debug/Shotdeck"
fi
if [[ ! -x "${BINARY}" ]]; then
echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2
exit 1
fi
REDLINE_SELFTEST_PHASE="${PHASE}" "${BINARY}"