Skip to content

Stop duplicate instances and fix update-check edge cases (SP4 batch D) - #21

Merged
donky-ey merged 7 commits into
mainfrom
port/sp4-d-app-lifecycle
Oct 16, 2026
Merged

donky-ey merged 7 commits into
mainfrom
port/sp4-d-app-lifecycle

Conversation

@donky-ey

@donky-ey donky-ey commented Oct 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

SP4 batch D: app lifecycle fixes ported from upstream. The spec and plan are in #20; this branch is cut from main and does not depend on it.

Upstream commits: chattymin#163 (de0ddd8), chattymin#174/chattymin#180 (052eacf), chattymin#175/chattymin#186 (566818a), chattymin#311 (1c695c7), chattymin#321 (a2ec364; its stray default.profraw is not ported).

Review changes (a4c3e72)

Known limitations

  • AppLogTests.testFlushDrainsAQueuedWriteBeforeReturning (AppLogTests.swift:24) relies on a 30 ms sleep in the sink to observe that write returns before the sink runs. It is inherited from upstream and left as is.
  • The SingleInstance decision is not atomic. Two instances launched at the same moment could both survive (for example, session restore and RunAtLoad at login). This is not demonstrated; a lock-file fix is tracked separately.

Review notes

  • Trade-off inherited from fix: stop a second instance from appearing when the login agent is registered chattymin/PokeTokenBar#163. The later instance yields, which is the launchd-owned one, so the survivor sits outside the KeepAlive crash-restart watchdog until the next login. Upstream chose this to keep the window the user is looking at, and the code comment records the trade-off. I kept upstream's choice; flipping it would be a one-line change.
  • Pre-existing issue, not changed here. The upgrade script's launchctl kickstart label is hard-coded to the release bundle ID, so a Dev build would kickstart the release agent. Noted as a follow-up.

Type of change

  • Bug fix
  • New feature
  • Refactor / cleanup
  • Documentation
  • Other:

UI changes

Before After
Popover update banner: one row with the message, then Update and Later Message on its own line (wraps), then a row with Skip this version and Update
Settings → Check now after skipping a version: "You're on the latest (vX)" "You skipped vY", with Show again and Update

No images; the canonical screenshots are regenerated at release.

Verification

  • ./scripts/test-gate.sh (after the review changes):
    • Executed 2015 tests, with 11 tests skipped and 0 failures (0 unexpected)
    • ✓ 게이트 통과 — 로직 코어 라인 커버리지 94.03% >= 75%
    • The first two runs failed only on the known-flaky SessionKeySettingsRenderingTests:46, the scroll-into-view timing that batch F's b716054 addresses. The third run was clean, and the test passed 5/5 when run alone. The machine was under heavy WindowServer load from other work.
  • The overlap tests passed 8/8 repeated runs.
  • Mutation checks:
    • Moving the guard after CrashReporter.install fails the order test.
    • Rewriting writeAndFlush as write()+flush() fails the routing test.
  • bash -n on the upgrade script body, with the cask name interpolated.
  • Not verified:
    • A real launchd duplicate. That needs the installed app and the login-item toggle; e2e.sh only counts instances.
    • The new banner layout in a running app.

Hotspot files

  • UI/PopoverView.swift: update banner only.
  • UI/SettingsView.swift: update result row only.
  • Core/Localization.swift: updateLater replaced by skipThisVersion; skippedVersion(_:) and showSkippedAgain added.
  • Core/UsageStore.swift: not touched.

Checklist

  • swift build and swift test pass locally
  • PR title and description are written in English
  • UI changes are described above (before/after — images optional)
  • No copyrighted assets, secrets, or private tooling references are committed (see CONTRIBUTING)
  • Tests were added or updated for this change

…gistered (upstream chattymin#163)

The login item is an SMAppService agent whose plist sets RunAtLoad, so
registering it while the app runs makes launchd exec the binary again.
LaunchServices' duplicate-launch protection does not cover a direct exec,
so turning on "Launch at login" left two menu bar icons, and both
instances wrote player-state.json.

At launch, the later instance yields (ordered by the kernel's p_starttime;
launchDate is nil for launchd-exec'd processes) before the status item and
before CrashReporter.install, so the yielding instance cannot clear the
crash marker. Missing or tied start times never yield.

Fork changes: the legacy login-item migration path does not exist here;
an extra test pins the guard's position before CrashReporter.install
(mutation-checked); e2e.sh asserts a single instance.
)

AppKit posts willTerminate and then exits, so markClean's async
"clean shutdown" line was usually lost. AppLog now writes through an
injectable AsyncLineLog backend, and exit paths (markClean, the duplicate
instance yield) use AppLog.writeAndFlush, which drains the queue before
returning. The bundled-app write guard stays, so tests never touch the
real log.

Fork change: AppLogTests' functionBody helper now stops at the nearest
boundary. Upstream preferred the next `func` over the next `///`, so with
the fork's member order the scanned body ran into writeIfChanged and
failed on its legitimate write(message) call. The routing guard still
fails when writeAndFlush is rewritten as write()+flush() (checked).
…pstream chattymin#175)

The detached upgrade script waited with 'pgrep -x PokeDexBar', which matches
any instance by name. With a duplicate instance running it always ran out
the 20 s wait and then swapped the bundle under a live app. Pass the
terminating PID as $3 and wait with 'kill -0'. The script body is now a
static constant so tests can pin it; a fork-only assertion checks that it
upgrades this app's cask.
Josa's digit table left out 0, so a number ending in 0 took the
no-final-consonant particle ("#20가", "v1.19.0를"). However it is read
(영, 십, 백, 천, 만), a trailing zero ends in a consonant. Found while
porting the skipped-version copy; the digit test never covered 0.
…ream chattymin#311)

The banner button said "Later" but permanently skipped that version, so
Check now then claimed the installed build was the latest. The button now
reads "Skip this version"; a skipped release is kept as `skipped`, and
Settings says so, with "Show again" and an Update button that installs it.
UpdateChecker takes injected UserDefaults so tests do not touch the real
skip key. Strings are ko/en/ja only; the Korean copy picks its particle
from the version.
…upstream chattymin#321)

check() stamped lastChecked before fetching, so one failed lookup (network,
bad response, unsafe URL) blocked the next attempt for 30 minutes. Record the
cooldown only when the release has a trusted github.com URL and a plain
MAJOR.MINOR.PATCH tag; malformed and prerelease tags count as failed checks.
An in-flight guard keeps overlapping popover opens to one fetch. The fetch is
injectable so tests never hit the network. Upstream's stray default.profraw
is not ported.
Upstream chattymin#321 made a check return immediately while another was running.
Here that regressed manual checks: pressing Check now in Settings while a
popover-triggered lookup was in flight returned at once and showed "up to
date" until the first lookup finished (up to 15 s on a slow network). On
main, a manual check always waited for its own lookup. Keep the in-flight
Task and have overlapping callers await it, so there is still one fetch and
every caller sees its result. testOverlappingChecksShareOneFetch now fails
on the early return; the failed-then-retry case moved to its own test.

Also remove AppLog.flush(): since the chattymin#174 port, production uses only
writeAndFlush.
@donky-ey
donky-ey merged commit 9f44e79 into main Oct 16, 2026
donky-ey pushed a commit that referenced this pull request Oct 16, 2026
Merging main brought #21's AppLogTests, whose two Thread.sleep(0.03)
calls are slow-sink stubs rather than waits: they make a flush that
returns before the write lands observable. Add both to the guard's
allowlist with that reason.

Its "write returns before the sink runs" assert, flagged as
timing-dependent in #21's review, only held if the test thread came back
within those 30 ms. The sink now parks on a semaphore until that assert
has looked; a write that ran the sink inline gives up after 5 s and
fails instead of hanging.

The guard strips comments with SourceScan.code, so a `//` inside a
string no longer hides the rest of the line.
donky-ey added a commit that referenced this pull request Oct 16, 2026
…d waits out of the tests (#23)

* test: wait for UI state instead of fixed sleeps, fixing the flaky session key settings test

SessionKeySettingsRenderingTests slept 500 ms and then asserted that the
session key field had scrolled into view. The scroll lands after an
untimed chain (render, onAppear, a queued main-actor Task, an 80 ms sleep,
a 0.25 s animated scrollTo): ~0.45 s on its own, 0.58-1.03 s inside the
full suite with coverage, where it failed 2 of 4 runs. Saturating the CPU
does not reproduce it; a congested main run loop does.

- Add waitUntil (async) and pumpRunLoop(until:) (sync) in Waiting.swift
  and wait for the field instead of a fixed time.
- Sweep the other fixed waits: convert the ones that wait for something to
  appear (shiny hatch sparkles, offer burst, first timeline tick) and make
  the gated-fetch poll fail instead of hanging; keep absence windows and
  sampling intervals, each with a `fixed-wait:` reason on the line.
- Tear down the sparkle test's view after measuring: once it stopped
  early, the still-running hatch reveal leaked into the plain control.
- FixedWaitGuardTests rejects new fixed waits without a stated reason.
- Record the rule in CLAUDE.md.

* test: skip the session key scroll check while the display is asleep

With the display asleep the window's display cycle stops, and SwiftUI
never lands the scrollTo: the section expands, the Task and scrollTo run
on time, but the clip view stays put, also with animations disabled and
with display()/displayIfNeeded()/CATransaction.flush() forced. The old
fixed-sleep version failed 3/3 in that state too, so no wait can pass it.

A session running the gate while nobody is at the Mac meets exactly
this. Skip with the reason instead; hosted runners keep their display
awake, so CI still runs the check. Record the case in CLAUDE.md.

* test: address review of the fixed-wait sweep

- Session key test: run the display-independent checks (expansion,
  sliders, navigation) first and regardless; wait until the field is
  inside the viewport and has stopped moving for 150 ms, not merely
  crossed it; skip only when that wait times out with the display
  asleep, judged at the timeout, and never when CI or GITHUB_ACTIONS is
  set (excusesMissingScroll, unit-tested).
- Sparkle controls wait for the moment sparkles would have appeared (the
  hatch reveal's onDone, the detail screen's first render) instead of a
  fixed 0.9 s window.
- Fold the per-file pump helpers into pumpRunLoop(for:because:), which
  takes the reason at each call site, and make the guard count wait
  primitives outside Waiting.swift against a closed allowlist; a marker
  on a helper's definition no longer hides its callers. Also catch clock
  sleeps, bare sleep/usleep, CFRunLoopRunInMode and asyncAfter.
- waitUntil returns at once when the task is cancelled instead of
  spinning the main actor.
- CLAUDE.md states what the guard does and does not cover.

* test: list AppLogTests' slow sinks and gate its not-landed-yet check

Merging main brought #21's AppLogTests, whose two Thread.sleep(0.03)
calls are slow-sink stubs rather than waits: they make a flush that
returns before the write lands observable. Add both to the guard's
allowlist with that reason.

Its "write returns before the sink runs" assert, flagged as
timing-dependent in #21's review, only held if the test thread came back
within those 30 ms. The sink now parks on a semaphore until that assert
has looked; a write that ran the sink inline gives up after 5 s and
fails instead of hanging.

The guard strips comments with SourceScan.code, so a `//` inside a
string no longer hides the rest of the line.

---------

Co-authored-by: 이동기 <ldg0831@midasin.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants