Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ open Package.swift # opens the package in Xcode for GUI editing / previ
the unsigned app opens without Gatekeeper's block. It verifies `Tic.zip.sha256` and quits only the
app process (the `pgrep -f` pattern is anchored, so `Tic --mcp` helpers and their wrappers survive).
Test it with `TIC_DEST=<tmp dir>` and a stub `open` first on `PATH`.
- **Verification** is a clean `swift build`, `swift test` (Swift Testing — `AppDatabaseTests`,
- **Verification** is a clean `swift build`, `swift test` (Swift Testing — `AppDatabaseTests`, `SyncTests`,
`TaskOutlineTests`, `NoteColorTests`, `TaskImageTests`, …), plus running the app. The outline logic lives in pure,
testable functions (`TaskOutline`) precisely so it can be covered without a DB or the main actor.
- `swift run` produces a bare executable (no bundle): fine for dev, but it has no Dock identity
Expand Down Expand Up @@ -108,9 +108,50 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw
(`WindowActions`), reusing `TaskOutline` for every structural rule so tools and UI can't diverge.
Clients speak **stdio** to `Tic --mcp` (`MCPProxy`), which pipes to the socket — one config works
for every client, and the server lives in the app next to the observers. Off by default
(`AppModel.mcpEnabled`). **Live updates are free:** tools write the DB, the existing
(`AppModel.mcpEnabled`); switched on, with per-client setup snippets, in Settings › AI Agents. **Live updates are free:** tools write the DB, the existing
`ValueObservation` streams push into open panels; the one addition is `observeNote(id:)` so the
controller streams its own note row too (an agent's title/colour/flag write shows live).
- **Sync between Macs (`Sync/`)** — one person's Macs share lists through a folder something else
syncs (iCloud Drive by default, or any Dropbox / Google Drive / OneDrive / Syncthing folder). **No
CloudKit:** every iCloud API needs an entitlement an ad-hoc app can't carry; plain files need none.
Each Mac writes only `devices/<id>.json` (a `SyncSnapshot`) and reads the others, so a sync service
never sees a conflict. `SyncMerge` (pure, like `TaskOutline`) is a state-based CRDT: every synced
field is a `Register` (newest stamp wins), a note's whole outline (order + nesting) is one
register, **delete always wins**, and stamps are `max(now, clock + 1)` so an edit made after seeing a
change beats it on a slow clock. `record` diffs the DB against `resolve(snapshot)` (not the raw
registers), so values this Mac adjusted on apply never look like local edits.
`AppDatabase.syncCycle` does record → merge → apply in **one write transaction**, touching only
synced columns: frame, `isOpen`, collapsed, float, all-Spaces and the note's own `sortIndex` stay
per Mac, and lists from another Mac arrive **closed**.
**Per list, opt-in** (`note.isSynced`, off for new lists): the switch is itself a register
(`sharing`), so off on one Mac is off on all, each keeping its copy. Every Mac still *records* every
list (`sync-state.json` holds them all), but the folder file is `published()` — synced lists only —
so a list switched back on merges with real stamps. Deletes are scoped: a list deleted while synced
is tombstoned everywhere; one deleted while not synced only leaves this Mac (the `syncLocalDelete`
table, filled by an `AFTER DELETE` trigger, notes the switch **at the moment of deletion** — a
switch-off followed at once by a delete wasn't recorded yet and used to delete everywhere; the fuzz
run caught it). Task tombstones are made only for lists that ever synced.
**Images** travel as `images/<sha256>.png` (immutable, named by `taskImage.hash`, filled on write or
lazily by the first sync); a task's `image` register holds the hash and crop. A picture whose file
hasn't arrived keeps this Mac's own register for that cycle (`waitingImages`), so it never reads as a
removal; files are loaded only when their hash checks out, and unreferenced ones are deleted after a
week. `observeTaskImageCrops` carries the hash so a replacement with the same crop reloads its thumbnail.
**UI:** ⋯ › Sync (shown only once sync is on in Settings) and Sync Now (for a list that syncs); the header's sync mark shows only while a cycle touches the
list (`FolderSync.activity`) and stays, orange, while there's a `problem`. `NoteWindowManager.sync` is
injected into note views as an optional environment object (nil in tests). `FolderSync` (`@MainActor`) runs a cycle at
start, 2 s after a synced edit (`observeSyncedChanges`, a column-limited region observation, so frame
drags don't trigger it), every 30 s, on wake, and at once on sleep; file IO is off the main actor
(an iCloud file may download as it's read). It keeps its own snapshot in `sync-state.json` beside the
DB and its device id in the `syncDeviceID` default (issued once, so a lost state file never leaves a
ghost Mac in the folder), refuses to recreate a folder whose parent vanished (an unmounted Dropbox reads as "can't
reach"), and skips files with a newer `schema` — bump it when the format changes **or `NoteColor` /
`NoteMaterial` gains a case**. Off by default (`syncEnabled` default).
- **Settings window (`SettingsView`)** — a SwiftUI `Settings` scene (⌘, and Tic › Settings… come
free) with three `Form(.grouped)` tabs: General (Launch at Login, version, update frequency + Check
Now), Sync (switch, folder, other Macs, and a switch per list), AI Agents (the MCP switch and
per-client snippets). The selected tab is remembered in the `settingsTab` default. The menu-bar item calls
`openSettings` after `NSApp.activate()`: a window opened from a menu-bar menu otherwise appears behind
the frontmost app.
- **App shell** — `TicApp` provides a `MenuBarExtra`; `main.swift` (not `@main`) routes `--mcp` to
the proxy, else `TicApp.main()`; `AppDelegate`
(`NSApplicationDelegateAdaptor`) builds the shared `AppDatabase` + `NoteWindowManager` and calls
Expand Down Expand Up @@ -214,8 +255,9 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw
(title/task/secondary/completed/checkbox) for a `Surface` (`.solid` uses per-theme tuned inks;
`.glass` uses adaptive `.primary`/`.secondary`). Views read a resolved `NoteTheme`, never branch
on material themselves.
- **Updates install in place, after a confirmation (`UpdateChecker` + `UpdateInstaller`).** Daily
GET of the GitHub releases list (one request brings every release's git-cliff notes, parsed by
- **Updates install in place, after a confirmation (`UpdateChecker` + `UpdateInstaller`).** A GET of
the GitHub releases list at launch and then daily or weekly (`Frequency`, Settings › General; Never
turns it off; `lastChecked` is remembered and re-evaluated hourly) (one request brings every release's git-cliff notes, parsed by
`ReleaseNotes`), compared numerically against `CFBundleShortVersionString` (nil under `swift run` →
checker off). The menu item and the banner open the update window (`UpdateView`, a floating panel
from `AppModel.openUpdate`): the notes for every version since the installed one, then Update Later /
Expand All @@ -242,8 +284,8 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw
banner, copy the build to `/Applications/Tic Dev.app`, give it a unique `CFBundleIdentifier`
(PlistBuddy), re-sign ad-hoc, then `open` it. Re-arm with
`defaults delete <bundle id> updateNotifiedVersion updateSeenVersion`, and delete the copy after.
- **Models are sync-friendly.** `Note`/`TaskItem` use `UUID` PKs + `updatedAt`; relationships and
defaults are chosen so CloudKit/iCloud sync stays feasible later (currently local-only).
- **Models are sync-friendly.** `Note`/`TaskItem` use `UUID` PKs, which is what lets `SyncMerge` key
every register by id across Macs.

### Swift 6 strict concurrency

Expand Down
80 changes: 77 additions & 3 deletions PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,84 @@ Tests/TicTests/
open panel. Toggle MCP off → the agent's next call fails with the stderr hint. Connect a second
client and confirm "2 connected" and that both see each other's writes via `get_note`.

## Sync between Macs (planned)

The request: one person, two Macs (work laptop + home desktop), used **one at a time**. Same lists
on both, changes carried between sessions, but **each Mac chooses which lists are open**.

### Decision: files in a synced folder, not CloudKit

CloudKit (and every other iCloud API) needs the iCloud entitlement, which an ad-hoc signed app can't
carry — it takes a paid Developer Program account, Developer ID signing, a provisioning profile and
notarisation. A synced *folder* needs none of that: Tic only reads and writes plain files, and
whatever syncs the folder does the networking. Default `iCloud Drive/Tic`; a "Choose Folder…"
picker covers a work Mac without personal iCloud (Dropbox, Google Drive, OneDrive, Syncthing).
Rejected: the SQLite file itself in iCloud Drive (WAL files sync separately → corruption), a server
of our own (accounts, hosting, breaks local-only), LAN peer-to-peer (the Macs are rarely on together).

### Shape: one file per Mac, a last-writer-wins CRDT

```
<sync folder>/devices/<deviceId>.json ← each Mac writes only its own file
<sync folder>/images/<sha256>.png ← immutable, named by content
```

- **Single writer per file**, so a sync service never sees a write conflict (no "conflicted copy").
- **Export** (a second or two after a DB change, via a GRDB observation on `note`/`task`): diff the
DB against this Mac's last snapshot, stamp the changed fields, write the file atomically. Offline
is fine — the write is local and uploads later.
- **Import** (launch, wake, ~30 s poll): read the other Macs' files, merge with the pure
`SyncMerge`, apply in one transaction, and copy the winners into this Mac's snapshot so it doesn't
re-claim them. SQLite stays the only source of truth; the schema is unchanged; open panels update
through the existing `ValueObservation`s.
- The merge is a state-based CRDT (commutative, idempotent), so file read order and repeats don't
matter. Tests assert exactly those properties plus the rules below.

| What | Rule |
|---|---|
| Task text, `isDone` (+ `completedAt`) | One register per field; newest stamp wins |
| Note title, colour, material, list options | One register per field; newest stamp wins |
| A note's task order + nesting | **One register for the whole outline** (`[(taskId, level)]`); newest wins; a task missing from the winner goes after its previous neighbour; written back via `applyStructuralUpdate` + `normalizedLevels` |
| Deletes | **Delete always wins**, even over a newer edit; a deleted note takes its tasks |
| Frame, `isOpen`, collapsed, float, all-Spaces, the note's own `sortIndex` | Never in the file — per Mac |
| Stamp | `max(now, highest stamp seen + 1)`; a same-millisecond tie goes to the larger encoded value, so every Mac picks the same winner |

Per-field registers mean a tick on one Mac and a text edit on the other both survive; the outline as
one register means two reorders never interleave into a jumble. Files carry a `schema` number — a
Mac that sees a newer one skips it and asks to update Tic.

- **Sync is per list and opt-in.** New lists stay on their Mac until switched on (⋯ › Sync, or the
list of lists in Settings › Sync). The switch is itself a register: off on one Mac is off on all,
every Mac keeps its copy, and only synced lists are written to the folder. Every Mac keeps recording
all its lists locally, so switching a list back on merges the copies field by field. A list deleted
while synced is deleted everywhere; one deleted while not synced only on that Mac (noted by a trigger
at deletion time). The note's sync mark shows only while a sync touches it (orange while the folder
can't be reached), and ⋯ has Sync Now.
- A list **created on the other Mac arrives closed** and shows up in the menu-bar Lists; opening it
makes it open on that Mac from then on.
- Settings › Sync lists each other Mac with **"Latest changes <time>"** — the real risk with
one-at-a-time use is the laptop lid closing before its upload finishes, and this lets the user see
whether changes arrived. Tic also writes pending edits at once when the Mac goes to sleep.
- Welcome notes never sync unless switched on, so nothing is duplicated.

**Accepted limits** (rare for one person on one Mac at a time): the same task's text edited on both
Macs before a sync → one version wins; a parent ticked on one Mac while a child is added under it on
the other → ticked parent with an unticked child; deletion markers are kept forever (tiny).
Automerge/Yjs would merge text character by character, but only help with simultaneous editing,
would make SQLite a second source of truth, and add a Rust dependency — revisit only for lists
shared live with other people.

### Build order

1. Check on one Mac that an ad-hoc `.app` can write to iCloud Drive (privacy prompt? re-asked after a
rebuild changes the signature?).
2. `SyncSnapshot` + `SyncMerge` (pure, unit-tested) and the export/import loop (`FolderSync`),
notes + tasks only, set up in a new **Settings window** (General · Sync · AI Agents), which also
takes over Launch at Login, update-check frequency, and the MCP setup window. *(Built.)*
3. Images as content-addressed files (`images/<sha256>.png`), and per-list opt-in. *(Built.)*

## Open follow-ups (post-MVP, not built now)

Daily-vs-planned rollover (the signature feature — a Today note that carries unfinished items to
tomorrow), recurring tasks, due dates + Reminders/Calendar, tags/priority, global quick-add
hotkey, **iCloud sync** (its own project with SQLite — either iCloud-Drive the DB file or build
CloudKit record sync; the UUID + `updatedAt` schema keeps this feasible), App Store
notarization.
hotkey, App Store notarization. (Sync between Macs: see above.)
30 changes: 16 additions & 14 deletions Sources/Tic/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ final class AppModel {
let database: AppDatabase
let windows: NoteWindowManager
let updates = UpdateChecker()
let sync: FolderSync
@ObservationIgnored private let mcp: MCPService

/// All saved notes (ascending `sortIndex`, i.e. creation order) — drives the menu bar list.
Expand All @@ -23,7 +24,6 @@ final class AppModel {

@ObservationIgnored private var notesObservation: Task<Void, Never>?
@ObservationIgnored private var searchWindow: NSWindow?
@ObservationIgnored private var mcpWindow: NSWindow?
@ObservationIgnored private var updateWindow: NSWindow?

private init() {
Expand All @@ -35,6 +35,9 @@ final class AppModel {
self.database = db
self.windows = NoteWindowManager(appDatabase: db)
self.mcp = MCPService(database: db)
let support = (try? AppDatabase.supportDirectory()) ?? FileManager.default.temporaryDirectory
self.sync = FolderSync(database: db, stateURL: support.appendingPathComponent("sync-state.json"))
windows.sync = sync
NSLog("[Tic] Database ready at \(db.path)")
mcp.onConnectionCountChange = { [weak self] count in
Task { @MainActor in self?.mcpConnections = count }
Expand All @@ -46,6 +49,10 @@ final class AppModel {
setFrame: { [weak self] id, rect in await self?.windows.setFrame(id, to: rect) },
focus: { [weak self] id in await self?.windows.focusNoteByID(id) }
)
// A list deleted on another Mac is already gone from the database; take its panel down.
sync.onNotesDeleted = { [weak self] ids in
for id in ids { Task { await self?.windows.closeNoteByID(id) } }
}
}

/// Run once after launch: open saved note panels, then start streaming the notes list.
Expand All @@ -55,6 +62,7 @@ final class AppModel {
applyLaunchAtLogin(launchAtLogin) // honor the saved preference (effective when packaged)
if mcpEnabled { applyMCPEnabled(true) }
updates.start()
sync.start()
}

private func startObservingNotes() {
Expand Down Expand Up @@ -90,6 +98,11 @@ final class AppModel {
NSApp.activate()
}

/// Whether a list syncs with the user's other Macs (Settings › Sync's list of lists).
func setSynced(_ note: Note, _ on: Bool) {
Task { [database] in try? await database.updateNoteSynced(id: note.id, isSynced: on) }
}

/// Permanently delete a note (and its tasks, via the FK cascade). Removed from the list
/// immediately so it can't be reopened during the async delete; the observation confirms.
func delete(_ note: Note) {
Expand All @@ -107,8 +120,8 @@ final class AppModel {
searchWindow.map(present)
}

/// A borderless-looking floating panel hosting `content` — the shared shell of the Lists palette,
/// the MCP setup window and the update window. Created once and reused.
/// A borderless-looking floating panel hosting `content` — the shared shell of the Lists palette
/// and the update window. Created once and reused.
private static func floatingPanel(width: CGFloat, height: CGFloat, content: some View) -> NSPanel {
let panel = NSPanel(
contentRect: NSRect(x: 0, y: 0, width: width, height: height),
Expand Down Expand Up @@ -153,17 +166,6 @@ final class AppModel {
searchWindow?.orderOut(nil)
}

/// Opens the "AI Agents (MCP)" setup window (the toggle + per-client install snippets). A single
/// reused, centered, floating panel — same treatment as the Lists palette.
func openMCPSetup() {
if mcpWindow == nil { mcpWindow = Self.floatingPanel(width: 680, height: 460, content: MCPSetupView()) }
mcpWindow.map(present)
}

func dismissMCPSetup() {
mcpWindow?.orderOut(nil)
}

/// Opens the update window (what's new since this version, then Update Now / Later) from the
/// menu item or the banner. Opening it counts as having seen the update.
func openUpdate() {
Expand Down
30 changes: 27 additions & 3 deletions Sources/Tic/Controllers/NoteController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ final class NoteController {
private(set) var tasks: [TaskItem] = []
/// The crop of each task's image, keyed by task id — a key's presence means the task has an image.
private(set) var imageCrops: [UUID: CGRect] = [:]
/// Each image's content hash, to spot a replaced image whose crop didn't change.
@ObservationIgnored private var imageHashes: [UUID: String] = [:]
/// Downsampled, uncropped bitmaps for drawing images on the note, loaded lazily per task.
private(set) var thumbnails: [UUID: CGImage] = [:]

Expand Down Expand Up @@ -71,9 +73,8 @@ final class NoteController {
imageObservation?.cancel()
imageObservation = Task { [weak self, db, noteID] in
do {
for try await crops in db.observeTaskImageCrops(noteId: noteID) {
self?.imageCrops = crops
self?.syncThumbnails()
for try await images in db.observeTaskImageCrops(noteId: noteID) {
self?.applyObservedImages(images)
}
} catch {
NSLog("[Tic] image observation ended for \(noteID): \(error)")
Expand Down Expand Up @@ -510,3 +511,26 @@ extension NoteController {
onNewNote?()
}
}

extension NoteController {
/// New crops, plus a fresh thumbnail for any image whose content changed under the same task — a
/// replacement made on another Mac, where the crop may well be the same. The old thumbnail stays up
/// until the new one is decoded.
fileprivate func applyObservedImages(_ images: [UUID: TaskImageState]) {
let replaced = images.compactMap { id, image -> UUID? in
guard let hash = image.hash, let known = imageHashes[id], known != hash else { return nil }
return id
}
imageHashes = images.compactMapValues(\.hash)
imageCrops = images.mapValues(\.crop)
syncThumbnails()
for id in replaced where !loadingThumbnails.contains(id) { loadThumbnail(id) }
}

/// Switches sync with the user's other Macs on or off for this list (⋯ › Sync).
func toggleSynced() {
note.isSynced.toggle()
let id = noteID, on = note.isSynced
Task { [db] in try? await db.updateNoteSynced(id: id, isSynced: on) }
}
}
Loading
Loading