Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Coucou — first public release

Louis Railleaf080da8065b
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..e0153739
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,17 @@
+---
+name: Bug report
+about: Something isn't working
+labels: bug
+---
+
+**What happened**
+
+**What you expected**
+
+**How to reproduce**
+
+**macOS version**
+
+**Mac model**
+
+**Coucou version**
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 00000000..25c2887f
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,9 @@
+---
+name: Feature request
+about: A new idea for Mochi
+labels: enhancement
+---
+
+**What would you like Mochi to do?**
+
+**Why would it be useful?**
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 00000000..0813b207
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,29 @@
+name: Build
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ build:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install XcodeGen
+ run: brew install xcodegen
+
+ - name: Generate project
+ run: cd NotchBuddy && xcodegen
+
+ - name: Build
+ run: |
+ xcodebuild \
+ -project NotchBuddy/NotchBuddy.xcodeproj \
+ -scheme NotchBuddy \
+ -configuration Release \
+ build \
+ CODE_SIGNING_ALLOWED=NO \
+ CODE_SIGNING_REQUIRED=NO
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..81fe0df4
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,53 @@
+name: Release
+
+on:
+ push:
+ tags:
+ - 'v*'
+
+jobs:
+ release:
+ runs-on: macos-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install XcodeGen
+ run: brew install xcodegen
+
+ - name: Generate project
+ run: cd NotchBuddy && xcodegen
+
+ - name: Build Release
+ run: |
+ xcodebuild \
+ -project NotchBuddy/NotchBuddy.xcodeproj \
+ -scheme NotchBuddy \
+ -configuration Release \
+ build \
+ CODE_SIGNING_ALLOWED=NO \
+ CODE_SIGNING_REQUIRED=NO \
+ CONFIGURATION_BUILD_DIR=${{ github.workspace }}/build
+
+ - name: Sign ad hoc
+ run: codesign --force --deep -s - "${{ github.workspace }}/build/Coucou.app"
+
+ - name: Zip
+ run: |
+ ditto -c -k --keepParent \
+ "${{ github.workspace }}/build/Coucou.app" \
+ "${{ github.workspace }}/Coucou.zip"
+
+ - name: Publish release
+ uses: softprops/action-gh-release@v2
+ with:
+ files: Coucou.zip
+ generate_release_notes: false
+ body: |
+ ## First launch
+
+ macOS will say it can't verify Coucou (it's a free side project, not notarized).
+
+ Either open **System Settings → Privacy & Security** and click **Open Anyway**, or run once in Terminal:
+ ```
+ xattr -dr com.apple.quarantine /Applications/Coucou.app
+ ```
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..a3be2384
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,20 @@
+# Build artefacts
+NotchBuddy/build/
+NotchBuddy/NotchBuddy.xcodeproj/project.xcworkspace/xcuserdata/
+NotchBuddy/NotchBuddy.xcodeproj/xcuserdata/
+*.xcuserstate
+
+# Xcode DerivedData (outside repo — listed for clarity)
+DerivedData/
+
+# macOS
+.DS_Store
+.AppleDouble
+.LSOverride
+
+# iCloud stubs
+*.icloud
+
+# Local only (never published)
+.claude/
+_prive/
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..ab0f1219
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,63 @@
+# Coucou (Notch Buddy) — règles du projet
+
+App macOS **perso** de Louis. Un petit personnage (piste « Mochi ») vit dans le notch du MacBook et montre ce que font ses agents : sessions Claude Code et workflows n8n. On peut tout faire depuis le notch : approuver, répondre, relancer, sauter au terminal, lancer une recherche Claude sur une fenêtre, déposer un fichier pour un prompt ou un mail.
+
+Pas d'App Store, pas de distribution. Un seul Mac, un seul utilisateur.
+
+## Sources de vérité (dans cet ordre)
+
+1. `design/prototype/notch-buddy.html` : prototype validé par Louis. **Le visuel, le personnage, les timings, les couleurs et les sons de l'app doivent être identiques.** Le moteur du personnage (classe `Bot` : `update()`, `draw()`, `eye()`) est à porter en Swift **ligne à ligne**, mêmes constantes, mêmes formules.
+2. `docs/SPEC.md` : comportement, dimensions, états, vues.
+3. `docs/INTEGRATIONS.md` : Claude Code, n8n, API Claude, Mail, fenêtres, fichiers.
+4. `design/captures/*.png` : captures cibles du prototype (Mochi) pour la QA visuelle.
+5. `NotchBuddy/Resources/sounds/*.wav` : sons rendus depuis le prototype. Les utiliser tels quels, ne pas en synthétiser d'autres.
+
+Si la spec et le prototype divergent sur un détail visuel, **le prototype gagne**. Si un doc Anthropic officiel contredit `INTEGRATIONS.md` (format des hooks, noms de modèles, outil de recherche web), **le doc officiel gagne** : vérifie-le avant d'implémenter.
+
+## Rangement du dossier
+
+- `NotchBuddy/` : l'app (code dans `Sources/`, sons dans `Resources/sounds/`, projet généré par `project.yml`).
+- `docs/` : `SPEC.md`, `INTEGRATIONS.md`. `docs/historique/` : anciens documents, pour mémoire seulement.
+- `design/` : prototype, captures cibles, séquences d'animation de référence.
+- `video/` : la vidéo de présentation et sa musique.
+
+Le mode tournage, le Studio 9:16 et le menu Debug ont été retirés : ne pas les recréer.
+
+## Stack imposée
+
+- Swift 6, SwiftUI + AppKit. Pas d'Electron, pas de web view pour l'UI.
+- Projet généré avec **XcodeGen** (`project.yml` versionné) ; build avec `xcodebuild`. Installer XcodeGen avec Homebrew si absent.
+- Cible de déploiement = la version de macOS installée sur ce Mac (`sw_vers -productVersion`).
+- App agent : `LSUIElement = YES` (pas d'icône dans le Dock), petit item dans la barre de menus pour les réglages.
+- Pas de sandbox. Signature « Sign to Run Locally ».
+- Secrets (clé API Anthropic, clé API n8n) dans le **Trousseau**, jamais en clair sur disque ni dans git.
+- Aucune dépendance tierce sauf si vraiment indispensable. Pas de Rive : le personnage est codé (SwiftUI `Canvas` + `TimelineView`).
+
+## Façon de travailler
+
+- Enchaîne les jalons M0 → M9 de `docs/SPEC.md` **sans demander de validation entre eux**. Louis ne veut rien avoir à faire.
+- Les seules raisons de t'arrêter pour lui parler :
+ 1. Xcode absent (il doit l'installer depuis l'App Store).
+ 2. Saisir une clé API (tu ouvres la fenêtre Réglages de l'app, il colle la clé).
+ 3. Valider le diff de `~/.claude/settings.json` avant écriture (voir INTEGRATIONS.md).
+ 4. Cliquer une autorisation macOS (Enregistrement de l'écran, Automatisation pour Mail/Safari/Terminal).
+- À la fin de **chaque** jalon :
+ 1. `xcodebuild` sans warning nouveau.
+ 2. Lance l'app et déclenche les états concernés.
+ 3. Capture la zone du notch avec `screencapture -x -R x,y,w,h` et **compare-la visuellement** aux fichiers de `design/captures/`. Corrige jusqu'à ce que ça corresponde.
+ 4. `git commit` avec un message clair.
+ 5. Donne à Louis un résumé de 3 lignes maximum, en français.
+- Tests unitaires pour la logique pure : machine à états de l'island, parsing des événements de hooks, parsing de l'API n8n, réponse de l'API Claude.
+
+## Interdits
+
+- Ne jamais écraser `~/.claude/settings.json` : sauvegarde datée, fusion, diff montré à Louis, puis écriture.
+- Ne jamais envoyer un mail sans clic explicite sur « Envoyer ».
+- Ne jamais approuver une permission Claude Code sans clic explicite (sauf règle « Toujours autoriser » créée par Louis).
+- Pas de télémétrie, pas d'appel réseau autre que : API Anthropic, instance n8n de Louis.
+- Ne pas bloquer une session Claude Code : si l'app est fermée ou ne répond pas, le hook rend la main immédiatement au terminal.
+- Performance : 0 % CPU quand l'island est masquée (animations en pause), moins de 3 % en compact.
+
+## Langue
+
+UI en français, phrases courtes, pas de jargon. Code, identifiants et commentaires en anglais.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..4a3ee4d6
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,32 @@
+# Contributing to Coucou
+
+Thanks for wanting to help Mochi grow up! 🫶
+
+## Getting started
+
+```bash
+brew install xcodegen
+cd NotchBuddy && xcodegen && open NotchBuddy.xcodeproj
+```
+
+Never edit `NotchBuddy.xcodeproj` by hand: change `project.yml` and run `xcodegen`.
+
+## Good first contributions
+
+- A new integration (a poller + a pill + a detail card). Look at `StripePoller.swift` for a compact example.
+- A new emote or sound for Mochi.
+- Bug fixes — please describe how to reproduce.
+
+## Rules of the house
+
+- Swift 6, SwiftUI + AppKit, **no third-party dependencies** unless there's really no other way.
+- Secrets go in the Keychain, never on disk or in git.
+- No telemetry, no network calls except to services the user configured.
+- Never block Claude Code: if the app doesn't answer, the hook must exit right away.
+- Never write `~/.claude/settings.json` without a backup and the user's confirmation.
+- Keep it light: 0 % CPU when the island is hidden.
+
+## Pull requests
+
+- One topic per PR, with a short GIF or screenshot for anything visual.
+- Build must pass with no new warnings.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..8efefc78
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Louis Raillé
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/Contents.json b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 00000000..1717346b
--- /dev/null
+++ b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,68 @@
+{
+ "images": [
+ {
+ "idiom": "mac",
+ "size": "16x16",
+ "scale": "1x",
+ "filename": "icon_16x16.png"
+ },
+ {
+ "idiom": "mac",
+ "size": "16x16",
+ "scale": "2x",
+ "filename": "[email protected]"
+ },
+ {
+ "idiom": "mac",
+ "size": "32x32",
+ "scale": "1x",
+ "filename": "icon_32x32.png"
+ },
+ {
+ "idiom": "mac",
+ "size": "32x32",
+ "scale": "2x",
+ "filename": "[email protected]"
+ },
+ {
+ "idiom": "mac",
+ "size": "128x128",
+ "scale": "1x",
+ "filename": "icon_128x128.png"
+ },
+ {
+ "idiom": "mac",
+ "size": "128x128",
+ "scale": "2x",
+ "filename": "[email protected]"
+ },
+ {
+ "idiom": "mac",
+ "size": "256x256",
+ "scale": "1x",
+ "filename": "icon_256x256.png"
+ },
+ {
+ "idiom": "mac",
+ "size": "256x256",
+ "scale": "2x",
+ "filename": "[email protected]"
+ },
+ {
+ "idiom": "mac",
+ "size": "512x512",
+ "scale": "1x",
+ "filename": "icon_512x512.png"
+ },
+ {
+ "idiom": "mac",
+ "size": "512x512",
+ "scale": "2x",
+ "filename": "[email protected]"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
\ No newline at end of file
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_128x128.png b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
new file mode 100644
index 00000000..80358b54
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_128x128.png differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..4aaea44e
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_16x16.png b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
new file mode 100644
index 00000000..4ab622d4
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_16x16.png differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..f678cb2e
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_256x256.png b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
new file mode 100644
index 00000000..78f8ba1d
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_256x256.png differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..5bd5779f
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_32x32.png b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
new file mode 100644
index 00000000..49d72b98
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_32x32.png differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..c618f663
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_512x512.png b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
new file mode 100644
index 00000000..0594e4be
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_512x512.png differ
diff --git a/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 00000000..af79fdc0
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/Contents.json b/NotchBuddy/Assets.xcassets/Contents.json
new file mode 100644
index 00000000..74d6a722
--- /dev/null
+++ b/NotchBuddy/Assets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info": {
+ "author": "xcode",
+ "version": 1
+ }
+}
diff --git a/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/Contents.json b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/Contents.json
new file mode 100644
index 00000000..42133dde
--- /dev/null
+++ b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/Contents.json
@@ -0,0 +1,26 @@
+{
+ "images": [
+ {
+ "idiom": "universal",
+ "scale": "1x",
+ "filename": "menubar.png"
+ },
+ {
+ "idiom": "universal",
+ "scale": "2x",
+ "filename": "[email protected]"
+ },
+ {
+ "idiom": "universal",
+ "scale": "3x",
+ "filename": "[email protected]"
+ }
+ ],
+ "info": {
+ "author": "xcode",
+ "version": 1
+ },
+ "properties": {
+ "template-rendering-intent": "template"
+ }
+}
\ No newline at end of file
diff --git a/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/menubar.png b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/menubar.png
new file mode 100644
index 00000000..b89ab1d3
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/menubar.png differ
diff --git a/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected]
new file mode 100644
index 00000000..b2ffb998
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected] differ
diff --git a/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected] b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected]
new file mode 100644
index 00000000..12c49ecb
Binary files /dev/null and b/NotchBuddy/Assets.xcassets/MenuBarIcon.imageset/[email protected] differ
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
new file mode 100644
index 00000000..a7d335ad
--- /dev/null
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -0,0 +1,432 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 77;
+ objects = {
+
+/* Begin PBXBuildFile section */
+ 065FCE817315454DE3F85F25 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };
+ 06BF5FD95E03010CAFDBF2D0 /* NotchBuddyApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */; };
+ 091EC3B2F1060D7EE1317E4E /* IslandWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D710BD7834228045869D0184 /* IslandWindowController.swift */; };
+ 0A267EE2955C7AD8E02A296C /* N8nPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = B89DA1A0C21AE3535A1760BB /* N8nPoller.swift */; };
+ 118FC4AE0AC74D84B4A134D8 /* VercelPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71718D1B87A39A4879DD2A9D /* VercelPoller.swift */; };
+ 1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */; };
+ 1F11EC4E6F604C612A1ADAD1 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2E4F18AA940EFF7E047B9F7 /* AppState.swift */; };
+ 2875610F701376BD65573386 /* WindowContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */; };
+ 2C798C3837A63B9BB561A1A0 /* HookServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */; };
+ 2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */; };
+ 2F36E3C6C073E968A682AFA4 /* NotionPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */; };
+ 3F19756A396F125EC711247F /* IslandTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */; };
+ 4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };
+ 56BE8C733F10A030A638FB60 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */; };
+ 5B9A00AFB0837731FA678E4E /* IslandStateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */; };
+ 60E361FFE84C387E5E3ED1AA /* SoundEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */; };
+ 62C4EE3F74DAA59764729E62 /* UploadCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */; };
+ 8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */; };
+ 967B525F7D3837F31D740D18 /* ResendPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */; };
+ C24D863967D8D32D828ED4B1 /* BotEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4540F630F8BA04AFFFA3979 /* BotEngine.swift */; };
+ C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */; };
+ C940B651C6CA952D99388E04 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 192844E7299DEED5C2372067 /* AppDelegate.swift */; };
+ CA3321C14A11FED94E48B3E3 /* IslandRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */; };
+ CD8DECA66B9E09C97E469DB9 /* BotCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */; };
+ DCAC390FF9EC65B945A15B24 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 506824380E9C80B9BC6DCE72 /* Assets.xcassets */; };
+ E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3232F258523DD8D09B670363 /* FileDropView.swift */; };
+ F06EE0A97CB77096A337AA8B /* sounds in Resources */ = {isa = PBXBuildFile; fileRef = C066E2B991AA4F56B2724263 /* sounds */; };
+ FAD78D74C6906D4EC8AA4101 /* UploadSequenceEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXFileReference section */
+ 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandRootView.swift; sourceTree = "<group>"; };
+ 192844E7299DEED5C2372067 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+ 1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SoundEngine.swift; sourceTree = "<group>"; };
+ 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StripePoller.swift; sourceTree = "<group>"; };
+ 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalcomPoller.swift; sourceTree = "<group>"; };
+ 3232F258523DD8D09B670363 /* FileDropView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileDropView.swift; sourceTree = "<group>"; };
+ 506824380E9C80B9BC6DCE72 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResendPoller.swift; sourceTree = "<group>"; };
+ 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadSequenceEngine.swift; sourceTree = "<group>"; };
+ 71718D1B87A39A4879DD2A9D /* VercelPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VercelPoller.swift; sourceTree = "<group>"; };
+ 79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HookServer.swift; sourceTree = "<group>"; };
+ 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
+ 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GithubPoller.swift; sourceTree = "<group>"; };
+ 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandTypes.swift; sourceTree = "<group>"; };
+ A14A61070D293AB4BBA303F7 /* NotchBuddy.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NotchBuddy.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotCanvasView.swift; sourceTree = "<group>"; };
+ A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeService.swift; sourceTree = "<group>"; };
+ B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UploadCanvasView.swift; sourceTree = "<group>"; };
+ B89DA1A0C21AE3535A1760BB /* N8nPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = N8nPoller.swift; sourceTree = "<group>"; };
+ BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotionPoller.swift; sourceTree = "<group>"; };
+ C066E2B991AA4F56B2724263 /* sounds */ = {isa = PBXFileReference; lastKnownFileType = folder; name = sounds; path = Resources/sounds; sourceTree = SOURCE_ROOT; };
+ C2E4F18AA940EFF7E047B9F7 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
+ C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GreetingCanvasView.swift; sourceTree = "<group>"; };
+ D4540F630F8BA04AFFFA3979 /* BotEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotEngine.swift; sourceTree = "<group>"; };
+ D710BD7834228045869D0184 /* IslandWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandWindowController.swift; sourceTree = "<group>"; };
+ D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandStateMachine.swift; sourceTree = "<group>"; };
+ E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowContextCapture.swift; sourceTree = "<group>"; };
+ F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotchBuddyApp.swift; sourceTree = "<group>"; };
+ FA02B08886939FF6FE0475DD /* IslandViewContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandViewContent.swift; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXGroup section */
+ 2D4550630644796DA0649B81 /* App */ = {
+ isa = PBXGroup;
+ children = (
+ 192844E7299DEED5C2372067 /* AppDelegate.swift */,
+ C2E4F18AA940EFF7E047B9F7 /* AppState.swift */,
+ A29F4C0B02BE91654D02AA0C /* BotCanvasView.swift */,
+ D4540F630F8BA04AFFFA3979 /* BotEngine.swift */,
+ 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */,
+ A83D5410BD030B243ADDCFF4 /* ClaudeService.swift */,
+ 3232F258523DD8D09B670363 /* FileDropView.swift */,
+ 8CB8B6E5E9DA6164F979E88F /* GithubPoller.swift */,
+ C581F7B1A9F14B281B60063E /* GreetingCanvasView.swift */,
+ 79D8DD79C3DD9BBC584B3CB2 /* HookServer.swift */,
+ 15A1A8206F73376F4CAF2057 /* IslandRootView.swift */,
+ D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */,
+ 8D3CE3617E9D336DDBA10F7A /* IslandTypes.swift */,
+ FA02B08886939FF6FE0475DD /* IslandViewContent.swift */,
+ D710BD7834228045869D0184 /* IslandWindowController.swift */,
+ B89DA1A0C21AE3535A1760BB /* N8nPoller.swift */,
+ F1BD8F3CAA60CF37640759E1 /* NotchBuddyApp.swift */,
+ BE03E03D1804B0B92C5C2DAD /* NotionPoller.swift */,
+ 61B5FDDE03F5F711146937E2 /* ResendPoller.swift */,
+ 7C1A7D5CBE2AC084A10C5FF3 /* SettingsView.swift */,
+ 1BE21C2B315D37AA70ED45E9 /* SoundEngine.swift */,
+ 2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,
+ B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */,
+ 6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */,
+ 71718D1B87A39A4879DD2A9D /* VercelPoller.swift */,
+ E91B733ADC638E14E9BB6EFA /* WindowContextCapture.swift */,
+ );
+ path = App;
+ sourceTree = "<group>";
+ };
+ 6CF11AAA7898712CF6DB364A /* Products */ = {
+ isa = PBXGroup;
+ children = (
+ A14A61070D293AB4BBA303F7 /* NotchBuddy.app */,
+ );
+ name = Products;
+ sourceTree = "<group>";
+ };
+ B382DF6D17081F63DA1CC08B /* Sources */ = {
+ isa = PBXGroup;
+ children = (
+ 2D4550630644796DA0649B81 /* App */,
+ );
+ path = Sources;
+ sourceTree = "<group>";
+ };
+ C8A9AE71DB5C532D78C7784B = {
+ isa = PBXGroup;
+ children = (
+ 506824380E9C80B9BC6DCE72 /* Assets.xcassets */,
+ D3593DF62D69E62DA5121807 /* Resources */,
+ B382DF6D17081F63DA1CC08B /* Sources */,
+ 6CF11AAA7898712CF6DB364A /* Products */,
+ );
+ sourceTree = "<group>";
+ };
+ D3593DF62D69E62DA5121807 /* Resources */ = {
+ isa = PBXGroup;
+ children = (
+ C066E2B991AA4F56B2724263 /* sounds */,
+ );
+ path = Resources;
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+ 12E59C1D41BFA3D2F7CDD7F5 /* NotchBuddy */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = DFC46BE61950064F9ADCEFC3 /* Build configuration list for PBXNativeTarget "NotchBuddy" */;
+ buildPhases = (
+ 002591692F471861383A29CD /* Sources */,
+ A0E1A749D68BF03D3FDE4473 /* Resources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = NotchBuddy;
+ packageProductDependencies = (
+ );
+ productName = NotchBuddy;
+ productReference = A14A61070D293AB4BBA303F7 /* NotchBuddy.app */;
+ productType = "com.apple.product-type.application";
+ };
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+ ACF315E0C1F7FECADF1B4FBC /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ BuildIndependentTargetsInParallel = YES;
+ LastUpgradeCheck = 2700;
+ TargetAttributes = {
+ 12E59C1D41BFA3D2F7CDD7F5 = {
+ ProvisioningStyle = Manual;
+ };
+ };
+ };
+ buildConfigurationList = 2B80F5D9D7D10C755DEF1E61 /* Build configuration list for PBXProject "NotchBuddy" */;
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ Base,
+ en,
+ );
+ mainGroup = C8A9AE71DB5C532D78C7784B;
+ minimizedProjectReferenceProxies = 1;
+ preferredProjectObjectVersion = 77;
+ productRefGroup = 6CF11AAA7898712CF6DB364A /* Products */;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ 12E59C1D41BFA3D2F7CDD7F5 /* NotchBuddy */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+ A0E1A749D68BF03D3FDE4473 /* Resources */ = {
+ isa = PBXResourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ DCAC390FF9EC65B945A15B24 /* Assets.xcassets in Resources */,
+ F06EE0A97CB77096A337AA8B /* sounds in Resources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+ 002591692F471861383A29CD /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ C940B651C6CA952D99388E04 /* AppDelegate.swift in Sources */,
+ 1F11EC4E6F604C612A1ADAD1 /* AppState.swift in Sources */,
+ CD8DECA66B9E09C97E469DB9 /* BotCanvasView.swift in Sources */,
+ C24D863967D8D32D828ED4B1 /* BotEngine.swift in Sources */,
+ 4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */,
+ 2DEB459FBD0BA3CEAAA5FDE9 /* ClaudeService.swift in Sources */,
+ E776C7D1DE5C62EA8D4BA3E3 /* FileDropView.swift in Sources */,
+ C808B654C84D9F71DBF8493A /* GithubPoller.swift in Sources */,
+ 8C32A0C3EAF536D3836F61D5 /* GreetingCanvasView.swift in Sources */,
+ 2C798C3837A63B9BB561A1A0 /* HookServer.swift in Sources */,
+ CA3321C14A11FED94E48B3E3 /* IslandRootView.swift in Sources */,
+ 5B9A00AFB0837731FA678E4E /* IslandStateMachine.swift in Sources */,
+ 3F19756A396F125EC711247F /* IslandTypes.swift in Sources */,
+ 065FCE817315454DE3F85F25 /* IslandViewContent.swift in Sources */,
+ 091EC3B2F1060D7EE1317E4E /* IslandWindowController.swift in Sources */,
+ 0A267EE2955C7AD8E02A296C /* N8nPoller.swift in Sources */,
+ 06BF5FD95E03010CAFDBF2D0 /* NotchBuddyApp.swift in Sources */,
+ 2F36E3C6C073E968A682AFA4 /* NotionPoller.swift in Sources */,
+ 967B525F7D3837F31D740D18 /* ResendPoller.swift in Sources */,
+ 56BE8C733F10A030A638FB60 /* SettingsView.swift in Sources */,
+ 60E361FFE84C387E5E3ED1AA /* SoundEngine.swift in Sources */,
+ 1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,
+ 62C4EE3F74DAA59764729E62 /* UploadCanvasView.swift in Sources */,
+ FAD78D74C6906D4EC8AA4101 /* UploadSequenceEngine.swift in Sources */,
+ 118FC4AE0AC74D84B4A134D8 /* VercelPoller.swift in Sources */,
+ 2875610F701376BD65573386 /* WindowContextCapture.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXSourcesBuildPhase section */
+
+/* Begin XCBuildConfiguration section */
+ 0C135EF4AD7F69AB24CA6CEF /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ COMBINE_HIDPI_IMAGES = YES;
+ ENABLE_SANDBOX = NO;
+ INFOPLIST_FILE = Resources/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ PRODUCT_BUNDLE_IDENTIFIER = fr.louisraille.NotchBuddy;
+ PRODUCT_NAME = Coucou;
+ SDKROOT = macosx;
+ };
+ name = Release;
+ };
+ 601A86C280BDF7077864F3F0 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ COMBINE_HIDPI_IMAGES = YES;
+ ENABLE_SANDBOX = NO;
+ INFOPLIST_FILE = Resources/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/../Frameworks",
+ );
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ PRODUCT_BUNDLE_IDENTIFIER = fr.louisraille.NotchBuddy;
+ PRODUCT_NAME = Coucou;
+ SDKROOT = macosx;
+ };
+ name = Debug;
+ };
+ CA9D2D4E8E2B8015D8EA90A2 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGNING_ALLOWED = NO;
+ CODE_SIGNING_REQUIRED = NO;
+ CODE_SIGN_STYLE = Manual;
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = dwarf;
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ ENABLE_TESTABILITY = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_DYNAMIC_NO_PIC = NO;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_OPTIMIZATION_LEVEL = 0;
+ GCC_PREPROCESSOR_DEFINITIONS = (
+ "$(inherited)",
+ "DEBUG=1",
+ );
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
+ MTL_FAST_MATH = YES;
+ ONLY_ACTIVE_ARCH = YES;
+ OTHER_SWIFT_FLAGS = "-strict-concurrency=complete";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SDKROOT = macosx;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 6.0;
+ };
+ name = Debug;
+ };
+ ECAB43E9AE0B6830F8D4C6BA /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ CLANG_ANALYZER_NONNULL = YES;
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+ CLANG_CXX_LIBRARY = "libc++";
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CLANG_ENABLE_OBJC_WEAK = YES;
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+ CLANG_WARN_BOOL_CONVERSION = YES;
+ CLANG_WARN_COMMA = YES;
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_ENUM_CONVERSION = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
+ CLANG_WARN_INT_CONVERSION = YES;
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+ CLANG_WARN_UNREACHABLE_CODE = YES;
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ CODE_SIGNING_ALLOWED = NO;
+ CODE_SIGNING_REQUIRED = NO;
+ CODE_SIGN_STYLE = Manual;
+ COPY_PHASE_STRIP = NO;
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+ ENABLE_HARDENED_RUNTIME = YES;
+ ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
+ GCC_C_LANGUAGE_STANDARD = gnu11;
+ GCC_NO_COMMON_BLOCKS = YES;
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+ GCC_WARN_UNUSED_FUNCTION = YES;
+ GCC_WARN_UNUSED_VARIABLE = YES;
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
+ MTL_ENABLE_DEBUG_INFO = NO;
+ MTL_FAST_MATH = YES;
+ OTHER_SWIFT_FLAGS = "-strict-concurrency=complete";
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ SDKROOT = macosx;
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ SWIFT_VERSION = 6.0;
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ 2B80F5D9D7D10C755DEF1E61 /* Build configuration list for PBXProject "NotchBuddy" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ CA9D2D4E8E2B8015D8EA90A2 /* Debug */,
+ ECAB43E9AE0B6830F8D4C6BA /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Debug;
+ };
+ DFC46BE61950064F9ADCEFC3 /* Build configuration list for PBXNativeTarget "NotchBuddy" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 601A86C280BDF7077864F3F0 /* Debug */,
+ 0C135EF4AD7F69AB24CA6CEF /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Debug;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = ACF315E0C1F7FECADF1B4FBC /* Project object */;
+}
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/NotchBuddy/NotchBuddy.xcodeproj/project.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 00000000..919434a6
--- /dev/null
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+ version = "1.0">
+ <FileRef
+ location = "self:">
+ </FileRef>
+</Workspace>
diff --git a/NotchBuddy/Resources/Info.plist b/NotchBuddy/Resources/Info.plist
new file mode 100644
index 00000000..227653eb
--- /dev/null
+++ b/NotchBuddy/Resources/Info.plist
@@ -0,0 +1,34 @@
+<?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>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleDisplayName</key>
+ <string>Coucou</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>fr.louisraille.NotchBuddy</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>Coucou</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.1</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSUIElement</key>
+ <true/>
+ <key>NSAccessibilityUsageDescription</key>
+ <string>Pour lire le titre de la fenêtre active et l'attacher comme contexte.</string>
+ <key>NSAppleEventsUsageDescription</key>
+ <string>Pour sauter au terminal et envoyer des mails.</string>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>NSSupportsAutomaticGraphicsSwitching</key>
+ <true/>
+</dict>
+</plist>
diff --git a/NotchBuddy/Resources/sounds/annoyed.wav b/NotchBuddy/Resources/sounds/annoyed.wav
new file mode 100644
index 00000000..04e7653f
Binary files /dev/null and b/NotchBuddy/Resources/sounds/annoyed.wav differ
diff --git a/NotchBuddy/Resources/sounds/approval.wav b/NotchBuddy/Resources/sounds/approval.wav
new file mode 100644
index 00000000..df865d38
Binary files /dev/null and b/NotchBuddy/Resources/sounds/approval.wav differ
diff --git a/NotchBuddy/Resources/sounds/approve.wav b/NotchBuddy/Resources/sounds/approve.wav
new file mode 100644
index 00000000..ee3d7a4c
Binary files /dev/null and b/NotchBuddy/Resources/sounds/approve.wav differ
diff --git a/NotchBuddy/Resources/sounds/attach.wav b/NotchBuddy/Resources/sounds/attach.wav
new file mode 100644
index 00000000..33cc68aa
Binary files /dev/null and b/NotchBuddy/Resources/sounds/attach.wav differ
diff --git a/NotchBuddy/Resources/sounds/blip.wav b/NotchBuddy/Resources/sounds/blip.wav
new file mode 100644
index 00000000..8359a948
Binary files /dev/null and b/NotchBuddy/Resources/sounds/blip.wav differ
diff --git a/NotchBuddy/Resources/sounds/close.wav b/NotchBuddy/Resources/sounds/close.wav
new file mode 100644
index 00000000..39c02713
Binary files /dev/null and b/NotchBuddy/Resources/sounds/close.wav differ
diff --git a/NotchBuddy/Resources/sounds/dizzy.wav b/NotchBuddy/Resources/sounds/dizzy.wav
new file mode 100644
index 00000000..598b5d9b
Binary files /dev/null and b/NotchBuddy/Resources/sounds/dizzy.wav differ
diff --git a/NotchBuddy/Resources/sounds/error.wav b/NotchBuddy/Resources/sounds/error.wav
new file mode 100644
index 00000000..89738c96
Binary files /dev/null and b/NotchBuddy/Resources/sounds/error.wav differ
diff --git a/NotchBuddy/Resources/sounds/finish.wav b/NotchBuddy/Resources/sounds/finish.wav
new file mode 100644
index 00000000..c430e46c
Binary files /dev/null and b/NotchBuddy/Resources/sounds/finish.wav differ
diff --git a/NotchBuddy/Resources/sounds/greet.wav b/NotchBuddy/Resources/sounds/greet.wav
new file mode 100644
index 00000000..7fa6d0c1
Binary files /dev/null and b/NotchBuddy/Resources/sounds/greet.wav differ
diff --git a/NotchBuddy/Resources/sounds/gulp.wav b/NotchBuddy/Resources/sounds/gulp.wav
new file mode 100644
index 00000000..c1680acf
Binary files /dev/null and b/NotchBuddy/Resources/sounds/gulp.wav differ
diff --git a/NotchBuddy/Resources/sounds/hover.wav b/NotchBuddy/Resources/sounds/hover.wav
new file mode 100644
index 00000000..8d069404
Binary files /dev/null and b/NotchBuddy/Resources/sounds/hover.wav differ
diff --git a/NotchBuddy/Resources/sounds/love.wav b/NotchBuddy/Resources/sounds/love.wav
new file mode 100644
index 00000000..8c5b4740
Binary files /dev/null and b/NotchBuddy/Resources/sounds/love.wav differ
diff --git a/NotchBuddy/Resources/sounds/open.wav b/NotchBuddy/Resources/sounds/open.wav
new file mode 100644
index 00000000..5a169d00
Binary files /dev/null and b/NotchBuddy/Resources/sounds/open.wav differ
diff --git a/NotchBuddy/Resources/sounds/peek.wav b/NotchBuddy/Resources/sounds/peek.wav
new file mode 100644
index 00000000..33dc5f3b
Binary files /dev/null and b/NotchBuddy/Resources/sounds/peek.wav differ
diff --git a/NotchBuddy/Resources/sounds/pop.wav b/NotchBuddy/Resources/sounds/pop.wav
new file mode 100644
index 00000000..e551c18d
Binary files /dev/null and b/NotchBuddy/Resources/sounds/pop.wav differ
diff --git a/NotchBuddy/Resources/sounds/proud.wav b/NotchBuddy/Resources/sounds/proud.wav
new file mode 100644
index 00000000..d6ad4687
Binary files /dev/null and b/NotchBuddy/Resources/sounds/proud.wav differ
diff --git a/NotchBuddy/Resources/sounds/question.wav b/NotchBuddy/Resources/sounds/question.wav
new file mode 100644
index 00000000..9b6e0251
Binary files /dev/null and b/NotchBuddy/Resources/sounds/question.wav differ
diff --git a/NotchBuddy/Resources/sounds/rate.wav b/NotchBuddy/Resources/sounds/rate.wav
new file mode 100644
index 00000000..2a0cc03f
Binary files /dev/null and b/NotchBuddy/Resources/sounds/rate.wav differ
diff --git a/NotchBuddy/Resources/sounds/search.wav b/NotchBuddy/Resources/sounds/search.wav
new file mode 100644
index 00000000..eac10791
Binary files /dev/null and b/NotchBuddy/Resources/sounds/search.wav differ
diff --git a/NotchBuddy/Resources/sounds/send.wav b/NotchBuddy/Resources/sounds/send.wav
new file mode 100644
index 00000000..f493f0c5
Binary files /dev/null and b/NotchBuddy/Resources/sounds/send.wav differ
diff --git a/NotchBuddy/Resources/sounds/slap.wav b/NotchBuddy/Resources/sounds/slap.wav
new file mode 100644
index 00000000..d82a676c
Binary files /dev/null and b/NotchBuddy/Resources/sounds/slap.wav differ
diff --git a/NotchBuddy/Resources/sounds/sleep.wav b/NotchBuddy/Resources/sounds/sleep.wav
new file mode 100644
index 00000000..41453cca
Binary files /dev/null and b/NotchBuddy/Resources/sounds/sleep.wav differ
diff --git a/NotchBuddy/Resources/sounds/think.wav b/NotchBuddy/Resources/sounds/think.wav
new file mode 100644
index 00000000..49c1dde9
Binary files /dev/null and b/NotchBuddy/Resources/sounds/think.wav differ
diff --git a/NotchBuddy/Resources/sounds/tick.wav b/NotchBuddy/Resources/sounds/tick.wav
new file mode 100644
index 00000000..6039f66a
Binary files /dev/null and b/NotchBuddy/Resources/sounds/tick.wav differ
diff --git a/NotchBuddy/Resources/sounds/wink.wav b/NotchBuddy/Resources/sounds/wink.wav
new file mode 100644
index 00000000..61d71fcf
Binary files /dev/null and b/NotchBuddy/Resources/sounds/wink.wav differ
diff --git a/NotchBuddy/Resources/sounds/work.wav b/NotchBuddy/Resources/sounds/work.wav
new file mode 100644
index 00000000..523ffc69
Binary files /dev/null and b/NotchBuddy/Resources/sounds/work.wav differ
diff --git a/NotchBuddy/Resources/sounds/yawn.wav b/NotchBuddy/Resources/sounds/yawn.wav
new file mode 100644
index 00000000..c96c66df
Binary files /dev/null and b/NotchBuddy/Resources/sounds/yawn.wav differ
diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swift
new file mode 100644
index 00000000..fae5920e
--- /dev/null
+++ b/NotchBuddy/Sources/App/AppDelegate.swift
@@ -0,0 +1,77 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class AppDelegate: NSObject, NSApplicationDelegate {
+ var statusItem: NSStatusItem?
+ private(set) var islandController: IslandWindowController?
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ // Ignore SIGPIPE — prevents crash when nb-hook closes socket before we write response
+ signal(SIGPIPE, SIG_IGN)
+ // Warm up Keychain cache on main thread BEFORE any poller or view touches it
+ _ = KeychainStore.shared
+ NSApp.setActivationPolicy(.accessory)
+ setupMenuBarItem()
+ setupIsland()
+ }
+
+ // MARK: - Menu bar
+
+ private func setupMenuBarItem() {
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
+ guard let button = statusItem?.button else { return }
+ button.image = NSImage(named: "MenuBarIcon") ?? NSImage(systemSymbolName: "circle.fill", accessibilityDescription: "Coucou")
+ button.image?.size = NSSize(width: 24, height: 18)
+ button.image?.accessibilityDescription = "Coucou"
+ button.image?.isTemplate = true
+
+ let menu = NSMenu()
+ menu.addItem(withTitle: "Open Coucou", action: #selector(openIsland), keyEquivalent: "")
+ menu.addItem(.separator())
+ menu.addItem(withTitle: "Settings…", action: #selector(openSettings), keyEquivalent: ",")
+ menu.addItem(.separator())
+ menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
+
+ statusItem?.menu = menu
+ }
+
+ // MARK: - Actions
+
+ @objc private func openIsland() {
+ islandController?.expand(to: .overview)
+ }
+
+ private var settingsWindow: NSWindow?
+
+ @objc private func openSettings() {
+ if let w = settingsWindow, w.isVisible { w.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true); return }
+ let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 480, height: 540),
+ styleMask: [.titled, .closable], backing: .buffered, defer: false)
+ win.title = "Settings — Coucou"
+ win.contentView = NSHostingView(rootView: SettingsView())
+ win.center()
+ win.isReleasedWhenClosed = false
+ settingsWindow = win
+ win.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+
+ // MARK: - Island setup
+
+ private func setupIsland() {
+ islandController = IslandWindowController()
+ islandController?.showWindow(nil)
+ islandController?.fsm.launch()
+ HookServer.shared.start()
+ N8nPoller.shared.start()
+ VercelPoller.shared.start()
+ ResendPoller.shared.start()
+ GithubPoller.shared.start()
+ StripePoller.shared.start()
+ CalcomPoller.shared.start()
+ NotionPoller.shared.start()
+ NotificationCenter.default.addObserver(self, selector: #selector(openSettings),
+ name: .openFullSettings, object: nil)
+ }
+}
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
new file mode 100644
index 00000000..ed3bd038
--- /dev/null
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -0,0 +1,447 @@
+import Foundation
+import SwiftUI
+import Combine
+
+// Integration pills — always-present, never purged
+extension AgentTask {
+ /// All available integration pills. Claude is always active; others are opt-in (max 4).
+ static let integrationAgents: [AgentTask] = [
+ AgentTask(id: "integration_claude", name: "VS Code", color: "#F5F6F8", state: .idle, steps: [], source: .claudeCode, isIntegration: true),
+ AgentTask(id: "integration_resend", name: "Resend", color: "#22C55E", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_n8n", name: "n8n", color: "#F29B38", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_vercel", name: "Vercel", color: "#7C5CFF", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_github", name: "GitHub", color: "#F4505E", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_notion", name: "Notion", color: "#8C8C8C", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_calcom", name: "Cal.com", color: "#C9956A", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ AgentTask(id: "integration_stripe", name: "Stripe", color: "#0570DE", state: .idle, steps: [], source: .n8n, isIntegration: true),
+ ]
+
+ /// IDs that can be toggled (VS Code is always on and excluded from this list)
+ static let toggleableIntegrationIds: [String] = [
+ "integration_resend", "integration_n8n", "integration_vercel", "integration_github",
+ "integration_notion", "integration_calcom", "integration_stripe",
+ ]
+
+}
+
+@MainActor
+final class AppState: ObservableObject {
+ static let shared = AppState()
+
+ // Island state
+ @Published var mode: IslandMode = .hidden
+ @Published var view: IslandView = .overview
+
+ // Tasks
+ @Published var tasks: [AgentTask] = []
+ @Published var focusId: String? = nil
+
+ // Bot state override
+ @Published var stateOverride: BotState? = nil
+
+ // Real notch dimensions (set by IslandWindowController on launch)
+ var notchWidth: CGFloat = IslandConst.notchWidth
+ var notchHeight: CGFloat = IslandConst.notchHeight
+
+ // Last app active before NotchBuddy (for window context capture)
+ var lastExternalApp: NSRunningApplication? = nil
+
+ // Bot drag-attach state (hides original bot while ghost follows cursor)
+ @Published var isDraggingBot: Bool = false
+
+ // Mouse tracking
+ var mousePosition: CGPoint = .zero
+ var lastMouseMove: Date = .now
+ var lastActivity: Date = .now
+ var isPresent: Bool = true
+
+ // Pinned (alerts that stay open, never auto-close)
+ var isPinned: Bool = false
+
+ // Upload progress (0-1) — set to 1.0 only at completion; animation is time-based
+ @Published var uploadProgress: Double = 0
+
+ // Upload animation timing (non-published — TimelineViews read these directly)
+ var uploadStartTime: Date?
+ var uploadDuration: Double = 2.4
+
+ // File drag-over state (mailbox morph glow + mouth spring)
+ @Published var fileDragOver: Bool = false
+
+ // Sound enabled — persisted
+ @Published var soundEnabled: Bool = true {
+ didSet { UserDefaults.standard.set(soundEnabled, forKey: "soundEnabled") }
+ }
+
+ // Sound volume (0–0.2) — persisted, synced to SoundEngine
+ @Published var soundVolume: Double = 0.12 {
+ didSet {
+ UserDefaults.standard.set(soundVolume, forKey: "soundVolume")
+ SoundEngine.shared.volume = Float(soundVolume)
+ }
+ }
+
+ // Context for prompt (window attach / file)
+ @Published var promptContext: PromptContext? = nil
+
+ // Dropped file (set during upload flow)
+ @Published var droppedFile: DroppedFile? = nil
+
+ // Short note message (shown in NoteView)
+ @Published var noteMessage: String? = nil
+
+ // Auto-close delay — persisted
+ @Published var autoCloseInterval: TimeInterval = 15 {
+ didSet { UserDefaults.standard.set(autoCloseInterval, forKey: "autoCloseInterval") }
+ }
+
+ // Absence interval — persisted
+ var absenceInterval: TimeInterval = 3 * 60 {
+ didSet { UserDefaults.standard.set(absenceInterval, forKey: "absenceInterval") }
+ }
+
+ // Greeting threshold — how long hidden before greeting on reappear (default 2 min)
+ var greetThresholdSeconds: TimeInterval = 120 {
+ didSet { UserDefaults.standard.set(greetThresholdSeconds, forKey: "greetThreshold") }
+ }
+
+ // Hotkey to show island (e.g. ⌘⇧N)
+ @Published var hotkeyEnabled: Bool = false {
+ didSet { UserDefaults.standard.set(hotkeyEnabled, forKey: "hotkeyEnabled") }
+ }
+ var hotkeyFlags: UInt = NSEvent.ModifierFlags([.command, .shift]).rawValue {
+ didSet { UserDefaults.standard.set(Int(hotkeyFlags), forKey: "hotkeyFlags") }
+ }
+ var hotkeyCode: UInt16 = 45 { // 'n'
+ didSet { UserDefaults.standard.set(Int(hotkeyCode), forKey: "hotkeyCode") }
+ }
+
+ // Vercel project filter — empty = watch all projects
+ @Published var vercelProjectFilter: Set<String> = [] {
+ didSet {
+ if let data = try? JSONEncoder().encode(Array(vercelProjectFilter)) {
+ UserDefaults.standard.set(data, forKey: "vercelProjectFilter")
+ }
+ }
+ }
+
+ // n8n workflow filter — empty = watch all workflows
+ @Published var n8nWorkflowFilter: Set<String> = [] {
+ didSet {
+ if let data = try? JSONEncoder().encode(Array(n8nWorkflowFilter)) {
+ UserDefaults.standard.set(data, forKey: "n8nWorkflowFilter")
+ }
+ }
+ }
+
+ // Active integration pills (VS Code excluded — always on). Max 4.
+ @Published var activeIntegrations: Set<String> = ["integration_resend", "integration_n8n", "integration_vercel", "integration_github"] {
+ didSet {
+ if let data = try? JSONEncoder().encode(Array(activeIntegrations)) {
+ UserDefaults.standard.set(data, forKey: "activeIntegrations")
+ }
+ }
+ }
+
+ // Pending API result
+ @Published var searchResult: SearchResult? = nil
+
+ // Vercel deployments (populated by VercelPoller)
+ @Published var vercelDeployments: [VercelDeployment] = []
+
+ // Resend emails (populated by ResendPoller)
+ @Published var resendEmails: [ResendEmail] = []
+ @Published var resendTotal: Int? = nil
+
+ // GitHub stats (populated by GithubPoller)
+ @Published var githubStats: GitHubStats? = nil
+
+ // Stripe (populated by StripePoller)
+ @Published var stripePayments: [StripePayment] = []
+ @Published var stripeBalance: Int = 0 // raw balance in cents
+ @Published var stripeDisplayBalance: Int = 0 // animated balance target
+ @Published var stripeCurrency: String = "eur"
+ @Published var stripeLoaded: Bool = false // true after first successful poll
+ @Published var stripeError: String? = nil // last API error (nil = ok)
+
+ // Cal.com (populated by CalcomPoller)
+ @Published var calcomBookings: [CalcomBooking] = []
+ @Published var calcomLoaded: Bool = false
+ @Published var calcomError: String? = nil
+
+ // Notion (populated by NotionPoller)
+ @Published var notionPages: [NotionPage] = []
+ @Published var notionLoaded: Bool = false
+ @Published var notionError: String? = nil
+
+ // Chat conversation history
+ @Published var chatHistory: [ChatMessage] = []
+
+ // Pending approval request from Claude Code hook
+ @Published var pendingApproval: ApprovalInfo? = nil
+
+ // Always-allow mode (set by "Toujours autoriser" button)
+ @Published var alwaysAllow: Bool = false
+
+
+ // MARK: - Init (loads persisted settings)
+
+ private init() {
+ let ud = UserDefaults.standard
+
+ if let v = ud.object(forKey: "soundEnabled") as? Bool { soundEnabled = v }
+ if let v = ud.object(forKey: "soundVolume") as? Double { soundVolume = v }
+ // Migrate old 60s default → 15s
+ if let v = ud.object(forKey: "autoCloseInterval") as? Double {
+ autoCloseInterval = (v == 60) ? 15 : v
+ }
+ if let v = ud.object(forKey: "absenceInterval") as? Double { absenceInterval = v }
+ if let v = ud.object(forKey: "greetThreshold") as? Double { greetThresholdSeconds = v }
+ if let v = ud.object(forKey: "hotkeyEnabled") as? Bool { hotkeyEnabled = v }
+ if let v = ud.object(forKey: "hotkeyFlags") as? Int { hotkeyFlags = UInt(v) }
+ if let v = ud.object(forKey: "hotkeyCode") as? Int { hotkeyCode = UInt16(v) }
+ if let d = ud.data(forKey: "vercelProjectFilter"),
+ let a = try? JSONDecoder().decode([String].self, from: d) { vercelProjectFilter = Set(a) }
+ if let d = ud.data(forKey: "n8nWorkflowFilter"),
+ let a = try? JSONDecoder().decode([String].self, from: d) { n8nWorkflowFilter = Set(a) }
+ if let d = ud.data(forKey: "activeIntegrations"),
+ let a = try? JSONDecoder().decode([String].self, from: d) { activeIntegrations = Set(a) }
+
+ // Sync SoundEngine volume on launch
+ SoundEngine.shared.volume = Float(soundVolume)
+
+ // Always load integration pills
+ loadIntegrationTasks()
+ }
+
+ // MARK: - Computed
+
+ var focusTask: AgentTask? {
+ tasks.first { $0.id == focusId } ?? tasks.first
+ }
+
+ var effectiveState: BotState {
+ stateOverride ?? focusTask?.state ?? .idle
+ }
+
+ // MARK: - Task management
+
+ func addTask(_ task: AgentTask) {
+ guard !tasks.contains(where: { $0.id == task.id }) else { return }
+ tasks.append(task)
+ if focusId == nil { focusId = task.id }
+ syncMode()
+ syncView()
+ }
+
+ func removeTask(id: String) {
+ tasks.removeAll { $0.id == id }
+ if focusId == id { focusId = tasks.first?.id }
+ syncMode()
+ syncView()
+ }
+
+ func updateTask(id: String, state: BotState) {
+ guard let idx = tasks.firstIndex(where: { $0.id == id }) else { return }
+ tasks[idx].state = state
+ }
+
+ func setFocus(_ id: String) {
+ guard let idx = tasks.firstIndex(where: { $0.id == id }) else { return }
+ focusId = id
+ tasks[idx].pillBadge = nil // clear badge when user brings task to focus
+ }
+
+ func syncMode() {
+ // If no tasks and not expanded/peek, go hidden
+ if tasks.isEmpty && mode == .compact {
+ mode = .hidden
+ } else if !tasks.isEmpty && mode == .hidden && isPresent {
+ mode = .compact
+ }
+ }
+
+ func syncView() {
+ guard mode == .expanded else { return }
+ if view == .empty && !tasks.isEmpty { view = .overview }
+ else if view == .overview && tasks.isEmpty { view = .empty }
+ }
+
+ /// Load integration pills respecting activeIntegrations. VS Code always loads. Safe to call multiple times.
+ func loadIntegrationTasks() {
+ for task in AgentTask.integrationAgents {
+ let shouldLoad = task.id == "integration_claude" || activeIntegrations.contains(task.id)
+ let loaded = tasks.contains(where: { $0.id == task.id })
+ if shouldLoad && !loaded { tasks.append(task) }
+ if !shouldLoad && loaded { tasks.removeAll { $0.id == task.id } }
+ }
+ if focusId == nil { focusId = "integration_claude" }
+ syncMode()
+ }
+
+ /// Toggle an integration pill on/off. VS Code cannot be toggled. Max 4 active at once.
+ func toggleIntegration(_ id: String) {
+ guard id != "integration_claude" else { return }
+ if activeIntegrations.contains(id) {
+ activeIntegrations.remove(id)
+ tasks.removeAll { $0.id == id }
+ if focusId == id { focusId = "integration_claude" }
+ } else {
+ guard activeIntegrations.count < 4 else { return }
+ activeIntegrations.insert(id)
+ if let task = AgentTask.integrationAgents.first(where: { $0.id == id }),
+ !tasks.contains(where: { $0.id == id }) {
+ tasks.append(task)
+ }
+ }
+ syncMode()
+ }
+
+}
+
+// MARK: - Supporting types
+
+enum PromptContext {
+ case window(appName: String, title: String, url: String?)
+ case file(name: String, fileURL: URL?)
+}
+
+struct DroppedFile {
+ var url: URL
+ var name: String
+}
+
+struct SearchResult {
+ var title: String
+ var items: [ResultItem]
+ var note: String?
+}
+
+struct ResultItem {
+ var label: String
+ var detail: String
+ var url: String?
+}
+
+// MARK: - Vercel
+
+struct VercelDeployment: Identifiable {
+ let id: String
+ let projectName: String
+ let url: String
+ let state: String // "READY", "ERROR", "CANCELED"
+ let createdAt: Date
+ let commitMessage: String?
+ let branch: String?
+
+ var isSuccess: Bool { state == "READY" }
+ var statusLabel: String { isSuccess ? "Ready" : (state == "CANCELED" ? "Canceled" : "Error") }
+ var timeAgo: String {
+ let diff = Date().timeIntervalSince(createdAt)
+ if diff < 60 { return "just now" }
+ if diff < 3600 { return "\(Int(diff/60))m" }
+ if diff < 86400 { return "\(Int(diff/3600))h" }
+ return "\(Int(diff/86400))d"
+ }
+}
+
+// MARK: - Resend
+
+struct ResendEmail: Identifiable {
+ let id: String
+ let to: [String]
+ let subject: String
+ let createdAt: Date
+ let lastEvent: String // "delivered", "bounced", "complained", "opened", etc.
+
+ var recipientShort: String {
+ guard let first = to.first else { return "?" }
+ return first.components(separatedBy: "@").first ?? first
+ }
+ var timeAgo: String {
+ let diff = Date().timeIntervalSince(createdAt)
+ if diff < 60 { return "just now" }
+ if diff < 3600 { return "\(Int(diff/60))m" }
+ if diff < 86400 { return "\(Int(diff/3600))h" }
+ return "\(Int(diff/86400))d"
+ }
+ var isDelivered: Bool { lastEvent == "delivered" }
+}
+
+// MARK: - GitHub
+
+struct GitHubStats {
+ let totalRepos: Int
+ let totalStars: Int
+}
+
+// MARK: - Stripe
+
+struct StripePayment: Identifiable, Equatable {
+ let id: String
+ let amount: Int // in cents/smallest unit
+ let currency: String
+ let description: String?
+ let createdAt: Date
+ let status: String // "succeeded", "pending", "failed"
+
+ var amountFormatted: String { String(format: "%.2f", Double(amount) / 100.0) }
+ var isSuccess: Bool { status == "succeeded" }
+ var timeAgo: String {
+ let diff = Date().timeIntervalSince(createdAt)
+ if diff < 60 { return "just now" }
+ if diff < 3600 { return "\(Int(diff/60))m" }
+ if diff < 86400 { return "\(Int(diff/3600))h" }
+ return "\(Int(diff/86400))d"
+ }
+}
+
+// MARK: - Cal.com
+
+struct CalcomBooking: Identifiable, Equatable {
+ let id: Int
+ let title: String
+ let startTime: Date
+ let endTime: Date
+ let status: String
+ let attendeeName: String?
+ let attendeeEmail: String?
+ let attendeeNotes: String?
+
+ var isActive: Bool { status == "ACCEPTED" || status == "PENDING" }
+ var timeLabel: String {
+ let f = DateFormatter(); f.dateFormat = "HH:mm"; return f.string(from: startTime)
+ }
+ var dayKey: String {
+ let c = Calendar.current.dateComponents([.year, .month, .day], from: startTime)
+ return "\(c.year!)-\(String(format: "%02d", c.month!))-\(String(format: "%02d", c.day!))"
+ }
+}
+
+// MARK: - Notion
+
+struct NotionPage: Identifiable {
+ let id: String
+ let title: String
+ let emoji: String?
+ let lastEditedAt: Date
+ let url: String
+
+ var timeAgo: String {
+ let diff = Date().timeIntervalSince(lastEditedAt)
+ if diff < 60 { return "now" }
+ if diff < 3600 { return "\(Int(diff/60))m" }
+ if diff < 86400 { return "\(Int(diff/3600))h" }
+ return "\(Int(diff/86400))d"
+ }
+}
+
+// MARK: - Chat
+
+enum ChatRole { case user, assistant }
+
+struct ChatMessage: Identifiable {
+ let id = UUID()
+ let role: ChatRole
+ let content: String
+}
diff --git a/NotchBuddy/Sources/App/BotCanvasView.swift b/NotchBuddy/Sources/App/BotCanvasView.swift
new file mode 100644
index 00000000..866bda8e
--- /dev/null
+++ b/NotchBuddy/Sources/App/BotCanvasView.swift
@@ -0,0 +1,178 @@
+import SwiftUI
+
+/// SwiftUI wrapper: TimelineView drives a Canvas that calls BotEngine.draw().
+/// Uses a shared engine per-task; the main bot uses AppState's shared engine.
+struct BotCanvasView: View {
+ @ObservedObject var state: AppState
+ var particleOverhang: CGFloat = 0
+
+ // One engine per view instance (main bot)
+ @StateObject private var engine = BotEngine()
+
+ var body: some View {
+ TimelineView(.animation(paused: state.mode == .hidden)) { timeline in
+ Canvas { context, size in
+ let now = timeline.date.timeIntervalSinceReferenceDate
+ let dtRaw = min(0.05, now - engine.lastTime)
+ let dt = dtRaw
+ engine.lookX = lookX(state: state, size: size)
+ engine.lookY = lookY(state: state, size: size)
+ engine.particleOverhang = particleOverhang
+ // Widen slot when file is hovering over the mailbox (morph > 0.5)
+ // Open mouth (hover=0.20R) when file dragged over box; close when not
+ if engine.morph > 0.3 {
+ engine.slotHTarget = state.fileDragOver ? 0.20 : 0
+ } else {
+ engine.slotHTarget = 0
+ if engine.morph < 0.05 { engine.slotH = 0; engine.slotHVel = 0 }
+ }
+ // Integration pills have a fixed brand color → use it as bodyColor.
+ // Claude Code tasks use state-based gradient (working=blue, thinking=purple, etc.).
+ engine.bodyColor = (state.focusTask?.isIntegration == true)
+ ? cgColorFromHex(state.focusTask!.color)
+ : nil
+ engine.update(dt: dt)
+ engine.drawHandsBehind(context: context, size: size)
+ engine.draw(context: context, size: size)
+ engine.drawHandsAndExtras(context: context, size: size)
+ }
+ }
+ .onChange(of: state.effectiveState) { _, newState in
+ engine.setState(newState)
+ }
+ .onChange(of: state.view) { _, newView in
+ // Morph up when upload view is active
+ if state.mode == .expanded && newView == .upload {
+ engine.anim("morph", keys: [TweenKey(target: 1, duration: 550, ease: Ease.inOut)])
+ } else if newView != .upload && newView != .uploading && engine.morph > 0.01 {
+ // Any other view (not mid-gulp): morph back
+ engine.anim("morph", keys: [TweenKey(target: 0, duration: 550, ease: Ease.inOut)])
+ }
+ }
+ .onChange(of: state.mode) { _, newMode in
+ // Hard-reset morph when island collapses
+ if newMode != .expanded {
+ engine.tweens.removeValue(forKey: "morph")
+ engine.locks.remove("morph")
+ engine.morph = 0
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .triggerEmote)) { notif in
+ if let emote = notif.object as? BotEmote {
+ engine.triggerEmote(emote)
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .triggerSlap)) { _ in
+ engine.slap()
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botBlink)) { _ in
+ engine.blink()
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botSetTgEs)) { notif in
+ if let v = notif.object as? CGFloat {
+ engine.tgEs = v
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botGulp)) { _ in
+ engine.gulp()
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botMorphTo)) { notif in
+ if let target = notif.object as? CGFloat {
+ let dur: CGFloat = target > 0.5 ? 550 : 650
+ engine.anim("morph", keys: [TweenKey(target: target, duration: dur, ease: Ease.inOut)])
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botGreet)) { _ in
+ engine.greet()
+ }
+ .onAppear {
+ engine.setState(state.effectiveState, force: true)
+ }
+ }
+
+ private func lookX(state: AppState, size: CGSize) -> CGFloat {
+ let screen = NSScreen.main ?? NSScreen.screens[0]
+ let (islandW, islandH) = islandSize(mode: state.mode, view: state.view,
+ progress: state.uploadProgress,
+ nw: state.notchWidth, nh: state.notchHeight)
+ let (botCx, _, _, _) = botPosition(mode: state.mode, view: state.view,
+ islandW: islandW, islandH: islandH,
+ uploadProgress: state.uploadProgress)
+ // Island is centered on screen; bot is at botCx within island coords
+ let botScreenX = screen.frame.midX - islandW / 2 + botCx
+ return tanh((state.mousePosition.x - botScreenX) / 260)
+ }
+
+ private func lookY(state: AppState, size: CGSize) -> CGFloat {
+ let (islandW, islandH) = islandSize(mode: state.mode, view: state.view,
+ progress: state.uploadProgress,
+ nw: state.notchWidth, nh: state.notchHeight)
+ let actualH: CGFloat = (state.mode == .expanded && state.view == .prompt)
+ ? min(300, 240 + CGFloat(state.chatHistory.count) * 40)
+ : islandH
+ let (_, botCy, _, _) = botPosition(mode: state.mode, view: state.view,
+ islandW: islandW, islandH: actualH,
+ uploadProgress: state.uploadProgress)
+ // Island top = screen top → bot screen Y = botCy from island top
+ return -tanh((state.mousePosition.y - botCy) / 200)
+ }
+}
+
+/// Mini bot canvas (for agent pills/column)
+struct MiniBotCanvasView: View {
+ let task: AgentTask
+ @StateObject private var engine: BotEngine
+
+ init(task: AgentTask) {
+ self.task = task
+ _engine = StateObject(wrappedValue: {
+ let e = BotEngine()
+ e.isMini = true
+ e.bodyColor = cgColorFromHex(task.color)
+ return e
+ }())
+ }
+
+ var body: some View {
+ TimelineView(.animation) { timeline in
+ Canvas { context, size in
+ let now = timeline.date.timeIntervalSinceReferenceDate
+ let dt = min(0.05, now - engine.lastTime)
+ engine.update(dt: dt)
+ engine.draw(context: context, size: size)
+ }
+ }
+ .onChange(of: task.state) { _, newState in
+ engine.setState(newState)
+ }
+ .onAppear {
+ engine.setState(task.state, force: true)
+ if let emote = task.emote {
+ engine.setPermanentEmote(emote)
+ }
+ // Direct eye override takes priority (e.g. .wide eyes for Research)
+ if let eye = task.miniEye {
+ engine.permanentEye = eye
+ engine.eyeOverride = eye
+ engine.eyeOverrideUntil = .greatestFiniteMagnitude
+ }
+ }
+ }
+}
+
+// MARK: - CGColor from hex string
+
+func cgColorFromHex(_ hex: String) -> CGColor? {
+ let h = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
+ guard let val = UInt64(h, radix: 16) else { return nil }
+ let r = CGFloat((val >> 16) & 0xFF) / 255
+ let g = CGFloat((val >> 8) & 0xFF) / 255
+ let b = CGFloat( val & 0xFF) / 255
+ return CGColor(red: r, green: g, blue: b, alpha: 1)
+}
+
+extension CGColor {
+ static func from(_ hex: String) -> CGColor {
+ cgColorFromHex(hex) ?? CGColor(gray: 0.5, alpha: 1)
+ }
+}
diff --git a/NotchBuddy/Sources/App/BotEngine.swift b/NotchBuddy/Sources/App/BotEngine.swift
new file mode 100644
index 00000000..3ff297fc
--- /dev/null
+++ b/NotchBuddy/Sources/App/BotEngine.swift
@@ -0,0 +1,1503 @@
+import Foundation
+import CoreGraphics
+import SwiftUI
+
+// MARK: - Easing functions (same as prototype: E.out, E.inOut, E.back, E.lin)
+
+enum Ease {
+ static func out(_ t: CGFloat) -> CGFloat { 1 - pow(1 - t, 3) }
+ static func inOut(_ t: CGFloat) -> CGFloat { t < 0.5 ? 4*t*t*t : 1 - pow(-2*t+2, 3)/2 }
+ static func back(_ t: CGFloat) -> CGFloat { let c1: CGFloat = 1.7; let c3 = c1+1; return 1+c3*pow(t-1,3)+c1*pow(t-1,2) }
+ static func lin(_ t: CGFloat) -> CGFloat { t }
+}
+
+// MARK: - Tween key: [target, duration_ms, easing]
+
+struct TweenKey {
+ let target: CGFloat
+ let duration: CGFloat // milliseconds
+ let ease: (CGFloat) -> CGFloat
+}
+
+struct Tween {
+ let property: String
+ var keys: [TweenKey]
+ var keyIndex: Int = 0
+ var from: CGFloat
+ var startTime: Double // CACurrentMediaTime() * 1000
+ var onComplete: (() -> Void)? = nil
+}
+
+// MARK: - Particle
+
+struct Particle {
+ enum ParticleType { case heart, star, spark, sweat, z }
+ var type: ParticleType
+ var x, y, vx, vy: CGFloat
+ var age: Double // seconds
+ var life: Double
+ var rot: CGFloat
+ var size: CGFloat
+}
+
+// MARK: - Bot state config (mirrors STATES in prototype)
+
+struct BotStateCfg {
+ let color: CGColor
+ let tint: CGFloat
+ let eye: EyeShape
+ let badge: BadgeType?
+ let badgeColor: CGColor
+ let glow: CGColor
+ let glowOpacity: CGFloat
+ let bounces: Bool
+ let scans: Bool
+ let breathes: Bool
+ let zz: Bool
+ let sweat: Bool
+ let look: CGPoint? // fixed look direction
+ let tilt: CGFloat
+ let sound: String?
+}
+
+enum EyeShape: String {
+ case pill, wide, dot, line, flat, happy, closed, spiral, heart, star, tired, wink, cup
+}
+
+enum BadgeType {
+ case dots(CGColor)
+ case bang(CGColor)
+ case question(CGColor)
+ case dot(CGColor)
+}
+
+// MARK: - Mochi track constants (from PISTES.mochi)
+
+enum MochiConst {
+ static let eyeW: CGFloat = 0.25
+ static let eyeH: CGFloat = 0.27
+ static let eyeSp: CGFloat = 0.37
+ static let eyeP: CGFloat = -0.12
+ static let baseTop = CGColor(red: 0.929, green: 0.929, blue: 0.937, alpha: 1) // #EDEDEF
+ static let baseBottom = CGColor(red: 0.769, green: 0.773, blue: 0.792, alpha: 1) // #C4C5CA
+ static let ink = CGColor(red: 0.102, green: 0.082, blue: 0.071, alpha: 1) // #1A1412
+ static let miniInk = CGColor(red: 0.063, green: 0.075, blue: 0.102, alpha: 1) // #10131A
+}
+
+// MARK: - Bot state configs
+
+let BotStates: [BotState: BotStateCfg] = [
+ .idle: BotStateCfg(
+ color: CGColor(red:0.902,green:0.914,blue:0.933,alpha:1), tint:0,
+ eye:.pill, badge:nil,
+ badgeColor: .white, glow: CGColor(red:1,green:1,blue:1,alpha:0.35), glowOpacity:0.25,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:nil),
+ .working: BotStateCfg(
+ color: CGColor(red:0.231,green:0.620,blue:1,alpha:1), tint:0.72,
+ eye:.pill, badge:.dots(CGColor(red:0.231,green:0.620,blue:1,alpha:1)),
+ badgeColor: CGColor(red:0.231,green:0.620,blue:1,alpha:1),
+ glow: CGColor(red:0.231,green:0.620,blue:1,alpha:1), glowOpacity:0.55,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"work"),
+ .thinking: BotStateCfg(
+ color: CGColor(red:0.545,green:0.361,blue:0.965,alpha:1), tint:0.72,
+ eye:.pill, badge:.dots(CGColor(red:0.545,green:0.361,blue:0.965,alpha:1)),
+ badgeColor: CGColor(red:0.545,green:0.361,blue:0.965,alpha:1),
+ glow: CGColor(red:0.545,green:0.361,blue:0.965,alpha:1), glowOpacity:0.5,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look: CGPoint(x:0.55, y:0.55), tilt:0, sound:"think"),
+ .searching: BotStateCfg(
+ color: CGColor(red:0.388,green:0.396,blue:0.949,alpha:1), tint:0.72,
+ eye:.pill, badge:.dots(CGColor(red:0.388,green:0.396,blue:0.949,alpha:1)),
+ badgeColor: CGColor(red:0.388,green:0.396,blue:0.949,alpha:1),
+ glow: CGColor(red:0.388,green:0.396,blue:0.949,alpha:1), glowOpacity:0.55,
+ bounces:false, scans:true, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"search"),
+ .approval: BotStateCfg(
+ color: CGColor(red:0.961,green:0.647,blue:0.141,alpha:1), tint:0.78,
+ eye:.wide, badge:.bang(CGColor(red:0.961,green:0.647,blue:0.141,alpha:1)),
+ badgeColor: CGColor(red:0.961,green:0.647,blue:0.141,alpha:1),
+ glow: CGColor(red:0.961,green:0.647,blue:0.141,alpha:1), glowOpacity:0.6,
+ bounces:true, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"approval"),
+ .question: BotStateCfg(
+ color: CGColor(red:0.133,green:0.827,blue:0.933,alpha:1), tint:0.75,
+ eye:.pill, badge:.question(CGColor(red:0.133,green:0.827,blue:0.933,alpha:1)),
+ badgeColor: CGColor(red:0.133,green:0.827,blue:0.933,alpha:1),
+ glow: CGColor(red:0.133,green:0.827,blue:0.933,alpha:1), glowOpacity:0.55,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0.17, sound:"question"),
+ .error: BotStateCfg(
+ color: CGColor(red:0.957,green:0.314,blue:0.369,alpha:1), tint:0.78,
+ eye:.flat, badge:.dot(CGColor(red:0.957,green:0.314,blue:0.369,alpha:1)),
+ badgeColor: CGColor(red:0.957,green:0.314,blue:0.369,alpha:1),
+ glow: CGColor(red:0.957,green:0.314,blue:0.369,alpha:1), glowOpacity:0.55,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"error"),
+ .finished: BotStateCfg(
+ color: CGColor(red:0.204,green:0.831,blue:0.600,alpha:1), tint:0.35,
+ eye:.happy, badge:.dot(CGColor(red:0.204,green:0.831,blue:0.600,alpha:1)),
+ badgeColor: CGColor(red:0.204,green:0.831,blue:0.600,alpha:1),
+ glow: CGColor(red:0.204,green:0.831,blue:0.600,alpha:1), glowOpacity:0.5,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"finish"),
+ .ratelimit: BotStateCfg(
+ color: CGColor(red:0.984,green:0.573,blue:0.235,alpha:1), tint:0.72,
+ eye:.tired, badge:.dot(CGColor(red:0.984,green:0.573,blue:0.235,alpha:1)),
+ badgeColor: CGColor(red:0.984,green:0.573,blue:0.235,alpha:1),
+ glow: CGColor(red:0.984,green:0.573,blue:0.235,alpha:1), glowOpacity:0.45,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:true,
+ look:nil, tilt:0, sound:"rate"),
+ .sleeping: BotStateCfg(
+ color: CGColor(red:0.580,green:0.635,blue:0.722,alpha:1), tint:0.32,
+ eye:.closed, badge:nil,
+ badgeColor: .white,
+ glow: CGColor(red:0.580,green:0.635,blue:0.722,alpha:1), glowOpacity:0.2,
+ bounces:false, scans:false, breathes:true, zz:true, sweat:false,
+ look:nil, tilt:0, sound:"sleep"),
+ .dizzy: BotStateCfg(
+ color: CGColor(red:0.957,green:0.447,blue:0.714,alpha:1), tint:0.7,
+ eye:.spiral, badge:nil,
+ badgeColor: .white,
+ glow: CGColor(red:0.957,green:0.447,blue:0.714,alpha:1), glowOpacity:0.55,
+ bounces:false, scans:false, breathes:false, zz:false, sweat:false,
+ look:nil, tilt:0, sound:"dizzy"),
+]
+
+// MARK: - Bot engine
+
+@MainActor
+final class BotEngine: ObservableObject {
+ var isMini: Bool = false
+ var bodyColor: CGColor? = nil // override for mini bots
+
+ // Animation state (mirrors prototype 's' object)
+ var yaw: CGFloat = 0
+ var pitch: CGFloat = 0
+ var roll: CGFloat = 0
+ var tilt: CGFloat = 0
+ var open: CGFloat = 1 // eye open amount
+ var sx: CGFloat = 1 // scale X
+ var sy: CGFloat = 1 // scale Y
+ var oy: CGFloat = 0 // offset Y (bounce)
+ var ox: CGFloat = 0 // offset X (shake)
+ var tint: CGFloat = 0
+ var morph: CGFloat = 0 // morph to rect (for upload bucket)
+ var hands: CGFloat = 0
+ var blush: CGFloat = 0
+ var es: CGFloat = 1 // eye scale
+ var badgeS: CGFloat = 0 // badge scale
+
+ // Targets
+ var tgYaw: CGFloat = 0
+ var tgPitch: CGFloat = 0
+ var tgTilt: CGFloat = 0
+ var tgSy: CGFloat = 1
+ var tgSx: CGFloat = 1
+ var tgEs: CGFloat = 1 // eye-scale target (hover love: 1.08, normal: 1)
+
+ // Particle canvas overhang (extra canvas height at top for hearts to fly into)
+ var particleOverhang: CGFloat = 0
+
+ // Mouth spring (fraction of R: 0=closed, 0.20=hover, 0.42=open, 0.50=overopen)
+ var slotH: CGFloat = 0 // current height (fraction of R)
+ var slotHTarget: CGFloat = 0 // spring target
+ var slotHVel: CGFloat = 0 // spring velocity (fraction of R / s)
+ var isChewing: Bool = false // true for ~800ms after gulp swallow
+
+ // Color (animated)
+ var col: (CGFloat, CGFloat, CGFloat) = (0.902, 0.914, 0.933) // idle
+ var colT: (CGFloat, CGFloat, CGFloat) = (0.902, 0.914, 0.933)
+
+ // State
+ var state: BotState = .idle
+ var cfg: BotStateCfg = BotStates[.idle]!
+
+ // Eye override (emote)
+ var eyeOverride: EyeShape? = nil
+ var eyeOverrideUntil: Double = 0 // CACurrentMediaTime()
+ var permanentEye: EyeShape? = nil // restored after temporary emote/blink expires
+ var permanentEmote: BotEmote? = nil // stored so doMiniBehaviorLoop can switch on it
+ var miniNextBehavior: Double = 0 // CACurrentMediaTime() of next periodic mini action
+
+ // Badge animation
+ var badge: BadgeType? = nil
+ var badgeKey: String = "none"
+ var badgeToken: Int = 0
+
+ // Tweens (keyed by property name)
+ var tweens: [String: Tween] = [:]
+ var locks: Set<String> = []
+
+ // Particles
+ var particles: [Particle] = []
+
+ // Look target
+ var lookX: CGFloat = 0
+ var lookY: CGFloat = 0
+
+ // Timing
+ var lastTime: Double = CACurrentMediaTime()
+ var t0: Double = CACurrentMediaTime() - Double.random(in: 0...5)
+ var nextBlink: Double = CACurrentMediaTime() + 1.5 + Double.random(in: 0...2)
+ var waveUntil: Double = 0
+ var waveStart: Double = 0 // CACurrentMediaTime() when wave animation began
+ var greetToken: Int = 0 // incremented to invalidate stale greet closures
+ var lastAmbient: Double = 0
+
+ // Slap tracking (for dizzy on 3 slaps)
+ var slapTimes: [Double] = []
+
+ // Mini wandering look (random, ignores mouse)
+ var miniLookTarget: CGPoint = .zero
+ var miniLookNextTime: Double = 0
+
+ // MARK: - Public API
+
+ func setState(_ newState: BotState, force: Bool = false) {
+ guard state != newState || force else { return }
+ let prev = state
+ state = newState
+ cfg = BotStates[newState]!
+ colT = cgColorToTuple(cfg.color)
+ setTarget(key: "tint", value: cfg.tint)
+ setTarget(key: "tilt", value: cfg.tilt)
+ setBadge(cfg.badge)
+
+ switch newState {
+ case .finished:
+ doRoll(duration: 950, turns: 1)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
+ self?.emit(.spark, count: 5)
+ }
+ case .error:
+ anim("ox", keys: [
+ TweenKey(target: 0.08, duration: 50, ease: Ease.out),
+ TweenKey(target: -0.08, duration: 70, ease: Ease.inOut),
+ TweenKey(target: 0.05, duration: 70, ease: Ease.inOut),
+ TweenKey(target: 0, duration: 90, ease: Ease.out),
+ ])
+ case .approval:
+ anim("oy", keys: [
+ TweenKey(target: -0.2, duration: 150, ease: Ease.out),
+ TweenKey(target: 0, duration: 300, ease: Ease.back),
+ ])
+ case .dizzy:
+ doRoll(duration: 1300, turns: 2)
+ case .question:
+ blink()
+ case .ratelimit:
+ emit(.sweat, count: 1)
+ default:
+ if prev != .idle || newState != .idle { blink() }
+ }
+ }
+
+ func setBadge(_ b: BadgeType?) {
+ let key = badgeString(b)
+ guard key != badgeKey else { return }
+ badgeKey = key
+ let tok = badgeToken + 1
+ badgeToken = tok
+ anim("badgeS", keys: [TweenKey(target: 0, duration: 90, ease: Ease.inOut)])
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
+ guard let self, tok == self.badgeToken else { return }
+ self.badge = b
+ if b != nil {
+ self.anim("badgeS", keys: [TweenKey(target: 1, duration: 280, ease: Ease.back)])
+ }
+ }
+ }
+
+ func blink() {
+ guard !locks.contains("open") else { return }
+ anim("open", keys: [
+ TweenKey(target: 0.06, duration: 70, ease: Ease.inOut),
+ TweenKey(target: 1, duration: 130, ease: Ease.out),
+ ])
+ }
+
+ func squash() {
+ anim("sy", keys: [
+ TweenKey(target: 0.78, duration: 70, ease: Ease.out),
+ TweenKey(target: 1.1, duration: 130, ease: Ease.out),
+ TweenKey(target: 1, duration: 170, ease: Ease.inOut),
+ ])
+ anim("sx", keys: [
+ TweenKey(target: 1.16, duration: 70, ease: Ease.out),
+ TweenKey(target: 0.95, duration: 130, ease: Ease.out),
+ TweenKey(target: 1, duration: 170, ease: Ease.inOut),
+ ])
+ }
+
+ // MARK: - Gulp (mailbox swallow)
+
+ func gulp() {
+ // Open mouth wide for the swallow, then close during chewing
+ slotHTarget = 0.42
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.46) { [weak self] in
+ self?.slotHTarget = 0
+ self?.isChewing = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.80) { [weak self] in
+ self?.isChewing = false
+ }
+ }
+ anim("sy", keys: [
+ TweenKey(target: 0.78, duration: 80, ease: Ease.out),
+ TweenKey(target: 1.18, duration: 130, ease: Ease.out),
+ TweenKey(target: 1, duration: 220, ease: Ease.back),
+ ])
+ anim("sx", keys: [
+ TweenKey(target: 1.28, duration: 80, ease: Ease.out),
+ TweenKey(target: 0.92, duration: 130, ease: Ease.out),
+ TweenKey(target: 1, duration: 220, ease: Ease.back),
+ ])
+ blink()
+ }
+
+ // MARK: - Slap (dizzy mechanic)
+
+ func slap() {
+ interruptGreet()
+ guard state != .dizzy else { return }
+ let now = CACurrentMediaTime()
+ slapTimes = slapTimes.filter { now - $0 < 1.7 }
+ slapTimes.append(now)
+ SoundEngine.shared.play("slap")
+ squash()
+ if slapTimes.count >= 3 {
+ slapTimes = []
+ NotificationCenter.default.post(name: .botDizzy, object: nil)
+ } else {
+ // Annoyed: line eyes for 800ms, annoyed sound after 60ms delay
+ eyeOverride = .line
+ eyeOverrideUntil = now + 0.8
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) {
+ SoundEngine.shared.play("annoyed")
+ }
+ }
+ }
+
+ // MARK: - Mini periodic behavior loop
+
+ func doMiniBehaviorLoop() {
+ switch permanentEmote {
+
+ case .happy:
+ // Little jump + squash
+ guard !locks.contains("oy") else {
+ miniNextBehavior = CACurrentMediaTime() + 0.4
+ return
+ }
+ anim("oy", keys: [
+ TweenKey(target: -0.30, duration: 120, ease: Ease.out),
+ TweenKey(target: 0.03, duration: 200, ease: Ease.inOut),
+ TweenKey(target: 0, duration: 160, ease: Ease.back),
+ ])
+ anim("sy", keys: [
+ TweenKey(target: 0.82, duration: 80, ease: Ease.out),
+ TweenKey(target: 1.18, duration: 130, ease: Ease.out),
+ TweenKey(target: 0.88, duration: 160, ease: Ease.inOut),
+ TweenKey(target: 1, duration: 200, ease: Ease.back),
+ ])
+ anim("sx", keys: [
+ TweenKey(target: 1.15, duration: 80, ease: Ease.out),
+ TweenKey(target: 0.88, duration: 130, ease: Ease.out),
+ TweenKey(target: 1.06, duration: 160, ease: Ease.inOut),
+ TweenKey(target: 1, duration: 200, ease: Ease.back),
+ ])
+ miniNextBehavior = CACurrentMediaTime() + 2.2 + Double.random(in: 0...1.2)
+
+ case .annoyed:
+ // Rapid head shake
+ guard !locks.contains("yaw") else {
+ miniNextBehavior = CACurrentMediaTime() + 0.5
+ return
+ }
+ anim("yaw", keys: [
+ TweenKey(target: -0.65, duration: 50, ease: Ease.out),
+ TweenKey(target: 0.65, duration: 90, ease: Ease.inOut),
+ TweenKey(target: -0.5, duration: 80, ease: Ease.inOut),
+ TweenKey(target: 0.4, duration: 75, ease: Ease.inOut),
+ TweenKey(target: -0.2, duration: 70, ease: Ease.inOut),
+ TweenKey(target: 0, duration: 140, ease: Ease.out),
+ ])
+ miniNextBehavior = CACurrentMediaTime() + 3.0 + Double.random(in: 0...2.5)
+
+ case .wink:
+ // Brief wink: eye closes, head tilts slightly
+ let now2 = CACurrentMediaTime()
+ eyeOverride = .wink
+ eyeOverrideUntil = now2 + 0.55
+ anim("tilt", keys: [
+ TweenKey(target: 0.13, duration: 100, ease: Ease.out),
+ TweenKey(target: 0.13, duration: 320, ease: Ease.lin),
+ TweenKey(target: 0, duration: 200, ease: Ease.inOut),
+ ])
+ miniNextBehavior = CACurrentMediaTime() + 2.2 + Double.random(in: 0...2.0)
+
+ case .love:
+ // Emit hearts + gentle sway
+ emit(.heart, count: 2)
+ anim("tilt", keys: [
+ TweenKey(target: -0.1, duration: 180, ease: Ease.out),
+ TweenKey(target: 0.1, duration: 340, ease: Ease.inOut),
+ TweenKey(target: 0, duration: 220, ease: Ease.inOut),
+ ])
+ miniNextBehavior = CACurrentMediaTime() + 2.6 + Double.random(in: 0...1.5)
+
+ default:
+ miniNextBehavior = CACurrentMediaTime() + 3.0 + Double.random(in: 0...2.0)
+ }
+ }
+
+ func doRoll(duration: CGFloat, turns: CGFloat) {
+ roll = 0
+ anim("roll", keys: [TweenKey(target: .pi * 2 * turns, duration: duration, ease: Ease.inOut)]) { [weak self] in
+ self?.roll = 0
+ }
+ }
+
+ func greet() {
+ let now = CACurrentMediaTime()
+ greetToken += 1
+ let tok = greetToken
+ waveStart = now + 0.45 // wave begins at 0.45s
+ waveUntil = now + 1.55 // wave ends at 1.55s
+
+ // 0s: happy eyes for full greeting (2s — no gap, no flicker)
+ eyeOverride = .happy
+ eyeOverrideUntil = now + 2.0
+ anim("oy", keys: [
+ TweenKey(target: -0.06, duration: 220, ease: Ease.out),
+ TweenKey(target: 0.0, duration: 220, ease: Ease.back),
+ ])
+
+ // 0.25s: hands out + body squash + sound
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
+ guard let self, self.greetToken == tok else { return }
+ self.anim("hands", keys: [TweenKey(target: 1, duration: 280, ease: Ease.out)])
+ self.anim("sy", keys: [
+ TweenKey(target: 0.95, duration: 100, ease: Ease.out),
+ TweenKey(target: 1.0, duration: 260, ease: Ease.back),
+ ])
+ self.anim("sx", keys: [
+ TweenKey(target: 1.04, duration: 100, ease: Ease.out),
+ TweenKey(target: 1.0, duration: 260, ease: Ease.back),
+ ])
+ SoundEngine.shared.play("greet")
+ }
+
+ // 0.55s: first blink
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.55) { [weak self] in
+ guard let self, self.greetToken == tok else { return }
+ self.blink()
+ }
+
+ // 1.50s: second blink
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.50) { [weak self] in
+ guard let self, self.greetToken == tok else { return }
+ self.blink()
+ }
+
+ // 1.55s: retract hands
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.55) { [weak self] in
+ guard let self, self.greetToken == tok else { return }
+ self.waveUntil = 0
+ self.anim("hands", keys: [TweenKey(target: 0, duration: 200, ease: Ease.inOut)])
+ }
+
+ // 1.75s: brief happy eyes then back to normal
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.75) { [weak self] in
+ guard let self, self.greetToken == tok else { return }
+ self.eyeOverride = .happy
+ self.eyeOverrideUntil = CACurrentMediaTime() + 0.30
+ }
+ }
+
+ /// Immediately interrupts an in-progress greeting (hands retract in 150 ms).
+ func interruptGreet() {
+ guard hands > 0.01 || CACurrentMediaTime() < waveUntil else { return }
+ greetToken += 1 // invalidate any pending closures
+ waveUntil = 0
+ waveStart = 0
+ anim("hands", keys: [TweenKey(target: 0, duration: 150, ease: Ease.inOut)])
+ }
+
+ /// Sets a permanent eye expression that survives blinks and transient emotes.
+ func setPermanentEmote(_ emote: BotEmote?) {
+ permanentEmote = emote
+ // .wink fires periodically — don't freeze the eye (normal between winks)
+ if emote == .wink {
+ miniNextBehavior = CACurrentMediaTime() + Double.random(in: 0.8...2.5)
+ return
+ }
+ permanentEye = emote.map { emoteEyeShape($0) }
+ if let eye = permanentEye {
+ eyeOverride = eye
+ eyeOverrideUntil = .greatestFiniteMagnitude
+ } else {
+ if eyeOverrideUntil == .greatestFiniteMagnitude {
+ eyeOverride = nil
+ eyeOverrideUntil = 0
+ }
+ }
+ // Stagger first periodic behavior so bots don't all fire at once
+ miniNextBehavior = CACurrentMediaTime() + Double.random(in: 0.8...2.5)
+ }
+
+ func triggerEmote(_ emote: BotEmote, duration: Double = 1.8, silent: Bool = false) {
+ let now = CACurrentMediaTime()
+ eyeOverride = emoteEyeShape(emote)
+ eyeOverrideUntil = now + duration
+
+ switch emote {
+ case .love:
+ anim("blush", keys: [
+ TweenKey(target: 1, duration: 300, ease: Ease.out),
+ TweenKey(target: 1, duration: CGFloat((duration - 0.6) * 1000), ease: Ease.lin),
+ TweenKey(target: 0, duration: 300, ease: Ease.inOut),
+ ])
+ emit(.heart, count: 4)
+ anim("oy", keys: [
+ TweenKey(target: -0.1, duration: 160, ease: Ease.out),
+ TweenKey(target: 0, duration: 300, ease: Ease.back),
+ ])
+ case .surprised:
+ anim("oy", keys: [
+ TweenKey(target: -0.3, duration: 140, ease: Ease.out),
+ TweenKey(target: 0, duration: 380, ease: Ease.back),
+ ])
+ anim("es", keys: [
+ TweenKey(target: 1.25, duration: 120, ease: Ease.out),
+ TweenKey(target: 1, duration: 500, ease: Ease.inOut),
+ ])
+ case .proud:
+ emit(.star, count: 5)
+ anim("tilt", keys: [
+ TweenKey(target: -0.14, duration: 220, ease: Ease.out),
+ TweenKey(target: -0.14, duration: CGFloat((duration - 0.5) * 1000), ease: Ease.lin),
+ TweenKey(target: 0, duration: 280, ease: Ease.inOut),
+ ])
+ anim("blush", keys: [
+ TweenKey(target: 0.7, duration: 250, ease: Ease.out),
+ TweenKey(target: 0.7, duration: CGFloat((duration - 0.5) * 1000), ease: Ease.lin),
+ TweenKey(target: 0, duration: 300, ease: Ease.inOut),
+ ])
+ case .wink:
+ anim("tilt", keys: [
+ TweenKey(target: 0.12, duration: 160, ease: Ease.out),
+ TweenKey(target: 0.12, duration: CGFloat((duration - 0.4) * 1000), ease: Ease.lin),
+ TweenKey(target: 0, duration: 240, ease: Ease.inOut),
+ ])
+ case .yawn:
+ anim("sy", keys: [
+ TweenKey(target: 1.12, duration: 500, ease: Ease.inOut),
+ TweenKey(target: 1, duration: 500, ease: Ease.inOut),
+ ])
+ anim("sx", keys: [
+ TweenKey(target: 0.94, duration: 500, ease: Ease.inOut),
+ TweenKey(target: 1, duration: 500, ease: Ease.inOut),
+ ])
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { [weak self] in
+ self?.eyeOverride = .closed
+ self?.emit(.z, count: 2)
+ }
+ case .happy:
+ anim("blush", keys: [
+ TweenKey(target: 0.6, duration: 200, ease: Ease.out),
+ TweenKey(target: 0, duration: 600, ease: Ease.inOut),
+ ])
+ case .annoyed:
+ eyeOverride = .line
+ eyeOverrideUntil = now + 0.8
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) {
+ SoundEngine.shared.play("annoyed")
+ }
+ }
+ }
+
+ func emit(_ type: Particle.ParticleType, count: Int) {
+ for i in 0..<count {
+ let isZ = type == .z
+ let p = Particle(
+ type: type,
+ x: (CGFloat.random(in: -0.5...0.5)) * 0.9 + (isZ ? 0.55 : 0),
+ y: -0.7 - CGFloat.random(in: 0...0.2),
+ vx: CGFloat.random(in: -0.5...0.5) * 0.35 + (isZ ? 0.18 : 0),
+ vy: -(0.45 + CGFloat.random(in: 0...0.35)),
+ age: -Double(i) * 0.14,
+ life: 1.3 + Double.random(in: 0...0.5),
+ rot: CGFloat.random(in: 0...(.pi * 2)),
+ size: 0.15 + CGFloat.random(in: 0...0.08)
+ )
+ particles.append(p)
+ }
+ }
+
+ // MARK: - Update (called every frame from TimelineView)
+
+ func update(dt: Double) {
+ let now = CACurrentMediaTime()
+ let dtCG = CGFloat(dt)
+
+ // Process tweens
+ for key in tweens.keys {
+ guard var tw = tweens[key] else { continue }
+ let k = tw.keys[tw.keyIndex]
+ let elapsed = now * 1000 - tw.startTime
+ let p = min(1, max(0, CGFloat(elapsed) / k.duration))
+ let val = tw.from + (k.target - tw.from) * k.ease(p)
+ setProperty(key, value: val)
+
+ if p >= 1 {
+ tw.from = k.target
+ tw.keyIndex += 1
+ tw.startTime = now * 1000
+ if tw.keyIndex >= tw.keys.count {
+ tweens.removeValue(forKey: key)
+ locks.remove(key)
+ tw.onComplete?()
+ } else {
+ tweens[key] = tw
+ }
+ } else {
+ tweens[key] = tw
+ }
+ }
+
+ // Compute look targets
+ let t = CGFloat(now - t0)
+ var ty: CGFloat = lookX * 0.62
+ var tp: CGFloat = lookY * 0.5
+
+ if let fixedLook = cfg.look {
+ ty = ty * 0.35 + fixedLook.x * 0.55
+ tp = tp * 0.3 + fixedLook.y * 0.5
+ }
+ if cfg.scans {
+ ty = sin(t * 2.6) * 0.6
+ tp = -0.06
+ }
+ if state == .sleeping { ty = 0; tp = -0.14 }
+ if state == .dizzy { ty = sin(t * 9) * 0.25 }
+
+ // Mini bots: override look with random wandering (never follows mouse)
+ if isMini && cfg.look == nil && !cfg.scans && state != .sleeping && state != .dizzy {
+ if now > miniLookNextTime {
+ miniLookTarget = CGPoint(
+ x: CGFloat.random(in: -0.88...0.88),
+ y: CGFloat.random(in: -0.55...0.45)
+ )
+ miniLookNextTime = now + Double.random(in: 0.5...2.0)
+ }
+ ty = miniLookTarget.x * 0.62
+ tp = miniLookTarget.y * 0.5
+ }
+
+ tgYaw = ty
+ tgPitch = tp
+ tgTilt = cfg.tilt
+
+ // Body sway during greeting wave
+ if now > waveStart && now < waveUntil {
+ let wt = CGFloat(now - waveStart)
+ tgTilt = -0.06 + sin(2 * .pi * 1.2 * wt) * 0.07
+ }
+
+ let bounce = cfg.bounces ? -abs(sin(t * 5.2)) * 0.07 : CGFloat(0)
+ // oy tween can override if not locked
+ if !locks.contains("oy") { oy += (bounce - oy) * CGFloat(1 - pow(0.0008, dt)) }
+
+ if cfg.breathes {
+ let amp: CGFloat = isMini ? 0.07 : 0.035
+ tgSy = 1 + sin(t * 1.8) * amp
+ tgSx = 1 - sin(t * 1.8) * amp * 0.57
+ } else if isMini {
+ // Subtle idle pulse (unique phase per engine via t0)
+ tgSy = 1 + sin(t * 2.2) * 0.04
+ tgSx = 1 - sin(t * 2.2) * 0.02
+ } else {
+ tgSy = 1; tgSx = 1
+ }
+
+ // Mini bots: periodic dramatic behaviors
+ if isMini && now > miniNextBehavior {
+ doMiniBehaviorLoop()
+ }
+
+ // Smooth look
+ let kLook = CGFloat(1 - pow(0.0025, dt))
+ let kGen = CGFloat(1 - pow(0.0008, dt))
+
+ if !locks.contains("yaw") { yaw += (tgYaw - yaw) * kLook }
+ if !locks.contains("pitch") { pitch += (tgPitch - pitch) * kLook }
+ if !locks.contains("tilt") { tilt += (tgTilt - tilt) * kGen }
+ if !locks.contains("sy") { sy += (tgSy - sy) * kGen }
+ if !locks.contains("sx") { sx += (tgSx - sx) * kGen }
+ if !locks.contains("es") { es += (tgEs - es) * kGen }
+
+ // Animate color
+ col = mixColor(col, colT, 1 - pow(0.002, dt))
+
+ // Blink
+ if now > nextBlink {
+ if state != .sleeping && state != .dizzy {
+ blink()
+ if Double.random(in: 0...1) < 0.22 {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.23) { [weak self] in self?.blink() }
+ }
+ }
+ nextBlink = now + 2.2 + Double.random(in: 0...3.2)
+ }
+
+ // Clear expired eye override (restore permanent if set)
+ if eyeOverride != nil && now > eyeOverrideUntil {
+ eyeOverride = permanentEye
+ if permanentEye != nil { eyeOverrideUntil = .greatestFiniteMagnitude }
+ }
+
+ // Ambient particles
+ if now - lastAmbient > 1.3 {
+ lastAmbient = now
+ if cfg.zz { emit(.z, count: 1) } // ZZZ works for mini too
+ if !isMini && cfg.sweat && Double.random(in: 0...1) < 0.5 { emit(.sweat, count: 1) }
+ }
+
+ // Age particles
+ for i in particles.indices { particles[i].age += dt }
+ particles.removeAll { $0.age >= $0.life }
+
+ // Mouth slot spring — ω₀ ≈ 25 rad/s (T=0.25s), ζ=0.6 (underdamped, slight clack)
+ let slotOmega: CGFloat = 2 * .pi / 0.25
+ let slotZeta: CGFloat = 0.6
+ let slotAcc = slotOmega * slotOmega * (slotHTarget - slotH)
+ - 2 * slotZeta * slotOmega * slotHVel
+ slotHVel += slotAcc * dtCG
+ slotH = max(0, slotH + slotHVel * dtCG)
+
+ lastTime = now
+ }
+
+ // MARK: - Draw
+
+ func draw(context: GraphicsContext, size: CGSize) {
+ let W = size.width
+ let H = size.height
+ let R = W * 0.3
+ let rx = R * 1.14
+ let ry = R * 0.88
+
+ let cx = W / 2 + ox * R
+ // particleOverhang shifts the bot body down in canvas coords so hearts can fly into
+ // the extended canvas above without clipping (BotPlacement compensates with position offset)
+ let cy = H / 2 + particleOverhang / 2 + oy * R + R * 0.06
+
+ var ctx = context
+ ctx.translateBy(x: cx, y: cy)
+ if tilt != 0 { ctx.rotate(by: .radians(tilt)) }
+ ctx.scaleBy(x: sx, y: sy)
+
+ // Body path (superellipse for Mochi, morph to rect for upload)
+ let bodyPath = mochiPath(rx: rx, ry: ry, morph: morph, R: R)
+
+ // Body fill
+ drawBody(ctx: &ctx, path: bodyPath, R: R, rx: rx, ry: ry)
+
+ // Blush — always shows a floor proportional to tint (prototype behaviour)
+ let blushVal = max(blush, tint * 0.5) * (1 - morph)
+ if blushVal > 0.01 {
+ drawBlush(ctx: &ctx, path: bodyPath, rx: rx, ry: ry, R: R, blush: blushVal)
+ }
+
+ // Eyes
+ drawEyes(ctx: &ctx, path: bodyPath, R: R, rx: rx, ry: ry)
+
+ // Mouth hole — dark pill cutout inside the box face
+ // Spec: left/right margins 0.10R, top margin 0.08R from box top (-0.94R)
+ if morph > 0.05 {
+ let hW = R * 1.80 * morph // hole width = box width (2×1.0R) − 2×0.10R margin
+ let hH = slotH * R * morph // hole height (spring-animated, scaled by morph)
+ let hX = -hW / 2
+ // Hole Y: box top is -R*0.94 at morph=1, lerped from -R*0.88 at morph=0
+ let boxTop = -R * (0.88 + 0.06 * morph)
+ let hY = boxTop + R * 0.08 * morph // top margin scales with morph
+
+ var boxCtx = ctx
+ boxCtx.clip(to: bodyPath) // everything clipped inside body
+
+ // Top rim — 1pt white 55% line at box top edge
+ var rim = Path()
+ rim.move(to: CGPoint(x: -R * 0.90 * morph, y: boxTop + 1))
+ rim.addLine(to: CGPoint(x: R * 0.90 * morph, y: boxTop + 1))
+ boxCtx.stroke(rim, with: .color(Color.white.opacity(0.55 * Double(morph))),
+ style: StrokeStyle(lineWidth: 1, lineCap: .round))
+
+ // Hole interior — only draw if visibly open
+ if hH > 0.8 {
+ let hR = min(hW / 2, hH / 2) // fully rounded when hH < hW (pill shape)
+ var hole = Path()
+ hole.addRoundedRect(in: CGRect(x: hX, y: hY, width: hW, height: hH),
+ cornerSize: CGSize(width: hR, height: hR))
+ boxCtx.fill(hole, with: .linearGradient(
+ Gradient(colors: [Color(red: 0.027, green: 0.031, blue: 0.039),
+ Color(red: 0.063, green: 0.075, blue: 0.102)]),
+ startPoint: CGPoint(x: 0, y: hY),
+ endPoint: CGPoint(x: 0, y: hY + hH)
+ ))
+ // Bottom lip — 1pt white 28% highlight
+ if hH > 4 {
+ let lipR = min(hR, (hW - 2) / 2)
+ var lip = Path()
+ lip.move(to: CGPoint(x: hX + lipR, y: hY + hH - 0.5))
+ lip.addLine(to: CGPoint(x: hX + hW - lipR, y: hY + hH - 0.5))
+ boxCtx.stroke(lip, with: .color(Color.white.opacity(0.28 * Double(morph))),
+ style: StrokeStyle(lineWidth: 1, lineCap: .round))
+ }
+ }
+ }
+
+ // Reset transform for hands, badge, particles which need world coords
+ // (We'll pass world-space cx/cy to these helpers)
+ }
+
+ // MARK: - Draw hands behind body (called before draw() so hands appear under Mochi)
+
+ func drawHandsBehind(context: GraphicsContext, size: CGSize) {
+ guard hands > 0.01, !isMini else { return }
+ let W = size.width, H = size.height
+ let R = W * 0.3
+ // Only draw hands when Mochi is large enough to be meaningful (not compact/peek)
+ guard R > 14 else { return }
+ let rx = R * 1.14
+ let ry = R * 0.88
+ let cx = W / 2 + ox * R
+ let cy = H / 2 + particleOverhang / 2 + oy * R + R * 0.06
+
+ let now = CACurrentMediaTime()
+ let bodyH = 2 * ry // full body height
+
+ // Hand ellipse half-dims: 0.30×bodyH wide, 0.26×bodyH tall (scaled by hands 0→1)
+ let hew = 0.30 * ry * hands // half-width
+ let heh = 0.26 * ry * hands // half-height
+
+ // Body half-dims with current squash scale
+ let hwB = rx * sx
+ let hhB = ry * sy
+
+ let isWaving = now >= waveStart && waveStart > 0 && now < waveUntil
+
+ for sd in [-1.0, 1.0] {
+ var localX: CGFloat
+ var localY: CGFloat
+ var handRot: CGFloat = 0
+
+ if sd > 0 && isWaving {
+ // Right hand: rise to wave position over first 180ms, then oscillate
+ let wt = CGFloat(now - waveStart)
+ let rise = min(1.0, wt / 0.18)
+ let riseEased: CGFloat = 1 - pow(1 - rise, 3) // easeOut cubic
+
+ // Rest position is lower-side; wave position is upper-side (at eye height)
+ let restX: CGFloat = hwB * 1.08
+ let restY: CGFloat = hhB * 0.70
+ let oscX = cos(13 * wt) * 0.06 * bodyH
+ let oscY = -sin(13 * wt) * 0.14 * bodyH
+ let waveX: CGFloat = hwB * 1.10 + oscX
+ let waveY: CGFloat = -hhB * 0.15 + oscY
+ localX = restX + (waveX - restX) * riseEased
+ localY = restY + (waveY - restY) * riseEased
+ handRot = (-0.5 + sin(13 * wt) * 0.35) * riseEased
+
+ } else if sd < 0 && isWaving {
+ // Left hand: gentle sway at rest position
+ let wt = CGFloat(now - waveStart)
+ localX = -hwB * 1.08
+ localY = hhB * 0.70 + sin(6 * wt) * 0.04 * bodyH
+
+ } else {
+ // Rest: lower-side, clearly peeking behind body bottom
+ localX = CGFloat(sd) * hwB * 1.08
+ localY = hhB * 0.70
+ }
+
+ // Apply body tilt to get world position
+ let cosT = cos(tilt), sinT = sin(tilt)
+ let worldX = cx + cosT * localX - sinT * localY
+ let worldY = cy + sinT * localX + cosT * localY
+
+ // Draw
+ var handCtx = context
+ handCtx.translateBy(x: worldX, y: worldY)
+ if handRot != 0 { handCtx.rotate(by: .radians(handRot)) }
+
+ let handRect = CGRect(x: -hew, y: -heh, width: hew * 2, height: heh * 2)
+ var handPath = Path()
+ handPath.addEllipse(in: handRect)
+
+ // Fill with body material (same gradient as body)
+ if let bc = bodyColor {
+ let c0 = mix3(cgColorToTuple(bc), (1, 1, 1), 0.35)
+ let c1 = cgColorToTuple(bc)
+ handCtx.fill(handPath, with: .linearGradient(
+ Gradient(colors: [colorFromTuple(c0), colorFromTuple(c1)]),
+ startPoint: CGPoint(x: hew * 0.7, y: -heh * 0.85),
+ endPoint: CGPoint(x: -hew * 0.8, y: heh * 0.9)
+ ))
+ } else {
+ let c0 = cgColorToTuple(MochiConst.baseTop)
+ let c1 = cgColorToTuple(MochiConst.baseBottom)
+ handCtx.fill(handPath, with: .linearGradient(
+ Gradient(colors: [colorFromTuple(c0), colorFromTuple(c1)]),
+ startPoint: CGPoint(x: hew * 0.7, y: -heh * 0.85),
+ endPoint: CGPoint(x: -hew * 0.8, y: heh * 0.9)
+ ))
+ }
+
+ // Subtle separation border — rgba(0,0,0,0.08) 1pt
+ handCtx.stroke(handPath, with: .color(Color.black.opacity(0.08)), lineWidth: 1)
+ }
+ }
+
+ func drawHandsAndExtras(context: GraphicsContext, size: CGSize) {
+ let W = size.width
+ let H = size.height
+ let R = W * 0.3
+ let rx = R * 1.14
+ let ry = R * 0.88
+ let cx = W / 2 + ox * R
+ let cy = H / 2 + particleOverhang / 2 + oy * R + R * 0.06
+
+ // Badge — hidden while morphing to mailbox
+ if let badge = badge, badgeS > 0.01, morph < 0.25 {
+ drawBadge(context: context, size: size, badge: badge, R: R, rx: rx, ry: ry, cx: cx, cy: cy)
+ }
+
+ // Particles
+ drawParticles(context: context, size: size, R: R, cx: cx, cy: cy)
+ }
+
+ // MARK: - Private draw helpers
+
+ private func mochiPath(rx: CGFloat, ry: CGFloat, morph: CGFloat, R: CGFloat) -> Path {
+ let n = 72
+ let expN: CGFloat = 2.0 / 2.7
+ // Target mailbox dims (spec: 1.0R wide, 0.94R tall, 0.42R corner radius)
+ let tw = R * 1.0
+ let th = R * 0.94
+ let tr = R * 0.42
+ var path = Path()
+ for i in 0...n {
+ let a = CGFloat(i) / CGFloat(n) * .pi * 2
+ let ca = cos(a), sa = sin(a)
+ let px0 = rx * (ca >= 0 ? pow(ca, expN) : -pow(-ca, expN))
+ let py0 = ry * (sa >= 0 ? pow(sa, expN) : -pow(-sa, expN))
+ let px: CGFloat
+ let py: CGFloat
+ if morph < 0.005 {
+ px = px0; py = py0
+ } else {
+ let rr = rrPoint(ca: ca, sa: sa, W: tw, H: th, cr: tr)
+ px = lerp(px0, rr.x, morph)
+ py = lerp(py0, rr.y, morph)
+ }
+ if i == 0 { path.move(to: CGPoint(x: px, y: py)) }
+ else { path.addLine(to: CGPoint(x: px, y: py)) }
+ }
+ path.closeSubpath()
+ return path
+ }
+
+ /// Ray-rounded-rect intersection: find the point on the rounded rect boundary in direction (ca, sa).
+ private func rrPoint(ca: CGFloat, sa: CGFloat, W: CGFloat, H: CGFloat, cr: CGFloat) -> CGPoint {
+ let eps: CGFloat = 1e-6
+ let kx: CGFloat = ca >= 0 ? 1 : -1
+ let ky: CGFloat = sa >= 0 ? 1 : -1
+ let cx = kx * (W - cr)
+ let cy = ky * (H - cr)
+
+ // Try corner arc
+ let dot = ca * cx + sa * cy
+ let disc = dot * dot - (cx*cx + cy*cy - cr*cr)
+ if disc >= 0 {
+ let t = dot + sqrt(disc)
+ if t > eps {
+ let px = ca * t, py = sa * t
+ if abs(px) >= W - cr - eps && abs(py) >= H - cr - eps {
+ return CGPoint(x: px, y: py)
+ }
+ }
+ }
+
+ // Horizontal edge |y| = H
+ if abs(sa) > eps {
+ let t = (ky * H) / sa
+ if t > eps {
+ let x = ca * t
+ if abs(x) <= W - cr + eps { return CGPoint(x: x, y: ky * H) }
+ }
+ }
+ // Vertical edge |x| = W
+ if abs(ca) > eps {
+ let t = (kx * W) / ca
+ if t > eps {
+ let y = sa * t
+ if abs(y) <= H - cr + eps { return CGPoint(x: kx * W, y: y) }
+ }
+ }
+
+ return CGPoint(x: kx * W, y: ky * H)
+ }
+
+ private func drawBody(ctx: inout GraphicsContext, path: Path, R: CGFloat, rx: CGFloat, ry: CGFloat) {
+ if let bc = bodyColor {
+ // Mini bots: flat solid fill — no gradient, no reflection, no highlight
+ ctx.fill(path, with: .color(Color(cgColor: bc)))
+ } else {
+ // Main bot: linear gradient body
+ let c0 = cgColorToTuple(MochiConst.baseTop)
+ let c1 = cgColorToTuple(MochiConst.baseBottom)
+ ctx.fill(path, with: .linearGradient(
+ Gradient(colors: [colorFromTuple(c0), colorFromTuple(c1)]),
+ startPoint: CGPoint(x: rx*0.7, y: -ry*0.85),
+ endPoint: CGPoint(x: -rx*0.8, y: ry*0.9)
+ ))
+ // State tint — fades out as morph increases (mailbox has no tint)
+ let effectiveTint = tint * (1 - morph)
+ if effectiveTint > 0.01 {
+ let tc = colorFromTuple(col)
+ ctx.fill(path, with: .linearGradient(
+ Gradient(stops: [
+ .init(color: tc.opacity(Double(0.72 * effectiveTint)), location: 0),
+ .init(color: tc.opacity(0), location: 1)
+ ]),
+ startPoint: CGPoint(x: 0, y: ry),
+ endPoint: CGPoint(x: 0, y: -ry)
+ ))
+ }
+ // Shadow rim
+ ctx.fill(path, with: .radialGradient(
+ Gradient(stops: [
+ .init(color: .clear, location: 0),
+ .init(color: .clear, location: 0.6),
+ .init(color: Color.black.opacity(0.2), location: 1)
+ ]),
+ center: .zero, startRadius: R*0.15, endRadius: R*1.25
+ ))
+ // Highlight
+ ctx.fill(path, with: .radialGradient(
+ Gradient(stops: [
+ .init(color: Color.white.opacity(0.55), location: 0),
+ .init(color: .clear, location: 1)
+ ]),
+ center: CGPoint(x: rx*0.34, y: -ry*0.46),
+ startRadius: 0,
+ endRadius: R*0.42
+ ))
+ }
+ }
+
+ private func drawBlush(ctx: inout GraphicsContext, path: Path, rx: CGFloat, ry: CGFloat, R: CGFloat, blush: CGFloat) {
+ ctx.clip(to: path)
+ let yOffset = sin(yaw) * rx * 0.8
+ for sd in [-1.0, 1.0] {
+ let bx = CGFloat(sd) * rx * 0.55 + yOffset
+ let by = ry * 0.2
+ var ellipse = Path()
+ ellipse.addEllipse(in: CGRect(x: bx - R*0.17, y: by - R*0.1, width: R*0.34, height: R*0.2))
+ ctx.fill(ellipse, with: .color(Color(red: 1, green: 0.471, blue: 0.588, opacity: Double(0.5 * blush))))
+ }
+ }
+
+ private func drawEyes(ctx: inout GraphicsContext, path: Path, R: CGFloat, rx: CGFloat, ry: CGFloat) {
+ var shape = eyeOverride ?? cfg.eye
+ // In box mode: cup eyes when file over box (slotHTarget set), happy arcs while chewing
+ if morph > 0.5 {
+ if isChewing { shape = .happy }
+ else if slotHTarget > 0.05 || slotH > 0.10 { shape = .cup }
+ }
+ ctx.clip(to: path)
+
+ for sd in [-1.0, 1.0] {
+ let eyeYaw = CGFloat(sd) * MochiConst.eyeSp + yaw
+ var eyePitch = MochiConst.eyeP + pitch + roll
+ // Wrap pitch for roll-through effect
+ eyePitch = ((eyePitch + .pi).truncatingRemainder(dividingBy: .pi*2) + .pi*2).truncatingRemainder(dividingBy: .pi*2) - .pi
+
+ let cp = cos(eyePitch)
+ guard cos(eyeYaw) * cp > 0.04 else { continue } // behind head
+
+ let ex = sin(eyeYaw) * cp * rx
+ let ey = -sin(eyePitch) * ry + (morph > 0 ? ry * 0.14 * morph : 0)
+
+ let fx = lerp(max(0.18, cos(eyeYaw)), 1, morph * 0.7)
+ let fy = lerp(max(0.18, cp), 1, morph * 0.7)
+
+ let eyeMult: CGFloat = isMini ? 1.9 : 1.0
+ let ew = R * MochiConst.eyeW * es * eyeMult
+ let eh = R * MochiConst.eyeH * es * eyeMult
+
+ var eyeCtx = ctx
+ eyeCtx.translateBy(x: ex, y: ey)
+ eyeCtx.scaleBy(x: fx, y: fy)
+ drawEyeShape(ctx: &eyeCtx, shape: shape, w: ew, h: eh, open: open, sd: CGFloat(sd), R: R)
+ }
+ }
+
+ private func drawEyeShape(ctx: inout GraphicsContext, shape: EyeShape, w: CGFloat, h: CGFloat, open: CGFloat, sd: CGFloat, R: CGFloat) {
+ let ink = isMini ? Color(cgColor: MochiConst.miniInk) : Color(cgColor: MochiConst.ink)
+ let now = CGFloat(CACurrentMediaTime())
+
+ switch shape {
+ case .wide:
+ drawEyeShape(ctx: &ctx, shape: .pill, w: w*1.16, h: h*1.12, open: open, sd: sd, R: R)
+
+ case .pill:
+ let hh = max(h * open, w * 0.3)
+ var p = Path()
+ p.addRoundedRect(in: CGRect(x: -w/2, y: -hh/2, width: w, height: hh),
+ cornerSize: CGSize(width: min(w/2, hh/2), height: min(w/2, hh/2)))
+ ctx.fill(p, with: .color(ink))
+
+ case .dot:
+ var p = Path()
+ p.addEllipse(in: CGRect(x: -w*0.45, y: -w*0.45, width: w*0.9, height: w*0.9))
+ ctx.fill(p, with: .color(ink))
+
+ case .line:
+ ctx.rotate(by: .radians(-sd * 0.2))
+ var p = Path()
+ p.addRoundedRect(in: CGRect(x: -w*0.78, y: -w*0.21, width: w*1.56, height: w*0.42),
+ cornerSize: CGSize(width: w*0.21, height: w*0.21))
+ ctx.fill(p, with: .color(ink))
+
+ case .flat:
+ var p = Path()
+ p.addRoundedRect(in: CGRect(x: -w*0.72, y: -w*0.2, width: w*1.44, height: w*0.4),
+ cornerSize: CGSize(width: w*0.2, height: w*0.2))
+ ctx.fill(p, with: .color(ink))
+
+ case .happy:
+ var p = Path()
+ p.addArc(center: CGPoint(x: 0, y: h*0.18), radius: w*0.82,
+ startAngle: .degrees(180 + 12), endAngle: .degrees(180 - 12), clockwise: true)
+ ctx.stroke(p, with: .color(ink), style: StrokeStyle(lineWidth: w*0.5, lineCap: .round))
+
+ case .closed:
+ var p = Path()
+ p.addArc(center: CGPoint(x: 0, y: -h*0.08), radius: w*0.78,
+ startAngle: .degrees(15), endAngle: .degrees(165), clockwise: false)
+ ctx.stroke(p, with: .color(ink), style: StrokeStyle(lineWidth: w*0.36, lineCap: .round))
+
+ case .spiral:
+ var p = Path()
+ var a: CGFloat = 0
+ while a < 4.4 * .pi {
+ let r = w * 0.06 + a * w * 0.058
+ let aa = a + now * 9 * sd
+ let px = cos(aa) * r
+ let py = sin(aa) * r
+ if a == 0 { p.move(to: CGPoint(x: px, y: py)) }
+ else { p.addLine(to: CGPoint(x: px, y: py)) }
+ a += 0.2
+ }
+ ctx.stroke(p, with: .color(ink), style: StrokeStyle(lineWidth: w*0.22, lineCap: .round))
+
+ case .heart:
+ let heartPath = heartShape(size: w * 1.2)
+ ctx.fill(heartPath, with: .color(Color(hex: "#FF4D6D")))
+
+ case .star:
+ ctx.rotate(by: .radians(now * 1.5 * sd))
+ let starPath = starShape(outer: w * 1.05, inner: w * 0.46)
+ ctx.fill(starPath, with: .color(Color(hex: "#F7B32B")))
+
+ case .tired:
+ var p1 = Path()
+ p1.addRoundedRect(in: CGRect(x: -w/2, y: -h*0.02, width: w, height: h*0.38),
+ cornerSize: CGSize(width: w/2, height: w/2))
+ ctx.fill(p1, with: .color(ink))
+ var p2 = Path()
+ p2.addRoundedRect(in: CGRect(x: -w*0.62, y: -h*0.1, width: w*1.24, height: w*0.22),
+ cornerSize: CGSize(width: w*0.11, height: w*0.11))
+ ctx.fill(p2, with: .color(ink))
+
+ case .wink:
+ if sd < 0 {
+ let hh = max(h * open, w * 0.3)
+ var p = Path()
+ p.addRoundedRect(in: CGRect(x: -w/2, y: -hh/2, width: w, height: hh),
+ cornerSize: CGSize(width: min(w/2,hh/2), height: min(w/2,hh/2)))
+ ctx.fill(p, with: .color(ink))
+ } else {
+ var p = Path()
+ p.addArc(center: CGPoint(x: 0, y: h*0.18), radius: w*0.82,
+ startAngle: .degrees(180+12), endAngle: .degrees(180-12), clockwise: true)
+ ctx.stroke(p, with: .color(ink), style: StrokeStyle(lineWidth: w*0.5, lineCap: .round))
+ }
+
+ case .cup:
+ // Flat top, rounded bottom corners (like a cup / U-shape)
+ let hh = max(h * open, w * 0.3)
+ let cr = min(w / 2, hh / 2) // bottom corner radius
+ var p = Path()
+ p.move(to: CGPoint(x: -w/2, y: -hh/2))
+ p.addLine(to: CGPoint(x: w/2, y: -hh/2))
+ p.addLine(to: CGPoint(x: w/2, y: hh/2 - cr))
+ p.addQuadCurve(to: CGPoint(x: w/2 - cr, y: hh/2),
+ control: CGPoint(x: w/2, y: hh/2))
+ p.addLine(to: CGPoint(x: -w/2 + cr, y: hh/2))
+ p.addQuadCurve(to: CGPoint(x: -w/2, y: hh/2 - cr),
+ control: CGPoint(x: -w/2, y: hh/2))
+ p.closeSubpath()
+ ctx.fill(p, with: .color(ink))
+ }
+ }
+
+ private func drawBadge(context: GraphicsContext, size: CGSize, badge: BadgeType, R: CGFloat, rx: CGFloat, ry: CGFloat, cx: CGFloat, cy: CGFloat) {
+ let bs = badgeS * (isMini ? 1.25 : 1)
+ let bx = cx - R * 0.72 * sx
+ let by = cy - R * 0.72 * sy
+ var ctx = context
+ ctx.translateBy(x: bx, y: by)
+ ctx.scaleBy(x: bs, y: bs)
+ let now = CGFloat(CACurrentMediaTime())
+
+ switch badge {
+ case .dots(let col):
+ if isMini {
+ // Mini: animated pulsing dot
+ let phase = (now * 2.4).truncatingRemainder(dividingBy: 1)
+ let dotR = R * 0.22 * (1 + 0.25 * sin(phase * .pi * 2))
+ var outer = Path()
+ outer.addEllipse(in: CGRect(x: -R*0.2, y: -R*0.2, width: R*0.4, height: R*0.4))
+ ctx.fill(outer, with: .color(.black))
+ var dot = Path()
+ dot.addEllipse(in: CGRect(x: -dotR, y: -dotR, width: dotR*2, height: dotR*2))
+ ctx.fill(dot, with: .color(Color(cgColor: col)))
+ } else {
+ // Pill badge with animated dots (prototype style)
+ let pw: CGFloat = R * 0.72
+ let ph: CGFloat = R * 0.36
+ var pill = Path()
+ pill.addRoundedRect(in: CGRect(x: -pw/2, y: -ph/2, width: pw, height: ph),
+ cornerSize: CGSize(width: ph/2, height: ph/2))
+ ctx.fill(pill, with: .color(Color(cgColor: col)))
+ for i in 0..<3 {
+ let phase = ((now * 2.4 - CGFloat(i) * 0.22).truncatingRemainder(dividingBy: 1) + 1).truncatingRemainder(dividingBy: 1)
+ let dotR = R * 0.055 * (1 + 0.4 * max(0, sin(phase * .pi * 2)))
+ var dot = Path()
+ dot.addEllipse(in: CGRect(x: (CGFloat(i)-1)*R*0.18 - dotR, y: -dotR, width: dotR*2, height: dotR*2))
+ ctx.fill(dot, with: .color(.white))
+ }
+ }
+
+ case .bang(let col), .question(let col):
+ var ring = Path()
+ ring.addEllipse(in: CGRect(x: -R*0.3, y: -R*0.3, width: R*0.6, height: R*0.6))
+ ctx.fill(ring, with: .color(.black))
+ var inner = Path()
+ inner.addEllipse(in: CGRect(x: -R*0.23, y: -R*0.23, width: R*0.46, height: R*0.46))
+ ctx.fill(inner, with: .color(Color(cgColor: col)))
+ if !isMini {
+ let text = badge == .bang(col) ? "!" : "?"
+ ctx.draw(Text(text).font(.system(size: R*0.32, weight: .black)).foregroundColor(.white),
+ at: CGPoint(x: 0, y: R*0.02))
+ }
+
+ case .dot(let col):
+ var outer = Path()
+ outer.addEllipse(in: CGRect(x: -R*0.2, y: -R*0.2, width: R*0.4, height: R*0.4))
+ ctx.fill(outer, with: .color(.black))
+ var inner = Path()
+ inner.addEllipse(in: CGRect(x: -R*0.135, y: -R*0.135, width: R*0.27, height: R*0.27))
+ ctx.fill(inner, with: .color(Color(cgColor: col)))
+ }
+ }
+
+ private func drawParticles(context: GraphicsContext, size: CGSize, R: CGFloat, cx: CGFloat, cy: CGFloat) {
+ for p in particles {
+ guard p.age > 0 else { continue }
+ let k = CGFloat(p.age / p.life)
+ let a = k < 0.2 ? k / 0.2 : 1 - (k - 0.2) / 0.8
+ let px = cx + (p.x + p.vx * CGFloat(p.age)) * R * 1.3
+ let py = cy + (p.y + p.vy * CGFloat(p.age)) * R * 1.3
+ let sz = R * p.size * (1 + k * 0.4)
+
+ var pctx = context
+ pctx.translateBy(x: px, y: py)
+ pctx.opacity = Double(min(max(a, 0), 1))
+
+ switch p.type {
+ case .heart:
+ pctx.rotate(by: .radians(sin(CGFloat(p.age) * 6) * 0.3))
+ pctx.fill(heartShape(size: sz), with: .color(Color(hex: "#FF4D6D")))
+ case .star:
+ pctx.rotate(by: .radians(p.rot + CGFloat(p.age) * 2))
+ pctx.fill(starShape(outer: sz, inner: sz*0.45), with: .color(Color(hex: "#F7B32B")))
+ case .spark:
+ pctx.rotate(by: .radians(p.rot))
+ pctx.fill(starShape(outer: sz*0.8, inner: sz*0.18), with: .color(.white))
+ case .sweat:
+ var drop = Path()
+ drop.move(to: CGPoint(x: 0, y: -sz))
+ drop.addQuadCurve(to: CGPoint(x: 0, y: sz*0.6), control: CGPoint(x: sz*0.8, y: sz*0.2))
+ drop.addQuadCurve(to: CGPoint(x: 0, y: -sz), control: CGPoint(x: -sz*0.8, y: sz*0.2))
+ pctx.fill(drop, with: .color(Color(hex: "#7CC7FF")))
+ case .z:
+ pctx.draw(Text("z").font(.system(size: sz*1.9, weight: .bold)).foregroundColor(Color(red: 0.82, green: 0.86, blue: 0.92)),
+ at: .zero)
+ }
+ }
+ }
+
+ // MARK: - Tween helpers
+
+ func anim(_ key: String, keys: [TweenKey], onComplete: (() -> Void)? = nil) {
+ let current = getProperty(key)
+ tweens[key] = Tween(property: key, keys: keys, keyIndex: 0,
+ from: current, startTime: CACurrentMediaTime() * 1000,
+ onComplete: onComplete)
+ locks.insert(key)
+ }
+
+ private func setTarget(key: String, value: CGFloat) {
+ guard !locks.contains(key) else { return }
+ switch key {
+ case "tint": tint += (value - tint) // immediate target, smoothed in update
+ case "tilt": tgTilt = value
+ default: break
+ }
+ }
+
+ private func setProperty(_ key: String, value: CGFloat) {
+ switch key {
+ case "yaw": yaw = value
+ case "pitch": pitch = value
+ case "roll": roll = value
+ case "tilt": tilt = value
+ case "open": open = value
+ case "sx": sx = value
+ case "sy": sy = value
+ case "oy": oy = value
+ case "ox": ox = value
+ case "tint": tint = value
+ case "morph": morph = value
+ case "hands": hands = value
+ case "blush": blush = value
+ case "es": es = value
+ case "badgeS": badgeS = value
+ default: break
+ }
+ }
+
+ private func getProperty(_ key: String) -> CGFloat {
+ switch key {
+ case "yaw": return yaw
+ case "pitch": return pitch
+ case "roll": return roll
+ case "tilt": return tilt
+ case "open": return open
+ case "sx": return sx
+ case "sy": return sy
+ case "oy": return oy
+ case "ox": return ox
+ case "tint": return tint
+ case "morph": return morph
+ case "hands": return hands
+ case "blush": return blush
+ case "es": return es
+ case "badgeS": return badgeS
+ default: return 0
+ }
+ }
+}
+
+// MARK: - Math helpers
+
+private func lerp(_ a: CGFloat, _ b: CGFloat, _ t: CGFloat) -> CGFloat { a + (b-a) * t }
+private func clamp(_ v: CGFloat, _ lo: CGFloat, _ hi: CGFloat) -> CGFloat { max(lo, min(hi, v)) }
+
+private func cgColorToTuple(_ c: CGColor) -> (CGFloat, CGFloat, CGFloat) {
+ guard let comps = c.components, comps.count >= 3 else { return (1,1,1) }
+ return (comps[0], comps[1], comps[2])
+}
+
+private func mix3(_ a: (CGFloat,CGFloat,CGFloat), _ b: (CGFloat,CGFloat,CGFloat), _ t: CGFloat) -> (CGFloat,CGFloat,CGFloat) {
+ (lerp(a.0,b.0,t), lerp(a.1,b.1,t), lerp(a.2,b.2,t))
+}
+
+private func mixColor(_ a: (CGFloat,CGFloat,CGFloat), _ b: (CGFloat,CGFloat,CGFloat), _ t: CGFloat) -> (CGFloat,CGFloat,CGFloat) {
+ mix3(a, b, t)
+}
+
+private func colorFromTuple(_ t: (CGFloat,CGFloat,CGFloat)) -> Color {
+ Color(red: Double(t.0), green: Double(t.1), blue: Double(t.2))
+}
+
+private func badgeString(_ b: BadgeType?) -> String {
+ guard let b else { return "none" }
+ func hex(_ c: CGColor) -> String {
+ guard let k = c.components, k.count >= 3 else { return "?" }
+ return "\(Int(k[0]*255)).\(Int(k[1]*255)).\(Int(k[2]*255))"
+ }
+ switch b {
+ case .dots(let c): return "dots-\(hex(c))"
+ case .bang(let c): return "bang-\(hex(c))"
+ case .question(let c): return "q-\(hex(c))"
+ case .dot(let c): return "dot-\(hex(c))"
+ }
+}
+
+private func emoteEyeShape(_ e: BotEmote) -> EyeShape {
+ switch e {
+ case .love: return .heart
+ case .surprised: return .dot
+ case .proud: return .star
+ case .wink: return .wink
+ case .yawn: return .tired
+ case .happy: return .happy
+ case .annoyed: return .line
+ }
+}
+
+// MARK: - Shape helpers
+
+private func heartShape(size s: CGFloat) -> Path {
+ var p = Path()
+ p.move(to: CGPoint(x: 0, y: s * 0.38))
+ p.addCurve(to: CGPoint(x: 0, y: -s * 0.38),
+ control1: CGPoint(x: -s * 1.05, y: -s * 0.15),
+ control2: CGPoint(x: -s * 0.5, y: -s * 0.95))
+ p.addCurve(to: CGPoint(x: 0, y: s * 0.38),
+ control1: CGPoint(x: s * 0.5, y: -s * 0.95),
+ control2: CGPoint(x: s * 1.05, y: -s * 0.15))
+ p.closeSubpath()
+ return p
+}
+
+private func starShape(outer ro: CGFloat, inner ri: CGFloat) -> Path {
+ var p = Path()
+ for i in 0..<10 {
+ let r = i.isMultiple(of: 2) ? ro : ri
+ let a = -.pi/2 + CGFloat(i) * .pi/5
+ let pt = CGPoint(x: cos(a) * r, y: sin(a) * r)
+ if i == 0 { p.move(to: pt) } else { p.addLine(to: pt) }
+ }
+ p.closeSubpath()
+ return p
+}
+
+// Equatable for BadgeType (needed for comparing)
+extension BadgeType: Equatable {
+ static func == (lhs: BadgeType, rhs: BadgeType) -> Bool {
+ switch (lhs, rhs) {
+ case (.dots, .dots): return true
+ case (.bang, .bang): return true
+ case (.question, .question): return true
+ case (.dot, .dot): return true
+ default: return false
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/App/CalcomPoller.swift b/NotchBuddy/Sources/App/CalcomPoller.swift
new file mode 100644
index 00000000..ca08cd71
--- /dev/null
+++ b/NotchBuddy/Sources/App/CalcomPoller.swift
@@ -0,0 +1,97 @@
+import Foundation
+
+final class CalcomPoller: @unchecked Sendable {
+ static let shared = CalcomPoller()
+ private var timer: DispatchSourceTimer?
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 8, repeating: 300)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ func pollNow() { poll() }
+
+ private func poll() {
+ guard let key = KeychainStore.shared.get("calcom-api-key") else { return }
+ let cal = Calendar.current
+ let today = cal.startOfDay(for: Date())
+ let future = cal.date(byAdding: .day, value: 60, to: today)!
+ let iso = ISO8601DateFormatter(); iso.formatOptions = [.withInternetDateTime]
+ let startStr = iso.string(from: today)
+ let endStr = iso.string(from: future)
+
+ guard let url = URL(string: "https://api.cal.com/v2/bookings?status=upcoming&start=\(startStr)&end=\(endStr)") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
+ req.setValue("2024-08-13", forHTTPHeaderField: "cal-api-version")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if code != 200 {
+ let msg: String
+ if code == 401 { msg = "Invalid API key (401)" }
+ else if code == 0 { msg = error?.localizedDescription ?? "No connection" }
+ else { msg = "API error \(code)" }
+ DispatchQueue.main.async { AppState.shared.calcomError = msg }
+ return
+ }
+ guard let data,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let rawList = json["data"] as? [[String: Any]] else { return }
+
+ let parsed = rawList.compactMap { self.parseBooking($0) }
+ DispatchQueue.main.async {
+ AppState.shared.calcomError = nil
+ AppState.shared.calcomBookings = parsed
+ AppState.shared.calcomLoaded = true
+ }
+ }.resume()
+ }
+
+ private func parseBooking(_ b: [String: Any]) -> CalcomBooking? {
+ let id: Int
+ if let i = b["id"] as? Int { id = i }
+ else if let s = b["id"] as? String, let i = Int(s) { id = i }
+ else { return nil }
+
+ let title = (b["title"] as? String) ?? "Meeting"
+ let status = (b["status"] as? String) ?? "accepted"
+ guard let startStr = (b["start"] as? String) ?? (b["startTime"] as? String) else { return nil }
+
+ let iso = ISO8601DateFormatter()
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ var startTime = iso.date(from: startStr)
+ if startTime == nil {
+ let iso2 = ISO8601DateFormatter(); iso2.formatOptions = [.withInternetDateTime]
+ startTime = iso2.date(from: startStr)
+ }
+ guard let startTime else { return nil }
+
+ let endStr = (b["end"] as? String) ?? (b["endTime"] as? String) ?? ""
+ let endTime: Date = iso.date(from: endStr) ?? startTime
+
+ let attendees = b["attendees"] as? [[String: Any]] ?? []
+ let first = attendees.first
+ let name = first?["name"] as? String
+ let email = first?["email"] as? String
+
+ var notes: String? = nil
+ if let responses = b["responses"] as? [String: Any],
+ let notesObj = responses["notes"] as? [String: Any] {
+ notes = notesObj["value"] as? String
+ }
+ if (notes == nil || notes!.isEmpty), let desc = b["description"] as? String, !desc.isEmpty {
+ notes = desc
+ }
+
+ return CalcomBooking(id: id, title: title, startTime: startTime, endTime: endTime,
+ status: status, attendeeName: name, attendeeEmail: email,
+ attendeeNotes: notes)
+ }
+}
diff --git a/NotchBuddy/Sources/App/ClaudeService.swift b/NotchBuddy/Sources/App/ClaudeService.swift
new file mode 100644
index 00000000..503582be
--- /dev/null
+++ b/NotchBuddy/Sources/App/ClaudeService.swift
@@ -0,0 +1,358 @@
+import Foundation
+import Security
+
+// MARK: - Keychain helpers
+
+enum Keychain {
+ static let service = "fr.louisraille.NotchBuddy"
+
+ static func save(key: String, value: String) {
+ guard let data = value.data(using: .utf8) else { return }
+ // Delete existing item first (update pattern)
+ let lookup: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: key,
+ ]
+ SecItemDelete(lookup as CFDictionary)
+ // Add with strictest access control:
+ // WhenUnlockedThisDeviceOnly = accessible only while Mac is unlocked,
+ // never synced to iCloud, never migrated to another device.
+ let item: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: key,
+ kSecValueData as String: data,
+ kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
+ kSecAttrSynchronizable as String: kCFBooleanFalse!,
+ ]
+ SecItemAdd(item as CFDictionary, nil)
+ }
+
+ static func load(key: String) -> String? {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: key,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+ var result: AnyObject?
+ guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
+ let data = result as? Data else { return nil }
+ return String(data: data, encoding: .utf8)
+ }
+
+ static func delete(key: String) {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: key,
+ ]
+ SecItemDelete(query as CFDictionary)
+ }
+}
+
+// MARK: - Keychain cache (reads each key ONCE at launch; all subsequent access via dict)
+
+final class KeychainStore: @unchecked Sendable {
+ static let shared = KeychainStore()
+ private var cache: [String: String] = [:]
+ private let lock = NSLock()
+
+ private static let allKeys = [
+ "anthropic-api-key",
+ "resend-api-key", "resend-from",
+ "n8n-url", "n8n-api-key",
+ "vercel-token",
+ "github-token",
+ "stripe-api-key",
+ "calcom-api-key",
+ "notion-api-key",
+ ]
+
+ private init() {
+ // Called once, on main thread (AppDelegate triggers shared at launch).
+ for key in Self.allKeys {
+ if let v = Keychain.load(key: key) { cache[key] = v }
+ }
+ }
+
+ /// Thread-safe read — never touches the Keychain.
+ func get(_ key: String) -> String? {
+ lock.withLock { cache[key] }
+ }
+
+ /// Updates cache + persists to Keychain.
+ func set(_ key: String, value: String) {
+ lock.withLock { cache[key] = value }
+ Keychain.save(key: key, value: value)
+ }
+
+ /// Removes from cache + Keychain only if the key was previously set.
+ func remove(_ key: String) {
+ let had = lock.withLock { () -> Bool in
+ let exists = cache[key] != nil
+ cache[key] = nil
+ return exists
+ }
+ if had { Keychain.delete(key: key) }
+ }
+}
+
+// MARK: - Claude API
+
+@MainActor
+final class ClaudeService {
+ static let shared = ClaudeService()
+
+ private let endpoint = URL(string: "https://api.anthropic.com/v1/messages")!
+ private let anthropicVersion = "2023-06-01"
+ private let model = "claude-sonnet-4-6"
+
+ var apiKey: String? { KeychainStore.shared.get("anthropic-api-key") }
+
+ // Multi-turn conversation messages (for API)
+ private var conversationMessages: [[String: Any]] = []
+
+ func clearConversation() {
+ conversationMessages = []
+ }
+
+ private let systemPrompt = """
+ You are Mochi, Louis's personal AI assistant embedded in the notch of his Mac. \
+ You have web search access and can help with absolutely anything — research, coding, finding places, recommendations, tasks, questions. \
+ Respond in the user's language. Be thorough and complete — use as much detail as the task requires. \
+ No markdown formatting (no **, no ##, no bullet dashes). Use plain text with line breaks.
+ """
+
+ private let webSearchTools: [[String: Any]] = [
+ ["type": "web_search_20250305", "name": "web_search", "max_uses": 5]
+ ]
+
+ // MARK: - Chat (multi-turn, natural text + web search)
+
+ func chat(query: String, context: PromptContext?, state: AppState) async {
+ guard let key = apiKey, !key.isEmpty else {
+ await showError("API key missing. Open settings.", state: state)
+ return
+ }
+
+ // Build user content for this turn
+ var userContent: [[String: Any]] = []
+
+ // Add file/window context on first message only
+ if conversationMessages.isEmpty, let context = context {
+ switch context {
+ case .window(let app, let title, let url):
+ var text = "Context — App: \(app), Window: \(title)"
+ if let url = url { text += ", URL: \(url)" }
+ userContent.append(["type": "text", "text": text])
+ case .file(let name, let fileURL):
+ if let fileURL = fileURL, let block = readFileAsBlock(url: fileURL) {
+ userContent.append(block)
+ }
+ userContent.append(["type": "text", "text": "File: \(name)"])
+ }
+ }
+ userContent.append(["type": "text", "text": query])
+
+ conversationMessages.append(["role": "user", "content": userContent])
+
+ let body: [String: Any] = [
+ "model": model,
+ "max_tokens": 4096,
+ "tools": webSearchTools,
+ "system": systemPrompt,
+ "messages": conversationMessages,
+ ]
+
+ do {
+ let data = try await callAPI(body: body, key: key, beta: "web-search-2025-03-05")
+ await handleChatResult(data, state: state)
+ } catch {
+ conversationMessages.removeLast()
+ await showError("Network error: \(error.localizedDescription)", state: state)
+ }
+ }
+
+ // MARK: - Structured search (M8 — window attach + web search)
+
+ func search(query: String, context: PromptContext?, state: AppState) async {
+ guard let key = apiKey, !key.isEmpty else {
+ await showError("Anthropic API key missing. Open settings to configure it.", state: state)
+ return
+ }
+
+ var userContent: [[String: Any]] = []
+ switch context {
+ case .window(let appName, let title, let url):
+ var text = "App: \(appName)\nWindow title: \(title)"
+ if let url = url { text += "\nURL: \(url)" }
+ text += "\n\nRequest: \(query)"
+ userContent.append(["type": "text", "text": text])
+ case .file(let name, let fileURL):
+ if let fileURL = fileURL, let fileBlock = readFileAsBlock(url: fileURL) {
+ userContent.append(fileBlock)
+ }
+ userContent.append(["type": "text", "text": "File: \(name)\n\nRequest: \(query)"])
+ case nil:
+ userContent.append(["type": "text", "text": query])
+ }
+
+ let system = """
+ You are an assistant built into the notch of a Mac. Reply in English, short and precise.
+ Reply ONLY with valid JSON in this exact format:
+ {"title":"...","items":[{"label":"...","detail":"...","url":"..."}],"note":"..."}
+ Maximum 3 items. "url" is optional. "note" is optional.
+ """
+
+ let tools: [[String: Any]] = [
+ ["type": "web_search_20250305", "name": "web_search", "max_uses": 3]
+ ]
+
+ let body: [String: Any] = [
+ "model": model,
+ "max_tokens": 1024,
+ "tools": tools,
+ "system": system,
+ "messages": [["role": "user", "content": userContent]],
+ ]
+
+ do {
+ let result = try await callAPI(body: body, key: key, beta: "web-search-2025-03-05")
+ await handleResult(result, state: state)
+ } catch {
+ await showError("Network error: \(error.localizedDescription)", state: state)
+ }
+ }
+
+ // MARK: - API call
+
+ private func callAPI(body: [String: Any], key: String, beta: String? = nil) async throws -> Data {
+ var request = URLRequest(url: endpoint)
+ request.httpMethod = "POST"
+ request.setValue(key, forHTTPHeaderField: "x-api-key")
+ request.setValue(anthropicVersion, forHTTPHeaderField: "anthropic-version")
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ if let beta { request.setValue(beta, forHTTPHeaderField: "anthropic-beta") }
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+ request.timeoutInterval = 45
+
+ let (data, response) = try await URLSession.shared.data(for: request)
+
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ let msg = String(data: data, encoding: .utf8) ?? "unknown error"
+ throw NSError(domain: "Claude", code: 0, userInfo: [NSLocalizedDescriptionKey: msg])
+ }
+ return data
+ }
+
+ // MARK: - Chat result handler
+
+ private func handleChatResult(_ data: Data, state: AppState) async {
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let content = json["content"] as? [[String: Any]] else {
+ await showError("Unexpected API response.", state: state)
+ return
+ }
+
+ // Store full content (includes tool_use/tool_result blocks) for correct multi-turn context
+ conversationMessages.append(["role": "assistant", "content": content])
+
+ guard let textBlock = content.first(where: { $0["type"] as? String == "text" }),
+ let text = textBlock["text"] as? String, !text.isEmpty else {
+ await showError("No response text.", state: state)
+ return
+ }
+
+ // Add to display history
+ state.chatHistory.append(ChatMessage(role: .assistant, content: text.trimmingCharacters(in: .whitespacesAndNewlines)))
+
+ state.stateOverride = nil
+ state.view = .prompt
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+ }
+
+ // MARK: - Structured result handler
+
+ private func handleResult(_ data: Data, state: AppState) async {
+ // Extract text from Anthropic response (may contain tool_use / web_search_tool_result blocks)
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let content = json["content"] as? [[String: Any]],
+ let textBlock = content.first(where: { $0["type"] as? String == "text" }),
+ let text = textBlock["text"] as? String else {
+ await showError("Unexpected API response.", state: state)
+ return
+ }
+
+ // Strip markdown code fences if present, then extract JSON object
+ let cleanText: String
+ if let start = text.firstIndex(of: "{"), let end = text.lastIndex(of: "}") {
+ cleanText = String(text[start...end])
+ } else {
+ cleanText = text
+ }
+
+ // Try to parse as our JSON format
+ if let resultData = cleanText.data(using: .utf8),
+ let parsed = try? JSONSerialization.jsonObject(with: resultData) as? [String: Any] {
+ let title = parsed["title"] as? String ?? "Result"
+ let note = parsed["note"] as? String
+ var items: [ResultItem] = []
+ if let rawItems = parsed["items"] as? [[String: Any]] {
+ for item in rawItems.prefix(3) {
+ items.append(ResultItem(
+ label: item["label"] as? String ?? "",
+ detail: item["detail"] as? String ?? "",
+ url: item["url"] as? String
+ ))
+ }
+ }
+ state.searchResult = SearchResult(title: title, items: items, note: note)
+ } else {
+ // Fallback: show raw text in 3-line chunks
+ let lines = cleanText.components(separatedBy: "\n").filter { !$0.isEmpty }.prefix(3)
+ state.searchResult = SearchResult(
+ title: "Claude's response",
+ items: lines.map { ResultItem(label: $0, detail: "", url: nil) },
+ note: nil
+ )
+ }
+
+ state.stateOverride = nil
+ state.view = .result
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.proud)
+ }
+
+ private func showError(_ message: String, state: AppState) async {
+ state.stateOverride = .error
+ state.noteMessage = message
+ state.view = .note
+ }
+
+ // MARK: - File content block builder
+
+ private func readFileAsBlock(url: URL) -> [String: Any]? {
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ let ext = url.pathExtension.lowercased()
+ let base64 = data.base64EncodedString()
+
+ if ext == "pdf" {
+ return ["type": "document", "source": ["type": "base64", "media_type": "application/pdf", "data": base64]]
+ } else if ["jpg", "jpeg"].contains(ext) {
+ return ["type": "image", "source": ["type": "base64", "media_type": "image/jpeg", "data": base64]]
+ } else if ext == "png" {
+ return ["type": "image", "source": ["type": "base64", "media_type": "image/png", "data": base64]]
+ } else if ext == "gif" {
+ return ["type": "image", "source": ["type": "base64", "media_type": "image/gif", "data": base64]]
+ } else if ext == "webp" {
+ return ["type": "image", "source": ["type": "base64", "media_type": "image/webp", "data": base64]]
+ } else {
+ // Text/code — inline as text if <= 200 KB
+ guard data.count <= 200_000,
+ let text = String(data: data, encoding: .utf8) else { return nil }
+ return ["type": "text", "text": "File contents:\n\(text)"]
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/App/FileDropView.swift b/NotchBuddy/Sources/App/FileDropView.swift
new file mode 100644
index 00000000..9a47a33d
--- /dev/null
+++ b/NotchBuddy/Sources/App/FileDropView.swift
@@ -0,0 +1,124 @@
+import AppKit
+import SwiftUI
+
+// MARK: - NSView drag destination
+// Wired at the AppKit level in IslandWindowController (not via SwiftUI NSViewRepresentable)
+// so it never interferes with SwiftUI hit-testing.
+
+final class FileDropNSView: NSView {
+ var onDragEntered: ((CGPoint) -> Void)?
+ var onDragUpdated: ((CGPoint) -> Void)?
+ var onDragExited: (() -> Void)?
+ var onFilesDropped: (([URL]) -> Void)?
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ registerForDraggedTypes([.fileURL])
+ }
+ required init?(coder: NSCoder) { fatalError() }
+
+ // Pass all mouse events through — drag-drop uses NSDraggingDestination, not hitTest
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ onDragEntered?(sender.draggingLocation)
+ return .copy
+ }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ onDragUpdated?(sender.draggingLocation)
+ return .copy
+ }
+ override func draggingExited(_ sender: NSDraggingInfo?) { onDragExited?() }
+
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ guard let urls = sender.draggingPasteboard.readObjects(
+ forClasses: [NSURL.self],
+ options: [.urlReadingFileURLsOnly: true]
+ ) as? [URL], !urls.isEmpty else { return false }
+ onFilesDropped?(urls)
+ return true
+ }
+}
+
+// MARK: - File drop handler
+
+enum FileDropHandler {
+ @MainActor
+ static func handle(urls: [URL], state: AppState) async {
+ guard let url = urls.first else { return }
+ let name = url.lastPathComponent
+
+ // Start animation immediately — do NOT block on file copy.
+ // Use original URL first; swap to inbox copy once background copy finishes.
+ state.droppedFile = DroppedFile(url: url, name: name)
+ state.uploadProgress = 0
+ state.fileDragOver = false
+ state.promptContext = .file(name: name, fileURL: url)
+
+ let dur = 2.4
+ UploadSequenceEngine.shared.performDrop(uploadDuration: dur)
+
+ // Copy to inbox in background — update state when done
+ let inbox = HookServer.supportDir.appendingPathComponent("inbox")
+ Task.detached {
+ try? FileManager.default.createDirectory(at: inbox, withIntermediateDirectories: true)
+ let dest = inbox.appendingPathComponent(name)
+ try? FileManager.default.removeItem(at: dest)
+ if (try? FileManager.default.copyItem(at: url, to: dest)) != nil {
+ await MainActor.run {
+ state.droppedFile = DroppedFile(url: dest, name: name)
+ state.promptContext = .file(name: name, fileURL: dest)
+ }
+ }
+ }
+
+ // Drop feedback
+ NotificationCenter.default.post(name: .botGulp, object: nil)
+ SoundEngine.shared.play("approve")
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+ NotificationCenter.default.post(name: .botMorphTo, object: CGFloat(0))
+
+ state.uploadDuration = dur
+ state.uploadStartTime = Date()
+ state.view = .uploading // canvas stays active: uploadActive covers .uploading
+
+ // Canvas timeline from drop:
+ // T_DROP → T_PROG_START : ≈1.30s gulp + shrink + bar reveal
+ // T_PROG_START → progEnd: dur progress bar fills
+ // progEnd → growEnd : 0.70s Mochi grows back to choose position
+ let preProgress = USC.T_PROG_START - USC.T_DROP // ≈1.30s
+
+ // Tick sounds — delayed to sync with canvas progress start
+ Task { @MainActor in
+ var lastTens = 0
+ let progStart = Date().addingTimeInterval(preProgress)
+ while lastTens < 9 {
+ try? await Task.sleep(nanoseconds: 80_000_000)
+ let approxP = min(1.0, max(0, Date().timeIntervalSince(progStart) / dur))
+ let tens = Int(approxP * 10)
+ if tens > lastTens {
+ SoundEngine.shared.play("tick")
+ lastTens = tens
+ }
+ }
+ }
+
+ // Wait for canvas progress to complete (gulp/shrink phase + upload duration)
+ try? await Task.sleep(nanoseconds: UInt64((preProgress + dur) * 1_000_000_000))
+
+ // Canvas shows checkmark at this point
+ SoundEngine.shared.play("approve")
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+
+ // Wait for grow-back animation + choose overlay settle
+ try? await Task.sleep(nanoseconds: UInt64(1_000_000_000))
+
+ // Clean up upload state
+ state.uploadProgress = 0
+ state.uploadStartTime = nil
+
+ // Switch to choose — canvas stays active (uploadActive covers .choose).
+ // Engine deactivates when user clicks a canvas choose button or navigates away.
+ state.view = .choose
+ }
+}
diff --git a/NotchBuddy/Sources/App/GithubPoller.swift b/NotchBuddy/Sources/App/GithubPoller.swift
new file mode 100644
index 00000000..7b51c4cc
--- /dev/null
+++ b/NotchBuddy/Sources/App/GithubPoller.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+final class GithubPoller: @unchecked Sendable {
+ static let shared = GithubPoller()
+ private var timer: DispatchSourceTimer?
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 7, repeating: 300) // every 5 minutes
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ private func poll() {
+ guard let token = KeychainStore.shared.get("github-token") else { return }
+ fetchUser(token: token)
+ }
+
+ private func fetchUser(token: String) {
+ guard let url = URL(string: "https://api.github.com/user") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, _ in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
+
+ let publicRepos = (json["public_repos"] as? Int) ?? 0
+ let privateOwned = (json["owned_private_repos"] as? Int)
+ ?? (json["total_private_repos"] as? Int)
+ ?? 0
+ let totalRepos = publicRepos + privateOwned
+
+ self.fetchStars(token: token, totalRepos: totalRepos)
+ }.resume()
+ }
+
+ private func fetchStars(token: String, totalRepos: Int) {
+ guard let url = URL(string: "https://api.github.com/user/repos?per_page=100&affiliation=owner&sort=pushed") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 15)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+
+ URLSession.shared.dataTask(with: req) { data, response, _ in
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200,
+ let repos = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return }
+
+ let totalStars = repos.reduce(0) { $0 + ((($1["stargazers_count"] as? Int) ?? 0)) }
+
+ DispatchQueue.main.async {
+ AppState.shared.githubStats = GitHubStats(totalRepos: totalRepos, totalStars: totalStars)
+ }
+ }.resume()
+ }
+}
diff --git a/NotchBuddy/Sources/App/GreetingCanvasView.swift b/NotchBuddy/Sources/App/GreetingCanvasView.swift
new file mode 100644
index 00000000..5c7ffe15
--- /dev/null
+++ b/NotchBuddy/Sources/App/GreetingCanvasView.swift
@@ -0,0 +1,617 @@
+import SwiftUI
+
+// MARK: - Timing constants (mirrors greeting-v2.html T = {...})
+
+private enum GT {
+ static let grow: Double = 0.45
+ static let squint0: Double = 0.60
+ static let squint1: Double = 0.82
+ static let dip0: Double = 1.25
+ static let dip1: Double = 1.40
+ static let pop0: Double = 1.36
+ static let pop1: Double = 1.52
+ static let content0: Double = 2.45
+ static let content1: Double = 2.58
+ static let tuck0: Double = 2.58
+ static let tuck1: Double = 2.80
+ static let badge: Double = 2.72
+ static let down0: Double = 2.85
+ static let down1: Double = 3.20
+ static let blink2: Double = 3.80
+ static let tint0: Double = 3.85
+ static let tint1: Double = 4.15
+ static let end: Double = 4.60 // animation done; greetComplete fires here
+ static let autoLeave:Double = 4.90 // visual collapse trigger (no hover)
+ static let COLLAPSE: Double = 0.34
+}
+
+// MARK: - Geometry constants (640×150 reference space)
+
+private let GC0 = CGPoint(x: 320, y: 90) // Mochi center
+private let GHB: CGFloat = 58 // body height at full size
+private let GASP: CGFloat = 1.34 // body width/height ratio
+private let GEAR_X: CGFloat = 40 // ear x from small island left edge (matches BotPlacement compact x=40)
+private let GEAR_Y: CGFloat = 16 // ear y
+private let GEAR_HB:CGFloat = 17 // ear body height
+private let GCARD = CGRect(x: 10, y: 36, width: 620, height: 104)
+private let GCARD_R:CGFloat = 20
+
+// Small island = compact mode size (matches our actual nw+160)
+private var GSMALL_W: CGFloat { IslandConst.notchWidth + 160 }
+private let GSMALL_H: CGFloat = IslandConst.notchHeight
+
+// MARK: - Easing (mirrors E = {...})
+
+private enum GE {
+ static func out(_ t: Double) -> Double { 1 - pow(1 - t, 3) }
+ static func easeIn(_ t: Double)-> Double { t * t * t }
+ static func inOut(_ t: Double) -> Double {
+ t < 0.5 ? 4*t*t*t : 1 - pow(-2*t+2, 3)/2
+ }
+ static func back(_ t: Double) -> Double {
+ let c1=1.70158, c3=c1+1
+ return 1 + c3*pow(t-1,3) + c1*pow(t-1,2)
+ }
+}
+
+private func gClamp(_ v: Double, _ a: Double, _ b: Double) -> Double { max(a, min(b, v)) }
+private func gLerp(_ a: Double, _ b: Double, _ t: Double) -> Double { a + (b - a) * t }
+private func gSeg(_ t: Double, _ a: Double, _ b: Double) -> Double { gClamp((t-a)/(b-a), 0, 1) }
+private func gLerpF(_ a: CGFloat, _ b: CGFloat, _ t: CGFloat) -> CGFloat { a + (b-a)*t }
+
+// MARK: - Pose
+
+private enum GEyeType { case dot, happy, content }
+
+private struct GreetPose {
+ var hb, x, y, sx, sy, tilt: Double
+ var eye: GEyeType; var open, eyeRoll: Double
+ var lookX, lookY: Double
+ var handL, handR, wave: Double
+ var badge, tint, halo, haloBlue, minis, fx: Double
+ var header, card: Double
+ // island dims (only for reference — not drawn here, just used for clip ref)
+ var iw, ih: Double
+}
+
+// MARK: - Particles (seeded LCG matching JS reference seed=7)
+
+private struct GRingDot { let a, j, s, al: Double }
+private struct GRing { let t0: Double; let dots: [GRingDot] }
+private struct GStreak { let a, sp, len, t0: Double; let col: String }
+
+private let greetParticles: (rings: [GRing], streaks: [GStreak]) = {
+ var seed: UInt32 = 7
+ func rnd() -> Double {
+ seed = (seed &* 1103515245 &+ 12345) & 0x7fffffff
+ return Double(seed) / Double(0x7fff_ffff)
+ }
+ let rings = [0.10, 0.20, 0.30, 0.45, 0.60].map { t0 in
+ GRing(t0: t0, dots: (0..<170).map { _ in
+ GRingDot(a: rnd() * .pi * 2, j: (rnd()-0.5)*0.22, s: 0.7+rnd()*0.9, al: 0.45+rnd()*0.55)
+ })
+ }
+ let cols = ["#3B9EFF","#F29B38","#FF5A4E","#2EC4A0","#A78BFA"]
+ let streaks = (0..<16).map { i in
+ GStreak(a: Double(i)/16 * .pi * 2+(rnd()-0.5)*0.3, sp: 230+rnd()*260,
+ len: 6+rnd()*9, t0: 0.08+rnd()*0.14, col: cols[i%5])
+ }
+ return (rings, streaks)
+}()
+
+// MARK: - Pose computation
+
+private func greetPose(_ t: Double) -> GreetPose {
+ // island size interpolation (used as reference for clip, not drawn)
+ let gx = gSeg(t, 0, 0.5)
+ let g = sin(.pi*gx/2) + 0.04*sin(.pi*gx)*gx
+ let iw = gLerp(Double(IslandConst.notchWidth), 640, g)
+ let ih = gLerp(Double(IslandConst.notchHeight), 150, g)
+
+ // body grows with back-ease (tiny → full size)
+ let gg = GE.back(gSeg(t, 0.02, GT.grow))
+ var hb = gLerp(3, Double(GHB), gg)
+ var x = Double(GC0.x)
+ var y = gLerp(16, Double(GC0.y), GE.out(gSeg(t, 0.02, GT.grow)))
+ var sx = 1.0, sy = 1.0, tilt = 0.0
+
+ // dip (1.25→1.52): body squishes forward
+ if t >= GT.dip0 && t < GT.pop1 {
+ let k = sin(.pi*gSeg(t, GT.dip0, GT.pop1))
+ y += hb*0.22*k; sy = 1-0.06*k; sx = 1+0.04*k
+ }
+ // wave sway (1.52→2.80)
+ if t >= GT.pop1 && t < GT.tuck1 {
+ let w = t - GT.pop1
+ let fade = 1 - gSeg(t, GT.tuck0, GT.tuck1)
+ x += sin(w*2 * .pi*0.9)*hb*Double(GASP)*0.05*fade
+ tilt = sin(w*2 * .pi*0.9+0.6)*0.05*fade
+ y += sin(w*2 * .pi*1.8)*0.8*fade
+ }
+ // settle (2.58→3.20)
+ if t >= GT.tuck0 && t < GT.down1 {
+ y += hb*0.12*sin(.pi*gSeg(t, GT.tuck0, GT.down1))
+ }
+
+ // eyes
+ var eye: GEyeType = .dot
+ if t >= GT.squint0 && t < GT.squint1 { eye = .happy }
+ if t >= GT.content0 && t < GT.content1 { eye = .content }
+ if t >= GT.down0 && t < GT.down1 { eye = .content }
+ var eyeRoll = 0.0
+ if t >= GT.dip0 && t < GT.pop1 { eyeRoll = sin(.pi*gSeg(t, GT.dip0, GT.pop1)) }
+ let blink: (Double) -> Double = { tb in
+ let k = gSeg(t, tb, tb+0.12); return (k>0&&k<1) ? 1-sin(.pi*k)*0.94 : 1
+ }
+ let openVal = min(blink(1.95), blink(GT.blink2))
+
+ // look
+ var lookX = 0.0, lookY = 0.0
+ if t >= GT.squint1 && t < GT.dip0 { lookY = -0.2 }
+ if t >= GT.pop1 && t < GT.content0 { lookX = 0.55; lookY = -0.45 }
+ if t >= GT.content0 && t < GT.down1 { lookX = -0.3; lookY = 0.6 }
+ if t >= GT.down1 {
+ let k = GE.inOut(gSeg(t, GT.down1, GT.down1+0.35))
+ lookX = gLerp(-0.3, 0, k); lookY = gLerp(0.6, 0, k)
+ }
+
+ // hands
+ let handL = t < GT.tuck0
+ ? GE.back(gSeg(t, GT.pop0, GT.pop0+0.14))
+ : 1 - GE.easeIn(gSeg(t, GT.tuck0, GT.tuck1-0.03))
+ let handR = t < GT.tuck0
+ ? GE.back(gSeg(t, GT.pop0+0.04, GT.pop0+0.18))
+ : 1 - GE.easeIn(gSeg(t, GT.tuck0+0.03, GT.tuck1))
+ let wave = (t >= GT.pop1 && t < GT.tuck0) ? t - GT.pop1 : -1.0
+
+ return GreetPose(
+ hb: hb, x: x, y: y, sx: sx, sy: sy, tilt: tilt,
+ eye: eye, open: openVal, eyeRoll: eyeRoll,
+ lookX: lookX, lookY: lookY,
+ handL: handL, handR: handR, wave: wave,
+ badge: GE.back(gSeg(t, GT.badge, GT.badge+0.28)),
+ tint: 0.6*GE.inOut(gSeg(t, GT.tint0, GT.tint1)),
+ halo: GE.out(gSeg(t, 0.3, 0.7)),
+ haloBlue: gSeg(t, GT.tint0, GT.tint1),
+ minis: 0, fx: 1,
+ header: gSeg(t, 0.35, 0.6), card: gSeg(t, 0.18, 0.45),
+ iw: iw, ih: ih
+ )
+}
+
+private func smallPose() -> GreetPose {
+ let sw = Double(GSMALL_W)
+ return GreetPose(
+ hb: Double(GEAR_HB),
+ x: 320 - sw/2 + Double(GEAR_X),
+ y: Double(GEAR_Y),
+ sx: 1, sy: 1, tilt: 0,
+ eye: .dot, open: 1, eyeRoll: 0,
+ lookX: 0, lookY: 0,
+ handL: 0, handR: 0, wave: -1,
+ badge: 1, tint: 0.6, halo: 0.6, haloBlue: 1,
+ minis: 1, fx: 1,
+ header: 0, card: 0,
+ iw: sw, ih: Double(GSMALL_H)
+ )
+}
+
+private func pose(_ t: Double, tc: Double) -> GreetPose {
+ if t < tc { return greetPose(min(t, GT.end + 10)) }
+ let a = greetPose(tc)
+ let b = smallPose()
+ let e = GE.inOut(gSeg(t, tc, tc + GT.COLLAPSE))
+ var p = a
+ p.iw = gLerp(a.iw, b.iw, e); p.ih = gLerp(a.ih, b.ih, e)
+ p.x = gLerp(a.x, b.x, e); p.y = gLerp(a.y, b.y, e)
+ p.hb = gLerp(a.hb, b.hb, e)
+ p.badge = gLerp(a.badge, b.badge, e)
+ p.tint = gLerp(a.tint, b.tint, e)
+ p.halo = gLerp(a.halo, b.halo, e)
+ p.haloBlue = gLerp(a.haloBlue, b.haloBlue, e)
+ p.header = a.header * (1 - gSeg(t, tc, tc+0.1))
+ p.card = a.card * (1 - gSeg(t, tc, tc+0.18))
+ p.handL = a.handL * (1 - gSeg(t, tc, tc+0.15))
+ p.handR = a.handR * (1 - gSeg(t, tc, tc+0.15))
+ p.wave = a.wave >= 0 ? a.wave : -1
+ p.tilt = a.tilt * (1 - e)
+ p.sx = gLerp(a.sx, 1, e); p.sy = gLerp(a.sy, 1, e)
+ p.eyeRoll = a.eyeRoll * (1 - e)
+ let bk = gSeg(t, tc+0.14, tc+0.26)
+ p.eye = .dot; p.open = (bk > 0 && bk < 1) ? 1 - sin(.pi*bk)*0.94 : 1
+ p.lookX = a.lookX*(1-e); p.lookY = a.lookY*(1-e)
+ p.minis = GE.back(gSeg(t, tc+0.24, tc+0.42))
+ p.fx = 1 - gSeg(t, tc, tc+0.2)
+ return p
+}
+
+// MARK: - Drawing helpers
+
+private func gHex(_ hex: String, alpha: CGFloat = 1) -> CGColor {
+ let h = hex.trimmingCharacters(in: CharacterSet(charactersIn:"#"))
+ let v = UInt64(h, radix: 16) ?? 0
+ return CGColor(red: CGFloat((v>>16)&0xFF)/255,
+ green: CGFloat((v>>8)&0xFF)/255,
+ blue: CGFloat(v&0xFF)/255, alpha: alpha)
+}
+
+private func gRR(_ ctx: CGContext, _ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat, _ r: CGFloat) {
+ let r = max(0, min(r, w/2, h/2))
+ ctx.beginPath()
+ ctx.move(to: CGPoint(x: x+r, y: y))
+ ctx.addArc(tangent1End: CGPoint(x: x+w, y: y), tangent2End: CGPoint(x: x+w, y: y+h), radius: r)
+ ctx.addArc(tangent1End: CGPoint(x: x+w, y: y+h), tangent2End: CGPoint(x: x, y: y+h), radius: r)
+ ctx.addArc(tangent1End: CGPoint(x: x, y: y+h), tangent2End: CGPoint(x: x, y: y), radius: r)
+ ctx.addArc(tangent1End: CGPoint(x: x, y: y), tangent2End: CGPoint(x: x+r, y: y), radius: r)
+ ctx.closePath()
+}
+
+private func mochiPath(hw: CGFloat, hh: CGFloat) -> CGPath {
+ let n: CGFloat = 3.2
+ let path = CGMutablePath()
+ let steps = 96
+ for i in 0...steps {
+ let a = CGFloat(i)/CGFloat(steps)*2 * .pi
+ let ca = cos(a), sa = sin(a)
+ let px = hw * (ca < 0 ? -1 : 1) * pow(abs(ca), 2/n)
+ let py = hh * (sa < 0 ? -1 : 1) * pow(abs(sa), 2/n)
+ if i == 0 { path.move(to: CGPoint(x: px, y: py)) }
+ else { path.addLine(to: CGPoint(x: px, y: py)) }
+ }
+ path.closeSubpath(); return path
+}
+
+// Linear gradient fill clipped to path (body-local coords, centered at origin)
+private func whiteFill(_ ctx: CGContext, _ path: CGPath,
+ x0: CGFloat, y0: CGFloat, x1: CGFloat, y1: CGFloat) {
+ let cs = CGColorSpaceCreateDeviceRGB()
+ let c0 = CGColor(red: 251/255, green: 251/255, blue: 252/255, alpha: 1)
+ let c1 = CGColor(red: 231/255, green: 233/255, blue: 236/255, alpha: 1)
+ guard let g = CGGradient(colorsSpace: cs, colors: [c0,c1] as CFArray, locations: [0,1]) else { return }
+ ctx.saveGState()
+ ctx.addPath(path); ctx.clip()
+ ctx.drawLinearGradient(g, start: CGPoint(x: x0, y: y0), end: CGPoint(x: x1, y: y1), options: [])
+ ctx.restoreGState()
+}
+
+private func drawHandL(_ ctx: CGContext, hw: CGFloat, hh: CGFloat, p: GreetPose) {
+ let k = CGFloat(p.handL); guard k > 0.01 else { return }
+ let hb = hh*2, r = hb*0.15*k
+ let rx = gLerpF(-hw*0.35, -hw-hb*0.22, k)
+ let ry0 = gLerpF(hh*0.85, hh*0.62, k)
+ var ry = Double(ry0)
+ if p.wave >= 0 { ry += sin(p.wave*6)*Double(hb)*0.02 }
+ ctx.saveGState()
+ ctx.translateBy(x: rx, y: CGFloat(ry))
+ let circ = CGPath(ellipseIn: CGRect(x: -r, y: -r, width: r*2, height: r*2), transform: nil)
+ whiteFill(ctx, circ, x0: r, y0: -r, x1: -r, y1: r)
+ ctx.addEllipse(in: CGRect(x: -r, y: -r, width: r*2, height: r*2))
+ ctx.setStrokeColor(CGColor(red: 0, green: 0, blue: 0, alpha: 0.08))
+ ctx.setLineWidth(0.8); ctx.strokePath()
+ ctx.restoreGState()
+}
+
+private func drawHandR(_ ctx: CGContext, hw: CGFloat, hh: CGFloat, p: GreetPose) {
+ let k = CGFloat(p.handR); guard k > 0.01 else { return }
+ let hb = hh*2, L = hb*0.40*k, T2 = hb*0.22*k
+ let rx0 = gLerpF(hw*0.35, hw+hb*0.20, k)
+ let ry0 = gLerpF(hh*0.85, hh*0.20, k)
+ var rx = Double(rx0), ry = Double(ry0), ang = -0.61
+ if p.wave >= 0 {
+ let w = p.wave*2 * .pi*2.5
+ ang += sin(w)*0.21; ry += sin(w+0.8)*Double(hb)*0.04; rx += cos(w)*Double(hb)*0.015
+ }
+ ctx.saveGState()
+ ctx.translateBy(x: CGFloat(rx), y: CGFloat(ry)); ctx.rotate(by: CGFloat(ang))
+ let cap = CGMutablePath()
+ gRR(ctx, -L/2, -T2/2, L, T2, T2/2)
+ cap.addPath(ctx.path!); ctx.beginPath() // use current ctx path as clip path
+ whiteFill(ctx, cap, x0: L/2, y0: -T2/2, x1: -L/2, y1: T2/2)
+ gRR(ctx, -L/2, -T2/2, L, T2, T2/2)
+ ctx.setStrokeColor(CGColor(red: 0, green: 0, blue: 0, alpha: 0.08))
+ ctx.setLineWidth(0.8); ctx.strokePath()
+ ctx.restoreGState()
+}
+
+private func drawMochi(_ ctx: CGContext, p: GreetPose) {
+ let hh = CGFloat(p.hb/2), hw = hh*GASP; guard hh > 0.4 else { return }
+
+ // Halo (golden → blue) — soft diffuse aura, two-pass for smoothness
+ if p.halo > 0 {
+ let bl = CGFloat(p.haloBlue)
+ let cr = gLerpF(232/255, 59/255, bl)
+ let cg = gLerpF(195/255, 158/255, bl)
+ let cb = gLerpF(154/255, 255/255, bl)
+ let cs = CGColorSpaceCreateDeviceRGB()
+ let cx = CGFloat(p.x), cy = CGFloat(p.y)
+ // Inner soft glow
+ let R1 = hw * 2.6
+ let ic1 = CGColor(red: cr, green: cg, blue: cb, alpha: CGFloat(0.18 * p.halo))
+ let oc1 = CGColor(red: cr, green: cg, blue: cb, alpha: 0)
+ if let g1 = CGGradient(colorsSpace: cs, colors: [ic1, oc1] as CFArray, locations: [0, 1]) {
+ ctx.saveGState()
+ ctx.addEllipse(in: CGRect(x: cx-R1, y: cy-R1, width: R1*2, height: R1*2))
+ ctx.clip()
+ ctx.drawRadialGradient(g1, startCenter: CGPoint(x: cx, y: cy), startRadius: 0,
+ endCenter: CGPoint(x: cx, y: cy), endRadius: R1, options: [])
+ ctx.restoreGState()
+ }
+ // Outer wide aura
+ let R2 = hw * 4.2
+ let ic2 = CGColor(red: cr, green: cg, blue: cb, alpha: CGFloat(0.07 * p.halo))
+ let oc2 = CGColor(red: cr, green: cg, blue: cb, alpha: 0)
+ if let g2 = CGGradient(colorsSpace: cs, colors: [ic2, oc2] as CFArray, locations: [0, 1]) {
+ ctx.saveGState()
+ ctx.addEllipse(in: CGRect(x: cx-R2, y: cy-R2, width: R2*2, height: R2*2))
+ ctx.clip()
+ ctx.drawRadialGradient(g2, startCenter: CGPoint(x: cx, y: cy), startRadius: 0,
+ endCenter: CGPoint(x: cx, y: cy), endRadius: R2, options: [])
+ ctx.restoreGState()
+ }
+ }
+
+ ctx.saveGState()
+ ctx.translateBy(x: CGFloat(p.x), y: CGFloat(p.y))
+ ctx.rotate(by: CGFloat(p.tilt))
+ ctx.scaleBy(x: CGFloat(p.sx), y: CGFloat(p.sy))
+
+ // Hands behind body
+ drawHandL(ctx, hw: hw, hh: hh, p: p)
+ drawHandR(ctx, hw: hw, hh: hh, p: p)
+
+ // Body
+ let mpath = mochiPath(hw: hw, hh: hh)
+ whiteFill(ctx, mpath, x0: hw*0.6, y0: -hh, x1: -hw*0.6, y1: hh)
+
+ // Blue tint overlay
+ if p.tint > 0 {
+ let cs = CGColorSpaceCreateDeviceRGB()
+ let c0 = CGColor(red: 127/255, green: 180/255, blue: 234/255, alpha: CGFloat(p.tint))
+ let c1 = CGColor(red: 127/255, green: 180/255, blue: 234/255, alpha: 0)
+ if let g = CGGradient(colorsSpace: cs, colors: [c0,c1] as CFArray, locations: [0,1]) {
+ ctx.saveGState()
+ ctx.addPath(mpath); ctx.clip()
+ ctx.drawLinearGradient(g, start: CGPoint(x: 0, y: hh), end: CGPoint(x: 0, y: -hh*0.1), options: [])
+ ctx.restoreGState()
+ }
+ }
+
+ // Eyes (clipped to body)
+ ctx.saveGState()
+ ctx.addPath(mpath); ctx.clip()
+ ctx.setFillColor(gHex("#16171A"))
+ ctx.setStrokeColor(gHex("#16171A"))
+ let er = CGFloat(p.hb*0.06)
+ let sp = CGFloat(p.hb*0.19)
+ let lx = CGFloat(p.lookX)*hw*0.42
+ let ly = CGFloat(p.lookY)*hh*0.28 + hh*0.12 + CGFloat(p.eyeRoll)*hh*1.25
+ for sd: CGFloat in [-1, 1] {
+ ctx.saveGState()
+ ctx.translateBy(x: sd*sp+lx, y: ly)
+ if p.eye == .happy {
+ ctx.setLineWidth(er*0.95)
+ ctx.setLineCap(.round)
+ ctx.beginPath()
+ ctx.addArc(center: CGPoint(x: 0, y: er*0.6), radius: er*1.25,
+ startAngle: .pi*1.15, endAngle: .pi*1.85, clockwise: false)
+ ctx.strokePath()
+ } else if p.eye == .content {
+ ctx.setLineWidth(er*0.95)
+ ctx.setLineCap(.round)
+ ctx.beginPath()
+ ctx.addArc(center: CGPoint(x: 0, y: -er*0.5), radius: er*1.25,
+ startAngle: .pi*0.15, endAngle: .pi*0.85, clockwise: false)
+ ctx.strokePath()
+ } else {
+ ctx.scaleBy(x: 1, y: max(0.12, CGFloat(p.open)))
+ ctx.addEllipse(in: CGRect(x: -er, y: -er, width: er*2, height: er*2))
+ ctx.fillPath()
+ }
+ ctx.restoreGState()
+ }
+ ctx.restoreGState()
+
+ // Activity badge (top-left corner)
+ if p.badge > 0.01 {
+ let bs = CGFloat(p.badge)
+ let br = hh*0.3
+ ctx.saveGState()
+ ctx.translateBy(x: -hw*0.78, y: -hh*0.72)
+ ctx.scaleBy(x: bs, y: bs)
+ ctx.setFillColor(gHex("#000000"))
+ ctx.addEllipse(in: CGRect(x: -(br+hh*0.07), y: -(br+hh*0.07),
+ width: (br+hh*0.07)*2, height: (br+hh*0.07)*2))
+ ctx.fillPath()
+ ctx.setFillColor(gHex("#3BA0F5"))
+ ctx.addEllipse(in: CGRect(x: -br, y: -br, width: br*2, height: br*2)); ctx.fillPath()
+ ctx.setFillColor(gHex("#0B1B3A"))
+ for i: CGFloat in [-1, 0, 1] {
+ ctx.addEllipse(in: CGRect(x: i*br*0.5-br*0.17, y: -br*0.17, width: br*0.34, height: br*0.34))
+ ctx.fillPath()
+ }
+ ctx.restoreGState()
+ }
+
+ ctx.restoreGState()
+}
+
+private func drawParticles(_ ctx: CGContext, t: Double, tc: Double, p: GreetPose) {
+ guard p.card > 0 || p.fx < 1 else { return }
+ let fx = p.fx
+ // RINGS
+ for ring in greetParticles.rings {
+ let k = gSeg(t, ring.t0, ring.t0 + 1.35)
+ guard k > 0 && k < 1 else { continue }
+ let rx = gLerpF(14, 380, CGFloat(GE.out(k)))
+ let ry = rx * 0.34
+ let fade = CGFloat((1-k) * (k < 0.08 ? k/0.08 : 1) * fx * p.card)
+ for dot in ring.dots {
+ let r: CGFloat = 1 + CGFloat(dot.j)
+ ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: CGFloat(dot.al)*fade))
+ let dx = CGFloat(GC0.x) + cos(CGFloat(dot.a))*rx*r
+ let dy = CGFloat(GC0.y) + sin(CGFloat(dot.a))*ry*r
+ ctx.fill(CGRect(x: dx, y: dy, width: CGFloat(dot.s), height: CGFloat(dot.s)))
+ }
+ }
+ // STREAKS
+ for s in greetParticles.streaks {
+ let k = gSeg(t, s.t0, s.t0 + 0.6)
+ guard k > 0 && k < 1 else { continue }
+ let dist = CGFloat(s.sp * GE.out(k) * 0.9 + 10)
+ let alpha = CGFloat((1-k) * fx)
+ ctx.setStrokeColor(gHex(s.col, alpha: alpha))
+ ctx.setLineWidth(1.6); ctx.setLineCap(.round)
+ let a = CGFloat(s.a)
+ ctx.beginPath()
+ ctx.move(to: CGPoint(x: CGFloat(GC0.x)+cos(a)*(dist-CGFloat(s.len)),
+ y: CGFloat(GC0.y)+sin(a)*(dist-CGFloat(s.len))*0.42))
+ ctx.addLine(to: CGPoint(x: CGFloat(GC0.x)+cos(a)*dist,
+ y: CGFloat(GC0.y)+sin(a)*dist*0.42))
+ ctx.strokePath()
+ }
+}
+
+private func drawHeader(_ ctx: CGContext, alpha: Double) {
+ guard alpha > 0 else { return }
+ ctx.saveGState()
+ ctx.setAlpha(CGFloat(alpha))
+ // VS Code icon pill (top-left)
+ gRR(ctx, 18, 4, 44, 26, 13)
+ ctx.setFillColor(gHex("#1D1F23")); ctx.fillPath()
+ ctx.setFillColor(gHex("#F5F6F8"))
+ // Simple chevron-up shape
+ ctx.beginPath()
+ ctx.move(to: CGPoint(x: 33, y: 20)); ctx.addLine(to: CGPoint(x: 40, y: 13))
+ ctx.addLine(to: CGPoint(x: 47, y: 20)); ctx.addLine(to: CGPoint(x: 47, y: 25))
+ ctx.addLine(to: CGPoint(x: 33, y: 25)); ctx.closePath(); ctx.fillPath()
+ // Two dots (circles) top-right
+ ctx.setFillColor(gHex("#8E939C"))
+ ctx.addEllipse(in: CGRect(x: 75.5, y: 10.5, width: 13, height: 13)); ctx.fillPath()
+ ctx.addEllipse(in: CGRect(x: 572, y: 11, width: 12, height: 12)); ctx.fillPath()
+ ctx.setFillColor(gHex("#000000"))
+ ctx.addEllipse(in: CGRect(x: 575.6, y: 14.6, width: 4.8, height: 4.8)); ctx.fillPath()
+ ctx.restoreGState()
+}
+
+private let miniColors = ["#E86A6A","#3E86E0","#EFAE5A","#8C73F2"]
+
+private func drawMinis(_ ctx: CGContext, alpha: Double) {
+ guard alpha > 0.01 else { return }
+ let cx = 320 + GSMALL_W/2 - 27
+ let cy: CGFloat = 16
+ let sp: CGFloat = 6
+ let offsets: [(CGFloat, CGFloat)] = [(-sp,-sp),(sp,-sp),(-sp,sp),(sp,sp)]
+ for (i,(dx,dy)) in offsets.enumerated() {
+ ctx.saveGState()
+ ctx.translateBy(x: cx+dx, y: cy+dy)
+ ctx.scaleBy(x: CGFloat(alpha), y: CGFloat(alpha))
+ ctx.setFillColor(gHex(miniColors[i]))
+ ctx.addPath(mochiPath(hw: 5.3, hh: 4)); ctx.fillPath()
+ ctx.restoreGState()
+ }
+}
+
+// MARK: - Full draw function
+
+private func drawGreeting(_ ctx: CGContext, size: CGSize, t: Double, tc: Double) {
+ let p = pose(t, tc: tc)
+
+ // Card background (dark panel)
+ if p.card > 0 {
+ ctx.saveGState()
+ ctx.setAlpha(CGFloat(p.card))
+ gRR(ctx, GCARD.minX, GCARD.minY, GCARD.width, GCARD.height, GCARD_R)
+ ctx.setFillColor(gHex("#141518")); ctx.fillPath()
+ ctx.restoreGState()
+
+ // Particles inside card area
+ ctx.saveGState()
+ gRR(ctx, GCARD.minX, GCARD.minY, GCARD.width, GCARD.height, GCARD_R)
+ ctx.clip()
+ drawParticles(ctx, t: t, tc: tc, p: p)
+ ctx.restoreGState()
+ } else if tc.isFinite && t >= tc {
+ // During collapse, fade particles without card clip
+ ctx.saveGState()
+ drawParticles(ctx, t: t, tc: tc, p: p)
+ ctx.restoreGState()
+ }
+
+ // drawHeader: no icons during greeting
+ drawMinis(ctx, alpha: p.minis)
+ drawMochi(ctx, p: p)
+}
+
+// MARK: - SwiftUI View
+
+struct GreetingCanvasView: View {
+ @ObservedObject var state: AppState
+
+ @State private var startDate = Date()
+ @State private var tc: Double = .infinity // collapses only when FSM fires .greetingInterrupt
+ @State private var greetFired = false
+
+ // Scheduled works (cancellable)
+ @State private var soundWork1: DispatchWorkItem? = nil
+ @State private var soundWork2: DispatchWorkItem? = nil
+ @State private var doneWork: DispatchWorkItem? = nil
+
+ var body: some View {
+ TimelineView(.animation) { timeline in
+ let t = timeline.date.timeIntervalSince(startDate)
+ Canvas { context, size in
+ context.withCGContext { cgCtx in
+ drawGreeting(cgCtx, size: size, t: t, tc: tc)
+ }
+ }
+ // Fire greetComplete exactly once at T.end (when no hover)
+ .onChange(of: !greetFired && t >= GT.end && tc >= GT.autoLeave) { _, trigger in
+ if trigger { fireGreetComplete() }
+ }
+ }
+ .onAppear {
+ startDate = Date()
+ tc = .infinity
+ greetFired = false
+ scheduleWorks()
+ }
+ .onDisappear {
+ cancelWorks()
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .greetingHover)) { _ in
+ // Mouse on notch during greeting → hold open (no auto-collapse)
+ if tc >= GT.autoLeave { tc = .infinity }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .greetingInterrupt)) { _ in
+ // Mouse left during greeting → start collapse from current time
+ let t = Date().timeIntervalSince(startDate)
+ if tc.isInfinite || tc > t { tc = t }
+ cancelWorks() // cancel auto-done timer (FSM already went to .petit)
+ }
+ }
+
+ private func fireGreetComplete() {
+ guard !greetFired else { return }
+ greetFired = true
+ cancelWorks()
+ NotificationCenter.default.post(name: .greetComplete, object: nil)
+ }
+
+ private func scheduleWorks() {
+ func schedule(_ delay: Double, _ block: @escaping () -> Void) -> DispatchWorkItem {
+ let item = DispatchWorkItem(block: block)
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
+ return item
+ }
+ soundWork1 = schedule(GT.pop0) { SoundEngine.shared.play("greet") }
+ soundWork2 = schedule(GT.badge) { SoundEngine.shared.play("blip") }
+ // doneWork is a safety fallback; normal path fires via .onChange
+ doneWork = schedule(GT.end + 0.05) { fireGreetComplete() }
+ }
+
+ private func cancelWorks() {
+ soundWork1?.cancel(); soundWork1 = nil
+ soundWork2?.cancel(); soundWork2 = nil
+ doneWork?.cancel(); doneWork = nil
+ }
+}
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
new file mode 100644
index 00000000..b79a37e1
--- /dev/null
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -0,0 +1,614 @@
+import Foundation
+import Darwin
+import AppKit
+
+// MARK: - HookServer
+// Listens on a Unix domain socket for events from nb-hook (Claude Code hooks).
+// Thread-safe: socket I/O on background threads, state updates dispatched to main queue.
+
+final class HookServer: @unchecked Sendable {
+ static let shared = HookServer()
+
+ // Support directory paths
+ static var supportDir: URL {
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("NotchBuddy")
+ }
+ static var socketPath: String { supportDir.appendingPathComponent("nb.sock").path }
+ static var hookScriptPath: String { supportDir.appendingPathComponent("nb-hook").path }
+
+ // No approval blocking state — notch is notification-only, user answers in VS Code
+
+ private var serverFD: Int32 = -1
+ private var pendingApprovalFD: Int32 = -1 // held open while user decides
+ private var activeSessionId: String? = nil // current Claude Code session
+
+ private init() {}
+
+ // MARK: - Start
+
+ func start() {
+ installHookScript()
+ Thread.detachNewThread { self.serverThread() }
+ }
+
+ // MARK: - Socket server (background thread)
+
+ private func serverThread() {
+ let path = Self.socketPath
+ try? FileManager.default.removeItem(atPath: path)
+
+ let fd = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard fd >= 0 else { return }
+ serverFD = fd
+
+ var addr = sockaddr_un()
+ addr.sun_family = sa_family_t(AF_UNIX)
+ let cpath = Array(path.utf8CString)
+ withUnsafeMutableBytes(of: &addr.sun_path) { raw in
+ for (i, c) in cpath.enumerated() where i < raw.count { raw[i] = UInt8(bitPattern: c) }
+ }
+
+ let bindRC = withUnsafePointer(to: &addr) { ptr in
+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.bind(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
+ }
+ guard bindRC == 0 else { close(fd); return }
+ guard Darwin.listen(fd, 10) == 0 else { close(fd); return }
+
+ while true {
+ let clientFD = Darwin.accept(fd, nil, nil)
+ guard clientFD >= 0 else { break }
+ Thread.detachNewThread { self.handleClient(fd: clientFD) }
+ }
+ }
+
+ // MARK: - Client handler (background thread)
+
+ private func handleClient(fd: Int32) {
+ // Read newline-delimited JSON
+ var raw = Data()
+ var buf = [UInt8](repeating: 0, count: 4096)
+ outer: while true {
+ let n = recv(fd, &buf, buf.count, 0)
+ if n <= 0 { break }
+ for i in 0..<n {
+ if buf[i] == UInt8(ascii: "\n") { break outer }
+ raw.append(buf[i])
+ }
+ }
+
+ guard !raw.isEmpty,
+ let payload = try? JSONSerialization.jsonObject(with: raw) as? [String: Any] else {
+ sendLine(fd: fd, text: #"{"ok":true}"#)
+ close(fd)
+ return
+ }
+
+ let eventName = payload["hook_event_name"] as? String ?? ""
+
+ if eventName == "PermissionRequest" {
+ // Hold fd open — Claude Code waits for our decision (up to 120s)
+ Task { @MainActor in self.processPermissionRequest(fd: fd, payload: payload) }
+ } else {
+ Task { @MainActor in self.processEvent(name: eventName, payload: payload) }
+ sendLine(fd: fd, text: #"{"ok":true}"#)
+ close(fd)
+ }
+ }
+
+
+ // MARK: - Event → AppState
+ // All Claude Code events route to the permanent "integration_claude" task.
+ // View switches only happen if VS Code is the currently focused mochi.
+ // When not focused: state updates animate the mini bot in the pill; badge shown for alerts.
+
+ @MainActor
+ private func processEvent(name: String, payload: [String: Any]) {
+ let state = AppState.shared
+ let sessionId = payload["session_id"] as? String ?? "unknown"
+ let cwd = payload["cwd"] as? String ?? ""
+ let rawName = URL(fileURLWithPath: cwd).lastPathComponent
+ let projectName = aliasProjectName(rawName.isEmpty ? "Session" : rawName)
+
+ let termProgram = payload["term_program"] as? String ?? ""
+ let bundleId = payload["bundle_id"] as? String ?? ""
+ let isVSCode = termProgram.lowercased().contains("vscode") ||
+ bundleId.lowercased().contains("vscode")
+ guard isVSCode else {
+ nbLog("Ignored \(name) from \(termProgram.isEmpty ? bundleId : termProgram) (\(projectName))")
+ return
+ }
+
+ let focused = state.focusId == "integration_claude"
+
+ switch name {
+
+ case "SessionStart":
+ activeSessionId = sessionId
+ upsertTask(projectName: projectName, cwd: cwd)
+ nbLog("SessionStart \(projectName) (\(sessionId.prefix(8)))")
+ if state.isPresent { expandIfNeeded(to: .overview) }
+ SoundEngine.shared.play("work")
+
+ case "UserPromptSubmit":
+ activeSessionId = sessionId
+ upsertTask(projectName: projectName, cwd: cwd)
+ state.updateTask(id: "integration_claude", state: .thinking)
+ if let message = payload["message"] as? String, !message.isEmpty {
+ appendStep(id: "integration_claude", step: String(message.prefix(60)))
+ }
+ if state.isPresent { expandIfNeeded(to: .overview) }
+
+ case "PreToolUse":
+ activeSessionId = sessionId
+ upsertTask(projectName: projectName, cwd: cwd)
+ state.updateTask(id: "integration_claude", state: .working)
+ let tool = payload["tool_name"] as? String ?? "Tool"
+ let input = payload["tool_input"] as? [String: Any] ?? [:]
+ let step = frenchStep(tool: tool, input: input)
+ appendStep(id: "integration_claude", step: step)
+ nbLog("PreToolUse \(step)")
+
+ case "PostToolUse":
+ state.updateTask(id: "integration_claude", state: .working)
+
+ case "PostToolUseFailure":
+ state.updateTask(id: "integration_claude", state: .working)
+ appendStep(id: "integration_claude", step: "⚠ failed")
+
+ case "Notification":
+ let message = payload["message"] as? String ?? ""
+ let lower = message.lowercased()
+ if lower.contains("rate limit") || lower.contains("limite d") {
+ state.updateTask(id: "integration_claude", state: .ratelimit)
+ SoundEngine.shared.play("rate")
+ } else if message.hasSuffix("?") {
+ state.updateTask(id: "integration_claude", state: .question)
+ appendStep(id: "integration_claude", step: message)
+ }
+
+ case "Stop":
+ state.updateTask(id: "integration_claude", state: .finished)
+ if let message = payload["message"] as? String, !message.isEmpty {
+ appendStep(id: "integration_claude", step: String(message.prefix(60)))
+ }
+ SoundEngine.shared.play("finish")
+ if focused {
+ expandIfNeeded(to: .finished)
+ } else {
+ setPillBadge(id: "integration_claude", badge: .finished)
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5.2) {
+ state.updateTask(id: "integration_claude", state: .idle)
+ self.clearPillBadge(id: "integration_claude")
+ }
+
+ case "StopFailure":
+ state.updateTask(id: "integration_claude", state: .error)
+ SoundEngine.shared.play("error")
+ if focused {
+ expandIfNeeded(to: .error)
+ } else {
+ setPillBadge(id: "integration_claude", badge: .error)
+ }
+
+ case "SessionEnd":
+ activeSessionId = nil
+ state.updateTask(id: "integration_claude", state: .idle)
+ clearSession()
+
+ case "SubagentStart":
+ appendStep(id: "integration_claude", step: "+ subagent")
+
+ case "SubagentStop":
+ appendStep(id: "integration_claude", step: "• subagent done")
+
+ default:
+ break
+ }
+ }
+
+ // MARK: - Helpers
+
+ @MainActor
+ private func expandIfNeeded(to view: IslandView) {
+ let state = AppState.shared
+ let isAlert: Bool
+ switch view {
+ case .approval, .finished, .error, .confused: isAlert = true
+ default: isAlert = false
+ }
+ if state.mode == .expanded {
+ // Only force-switch view for alerts — leave user on their current view otherwise
+ if isAlert { state.view = view }
+ } else if isAlert {
+ // Alerts always force-expand
+ NotificationCenter.default.post(name: .hookExpand, object: view)
+ } else if state.mode == .hidden {
+ // Non-alert work events: reveal compact only, never force-expand
+ NotificationCenter.default.post(name: .hookReveal, object: nil)
+ }
+ // Already compact and non-alert: Mochi state update is enough, no expand
+ }
+
+ // MARK: - Permission request (blocking — Claude Code waits for decision)
+
+ @MainActor
+ private func processPermissionRequest(fd: Int32, payload: [String: Any]) {
+ let state = AppState.shared
+ let sessionId = payload["session_id"] as? String ?? "unknown"
+ let cwd = payload["cwd"] as? String ?? ""
+ let rawName = URL(fileURLWithPath: cwd).lastPathComponent
+ let projectName = aliasProjectName(rawName.isEmpty ? "Session" : rawName)
+
+ let termProgram = payload["term_program"] as? String ?? ""
+ let bundleId = payload["bundle_id"] as? String ?? ""
+ let isVSCode = termProgram.lowercased().contains("vscode") ||
+ bundleId.lowercased().contains("vscode")
+ guard isVSCode else {
+ Task.detached { [weak self] in
+ self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
+ close(fd)
+ }
+ return
+ }
+
+ let tool = payload["tool_name"] as? String ?? "Tool"
+ var command = tool
+ if let input = payload["tool_input"] as? [String: Any] {
+ command = input["command"] as? String ?? tool
+ }
+ nbLog("PermissionRequest \(tool): \(command)")
+
+ if pendingApprovalFD >= 0 {
+ let old = pendingApprovalFD
+ Task.detached { [weak self] in
+ self?.sendLine(fd: old, text: #"{"permissionDecision":"deny"}"#)
+ close(old)
+ }
+ }
+ pendingApprovalFD = fd
+ activeSessionId = sessionId
+
+ upsertTask(projectName: projectName, cwd: cwd)
+ state.updateTask(id: "integration_claude", state: .approval)
+ state.pendingApproval = ApprovalInfo(sessionId: sessionId, tool: tool, command: command)
+ state.isPinned = true
+ SoundEngine.shared.play("approval")
+
+ let focused = state.focusId == "integration_claude"
+ if focused {
+ expandIfNeeded(to: .approval)
+ } else {
+ setPillBadge(id: "integration_claude", badge: .approval)
+ }
+
+ let captured = fd
+ DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
+ guard let self, self.pendingApprovalFD == captured else { return }
+ self.sendApprovalDecision("deny")
+ }
+ }
+
+ /// Called by ApprovalView buttons. Writes the decision to the waiting nb-hook and cleans up.
+ @MainActor
+ func sendApprovalDecision(_ decision: String) {
+ let fd = pendingApprovalFD
+ pendingApprovalFD = -1
+
+ let json: String
+ switch decision {
+ case "allow": json = #"{"permissionDecision":"allow"}"#
+ case "always": json = #"{"permissionDecision":"allow","alwaysAllow":true}"#
+ default: json = #"{"permissionDecision":"deny"}"#
+ }
+
+ if fd >= 0 {
+ Task.detached { [weak self] in
+ self?.sendLine(fd: fd, text: json)
+ close(fd)
+ }
+ }
+
+ let state = AppState.shared
+ if decision == "always" { state.alwaysAllow = true }
+ state.pendingApproval = nil
+ state.isPinned = false
+ state.updateTask(id: "integration_claude", state: .working)
+ clearPillBadge(id: "integration_claude")
+ state.view = state.tasks.isEmpty ? .empty : .overview
+ }
+
+ /// Updates integration_claude with the current session project name and cwd.
+ @MainActor
+ private func upsertTask(projectName: String, cwd: String = "") {
+ let state = AppState.shared
+ guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_claude" }) else { return }
+ state.tasks[idx].name = projectName
+ if !cwd.isEmpty { state.tasks[idx].sessionCwd = cwd }
+ }
+
+ // MARK: - Badge helpers
+
+ @MainActor
+ private func setPillBadge(id: String, badge: PillBadge) {
+ let state = AppState.shared
+ guard let idx = state.tasks.firstIndex(where: { $0.id == id }) else { return }
+ state.tasks[idx].pillBadge = badge
+ }
+
+ @MainActor
+ private func clearPillBadge(id: String) {
+ let state = AppState.shared
+ guard let idx = state.tasks.firstIndex(where: { $0.id == id }) else { return }
+ state.tasks[idx].pillBadge = nil
+ }
+
+ /// Resets integration_claude to idle, clears steps and project name.
+ @MainActor
+ private func clearSession() {
+ let state = AppState.shared
+ guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_claude" }) else { return }
+ state.tasks[idx].steps = []
+ state.tasks[idx].stepIndex = 0
+ state.tasks[idx].name = "VS Code"
+ state.tasks[idx].pillBadge = nil
+ }
+
+ @MainActor
+ private func appendStep(id: String, step: String) {
+ let state = AppState.shared
+ guard let idx = state.tasks.firstIndex(where: { $0.id == id }) else { return }
+ state.tasks[idx].steps.append(step)
+ if state.tasks[idx].steps.count > 20 { state.tasks[idx].steps.removeFirst() }
+ state.tasks[idx].stepIndex = state.tasks[idx].steps.count - 1
+ }
+
+ // MARK: - Project name alias mapping
+
+ private func aliasProjectName(_ name: String) -> String {
+ let aliases: [String: String] = [
+ "notch-buddy": "Notch Buddy",
+ "notchbuddy": "Notch Buddy",
+ "notch_buddy": "Notch Buddy",
+ ]
+ return aliases[name.lowercased()] ?? name
+ }
+
+ // MARK: - French step labels
+
+ private func frenchStep(tool: String, input: [String: Any]) -> String {
+ let labels: [String: String] = [
+ "Bash": "Exécute",
+ "Read": "Lit",
+ "Write": "Écrit",
+ "Edit": "Modifie",
+ "Glob": "Cherche",
+ "Grep": "Recherche",
+ "WebSearch": "Recherche web",
+ "WebFetch": "Récupère",
+ "TodoWrite": "Tâches",
+ "Task": "Agent",
+ "LS": "Liste",
+ "MultiEdit": "Modifie",
+ "NotebookEdit": "Notebook",
+ ]
+ let label = labels[tool] ?? tool
+ if let cmd = input["command"] as? String {
+ let short = String(cmd.prefix(40))
+ return "\(label) · \(short)"
+ } else if let path = input["path"] as? String {
+ return "\(label) · \(URL(fileURLWithPath: path).lastPathComponent)"
+ } else if let file = input["file_path"] as? String {
+ return "\(label) · \(URL(fileURLWithPath: file).lastPathComponent)"
+ } else if let query = input["query"] as? String {
+ return "\(label) · \(String(query.prefix(40)))"
+ }
+ return label
+ }
+
+ // MARK: - Logging
+
+ private func nbLog(_ message: String) {
+ let logsDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Logs/NotchBuddy")
+ try? FileManager.default.createDirectory(at: logsDir, withIntermediateDirectories: true)
+ let logFile = logsDir.appendingPathComponent("nb.log")
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
+ let line = "\(formatter.string(from: Date())) \(message)\n"
+ guard let data = line.data(using: .utf8) else { return }
+ if FileManager.default.fileExists(atPath: logFile.path) {
+ if let handle = try? FileHandle(forWritingTo: logFile) {
+ handle.seekToEndOfFile()
+ handle.write(data)
+ try? handle.close()
+ }
+ } else {
+ try? data.write(to: logFile)
+ }
+ }
+
+ private func sendLine(fd: Int32, text: String) {
+ var bytes = Array((text + "\n").utf8)
+ var sent = 0
+ while sent < bytes.count {
+ let n = Darwin.send(fd, &bytes[sent], bytes.count - sent, 0)
+ if n <= 0 { break }
+ sent += n
+ }
+ }
+
+ // MARK: - nb-hook script installation
+
+ func installHookScript() {
+ let dir = Self.supportDir
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let scriptURL = URL(fileURLWithPath: Self.hookScriptPath)
+ let script = nbHookScript
+ try? script.write(to: scriptURL, atomically: true, encoding: .utf8)
+ _ = try? FileManager.default.setAttributes(
+ [.posixPermissions: 0o755 as NSNumber],
+ ofItemAtPath: scriptURL.path
+ )
+ }
+
+ // MARK: - Claude Code settings.json hook installer
+
+ private var _pendingHooksData: Data?
+
+ /// Returns preview JSON without writing — call writeClaudeHooks() to confirm.
+ func previewClaudeHooks() throws -> String {
+ let data = try buildHooksData()
+ _pendingHooksData = data
+ return String(data: data, encoding: .utf8) ?? ""
+ }
+
+ /// Writes the hooks to disk (call after user confirms preview).
+ func writeClaudeHooks() throws {
+ guard let data = _pendingHooksData else { return }
+ let settingsURL = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".claude/settings.json")
+ // Backup first
+ let formatter = DateFormatter()
+ formatter.dateFormat = "yyyyMMdd-HHmm"
+ let stamp = formatter.string(from: Date())
+ let backupURL = settingsURL.deletingLastPathComponent()
+ .appendingPathComponent("settings.json.bak-\(stamp)")
+ try? FileManager.default.copyItem(at: settingsURL, to: backupURL)
+ try? FileManager.default.createDirectory(at: settingsURL.deletingLastPathComponent(),
+ withIntermediateDirectories: true)
+ try data.write(to: settingsURL, options: .atomic)
+ _pendingHooksData = nil
+ }
+
+ private func buildHooksData() throws -> Data {
+ let settingsURL = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".claude/settings.json")
+ var settings: [String: Any] = [:]
+ if let data = try? Data(contentsOf: settingsURL),
+ let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
+ settings = parsed
+ }
+ let hookPath = Self.hookScriptPath
+ let events: [(String, Int)] = [
+ ("SessionStart", 10), ("SessionEnd", 10),
+ ("UserPromptSubmit", 10),
+ ("PreToolUse", 10), ("PostToolUse", 10), ("PostToolUseFailure", 10),
+ ("PermissionRequest", 10),
+ ("Notification", 10),
+ ("Stop", 10), ("StopFailure", 10),
+ ("SubagentStart", 10), ("SubagentStop", 10),
+ ]
+ var hooks = settings["hooks"] as? [String: Any] ?? [:]
+ for (event, timeout) in events {
+ var existing = hooks[event] as? [[String: Any]] ?? []
+ existing.removeAll { ($0["hooks"] as? [[String: Any]])?.contains { ($0["command"] as? String)?.contains("NotchBuddy") == true } ?? false }
+ let quotedPath = "\"\(hookPath.replacingOccurrences(of: "\"", with: "\\\""))\""
+ existing.append(["hooks": [["type": "command", "command": quotedPath, "timeout": timeout]]])
+ hooks[event] = existing
+ }
+ settings["hooks"] = hooks
+ return try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])
+ }
+
+ func uninstallClaudeHooks() throws {
+ let settingsURL = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".claude/settings.json")
+ guard let data = try? Data(contentsOf: settingsURL),
+ var settings = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ var hooks = settings["hooks"] as? [String: Any] else { return }
+
+ for key in hooks.keys {
+ if var matchers = hooks[key] as? [[String: Any]] {
+ matchers.removeAll { matcher in
+ (matcher["hooks"] as? [[String: Any]])?.contains { ($0["command"] as? String)?.contains("NotchBuddy") == true } ?? false
+ }
+ if matchers.isEmpty { hooks.removeValue(forKey: key) }
+ else { hooks[key] = matchers }
+ }
+ }
+ settings["hooks"] = hooks
+ let newData = try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])
+ try newData.write(to: settingsURL, options: .atomic)
+ }
+}
+
+// MARK: - Notification names for hook server → controller communication
+
+extension Notification.Name {
+ static let hookExpand = Notification.Name("notchBuddy.hookExpand")
+}
+
+// MARK: - nb-hook Python script content
+
+private let nbHookScript = """
+#!/usr/bin/env python3
+# nb-hook — Notch Buddy hook relay for Claude Code
+# Reads JSON from stdin, forwards to NotchBuddy via Unix socket, relays response.
+import sys, json, os, socket
+
+def main():
+ try:
+ raw = sys.stdin.buffer.read()
+ if not raw:
+ return
+ payload = json.loads(raw)
+ except Exception:
+ return
+
+ # Enrich with terminal context
+ env = os.environ
+ payload.setdefault('term_program', env.get('TERM_PROGRAM', ''))
+ payload.setdefault('iterm_session_id', env.get('ITERM_SESSION_ID', ''))
+ payload.setdefault('term_session_id', env.get('TERM_SESSION_ID', ''))
+ payload.setdefault('bundle_id', env.get('__CFBundleIdentifier', ''))
+ if 'cwd' not in payload or not payload['cwd']:
+ payload['cwd'] = os.getcwd()
+
+ event = payload.get('hook_event_name', '')
+ socket_path = os.path.expanduser(
+ '~/Library/Application Support/NotchBuddy/nb.sock'
+ )
+
+ if event == 'PermissionRequest':
+ # Block and wait for NotchBuddy's decision (Claude Code allows up to 120s)
+ try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.settimeout(118)
+ s.connect(socket_path)
+ s.sendall((json.dumps(payload) + '\\n').encode())
+ chunks = []
+ while True:
+ chunk = s.recv(4096)
+ if not chunk:
+ break
+ chunks.append(chunk)
+ if b'\\n' in chunk:
+ break
+ s.close()
+ response = b''.join(chunks).decode().strip()
+ if response and 'permissionDecision' in response:
+ sys.stdout.write(response + '\\n')
+ sys.stdout.flush()
+ sys.exit(0)
+ except Exception:
+ pass
+ # Fallback: deny if NotchBuddy unreachable or timeout
+ sys.stdout.write('{"permissionDecision":"deny"}\\n')
+ sys.stdout.flush()
+ sys.exit(0)
+
+ # All other events: fire-and-forget (0.3s timeout, never blocks)
+ try:
+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ s.settimeout(0.3)
+ s.connect(socket_path)
+ s.sendall((json.dumps(payload) + '\\n').encode())
+ s.close()
+ except Exception:
+ pass # Always exit cleanly — never block Claude Code
+
+main()
+sys.exit(0)
+"""
diff --git a/NotchBuddy/Sources/App/IslandRootView.swift b/NotchBuddy/Sources/App/IslandRootView.swift
new file mode 100644
index 00000000..a4dbdf9c
--- /dev/null
+++ b/NotchBuddy/Sources/App/IslandRootView.swift
@@ -0,0 +1,567 @@
+import SwiftUI
+
+/// Top-level SwiftUI view rendered inside the 720×320 transparent panel.
+/// The island is drawn at the top-center; everything else is transparent and click-through.
+/// Note: drag-drop is handled at the AppKit level in IslandWindowController (FileDropNSView),
+/// not in SwiftUI, to avoid interfering with SwiftUI hit-testing.
+struct IslandRootView: View {
+ @EnvironmentObject var state: AppState
+
+ var body: some View {
+ ZStack(alignment: .top) {
+ Color.clear
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ IslandContainer(state: state)
+ .frame(maxWidth: .infinity, alignment: .center)
+ }
+ .ignoresSafeArea()
+ }
+}
+
+// MARK: - Island container
+
+struct IslandContainer: View {
+ @ObservedObject var state: AppState
+ @State private var islandWidth: CGFloat = IslandConst.notchWidth
+ @State private var islandHeight: CGFloat = IslandConst.notchHeight
+ @State private var cornerRadius: CGFloat = IslandConst.roundedCorner
+ // topRadius > 0 → convex expanded corners; < 0 → concave ear cutouts
+ @State private var islandTopRadius: CGFloat = 0
+ @State private var greetNotif: Bool = false
+
+ private let openSpring = Animation.spring(response: 0.5, dampingFraction: 0.72)
+ private let closeEase = Animation.timingCurve(0.45, 0, 0.2, 1, duration: 0.34)
+
+ private var chatPromptHeight: CGFloat {
+ let base: CGFloat = 240
+ let perMsg: CGFloat = 40
+ return min(300, base + CGFloat(state.chatHistory.count) * perMsg)
+ }
+
+ /// Pixels the content must be pushed down to clear the concave ear transparent area.
+ /// = 0 in expanded mode (no ears), = earRadius in compact/notch mode.
+ private var earOffset: CGFloat { max(0, -islandTopRadius) }
+
+ var body: some View {
+ // Canvas active during drag-over (.upload), post-drop animation (.uploading),
+ // AND choose overlay (.choose) — canvas handles the full sequence through user action.
+ // Engine deactivates when user clicks a canvas choose button or navigates away.
+ let uploadActive = state.mode == .expanded
+ && UploadSequenceEngine.shared.isActive
+ && (state.view == .upload || state.view == .uploading || state.view == .choose)
+
+ let greetingActive = state.mode == .expanded && state.view == .greeting
+
+ return ZStack(alignment: .topLeading) {
+ // Black island shape
+ IslandShape(width: islandWidth, height: islandHeight,
+ cornerRadius: cornerRadius, topRadius: islandTopRadius)
+ .fill(Color.black)
+
+ // Content
+ if state.mode == .expanded {
+ if greetingActive {
+ // Greeting canvas: fixed 640-wide, centered by offset so x=320 aligns with island center
+ GreetingCanvasView(state: state)
+ .frame(width: IslandConst.expandedWidth, height: 150)
+ .offset(x: (islandWidth - IslandConst.expandedWidth) / 2)
+ .clipShape(IslandShape(width: islandWidth, height: islandHeight,
+ cornerRadius: cornerRadius, topRadius: islandTopRadius))
+ .transition(.opacity)
+ } else if uploadActive {
+ ZStack(alignment: .topLeading) {
+ UploadCanvasView(state: state)
+ .frame(width: islandWidth, height: islandHeight)
+ .clipShape(IslandShape(width: islandWidth, height: islandHeight,
+ cornerRadius: cornerRadius, topRadius: islandTopRadius))
+ // Header overlaid: canvas CARD_Y=42 aligns exactly with header bottom,
+ // matching normal view proportions (8pt top + 34pt header + card + 10pt bottom).
+ IslandHeader(state: state)
+ .frame(width: islandWidth, height: 34)
+ .offset(y: 8)
+ }
+ .transition(.opacity)
+ } else {
+ IslandContentView(state: state)
+ .frame(width: islandWidth, height: islandHeight - earOffset)
+ .offset(y: earOffset)
+ .clipShape(IslandShape(width: islandWidth, height: islandHeight,
+ cornerRadius: cornerRadius, topRadius: islandTopRadius))
+ .transition(.opacity)
+ }
+ }
+
+ // Single BotPlacement — always alive in the view tree so spring animations
+ // fire from the current position (e.g. choose at 60,101) when canvas deactivates.
+ // Hidden during upload canvas or greeting (both draw their own Mochi).
+ BotPlacement(state: state, islandW: islandWidth, islandH: islandHeight)
+ .opacity(uploadActive || greetingActive ? 0 : 1)
+ .animation(.easeInOut(duration: 0.25), value: uploadActive || greetingActive)
+
+ CountdownBar(state: state, islandW: islandWidth)
+
+ Group {
+ if state.mode == .compact {
+ CompactMiniGrid(state: state)
+ .position(x: islandWidth - 40, y: islandHeight / 2)
+ .transition(.opacity)
+ }
+ }
+ .animation(.easeInOut(duration: 0.25), value: state.mode == .compact)
+ }
+ .frame(width: islandWidth, height: islandHeight, alignment: .topLeading)
+ .onChange(of: state.mode) { oldMode, newMode in
+ let shrinking = modeOrder(newMode) < modeOrder(oldMode)
+ let anim = shrinking ? closeEase : openSpring
+ let (w, h) = islandSize(mode: newMode, view: state.view,
+ progress: state.uploadProgress,
+ nw: state.notchWidth, nh: state.notchHeight)
+ let cr = newMode == .expanded ? IslandConst.expandedCorner : IslandConst.roundedCorner
+ let tr: CGFloat = 0
+ withAnimation(anim) {
+ islandWidth = w
+ islandHeight = (newMode == .expanded && state.view == .prompt) ? chatPromptHeight : h
+ cornerRadius = cr
+ islandTopRadius = tr
+ }
+ }
+ .onChange(of: state.view) { _, newView in
+ guard state.mode == .expanded else { return }
+ // Deactivate engine if user navigates outside the upload flow
+ let uploadViews: Set<IslandView> = [.upload, .uploading, .choose]
+ if UploadSequenceEngine.shared.isActive && !uploadViews.contains(newView) {
+ UploadSequenceEngine.shared.deactivate()
+ }
+ let (w, h) = islandSize(mode: .expanded, view: newView,
+ progress: state.uploadProgress,
+ nw: state.notchWidth, nh: state.notchHeight)
+ withAnimation(openSpring) {
+ islandWidth = w
+ islandHeight = newView == .prompt ? chatPromptHeight : h
+ }
+ }
+ .onChange(of: state.chatHistory.count) { _, _ in
+ guard state.mode == .expanded, state.view == .prompt else { return }
+ withAnimation(openSpring) { islandHeight = chatPromptHeight }
+ }
+ .onAppear {
+ let (w, h) = islandSize(mode: state.mode, view: state.view,
+ progress: state.uploadProgress,
+ nw: state.notchWidth, nh: state.notchHeight)
+ islandWidth = w
+ islandHeight = state.view == .prompt ? chatPromptHeight : h
+ cornerRadius = state.mode == .expanded ? IslandConst.expandedCorner : IslandConst.roundedCorner
+ islandTopRadius = 0
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .botGreet)) { _ in
+ greetNotif.toggle()
+ }
+ }
+
+ private func modeOrder(_ m: IslandMode) -> Int {
+ switch m { case .hidden: return 0; case .compact: return 1; case .expanded: return 2 }
+ }
+}
+
+// MARK: - Island shape
+//
+// topRadius > 0 → convex rounded top corners (expanded mode)
+// topRadius < 0 → concave ear cutouts, |topRadius| = ear radius (compact/notch mode)
+// topRadius = 0 → sharp top corners (transient during animation)
+
+struct IslandShape: Shape {
+ var width: CGFloat
+ var height: CGFloat
+ var cornerRadius: CGFloat // bottom corners
+ var topRadius: CGFloat // see above
+
+ var animatableData: AnimatablePair<AnimatablePair<AnimatablePair<CGFloat, CGFloat>, CGFloat>, CGFloat> {
+ get { .init(.init(.init(width, height), cornerRadius), topRadius) }
+ set {
+ width = newValue.first.first.first
+ height = newValue.first.first.second
+ cornerRadius = newValue.first.second
+ topRadius = newValue.second
+ }
+ }
+
+ func path(in rect: CGRect) -> Path {
+ let cr = max(0, cornerRadius)
+ var p = Path()
+
+ if topRadius >= 0 {
+ // ── Convex rounded top corners (expanded) ──────────────────────────
+ let tr = min(topRadius, min(width / 2, height / 2))
+ p.move(to: CGPoint(x: tr, y: 0))
+ p.addLine(to: CGPoint(x: width - tr, y: 0))
+ // Top-right convex corner
+ p.addArc(center: CGPoint(x: width - tr, y: tr), radius: tr,
+ startAngle: .degrees(270), endAngle: .degrees(0), clockwise: false)
+ // Right edge
+ p.addLine(to: CGPoint(x: width, y: height - cr))
+ // Bottom-right corner
+ p.addArc(center: CGPoint(x: width - cr, y: height - cr), radius: cr,
+ startAngle: .degrees(0), endAngle: .degrees(90), clockwise: false)
+ // Bottom edge
+ p.addLine(to: CGPoint(x: cr, y: height))
+ // Bottom-left corner
+ p.addArc(center: CGPoint(x: cr, y: height - cr), radius: cr,
+ startAngle: .degrees(90), endAngle: .degrees(180), clockwise: false)
+ // Left edge
+ p.addLine(to: CGPoint(x: 0, y: tr))
+ // Top-left convex corner
+ p.addArc(center: CGPoint(x: tr, y: tr), radius: tr,
+ startAngle: .degrees(180), endAngle: .degrees(270), clockwise: false)
+ } else {
+ // ── Concave ear cutouts (compact / notch) ─────────────────────────
+ let er = -topRadius // positive ear radius
+ p.move(to: CGPoint(x: 0, y: 0))
+ // Top-left ear
+ p.addArc(center: CGPoint(x: 0, y: er), radius: er,
+ startAngle: .degrees(270), endAngle: .degrees(0), clockwise: false)
+ // Top edge
+ p.addLine(to: CGPoint(x: width - er, y: er))
+ // Top-right ear
+ p.addArc(center: CGPoint(x: width, y: er), radius: er,
+ startAngle: .degrees(180), endAngle: .degrees(270), clockwise: false)
+ // Right edge
+ p.addLine(to: CGPoint(x: width, y: height - cr))
+ // Bottom-right corner
+ p.addArc(center: CGPoint(x: width - cr, y: height - cr), radius: cr,
+ startAngle: .degrees(0), endAngle: .degrees(90), clockwise: false)
+ // Bottom edge
+ p.addLine(to: CGPoint(x: cr, y: height))
+ // Bottom-left corner
+ p.addArc(center: CGPoint(x: cr, y: height - cr), radius: cr,
+ startAngle: .degrees(90), endAngle: .degrees(180), clockwise: false)
+ // Left edge back to top-left corner
+ p.addLine(to: CGPoint(x: 0, y: 0))
+ }
+
+ p.closeSubpath()
+ return p
+ }
+}
+
+// MARK: - Bot placement helper
+
+struct BotPlacement: View {
+ @ObservedObject var state: AppState
+ let islandW: CGFloat
+ let islandH: CGFloat
+
+ var body: some View {
+ let (cx, cy, diameter, opacity) = botPosition(mode: state.mode, view: state.view, islandW: islandW, islandH: islandH, uploadProgress: state.uploadProgress)
+ let canvasSize = diameter / 0.6
+ let overhang: CGFloat = 40
+ let isUploading = state.view == .uploading
+
+ Group {
+ // No glow in uploading mode — the tiny dot doesn't need it
+ if state.mode == .expanded && !isUploading {
+ Circle()
+ .fill(RadialGradient(
+ gradient: Gradient(stops: [
+ .init(color: botGlowColor(state.effectiveState), location: 0),
+ .init(color: .clear, location: 0.62)
+ ]),
+ center: .center,
+ startRadius: 0,
+ endRadius: diameter * 1.1
+ ))
+ .frame(width: diameter * 2.2, height: diameter * 2.2)
+ .blur(radius: 6)
+ .opacity(botGlowOpacity(state.effectiveState))
+ .position(x: cx, y: cy)
+ .animation(.easeInOut(duration: 0.4), value: state.effectiveState)
+ }
+
+ // Uploading: no particle overhang (no hearts during upload), positioned directly at cy.
+ // BotEngine cy = H/2 + 0 + oy*R + R*0.06 ≈ H/2 (body centered in canvas).
+ // With .position(x:y:) placing the frame center at (uploadCx, cy), bot is at cy ✓.
+ //
+ // Normal: extra 40pt canvas at top for heart particles; position offset up by 20pt;
+ // BotEngine compensates with cy = H/2 + particleOverhang/2 + oy*R + R*0.06.
+ if isUploading {
+ TimelineView(.animation) { tl in
+ let elapsed: Double = {
+ guard let start = state.uploadStartTime else { return 0 }
+ return tl.date.timeIntervalSince(start)
+ }()
+ let t = min(1.0, max(0, elapsed / state.uploadDuration))
+ // cx = 36 + 526*t: bot center at fill right edge (bar left=36, width=526)
+ let uploadCx = 36 + CGFloat(t * (2 - t)) * 526
+ BotCanvasView(state: state, particleOverhang: 0)
+ .frame(width: canvasSize, height: canvasSize)
+ .opacity(state.isDraggingBot ? 0 : opacity)
+ .position(x: uploadCx, y: cy)
+ }
+ .transition(.scale(scale: 0.01, anchor: .center).combined(with: .opacity))
+ } else {
+ BotCanvasView(state: state, particleOverhang: overhang)
+ .frame(width: canvasSize, height: canvasSize + overhang)
+ .opacity(state.isDraggingBot ? 0 : opacity)
+ .position(x: cx, y: cy - overhang / 2)
+ .animation(.spring(response: 0.5, dampingFraction: 0.72), value: cx)
+ .animation(.spring(response: 0.5, dampingFraction: 0.72), value: cy)
+ .animation(.spring(response: 0.5, dampingFraction: 0.72), value: canvasSize)
+ .transition(.scale(scale: 0.01, anchor: .center).combined(with: .opacity))
+ }
+ }
+ // Branch switch (uploading ↔ normal) animates with a fast spring: uploading dot
+ // scales out at bar-end while normal bot scales in at choose position.
+ .animation(.spring(response: 0.36, dampingFraction: 0.72), value: isUploading)
+ // Slap, drag, and hover are handled by the AppKit NSEvent monitor in
+ // IslandWindowController — not SwiftUI gestures — so this is safe.
+ .allowsHitTesting(false)
+ }
+
+ private func botGlowColor(_ s: BotState) -> Color {
+ switch s {
+ case .working: return Color(hex: "#3B9EFF")
+ case .thinking: return Color(hex: "#A78BFA")
+ case .searching: return Color(hex: "#6366F1")
+ case .approval: return Color(hex: "#F5A524")
+ case .error: return Color(hex: "#F4505E")
+ case .finished: return Color(hex: "#34D399")
+ case .ratelimit: return Color(hex: "#F59E0B")
+ default: return Color.white
+ }
+ }
+
+ private func botGlowOpacity(_ s: BotState) -> Double {
+ switch s {
+ case .idle, .sleeping: return 0.15
+ case .dizzy: return 0.0
+ default: return 0.65
+ }
+ }
+}
+
+func botPosition(mode: IslandMode, view: IslandView, islandW: CGFloat, islandH: CGFloat, uploadProgress: Double) -> (CGFloat, CGFloat, CGFloat, Double) {
+ switch mode {
+ case .hidden: return (46, 16, 6, 0)
+ case .compact: return (40, 16, 20, 1)
+ case .expanded:
+ let layout = IslandConst.viewLayouts[view]!
+ let diameter = layout.botDiameter
+ // Uploading: Mochi dot rides the leading edge of the progress fill.
+ // Bar in island coords: left=36, width=526. cx = 36 + progress*526 (dot center at fill right edge).
+ // cy comes from ViewLayout.botY (bar center in island coords).
+ if view == .uploading {
+ let cx = 36 + CGFloat(uploadProgress) * 526
+ return (cx, layout.botY ?? 103, diameter, 1)
+ }
+ let cx = layout.botX
+ let cy: CGFloat
+ if let fixedY = layout.botY {
+ cy = fixedY
+ } else {
+ // Center of the fixed 84pt card (VStack top=8, header=34 → content starts at y=42)
+ let headerBottom: CGFloat = 42
+ let cardH: CGFloat = 84
+ cy = headerBottom + (islandH - headerBottom - cardH) / 2 + cardH / 2
+ }
+ return (cx, cy, diameter, 1)
+ }
+}
+
+// MARK: - Countdown bar
+
+struct CountdownBar: View {
+ @ObservedObject var state: AppState
+ let islandW: CGFloat
+ @State private var barWidth: CGFloat = 0
+ @State private var timer: Timer? = nil
+
+ var body: some View {
+ GeometryReader { _ in
+ Rectangle()
+ .fill(Color.white.opacity(0.35))
+ .frame(width: barWidth, height: 2)
+ .cornerRadius(2)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
+ }
+ .onAppear { startTimer() }
+ .onDisappear { timer?.invalidate() }
+ }
+
+ private func startTimer() {
+ timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
+ updateBar()
+ }
+ }
+
+ private func updateBar() {
+ guard state.mode == .expanded && !state.isPinned else {
+ barWidth = 0
+ return
+ }
+ let autoClose = state.autoCloseInterval
+ let window = min(10.0, autoClose * 0.6)
+ let elapsed = Date.now.timeIntervalSince(state.lastActivity)
+ let remaining = autoClose - elapsed
+ if remaining < window {
+ barWidth = max(0, CGFloat(remaining / window) * 160)
+ } else {
+ barWidth = 0
+ }
+ }
+}
+
+// MARK: - Island content (header + views, only in expanded mode)
+
+struct IslandContentView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ VStack(spacing: 0) {
+ IslandHeader(state: state)
+ .frame(height: 34)
+ .opacity(state.view == .confused ? 0 : 1)
+ .animation(.easeInOut(duration: 0.2), value: state.view == .confused)
+
+ ZStack {
+ ForEach(IslandView.allCases, id: \.self) { v in
+ let active = state.view == v
+ // Views that fill available height instead of the fixed 98pt content frame:
+ // chat (prompt) is always flexible; mail is flexible only when active so
+ // it doesn't push the ZStack taller when inactive.
+ let isTall = v == .prompt || (v == .mail && active)
+ let anim: Animation = active
+ ? .spring(response: 0.4, dampingFraction: 0.8).delay(0.16)
+ : .easeIn(duration: 0.16)
+ IslandViewContent(view: v, state: state)
+ .frame(maxWidth: .infinity)
+ .frame(height: isTall ? nil : 98)
+ .frame(maxHeight: isTall ? .infinity : nil)
+ .opacity(active ? 1 : 0)
+ .scaleEffect(active ? 1 : 0.97)
+ .allowsHitTesting(active)
+ .animation(anim, value: state.view)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .padding(.horizontal, 10)
+ }
+ .padding(.top, 8)
+ .padding(.bottom, 10)
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ }
+}
+
+// MARK: - Island header (tabs + icons)
+
+struct IslandHeader: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ HStack(spacing: 0) {
+ // Left: tab capsules
+ HStack(spacing: 5) {
+ TabButton(icon: "house.fill", view: .overview, state: state)
+ TabButton(icon: "bubble.left.fill", view: .prompt, state: state, preAction: {
+ if state.promptContext == nil {
+ state.promptContext = WindowContextCapture.captureActive(from: state.lastExternalApp)
+ }
+ })
+ TabButton(icon: "plus", view: .upload, state: state)
+ }
+ .padding(.leading, 14)
+
+ Spacer()
+
+ // Right: action icons
+ HStack(spacing: 14) {
+ Button(action: {
+ withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
+ state.view = .settings
+ }
+ }) {
+ Image(systemName: state.view == .settings ? "gearshape.fill" : "gearshape")
+ .font(.system(size: 14))
+ .foregroundColor(state.view == .settings ? Color(hex: "#F5F6F8") : Color(hex: "#8E939C"))
+ }
+ .buttonStyle(.plain)
+
+ Button(action: { state.soundEnabled.toggle() }) {
+ Image(systemName: state.soundEnabled ? "speaker.wave.2" : "speaker.slash")
+ .font(.system(size: 14))
+ .foregroundColor(Color(hex: "#8E939C"))
+ }
+ .buttonStyle(.plain)
+ }
+ .padding(.trailing, 16)
+ }
+ .frame(maxHeight: .infinity)
+ }
+}
+
+struct TabButton: View {
+ let icon: String
+ let view: IslandView
+ @ObservedObject var state: AppState
+ var preAction: (() -> Void)? = nil
+ @State private var isHovered = false
+
+ private var isOn: Bool {
+ if view == .overview { return state.view == .overview || state.view == .empty }
+ return state.view == view
+ }
+
+ var body: some View {
+ Button(action: {
+ preAction?()
+ withAnimation(.spring(response: 0.3, dampingFraction: 0.8)) {
+ state.view = view
+ }
+ }) {
+ Image(systemName: icon)
+ .font(.system(size: 13))
+ .foregroundColor(isOn ? Color(hex: "#F5F6F8") : (isHovered ? Color(hex: "#B0B5BE") : Color(hex: "#8E939C")))
+ .frame(width: 30, height: 22)
+ .background(
+ isOn ? Color(hex: "#1D1F23") :
+ isHovered ? Color.white.opacity(0.07) : Color.clear
+ )
+ .clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .onHover { isHovered = $0 }
+ }
+}
+
+// MARK: - Compact mini mochi grid (2×2 to the right of the notch)
+
+struct CompactMiniGrid: View {
+ @ObservedObject var state: AppState
+
+ private var others: [AgentTask] {
+ Array(state.tasks.filter { $0.id != state.focusId }.prefix(4))
+ }
+
+ var body: some View {
+ let cols = [GridItem(.fixed(12), spacing: 4), GridItem(.fixed(12), spacing: 4)]
+ LazyVGrid(columns: cols, spacing: 4) {
+ ForEach(others) { task in
+ MiniBotCanvasView(task: task)
+ .frame(width: 12 / 0.6, height: 12 / 0.6)
+ .frame(width: 12, height: 12, alignment: .center)
+ }
+ }
+ .frame(width: 28, height: 28)
+ }
+}
+
+// MARK: - Color helper
+
+extension Color {
+ init(hex: String) {
+ let h = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
+ let val = UInt64(h, radix: 16) ?? 0
+ let r = Double((val >> 16) & 0xFF) / 255
+ let g = Double((val >> 8) & 0xFF) / 255
+ let b = Double( val & 0xFF) / 255
+ self.init(red: r, green: g, blue: b)
+ }
+}
diff --git a/NotchBuddy/Sources/App/IslandStateMachine.swift b/NotchBuddy/Sources/App/IslandStateMachine.swift
new file mode 100644
index 00000000..fa937e69
--- /dev/null
+++ b/NotchBuddy/Sources/App/IslandStateMachine.swift
@@ -0,0 +1,145 @@
+import Foundation
+
+/// Pure 4-state FSM for island open/close logic.
+/// No AppKit / AppState dependencies — communicates via `onTransition`.
+@MainActor
+final class IslandStateMachine {
+
+ enum State: Equatable {
+ case hidden // island invisible (notch size)
+ case petit // compact island (notch + ears)
+ case home // expanded, overview
+ case coucou // expanded, greeting animation
+ }
+
+ private(set) var state: State = .hidden
+
+ /// Fired on every transition: (from, to)
+ var onTransition: ((State, State) -> Void)?
+
+ /// home → petit delay (seconds). Override for debug.
+ var homeToPetitDelay: TimeInterval = 15
+ /// petit → hidden delay (seconds). Override for debug.
+ var petitToHiddenDelay: TimeInterval = 60
+ /// coucou → petit delay after greeting animation ends (no hover). ~0.6s syncs with canvas collapse.
+ var greetAutoCollapseDelay: TimeInterval = 0.6
+ /// coucou → petit delay when mouse is hovering over the greeting.
+ var greetHoverCollapseDelay: TimeInterval = 10
+
+ private var petitHideWork: DispatchWorkItem?
+ private var homeCollapseWork: DispatchWorkItem?
+ private var greetCollapseWork: DispatchWorkItem?
+
+ // MARK: – Inputs
+
+ /// App launched or debug "launch greeting"
+ func launch() {
+ cancelTimers()
+ transition(to: .coucou)
+ }
+
+ /// Mouse entered the island notch area
+ func mouseEntered() {
+ switch state {
+ case .hidden:
+ cancelTimers()
+ transition(to: .petit)
+ case .petit:
+ petitHideWork?.cancel()
+ petitHideWork = nil
+ case .home:
+ homeCollapseWork?.cancel()
+ homeCollapseWork = nil
+ case .coucou:
+ // Mouse hovering during greeting — cancel short auto-collapse, extend to hover delay
+ scheduleGreetCollapse(delay: greetHoverCollapseDelay)
+ }
+ }
+
+ /// Mouse left the island notch area
+ func mouseLeft() {
+ switch state {
+ case .hidden:
+ break
+ case .petit:
+ schedulePetitHide()
+ case .home:
+ scheduleHomeCollapse()
+ case .coucou:
+ // Interrupt greeting immediately → compact (overrides 10s auto-collapse)
+ greetCollapseWork?.cancel(); greetCollapseWork = nil
+ transition(to: .petit)
+ }
+ }
+
+ /// Compact island clicked
+ func click() {
+ guard state == .petit else { return }
+ cancelTimers()
+ transition(to: .home)
+ }
+
+ /// Greeting animation finished (called at T.end ≈ 4.60 s).
+ /// Schedules auto-collapse. Does not override a longer hover timer already running.
+ func greetComplete() {
+ guard state == .coucou else { return }
+ // If mouse entered before this fires (hover timer already running), don't override it
+ if greetCollapseWork == nil {
+ scheduleGreetCollapse(delay: greetAutoCollapseDelay)
+ }
+ }
+
+ private func scheduleGreetCollapse(delay: TimeInterval) {
+ greetCollapseWork?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, self.state == .coucou else { return }
+ self.transition(to: .petit)
+ }
+ greetCollapseWork = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
+ }
+
+ /// Non-alert work event: show compact from hidden (HookServer reveal)
+ func reveal() {
+ guard state == .hidden else { return }
+ cancelTimers()
+ transition(to: .petit)
+ schedulePetitHide()
+ }
+
+ // MARK: – Timers
+
+ private func schedulePetitHide() {
+ petitHideWork?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, self.state == .petit else { return }
+ self.transition(to: .hidden)
+ }
+ petitHideWork = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + petitToHiddenDelay, execute: item)
+ }
+
+ private func scheduleHomeCollapse() {
+ homeCollapseWork?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, self.state == .home else { return }
+ self.transition(to: .petit)
+ }
+ homeCollapseWork = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + homeToPetitDelay, execute: item)
+ }
+
+ func cancelTimers() {
+ petitHideWork?.cancel(); petitHideWork = nil
+ homeCollapseWork?.cancel(); homeCollapseWork = nil
+ greetCollapseWork?.cancel(); greetCollapseWork = nil
+ }
+
+ private func transition(to new: State) {
+ guard new != state else { return }
+ let old = state
+ state = new
+ onTransition?(old, new)
+ }
+
+}
diff --git a/NotchBuddy/Sources/App/IslandTypes.swift b/NotchBuddy/Sources/App/IslandTypes.swift
new file mode 100644
index 00000000..8fe91387
--- /dev/null
+++ b/NotchBuddy/Sources/App/IslandTypes.swift
@@ -0,0 +1,164 @@
+import Foundation
+
+// MARK: - Island Mode
+
+enum IslandMode: String, CaseIterable {
+ case hidden, compact, expanded
+}
+
+// MARK: - Island View
+
+enum IslandView: String, CaseIterable {
+ case overview, empty, approval, question, error, finished
+ case confused, upload, uploading, choose, mail, prompt
+ case searching, result, note, settings, greeting
+}
+
+// MARK: - Bot State
+
+enum BotState: String, CaseIterable {
+ case idle, working, thinking, searching
+ case approval, question, error, finished
+ case ratelimit, sleeping, dizzy
+}
+
+// MARK: - Bot Emote
+
+enum BotEmote: String, CaseIterable {
+ case love, surprised, proud, wink, yawn, happy, annoyed
+}
+
+// MARK: - Approval info (pending PermissionRequest from Claude Code)
+
+struct ApprovalInfo: Sendable {
+ var sessionId: String
+ var tool: String
+ var command: String
+}
+
+// MARK: - Pill badge (shown on pill edge when non-focused task has an alert)
+
+enum PillBadge { case approval, finished, error }
+
+// MARK: - Agent Task
+
+struct AgentTask: Identifiable, Equatable {
+ var id: String
+ var name: String
+ var color: String // hex
+ var state: BotState
+ var stepIndex: Int = 0
+ var steps: [String]
+ var source: AgentSource
+ var isIntegration: Bool = false // true for persistent integration pills
+ var emote: BotEmote? = nil
+ var miniEye: EyeShape? = nil
+ var pillBadge: PillBadge? = nil // alert badge shown on pill when not focused
+ var sessionCwd: String? = nil // last known working directory (Claude Code sessions)
+}
+
+enum AgentSource: Equatable {
+ case claudeCode
+ case n8n
+}
+
+// MARK: - View dimensions (from VIEWS in prototype)
+
+struct ViewLayout {
+ let height: CGFloat
+ let botX: CGFloat
+ let botY: CGFloat? // nil = auto-centered
+ let botDiameter: CGFloat
+ let agentMode: AgentLayoutMode
+}
+
+enum AgentLayoutMode {
+ case none, grid, pills, column
+}
+
+// MARK: - Constants (from NW, NH, EW in prototype)
+
+enum IslandConst {
+ static let notchWidth: CGFloat = 184
+ static let notchHeight: CGFloat = 32
+ static let expandedWidth: CGFloat = 640
+ static let earRadius: CGFloat = 14
+ static let roundedCorner: CGFloat = 14 // hidden/peek/compact
+ static let expandedCorner: CGFloat = 22
+
+ static let viewLayouts: [IslandView: ViewLayout] = [
+ // Home is the reference: height 150
+ .overview: ViewLayout(height: 160, botX: 68, botY: nil, botDiameter: 58, agentMode: .pills),
+ // All non-chat views match home height (150) — law
+ .empty: ViewLayout(height: 160, botX: 70, botY: nil, botDiameter: 62, agentMode: .none),
+ .approval: ViewLayout(height: 160, botX: 62, botY: nil, botDiameter: 56, agentMode: .column),
+ .question: ViewLayout(height: 160, botX: 62, botY: nil, botDiameter: 56, agentMode: .column),
+ .error: ViewLayout(height: 160, botX: 62, botY: nil, botDiameter: 58, agentMode: .column),
+ .finished: ViewLayout(height: 160, botX: 62, botY: nil, botDiameter: 58, agentMode: .column),
+ .confused: ViewLayout(height: 160, botX: 76, botY: nil, botDiameter: 66, agentMode: .column),
+ .upload: ViewLayout(height: 176, botX: 140, botY: 104, botDiameter: 62, agentMode: .column),
+ .uploading: ViewLayout(height: 176, botX: 46, botY: 118, botDiameter: 20, agentMode: .none),
+ .choose: ViewLayout(height: 176, botX: 60, botY: 101, botDiameter: 52, agentMode: .column),
+ .mail: ViewLayout(height: 240, botX: 56, botY: nil, botDiameter: 46, agentMode: .column),
+ .prompt: ViewLayout(height: 160, botX: 52, botY: nil, botDiameter: 44, agentMode: .column),
+ .searching: ViewLayout(height: 160, botX: 52, botY: nil, botDiameter: 44, agentMode: .column),
+ .result: ViewLayout(height: 160, botX: 52, botY: nil, botDiameter: 44, agentMode: .column),
+ .note: ViewLayout(height: 160, botX: 60, botY: nil, botDiameter: 50, agentMode: .column),
+ .settings: ViewLayout(height: 160, botX: 54, botY: nil, botDiameter: 46, agentMode: .none),
+ // Greeting: bot drawn by GreetingCanvasView; no BotPlacement needed
+ .greeting: ViewLayout(height: 150, botX: 320, botY: 90, botDiameter: 0, agentMode: .none),
+ ]
+
+ // Project colors — keyed by lowercase display name or slug
+ static let projectColors: [String: String] = [
+ "korus": "#FF5A4E",
+ "sbe hub": "#2EC4A0",
+ "morning ai brief": "#F29B38",
+ "publication ig": "#7C5CFF",
+ "ig post": "#7C5CFF",
+ "louisraille.fr": "#38BDF8",
+ "louisraille": "#38BDF8",
+ "notch buddy": "#EC4899",
+ "notch-buddy": "#EC4899",
+ "notchbuddy": "#EC4899",
+ ]
+
+ static let fallbackColors = ["#22C55E", "#EAB308", "#60A5FA", "#E879F9"]
+
+ // Available integration pills (matches AgentTask.integrationAgents)
+ struct IntegrationMeta {
+ let id: String
+ let name: String
+ let color: String
+ }
+ static let allIntegrations: [IntegrationMeta] = [
+ .init(id: "integration_resend", name: "Resend", color: "#22C55E"),
+ .init(id: "integration_n8n", name: "n8n", color: "#F29B38"),
+ .init(id: "integration_vercel", name: "Vercel", color: "#7C5CFF"),
+ .init(id: "integration_github", name: "GitHub", color: "#F4505E"),
+ .init(id: "integration_notion", name: "Notion", color: "#8C8C8C"),
+ .init(id: "integration_calcom", name: "Cal.com", color: "#C9956A"),
+ .init(id: "integration_stripe", name: "Stripe", color: "#0570DE"),
+ ]
+
+ /// Returns the fixed project color for a display name, or a stable fallback.
+ static func colorForProject(_ name: String) -> String {
+ let key = name.lowercased().trimmingCharacters(in: .whitespaces)
+ if let c = projectColors[key] { return c }
+ // partial match (e.g. "korus-api" → "korus")
+ for (k, c) in projectColors where key.hasPrefix(k) || key.contains(k) { return c }
+ return fallbackColors[abs(name.hashValue) % fallbackColors.count]
+ }
+
+ // State card wash colors (radial gradient from bottom)
+ static let washColors: [IslandView: String] = [
+ .approval: "rgba(245,165,36,0.42)",
+ .question: "rgba(34,211,238,0.38)",
+ .error: "rgba(244,80,94,0.55)",
+ .finished: "rgba(52,211,153,0.5)",
+ .confused: "rgba(244,114,182,0.55)",
+ .searching: "rgba(99,102,241,0.5)",
+ .result: "rgba(52,211,153,0.22)",
+ .prompt: "rgba(99,102,241,0.22)",
+ ]
+}
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
new file mode 100644
index 00000000..1bd462f7
--- /dev/null
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -0,0 +1,2776 @@
+import SwiftUI
+
+// MARK: - Dispatch view content by IslandView
+
+struct IslandViewContent: View {
+ let view: IslandView
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ switch view {
+ case .overview: OverviewView(state: state)
+ case .empty: EmptyStateView(state: state)
+ case .approval: ApprovalView(state: state)
+ case .question: QuestionView(state: state)
+ case .error: ErrorView(state: state)
+ case .finished: FinishedView(state: state)
+ case .confused: ConfusedView()
+ case .upload: UploadView(state: state)
+ case .uploading: UploadingView(state: state)
+ case .choose: ChooseView(state: state)
+ case .mail: MailView(state: state)
+ case .prompt: PromptView(state: state)
+ case .searching: SearchingView(state: state)
+ case .result: ResultView(state: state)
+ case .note: NoteView(state: state)
+ case .settings: SettingsIslandView(state: state)
+ case .greeting: EmptyView() // GreetingCanvasView overlaid in IslandRootView
+ }
+ }
+}
+
+// MARK: - Overview
+
+struct OverviewView: View {
+ @ObservedObject var state: AppState
+ @State private var showingN8nDetail = false
+
+ var agent: AgentTask? { state.focusTask }
+
+ var body: some View {
+ HStack(spacing: 10) {
+ // Left card: title row + ticker below + ↗ button overlay
+ ZStack(alignment: .topLeading) {
+ CardBackground(wash: nil)
+
+ // Title row + ticker stacked (or integration card)
+ if let agent = agent {
+ if agent.isIntegration {
+ IntegrationCardView(task: agent, showingDetail: $showingN8nDetail)
+ } else {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: agent.color))
+ .frame(width: 7, height: 7)
+ Text(agent.name)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .layoutPriority(1)
+ Text(agent.source == .claudeCode ? "Claude Code" : "n8n")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ Spacer(minLength: 2)
+ if agent.steps.count > 1 {
+ Text("\(min(agent.stepIndex + 1, agent.steps.count))/\(agent.steps.count)")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .fixedSize()
+ }
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ TickerView(task: agent)
+ .frame(height: 44)
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ }
+ }
+
+ // ↗ jump button — last in ZStack so it renders on top; hidden while any detail is open
+ if !showingN8nDetail {
+ Button(action: { openAgentTarget(agent) }) {
+ Image(systemName: "arrow.up.right")
+ .font(.system(size: 8, weight: .medium))
+ .foregroundColor(Color(hex: "#5F646D"))
+ .frame(width: 16, height: 16)
+ .background(Color.white.opacity(0.07))
+ .clipShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .padding(.top, 8)
+ .padding(.trailing, 10)
+ .frame(maxWidth: .infinity, alignment: .trailing)
+ }
+ }
+ .frame(width: 322)
+
+ // Right card: agent pills
+ CardBackground(wash: nil) {
+ AgentPillsView(state: state)
+ }
+ }
+ .onChange(of: state.focusId) { _, _ in showingN8nDetail = false }
+ }
+
+ private func openAgentTarget(_ task: AgentTask?) {
+ guard let task else { return }
+ switch task.id {
+ case "integration_claude":
+ let vscodeBundleId = "com.microsoft.VSCode"
+ if let app = NSWorkspace.shared.runningApplications.first(where: { $0.bundleIdentifier == vscodeBundleId }) {
+ app.activate(options: .activateIgnoringOtherApps)
+ } else {
+ NSWorkspace.shared.open(URL(fileURLWithPath: "/Applications/Visual Studio Code.app"))
+ }
+ case "integration_resend":
+ NSWorkspace.shared.open(URL(string: "https://resend.com/emails")!)
+ case "integration_vercel":
+ NSWorkspace.shared.open(URL(string: "https://vercel.com/dashboard")!)
+ case "integration_github":
+ NSWorkspace.shared.open(URL(string: "https://github.com")!)
+ case "integration_n8n":
+ if let urlStr = KeychainStore.shared.get("n8n-url"), let url = URL(string: urlStr) {
+ NSWorkspace.shared.open(url)
+ }
+ case "integration_stripe":
+ NSWorkspace.shared.open(URL(string: "https://dashboard.stripe.com/payments")!)
+ case "integration_notion":
+ NSWorkspace.shared.open(URL(string: "https://notion.so")!)
+ case "integration_calcom":
+ NSWorkspace.shared.open(URL(string: "https://app.cal.com/bookings")!)
+ default:
+ // Non-integration real tasks
+ if task.source == .n8n {
+ if let urlStr = KeychainStore.shared.get("n8n-url"), let url = URL(string: urlStr) {
+ NSWorkspace.shared.open(url)
+ }
+ } else {
+ let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2",
+ "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
+ if let hit = terminalBundleIds.compactMap({ id in
+ NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }
+ }).first {
+ hit.activate(options: .activateIgnoringOtherApps)
+ }
+ }
+ }
+ }
+}
+
+// MARK: - Empty
+
+struct EmptyStateView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack {
+ CardBackground(wash: nil)
+ HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Nothing running right now.")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Drop a file or window, or ask me anything.")
+ .font(.system(size: 13))
+ .foregroundColor(Color(hex: "#9398A1"))
+ }
+ Spacer()
+ PrimaryButton("Ask Claude") {
+ state.view = .prompt
+ }
+ }
+ .padding(.leading, 118)
+ .padding(.trailing, 18)
+ }
+ }
+}
+
+// MARK: - Approval
+
+struct ApprovalView: View {
+ @ObservedObject var state: AppState
+
+ var approval: ApprovalInfo? { state.pendingApproval }
+
+ var body: some View {
+ ZStack {
+ CardBackground(wash: .amber)
+ VStack(alignment: .leading, spacing: 5) {
+ AgentWho(task: state.focusTask, label: "needs permission")
+ CodeBlock(text: approval?.command ?? approval?.tool ?? "…")
+ HStack(spacing: 8) {
+ SecondaryButton("Deny") {
+ HookServer.shared.sendApprovalDecision("deny")
+ }
+ PrimaryButton("Allow") {
+ HookServer.shared.sendApprovalDecision("allow")
+ }
+ if !state.alwaysAllow {
+ SecondaryButton("Always") {
+ HookServer.shared.sendApprovalDecision("always")
+ }
+ }
+ }
+ }
+ .padding(.leading, 116)
+ .padding(.trailing, 16)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+// MARK: - Question
+
+struct QuestionView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack {
+ CardBackground(wash: .cyan)
+ VStack(alignment: .leading, spacing: 5) {
+ AgentWho(task: state.focusTask, label: "Claude Code is asking a question")
+ Text("Which search engine to use?")
+ .font(.system(size: 15, weight: .semibold))
+ HStack(spacing: 8) {
+ ForEach(["Postgres full-text", "Meilisearch", "Algolia"], id: \.self) { opt in
+ SecondaryButton(opt) { /* answer */ }
+ }
+ }
+ }
+ .padding(.leading, 116)
+ .padding(.trailing, 16)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+// MARK: - Error
+
+struct ErrorView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack {
+ CardBackground(wash: .red)
+ VStack(alignment: .leading, spacing: 5) {
+ AgentWho(task: state.focusTask, label: "n8n")
+ Text("Workflow stopped.")
+ .font(.system(size: 15, weight: .semibold))
+ Text("Gmail node timed out after 30s. Retry or open n8n.")
+ .font(.system(size: 12))
+ .foregroundColor(Color(hex: "#FF8D97"))
+ HStack(spacing: 8) {
+ PrimaryButton("Retry") { /* retry */ }
+ SecondaryButton("Open in n8n") { /* open */ }
+ }
+ }
+ .padding(.leading, 116)
+ .padding(.trailing, 16)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+// MARK: - Finished
+
+struct FinishedView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack {
+ CardBackground(wash: .green)
+ VStack(alignment: .leading, spacing: 5) {
+ AgentWho(task: state.focusTask, label: "Claude Code finished")
+ Text(state.focusTask?.steps.last ?? "Session finished")
+ .font(.system(size: 15, weight: .semibold))
+ HStack(spacing: 8) {
+ PrimaryButton("Open terminal") {
+ let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2", "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
+ let activated = terminalBundleIds.compactMap { id in
+ NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }
+ }.first.map { $0.activate(options: .activateIgnoringOtherApps) }
+ if activated == nil {
+ NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app"))
+ }
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+ SecondaryButton("OK") {
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+ }
+ }
+ .padding(.leading, 116)
+ .padding(.trailing, 16)
+ .padding(.vertical, 4)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+// MARK: - Confused
+
+struct ConfusedView: View {
+ var body: some View {
+ ZStack {
+ CardBackground(wash: .pink)
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Too many hits at once.").font(.system(size: 15, weight: .semibold))
+ Text("Give me a sec — back to work in three seconds.")
+ .font(.system(size: 13)).foregroundColor(Color(hex: "#9398A1"))
+ }
+ .padding(.leading, 128)
+ .padding(.trailing, 18)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+}
+
+// MARK: - Upload (drop zone)
+
+struct UploadView: View {
+ @ObservedObject var state: AppState
+ @State private var dashPhase: CGFloat = 0
+ @State private var breathAngle: Double = 0
+ // Timer only runs while this is the active tab — killed on deactivation
+ @State private var animTimer: Timer? = nil
+
+ private var borderOpacity: Double {
+ let breathe = 0.11 + 0.04 * (sin(breathAngle) * 0.5 + 0.5)
+ return state.fileDragOver ? 0.65 : breathe
+ }
+
+ var body: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 20)
+ .fill(Color(hex: "#0E0F11"))
+ RoundedRectangle(cornerRadius: 20)
+ .stroke(
+ state.fileDragOver
+ ? Color(hex: "#22C55E").opacity(borderOpacity)
+ : Color.white.opacity(borderOpacity),
+ style: StrokeStyle(lineWidth: 1.5, dash: [6, 5], dashPhase: dashPhase)
+ )
+ RoundedRectangle(cornerRadius: 20)
+ .fill(RadialGradient(
+ colors: [Color(hex: "#22C55E").opacity(state.fileDragOver ? 0.13 : 0), Color.clear],
+ center: .bottom, startRadius: 0, endRadius: 200
+ ))
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Drop your files here")
+ .font(.system(size: 13, weight: .medium))
+ .foregroundColor(state.fileDragOver ? Color(hex: "#34D399") : Color(hex: "#D5D7DB"))
+ HStack(spacing: 6) {
+ ForEach(["PDF", "Images", "Code", "Docs"], id: \.self) { label in
+ Text(label)
+ .font(.system(size: 11))
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(Color.white.opacity(0.07))
+ .foregroundColor(Color(hex: "#B9BDC4"))
+ .clipShape(Capsule())
+ }
+ }
+ }
+ .padding(.leading, 196)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .onChange(of: state.view) { _, newView in
+ newView == .upload ? startTimer() : stopTimer()
+ }
+ .onAppear {
+ if state.view == .upload { startTimer() }
+ }
+ .onDisappear { stopTimer() }
+ }
+
+ private func startTimer() {
+ guard animTimer == nil else { return }
+ // 20 fps — smooth enough for slow dash, 3× lighter than 60fps
+ animTimer = Timer.scheduledTimer(withTimeInterval: 1.0/20.0, repeats: true) { _ in
+ dashPhase += 1.0 // 20 pt/s march
+ breathAngle += 0.9 / 20.0 // advance sin phase at 0.9 rad/s
+ }
+ }
+
+ private func stopTimer() {
+ animTimer?.invalidate()
+ animTimer = nil
+ }
+}
+
+// MARK: - Uploading
+
+struct UploadingView: View {
+ @ObservedObject var state: AppState
+
+ // Bar geometry in content coords (content has 10pt H padding each side).
+ // Island bar: left=36, right=562 (640-78), width=526.
+ // Content bar: left=26, width=526.
+ // barTop=58 → island y = content_start(42)+58 = 100; bot cy=103 (center = barTop+3).
+ private let barLeft: CGFloat = 26
+ private let barWidth: CGFloat = 526
+ private let barTop: CGFloat = 58
+
+ var body: some View {
+ // TimelineView fires at display refresh rate — progress derived from elapsed wall time,
+ // not from @Published uploadProgress (which only flips to 1.0 at completion).
+ TimelineView(.animation) { tl in
+ let elapsed: Double = {
+ guard let start = state.uploadStartTime else { return 0 }
+ return tl.date.timeIntervalSince(start)
+ }()
+ let t = min(1.0, max(0, elapsed / state.uploadDuration))
+ let progress = CGFloat(t * (2 - t)) // ease-out quad
+ let fillWidth = max(0, barWidth * progress)
+ let isDone = state.uploadProgress >= 0.999 // only true after handle() sets it
+
+ ZStack(alignment: .topLeading) {
+ // Background: dark base
+ RoundedRectangle(cornerRadius: 20)
+ .fill(Color(hex: "#141518"))
+
+ // Permanent green radial wash — brighter at completion
+ RoundedRectangle(cornerRadius: 20)
+ .fill(RadialGradient(
+ colors: [Color(hex: "#34D399").opacity(isDone ? 0.28 : 0.14), Color.clear],
+ center: UnitPoint(x: 0.5, y: 1.4),
+ startRadius: 0,
+ endRadius: 260
+ ))
+
+ // Bar track
+ RoundedRectangle(cornerRadius: 3)
+ .fill(Color.white.opacity(0.09))
+ .frame(width: barWidth, height: 6)
+ .offset(x: barLeft, y: barTop)
+
+ // Bar fill
+ RoundedRectangle(cornerRadius: 3)
+ .fill(LinearGradient(
+ colors: [Color(hex: "#1FA87A"), Color(hex: "#34D399")],
+ startPoint: .leading, endPoint: .trailing
+ ))
+ .frame(width: fillWidth, height: 6)
+ .offset(x: barLeft, y: barTop)
+
+ // Glow trail behind dot leading edge
+ if progress > 0.01 {
+ Ellipse()
+ .fill(Color(hex: "#6EE7B7").opacity(0.45))
+ .frame(width: 28, height: 12)
+ .blur(radius: 5)
+ .offset(x: barLeft + fillWidth - 14, y: barTop - 3)
+ }
+
+ // Text row — filename + % (above bar)
+ HStack(spacing: 0) {
+ if isDone {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 12))
+ .foregroundColor(Color(hex: "#34D399"))
+ Text(" \(state.droppedFile?.name ?? "File")")
+ .font(.system(size: 12.5, weight: .semibold))
+ .foregroundColor(Color(hex: "#34D399"))
+ .lineLimit(1).truncationMode(.middle)
+ } else {
+ Text("Uploading \(state.droppedFile?.name ?? "file")")
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#A9ADB5"))
+ .lineLimit(1).truncationMode(.middle)
+ Spacer(minLength: 8)
+ Text("\(Int(progress * 100)) %")
+ .font(.system(size: 12.5, weight: .medium))
+ .foregroundColor(Color(hex: "#A9ADB5"))
+ .monospacedDigit()
+ }
+ }
+ .frame(width: barWidth)
+ .offset(x: barLeft, y: barTop - 22)
+
+ // Subtle top border (same as CardBackground)
+ RoundedRectangle(cornerRadius: 20)
+ .stroke(Color.white.opacity(0.035), lineWidth: 1)
+ }
+ }
+ }
+}
+
+// MARK: - Choose
+
+struct ChooseView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: nil)
+ VStack(alignment: .leading, spacing: 8) {
+ let fileName = state.droppedFile?.name ?? "file"
+ (Text(fileName).font(.system(size: 14, weight: .semibold)) + Text(" is ready.").font(.system(size: 14, weight: .semibold)))
+ Text("What do you want to do with it?").font(.system(size: 12.5)).foregroundColor(Color(hex: "#9398A1"))
+ HStack(spacing: 8) {
+ PrimaryButton("Ask a question") { state.view = .prompt }
+ SecondaryButton("Send by email") { state.view = .mail }
+ }
+ }
+ .padding(.leading, 98)
+ .padding(.trailing, 18)
+ }
+ }
+}
+
+// MARK: - Mail
+
+struct MailView: View {
+ @ObservedObject var state: AppState
+ @State private var to: String = ""
+ @State private var subject: String = ""
+ @State private var bodyText: String = ""
+ @State private var statusMsg: String = ""
+ @State private var isSending = false
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: nil)
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ Text("New email").font(.system(size: 12, weight: .semibold))
+ if let name = state.droppedFile?.name {
+ Text("with").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
+ Text(name).font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
+ .lineLimit(1).truncationMode(.middle)
+ }
+ }
+
+ MailField(label: "To", placeholder: "[email protected]", text: $to)
+ MailField(label: "Subject", placeholder: state.droppedFile?.name ?? "Subject", text: $subject)
+
+ // Body — TextEditor scrolls internally when text overflows
+ TextEditor(text: $bodyText)
+ .scrollContentBackground(.hidden)
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .frame(height: 44)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(Color.white.opacity(0.06))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+
+ if !statusMsg.isEmpty {
+ Text(statusMsg).font(.system(size: 11)).foregroundColor(Color(hex: "#FF8D97"))
+ }
+
+ HStack(spacing: 8) {
+ PrimaryButton(isSending ? "Sending…" : "Send") {
+ guard !isSending else { return }
+ sendMail()
+ }
+ SecondaryButton("Cancel") { state.view = .choose }
+ }
+ }
+ .padding(.leading, 92)
+ .padding(.trailing, 18)
+ .padding(.vertical, 8)
+ }
+ .onAppear { subject = state.droppedFile?.name ?? "" }
+ }
+
+ private func sendMail() {
+ guard !to.isEmpty else { statusMsg = "Missing recipient."; return }
+ let subj = subject.isEmpty ? (state.droppedFile?.name ?? "File") : subject
+
+ // Prefer Resend if API key + sender address are configured
+ let apiKey = KeychainStore.shared.get("resend-api-key")
+ let fromAddr = KeychainStore.shared.get("resend-from")
+
+ if let apiKey, let fromAddr {
+ isSending = true
+ statusMsg = ""
+ let recipient = to
+ let msgBody = bodyText
+ let fileURL = state.droppedFile?.url
+ Task {
+ let ok = await sendViaResend(apiKey: apiKey, from: fromAddr,
+ to: recipient, subject: subj,
+ body: msgBody, fileURL: fileURL)
+ await MainActor.run {
+ isSending = false
+ if ok { onSuccess(recipient: recipient) }
+ else { statusMsg = "Resend error — check API key & sender." }
+ }
+ }
+ } else if apiKey != nil && fromAddr == nil {
+ // API key set but no sender — guide user instead of silent fallback
+ statusMsg = "Set sender address in Settings."
+ } else {
+ // No Resend — fallback to Apple Mail
+ sendViaAppleMail(to: to, subject: subj)
+ }
+ }
+
+ private func sendViaResend(apiKey: String, from: String, to: String,
+ subject: String, body: String, fileURL: URL?) async -> Bool {
+ guard let url = URL(string: "https://api.resend.com/emails") else { return false }
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+
+ var payload: [String: Any] = [
+ "from": from,
+ "to": [to],
+ "subject": subject,
+ "text": body.isEmpty ? " " : body
+ ]
+ if let fileURL, let data = try? Data(contentsOf: fileURL) {
+ payload["attachments"] = [[
+ "filename": fileURL.lastPathComponent,
+ "content": data.base64EncodedString()
+ ]]
+ }
+ guard let httpBody = try? JSONSerialization.data(withJSONObject: payload) else { return false }
+ request.httpBody = httpBody
+ guard let (data, response) = try? await URLSession.shared.data(for: request) else { return false }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if code == 200 || code == 201 { return true }
+ // Surface Resend error body for debugging
+ if let body = String(data: data, encoding: .utf8) {
+ print("[Resend] HTTP \(code): \(body)")
+ }
+ return false
+ }
+
+ private func sendViaAppleMail(to: String, subject: String) {
+ func asEscape(_ s: String) -> String {
+ s.replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ }
+
+ // Build body as AppleScript expression so newlines survive string boundary
+ let bodyLines = bodyText.isEmpty ? [""] : bodyText.components(separatedBy: "\n")
+ let bodyExpr = bodyLines.map { "\"\(asEscape($0))\"" }.joined(separator: " & linefeed & ")
+ + " & return & return" // trailing newlines ensure there's a paragraph to attach after
+
+ // Verify file exists before referencing it
+ let attachBlock: String
+ if let url = state.droppedFile?.url,
+ FileManager.default.fileExists(atPath: url.path) {
+ let escapedPath = asEscape(url.path)
+ attachBlock = "make new attachment with properties {file name:(POSIX file \"\(escapedPath)\")} at after the last paragraph of content"
+ } else {
+ attachBlock = ""
+ }
+
+ let script = """
+ tell application "Mail"
+ set m to make new outgoing message with properties {subject:"\(asEscape(subject))", visible:false}
+ set content of m to \(bodyExpr)
+ tell m
+ make new to recipient at end of to recipients with properties {address:"\(asEscape(to))"}
+ \(attachBlock)
+ end tell
+ delay 1
+ send m
+ end tell
+ """
+ var err: NSDictionary?
+ NSAppleScript(source: script)?.executeAndReturnError(&err)
+ if err == nil { onSuccess(recipient: to) }
+ else { statusMsg = "Mail error: \(err?["NSAppleScriptErrorMessage"] as? String ?? "unknown")" }
+ }
+
+ private func onSuccess(recipient: String) {
+ SoundEngine.shared.play("send")
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.wink)
+ state.noteMessage = "Email sent to \(recipient)."
+ state.view = .note
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ NotificationCenter.default.post(name: .islandCollapse, object: nil)
+ }
+ }
+}
+
+// MARK: - Prompt (chat)
+
+struct PromptView: View {
+ @ObservedObject var state: AppState
+ @State private var text: String = ""
+ @FocusState private var focused: Bool
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: .indigo)
+
+ VStack(alignment: .leading, spacing: 6) {
+ if let ctx = state.promptContext {
+ ContextChip(context: ctx).padding(.top, 4)
+ }
+
+ if !state.chatHistory.isEmpty {
+ ScrollViewReader { proxy in
+ ScrollView(.vertical, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 6) {
+ ForEach(state.chatHistory) { msg in
+ ChatBubble(message: msg).id(msg.id)
+ }
+ if state.stateOverride != nil {
+ HStack { TypingDotsView(); Spacer(minLength: 32) }
+ .id("typing")
+ }
+ }
+ .padding(.vertical, 2)
+ }
+ .onChange(of: state.chatHistory.count) { _, _ in
+ if let last = state.chatHistory.last {
+ withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
+ }
+ }
+ .onChange(of: state.stateOverride) { _, v in
+ if v != nil { withAnimation { proxy.scrollTo("typing", anchor: .bottom) } }
+ }
+ .onAppear {
+ if let last = state.chatHistory.last {
+ proxy.scrollTo(last.id, anchor: .bottom)
+ }
+ }
+ }
+ .frame(maxHeight: .infinity)
+ } else {
+ Spacer()
+ }
+
+ HStack(spacing: 8) {
+ TextField(state.chatHistory.isEmpty ? "Ask me anything…" : "Continue…", text: $text)
+ .textFieldStyle(.plain)
+ .font(.system(size: 13))
+ .focused($focused)
+ .onSubmit { sendMessage() }
+
+ Button(action: sendMessage) {
+ Image(systemName: "arrow.up")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundColor(Color(hex: "#0B0C0E"))
+ }
+ .buttonStyle(SendButtonStyle())
+ .disabled(text.isEmpty)
+ }
+ .padding(.horizontal, 10).padding(.vertical, 6)
+ .background(Color.white.opacity(0.07))
+ .clipShape(RoundedRectangle(cornerRadius: 12))
+ .simultaneousGesture(TapGesture().onEnded { focused = true })
+ }
+ .padding(.leading, 84)
+ .padding(.trailing, 16)
+ .padding(.top, 12)
+ .padding(.bottom, 14)
+ }
+ .padding(.bottom, 10)
+ .onAppear { focused = true }
+ }
+
+ private func sendMessage() {
+ let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !query.isEmpty else { return }
+ text = ""
+ focused = false
+ state.chatHistory.append(ChatMessage(role: .user, content: query))
+ state.stateOverride = .thinking
+ Task {
+ await ClaudeService.shared.chat(query: query, context: state.promptContext, state: state)
+ await MainActor.run { focused = true }
+ }
+ }
+}
+
+
+struct ChatBubble: View {
+ let message: ChatMessage
+
+ var body: some View {
+ HStack(alignment: .top) {
+ if message.role == .user {
+ Spacer(minLength: 32)
+ Text(message.content)
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#F1F2F4"))
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ .padding(.horizontal, 10).padding(.vertical, 6)
+ .background(Color.white.opacity(0.13))
+ .clipShape(RoundedRectangle(cornerRadius: 12))
+ } else {
+ Text(message.content)
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#B0B5BE"))
+ .fixedSize(horizontal: false, vertical: true)
+ .textSelection(.enabled)
+ Spacer(minLength: 8)
+ }
+ }
+ }
+}
+
+struct TypingDotsView: View {
+ @State private var phase = false
+
+ var body: some View {
+ HStack(spacing: 4) {
+ ForEach(0..<3, id: \.self) { i in
+ Circle()
+ .fill(Color(hex: "#6B7079"))
+ .frame(width: 5, height: 5)
+ .scaleEffect(phase ? 1.2 : 0.6)
+ .animation(
+ .easeInOut(duration: 0.45).repeatForever().delay(Double(i) * 0.14),
+ value: phase
+ )
+ }
+ }
+ .padding(.horizontal, 2).padding(.vertical, 4)
+ .onAppear { phase = true }
+ }
+}
+
+// MARK: - Searching
+
+struct SearchingView: View {
+ @ObservedObject var state: AppState
+
+ var label: String {
+ switch state.promptContext {
+ case .window(_, let title, _): return "Claude is reading \(title)…"
+ case .file(let name, _): return "Claude is reading \(name)…"
+ case nil: return "Claude is searching…"
+ }
+ }
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: .indigo)
+
+ VStack(alignment: .leading, spacing: 8) {
+ if let ctx = state.promptContext {
+ ContextChip(context: ctx)
+ }
+ ShimmeringText(label)
+ .font(.system(size: 13.5))
+ }
+ .padding(.leading, 84)
+ .padding(.trailing, 16)
+ }
+ }
+}
+
+// MARK: - Result
+
+struct ResultView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: .green)
+
+ if let result = state.searchResult {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(result.title)
+ .font(.system(size: 15, weight: .semibold))
+
+ VStack(spacing: 4) {
+ ForEach(result.items.prefix(3), id: \.label) { item in
+ HStack {
+ Text(item.label).font(.system(size: 12.5, weight: .semibold))
+ Spacer()
+ Text(item.detail).font(.system(size: 12.5)).foregroundColor(Color(hex: "#9398A1"))
+ }
+ .padding(.horizontal, 10).padding(.vertical, 6)
+ .background(Color.white.opacity(0.05))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ }
+ }
+
+ if let note = result.note {
+ Text(note).font(.system(size: 11)).foregroundColor(Color(hex: "#6E737C"))
+ }
+
+ HStack(spacing: 8) {
+ PrimaryButton("Open") {
+ if let urlStr = result.items.first?.url, let url = URL(string: urlStr) {
+ NSWorkspace.shared.open(url)
+ }
+ }
+ SecondaryButton("Copy") {
+ let text = result.items.map { "\($0.label): \($0.detail)" }.joined(separator: "\n")
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(text, forType: .string)
+ }
+ SecondaryButton("Close") { state.view = state.tasks.isEmpty ? .empty : .overview }
+ }
+ }
+ .padding(.leading, 84)
+ .padding(.trailing, 16)
+ }
+ }
+ }
+}
+
+// MARK: - Note (short message, auto-closes)
+
+struct NoteView: View {
+ @ObservedObject var state: AppState
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: nil)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(state.noteMessage ?? "")
+ .font(.system(size: 15, weight: .semibold))
+ }
+ .padding(.leading, 98)
+ }
+ }
+}
+
+// MARK: - Integration card (overview left card when an integration pill is focused)
+
+struct IntegrationCardView: View {
+ let task: AgentTask
+ @Binding var showingDetail: Bool
+ @ObservedObject private var appState = AppState.shared
+
+ private var isConfigured: Bool {
+ switch task.id {
+ case "integration_claude":
+ let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude/settings.json")
+ guard let data = try? Data(contentsOf: url),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let hooks = json["hooks"] as? [String: Any],
+ let ss = hooks["SessionStart"] as? [[String: Any]] else { return false }
+ return ss.contains { ($0["hooks"] as? [[String: Any]])?.contains {
+ ($0["command"] as? String)?.contains("NotchBuddy") == true
+ } ?? false }
+ case "integration_resend": return KeychainStore.shared.get("resend-api-key") != nil
+ case "integration_n8n": return KeychainStore.shared.get("n8n-api-key") != nil
+ case "integration_vercel": return KeychainStore.shared.get("vercel-token") != nil
+ case "integration_github": return KeychainStore.shared.get("github-token") != nil
+ case "integration_stripe": return KeychainStore.shared.get("stripe-api-key") != nil
+ case "integration_notion": return KeychainStore.shared.get("notion-api-key") != nil
+ case "integration_calcom": return KeychainStore.shared.get("calcom-api-key") != nil
+ default: return false
+ }
+ }
+
+ private var openURL: URL? {
+ switch task.id {
+ case "integration_claude": return nil // uses terminal button below
+ case "integration_resend": return URL(string: "https://resend.com/emails")
+ case "integration_n8n":
+ if let s = KeychainStore.shared.get("n8n-url") { return URL(string: s) }
+ return nil
+ case "integration_vercel": return URL(string: "https://vercel.com/dashboard")
+ case "integration_github": return URL(string: "https://github.com")
+ case "integration_stripe": return URL(string: "https://dashboard.stripe.com/payments")
+ case "integration_notion": return URL(string: "https://notion.so")
+ case "integration_calcom": return URL(string: "https://app.cal.com/bookings")
+ default: return nil
+ }
+ }
+
+ // VS Code with active session: show ticker layout (same as overview)
+ private var vsCodeSessionActive: Bool {
+ task.id == "integration_claude" && (task.state != .idle || !task.steps.isEmpty)
+ }
+
+ // n8n with a finished execution: show result row instead of "Open n8n" button
+ private var n8nHasActivity: Bool {
+ task.id == "integration_n8n" && !task.steps.isEmpty &&
+ (task.state == .finished || task.state == .error)
+ }
+
+ // Vercel with recent deployments
+ private var vercelHasActivity: Bool {
+ task.id == "integration_vercel" && !appState.vercelDeployments.isEmpty
+ }
+
+ // Resend with recent emails
+ private var resendHasData: Bool {
+ task.id == "integration_resend" && !appState.resendEmails.isEmpty
+ }
+
+ // GitHub with stats loaded
+ private var githubHasData: Bool {
+ task.id == "integration_github" && appState.githubStats != nil
+ }
+
+ // Stripe: show card as soon as first poll completes (balance OR payments)
+ private var stripeHasData: Bool {
+ task.id == "integration_stripe" && appState.stripeLoaded
+ }
+
+ // Cal.com: show calendar as soon as first poll completes
+ private var calcomHasData: Bool {
+ task.id == "integration_calcom" && appState.calcomLoaded
+ }
+
+ // Notion: show pages as soon as first poll completes
+ private var notionHasData: Bool {
+ task.id == "integration_notion" && appState.notionLoaded
+ }
+
+ var body: some View {
+ if showingDetail && n8nHasActivity {
+ N8nDetailView(task: task) {
+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = false }
+ }
+ .transition(.opacity)
+ } else if showingDetail && vercelHasActivity {
+ VercelDetailView(deployment: appState.vercelDeployments[0]) {
+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = false }
+ }
+ .transition(.opacity)
+ } else if vercelHasActivity {
+ VercelDeploymentListView(deployments: appState.vercelDeployments, onOpenDetail: {
+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = true }
+ })
+ .transition(.opacity)
+ } else if resendHasData {
+ ResendCardView(emails: appState.resendEmails, total: appState.resendTotal)
+ .transition(.opacity)
+ } else if githubHasData {
+ GitHubStatsCardView(stats: appState.githubStats!)
+ .transition(.opacity)
+ } else if stripeHasData {
+ StripeCardView()
+ .transition(.opacity)
+ } else if calcomHasData {
+ CalcomCardView()
+ .transition(.opacity)
+ } else if notionHasData {
+ NotionCardView()
+ .transition(.opacity)
+ } else if vsCodeSessionActive {
+ // Active session view — reuse overview layout
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: task.color))
+ .frame(width: 7, height: 7)
+ Text(task.name)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Text("Claude Code")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .lineLimit(1).truncationMode(.tail)
+ Spacer(minLength: 2)
+ if task.steps.count > 1 {
+ Text("\(min(task.stepIndex + 1, task.steps.count))/\(task.steps.count)")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .fixedSize()
+ }
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ TickerView(task: task)
+ .frame(height: 44)
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ } else {
+ // Idle / not connected view — slides in from left when returning from detail
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: task.color))
+ .frame(width: 7, height: 7)
+ Text(task.id == "integration_claude" ? "VS Code" : task.name)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Integration")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ Spacer(minLength: 2)
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ HStack(spacing: 5) {
+ let stripeErr = task.id == "integration_stripe" ? appState.stripeError
+ : task.id == "integration_calcom" ? appState.calcomError
+ : nil
+ let dot = stripeErr != nil ? Color(hex: "#F4505E")
+ : isConfigured ? Color(hex: "#22C55E")
+ : Color(hex: "#F4505E")
+ let label = stripeErr ?? (isConfigured ? "Connected · loading…" : "Key not configured")
+ Circle().fill(dot).frame(width: 5, height: 5)
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ .padding(.leading, 108)
+ .padding(.top, 2)
+
+ HStack(spacing: 8) {
+ if task.id == "integration_claude" {
+ Button("Open Visual Studio Code") { openVSCode() }
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: task.color).opacity(0.7))
+ .buttonStyle(.plain)
+ } else if n8nHasActivity {
+ // Clickable pill — tap to open execution detail
+ let success = task.state == .finished
+ let accent = success ? Color(hex: "#22C55E") : Color(hex: "#F4505E")
+ Button(action: {
+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { showingDetail = true }
+ }) {
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(task.steps.first ?? "Workflow")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail)
+ Image(systemName: "ellipsis")
+ .font(.system(size: 8, weight: .medium))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(accent.opacity(0.1))
+ .clipShape(Capsule())
+ .overlay(Capsule().stroke(accent.opacity(0.22), lineWidth: 1))
+ }
+ .buttonStyle(.plain)
+ } else if let url = openURL {
+ Button("Open \(task.name)") { NSWorkspace.shared.open(url) }
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: task.color).opacity(0.85))
+ .buttonStyle(.plain)
+ }
+ if task.id == "integration_stripe" {
+ if isConfigured {
+ Button("Refresh") { Task { @MainActor in StripePoller.shared.pollNow() } }
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#0570DE").opacity(0.85))
+ .buttonStyle(.plain)
+ }
+ }
+ if task.id == "integration_calcom" && isConfigured {
+ Button("Refresh") { Task { @MainActor in CalcomPoller.shared.pollNow() } }
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#C9956A").opacity(0.85))
+ .buttonStyle(.plain)
+ }
+ if !isConfigured {
+ Button("Settings…") {
+ NotificationCenter.default.post(name: .openFullSettings, object: nil)
+ }
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(.leading, 108)
+ .padding(.top, 2)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ .transition(.opacity)
+ }
+ }
+
+ private func openVSCode() {
+ let ids = ["com.microsoft.VSCode", "com.microsoft.VSCodeInsiders", "com.vscodium.codium"]
+ let appURL = ids.compactMap { NSWorkspace.shared.urlForApplication(withBundleIdentifier: $0) }.first
+
+ // If we have a project folder, open it directly in VS Code
+ if let cwd = task.sessionCwd, !cwd.isEmpty, let appURL = appURL {
+ NSWorkspace.shared.open(
+ [URL(fileURLWithPath: cwd)],
+ withApplicationAt: appURL,
+ configuration: .init(),
+ completionHandler: nil
+ )
+ return
+ }
+
+ // No cwd: activate running instance or launch fresh
+ if let running = ids.compactMap({ id in
+ NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == id }
+ }).first {
+ running.activate(options: .activateIgnoringOtherApps)
+ return
+ }
+ if let appURL = appURL {
+ NSWorkspace.shared.openApplication(at: appURL, configuration: .init(), completionHandler: nil)
+ }
+ }
+}
+
+// MARK: - Vercel Deployment List View
+
+struct VercelDeploymentListView: View {
+ let deployments: [VercelDeployment]
+ let onOpenDetail: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ // Header
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: "#7C5CFF"))
+ .frame(width: 7, height: 7)
+ Text("Vercel")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Deployments")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ // Deployment rows
+ VStack(alignment: .leading, spacing: 3) {
+ // First deployment — highlighted, with detail button
+ if let first = deployments.first {
+ let accent = Color(hex: first.isSuccess ? "#22C55E" : "#F4505E")
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(first.projectName)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Text(first.timeAgo)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ Button(action: onOpenDetail) {
+ Image(systemName: "ellipsis")
+ .font(.system(size: 8, weight: .medium))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .frame(width: 18, height: 18)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(accent.opacity(0.08))
+ .clipShape(RoundedRectangle(cornerRadius: 5))
+ }
+
+ // Remaining deployments — plain rows, identical structure → perfect alignment
+ ForEach(Array(deployments.dropFirst().prefix(2))) { dep in
+ let accent = Color(hex: dep.isSuccess ? "#22C55E" : "#F4505E")
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(dep.projectName)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#9398A1"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Text(dep.timeAgo)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(.top, 5)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ }
+}
+
+// MARK: - Vercel Deployment Detail View
+
+struct VercelDetailView: View {
+ let deployment: VercelDeployment
+ let onClose: () -> Void
+
+ private var accent: Color { Color(hex: deployment.isSuccess ? "#22C55E" : "#F4505E") }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ // Header
+ HStack(spacing: 7) {
+ Button(action: onClose) {
+ Image(systemName: "chevron.left")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .frame(width: 28, height: 28)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+
+ Circle().fill(accent).frame(width: 6, height: 6)
+ Text(deployment.projectName)
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .lineLimit(1).truncationMode(.middle)
+ .layoutPriority(1)
+ Spacer(minLength: 2)
+ Text(deployment.statusLabel)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundColor(accent)
+ .padding(.horizontal, 6).padding(.vertical, 2)
+ .background(accent.opacity(0.14))
+ .clipShape(Capsule())
+ }
+
+ // Details
+ VStack(alignment: .leading, spacing: 4) {
+ if let commit = deployment.commitMessage {
+ Text(commit)
+ .font(.system(size: 10.5))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(2)
+ }
+ HStack(spacing: 8) {
+ if let branch = deployment.branch {
+ Label(branch, systemImage: "arrow.branch")
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ Text(deployment.timeAgo + " ago")
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ Button(action: {
+ if let url = URL(string: "https://\(deployment.url)") {
+ NSWorkspace.shared.open(url)
+ }
+ }) {
+ Text(deployment.url)
+ .font(.system(size: 10, design: .monospaced))
+ .foregroundColor(Color(hex: "#7C5CFF").opacity(0.85))
+ .lineLimit(1).truncationMode(.middle)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(.top, 8)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .contentShape(Rectangle())
+ }
+}
+
+// MARK: - Resend Card View
+
+struct ResendPulseDot: View {
+ @State private var on = false
+ var body: some View {
+ Circle()
+ .fill(Color(hex: "#22C55E"))
+ .frame(width: 4, height: 4)
+ .opacity(on ? 1 : 0.2)
+ .onAppear {
+ withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { on = true }
+ }
+ }
+}
+
+struct ResendCardView: View {
+ let emails: [ResendEmail]
+ let total: Int?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ // Header
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: "#22C55E"))
+ .frame(width: 7, height: 7)
+ Text("Resend")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Emails")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ if let total {
+ ResendPulseDot()
+ Text("\(total)")
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .monospacedDigit()
+ }
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ // Email rows — first is highlighted, rest plain (same structure as Vercel list)
+ VStack(alignment: .leading, spacing: 3) {
+ if let first = emails.first {
+ let accent = Color(hex: first.isDelivered ? "#22C55E" : "#F4505E")
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(first.recipientShort)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Text(first.timeAgo)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ if !first.subject.isEmpty {
+ Text(first.subject)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#4D5159"))
+ .lineLimit(1).truncationMode(.tail)
+ }
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(accent.opacity(0.08))
+ .clipShape(RoundedRectangle(cornerRadius: 5))
+ }
+
+ ForEach(Array(emails.dropFirst().prefix(2))) { email in
+ let accent = Color(hex: email.isDelivered ? "#22C55E" : "#F4505E")
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(email.recipientShort)
+ .font(.system(size: 11, weight: .medium))
+ .foregroundColor(Color(hex: "#9398A1"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Text(email.timeAgo)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(.top, 5)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ }
+}
+
+// MARK: - GitHub Stats Card View
+
+struct GitHubStatsCardView: View {
+ let stats: GitHubStats
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ // Header
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: "#F4505E"))
+ .frame(width: 7, height: 7)
+ Text("GitHub")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Overview")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ // Stats rows
+ VStack(alignment: .leading, spacing: 5) {
+ StatRow(icon: "star.fill", color: "#F5A524",
+ label: "Total stars", value: formatCount(stats.totalStars))
+ StatRow(icon: "square.stack.fill", color: "#6B7079",
+ label: "Repositories", value: "\(stats.totalRepos)")
+ }
+ .padding(.top, 8)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ }
+
+ private func formatCount(_ n: Int) -> String {
+ if n >= 1000 { return String(format: "%.1fk", Double(n) / 1000) }
+ return "\(n)"
+ }
+}
+
+private struct StatRow: View {
+ let icon: String
+ let color: String
+ let label: String
+ let value: String
+
+ var body: some View {
+ HStack(spacing: 7) {
+ Image(systemName: icon)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: color))
+ .frame(width: 14)
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#6B7079"))
+ Spacer()
+ Text(value)
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .monospacedDigit()
+ }
+ .frame(maxWidth: .infinity)
+ }
+}
+
+// MARK: - Stripe Card View
+
+struct StripeCardView: View {
+ @ObservedObject private var appState = AppState.shared
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ // Header
+ HStack(spacing: 6) {
+ Circle()
+ .fill(Color(hex: "#0570DE"))
+ .frame(width: 7, height: 7)
+ Text("Stripe")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Payments")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ }
+ .padding(.top, 6)
+ .padding(.leading, 108)
+ .padding(.trailing, 36)
+
+ // Balance
+ HStack(alignment: .firstTextBaseline, spacing: 3) {
+ Text(balanceFormatted)
+ .font(.system(size: 20, weight: .bold, design: .monospaced))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .contentTransition(.numericText(countsDown: false))
+ .animation(.easeOut(duration: 1.2), value: appState.stripeDisplayBalance)
+ Text(appState.stripeCurrency.uppercased())
+ .font(.system(size: 9, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .padding(.bottom, 1)
+ }
+ .padding(.leading, 108)
+ .padding(.top, 4)
+
+ // Payment rows (animated list)
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(appState.stripePayments) { payment in
+ StripePaymentRow(payment: payment)
+ .transition(.asymmetric(
+ insertion: .move(edge: .top).combined(with: .opacity),
+ removal: .move(edge: .bottom).combined(with: .opacity)
+ ))
+ }
+ }
+ .animation(.spring(response: 0.38, dampingFraction: 0.82),
+ value: appState.stripePayments.map(\.id))
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ .padding(.top, 4)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .padding(.top, 4)
+ }
+
+ private var balanceFormatted: String {
+ String(format: "%.2f", Double(appState.stripeDisplayBalance) / 100.0)
+ }
+}
+
+private struct StripePaymentRow: View {
+ let payment: StripePayment
+
+ var body: some View {
+ let accent = payment.isSuccess ? Color(hex: "#22C55E") : Color(hex: "#F4505E")
+ HStack(spacing: 5) {
+ Circle().fill(accent).frame(width: 5, height: 5)
+ Text(payment.description ?? "Payment")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail)
+ .layoutPriority(1)
+ Spacer(minLength: 4)
+ Text("+\(payment.amountFormatted)")
+ .font(.system(size: 11, weight: .medium, design: .monospaced))
+ .foregroundColor(Color(hex: "#22C55E"))
+ .fixedSize()
+ Text(payment.timeAgo)
+ .font(.system(size: 10))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .fixedSize()
+ }
+ .frame(maxWidth: .infinity)
+ }
+}
+
+// MARK: - Cal.com Card View
+
+struct CalcomCardView: View {
+ @ObservedObject private var appState = AppState.shared
+ @State private var selectedDate: Date? = nil
+ @State private var selectedBooking: CalcomBooking? = nil
+ @State private var displayMonth: Date = Date()
+ @State private var displayHalf: Int = 1 // 1 = first half, 2 = second half
+
+ var body: some View {
+ Group {
+ if let booking = selectedBooking {
+ CalcomBookingDetailView(booking: booking) {
+ withAnimation(.easeOut(duration: 0.2)) { selectedBooking = nil }
+ }
+ } else if let date = selectedDate {
+ CalcomDayView(
+ date: date,
+ bookings: bookingsFor(date),
+ onSelect: { b in withAnimation(.easeOut(duration: 0.2)) { selectedBooking = b } },
+ onBack: { withAnimation(.easeOut(duration: 0.2)) { selectedDate = nil } }
+ )
+ } else {
+ CalcomCalendarView(
+ displayMonth: $displayMonth,
+ displayHalf: $displayHalf,
+ bookings: appState.calcomBookings,
+ onSelect: { d in withAnimation(.easeOut(duration: 0.2)) { selectedDate = d } }
+ )
+ }
+ }
+ .onChange(of: appState.focusId) { _, _ in
+ selectedDate = nil; selectedBooking = nil; displayHalf = 1
+ }
+ }
+
+ private func bookingsFor(_ date: Date) -> [CalcomBooking] {
+ let c = Calendar.current.dateComponents([.year, .month, .day], from: date)
+ let key = "\(c.year!)-\(String(format: "%02d", c.month!))-\(String(format: "%02d", c.day!))"
+ return appState.calcomBookings.filter { $0.dayKey == key }
+ .sorted { $0.startTime < $1.startTime }
+ }
+}
+
+struct CalcomCalendarView: View {
+ @Binding var displayMonth: Date
+ @Binding var displayHalf: Int
+ let bookings: [CalcomBooking]
+ let onSelect: (Date) -> Void
+
+ private let cal = Calendar.current
+
+ private var navLabel: String {
+ let f = DateFormatter(); f.dateFormat = "MMMM yyyy"
+ return "\(f.string(from: displayMonth)) Q\(displayHalf)"
+ }
+
+ // 7 consecutive days per row, day 1 always at far left — no weekday alignment
+ private var allWeeks: [[Date?]] {
+ let comps = cal.dateComponents([.year, .month], from: displayMonth)
+ let monthStart = cal.date(from: comps)!
+ let daysInMonth = cal.range(of: .day, in: .month, for: displayMonth)!.count
+ var result: [[Date?]] = []
+ var chunk: [Date?] = []
+ for i in 0..<daysInMonth {
+ chunk.append(cal.date(byAdding: .day, value: i, to: monthStart)!)
+ if chunk.count == 7 { result.append(chunk); chunk = [] }
+ }
+ if !chunk.isEmpty {
+ while chunk.count < 7 { chunk.append(nil) }
+ result.append(chunk)
+ }
+ return result
+ }
+
+ // Visible weeks for current half
+ private var visibleWeeks: [[Date?]] {
+ let all = allWeeks
+ let splitAt = 2 // always 2 weeks per Q
+ return displayHalf == 1 ? Array(all[0..<splitAt]) : Array(all[splitAt...])
+ }
+
+ private func hasBookings(_ d: Date) -> Bool {
+ let c = cal.dateComponents([.year, .month, .day], from: d)
+ let key = "\(c.year!)-\(String(format: "%02d", c.month!))-\(String(format: "%02d", c.day!))"
+ return bookings.contains { $0.dayKey == key }
+ }
+
+ private func goBack() {
+ if displayHalf == 1 {
+ displayMonth = cal.date(byAdding: .month, value: -1, to: displayMonth) ?? displayMonth
+ displayHalf = 2
+ } else {
+ displayHalf = 1
+ }
+ }
+
+ private func goForward() {
+ if displayHalf == 1 {
+ displayHalf = 2
+ } else {
+ displayMonth = cal.date(byAdding: .month, value: 1, to: displayMonth) ?? displayMonth
+ displayHalf = 1
+ }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#C9956A")).frame(width: 7, height: 7)
+ Text("Cal.com").font(.system(size: 12, weight: .semibold)).foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Schedule").font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C"))
+ }
+ .padding(.top, 6).padding(.leading, 108).padding(.trailing, 36)
+
+ HStack(spacing: 0) {
+ Button { goBack() } label: {
+ Image(systemName: "chevron.left").font(.system(size: 8, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079")).frame(width: 18, height: 16)
+ }.buttonStyle(.plain)
+ Text(navLabel).font(.system(size: 10, weight: .semibold))
+ .foregroundColor(Color(hex: "#C5C8CD")).frame(maxWidth: .infinity)
+ Button { goForward() } label: {
+ Image(systemName: "chevron.right").font(.system(size: 8, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079")).frame(width: 18, height: 16)
+ }.buttonStyle(.plain)
+ }
+ .padding(.leading, 108).padding(.trailing, 12).padding(.top, 2)
+
+ VStack(spacing: 1) {
+ ForEach(visibleWeeks.indices, id: \.self) { i in
+ CalcomWeekRow(week: visibleWeeks[i], hasBookings: hasBookings,
+ isToday: cal.isDateInToday, onSelect: onSelect)
+ }
+ }
+ .padding(.leading, 108).padding(.trailing, 12).padding(.top, 2)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4)
+ .transition(.opacity)
+ }
+}
+
+private struct CalcomWeekRow: View {
+ let week: [Date?]
+ let hasBookings: (Date) -> Bool
+ let isToday: (Date) -> Bool
+ let onSelect: (Date) -> Void
+
+ private var weekLabel: String {
+ guard let first = week.compactMap({ $0 }).first else { return "" }
+ let f = DateFormatter(); f.dateFormat = "dd/MM"
+ return f.string(from: first)
+ }
+
+ var body: some View {
+ HStack(spacing: 0) {
+ Text(weekLabel).font(.system(size: 7)).foregroundColor(Color(hex: "#4B5563"))
+ .frame(width: 26, alignment: .leading)
+ ForEach(0..<7, id: \.self) { i in
+ if let day = week[i] {
+ CalcomDayCell(day: day, hasEvents: hasBookings(day), isToday: isToday(day))
+ .contentShape(Rectangle()).onTapGesture { onSelect(day) }.frame(maxWidth: .infinity)
+ } else {
+ Color.clear.frame(maxWidth: .infinity).frame(height: 18)
+ }
+ }
+ }
+ }
+}
+
+private struct CalcomDayCell: View {
+ let day: Date
+ let hasEvents: Bool
+ let isToday: Bool
+ var body: some View {
+ VStack(spacing: 1) {
+ Text("\(Calendar.current.component(.day, from: day))")
+ .font(.system(size: 9, weight: isToday ? .bold : .regular))
+ .foregroundColor(isToday ? .white : Color(hex: "#9398A1"))
+ .frame(width: 13, height: 13)
+ .background(isToday ? Color(hex: "#C9956A").opacity(0.55) : Color.clear)
+ .clipShape(Circle())
+ Circle().fill(hasEvents ? Color(hex: "#C9956A") : Color.clear).frame(width: 3, height: 3)
+ }
+ .frame(height: 18)
+ }
+}
+
+struct CalcomDayView: View {
+ let date: Date
+ let bookings: [CalcomBooking]
+ let onSelect: (CalcomBooking) -> Void
+ let onBack: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 4) {
+ Button(action: onBack) {
+ Image(systemName: "chevron.left").font(.system(size: 9, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079")).frame(width: 22, height: 22).contentShape(Rectangle())
+ }.buttonStyle(.plain).padding(.leading, 108)
+ Text(dayLabel).font(.system(size: 11, weight: .semibold)).foregroundColor(Color(hex: "#C5C8CD"))
+ Spacer()
+ }
+ .padding(.top, 6).padding(.trailing, 12)
+
+ if bookings.isEmpty {
+ Text("No calls scheduled").font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079"))
+ .padding(.leading, 116).padding(.top, 8)
+ } else {
+ VStack(alignment: .leading, spacing: 3) {
+ ForEach(bookings) { b in
+ Button { onSelect(b) } label: {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#C9956A")).frame(width: 4, height: 4)
+ Text(b.timeLabel)
+ .font(.system(size: 10, weight: .medium, design: .monospaced))
+ .foregroundColor(Color(hex: "#C9956A")).fixedSize()
+ Text(b.title).font(.system(size: 11)).foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail).layoutPriority(1)
+ Spacer(minLength: 2)
+ Image(systemName: "chevron.right").font(.system(size: 8))
+ .foregroundColor(Color(hex: "#4B5563"))
+ }
+ .padding(.horizontal, 6).padding(.vertical, 3)
+ .background(Color(hex: "#C9956A").opacity(0.06))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
+ }.buttonStyle(.plain)
+ }
+ }
+ .padding(.leading, 108).padding(.trailing, 12).padding(.top, 5)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4)
+ .transition(.opacity)
+ }
+ private var dayLabel: String {
+ let f = DateFormatter(); f.dateFormat = "EEEE d MMMM"; return f.string(from: date)
+ }
+}
+
+struct CalcomBookingDetailView: View {
+ let booking: CalcomBooking
+ let onBack: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 4) {
+ Button(action: onBack) {
+ Image(systemName: "chevron.left").font(.system(size: 9, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079")).frame(width: 22, height: 22).contentShape(Rectangle())
+ }.buttonStyle(.plain).padding(.leading, 108)
+ Text(booking.timeLabel)
+ .font(.system(size: 10, weight: .medium, design: .monospaced))
+ .foregroundColor(Color(hex: "#C9956A"))
+ Spacer()
+ }
+ .padding(.top, 6).padding(.trailing, 12)
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(booking.title).font(.system(size: 12, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8")).lineLimit(1)
+ if let name = booking.attendeeName, !name.isEmpty {
+ CalcomDetailRow(icon: "person.fill", text: name, size: 11)
+ }
+ if let email = booking.attendeeEmail, !email.isEmpty {
+ CalcomDetailRow(icon: "envelope.fill", text: email, size: 10, truncate: true)
+ }
+ if let notes = booking.attendeeNotes, !notes.isEmpty {
+ CalcomDetailRow(icon: "note.text", text: notes, size: 10, lines: 2)
+ }
+ }
+ .padding(.leading, 114).padding(.trailing, 12).padding(.top, 5)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4)
+ .transition(.opacity)
+ }
+}
+
+private struct CalcomDetailRow: View {
+ let icon: String
+ let text: String
+ var size: CGFloat = 11
+ var truncate: Bool = false
+ var lines: Int = 1
+ var body: some View {
+ HStack(alignment: .top, spacing: 4) {
+ Image(systemName: icon).font(.system(size: 9)).foregroundColor(Color(hex: "#6B7079")).frame(width: 10)
+ Text(text).font(.system(size: size)).foregroundColor(Color(hex: "#9398A1"))
+ .lineLimit(lines).truncationMode(truncate ? .middle : .tail)
+ }
+ }
+}
+
+// MARK: - Notion Card View
+
+struct NotionCardView: View {
+ @ObservedObject private var appState = AppState.shared
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#E8E8E8")).frame(width: 7, height: 7)
+ Text("Notion").font(.system(size: 12, weight: .semibold)).foregroundColor(Color(hex: "#F5F6F8"))
+ Text("Recent").font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C"))
+ }
+ .padding(.top, 6).padding(.leading, 108).padding(.trailing, 36)
+
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(appState.notionPages.prefix(3)) { page in
+ Button {
+ if let url = URL(string: page.url) { NSWorkspace.shared.open(url) }
+ } label: {
+ HStack(spacing: 6) {
+ if let emoji = page.emoji {
+ Text(emoji).font(.system(size: 10)).frame(width: 14)
+ } else {
+ Image(systemName: "doc.text").font(.system(size: 9))
+ .foregroundColor(Color(hex: "#6B7079")).frame(width: 14)
+ }
+ Text(page.title).font(.system(size: 11))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ .lineLimit(1).truncationMode(.tail).layoutPriority(1)
+ Spacer(minLength: 4)
+ Text(page.timeAgo).font(.system(size: 9))
+ .foregroundColor(Color(hex: "#4B5563"))
+ }
+ .padding(.horizontal, 6).padding(.vertical, 4)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(.leading, 102).padding(.trailing, 12).padding(.top, 5)
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading).padding(.top, 4)
+ .transition(.opacity)
+ }
+}
+
+// MARK: - n8n Execution Detail View
+
+struct N8nDetailView: View {
+ let task: AgentTask
+ let onClose: () -> Void
+
+ private var success: Bool { task.state == .finished }
+ private var accent: Color { success ? Color(hex: "#22C55E") : Color(hex: "#F4505E") }
+ private var statusLabel: String { success ? "Success" : "Failed" }
+ private var detail: String? { task.steps.dropFirst().first }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+
+ // Header: back button + workflow name + status badge
+ HStack(spacing: 7) {
+ Button(action: onClose) {
+ Image(systemName: "chevron.left")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .frame(width: 28, height: 28) // large hit area
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+
+ Circle().fill(accent).frame(width: 6, height: 6)
+
+ Text(task.steps.first ?? "Workflow")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ .lineLimit(1).truncationMode(.middle)
+ .layoutPriority(1)
+
+ Spacer(minLength: 2)
+
+ Text(statusLabel)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundColor(accent)
+ .padding(.horizontal, 6).padding(.vertical, 2)
+ .background(accent.opacity(0.14))
+ .clipShape(Capsule())
+ }
+
+ // Detail body — monospaced, selectable
+ if let detail {
+ ScrollView(.vertical, showsIndicators: false) {
+ Text(detail)
+ .font(.system(size: 10.5, design: .monospaced))
+ .foregroundColor(Color(hex: "#9398A1"))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .lineSpacing(2)
+ .textSelection(.enabled)
+ }
+ .frame(maxHeight: 88)
+ } else {
+ Text(success ? "Completed successfully." : "No error details available.")
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#6B7079"))
+ }
+ }
+ .padding(.top, 8)
+ .padding(.leading, 108)
+ .padding(.trailing, 12)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .contentShape(Rectangle()) // prevent taps falling through transparent areas
+ }
+}
+
+// MARK: - Ticker (overview scrolling task steps) V2
+
+struct TickerView: View {
+ let task: AgentTask?
+
+ @State private var rowA: String = "…" // completed (above, left-shifted)
+ @State private var rowB: String = "…" // current (below) → animates diagonally up-left
+ @State private var rowC: String = "" // incoming current — slides in from below
+
+ @State private var rowAOffset: CGFloat = 0
+ @State private var rowAOpacity: Double = 1
+ @State private var rowBOffset: CGFloat = 22
+ @State private var rowBPhase: Double = 0 // 0=current, 1=completed (drives X+scale)
+ @State private var rowCOffset: CGFloat = 44
+ @State private var rowCOpacity: Double = 0
+
+ @State private var displayIndex: Int = -1
+ @State private var isTransitioning = false
+
+ private let completedScale: CGFloat = 11.5 / 13 // 0.885 — matches completed font size
+
+ var steps: [String] {
+ let raw = task?.steps ?? []
+ return raw.isEmpty ? ["…"] : raw
+ }
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ Color.clear
+
+ // Row A: completed row — always rendered at phase=1 + completedScale
+ TickerRowView(text: rowA, phase: 1.0)
+ .scaleEffect(completedScale, anchor: .leading)
+ .offset(x: -10, y: rowAOffset)
+ .opacity(rowAOpacity)
+
+ // Row B: current step → animates diagonally up-left, phase 0→1, scale 1→completedScale
+ TickerRowView(text: rowB, phase: rowBPhase)
+ .scaleEffect(1 - rowBPhase * (1 - completedScale), anchor: .leading)
+ .offset(x: -rowBPhase * 10, y: rowBOffset)
+
+ // Row C: incoming new step — slides in from below at phase=0
+ TickerRowView(text: rowC, phase: 0.0)
+ .offset(y: rowCOffset)
+ .opacity(rowCOpacity)
+ }
+ .frame(height: 44)
+ .clipped()
+ .mask(LinearGradient(
+ stops: [
+ .init(color: .clear, location: 0),
+ .init(color: .black, location: 0.12),
+ .init(color: .black, location: 0.85),
+ .init(color: .clear, location: 1)
+ ],
+ startPoint: .top, endPoint: .bottom
+ ))
+ .onAppear {
+ let idx = task?.stepIndex ?? -1
+ displayIndex = idx
+ if idx >= 0, !steps.isEmpty {
+ rowA = idx > 0 ? steps[max(0, idx - 1)] : "…"
+ rowB = steps[min(idx, steps.count - 1)]
+ }
+ }
+ .onChange(of: task?.steps.count) { _, _ in
+ guard let task, !task.steps.isEmpty, !isTransitioning else { return }
+ let newIdx = task.stepIndex
+ if displayIndex < 0 {
+ displayIndex = newIdx
+ rowA = newIdx > 0 ? steps[max(0, newIdx - 1)] : "…"
+ rowB = steps[min(newIdx, steps.count - 1)]
+ return
+ }
+ guard newIdx != displayIndex else { return }
+ tickerAnimate(to: newIdx)
+ }
+ }
+
+ private func tickerAnimate(to newIdx: Int) {
+ isTransitioning = true
+ rowC = steps[min(newIdx, steps.count - 1)]
+ rowCOffset = 44
+ rowCOpacity = 0
+
+ // Old completed (rowA): fades + slides further up
+ withAnimation(.easeOut(duration: 0.28)) {
+ rowAOffset = -22
+ rowAOpacity = 0
+ }
+
+ // Current (rowB): moves diagonally up-left + shrinks to completed size
+ withAnimation(.timingCurve(0.4, 0, 0.2, 1, duration: 0.38)) {
+ rowBOffset = 0
+ rowBPhase = 1
+ }
+
+ // New current (rowC): slides in from below
+ withAnimation(.timingCurve(0.4, 0, 0.2, 1, duration: 0.38)) {
+ rowCOffset = 22
+ rowCOpacity = 1
+ }
+
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.50) {
+ self.displayIndex = newIdx
+ self.rowA = self.rowB
+ self.rowAOffset = 0
+ self.rowAOpacity = 1
+ self.rowB = self.rowC
+ self.rowBOffset = 22
+ self.rowBPhase = 0
+ self.rowCOffset = 44
+ self.rowCOpacity = 0
+ self.isTransitioning = false
+ }
+ }
+}
+
+struct TickerRowView: View {
+ let text: String
+ let phase: Double // 0 = current (shimmer, large), 1 = completed (dim, scaled down by caller)
+
+ var body: some View {
+ HStack(spacing: 6) {
+ // Icon: chevron fades out first half, checkmark fades in second half
+ ZStack {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 9, weight: .medium))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .opacity(max(0, 1 - phase * 2))
+ Image(systemName: "checkmark")
+ .font(.system(size: 8, weight: .regular))
+ .foregroundColor(Color(hex: "#454850"))
+ .opacity(max(0, phase * 2 - 1))
+ }
+ .frame(width: 12, alignment: .center)
+
+ // Text: shimmer fades out, dim completed text fades in (overlapping cross-fade)
+ ZStack(alignment: .leading) {
+ TickerShimmerText(text: text)
+ .opacity(max(0, 1 - phase * 1.6))
+ Text(text)
+ .font(.system(size: 13, weight: .medium))
+ .foregroundColor(Color(hex: "#6B7079"))
+ .lineLimit(1).truncationMode(.tail)
+ .opacity(min(1, max(0, phase * 2 - 0.4)))
+ }
+ }
+ .frame(height: 22, alignment: .leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
+struct TickerShimmerText: View {
+ let text: String
+
+ var body: some View {
+ TimelineView(.animation) { tl in
+ let t = tl.date.timeIntervalSinceReferenceDate
+ let p = CGFloat(t.truncatingRemainder(dividingBy: 2.2) / 2.2)
+ // phase sweeps -0.1 → 1.1 so white peak enters from left and exits right
+ let phase = p * 1.2 - 0.1
+ Text(text)
+ .font(.system(size: 13, weight: .medium))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .foregroundStyle(LinearGradient(stops: [
+ .init(color: Color(hex: "#7c818a"), location: max(0, phase - 0.3)),
+ .init(color: Color(hex: "#F2F3F5"), location: max(0, min(1, phase))),
+ .init(color: Color(hex: "#7c818a"), location: min(1, phase + 0.3)),
+ ], startPoint: .leading, endPoint: .trailing))
+ }
+ }
+}
+
+// MARK: - Agent pills (overview right card)
+
+struct AgentPillsView: View {
+ @ObservedObject var state: AppState
+ @State private var swapping = false
+
+ private var others: [AgentTask] {
+ state.tasks.filter { $0.id != state.focusId }
+ }
+
+ private var displayTasks: [AgentTask] {
+ Array(others.prefix(4))
+ }
+
+ private let columns = [
+ GridItem(.flexible(), spacing: 4),
+ GridItem(.flexible(), spacing: 4)
+ ]
+
+ var body: some View {
+ VStack(spacing: 0) {
+ Spacer(minLength: 0)
+ LazyVGrid(columns: columns, spacing: 4) {
+ ForEach(displayTasks) { task in
+ AgentPill(task: task, state: state, swapping: $swapping) {
+ swapping = true
+ state.setFocus(task.id)
+ SoundEngine.shared.play("blip")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { swapping = false }
+ }
+ }
+ }
+ .padding(.horizontal, 8)
+ Spacer(minLength: 0)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+}
+
+struct AgentPill: View {
+ let task: AgentTask
+ @ObservedObject var state: AppState
+ @Binding var swapping: Bool
+ let onTap: () -> Void
+ @State private var isHovered = false
+
+ // VS Code pill always shows "VS Code" label regardless of active project name
+ private var displayName: String {
+ task.id == "integration_claude" ? "VS Code" : task.name
+ }
+
+ var body: some View {
+ Button(action: { onTap() }) {
+ ZStack(alignment: .topTrailing) {
+ ZStack {
+ Capsule()
+ .fill(isHovered
+ ? Color(hex: task.color).opacity(0.18)
+ : Color(hex: "#0E0F11"))
+ Capsule()
+ .stroke(Color(hex: task.color).opacity(isHovered ? 0.55 : 0.14), lineWidth: 1)
+ HStack(spacing: 0) {
+ MiniBotCanvasView(task: task)
+ .frame(width: 22 / 0.6, height: 22 / 0.6)
+ .frame(width: 22, height: 22, alignment: .center)
+ .padding(.leading, 8)
+ Spacer()
+ }
+ Text(displayName)
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundColor(isHovered
+ ? Color(hex: task.color).lighter(by: 0.3)
+ : Color(hex: "#6B7079"))
+ .lineLimit(1)
+ .truncationMode(.tail)
+ .frame(maxWidth: .infinity, alignment: .center)
+ }
+ .frame(maxWidth: .infinity)
+ .frame(height: 28)
+ .shadow(color: Color(hex: task.color).opacity(isHovered ? 0.35 : 0), radius: 10, x: 0, y: 2)
+
+ // Alert badge (approval / finished / error)
+ if let badge = task.pillBadge {
+ PillBadgeView(badge: badge, taskColor: task.color)
+ .offset(x: 3, y: -3)
+ }
+ }
+ }
+ .buttonStyle(.plain)
+ .scaleEffect(isHovered ? 1.04 : 1.0)
+ .brightness(isHovered ? 0.06 : 0)
+ .onHover { newHover in
+ guard !swapping else { return }
+ withAnimation(.spring(response: 0.2, dampingFraction: 0.7)) { isHovered = newHover }
+ }
+ }
+}
+
+struct PillBadgeView: View {
+ let badge: PillBadge
+ let taskColor: String
+
+ private var badgeColor: Color {
+ switch badge {
+ case .approval: return Color(hex: "#F5A524")
+ case .finished: return Color(hex: "#22C55E")
+ case .error: return Color(hex: "#F4505E")
+ }
+ }
+
+ private var icon: String {
+ switch badge {
+ case .approval: return "exclamationmark"
+ case .finished: return "checkmark"
+ case .error: return "xmark"
+ }
+ }
+
+ var body: some View {
+ ZStack {
+ Circle()
+ .fill(Color(hex: "#0B0C0E"))
+ .frame(width: 14, height: 14)
+ Circle()
+ .fill(badgeColor)
+ .frame(width: 12, height: 12)
+ Image(systemName: icon)
+ .font(.system(size: 6, weight: .bold))
+ .foregroundColor(.black)
+ }
+ .shadow(color: badgeColor.opacity(0.6), radius: 4, x: 0, y: 0)
+ }
+}
+
+// MARK: - Column agents (right side of non-overview views)
+
+struct ColumnAgentsView: View {
+ @ObservedObject var state: AppState
+
+ var others: [AgentTask] {
+ state.tasks.filter { $0.id != state.focusId }
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ForEach(Array(others.prefix(4).enumerated()), id: \.1.id) { idx, task in
+ MiniBotCanvasView(task: task)
+ .frame(width: 16 / 0.6, height: 16 / 0.6)
+ .frame(width: 16, height: 16)
+ .position(x: 0, y: CGFloat(50 + idx * 24))
+ .animation(.spring(response: 0.5, dampingFraction: 0.72).delay(Double(idx) * 0.035), value: idx)
+ }
+ }
+ }
+}
+
+// MARK: - Card background
+
+struct CardBackground<Content: View>: View {
+ enum Wash { case red, green, pink, amber, cyan, indigo, soft }
+
+ let wash: Wash?
+ let content: (() -> Content)?
+
+ init(wash: Wash?, @ViewBuilder content: @escaping () -> Content) {
+ self.wash = wash
+ self.content = content
+ }
+
+ var washColor: Color {
+ switch wash {
+ case .red: return Color(hex: "#F4505E").opacity(0.55)
+ case .green: return Color(hex: "#34D399").opacity(0.5)
+ case .pink: return Color(hex: "#F472B6").opacity(0.55)
+ case .amber: return Color(hex: "#F5A524").opacity(0.42)
+ case .cyan: return Color(hex: "#22D3EE").opacity(0.38)
+ case .indigo: return Color(hex: "#6366F1").opacity(0.5)
+ case .soft: return Color.white.opacity(0.08)
+ case nil: return Color.clear
+ }
+ }
+
+ var body: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 20)
+ .fill(Color(hex: "#141518"))
+ .overlay(
+ RadialGradient(
+ gradient: Gradient(stops: [
+ .init(color: washColor, location: 0),
+ .init(color: .clear, location: 0.7)
+ ]),
+ center: UnitPoint(x: 0.5, y: 1.3),
+ startRadius: 0,
+ endRadius: 280
+ )
+ .clipShape(RoundedRectangle(cornerRadius: 20))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 20)
+ .stroke(Color.white.opacity(0.035), lineWidth: 1)
+ )
+
+ if let content = content {
+ content()
+ }
+ }
+ }
+}
+
+extension CardBackground where Content == EmptyView {
+ init(wash: Wash?) {
+ self.wash = wash
+ self.content = nil
+ }
+
+ var body: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 20)
+ .fill(Color(hex: "#141518"))
+ .overlay(
+ RadialGradient(
+ gradient: Gradient(stops: [
+ .init(color: washColor, location: 0),
+ .init(color: .clear, location: 0.7)
+ ]),
+ center: UnitPoint(x: 0.5, y: 1.3),
+ startRadius: 0,
+ endRadius: 280
+ )
+ .clipShape(RoundedRectangle(cornerRadius: 20))
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 20)
+ .stroke(Color.white.opacity(0.035), lineWidth: 1)
+ )
+ }
+ }
+}
+
+// MARK: - Shared sub-components
+
+struct AgentWho: View {
+ let task: AgentTask?
+ let label: String
+
+ var body: some View {
+ HStack(spacing: 7) {
+ if let task = task {
+ Circle().fill(Color(hex: task.color)).frame(width: 8, height: 8)
+ Text(task.name).font(.system(size: 12, weight: .semibold)).foregroundColor(Color(hex: "#F5F6F8"))
+ }
+ Text(label).font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
+ }
+ }
+}
+
+struct CodeBlock: View {
+ let text: String
+
+ var body: some View {
+ Text(text)
+ .font(.system(size: 12, design: .monospaced))
+ .padding(.horizontal, 10).padding(.vertical, 5)
+ .background(Color.white.opacity(0.07))
+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.white.opacity(0.06)))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ .foregroundColor(Color(hex: "#E8E9EC"))
+ }
+}
+
+struct ContextChip: View {
+ let context: PromptContext
+ @State private var glowing = false
+
+ var label: String {
+ switch context {
+ case .window(let app, _, let url):
+ if let url = url, let host = URL(string: url)?.host { return "\(app) · \(host)" }
+ return app
+ case .file(let name, _): return name
+ }
+ }
+
+ var body: some View {
+ HStack(spacing: 6) {
+ Circle()
+ .fill(LinearGradient(colors: [Color(hex: "#FF6B5B"), Color(hex: "#F7B32B"), Color(hex: "#2DD4A7"), Color(hex: "#38BDF8"), Color(hex: "#A78BFA")], startPoint: .topLeading, endPoint: .bottomTrailing))
+ .frame(width: 7, height: 7)
+ Text(label)
+ .font(.system(size: 11.5))
+ .foregroundColor(Color(hex: "#F1F2F4"))
+ }
+ .padding(.horizontal, 10).padding(.vertical, 4)
+ .background(Color.white.opacity(0.1))
+ .clipShape(Capsule())
+ .overlay(Capsule().stroke(Color.white.opacity(glowing ? 0.75 : 0), lineWidth: 1.5))
+ .scaleEffect(glowing ? 1.06 : 1.0)
+ .onAppear {
+ withAnimation(.spring(response: 0.25, dampingFraction: 0.55)) { glowing = true }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) {
+ withAnimation(.easeOut(duration: 0.3)) { glowing = false }
+ }
+ }
+ }
+}
+
+struct MailField: View {
+ let label: String
+ let placeholder: String
+ @Binding var text: String
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Text(label)
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#80858E"))
+ .frame(width: 44, alignment: .leading)
+ TextField(placeholder, text: $text)
+ .textFieldStyle(.plain)
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#F5F6F8"))
+ }
+ .padding(.horizontal, 10).padding(.vertical, 6)
+ .background(Color.white.opacity(0.06))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ }
+}
+
+struct ShimmeringText: View {
+ let text: String
+ init(_ text: String) { self.text = text }
+
+ var body: some View {
+ Text(text)
+ .foregroundStyle(
+ LinearGradient(
+ stops: [
+ .init(color: Color(hex: "#7c818a"), location: 0),
+ .init(color: .white, location: 0.4),
+ .init(color: Color(hex: "#7c818a"), location: 0.7)
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ )
+ )
+ }
+}
+
+struct ShimmerOverlay: View {
+ @State private var phase: CGFloat = 0.0
+
+ var body: some View {
+ LinearGradient(
+ stops: [
+ // Clamp all locations to [0,1] and keep them ordered
+ .init(color: .clear, location: max(0, phase - 0.3)),
+ .init(color: Color.white.opacity(0.6), location: max(0, min(1, phase))),
+ .init(color: .clear, location: min(1, phase + 0.3))
+ ],
+ startPoint: .leading, endPoint: .trailing
+ )
+ .blendMode(.overlay)
+ .onAppear {
+ withAnimation(.linear(duration: 2.2).repeatForever(autoreverses: false)) {
+ phase = 1.3 // travels left→right, exits right edge cleanly
+ }
+ }
+ }
+}
+
+// MARK: - Button styles
+
+struct PrimaryButton: View {
+ let title: String
+ let kbd: String?
+ let action: () -> Void
+
+ init(_ title: String, kbd: String? = nil, action: @escaping () -> Void) {
+ self.title = title; self.kbd = kbd; self.action = action
+ }
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 7) {
+ Text(title).font(.system(size: 12.5, weight: .medium))
+ if let k = kbd {
+ Text(k).font(.system(size: 10.5))
+ .padding(.horizontal, 4)
+ .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.black.opacity(0.4)))
+ .opacity(0.55)
+ }
+ }
+ .padding(.horizontal, 13).padding(.vertical, 7)
+ .background(Color(hex: "#F5F6F8"))
+ .foregroundColor(Color(hex: "#0B0C0E"))
+ .clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+struct SecondaryButton: View {
+ let title: String
+ let kbd: String?
+ let action: () -> Void
+
+ init(_ title: String, kbd: String? = nil, action: @escaping () -> Void) {
+ self.title = title; self.kbd = kbd; self.action = action
+ }
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 7) {
+ Text(title).font(.system(size: 12.5, weight: .medium))
+ if let k = kbd {
+ Text(k).font(.system(size: 10.5))
+ .padding(.horizontal, 4)
+ .overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.white.opacity(0.4)))
+ .opacity(0.55)
+ }
+ }
+ .padding(.horizontal, 13).padding(.vertical, 7)
+ .background(Color.white.opacity(0.09))
+ .foregroundColor(Color(hex: "#F1F2F4"))
+ .clipShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ }
+}
+
+struct IconButtonStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .frame(width: 28, height: 28)
+ .background(Color.white.opacity(0.08))
+ .clipShape(Circle())
+ .scaleEffect(configuration.isPressed ? 0.94 : 1)
+ }
+}
+
+struct SendButtonStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .frame(width: 28, height: 28)
+ .background(Color(hex: "#F5F6F8"))
+ .clipShape(Circle())
+ .scaleEffect(configuration.isPressed ? 0.94 : 1)
+ }
+}
+
+// MARK: - Settings island view (Point 7)
+
+struct SettingsIslandView: View {
+ @ObservedObject var state: AppState
+
+ private var claudeConnected: Bool {
+ let url = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".claude/settings.json")
+ guard let data = try? Data(contentsOf: url),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let hooks = json["hooks"] as? [String: Any],
+ let ss = hooks["SessionStart"] as? [[String: Any]] else { return false }
+ return ss.contains { matcher in
+ (matcher["hooks"] as? [[String: Any]])?.contains {
+ ($0["command"] as? String)?.contains("NotchBuddy") == true
+ } ?? false
+ }
+ }
+
+ private var apiConnected: Bool {
+ KeychainStore.shared.get("anthropic-api-key") != nil
+ }
+
+ var body: some View {
+ ZStack(alignment: .leading) {
+ CardBackground(wash: nil)
+ VStack(alignment: .leading, spacing: 10) {
+ // Sound row
+ HStack(spacing: 10) {
+ Toggle("", isOn: $state.soundEnabled)
+ .toggleStyle(.switch)
+ .labelsHidden()
+ .scaleEffect(0.75)
+ .frame(width: 44)
+ Text("Sound")
+ .font(.system(size: 12.5))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ Slider(value: $state.soundVolume, in: 0...0.2)
+ .frame(width: 72)
+ .opacity(state.soundEnabled ? 1 : 0.4)
+ }
+
+ // Auto-close row
+ HStack(spacing: 10) {
+ Image(systemName: "timer")
+ .font(.system(size: 12))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .frame(width: 16)
+ Text("Auto-close · \(Int(state.autoCloseInterval))s")
+ .font(.system(size: 12))
+ .foregroundColor(Color(hex: "#C5C8CD"))
+ Spacer()
+ HStack(spacing: 6) {
+ ForEach([10, 15, 30], id: \.self) { s in
+ Button("\(s)s") {
+ state.autoCloseInterval = Double(s)
+ }
+ .font(.system(size: 11))
+ .padding(.horizontal, 7).padding(.vertical, 3)
+ .background(state.autoCloseInterval == Double(s) ? Color(hex: "#252830") : Color.clear)
+ .foregroundColor(state.autoCloseInterval == Double(s) ? Color(hex: "#F5F6F8") : Color(hex: "#6B7079"))
+ .clipShape(Capsule())
+ .buttonStyle(.plain)
+ }
+ }
+ }
+
+ // Connection status
+ HStack(spacing: 14) {
+ StatusBadge(label: "Claude Code", ok: claudeConnected)
+ StatusBadge(label: "API", ok: apiConnected)
+ Spacer()
+ Button("Settings…") {
+ NotificationCenter.default.post(name: .openFullSettings, object: nil)
+ }
+ .font(.system(size: 11.5))
+ .foregroundColor(Color(hex: "#8E939C"))
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(.leading, 84)
+ .padding(.trailing, 16)
+ .padding(.vertical, 14)
+ }
+ }
+}
+
+struct StatusBadge: View {
+ let label: String
+ let ok: Bool
+
+ var body: some View {
+ HStack(spacing: 4) {
+ Circle()
+ .fill(ok ? Color(hex: "#22C55E") : Color(hex: "#F4505E"))
+ .frame(width: 6, height: 6)
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#8E939C"))
+ }
+ }
+}
+
+// MARK: - Color extension (lighten)
+
+extension Color {
+ func lighter(by amount: Double) -> Color {
+ guard let components = NSColor(self).usingColorSpace(.sRGB) else { return self }
+ return Color(
+ red: min(1, Double(components.redComponent) + amount),
+ green: min(1, Double(components.greenComponent) + amount),
+ blue: min(1, Double(components.blueComponent) + amount)
+ )
+ }
+}
diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift
new file mode 100644
index 00000000..64e26d11
--- /dev/null
+++ b/NotchBuddy/Sources/App/IslandWindowController.swift
@@ -0,0 +1,857 @@
+import AppKit
+import Combine
+import SwiftUI
+
+@MainActor
+final class IslandWindowController: NSWindowController {
+
+ private var islandPanel: IslandPanel!
+ private var state: AppState { AppState.shared }
+
+ // State machine (replaces all hover/absence/auto-close timers)
+ let fsm = IslandStateMachine()
+
+ private var wasInIsland = false
+ private var frameTimer: Timer?
+ private var keyMonitor: Any?
+ private var viewSubscription: AnyCancellable?
+
+ // Confused recovery timer (set by handleDizzy)
+ private var confusedRecoveryTimer: DispatchWorkItem?
+
+ // Finished-pin timer
+ private var finishedPinTimer: DispatchWorkItem?
+
+ // Bot-head hover (love emote — mirrors prototype botHover())
+ private var hoverTimer: DispatchWorkItem?
+ private var botHoverTimer: DispatchWorkItem?
+ private var botHovering: Bool = false
+ private var lastLoveTime: Double = 0
+ private var botHoverStartPos: CGPoint = .zero
+
+ // Window attach drag (M8)
+ private var attachDragStart: NSPoint? = nil
+ private var pendingIslandClick = false // any island click → expand on mouseUp
+ private var inAttachDrag = false
+ private var dragGhostPanel: NSPanel? = nil
+ private var dragGhostSize: CGFloat = 0
+ private var ghostCurrentOrigin: NSPoint = .zero
+ private var highlightPanel: NSPanel? = nil
+ private var highlightWindowPid: pid_t = 0
+
+ // Notch real dimensions (set on init)
+ private var notchW: CGFloat = IslandConst.notchWidth
+ private var notchH: CGFloat = IslandConst.notchHeight
+
+ convenience init() {
+ let screen = Self.notchScreen() ?? NSScreen.main!
+ let nW = Self.notchWidth(for: screen)
+ let nH = Self.notchHeight(for: screen)
+
+ let panelW: CGFloat = 720
+ let panelH: CGFloat = 320
+ let sf = screen.frame
+ let panel = IslandPanel(
+ contentRect: NSRect(x: sf.midX - panelW/2, y: sf.maxY - panelH,
+ width: panelW, height: panelH),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false
+ )
+ panel.notchWidth = nW
+ panel.notchHeight = nH
+
+ self.init(window: panel)
+ self.islandPanel = panel
+ self.notchW = nW
+ self.notchH = nH
+ setupPanel(screen: screen)
+ }
+
+ private func setupPanel(screen: NSScreen) {
+ guard let panel = window as? IslandPanel else { return }
+ panel.backgroundColor = .clear
+ panel.isOpaque = false
+ panel.hasShadow = false
+ panel.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.mainMenuWindow)) + 3)
+ panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary, .ignoresCycle]
+ panel.ignoresMouseEvents = true
+
+ // Propagate real notch dimensions to AppState
+ AppState.shared.notchWidth = notchW
+ AppState.shared.notchHeight = notchH
+
+ let contentSize = panel.contentRect(forFrameRect: panel.frame).size
+
+ // Apple-recommended pattern: put NSHostingView and drag destination as siblings
+ // inside a common superview, rather than embedding one inside the other.
+ let container = NSView(frame: NSRect(origin: .zero, size: contentSize))
+ container.autoresizingMask = [.width, .height]
+
+ let hosting = NSHostingView(rootView: IslandRootView().environmentObject(AppState.shared))
+ hosting.frame = NSRect(origin: .zero, size: contentSize)
+ hosting.autoresizingMask = [.width, .height]
+
+ // FileDropNSView sits below the hosting view (hitTest returns nil → no mouse interference).
+ // AppKit routes NSDraggingDestination events to registered views independently of hitTest.
+ let dropView = FileDropNSView(frame: NSRect(origin: .zero, size: contentSize))
+ dropView.autoresizingMask = [.width, .height]
+ dropView.onDragEntered = { [weak self] loc in
+ Task { @MainActor in
+ let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
+ AppState.shared.fileDragOver = true
+ // enterZone sets isActive=true BEFORE hookExpand triggers re-render,
+ // so IslandContainer sees isActive=true when state.view becomes .upload.
+ UploadSequenceEngine.shared.enterZone(x: iLoc.x, y: iLoc.y)
+ NotificationCenter.default.post(name: .hookExpand, object: IslandView.upload)
+ NotificationCenter.default.post(name: .botMorphTo, object: CGFloat(1))
+ }
+ }
+ dropView.onDragUpdated = { [weak self] loc in
+ Task { @MainActor in
+ let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
+ UploadSequenceEngine.shared.updateCursor(x: iLoc.x, y: iLoc.y)
+ }
+ }
+ dropView.onDragExited = {
+ Task { @MainActor in
+ AppState.shared.fileDragOver = false
+ // Do NOT collapse — drag session still active; island stays open.
+ NotificationCenter.default.post(name: .botMorphTo, object: CGFloat(0))
+ UploadSequenceEngine.shared.exitZone()
+ }
+ }
+ dropView.onFilesDropped = { urls in
+ Task { @MainActor in
+ await FileDropHandler.handle(urls: urls, state: AppState.shared)
+ }
+ }
+
+ container.addSubview(hosting) // z-bottom: SwiftUI + mouse events
+ container.addSubview(dropView) // z-top: drag only (hitTest→nil, transparent to mouse)
+ panel.contentView = container
+
+ startPolling()
+ startKeyMonitor()
+ wireFSM()
+
+ // Make panel key whenever the prompt/chat view becomes active
+ // (nonactivatingPanel never auto-becomes key, but TextField needs it)
+ viewSubscription = state.$view
+ .receive(on: DispatchQueue.main)
+ .sink { [weak self] newView in
+ guard let self else { return }
+ if newView == .prompt {
+ self.islandPanel.makeKey()
+ }
+ }
+ }
+
+ // MARK: - FSM wiring
+
+ private func wireFSM() {
+ fsm.onTransition = { [weak self] from, to in
+ guard let self else { return }
+ switch to {
+ case .hidden:
+ self.setMode(.hidden)
+
+ case .petit:
+ if from == .coucou {
+ // Fire interrupt first so canvas collapse starts before mode change
+ NotificationCenter.default.post(name: .greetingInterrupt, object: nil)
+ } else if from == .hidden {
+ SoundEngine.shared.play("peek")
+ }
+ // setMode BEFORE changing view: onChange(of: state.view) guards on .expanded,
+ // so setting view while already compact won't trigger a spurious open animation.
+ self.setMode(.compact)
+ if from == .coucou { self.state.view = self.defaultView() }
+ // Start 60s hide timer if mouse is not currently over the island
+ if !self.wasInIsland { self.fsm.mouseLeft() }
+
+ case .home:
+ self.expand(to: self.defaultView())
+ // Start collapse timer if mouse not currently hovering
+ if !self.wasInIsland {
+ self.fsm.mouseLeft()
+ }
+
+ case .coucou:
+ self.expand(to: .greeting)
+ }
+ }
+
+ // FSM observes greetComplete notification
+ NotificationCenter.default.addObserver(
+ forName: .greetComplete, object: nil, queue: .main
+ ) { [weak self] _ in
+ self?.fsm.greetComplete()
+ }
+ }
+
+ // MARK: - 60 Hz polling loop
+
+ private func startPolling() {
+ frameTimer = Timer.scheduledTimer(withTimeInterval: 1.0/60.0, repeats: true) { [weak self] _ in
+ guard let self else { return }
+ Task { @MainActor in self.pollFrame() }
+ }
+ RunLoop.main.add(frameTimer!, forMode: .common)
+ }
+
+ private func pollFrame() {
+ guard let panel = window as? IslandPanel else { return }
+
+ let mouse = NSEvent.mouseLocation
+
+ // Convert mouse to panel-local coords (macOS: origin bottom-left)
+ let pf = panel.frame
+ let local = CGPoint(x: mouse.x - pf.minX, y: mouse.y - pf.minY)
+
+ // Island rect in panel coords
+ let islandRect = panel.currentIslandFrame(nw: notchW, nh: notchH)
+ let inIsland = islandRect.insetBy(dx: -6, dy: -6).contains(local)
+
+ // Toggle click-through
+ let shouldAcceptMouse = inIsland || inAttachDrag || attachDragStart != nil
+ if panel.ignoresMouseEvents == shouldAcceptMouse {
+ panel.ignoresMouseEvents = !shouldAcceptMouse
+ if shouldAcceptMouse, let cv = panel.contentView {
+ panel.invalidateCursorRects(for: cv)
+ }
+ }
+
+ // Mouse in screen coords (Y flipped, origin top-left) for Bot look-at
+ let screenH = panel.screen?.frame.height ?? NSScreen.main!.frame.height
+ let newPos = CGPoint(x: mouse.x - (panel.screen?.frame.minX ?? 0), y: screenH - mouse.y)
+ let cur = AppState.shared.mousePosition
+ if abs(newPos.x - cur.x) > 1 || abs(newPos.y - cur.y) > 1 {
+ AppState.shared.mousePosition = newPos
+ }
+
+ // Feed FSM hover enter/leave
+ if inIsland && !wasInIsland {
+ guard !inAttachDrag else { wasInIsland = inIsland; return }
+ // If in coucou: tell greeting to stay open (tc → infinity)
+ if fsm.state == .coucou {
+ NotificationCenter.default.post(name: .greetingHover, object: nil)
+ }
+ fsm.mouseEntered()
+ }
+ if !inIsland && wasInIsland {
+ fsm.mouseLeft()
+ }
+ wasInIsland = inIsland
+
+ // Bot-head hover (love emote)
+ let overBot = state.mode == .expanded && state.stateOverride == nil && isBotHit(local)
+ if overBot && !botHovering { botHoverIn(mousePos: NSEvent.mouseLocation) }
+ if !overBot && botHovering { botHoverOut() }
+ botHovering = overBot
+ if botHovering {
+ let m = NSEvent.mouseLocation
+ let dist = hypot(m.x - botHoverStartPos.x, m.y - botHoverStartPos.y)
+ if dist > 40 {
+ botHoverStartPos = m
+ botHoverTimer?.cancel()
+ scheduleLoveTimer()
+ }
+ }
+
+ // Ghost Mochi follows cursor + window highlight during drag (60 Hz, no throttle)
+ if inAttachDrag {
+ updateDragGhost()
+ updateWindowHighlight()
+ }
+ }
+
+ private var lastMouse: CGPoint = .zero
+
+ // MARK: - Bot-head hover (love emote — mirrors prototype botHover())
+
+ private func botHoverIn(mousePos: CGPoint) {
+ guard state.mode == .expanded, state.stateOverride == nil else { return }
+ guard CACurrentMediaTime() - lastLoveTime > 6 else { return }
+ botHoverStartPos = mousePos
+ NotificationCenter.default.post(name: .botBlink, object: nil)
+ NotificationCenter.default.post(name: .botSetTgEs, object: CGFloat(1.08))
+ SoundEngine.shared.play("hover")
+ scheduleLoveTimer()
+ }
+
+ private func botHoverOut() {
+ botHoverTimer?.cancel()
+ NotificationCenter.default.post(name: .botSetTgEs, object: CGFloat(1))
+ }
+
+ private func scheduleLoveTimer() {
+ botHoverTimer?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, self.botHovering, self.state.stateOverride == nil else { return }
+ guard CACurrentMediaTime() - self.lastLoveTime > 6 else { return }
+ self.lastLoveTime = CACurrentMediaTime()
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.love)
+ SoundEngine.shared.play("love")
+ }
+ botHoverTimer = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.9, execute: item)
+ }
+
+ private func scheduleHover(after delay: TimeInterval, action: @escaping () -> Void) {
+ hoverTimer?.cancel()
+ let item = DispatchWorkItem(block: action)
+ hoverTimer = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
+ }
+
+ // MARK: - Mode transitions
+
+ private func modeLevel(_ m: IslandMode) -> Int {
+ switch m { case .hidden: return 0; case .compact: return 1; case .expanded: return 2 }
+ }
+
+ func setMode(_ mode: IslandMode) {
+ let prev = state.mode
+ guard mode != prev else { return }
+ let shrinking = modeLevel(mode) < modeLevel(prev)
+ let anim: Animation = shrinking
+ ? .timingCurve(0.45, 0, 0.2, 1, duration: 0.34)
+ : .spring(response: 0.5, dampingFraction: 0.72)
+ withAnimation(anim) { state.mode = mode }
+ if mode == .expanded { SoundEngine.shared.play("open") }
+ if prev == .expanded { SoundEngine.shared.play("close"); state.isPinned = false }
+ }
+
+ func expand(to view: IslandView) {
+ state.view = view
+ if state.mode == .expanded {
+ // Already expanded — just switch view
+ } else {
+ setMode(.expanded)
+ }
+ state.lastActivity = .now
+ }
+
+ func collapse() {
+ state.isPinned = false
+ finishedPinTimer?.cancel()
+ // Tell FSM we're going to compact (from home)
+ if fsm.state == .home { fsm.mouseLeft() }
+ setMode(.compact)
+ window?.resignKey()
+ }
+
+ // MARK: - Keyboard (Escape closes)
+
+ private func startKeyMonitor() {
+ keyMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in
+ Task { @MainActor in
+ guard let self = self else { return }
+ if event.keyCode == 53 { // Escape
+ if self.state.mode == .expanded && !self.state.isPinned {
+ self.collapse()
+ }
+ }
+ }
+ }
+
+ // Hook server expand requests (alerts only)
+ NotificationCenter.default.addObserver(forName: .hookExpand, object: nil, queue: .main) { [weak self] note in
+ guard let self, let view = note.object as? IslandView else { return }
+ self.expand(to: view)
+ }
+
+ // Hook server compact reveal (non-alert work events: session start, tool use, etc.)
+ NotificationCenter.default.addObserver(forName: .hookReveal, object: nil, queue: .main) { [weak self] _ in
+ guard let self else { return }
+ self.fsm.reveal()
+ }
+
+ // Collapse requests from views (OK button, etc.)
+ NotificationCenter.default.addObserver(forName: .islandCollapse, object: nil, queue: .main) { [weak self] _ in
+ self?.collapse()
+ }
+
+ // .botDizzy — posted by BotEngine.slap() on 3rd hit; show confused view + recover after 3.3s
+ NotificationCenter.default.addObserver(forName: .botDizzy, object: nil, queue: .main) { [weak self] _ in
+ self?.handleDizzy()
+ }
+
+ // Window attach drag.
+ // Uses MainActor.assumeIsolated (synchronous) to avoid race with pollFrame().
+ // Global mouseUp is the reliable fallback when cursor is outside our panel frame.
+ NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ guard self.wasInIsland else { return }
+ self.pendingIslandClick = true
+ self.hoverTimer?.cancel()
+ self.botHoverTimer?.cancel()
+ self.botHovering = false
+ // Drag only starts when clicking directly on the bot head
+ guard self.isBotHit(event.locationInWindow) else { return }
+ self.attachDragStart = NSEvent.mouseLocation
+ // Post slap only when expanded
+ guard self.state.mode == .expanded else { return }
+ NotificationCenter.default.post(name: .triggerSlap, object: nil)
+ }
+ return event
+ }
+ NSEvent.addLocalMonitorForEvents(matching: .leftMouseDragged) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ guard let start = self.attachDragStart, !self.inAttachDrag else { return }
+ let m = NSEvent.mouseLocation
+ guard hypot(m.x - start.x, m.y - start.y) > 3 else { return }
+ self.inAttachDrag = true
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.love)
+ self.showDragGhost()
+ }
+ return event
+ }
+
+ // mouseUp — local (cursor still in panel) + global (cursor moved outside panel frame)
+ let finishDrag: @Sendable () -> Void = { [weak self] in
+ Task { @MainActor in
+ guard let self, self.inAttachDrag else { return }
+ let mouse = NSEvent.mouseLocation
+ self.inAttachDrag = false
+ self.attachDragStart = nil
+ self.state.stateOverride = nil
+ self.hideDragGhost()
+ if let ctx = self.windowContextAtPoint(mouse) {
+ self.state.promptContext = ctx
+ SoundEngine.shared.play("approve")
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+ self.expand(to: .prompt)
+ }
+ }
+ }
+ NSEvent.addLocalMonitorForEvents(matching: .leftMouseUp) { [weak self] event in
+ guard let self else { return event }
+ MainActor.assumeIsolated {
+ let hadPendingClick = self.pendingIslandClick
+ let wasDragging = self.inAttachDrag
+ self.pendingIslandClick = false
+ if wasDragging {
+ finishDrag()
+ } else {
+ self.attachDragStart = nil
+ if hadPendingClick && self.state.mode != .expanded {
+ self.fsm.click() // FSM petit→home; onTransition calls expand(to:)
+ }
+ }
+ }
+ return event
+ }
+ NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { _ in
+ finishDrag()
+ }
+
+ // Global hotkey to show island
+ NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in
+ Task { @MainActor in
+ guard let self, self.state.hotkeyEnabled else { return }
+ let pressed = event.modifierFlags.intersection([.command, .control, .option, .shift]).rawValue
+ guard pressed == self.state.hotkeyFlags, event.keyCode == self.state.hotkeyCode else { return }
+ if self.state.mode == .hidden || self.state.mode == .compact {
+ self.expand(to: .overview)
+ }
+ }
+ }
+
+ // Track last external app for window context capture
+ let ourBundle = Bundle.main.bundleIdentifier ?? ""
+ NSWorkspace.shared.notificationCenter.addObserver(
+ forName: NSWorkspace.didActivateApplicationNotification,
+ object: nil, queue: .main
+ ) { [weak self] note in
+ guard let self else { return }
+ if let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
+ app.bundleIdentifier != ourBundle {
+ self.state.lastExternalApp = app
+ }
+ }
+ }
+
+ // MARK: - Drag ghost window (Mochi follows cursor during drag)
+
+ private func showDragGhost() {
+ guard dragGhostPanel == nil else { return }
+ // Same size as compact bot: diameter=20 → canvasSize≈33, scale 2× for grab comfort
+ let canvasSize: CGFloat = 40 / 0.6 // ~67
+ dragGhostSize = canvasSize
+
+ let mouse = NSEvent.mouseLocation
+ let s = dragGhostSize
+ ghostCurrentOrigin = NSPoint(x: mouse.x - s/2, y: mouse.y - s/2)
+
+ let panel = NSPanel(
+ contentRect: NSRect(x: ghostCurrentOrigin.x, y: ghostCurrentOrigin.y, width: s, height: s),
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered,
+ defer: false
+ )
+ panel.backgroundColor = .clear
+ panel.isOpaque = false
+ panel.hasShadow = false
+ panel.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.mainMenuWindow)) + 4)
+ panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
+ panel.ignoresMouseEvents = true
+
+ let hosting = NSHostingView(
+ rootView: GhostBotView(canvasSize: canvasSize)
+ )
+ hosting.frame = NSRect(x: 0, y: 0, width: s, height: s)
+ panel.contentView = hosting
+ panel.alphaValue = 0
+ panel.orderFront(nil)
+ dragGhostPanel = panel
+ AppState.shared.isDraggingBot = true
+
+ // Fade + scale-in handled by GhostBotView SwiftUI animation;
+ // also fade in the window itself for extra smoothness
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.18
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ panel.animator().alphaValue = 1
+ }
+ }
+
+ private func hideDragGhost() {
+ dragGhostPanel?.close()
+ dragGhostPanel = nil
+ highlightPanel?.close()
+ highlightPanel = nil
+ highlightWindowPid = 0
+ AppState.shared.isDraggingBot = false
+ }
+
+ private func updateDragGhost() {
+ guard let panel = dragGhostPanel else { return }
+ let s = dragGhostSize
+ let mouse = NSEvent.mouseLocation
+ // Direct follow — bot is "held", no trailing lag
+ ghostCurrentOrigin = NSPoint(x: mouse.x - s/2, y: mouse.y - s/2)
+ panel.setFrameOrigin(ghostCurrentOrigin)
+ }
+
+ // MARK: - Window highlight overlay (white border on target window during drag)
+
+ private func updateWindowHighlight() {
+ let mouse = NSEvent.mouseLocation
+ guard let (appKitBounds, pid) = windowBoundsAtScreenPoint(mouse) else {
+ // Fade out + close if no window under cursor
+ if let old = highlightPanel {
+ let captured = old
+ highlightPanel = nil
+ highlightWindowPid = 0
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.12
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeIn)
+ captured.animator().alphaValue = 0
+ }, completionHandler: { captured.close() })
+ }
+ return
+ }
+
+ if pid == highlightWindowPid, let existing = highlightPanel {
+ // Same window — just track position (windows rarely move, instant is fine)
+ existing.setFrame(appKitBounds, display: false)
+ } else {
+ // New window — close old immediately, fade-in new
+ highlightPanel?.close()
+ highlightPanel = nil
+ highlightWindowPid = pid
+
+ let panel = NSPanel(
+ contentRect: appKitBounds,
+ styleMask: [.borderless, .nonactivatingPanel],
+ backing: .buffered, defer: false
+ )
+ panel.backgroundColor = .clear
+ panel.isOpaque = false
+ panel.hasShadow = false
+ panel.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.mainMenuWindow)) + 2)
+ panel.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
+ panel.ignoresMouseEvents = true
+
+ let hosting = NSHostingView(rootView:
+ RoundedRectangle(cornerRadius: 12)
+ .stroke(Color.white.opacity(0.75), lineWidth: 3)
+ .shadow(color: Color.white.opacity(0.5), radius: 16)
+ .padding(2)
+ .ignoresSafeArea()
+ )
+ hosting.frame = CGRect(origin: .zero, size: appKitBounds.size)
+ hosting.autoresizingMask = [.width, .height]
+ panel.contentView = hosting
+ panel.alphaValue = 0
+ panel.orderFront(nil)
+ highlightPanel = panel
+
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.14
+ ctx.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ panel.animator().alphaValue = 1
+ }
+ }
+ }
+
+ private func windowBoundsAtScreenPoint(_ screenPoint: NSPoint) -> (CGRect, pid_t)? {
+ guard let screen = window?.screen ?? NSScreen.main else { return nil }
+ let screenMaxY = screen.frame.maxY
+ let cgPoint = CGPoint(x: screenPoint.x, y: screenMaxY - screenPoint.y)
+
+ guard let list = CGWindowListCopyWindowInfo(
+ [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID
+ ) as? [[String: Any]] else { return nil }
+
+ let ourBundle = Bundle.main.bundleIdentifier ?? ""
+ for info in list {
+ guard let b = info[kCGWindowBounds as String] as? [String: Any],
+ let x = b["X"] as? CGFloat, let y = b["Y"] as? CGFloat,
+ let w = b["Width"] as? CGFloat, let h = b["Height"] as? CGFloat else { continue }
+ guard CGRect(x: x, y: y, width: w, height: h).contains(cgPoint) else { continue }
+ let pid = info[kCGWindowOwnerPID as String] as? pid_t ?? 0
+ guard let app = NSRunningApplication(processIdentifier: pid),
+ app.bundleIdentifier != ourBundle,
+ app.activationPolicy == .regular else { continue }
+ // CG → AppKit: flip Y
+ return (CGRect(x: x, y: screenMaxY - y - h, width: w, height: h), pid)
+ }
+ return nil
+ }
+
+ // MARK: - Window context at screen point (for drag-attach)
+
+ private func windowContextAtPoint(_ screenPoint: NSPoint) -> PromptContext? {
+ let screen = window?.screen ?? NSScreen.main
+ // CGWindowList uses top-left origin; NSEvent.mouseLocation uses bottom-left
+ let screenMaxY = screen?.frame.maxY ?? NSScreen.main!.frame.maxY
+ let cgPoint = CGPoint(x: screenPoint.x, y: screenMaxY - screenPoint.y)
+
+ guard let windowList = CGWindowListCopyWindowInfo(
+ [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID
+ ) as? [[String: Any]] else { return nil }
+
+ let ourBundle = Bundle.main.bundleIdentifier ?? ""
+
+ for info in windowList {
+ guard let b = info[kCGWindowBounds as String] as? [String: Any],
+ let x = b["X"] as? CGFloat, let y = b["Y"] as? CGFloat,
+ let w = b["Width"] as? CGFloat, let h = b["Height"] as? CGFloat else { continue }
+ guard CGRect(x: x, y: y, width: w, height: h).contains(cgPoint) else { continue }
+
+ let pid = info[kCGWindowOwnerPID as String] as? pid_t ?? 0
+ guard let app = NSRunningApplication(processIdentifier: pid),
+ app.bundleIdentifier != ourBundle,
+ app.activationPolicy == .regular else { continue }
+
+ return WindowContextCapture.captureActive(from: app)
+ }
+ return nil
+ }
+
+ // MARK: - Coordinate conversion: window (AppKit, y-up) → island coords (y-down, 0,0 = island top-left)
+
+ func windowToIsland(_ loc: CGPoint) -> CGPoint {
+ let panelH = window?.frame.height ?? 320
+ let panelW = window?.frame.width ?? 720
+ let islandLeft = (panelW - IslandConst.expandedWidth) / 2
+ // Island is glued to panel top; its bottom in AppKit = panelH - 176
+ return CGPoint(
+ x: loc.x - islandLeft,
+ y: panelH - loc.y // AppKit y is from bottom; island y from top
+ )
+ }
+
+ // MARK: - Helpers
+
+ func defaultView() -> IslandView {
+ state.tasks.isEmpty ? .empty : .overview
+ }
+
+ func baseMode() -> IslandMode {
+ guard state.isPresent else { return .hidden }
+ return state.tasks.isEmpty ? .hidden : .compact
+ }
+
+ // MARK: - Activity reset (call on any user interaction in island)
+
+ func resetActivity() {
+ state.lastActivity = .now
+ }
+
+ // MARK: - Finished task pin (5.2s)
+
+ func pinForFinished(taskId: String) {
+ state.isPinned = true
+ finishedPinTimer?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self else { return }
+ self.state.removeTask(id: taskId)
+ self.state.isPinned = false
+ self.collapse()
+ }
+ finishedPinTimer = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5.2, execute: item)
+ }
+
+ // MARK: - Dizzy recovery (triggered by BotEngine.slap via .botDizzy)
+
+ private func handleDizzy() {
+ let prevView = state.view
+ state.stateOverride = .dizzy
+ expand(to: .confused)
+ confusedRecoveryTimer?.cancel()
+ let recovery = DispatchWorkItem { [weak self] in
+ guard let self else { return }
+ self.state.stateOverride = nil
+ if self.state.view == .confused {
+ let fallback = self.state.tasks.isEmpty ? IslandView.empty : .overview
+ self.state.view = (prevView == .confused) ? fallback : prevView
+ }
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+ }
+ confusedRecoveryTimer = recovery
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3.3, execute: recovery)
+ }
+
+ // MARK: - Bot hit test (for slap trigger)
+
+ private func isBotHit(_ windowPoint: CGPoint) -> Bool {
+ let s = AppState.shared
+ let panelH = window?.frame.height ?? 320
+ let panelW = window?.frame.width ?? 720
+ let (islandW, fixedH) = islandSize(mode: s.mode, view: s.view,
+ progress: s.uploadProgress, nw: notchW, nh: notchH)
+ // Chat view resizes dynamically — must match IslandContainer.chatPromptHeight
+ let islandH: CGFloat
+ if s.mode == .expanded && s.view == .prompt {
+ let base: CGFloat = 240
+ let perMsg: CGFloat = 40
+ islandH = min(300, base + CGFloat(s.chatHistory.count) * perMsg)
+ } else {
+ islandH = fixedH
+ }
+ let islandMinX = (panelW - islandW) / 2
+ let (cx, cy, diameter, _) = botPosition(mode: s.mode, view: s.view,
+ islandW: islandW, islandH: islandH,
+ uploadProgress: s.uploadProgress)
+ let radius = (diameter / 0.6) / 2
+ // botPosition cy is from island TOP; panel AppKit coords have y=0 at bottom
+ // island top in AppKit coords = panelH (island glued to top of panel/screen)
+ let botX = islandMinX + cx
+ let botY = panelH - cy
+ let dx = windowPoint.x - botX
+ let dy = windowPoint.y - botY
+ return dx*dx + dy*dy <= radius * radius
+ }
+
+ // MARK: - Notch detection (static)
+
+ static func notchScreen() -> NSScreen? {
+ NSScreen.screens.first { $0.safeAreaInsets.top > 0 }
+ }
+
+ static func notchWidth(for screen: NSScreen) -> CGFloat {
+ let aux = (screen.auxiliaryTopLeftArea?.width ?? 0) +
+ (screen.auxiliaryTopRightArea?.width ?? 0)
+ let w = screen.frame.width - aux
+ return w > 0 ? w : IslandConst.notchWidth
+ }
+
+ static func notchHeight(for screen: NSScreen) -> CGFloat {
+ let h = screen.safeAreaInsets.top
+ return h > 0 ? h : IslandConst.notchHeight
+ }
+
+ nonisolated func cleanup() {
+ // Called explicitly before release if needed
+ }
+}
+
+// MARK: - IslandPanel
+
+final class IslandPanel: NSPanel {
+ var notchWidth: CGFloat = IslandConst.notchWidth
+ var notchHeight: CGFloat = IslandConst.notchHeight
+
+ override var canBecomeKey: Bool { true }
+ override var canBecomeMain: Bool { false }
+
+ /// Allow panel to sit in the menu bar / notch area — don't let macOS push it down.
+ override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect {
+ return frameRect
+ }
+
+ func currentIslandFrame(nw: CGFloat, nh: CGFloat) -> CGRect {
+ let s = AppState.shared
+ let (w, fixedH) = islandSize(mode: s.mode, view: s.view,
+ progress: s.uploadProgress, nw: nw, nh: nh)
+ let h: CGFloat
+ if s.mode == .expanded && s.view == .prompt {
+ let base: CGFloat = 240
+ let perMsg: CGFloat = 40
+ h = min(300, base + CGFloat(s.chatHistory.count) * perMsg)
+ } else {
+ h = fixedH
+ }
+ return CGRect(x: (frame.width - w) / 2, y: frame.height - h, width: w, height: h)
+ }
+}
+
+// MARK: - Ghost bot view (animated scale-in on appear)
+
+struct GhostBotView: View {
+ let canvasSize: CGFloat
+ @State private var scale: CGFloat = 0.35
+
+ var body: some View {
+ BotCanvasView(state: AppState.shared)
+ .frame(width: canvasSize, height: canvasSize)
+ .scaleEffect(scale)
+ .onAppear {
+ withAnimation(.spring(response: 0.28, dampingFraction: 0.55)) {
+ scale = 1.0
+ }
+ }
+ }
+}
+
+// MARK: - Notification names
+
+extension Notification.Name {
+ static let triggerEmote = Notification.Name("notchBuddy.triggerEmote")
+ static let triggerSlap = Notification.Name("notchBuddy.triggerSlap")
+ static let botDizzy = Notification.Name("notchBuddy.botDizzy")
+ static let botGreet = Notification.Name("notchBuddy.botGreet")
+ static let botBlink = Notification.Name("notchBuddy.botBlink")
+ static let botSetTgEs = Notification.Name("notchBuddy.botSetTgEs")
+ static let botGulp = Notification.Name("notchBuddy.botGulp")
+ static let botMorphTo = Notification.Name("notchBuddy.botMorphTo")
+ static let islandAction = Notification.Name("notchBuddy.islandAction")
+ static let islandCollapse = Notification.Name("notchBuddy.islandCollapse")
+ static let openFullSettings = Notification.Name("notchBuddy.openFullSettings")
+ static let hookReveal = Notification.Name("notchBuddy.hookReveal")
+ // Greeting ↔ IslandWindowController
+ static let greetComplete = Notification.Name("notchBuddy.greetComplete")
+ static let greetingHover = Notification.Name("notchBuddy.greetingHover")
+ static let greetingInterrupt = Notification.Name("notchBuddy.greetingInterrupt")
+}
+
+// MARK: - islandSize (takes real notch dimensions)
+
+func islandSize(mode: IslandMode, view: IslandView,
+ progress: Double = 0,
+ nw: CGFloat = IslandConst.notchWidth,
+ nh: CGFloat = IslandConst.notchHeight) -> (CGFloat, CGFloat) {
+ switch mode {
+ case .hidden: return (nw, nh)
+ case .compact: return (nw + 160, nh)
+ case .expanded:
+ let layout = IslandConst.viewLayouts[view]!
+ return (IslandConst.expandedWidth, layout.height)
+ }
+}
diff --git a/NotchBuddy/Sources/App/N8nPoller.swift b/NotchBuddy/Sources/App/N8nPoller.swift
new file mode 100644
index 00000000..396c2ec1
--- /dev/null
+++ b/NotchBuddy/Sources/App/N8nPoller.swift
@@ -0,0 +1,272 @@
+import Foundation
+
+// MARK: - N8nPoller
+// Polls n8n for the latest workflow execution every 15s.
+// Tries /api/v1/executions first, falls back to /rest/executions.
+// On a new terminal execution: fetches full details, stores [name, detail] in steps.
+
+final class N8nPoller: @unchecked Sendable {
+ static let shared = N8nPoller()
+ private var timer: DispatchSourceTimer?
+ private var lastExecutionId: String = ""
+
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 3, repeating: 15)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ // MARK: - Poll list endpoint
+
+ private func poll() {
+ guard let apiKey = KeychainStore.shared.get("n8n-api-key"),
+ let rawBase = KeychainStore.shared.get("n8n-url") else {
+ n8nLog("No API key or URL configured")
+ return
+ }
+ let base = rawBase.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ let endpoints = [
+ "\(base)/api/v1/executions?limit=1&includeData=false",
+ "\(base)/rest/executions?limit=1&includeData=false",
+ ]
+ tryList(endpoints, apiKey: apiKey, base: base, idx: 0)
+ }
+
+ private func tryList(_ urls: [String], apiKey: String, base: String, idx: Int) {
+ guard idx < urls.count, let url = URL(string: urls[idx]) else {
+ n8nLog("All list endpoints failed")
+ return
+ }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue(apiKey, forHTTPHeaderField: "X-N8N-API-KEY")
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+ n8nLog("Polling \(url.absoluteString)")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if let error {
+ self.n8nLog("Network error: \(error.localizedDescription)")
+ self.tryList(urls, apiKey: apiKey, base: base, idx: idx + 1)
+ return
+ }
+ guard let data else {
+ self.tryList(urls, apiKey: apiKey, base: base, idx: idx + 1)
+ return
+ }
+ let preview = String(data: data.prefix(300), encoding: .utf8) ?? "?"
+ self.n8nLog("HTTP \(code) · \(preview)")
+ guard code == 200 else {
+ self.tryList(urls, apiKey: apiKey, base: base, idx: idx + 1)
+ return
+ }
+ guard let json = try? JSONSerialization.jsonObject(with: data) else { return }
+
+ // Response is either { "data": [...] } or [...]
+ let items: [[String: Any]]
+ if let obj = json as? [String: Any], let arr = obj["data"] as? [[String: Any]] {
+ items = arr
+ } else if let arr = json as? [[String: Any]] {
+ items = arr
+ } else {
+ self.n8nLog("Unexpected response shape")
+ return
+ }
+
+ guard let first = items.first else { self.n8nLog("No executions found"); return }
+
+ let id: String
+ if let s = first["id"] as? String { id = s }
+ else if let n = first["id"] as? Int { id = "\(n)" }
+ else { self.n8nLog("No id in execution"); return }
+
+ guard id != self.lastExecutionId else {
+ self.n8nLog("Same id=\(id) — no change")
+ return
+ }
+
+ // Terminal check: use status field — more reliable than the `finished` bool
+ // (published workflows often have finished=false on error)
+ let status = first["status"] as? String ?? ""
+ let isTerminal = ["success", "error", "crashed", "canceled", "failed"].contains(status)
+ guard isTerminal else {
+ self.n8nLog("id=\(id) status=\(status.isEmpty ? "?" : status) — not terminal")
+ return
+ }
+
+ self.lastExecutionId = id
+ let success = status == "success"
+ self.n8nLog("New execution id=\(id) status=\(status)")
+
+ // Fetch full detail (includeData=true required in some n8n versions)
+ let detailUrls = [
+ "\(base)/api/v1/executions/\(id)?includeData=true",
+ "\(base)/api/v1/executions/\(id)",
+ "\(base)/rest/executions/\(id)?includeData=true",
+ "\(base)/rest/executions/\(id)",
+ ]
+ self.fetchDetail(detailUrls, apiKey: apiKey, success: success, idx: 0)
+ }.resume()
+ }
+
+ // MARK: - Fetch full execution detail
+
+ private func fetchDetail(_ urls: [String], apiKey: String, success: Bool, idx: Int) {
+ guard idx < urls.count, let url = URL(string: urls[idx]) else {
+ dispatch(success: success, name: "Workflow", detail: nil)
+ return
+ }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue(apiKey, forHTTPHeaderField: "X-N8N-API-KEY")
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, _ in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200 else {
+ self.n8nLog("Detail HTTP \(code) for \(url.absoluteString)")
+ self.fetchDetail(urls, apiKey: apiKey, success: success, idx: idx + 1)
+ return
+ }
+ // Log raw response to help diagnose structure issues
+ let rawPreview = String(data: data.prefix(600), encoding: .utf8) ?? "?"
+ self.n8nLog("Detail raw: \(rawPreview)")
+
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ self.fetchDetail(urls, apiKey: apiKey, success: success, idx: idx + 1)
+ return
+ }
+ let name = self.extractWorkflowName(from: json)
+ let detail = self.parseDetail(from: json, success: success)
+ self.n8nLog("Parsed: \(name) · \(detail ?? "no detail")")
+ self.dispatch(success: success, name: name, detail: detail)
+ }.resume()
+ }
+
+ private func extractWorkflowName(from json: [String: Any]) -> String {
+ if let wd = json["workflowData"] as? [String: Any], let name = wd["name"] as? String { return name }
+ if let name = json["name"] as? String { return name }
+ return "Workflow"
+ }
+
+ // MARK: - Parse execution output / error message
+
+ private func parseDetail(from json: [String: Any], success: Bool) -> String? {
+ guard let execData = json["data"] as? [String: Any],
+ let resultData = execData["resultData"] as? [String: Any] else { return nil }
+
+ if success {
+ return parseSuccessDetail(resultData: resultData)
+ } else {
+ return parseErrorDetail(resultData: resultData)
+ }
+ }
+
+ private func parseErrorDetail(resultData: [String: Any]) -> String? {
+ // Top-level error
+ if let error = resultData["error"] as? [String: Any] {
+ let msg = error["message"] as? String ?? ""
+ if let node = (error["node"] as? [String: Any])?["name"] as? String, !node.isEmpty {
+ return "\(node)\n\(msg)"
+ }
+ return msg
+ }
+ // Scan runData for first node error
+ if let runData = resultData["runData"] as? [String: Any] {
+ for (nodeName, runs) in runData {
+ if let runs = runs as? [[String: Any]],
+ let run = runs.first,
+ let err = run["error"] as? [String: Any],
+ let msg = err["message"] as? String {
+ return "\(nodeName)\n\(msg)"
+ }
+ }
+ }
+ return nil
+ }
+
+ private func parseSuccessDetail(resultData: [String: Any]) -> String? {
+ guard let lastNode = resultData["lastNodeExecuted"] as? String,
+ let runData = resultData["runData"] as? [String: Any],
+ let nodeRuns = runData[lastNode] as? [[String: Any]],
+ let run = nodeRuns.first,
+ let data = run["data"] as? [String: Any],
+ let main = data["main"] as? [[[String: Any]]],
+ let items = main.first else { return nil }
+
+ let count = items.count
+ let header = "→ \(lastNode) · \(count) item\(count == 1 ? "" : "s")"
+
+ // Preview first item's JSON keys (up to 4)
+ if let firstItem = items.first,
+ let jsonObj = firstItem["json"] as? [String: Any], !jsonObj.isEmpty {
+ let lines = jsonObj.prefix(4).map { "\($0.key): \(fmtValue($0.value))" }
+ return "\(header)\n\(lines.joined(separator: "\n"))"
+ }
+ return header
+ }
+
+ private func fmtValue(_ v: Any) -> String {
+ if let s = v as? String { return String(s.prefix(50)) }
+ if let n = v as? NSNumber { return n.stringValue }
+ if let a = v as? [Any] { return "[\(a.count)]" }
+ if v is [String: Any] { return "{…}" }
+ return "\(v)"
+ }
+
+ // MARK: - Dispatch to main
+
+ private func dispatch(success: Bool, name: String, detail: String?) {
+ DispatchQueue.main.async { self.handleExecution(success: success, name: name, detail: detail) }
+ }
+
+ @MainActor
+ private func handleExecution(success: Bool, name: String, detail: String?) {
+ let state = AppState.shared
+
+ // Apply workflow filter (empty = all workflows)
+ if !state.n8nWorkflowFilter.isEmpty && !state.n8nWorkflowFilter.contains(name) { return }
+
+ guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_n8n" }) else { return }
+ let focused = state.focusId == "integration_n8n"
+
+ state.tasks[idx].state = success ? .finished : .error
+ state.tasks[idx].steps = detail != nil ? [name, detail!] : [name]
+
+ if !focused {
+ state.tasks[idx].pillBadge = success ? .finished : .error
+ }
+ SoundEngine.shared.play(success ? "finish" : "error")
+
+ // Auto-clear after 60s (user needs time to read detail)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
+ guard let i = state.tasks.firstIndex(where: { $0.id == "integration_n8n" }) else { return }
+ guard state.tasks[i].state == .finished || state.tasks[i].state == .error else { return }
+ state.tasks[i].state = .idle
+ state.tasks[i].steps = []
+ state.tasks[i].pillBadge = nil
+ }
+ }
+
+ // MARK: - Logging
+
+ private func n8nLog(_ message: String) {
+ let logsDir = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Logs/NotchBuddy")
+ try? FileManager.default.createDirectory(at: logsDir, withIntermediateDirectories: true)
+ let logFile = logsDir.appendingPathComponent("n8n.log")
+ let f = DateFormatter(); f.dateFormat = "HH:mm:ss"
+ let line = "\(f.string(from: Date())) · \(message)\n"
+ guard let data = line.data(using: .utf8) else { return }
+ if FileManager.default.fileExists(atPath: logFile.path) {
+ if let fh = try? FileHandle(forWritingTo: logFile) {
+ fh.seekToEndOfFile(); fh.write(data); try? fh.close()
+ }
+ } else { try? data.write(to: logFile) }
+ }
+}
diff --git a/NotchBuddy/Sources/App/NotchBuddyApp.swift b/NotchBuddy/Sources/App/NotchBuddyApp.swift
new file mode 100644
index 00000000..2adffe99
--- /dev/null
+++ b/NotchBuddy/Sources/App/NotchBuddyApp.swift
@@ -0,0 +1,13 @@
+import SwiftUI
+import AppKit
+
+@main
+struct NotchBuddyApp: App {
+ @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
+
+ var body: some Scene {
+ Settings {
+ SettingsView()
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/App/NotionPoller.swift b/NotchBuddy/Sources/App/NotionPoller.swift
new file mode 100644
index 00000000..1e6b7c3e
--- /dev/null
+++ b/NotchBuddy/Sources/App/NotionPoller.swift
@@ -0,0 +1,99 @@
+import Foundation
+
+final class NotionPoller: @unchecked Sendable {
+ static let shared = NotionPoller()
+ private var timer: DispatchSourceTimer?
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 9, repeating: 300)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ func pollNow() { poll() }
+
+ private func poll() {
+ guard let token = KeychainStore.shared.get("notion-api-key") else { return }
+ guard let url = URL(string: "https://api.notion.com/v1/search") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.httpMethod = "POST"
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("2022-06-28", forHTTPHeaderField: "Notion-Version")
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ let body: [String: Any] = [
+ "sort": ["direction": "descending", "timestamp": "last_edited_time"],
+ "page_size": 3
+ ]
+ req.httpBody = try? JSONSerialization.data(withJSONObject: body)
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if code != 200 {
+ let msg: String
+ if code == 401 { msg = "Invalid API key (401)" }
+ else if code == 0 { msg = error?.localizedDescription ?? "No connection" }
+ else { msg = "API error \(code)" }
+ DispatchQueue.main.async { AppState.shared.notionError = msg }
+ return
+ }
+ guard let data,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let results = json["results"] as? [[String: Any]] else { return }
+
+ let pages = results.compactMap { self.parsePage($0) }
+ DispatchQueue.main.async {
+ AppState.shared.notionError = nil
+ AppState.shared.notionPages = pages
+ AppState.shared.notionLoaded = true
+ }
+ }.resume()
+ }
+
+ private func parsePage(_ obj: [String: Any]) -> NotionPage? {
+ guard let id = obj["id"] as? String else { return nil }
+ let objType = obj["object"] as? String ?? "page"
+
+ var title = "Untitled"
+ if objType == "database" {
+ if let arr = obj["title"] as? [[String: Any]],
+ let text = arr.first?["plain_text"] as? String, !text.isEmpty {
+ title = text
+ }
+ } else {
+ if let props = obj["properties"] as? [String: Any] {
+ for (_, val) in props {
+ guard let prop = val as? [String: Any],
+ (prop["type"] as? String) == "title",
+ let arr = prop["title"] as? [[String: Any]],
+ let text = arr.first?["plain_text"] as? String, !text.isEmpty else { continue }
+ title = text; break
+ }
+ }
+ }
+
+ var emoji: String? = nil
+ if let icon = obj["icon"] as? [String: Any],
+ (icon["type"] as? String) == "emoji",
+ let em = icon["emoji"] as? String {
+ emoji = em
+ }
+
+ guard let editedStr = obj["last_edited_time"] as? String else { return nil }
+ let iso = ISO8601DateFormatter()
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ var lastEdited = iso.date(from: editedStr)
+ if lastEdited == nil {
+ let iso2 = ISO8601DateFormatter(); iso2.formatOptions = [.withInternetDateTime]
+ lastEdited = iso2.date(from: editedStr)
+ }
+ guard let lastEdited else { return nil }
+
+ let pageURL = (obj["url"] as? String) ?? "https://notion.so"
+ return NotionPage(id: id, title: title, emoji: emoji, lastEditedAt: lastEdited, url: pageURL)
+ }
+}
diff --git a/NotchBuddy/Sources/App/ResendPoller.swift b/NotchBuddy/Sources/App/ResendPoller.swift
new file mode 100644
index 00000000..a1f6e391
--- /dev/null
+++ b/NotchBuddy/Sources/App/ResendPoller.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+final class ResendPoller: @unchecked Sendable {
+ static let shared = ResendPoller()
+ private var timer: DispatchSourceTimer?
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 6, repeating: 60)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ private func poll() {
+ guard let apiKey = KeychainStore.shared.get("resend-api-key") else { return }
+ guard let url = URL(string: "https://api.resend.com/emails?limit=100") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, _ in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200 else { return }
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let rawList = json["data"] as? [[String: Any]] else { return }
+
+ let total = (json["total"] as? Int) ?? (json["count"] as? Int)
+ let emails = rawList.compactMap { self.parseEmail($0) }
+
+ DispatchQueue.main.async {
+ AppState.shared.resendEmails = Array(emails.prefix(5))
+ AppState.shared.resendTotal = total ?? (emails.isEmpty ? nil : emails.count)
+ }
+ }.resume()
+ }
+
+ private func parseEmail(_ d: [String: Any]) -> ResendEmail? {
+ guard let id = d["id"] as? String,
+ let createdAt = d["created_at"] as? String else { return nil }
+
+ let to: [String]
+ if let arr = d["to"] as? [String] { to = arr }
+ else if let single = d["to"] as? String { to = [single] }
+ else { to = [] }
+
+ let subject = (d["subject"] as? String) ?? ""
+ let lastEvent = (d["last_event"] as? String) ?? ""
+
+ // Parse ISO8601 date
+ let formatter = ISO8601DateFormatter()
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ let date = formatter.date(from: createdAt)
+ ?? ISO8601DateFormatter().date(from: createdAt)
+ ?? Date()
+
+ return ResendEmail(id: id, to: to, subject: subject, createdAt: date, lastEvent: lastEvent)
+ }
+}
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
new file mode 100644
index 00000000..ba2bd5c2
--- /dev/null
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -0,0 +1,564 @@
+import SwiftUI
+import ServiceManagement
+import AppKit
+
+struct SettingsView: View {
+ @ObservedObject private var state = AppState.shared
+ @State private var apiKey: String = KeychainStore.shared.get("anthropic-api-key") ?? ""
+ @State private var launchAtStartup: Bool = (SMAppService.mainApp.status == .enabled)
+ @State private var statusMessage: String = ""
+ @State private var showDiff: Bool = false
+ @State private var pendingHookJSON: String = ""
+
+ // Integration keys
+ @State private var resendKey: String = KeychainStore.shared.get("resend-api-key") ?? ""
+ @State private var resendFrom: String = KeychainStore.shared.get("resend-from") ?? ""
+ @State private var n8nUrl: String = KeychainStore.shared.get("n8n-url") ?? ""
+ @State private var n8nKey: String = KeychainStore.shared.get("n8n-api-key") ?? ""
+ @State private var vercelToken: String = KeychainStore.shared.get("vercel-token") ?? ""
+ @State private var githubToken: String = KeychainStore.shared.get("github-token") ?? ""
+ @State private var stripeKey: String = KeychainStore.shared.get("stripe-api-key") ?? ""
+ @State private var calcomKey: String = KeychainStore.shared.get("calcom-api-key") ?? ""
+ @State private var notionKey: String = KeychainStore.shared.get("notion-api-key") ?? ""
+
+ // Hotkey
+ @State private var hotkeyFlags: UInt = AppState.shared.hotkeyFlags
+ @State private var hotkeyCode: UInt16 = AppState.shared.hotkeyCode
+
+ // Vercel project filter
+ @State private var vercelProjects: [String] = []
+ @State private var loadingVercel: Bool = false
+
+ // n8n workflow filter
+ @State private var n8nWorkflows: [String] = []
+ @State private var loadingN8n: Bool = false
+
+ // Bindings in minutes for the absence field
+ private var absenceMinutes: Binding<Double> {
+ Binding(
+ get: { state.absenceInterval / 60 },
+ set: { state.absenceInterval = max(1, $0) * 60 }
+ )
+ }
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+
+ // MARK: API
+ GroupBox("Anthropic API") {
+ VStack(alignment: .leading, spacing: 8) {
+ SecureField("API key (sk-ant-…)", text: $apiKey)
+ .textFieldStyle(.roundedBorder)
+ Button("Save") {
+ KeychainStore.shared.set("anthropic-api-key", value: apiKey)
+ statusMessage = "✓ Key saved."
+ }
+ .buttonStyle(.borderedProminent)
+ }
+ .padding(6)
+ }
+
+ // MARK: Hooks
+ GroupBox("Hooks Claude Code") {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("nb-hook : \(HookServer.hookScriptPath)")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+
+ HStack(spacing: 10) {
+ Button("Install hooks") { installHooks() }
+ .buttonStyle(.borderedProminent)
+ Button("Uninstall") { uninstallHooks() }
+ .buttonStyle(.bordered)
+ }
+
+ if showDiff {
+ ScrollView {
+ Text(pendingHookJSON)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 140)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+
+ HStack {
+ Button("Confirm & write") { confirmInstall() }
+ .buttonStyle(.borderedProminent)
+ Button("Cancel") { showDiff = false; pendingHookJSON = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ // MARK: Integrations
+ GroupBox("Integrations") {
+ VStack(alignment: .leading, spacing: 14) {
+
+ // Resend
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#22C55E")).frame(width: 8, height: 8)
+ Text("Resend").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("API key (re_…)", text: $resendKey)
+ .textFieldStyle(.roundedBorder)
+ TextField("From address ([email protected])", text: $resendFrom)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ // n8n
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#F29B38")).frame(width: 8, height: 8)
+ Text("n8n").font(.system(size: 12, weight: .semibold))
+ }
+ TextField("Instance URL (https://…)", text: $n8nUrl)
+ .textFieldStyle(.roundedBorder)
+ SecureField("API key", text: $n8nKey)
+ .textFieldStyle(.roundedBorder)
+ IntegrationFilterRow(
+ label: "Workflows",
+ items: n8nWorkflows,
+ filter: $state.n8nWorkflowFilter,
+ loading: loadingN8n,
+ onLoad: loadN8nWorkflows
+ )
+ }
+
+ // Vercel
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#7C5CFF")).frame(width: 8, height: 8)
+ Text("Vercel").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("Token", text: $vercelToken)
+ .textFieldStyle(.roundedBorder)
+ IntegrationFilterRow(
+ label: "Projects",
+ items: vercelProjects,
+ filter: $state.vercelProjectFilter,
+ loading: loadingVercel,
+ onLoad: loadVercelProjects
+ )
+ }
+
+ // GitHub
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#F4505E")).frame(width: 8, height: 8)
+ Text("GitHub").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("Personal Access Token", text: $githubToken)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ // Stripe
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#0570DE")).frame(width: 8, height: 8)
+ Text("Stripe").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("Secret key (sk_live_… or sk_test_…)", text: $stripeKey)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ // Cal.com
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#C9956A")).frame(width: 8, height: 8)
+ Text("Cal.com").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("API key (cal_live_…)", text: $calcomKey)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ // Notion
+ VStack(alignment: .leading, spacing: 5) {
+ HStack(spacing: 6) {
+ Circle().fill(Color(hex: "#E8E8E8")).frame(width: 8, height: 8)
+ Text("Notion").font(.system(size: 12, weight: .semibold))
+ }
+ SecureField("Integration token (secret_…)", text: $notionKey)
+ .textFieldStyle(.roundedBorder)
+ }
+
+ Button("Save integrations") { saveIntegrations() }
+ .buttonStyle(.borderedProminent)
+ }
+ .padding(6)
+ }
+
+ // MARK: Son
+ GroupBox("Sound") {
+ VStack(alignment: .leading, spacing: 10) {
+ Toggle("Enable sounds", isOn: $state.soundEnabled)
+ HStack(spacing: 8) {
+ Text("Volume")
+ .frame(width: 56, alignment: .leading)
+ Slider(value: $state.soundVolume, in: 0...0.2)
+ .disabled(!state.soundEnabled)
+ Text("\(Int(state.soundVolume / 0.2 * 100)) %")
+ .frame(width: 36, alignment: .trailing)
+ .monospacedDigit()
+ }
+ }
+ .padding(6)
+ }
+
+ // MARK: Timings
+ GroupBox("Behavior") {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 8) {
+ Text("Close after")
+ TextField("60", value: $state.autoCloseInterval, format: .number)
+ .textFieldStyle(.roundedBorder)
+ .frame(width: 64)
+ Text("s inactive")
+ }
+ HStack(spacing: 8) {
+ Text("Hide after")
+ TextField("3", value: absenceMinutes, format: .number)
+ .textFieldStyle(.roundedBorder)
+ .frame(width: 48)
+ Text("min without movement")
+ }
+ }
+ .padding(6)
+ }
+
+ // MARK: Active pills
+ GroupBox("Active pills") {
+ VStack(alignment: .leading, spacing: 10) {
+ HStack {
+ Text("VS Code")
+ .font(.system(size: 12, weight: .semibold))
+ Circle().fill(Color(hex: "#F5F6F8")).frame(width: 8, height: 8)
+ Spacer()
+ Text("Always active")
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ }
+
+ Divider()
+
+ Text("\(state.activeIntegrations.count)/4 slots used")
+ .font(.system(size: 11))
+ .foregroundColor(state.activeIntegrations.count >= 4 ? .orange : .secondary)
+
+ ForEach(AgentTask.toggleableIntegrationIds, id: \.self) { id in
+ let task = AgentTask.integrationAgents.first { $0.id == id }!
+ let isOn = state.activeIntegrations.contains(id)
+ let atMax = state.activeIntegrations.count >= 4 && !isOn
+ HStack(spacing: 8) {
+ Circle()
+ .fill(Color(hex: task.color))
+ .frame(width: 10, height: 10)
+ Text(task.name)
+ .font(.system(size: 12))
+ .foregroundColor(atMax ? .secondary : .primary)
+ Spacer()
+ Toggle("", isOn: Binding(
+ get: { isOn },
+ set: { _ in state.toggleIntegration(id) }
+ ))
+ .labelsHidden()
+ .disabled(atMax)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ // MARK: Hotkey
+ GroupBox("Hotkey") {
+ VStack(alignment: .leading, spacing: 10) {
+ Toggle("Show island with shortcut", isOn: $state.hotkeyEnabled)
+ if state.hotkeyEnabled {
+ HStack(spacing: 8) {
+ Text("Shortcut")
+ .frame(width: 70, alignment: .leading)
+ ShortcutRecorderButton(flags: $hotkeyFlags, code: $hotkeyCode)
+ .onChange(of: hotkeyFlags) { _, v in state.hotkeyFlags = v }
+ .onChange(of: hotkeyCode) { _, v in state.hotkeyCode = v }
+ Text("presses this → island opens")
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ // MARK: Startup
+ GroupBox("Startup") {
+ Toggle("Launch at Mac startup", isOn: $launchAtStartup)
+ .onChange(of: launchAtStartup) { _, on in toggleStartup(on) }
+ .padding(6)
+ }
+
+ if !statusMessage.isEmpty {
+ Text(statusMessage)
+ .font(.system(size: 12))
+ .foregroundColor(statusMessage.hasPrefix("❌") ? .red : .secondary)
+ .padding(.horizontal, 2)
+ }
+
+ Spacer(minLength: 0)
+ }
+ .padding(20)
+ }
+ .frame(width: 480, height: 720)
+ }
+
+ // MARK: - Actions
+
+ private func toggleStartup(_ on: Bool) {
+ do {
+ if on { try SMAppService.mainApp.register() }
+ else { try SMAppService.mainApp.unregister() }
+ } catch {
+ statusMessage = "❌ Startup: \(error.localizedDescription)"
+ launchAtStartup = !on
+ }
+ }
+
+ private func installHooks() {
+ do {
+ pendingHookJSON = try HookServer.shared.previewClaudeHooks()
+ showDiff = true
+ statusMessage = "Review the JSON below before confirming."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmInstall() {
+ do {
+ try HookServer.shared.writeClaudeHooks()
+ showDiff = false
+ statusMessage = "✓ Hooks installed in ~/.claude/settings.json"
+ pendingHookJSON = ""
+ } catch {
+ statusMessage = "❌ Write error: \(error.localizedDescription)"
+ }
+ }
+
+ private func uninstallHooks() {
+ do {
+ try HookServer.shared.uninstallClaudeHooks()
+ statusMessage = "✓ Hooks removed."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func saveIntegrations() {
+ saveKey("resend-api-key", value: resendKey)
+ saveKey("resend-from", value: resendFrom)
+ saveKey("n8n-url", value: n8nUrl)
+ saveKey("n8n-api-key", value: n8nKey)
+ saveKey("vercel-token", value: vercelToken)
+ saveKey("github-token", value: githubToken)
+ saveKey("stripe-api-key", value: stripeKey)
+ saveKey("calcom-api-key", value: calcomKey)
+ saveKey("notion-api-key", value: notionKey)
+ statusMessage = "✓ Integration keys saved."
+ }
+
+ /// Saves non-empty value; removes only if key was previously set (explicit user clear).
+ private func saveKey(_ key: String, value: String) {
+ if value.isEmpty {
+ KeychainStore.shared.remove(key)
+ } else {
+ KeychainStore.shared.set(key, value: value)
+ }
+ }
+
+ // MARK: - Vercel project list
+
+ private func loadVercelProjects() {
+ guard let token = KeychainStore.shared.get("vercel-token") else {
+ statusMessage = "❌ Save Vercel token first."
+ return
+ }
+ loadingVercel = true
+ guard let url = URL(string: "https://api.vercel.com/v9/projects?limit=100") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ URLSession.shared.dataTask(with: req) { data, response, _ in
+ let names: [String]
+ if let data,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let projects = json["projects"] as? [[String: Any]] {
+ names = projects.compactMap { $0["name"] as? String }.sorted()
+ } else {
+ names = []
+ }
+ DispatchQueue.main.async {
+ self.vercelProjects = names
+ self.loadingVercel = false
+ if names.isEmpty { self.statusMessage = "❌ No Vercel projects found." }
+ }
+ }.resume()
+ }
+
+ // MARK: - n8n workflow list
+
+ private func loadN8nWorkflows() {
+ guard let apiKey = KeychainStore.shared.get("n8n-api-key"),
+ let rawBase = KeychainStore.shared.get("n8n-url") else {
+ statusMessage = "❌ Save n8n URL and API key first."
+ return
+ }
+ loadingN8n = true
+ let base = rawBase.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ let urls = ["\(base)/api/v1/workflows?limit=100", "\(base)/rest/workflows?limit=100"]
+ fetchN8nWorkflows(urls: urls, apiKey: apiKey, idx: 0)
+ }
+
+ private func fetchN8nWorkflows(urls: [String], apiKey: String, idx: Int) {
+ guard idx < urls.count, let url = URL(string: urls[idx]) else {
+ DispatchQueue.main.async { self.loadingN8n = false; self.statusMessage = "❌ No n8n workflows found." }
+ return
+ }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue(apiKey, forHTTPHeaderField: "X-N8N-API-KEY")
+ URLSession.shared.dataTask(with: req) { data, response, _ in
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200 else {
+ self.fetchN8nWorkflows(urls: urls, apiKey: apiKey, idx: idx + 1)
+ return
+ }
+ let items: [[String: Any]]
+ if let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let arr = obj["data"] as? [[String: Any]] { items = arr }
+ else if let arr = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] { items = arr }
+ else { items = [] }
+ let names = items.compactMap { $0["name"] as? String }.sorted()
+ DispatchQueue.main.async {
+ self.n8nWorkflows = names
+ self.loadingN8n = false
+ if names.isEmpty { self.statusMessage = "❌ No n8n workflows found." }
+ }
+ }.resume()
+ }
+}
+
+// MARK: - Integration filter row (reusable for Vercel / n8n)
+
+struct IntegrationFilterRow: View {
+ let label: String
+ let items: [String]
+ @Binding var filter: Set<String>
+ let loading: Bool
+ let onLoad: () -> Void
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 6) {
+ Text(label)
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ Spacer()
+ if loading {
+ ProgressView().scaleEffect(0.6)
+ } else {
+ Button(items.isEmpty ? "Load list" : "Refresh") { onLoad() }
+ .buttonStyle(.bordered)
+ .controlSize(.mini)
+ }
+ if !filter.isEmpty {
+ Button("Clear") { filter = [] }
+ .buttonStyle(.bordered)
+ .controlSize(.mini)
+ .foregroundColor(.secondary)
+ }
+ }
+ if !items.isEmpty {
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(items, id: \.self) { item in
+ Toggle(item, isOn: Binding(
+ get: { filter.isEmpty || filter.contains(item) },
+ set: { on in
+ if on { filter.insert(item) }
+ else {
+ // First click on any item: switch from "all" to explicit set
+ if filter.isEmpty { filter = Set(items).subtracting([item]) }
+ else { filter.remove(item) }
+ if filter.count == items.count { filter = [] } // all = empty
+ }
+ }
+ ))
+ .font(.system(size: 11))
+ .toggleStyle(.checkbox)
+ }
+ }
+ .padding(.leading, 4)
+ if !filter.isEmpty {
+ Text("Watching \(filter.count) of \(items.count)")
+ .font(.system(size: 10))
+ .foregroundColor(.secondary)
+ }
+ }
+ }
+ }
+}
+
+// MARK: - Shortcut recorder button
+
+struct ShortcutRecorderButton: View {
+ @Binding var flags: UInt
+ @Binding var code: UInt16
+ @State private var isRecording = false
+
+ var body: some View {
+ Button {
+ guard !isRecording else { return }
+ isRecording = true
+ var token: Any?
+ token = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
+ let mods = event.modifierFlags.intersection([.command, .control, .option, .shift])
+ guard !mods.isEmpty else { return event }
+ DispatchQueue.main.async {
+ self.flags = mods.rawValue
+ self.code = event.keyCode
+ self.isRecording = false
+ if let t = token { NSEvent.removeMonitor(t) }
+ }
+ return nil
+ }
+ } label: {
+ Text(isRecording ? "Press keys…" : shortcutLabel)
+ .font(.system(size: 11, design: .monospaced))
+ .padding(.horizontal, 8).padding(.vertical, 3)
+ .background(isRecording ? Color.accentColor.opacity(0.12) : Color(NSColor.controlBackgroundColor))
+ .cornerRadius(5)
+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color.gray.opacity(0.3), lineWidth: 1))
+ }
+ .buttonStyle(.plain)
+ }
+
+ private var shortcutLabel: String {
+ let f = NSEvent.ModifierFlags(rawValue: flags)
+ var s = ""
+ if f.contains(.control) { s += "⌃" }
+ if f.contains(.option) { s += "⌥" }
+ if f.contains(.shift) { s += "⇧" }
+ if f.contains(.command) { s += "⌘" }
+ s += keyChar(code)
+ return s.isEmpty ? "None" : s
+ }
+
+ private func keyChar(_ c: UInt16) -> String {
+ let map: [UInt16: String] = [
+ 0:"A", 1:"S", 2:"D", 3:"F", 4:"H", 5:"G", 6:"Z", 7:"X", 8:"C", 9:"V",
+ 11:"B", 12:"Q", 13:"W", 14:"E", 15:"R", 16:"Y", 17:"T", 31:"O", 32:"U",
+ 34:"I", 37:"L", 38:"J", 40:"K", 45:"N", 46:"M", 49:"Space", 50:"`", 27:"-"
+ ]
+ return map[c] ?? "·"
+ }
+}
diff --git a/NotchBuddy/Sources/App/SoundEngine.swift b/NotchBuddy/Sources/App/SoundEngine.swift
new file mode 100644
index 00000000..df75214b
--- /dev/null
+++ b/NotchBuddy/Sources/App/SoundEngine.swift
@@ -0,0 +1,50 @@
+import AVFoundation
+import AppKit
+
+/// Preloaded WAV players with near-zero latency.
+/// Volume default 0.12 (matches prototype: gain ×6 then vol=0.12).
+@MainActor
+final class SoundEngine {
+ static let shared = SoundEngine()
+
+ var enabled: Bool = true
+ var volume: Float = 0.12 {
+ didSet { players.values.forEach { $0.forEach { $0.volume = volume } } }
+ }
+
+ // Pool of 3 players per sound to allow overlapping playback
+ private var players: [String: [AVAudioPlayer]] = [:]
+
+ private init() {
+ preload()
+ }
+
+ private func preload() {
+ let names = ["peek","open","close","hover","blip","slap","annoyed","dizzy","greet",
+ "work","finish","error","approval","question","approve","gulp","tick",
+ "send","love","pop","proud","wink","yawn","attach","think","search",
+ "rate","sleep"]
+ for name in names {
+ guard let url = Bundle.main.url(forResource: name, withExtension: "wav", subdirectory: "sounds") else { continue }
+ var pool: [AVAudioPlayer] = []
+ for _ in 0..<3 {
+ if let p = try? AVAudioPlayer(contentsOf: url) {
+ p.volume = volume
+ p.prepareToPlay()
+ pool.append(p)
+ }
+ }
+ if !pool.isEmpty { players[name] = pool }
+ }
+ }
+
+ func play(_ name: String) {
+ guard enabled && AppState.shared.soundEnabled else { return }
+ guard let pool = players[name] else { return }
+ // Find a player that is not currently playing
+ let player = pool.first { !$0.isPlaying } ?? pool[0]
+ player.currentTime = 0
+ player.volume = volume
+ player.play()
+ }
+}
diff --git a/NotchBuddy/Sources/App/StripePoller.swift b/NotchBuddy/Sources/App/StripePoller.swift
new file mode 100644
index 00000000..6aeec6c1
--- /dev/null
+++ b/NotchBuddy/Sources/App/StripePoller.swift
@@ -0,0 +1,161 @@
+import Foundation
+import SwiftUI
+
+// MARK: - StripePoller
+// Polls Stripe API every 30s for balance + recent charges.
+// On new charge: slides payments list (newest first), then animates balance count-up.
+
+final class StripePoller: @unchecked Sendable {
+ static let shared = StripePoller()
+ private var timer: DispatchSourceTimer?
+ private var lastChargeId: String = ""
+
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 6, repeating: 30)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ // MARK: - Poll
+
+ func pollNow() { poll() }
+
+ private func poll() {
+ guard let key = KeychainStore.shared.get("stripe-api-key") else { return }
+ fetchBalance(key: key)
+ fetchCharges(key: key)
+ }
+
+ // MARK: - Balance
+
+ private func fetchBalance(key: String) {
+ guard let url = URL(string: "https://api.stripe.com/v1/balance") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ // Stripe primary auth: Basic with key as username, empty password
+ let creds = Data("\(key):".utf8).base64EncodedString()
+ req.setValue("Basic \(creds)", forHTTPHeaderField: "Authorization")
+
+ URLSession.shared.dataTask(with: req) { data, response, error in
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if code != 200 {
+ let errMsg: String
+ if code == 401 { errMsg = "Invalid API key (401)" }
+ else if code == 403 { errMsg = "Use secret key (sk_live_… not pk_live_…)" }
+ else if code == 0 { errMsg = error?.localizedDescription ?? "No connection" }
+ else { errMsg = "API error \(code)" }
+ DispatchQueue.main.async { AppState.shared.stripeError = errMsg }
+ return
+ }
+ guard let data,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
+
+ // Sum available + pending so recent charges show up immediately
+ let available = json["available"] as? [[String: Any]] ?? []
+ let pending = json["pending"] as? [[String: Any]] ?? []
+ let allBuckets = available + pending
+ guard let currency = (allBuckets.first)?["currency"] as? String else { return }
+ let amount = allBuckets.compactMap { $0["amount"] as? Int }.reduce(0, +)
+
+ DispatchQueue.main.async {
+ let state = AppState.shared
+ state.stripeError = nil
+ state.stripeCurrency = currency
+ state.stripeBalance = amount
+ // Always sync display balance if not yet showing a real value
+ // (charges may have set stripeLoaded=true before balance arrived)
+ if state.stripeDisplayBalance == 0 {
+ state.stripeDisplayBalance = amount
+ }
+ state.stripeLoaded = true
+ }
+ }.resume()
+ }
+
+ // MARK: - Charges
+
+ private func fetchCharges(key: String) {
+ guard let url = URL(string: "https://api.stripe.com/v1/charges?limit=3") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ let creds = Data("\(key):".utf8).base64EncodedString()
+ req.setValue("Basic \(creds)", forHTTPHeaderField: "Authorization")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, _ in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200 else { return }
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let rawList = json["data"] as? [[String: Any]] else { return }
+
+ let parsed = rawList.compactMap { self.parseCharge($0) }
+ DispatchQueue.main.async { self.handleCharges(parsed) }
+ }.resume()
+ }
+
+ private func parseCharge(_ c: [String: Any]) -> StripePayment? {
+ guard let id = c["id"] as? String,
+ let amount = c["amount"] as? Int,
+ let currency = c["currency"] as? String,
+ let status = c["status"] as? String else { return nil }
+
+ let ts = (c["created"] as? TimeInterval) ?? 0
+ let desc = c["description"] as? String
+ ?? (c["billing_details"] as? [String: Any]).flatMap { $0["name"] as? String }
+
+ return StripePayment(id: id, amount: amount, currency: currency,
+ description: desc, createdAt: Date(timeIntervalSince1970: ts),
+ status: status)
+ }
+
+ @MainActor
+ private func handleCharges(_ payments: [StripePayment]) {
+ let state = AppState.shared
+
+ // First load — populate silently, anchor lastChargeId to avoid duplicate on next poll
+ if state.stripePayments.isEmpty {
+ state.stripePayments = payments
+ lastChargeId = payments.first?.id ?? ""
+ // Sync display balance (balance may have already arrived; use it)
+ state.stripeDisplayBalance = state.stripeBalance
+ state.stripeLoaded = true
+ return
+ }
+
+ guard let newest = payments.first, newest.id != lastChargeId else { return }
+ lastChargeId = newest.id
+
+ guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_stripe" }) else { return }
+ let focused = state.focusId == "integration_stripe"
+
+ // 1. Slide payments: new enters top, max 3 shown
+ withAnimation(.spring(response: 0.38, dampingFraction: 0.82)) {
+ state.stripePayments = Array(([newest] + state.stripePayments).prefix(3))
+ }
+
+ state.tasks[idx].state = .finished
+ state.tasks[idx].steps = [newest.description ?? newest.amountFormatted]
+ if !focused { state.tasks[idx].pillBadge = .finished }
+ SoundEngine.shared.play("finish")
+
+ // 2. After slide settles, count up balance
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
+ withAnimation(.easeOut(duration: 1.2)) {
+ state.stripeDisplayBalance = state.stripeBalance
+ }
+ }
+
+ // 3. Auto-clear task state after 60s
+ DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
+ guard let i = state.tasks.firstIndex(where: { $0.id == "integration_stripe" }) else { return }
+ guard state.tasks[i].state == .finished else { return }
+ state.tasks[i].state = .idle
+ state.tasks[i].steps = []
+ state.tasks[i].pillBadge = nil
+ }
+ }
+}
+
diff --git a/NotchBuddy/Sources/App/UploadCanvasView.swift b/NotchBuddy/Sources/App/UploadCanvasView.swift
new file mode 100644
index 00000000..0efebfe1
--- /dev/null
+++ b/NotchBuddy/Sources/App/UploadCanvasView.swift
@@ -0,0 +1,582 @@
+import SwiftUI
+import AppKit
+
+// Full 640×176 canvas that drives the upload sequence animation.
+// Replaces the header + content area when the upload engine is active.
+
+struct UploadCanvasView: View {
+ @ObservedObject var state: AppState
+ @State private var fileIcon: NSImage? = nil
+
+ private var engine: UploadSequenceEngine { .shared }
+
+ var body: some View {
+ TimelineView(.animation) { tl in
+ let f = engine.frame(at: tl.date)
+ let wallTime = tl.date.timeIntervalSinceReferenceDate
+
+ ZStack(alignment: .topLeading) {
+ Canvas { ctx, _ in
+ drawScene(ctx: ctx, f: f, wallTime: wallTime)
+ }
+ .frame(width: 640, height: 176)
+
+ // Interactive choose buttons (invisible hit areas at reference positions)
+ if f.chooseAlpha > 0 {
+ chooseOverlay(f: f)
+ .frame(width: 640, height: 176)
+ }
+ }
+ }
+ .onChange(of: state.droppedFile?.url) { _, url in
+ if let url { loadIcon(url: url) }
+ }
+ .onAppear {
+ if let url = state.droppedFile?.url { loadIcon(url: url) }
+ }
+ .frame(width: 640, height: 176)
+ }
+
+ // MARK: - File icon
+
+ private func loadIcon(url: URL) {
+ let img = NSWorkspace.shared.icon(forFile: url.path)
+ img.size = NSSize(width: 64, height: 64)
+ fileIcon = img
+ }
+
+ // MARK: - Choose overlay (transparent SwiftUI buttons over canvas)
+
+ @ViewBuilder
+ private func chooseOverlay(f: USFrame) -> some View {
+ // Reference positions: button1 x=100 w=176 y=113 h=26, button2 x=284 w=128
+ ZStack(alignment: .topLeading) {
+ // Primary: "Ask a question about it"
+ Button {
+ withAnimation(.easeInOut(duration: 0.22)) { state.view = .prompt }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.22) {
+ UploadSequenceEngine.shared.deactivate()
+ }
+ } label: {
+ Color.clear
+ .frame(width: 168, height: 26)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .frame(width: 168, height: 26)
+ .position(x: 114 + 84, y: 113 + 13) // center = (198, 126)
+
+ // Secondary: "Send by email"
+ Button {
+ withAnimation(.easeInOut(duration: 0.22)) { state.view = .mail }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.22) {
+ UploadSequenceEngine.shared.deactivate()
+ }
+ } label: {
+ Color.clear
+ .frame(width: 120, height: 26)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .frame(width: 120, height: 26)
+ .position(x: 290 + 60, y: 113 + 13) // center = (350, 126)
+ }
+ .opacity(f.chooseAlpha)
+ .allowsHitTesting(f.chooseAlpha > 0.5)
+ }
+
+ // MARK: - Main draw
+
+ private func drawScene(ctx: GraphicsContext, f: USFrame, wallTime: Double = 0) {
+ var c = ctx
+
+ // ── Island background ──────────────────────────────────────
+ c.fill(Path(CGRect(x:0, y:0, width:640, height:176)), with: .color(Color.black))
+
+ // ── Card ──────────────────────────────────────────────────
+ let cardPath = roundedRect(CGRect(x: USC.CARD_X, y: USC.CARD_Y, width: USC.CARD_W, height: USC.CARD_H), r: USC.CARD_R)
+
+ var cardCtx = c
+ cardCtx.clip(to: cardPath)
+ cardCtx.fill(Path(CGRect(x: USC.CARD_X, y: USC.CARD_Y, width: USC.CARD_W, height: USC.CARD_H)),
+ with: .color(Color(red:0.051, green:0.055, blue:0.063)))
+
+ // Green glow from card bottom — grows slowly with upload progress
+ if f.greenWash > 0 {
+ // Center at card bottom edge; gradient fans upward through the card
+ let gx = USC.CARD_X + USC.CARD_W/2
+ let gy = USC.CARD_Y + USC.CARD_H // bottom of card
+ let gGrad = Gradient(stops: [
+ .init(color: Color(red:0.157,green:0.831,blue:0.510).opacity(f.greenWash * 0.90), location:0),
+ .init(color: Color(red:0.157,green:0.831,blue:0.510).opacity(f.greenWash * 0.30), location:0.55),
+ .init(color: Color(red:0.157,green:0.831,blue:0.510).opacity(0), location:1)
+ ])
+ cardCtx.fill(Path(CGRect(x:USC.CARD_X,y:USC.CARD_Y,width:USC.CARD_W,height:USC.CARD_H)),
+ with: .radialGradient(gGrad, center:CGPoint(x:gx,y:gy),
+ startRadius:0, endRadius:USC.CARD_H*1.5))
+ }
+
+ // ── Dashed border (animates left→right while on drop zone) ────
+ if f.zoneAlpha > 0 {
+ var borderCtx = c
+ borderCtx.opacity = f.zoneAlpha
+ let borderColor = f.zoneOver
+ ? Color(red:0.204,green:0.831,blue:0.600).opacity(0.55)
+ : Color.white.opacity(0.14)
+ let inset = CGRect(x: USC.CARD_X+0.75, y: USC.CARD_Y+0.75,
+ width: USC.CARD_W-1.5, height: USC.CARD_H-1.5)
+ // dashPhase increases → pattern marches left-to-right at ~20 pt/s
+ let dashPhase = CGFloat(wallTime * 20)
+ borderCtx.stroke(roundedRect(inset, r: USC.CARD_R-0.5),
+ with: .color(borderColor),
+ style: StrokeStyle(lineWidth:1.5, dash:[6,5], dashPhase: dashPhase))
+ }
+
+ // ── Drop zone text ─────────────────────────────────────────
+ if f.zoneAlpha > 0 && f.textAlpha > 0 {
+ drawDropText(ctx: &c, f: f)
+ }
+
+ // ── Progress bar ──────────────────────────────────────────
+ if f.barAlpha > 0 || f.barReveal > 0 {
+ drawProgressBar(ctx: &c, f: f)
+ }
+
+ // ── Choose view text ─────────────────────────────────────
+ if f.chooseAlpha > 0 {
+ drawChooseView(ctx: &c, f: f)
+ }
+
+ // ── Mochi ─────────────────────────────────────────────────
+ drawMochi(ctx: &c, f: f)
+
+ // ── File / suction ────────────────────────────────────────
+ if f.fileVisible { drawFile(ctx: &c, f: f) }
+ }
+
+ // MARK: - Drop zone text + chips
+
+ private func drawDropText(ctx: inout GraphicsContext, f: USFrame) {
+ var tCtx = ctx
+ tCtx.opacity = f.textAlpha
+
+ let label = Text("Drop your files here")
+ .font(.system(size:13, weight:.medium))
+ .foregroundColor(Color(hex:"#D5D7DB"))
+ tCtx.draw(label, at: CGPoint(x: USC.TEXT_X, y: USC.TEXT_Y - 4), anchor: .leading)
+
+ let chips = ["PDF","Images","Code","Docs"]
+ var cx = USC.TEXT_X
+ for chip in chips {
+ let chipText = Text(chip).font(.system(size:11, weight:.medium)).foregroundColor(Color(hex:"#B9BDC4"))
+ // measure approximate width
+ let estW = Double(chip.count) * 6.5 + 16
+ tCtx.fill(roundedRect(CGRect(x:cx, y:USC.TEXT_Y+9, width:estW, height:18), r:9),
+ with: .color(Color.white.opacity(0.07)))
+ tCtx.draw(chipText, at: CGPoint(x: cx + 8, y: USC.TEXT_Y + 18), anchor: .leading)
+ cx += estW + 6
+ }
+ }
+
+ // MARK: - Progress bar
+
+ private func drawProgressBar(ctx: inout GraphicsContext, f: USFrame) {
+ var pCtx = ctx
+ pCtx.opacity = max(f.barAlpha, 0.001)
+
+ let x0 = USC.BAR_X0, x1 = USC.BAR_X1, by = USC.BAR_Y
+ let barLen = (x1-x0) * f.barReveal
+
+ // Filename label
+ let name = state.droppedFile?.name ?? "file"
+ let label = Text("Uploading \(name)")
+ .font(.system(size:12.5, weight:.medium))
+ .foregroundColor(Color(hex:"#A9ADB5"))
+ pCtx.draw(label, at: CGPoint(x: x0, y: by-30), anchor: .leading)
+
+ // Checkmark or percentage
+ if f.check > 0 {
+ var ckCtx = pCtx
+ ckCtx.concatenate(CGAffineTransform(translationX: CGFloat(x1-8), y: CGFloat(by-30)))
+ ckCtx.concatenate(CGAffineTransform(scaleX: CGFloat(f.check), y: CGFloat(f.check)))
+ var circle = Path(); circle.addEllipse(in: CGRect(x:-8,y:-8,width:16,height:16))
+ ckCtx.fill(circle, with: .color(Color(hex:"#34D399")))
+ var ck = Path()
+ ck.move(to: CGPoint(x:-3.6,y:0.2)); ck.addLine(to: CGPoint(x:-1,y:2.8)); ck.addLine(to: CGPoint(x:3.8,y:-2.6))
+ ckCtx.stroke(ck, with: .color(Color(red:0.027,green:0.075,blue:0.055)),
+ style: StrokeStyle(lineWidth:2, lineCap:.round, lineJoin:.round))
+ } else {
+ let pct = Text("\(Int(f.progress*100)) %")
+ .font(.system(size:12.5, weight:.medium).monospacedDigit())
+ .foregroundColor(Color(hex:"#A9ADB5"))
+ pCtx.draw(pct, at: CGPoint(x: x1, y: by-30), anchor: .trailing)
+ }
+
+ // Bar track
+ if barLen > 0 {
+ pCtx.fill(roundedRect(CGRect(x:x0, y:by-3, width:barLen, height:6), r:3),
+ with: .color(Color.white.opacity(0.08)))
+ }
+
+ // Bar fill
+ let fx = usLerp(USC.BAR_X0, USC.BAR_X1, f.progress)
+ if fx > x0 + 1 {
+ // Flash color at completion
+ let flashGreen = Color(
+ red: usLerp(0.204, 0.431, f.flash),
+ green: usLerp(0.827, 0.906, f.flash),
+ blue: usLerp(0.600, 0.718, f.flash))
+ let fillGrad = Gradient(stops: [
+ .init(color: Color(hex:"#1FA87A"), location:0),
+ .init(color: flashGreen, location:1)
+ ])
+ pCtx.fill(roundedRect(CGRect(x:x0, y:by-3, width:fx-x0, height:6), r:3),
+ with: .linearGradient(fillGrad,
+ startPoint: CGPoint(x:x0, y:0),
+ endPoint: CGPoint(x:fx, y:0)))
+ }
+
+ // Glow trail
+ if f.progress > 0.01 && f.progress < 1 {
+ let v = (usProgressAt(f.t+0.01, progStart:USC.T_PROG_START, progEnd:f.progEnd)
+ - usProgressAt(f.t, progStart:USC.T_PROG_START, progEnd:f.progEnd)) / 0.01
+ let tl = max(8, min(34, 8 + v*40))
+ let tGrad = Gradient(stops:[
+ .init(color: Color(red:0.204,green:0.831,blue:0.600,opacity:0), location:0),
+ .init(color: Color(red:0.431,green:0.906,blue:0.718,opacity:0.6), location:1)
+ ])
+ var glowCtx = pCtx
+ glowCtx.addFilter(.blur(radius:3))
+ glowCtx.fill(roundedRect(CGRect(x:fx-tl, y:by-4, width:tl, height:8), r:4),
+ with: .linearGradient(tGrad,
+ startPoint:CGPoint(x:fx-tl,y:0),
+ endPoint: CGPoint(x:fx,y:0)))
+ }
+ }
+
+ // MARK: - Choose view text + buttons (canvas layer)
+
+ private func drawChooseView(ctx: inout GraphicsContext, f: USFrame) {
+ var cCtx = ctx
+ cCtx.opacity = f.chooseAlpha
+ // Slide up: translate down by (1-alpha)*4
+ cCtx.concatenate(CGAffineTransform(translationX: 0, y: CGFloat((1-f.chooseAlpha)*4)))
+
+ let name = state.droppedFile?.name ?? "file"
+ let titleText = Text("\(name) is ready.")
+ .font(.system(size:14, weight:.semibold))
+ .foregroundColor(Color(hex:"#F5F6F8"))
+ cCtx.draw(titleText, at: CGPoint(x:114, y:80), anchor: .leading)
+
+ let subText = Text("What do you want to do with it?")
+ .font(.system(size:12.5))
+ .foregroundColor(Color(hex:"#9398A1"))
+ cCtx.draw(subText, at: CGPoint(x:114, y:100), anchor: .leading)
+
+ // Primary button (white fill)
+ cCtx.fill(roundedRect(CGRect(x:114,y:113,width:168,height:26), r:13),
+ with: .color(Color(hex:"#F5F6F8")))
+ let btn1 = Text("Ask a question about it")
+ .font(.system(size:12.5, weight:.medium))
+ .foregroundColor(Color(red:0.043,green:0.047,blue:0.055))
+ cCtx.draw(btn1, at: CGPoint(x:198, y:126), anchor: .center)
+
+ // Secondary button (dim fill)
+ cCtx.fill(roundedRect(CGRect(x:290,y:113,width:120,height:26), r:13),
+ with: .color(Color.white.opacity(0.09)))
+ let btn2 = Text("Send by email")
+ .font(.system(size:12.5, weight:.medium))
+ .foregroundColor(Color(hex:"#F1F2F4"))
+ cCtx.draw(btn2, at: CGPoint(x:350, y:126), anchor: .center)
+ }
+
+ // MARK: - Mochi (superellipse body + eyes + mouth)
+
+ private func drawMochi(ctx: inout GraphicsContext, f: USFrame) {
+ let R = f.d / 2 / 1.04
+ let m = f.morph
+ let mc = max(0, min(m, 1.0))
+
+ var c = ctx
+ c.concatenate(CGAffineTransform(translationX: CGFloat(f.x), y: CGFloat(f.y + f.hop)))
+ c.concatenate(CGAffineTransform(rotationAngle: CGFloat(f.tilt)))
+ c.concatenate(CGAffineTransform(scaleX: CGFloat(f.sx), y: CGFloat(f.sy)))
+
+ let (bp, rx, ry) = usBodyPath(m: m, R: R)
+
+ // ── Body gradient ──────────────────────────────────────────
+ let bodyGrad = Gradient(stops:[
+ .init(color: Color(hex:"#EDEDEF"), location:0),
+ .init(color: Color(hex:"#C4C5CA"), location:1)
+ ])
+ c.fill(bp, with: .linearGradient(bodyGrad,
+ startPoint: CGPoint(x: rx*0.7, y: -ry*0.9),
+ endPoint: CGPoint(x: -rx*0.8, y: ry*0.9)))
+
+ // ── Edge shadow ────────────────────────────────────────────
+ let shadowGrad = Gradient(stops:[
+ .init(color: .clear, location:0),
+ .init(color: .clear, location:0.62),
+ .init(color: Color.black.opacity(0.12), location:1)
+ ])
+ c.fill(bp, with: .radialGradient(shadowGrad,
+ center: CGPoint(x:0,y:0), startRadius: CGFloat(R*0.2), endRadius: CGFloat(R*1.3)))
+
+ // ── Top rim (box mode) ─────────────────────────────────────
+ if mc > 0.3 {
+ let rimAlpha = max(0, min(1, (mc-0.3)/0.7))
+ var rimCtx = c
+ rimCtx.clip(to: bp)
+ var rim = Path()
+ rim.move(to: CGPoint(x: -rx*0.72, y: -ry+0.9))
+ rim.addLine(to: CGPoint(x: rx*0.72, y: -ry+0.9))
+ rimCtx.stroke(rim, with: .color(Color.white.opacity(0.6*rimAlpha)),
+ style: StrokeStyle(lineWidth:1.2, lineCap:.round))
+ }
+
+ // ── Mouth hole ─────────────────────────────────────────────
+ let mh = f.mouth * R * mc
+ if mh > 0.3 {
+ let mw = 2*rx - 0.24*R
+ let mxO = CGFloat(-mw/2)
+ let myO = CGFloat(-ry + 0.10*R)
+ let mhr = CGFloat(min(mw/2, mh/2))
+ var mCtx = c
+ mCtx.clip(to: bp)
+ let holeGrad = Gradient(stops:[
+ .init(color: Color(red:0.012,green:0.012,blue:0.016), location:0),
+ .init(color: Color(red:0.063,green:0.067,blue:0.078), location:1)
+ ])
+ let holePath = roundedRect(CGRect(x:mxO, y:myO, width:CGFloat(mw), height:CGFloat(mh)), r:Double(mhr))
+ mCtx.fill(holePath, with: .linearGradient(holeGrad,
+ startPoint: CGPoint(x:0, y:myO),
+ endPoint: CGPoint(x:0, y:myO+CGFloat(mh))))
+ // Bottom lip
+ if mh > 4 {
+ var lip = Path()
+ lip.move(to: CGPoint(x:mxO+mhr, y:myO+CGFloat(mh)+0.5))
+ lip.addLine(to: CGPoint(x:mxO+CGFloat(mw)-mhr, y:myO+CGFloat(mh)+0.5))
+ mCtx.stroke(lip, with: .color(Color.white.opacity(0.55)),
+ style: StrokeStyle(lineWidth:1, lineCap:.round))
+ }
+ }
+
+ // ── Eyes ───────────────────────────────────────────────────
+ let ew = R * 0.25
+ let eh = R * (0.62 - 0.16*mc)
+ let ey = R * (0.02 + 0.28*mc)
+ let sp = R * 0.30
+ let lx = f.lookX * R * (0.34 - 0.08*mc)
+ let ly = f.lookY * R * (0.16 - 0.09*mc)
+
+ var eCtx = c
+ eCtx.clip(to: bp)
+ for sd in [-1.0, 1.0] {
+ var ec = eCtx
+ ec.concatenate(CGAffineTransform(translationX: CGFloat(sd*sp+lx), y: CGFloat(ey+ly)))
+ drawEyeShape(ctx: &ec, shape: f.eye, w: CGFloat(ew), h: CGFloat(eh))
+ }
+ }
+
+ // MARK: - Eye shapes
+
+ private func drawEyeShape(ctx: inout GraphicsContext, shape: USEyeShape, w: CGFloat, h: CGFloat) {
+ let ink = Color(red:0.055,green:0.059,blue:0.071)
+ switch shape {
+ case .pill:
+ var p = Path()
+ p.addRoundedRect(in: CGRect(x:-w/2, y:-h/2, width:w, height:h),
+ cornerSize: CGSize(width:w/2, height:w/2))
+ ctx.fill(p, with: .color(ink))
+
+ case .cup:
+ // Flat top + semicircle bottom (cup shape)
+ let hh = h * 0.55
+ var p = Path()
+ p.move(to: CGPoint(x:-w/2, y:-hh/2))
+ p.addLine(to: CGPoint(x: w/2, y:-hh/2))
+ p.addLine(to: CGPoint(x: w/2, y: hh/2-w/2))
+ p.addArc(center: CGPoint(x:0, y:hh/2-w/2), radius:w/2, startAngle:.degrees(0), endAngle:.degrees(180), clockwise:false)
+ p.closeSubpath()
+ ctx.fill(p, with: .color(ink))
+
+ case .content:
+ // Upward arc (content / happy)
+ var p = Path()
+ p.addArc(center: CGPoint(x:0, y:-h*0.12), radius:w*0.85,
+ startAngle:.degrees(180*0.15), endAngle:.degrees(180*0.85), clockwise:false)
+ ctx.stroke(p, with: .color(ink),
+ style: StrokeStyle(lineWidth:w*0.5, lineCap:.round))
+ }
+ }
+
+ // MARK: - File / suction (drawFile port)
+
+ private func drawFile(ctx: inout GraphicsContext, f: USFrame) {
+ let cx = f.cursorX, cy = f.cursorY + 14
+ if f.suck <= 0 {
+ var fc = ctx; fc.opacity = 0.92
+ drawDoc(ctx: &fc, cx: cx, cy: cy, wsc:1, hsc:1)
+ return
+ }
+
+ let m = f.mouthRect
+ let W0 = 34.0, H0 = 42.0
+ let p = usEIn(f.suck)
+ let topY = usLerp(cy - H0/2, m.y - 2, usEInOut(f.suck))
+ let hs = usLerp(1.08, 0.55, usEInOut(f.suck))
+ let Hh = H0 * hs
+ let sc = usLerp(1, 0.55, p)
+ let q = usEOut(f.suck)
+ let fCx = usLerp(cx, m.x + m.w/2, usEOut(f.suck))
+ let wob = sin(f.suck * .pi * 2) * 0.1 * (1-p)
+ let clipY = m.y + m.h * 0.5
+
+ // Use withCGContext for the complex strip clipping
+ ctx.withCGContext { cg in
+ cg.saveGState()
+ // Outer clip: above mouth
+ cg.clip(to: CGRect(x:0, y:0, width:640, height:clipY))
+
+ for i in 0..<28 {
+ let v0 = Double(i) / 28
+ let wsc = usLerp(1, usLerp(0.92, 0.22*m.w/W0, pow(v0,1.2)), q) * sc
+ let yy = topY + v0*Hh
+ let hh = Hh/28 + 0.6
+
+ cg.saveGState()
+ cg.translateBy(x: CGFloat(fCx), y: CGFloat(yy))
+ cg.rotate(by: CGFloat(wob))
+ cg.clip(to: CGRect(x: CGFloat(-W0*wsc/2), y:0, width: CGFloat(W0*wsc), height: CGFloat(hh)))
+ cg.translateBy(x: CGFloat(-fCx), y: CGFloat(-yy))
+ drawDocCG(cg: cg, cx: fCx, cy: topY+Hh/2, wsc: wsc, hsc: hs, fileIcon: fileIcon)
+ cg.restoreGState()
+ }
+ cg.restoreGState()
+ }
+
+ // Green particles
+ for i in 0..<4 {
+ let a = Double(i)/4 * .pi*2 + 0.6
+ let r0 = 24.0
+ let k = max(0, min(1, (f.suck - Double(i)*0.08) / 0.7))
+ guard k > 0 && k < 1 else { continue }
+ let sx0 = cx + cos(a)*r0, sy0 = cy + sin(a)*r0
+ let ex = m.x + m.w/2, ey = m.y + m.h*0.3
+ let kk = pow(k, 0.7)
+ let px = usLerp(sx0,ex,kk), py = usLerp(sy0,ey,kk) - sin(.pi*k)*6
+ let rad = 2.2*(1-k*0.5)
+ var pp = Path(); pp.addEllipse(in: CGRect(x:px-rad, y:py-rad, width:rad*2, height:rad*2))
+ ctx.fill(pp, with: .color(Color(red:0.204,green:0.831,blue:0.600).opacity(1-k)))
+ }
+ }
+
+ // MARK: - Doc icon (SwiftUI wrapper)
+
+ private func drawDoc(ctx: inout GraphicsContext, cx: Double, cy: Double, wsc: Double, hsc: Double) {
+ let w = 34*wsc, h = 42*hsc
+ let x = cx-w/2, y = cy-h/2
+ let fold = 8*min(wsc,hsc)
+
+ var bodyCtx = ctx
+ bodyCtx.addFilter(.shadow(color:.black.opacity(0.45), radius:8, x:0, y:3))
+ var body = Path()
+ body.move(to: CGPoint(x:x+2,y:y))
+ body.addLine(to: CGPoint(x:x+w-fold,y:y))
+ body.addLine(to: CGPoint(x:x+w,y:y+fold))
+ body.addLine(to: CGPoint(x:x+w,y:y+h-2))
+ body.addQuadCurve(to: CGPoint(x:x+w-2,y:y+h), control:CGPoint(x:x+w,y:y+h))
+ body.addLine(to: CGPoint(x:x+2,y:y+h))
+ body.addQuadCurve(to: CGPoint(x:x,y:y+h-2), control:CGPoint(x:x,y:y+h))
+ body.addLine(to: CGPoint(x:x,y:y+2))
+ body.addQuadCurve(to: CGPoint(x:x+2,y:y), control:CGPoint(x:x,y:y))
+ body.closeSubpath()
+ bodyCtx.fill(body, with: .color(Color(red:0.957,green:0.957,blue:0.965)))
+
+ var foldPath = Path()
+ foldPath.move(to: CGPoint(x:x+w-fold,y:y))
+ foldPath.addLine(to: CGPoint(x:x+w-fold,y:y+fold))
+ foldPath.addLine(to: CGPoint(x:x+w,y:y+fold))
+ ctx.fill(foldPath, with: .color(Color(red:0.835,green:0.839,blue:0.859)))
+
+ ctx.fill(roundedRect(CGRect(x:x+w*0.18,y:y+h*0.58,width:w*0.64,height:h*0.16),r:2),
+ with: .color(Color(red:0.231,green:0.510,blue:0.961)))
+ }
+}
+
+// MARK: - Doc icon in CGContext (for suction strips)
+
+private func drawDocCG(cg: CGContext, cx: Double, cy: Double, wsc: Double, hsc: Double, fileIcon: NSImage?) {
+ let w = 34*wsc, h = 42*hsc
+ let x = cx-w/2, y = cy-h/2
+ let fold = 8.0*min(wsc,hsc)
+
+ // Use real file icon if available
+ if let icon = fileIcon,
+ let cgImg = icon.cgImage(forProposedRect: nil, context: nil, hints: nil) {
+ cg.saveGState()
+ cg.setShadow(offset: CGSize(width:0,height:3), blur:8, color: CGColor(gray:0, alpha:0.45))
+ let rect = CGRect(x:x, y:y, width:w, height:h)
+ cg.draw(cgImg, in: rect)
+ cg.restoreGState()
+ return
+ }
+
+ // Generic document shape
+ cg.saveGState()
+ cg.setShadow(offset: CGSize(width:0,height:3), blur:8, color: CGColor(gray:0, alpha:0.45))
+ cg.setFillColor(CGColor(red:0.957,green:0.957,blue:0.965,alpha:1))
+ let bp = CGMutablePath()
+ bp.move(to: CGPoint(x:x+2,y:y))
+ bp.addLine(to: CGPoint(x:x+w-fold,y:y))
+ bp.addLine(to: CGPoint(x:x+w,y:y+fold))
+ bp.addLine(to: CGPoint(x:x+w,y:y+h-2))
+ bp.addQuadCurve(to: CGPoint(x:x+w-2,y:y+h), control:CGPoint(x:x+w,y:y+h))
+ bp.addLine(to: CGPoint(x:x+2,y:y+h))
+ bp.addQuadCurve(to: CGPoint(x:x,y:y+h-2), control:CGPoint(x:x,y:y+h))
+ bp.addLine(to: CGPoint(x:x,y:y+2))
+ bp.addQuadCurve(to: CGPoint(x:x+2,y:y), control:CGPoint(x:x,y:y))
+ bp.closeSubpath()
+ cg.addPath(bp); cg.fillPath()
+ cg.restoreGState()
+
+ // Fold
+ cg.setFillColor(CGColor(red:0.835,green:0.839,blue:0.859,alpha:1))
+ let fp = CGMutablePath()
+ fp.move(to: CGPoint(x:x+w-fold,y:y)); fp.addLine(to: CGPoint(x:x+w-fold,y:y+fold)); fp.addLine(to: CGPoint(x:x+w,y:y+fold))
+ cg.addPath(fp); cg.fillPath()
+
+ // Blue accent line
+ cg.setFillColor(CGColor(red:0.231,green:0.510,blue:0.961,alpha:1))
+ cg.addRect(CGRect(x:x+w*0.18, y:y+h*0.58, width:w*0.64, height:h*0.16))
+ cg.fillPath()
+}
+
+// MARK: - Superellipse body path (port of reference bodyPath(m, R))
+
+func usBodyPath(m: Double, R: Double) -> (path: Path, rx: Double, ry: Double) {
+ let mc = max(0, min(m, 1.0))
+ let n = 2.15 + (5.5-2.15)*mc
+ let rx = R * (1.04 - 0.04*mc)
+ let ry = R * (0.97 - 0.03*mc)
+ var path = Path()
+ for i in 0...96 {
+ let a = Double(i)/96 * .pi*2
+ let ca = cos(a), sa = sin(a)
+ let px = rx * (ca<0 ? -1 : ca>0 ? 1 : 0) * pow(abs(ca), 2/n)
+ let py = ry * (sa<0 ? -1 : sa>0 ? 1 : 0) * pow(abs(sa), 2/n)
+ if i == 0 { path.move(to: CGPoint(x:px,y:py)) }
+ else { path.addLine(to: CGPoint(x:px,y:py)) }
+ }
+ path.closeSubpath()
+ return (path, rx, ry)
+}
+
+// MARK: - Rounded rect helper (mirrors reference rr())
+
+func roundedRect(_ rect: CGRect, r rr: Double) -> Path {
+ let r = max(0, min(rr, Double(rect.width)/2, Double(rect.height)/2))
+ var p = Path()
+ p.addRoundedRect(in: rect, cornerSize: CGSize(width:r, height:r))
+ return p
+}
diff --git a/NotchBuddy/Sources/App/UploadSequenceEngine.swift b/NotchBuddy/Sources/App/UploadSequenceEngine.swift
new file mode 100644
index 00000000..12b091b0
--- /dev/null
+++ b/NotchBuddy/Sources/App/UploadSequenceEngine.swift
@@ -0,0 +1,437 @@
+import Foundation
+import CoreGraphics
+
+// ============================================================
+// CONSTANTS — exact mirror of upload-sequence.html
+// All values in island-coordinate points (island = 640 × 176)
+// ============================================================
+
+enum USC {
+ static let W: Double = 640
+ static let ISL_H: Double = 176
+ static let CARD_X: Double = 10; static let CARD_Y: Double = 42
+ static let CARD_W: Double = 620; static let CARD_H: Double = 124; static let CARD_R: Double = 20
+ static let REST_X: Double = 140; static let REST_Y: Double = 104
+ static let D_BOX: Double = 62
+ static let FOLLOW_MIN: Double = 60 // CARD_X + 50
+ static let FOLLOW_MAX: Double = 580 // CARD_X + CARD_W - 50
+ static let TEXT_X: Double = 196; static let TEXT_Y: Double = 94
+ static let BAR_X0: Double = 46; static let BAR_X1: Double = 520; static let BAR_Y: Double = 118
+ static let CHOOSE_X: Double = 60; static let CHOOSE_Y: Double = 101; static let CHOOSE_D: Double = 62
+ static let LOCK_IN: Double = 60
+ static let LOCK_OUT: Double = 90
+ static let MOUTH_AJAR: Double = 0.20
+ static let MOUTH_OPEN: Double = 0.42
+ static let MOUTH_MAX: Double = 0.50
+ // Phase timestamps (t_ref, drop = 1.95)
+ static let T_DROP: Double = 1.95
+ static let T_SUCK_START: Double = 2.03
+ static let T_SUCK_END: Double = 2.33
+ static let T_CLOSE_END: Double = 2.42
+ static let T_CHEW1: Double = 2.60
+ static let T_CHEW_END: Double = 2.88
+ static let T_SHRINK_END: Double = 3.23
+ static let T_BAR_IN: Double = 3.00
+ static let T_PROG_START: Double = 3.25
+ static let DT: Double = 1.0 / 240.0
+ // Entry offset: gives 0.40 s of following before drop
+ static let ENTRY_T_REF: Double = T_DROP - 0.40 // = 1.55
+}
+
+// ============================================================
+// EASING — port of reference E.out / E.in / E.inOut / E.back
+// ============================================================
+
+func usEOut(_ t: Double) -> Double { 1 - pow(1-t, 3) }
+func usEIn(_ t: Double) -> Double { t*t*t }
+func usEInOut(_ t: Double) -> Double { t < 0.5 ? 4*t*t*t : 1 - pow(-2*t+2,3)/2 }
+func usEBack(_ t: Double) -> Double { let c1=1.70158,c3=c1+1; return 1+c3*pow(t-1,3)+c1*pow(t-1,2) }
+
+func usSeg(_ t: Double, _ a: Double, _ b: Double) -> Double { max(0, min(1,(t-a)/(b-a))) }
+func usLerp(_ a: Double, _ b: Double, _ t: Double) -> Double { a+(b-a)*t }
+
+// Squeeze keyframes for suckEnd→chew1 phase (inline to avoid Swift @escaping issues)
+func usSqueezeY(_ t: Double) -> Double {
+ let t0=USC.T_SUCK_END, t1=t0+0.07, t2=t0+0.20, t3=USC.T_CHEW1
+ if t<=t0 { return 1.06 }
+ if t<=t1 { return usLerp(1.06, 0.82, usEOut(usSeg(t,t0,t1))) }
+ if t<=t2 { return usLerp(0.82, 1.10, usEOut(usSeg(t,t1,t2))) }
+ if t<=t3 { return usLerp(1.10, 1.00, usEInOut(usSeg(t,t2,t3))) }
+ return 1.0
+}
+func usSqueezeX(_ t: Double) -> Double {
+ let t0=USC.T_SUCK_END, t1=t0+0.07, t2=t0+0.20, t3=USC.T_CHEW1
+ if t<=t0 { return 0.97 }
+ if t<=t1 { return usLerp(0.97, 1.14, usEOut(usSeg(t,t0,t1))) }
+ if t<=t2 { return usLerp(1.14, 0.95, usEOut(usSeg(t,t1,t2))) }
+ if t<=t3 { return usLerp(0.95, 1.00, usEInOut(usSeg(t,t2,t3))) }
+ return 1.0
+}
+
+func usProgressCurve(_ u: Double) -> Double {
+ if u < 0.40 { return 0.60 * usEOut(u/0.40) }
+ if u < 0.85 { return 0.60 + 0.32 * usEInOut((u-0.40)/0.45) }
+ return 0.92 + 0.08 * usEIn((u-0.85)/0.15)
+}
+func usProgressAt(_ t: Double, progStart: Double, progEnd: Double) -> Double {
+ t < progStart ? 0 : usProgressCurve(usSeg(t, progStart, progEnd))
+}
+
+// ============================================================
+// SPRING — port of reference spring(s, target, response, damping, dt)
+// ============================================================
+
+struct USSpring {
+ var v: Double
+ var vel: Double = 0
+ mutating func step(target: Double, response: Double, damping: Double, dt: Double) {
+ let k = pow(2 * .pi / response, 2)
+ let c = 2 * damping * sqrt(k)
+ let a = k*(target-v) - c*vel
+ vel += a*dt; v += vel*dt
+ }
+}
+
+// ============================================================
+// SIMULATION STATE — mirrors reference newSim()
+// ============================================================
+
+struct USSimState {
+ var t: Double = 0
+ var bx: USSpring = USSpring(v: USC.REST_X)
+ var by: USSpring = USSpring(v: USC.REST_Y)
+ var tilt: Double = 0
+ var mouth: USSpring = USSpring(v: 0)
+ var locked: Bool = false
+ var lockAt: Double = -9
+ var entered: Double = -9 // t_ref of zone entry; -9 = not entered
+ var gulp: Bool = false
+ var ok: Bool = false
+ var lastPct: Int = 0
+}
+
+// ============================================================
+// FRAME DATA — output of frame(), read by UploadCanvasView
+// ============================================================
+
+enum USEyeShape { case pill, cup, content }
+
+struct USMouthRect { var x,y,w,h: Double }
+
+struct USFrame {
+ var t: Double = 0
+ var cursorX: Double = 600; var cursorY: Double = 280
+ var morph: Double = 0
+ var x: Double = USC.REST_X; var y: Double = USC.REST_Y; var d: Double = USC.D_BOX
+ var sx: Double = 1; var sy: Double = 1; var tilt: Double = 0; var hop: Double = 0
+ var mouth: Double = 0
+ var mouthRect = USMouthRect(x:0,y:0,w:0,h:0)
+ var eye: USEyeShape = .pill
+ var lookX: Double = 0; var lookY: Double = 0
+ var fileVisible: Bool = true; var suck: Double = 0
+ var zoneOver: Bool = false
+ var zoneAlpha: Double = 1
+ var textAlpha: Double = 1
+ var barReveal: Double = 0
+ var barAlpha: Double = 0
+ var progress: Double = 0
+ var flash: Double = 0
+ var check: Double = 0
+ var greenWash: Double = 0
+ var chooseAlpha: Double = 0
+ var uploadDuration: Double = 2.4
+ var progEnd: Double = USC.T_PROG_START + 2.4
+ var growStart: Double = USC.T_PROG_START + 2.4 + 0.25
+ var growEnd: Double = USC.T_PROG_START + 2.4 + 0.70
+}
+
+// ============================================================
+// ENGINE
+// ============================================================
+
+@MainActor
+final class UploadSequenceEngine {
+ static let shared = UploadSequenceEngine()
+
+ var uploadDuration: Double = 2.4
+ var progEnd: Double { USC.T_PROG_START + uploadDuration }
+ var growStart: Double { progEnd + 0.25 }
+ var growEnd: Double { progEnd + 0.70 }
+
+ private(set) var isActive: Bool = false
+ private var entryWallTime: Double = 0 // Date().timeIntervalSinceReferenceDate at entry
+ private var dropWallTime: Double? = nil
+
+ private var sim = USSimState()
+
+ // Real cursor in island coords
+ var cursorX: Double = 600
+ var cursorY: Double = 280
+ private var prevCursorX: Double = 600
+ private var prevCursorY: Double = 280
+ private var prevCursorTime: Double = 0
+ private var cursorSpeed: Double = 0
+
+ // MARK: - Session lifecycle
+
+ func enterZone(x: CGFloat, y: CGFloat) {
+ let now = Date().timeIntervalSinceReferenceDate
+ cursorX = Double(x); cursorY = Double(y)
+ prevCursorX = cursorX; prevCursorY = cursorY; prevCursorTime = now
+ cursorSpeed = 0
+ sim = USSimState()
+ sim.t = USC.ENTRY_T_REF
+ sim.entered = USC.ENTRY_T_REF
+ sim.bx = USSpring(v: USC.REST_X)
+ sim.by = USSpring(v: USC.REST_Y)
+ entryWallTime = now
+ dropWallTime = nil
+ isActive = true
+ }
+
+ func updateCursor(x: CGFloat, y: CGFloat) {
+ let now = Date().timeIntervalSinceReferenceDate
+ let dt = now - prevCursorTime
+ if dt > 0.001 {
+ let dx = Double(x) - prevCursorX, dy = Double(y) - prevCursorY
+ cursorSpeed = hypot(dx, dy) / dt
+ }
+ prevCursorX = Double(x); prevCursorY = Double(y); prevCursorTime = now
+ cursorX = Double(x); cursorY = Double(y)
+ }
+
+ func exitZone() {
+ // Keep engine active — island stays open per spec
+ }
+
+ func performDrop(uploadDuration ud: Double) {
+ uploadDuration = ud
+ let now = Date().timeIntervalSinceReferenceDate
+ dropWallTime = now
+ // Reset sim.t to T_DROP so the canonical post-drop timeline starts correctly,
+ // regardless of how long the user hovered. Spring state (position/velocity) is preserved.
+ sim.t = USC.T_DROP
+ }
+
+ func deactivate() {
+ isActive = false
+ dropWallTime = nil
+ }
+
+ // MARK: - t_ref from wall clock
+
+ func tRef(at date: Date) -> Double {
+ guard isActive else { return 0 }
+ let now = date.timeIntervalSinceReferenceDate
+ if let dw = dropWallTime {
+ return USC.T_DROP + max(0, now - dw)
+ }
+ // No cap — spring keeps stepping as long as user hovers.
+ // computeFrame clamps phase-sensitive outputs to pre-drop state.
+ let elapsed = max(0, now - entryWallTime)
+ return USC.ENTRY_T_REF + elapsed
+ }
+
+ // MARK: - Public entry point
+
+ func frame(at date: Date) -> USFrame {
+ guard isActive else { return USFrame() }
+ let t = tRef(at: date)
+ simulateTo(t)
+ return computeFrame(t: t)
+ }
+
+ // MARK: - Simulation
+
+ private func simulateTo(_ tTarget: Double) {
+ while sim.t < tTarget - 1e-10 {
+ let dt = min(USC.DT, tTarget - sim.t)
+ stepOnce(dt: dt)
+ sim.t += dt
+ }
+ }
+
+ private func stepOnce(dt: Double) {
+ let isDragging = (dropWallTime == nil)
+
+ // Horizontal follow + lock (only while dragging and in zone)
+ if isDragging && sim.entered >= 0 {
+ let dist = hypot(cursorX - sim.bx.v, (cursorY + 14) - sim.by.v)
+ if !sim.locked && dist < USC.LOCK_IN && cursorSpeed < 180 {
+ sim.locked = true; sim.lockAt = sim.t
+ }
+ if sim.locked && dist > USC.LOCK_OUT { sim.locked = false }
+ let tx = max(USC.FOLLOW_MIN, min(USC.FOLLOW_MAX, cursorX))
+ if sim.locked {
+ sim.bx.step(target: tx, response:0.18, damping:0.75, dt:dt)
+ sim.by.step(target: USC.REST_Y, response:0.18, damping:0.75, dt:dt)
+ } else {
+ sim.bx.step(target: tx, response:0.35, damping:0.70, dt:dt)
+ sim.by.step(target: USC.REST_Y, response:0.35, damping:0.70, dt:dt)
+ }
+ }
+
+ // Tilt
+ let tiltTarget = isDragging ? max(-0.18, min(0.18, sim.bx.vel * 0.0015)) : 0.0
+ sim.tilt = usLerp(sim.tilt, tiltTarget, 1 - pow(0.0005, dt))
+
+ // Mouth — post-drop close only after drop has actually happened
+ let t = sim.t
+ if !isDragging && t >= USC.T_SUCK_END {
+ sim.mouth.v = max(0, usLerp(USC.MOUTH_MAX, 0, usEIn(usSeg(t, USC.T_SUCK_END, USC.T_CLOSE_END))))
+ } else {
+ var mt = 0.0
+ if sim.entered >= 0 {
+ mt = (sim.locked || !isDragging) ? USC.MOUTH_OPEN : USC.MOUTH_AJAR
+ }
+ if !isDragging && t < USC.T_SUCK_END { mt = USC.MOUTH_MAX }
+ sim.mouth.step(target: mt, response:0.25, damping:0.60, dt:dt)
+ if sim.mouth.v < 0 { sim.mouth.v = 0 }
+ }
+ }
+
+ // MARK: - Frame computation (mirrors reference frame(t))
+
+ private func computeFrame(t: Double) -> USFrame {
+ var f = USFrame()
+ f.t = t
+ f.cursorX = cursorX; f.cursorY = cursorY
+ f.uploadDuration = uploadDuration
+ f.progEnd = progEnd
+ f.growStart = growStart
+ f.growEnd = growEnd
+
+ let entered = sim.entered >= 0 ? sim.entered : 1e9
+ let isDragging = (dropWallTime == nil)
+ // For all phase-based calculations, clamp t to just before T_DROP while pre-drop
+ // so long hovers don't accidentally trigger post-drop visuals.
+ let pt = isDragging ? min(t, USC.T_DROP - USC.DT) : t
+
+ // Morph: 0→1 (entry), 1→0 (shrink to ball), 0→1 (grow back to box at choose)
+ var morph: Double
+ if pt < USC.T_CHEW_END {
+ morph = usEBack(usSeg(pt, entered, entered + 0.38))
+ } else if pt < growStart {
+ morph = 1 - usEOut(usSeg(pt, USC.T_CHEW_END, USC.T_SHRINK_END))
+ } else {
+ morph = usEBack(usSeg(pt, growStart, growEnd))
+ }
+ morph = max(0, min(morph, 1.08))
+ f.morph = morph
+
+ // Position / diameter
+ var x = sim.bx.v, y = sim.by.v, d = USC.D_BOX
+ if pt >= USC.T_CHEW_END && pt < USC.T_PROG_START {
+ let k = usEInOut(usSeg(pt, USC.T_CHEW_END, USC.T_SHRINK_END))
+ x = usLerp(sim.bx.v, USC.BAR_X0, k)
+ y = usLerp(sim.by.v, USC.BAR_Y, k)
+ d = usLerp(USC.D_BOX, 14, k)
+ }
+ if pt >= USC.T_PROG_START {
+ let p = usProgressAt(pt, progStart: USC.T_PROG_START, progEnd: progEnd)
+ x = usLerp(USC.BAR_X0, USC.BAR_X1, p); y = USC.BAR_Y; d = 14
+ }
+ if pt >= progEnd {
+ x = USC.BAR_X1
+ y = USC.BAR_Y - 8 * sin(.pi * usSeg(pt, progEnd, progEnd + 0.20))
+ }
+ if pt >= growStart {
+ x = usLerp(USC.BAR_X1, USC.CHOOSE_X, usEInOut(usSeg(pt, growStart, growEnd)))
+ y = usLerp(USC.BAR_Y, USC.CHOOSE_Y, usEInOut(usSeg(pt, growStart, growEnd)))
+ d = usLerp(14, USC.CHOOSE_D, usEBack(usSeg(pt, growStart, growEnd)))
+ }
+ f.x = x; f.y = y; f.d = d
+
+ // Squeeze
+ var sx = 1.0, sy = 1.0
+ if pt >= USC.T_DROP && pt < USC.T_SUCK_START {
+ let k = usEOut(usSeg(pt, USC.T_DROP, USC.T_SUCK_START))
+ sy = usLerp(1, 0.92, k); sx = usLerp(1, 1.06, k)
+ }
+ if pt >= USC.T_SUCK_START && pt < USC.T_SUCK_END {
+ let k = usEInOut(usSeg(pt, USC.T_SUCK_START, USC.T_SUCK_END))
+ sy = usLerp(0.92, 1.06, k); sx = usLerp(1.06, 0.97, k)
+ }
+ if pt >= USC.T_SUCK_END && pt < USC.T_CHEW1 {
+ sy = usSqueezeY(pt); sx = usSqueezeX(pt)
+ }
+ if pt >= USC.T_CHEW1 && pt < USC.T_CHEW_END {
+ let k = ((pt-USC.T_CHEW1).truncatingRemainder(dividingBy: 0.14)) / 0.14
+ sy = 1 - 0.05*sin(.pi*k); sx = 1 + 0.03*sin(.pi*k)
+ }
+ if pt >= USC.T_CHEW_END && pt < USC.T_SHRINK_END {
+ let k = usSeg(pt, USC.T_CHEW_END, USC.T_SHRINK_END)
+ sy = 1 + 0.12*sin(.pi*k); sx = 1 - 0.06*sin(.pi*k)
+ }
+ if pt >= USC.T_PROG_START && pt < progEnd {
+ let v = (usProgressAt(pt+0.01, progStart: USC.T_PROG_START, progEnd: progEnd)
+ - usProgressAt(pt, progStart: USC.T_PROG_START, progEnd: progEnd)) / 0.01
+ let st = max(0, min(1, v*0.18))
+ sx = 1 + 0.25*st; sy = 1 - 0.15*st
+ }
+ if pt >= growStart && pt < growEnd {
+ sy = 1 + 0.06*sin(.pi * usSeg(pt, growStart, growEnd))
+ }
+ f.sx = sx; f.sy = sy; f.tilt = sim.tilt
+ f.hop = (sim.lockAt > 0 && isDragging)
+ ? -5 * sin(.pi * usSeg(pt, sim.lockAt, sim.lockAt + 0.15)) : 0
+
+ f.mouth = sim.mouth.v
+
+ // Eyes
+ var eye: USEyeShape = .pill
+ if sim.locked && pt < USC.T_SUCK_END { eye = .cup }
+ if pt >= USC.T_SUCK_END && pt < USC.T_CHEW_END + 0.10 { eye = .content }
+ if pt >= progEnd && pt < growEnd + 0.30 { eye = .content }
+ f.eye = eye
+
+ let lkx = pt < USC.T_SUCK_END ? cursorX - x : (pt < USC.T_PROG_START ? 0.0 : 40.0)
+ let lky = pt < USC.T_SUCK_END ? (cursorY+10) - y : 0.0
+ f.lookX = max(-1, min(1, lkx/200)); f.lookY = max(-1, min(1, lky/150))
+
+ f.fileVisible = pt < USC.T_SUCK_END
+ f.suck = usSeg(pt, USC.T_SUCK_START, USC.T_SUCK_END)
+
+ // Content alpha values
+ f.zoneOver = sim.entered >= 0 && pt < USC.T_CHEW_END
+ f.zoneAlpha = 1 - usSeg(pt, USC.T_CHEW_END, USC.T_CHEW_END + 0.20)
+ f.textAlpha = f.zoneAlpha * ((x > USC.TEXT_X-40 && isDragging) ? 0.25 : 1.0)
+ f.barReveal = usEOut(usSeg(pt, USC.T_BAR_IN, USC.T_BAR_IN+0.25))
+ * (1 - usSeg(pt, growStart, growStart+0.20))
+ f.barAlpha = usSeg(pt, USC.T_BAR_IN+0.05, USC.T_BAR_IN+0.25)
+ * (1 - usSeg(pt, growStart, growStart+0.20))
+ f.progress = usProgressAt(pt, progStart: USC.T_PROG_START, progEnd: progEnd)
+ f.flash = pt >= progEnd ? sin(.pi * usSeg(pt, progEnd, progEnd+0.30)) : 0
+ f.check = pt >= progEnd ? usEBack(usSeg(pt, progEnd, progEnd+0.25)) : 0
+ let hoverGreen = f.zoneOver ? 0.22 : 0.0
+ var uploadGreen = 0.0
+ if pt >= USC.T_PROG_START {
+ // Grows gradually from 0→0.50 as upload progresses (tied to f.progress)
+ let baseGreen = f.progress * 0.50
+ // Brief flash burst at completion
+ let flashExtra = pt >= progEnd ? 0.20 * sin(.pi * usSeg(pt, progEnd, progEnd + 0.40)) : 0
+ // Fade out as Mochi grows back to choose position
+ let fadeOut = 1.0 - usSeg(pt, growEnd, growEnd + 0.60)
+ uploadGreen = (baseGreen + flashExtra) * fadeOut
+ }
+ f.greenWash = max(hoverGreen, uploadGreen)
+ f.chooseAlpha = usSeg(pt, growStart+0.15, growEnd)
+
+ // Mouth rect in island coords (used by drawFile for clipping)
+ let R = d / 2 / 1.04
+ let mc = max(0, min(morph, 1.0))
+ let rx = R * (1.04 - 0.04*mc)
+ let ry = R * (0.97 - 0.03*mc)
+ let mh = f.mouth * R * mc
+ let mw = 2*rx - 0.24*R
+ let mxOff = -mw/2
+ let myOff = -ry + 0.10*R
+ f.mouthRect = USMouthRect(
+ x: x + mxOff * sx,
+ y: y + f.hop + myOff * sy,
+ w: mw * sx,
+ h: mh * sy
+ )
+ return f
+ }
+}
diff --git a/NotchBuddy/Sources/App/VercelPoller.swift b/NotchBuddy/Sources/App/VercelPoller.swift
new file mode 100644
index 00000000..41b24923
--- /dev/null
+++ b/NotchBuddy/Sources/App/VercelPoller.swift
@@ -0,0 +1,108 @@
+import Foundation
+
+// MARK: - VercelPoller
+// Polls Vercel API for latest deployments every 30s.
+// On new terminal deployment: updates integration_vercel task state + AppState.vercelDeployments.
+
+final class VercelPoller: @unchecked Sendable {
+ static let shared = VercelPoller()
+ private var timer: DispatchSourceTimer?
+ private var lastDeploymentId: String = ""
+
+ private init() {}
+
+ func start() {
+ guard timer == nil else { return }
+ let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
+ t.schedule(deadline: .now() + 5, repeating: 30)
+ t.setEventHandler { [weak self] in self?.poll() }
+ t.resume()
+ timer = t
+ }
+
+ // MARK: - Poll
+
+ private func poll() {
+ guard let token = KeychainStore.shared.get("vercel-token") else { return }
+
+ // Fetch last 5 terminal deployments
+ guard let url = URL(string: "https://api.vercel.com/v6/deployments?limit=5") else { return }
+ var req = URLRequest(url: url, timeoutInterval: 10)
+ req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
+ req.setValue("application/json", forHTTPHeaderField: "Accept")
+
+ URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
+ guard let self else { return }
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ guard let data, code == 200 else { return }
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let rawList = json["deployments"] as? [[String: Any]] else { return }
+
+ // Only terminal deployments (READY, ERROR, CANCELED)
+ let terminal = ["READY", "ERROR", "CANCELED"]
+ let parsed = rawList
+ .compactMap { self.parseDeployment($0) }
+ .filter { terminal.contains($0.state) }
+ guard !parsed.isEmpty else { return }
+
+ DispatchQueue.main.async { self.handleDeployments(parsed) }
+ }.resume()
+ }
+
+ private func parseDeployment(_ d: [String: Any]) -> VercelDeployment? {
+ guard let uid = d["uid"] as? String,
+ let name = d["name"] as? String,
+ let state = d["state"] as? String else { return nil }
+
+ let url = (d["url"] as? String) ?? ""
+ let createdAtMs = (d["createdAt"] as? Double) ?? 0
+ let createdAt = Date(timeIntervalSince1970: createdAtMs / 1000)
+
+ let meta = d["meta"] as? [String: Any]
+ let commitMessage = meta?["githubCommitMessage"] as? String
+ ?? meta?["gitlabCommitMessage"] as? String
+ ?? meta?["bitbucketCommitMessage"] as? String
+ let branch = meta?["githubCommitRef"] as? String
+ ?? meta?["gitlabCommitRef"] as? String
+ ?? meta?["bitbucketBranch"] as? String
+
+ return VercelDeployment(id: uid, projectName: name, url: url, state: state,
+ createdAt: createdAt, commitMessage: commitMessage, branch: branch)
+ }
+
+ @MainActor
+ private func handleDeployments(_ deployments: [VercelDeployment]) {
+ let appState = AppState.shared
+ appState.vercelDeployments = deployments
+
+ // Apply project filter (empty = all projects)
+ let filter = appState.vercelProjectFilter
+ let filtered = filter.isEmpty ? deployments : deployments.filter { filter.contains($0.projectName) }
+ guard let latest = filtered.first else { return }
+ guard latest.id != lastDeploymentId else { return }
+ lastDeploymentId = latest.id
+
+ guard let idx = appState.tasks.firstIndex(where: { $0.id == "integration_vercel" }) else { return }
+ let focused = appState.focusId == "integration_vercel"
+
+ appState.tasks[idx].state = latest.isSuccess ? .finished : .error
+ appState.tasks[idx].steps = [latest.projectName]
+
+ if !focused {
+ appState.tasks[idx].pillBadge = latest.isSuccess ? .finished : .error
+ }
+ SoundEngine.shared.play(latest.isSuccess ? "finish" : "error")
+
+ // Reveal compact island so user sees the badge
+ NotificationCenter.default.post(name: .hookReveal, object: nil)
+
+ // Auto-clear task state after 60s (deployments list stays)
+ DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
+ guard let i = appState.tasks.firstIndex(where: { $0.id == "integration_vercel" }) else { return }
+ guard appState.tasks[i].state == .finished || appState.tasks[i].state == .error else { return }
+ appState.tasks[i].state = .idle
+ appState.tasks[i].steps = []
+ appState.tasks[i].pillBadge = nil
+ }
+ }
+}
diff --git a/NotchBuddy/Sources/App/WindowContextCapture.swift b/NotchBuddy/Sources/App/WindowContextCapture.swift
new file mode 100644
index 00000000..068a7b04
--- /dev/null
+++ b/NotchBuddy/Sources/App/WindowContextCapture.swift
@@ -0,0 +1,59 @@
+import AppKit
+import ApplicationServices
+
+// MARK: - Window context capture (M8)
+
+enum WindowContextCapture {
+
+ /// Returns a PromptContext from the given app (typically the last app active before NotchBuddy).
+ /// Uses AXUIElement for window title (requires Accessibility permission).
+ /// Uses AppleScript for browser URL (Safari, Chrome, Arc, Firefox, Edge).
+ static func captureActive(from app: NSRunningApplication? = NSWorkspace.shared.frontmostApplication) -> PromptContext? {
+ guard let app, let appName = app.localizedName else { return nil }
+
+ let pid = app.processIdentifier
+ let axApp = AXUIElementCreateApplication(pid)
+
+ // --- Window title ---
+ var title = ""
+ var windowRef: CFTypeRef?
+ if AXUIElementCopyAttributeValue(axApp, kAXFocusedWindowAttribute as CFString, &windowRef) == .success,
+ let windowRef {
+ // swiftlint:disable force_cast
+ let axWindow = windowRef as! AXUIElement
+ var titleRef: CFTypeRef?
+ if AXUIElementCopyAttributeValue(axWindow, kAXTitleAttribute as CFString, &titleRef) == .success,
+ let t = titleRef as? String {
+ title = t
+ }
+ }
+
+ // --- Browser URL ---
+ let url = browserURL(for: app)
+
+ return .window(appName: appName, title: title, url: url)
+ }
+
+ // MARK: - Private
+
+ private static let browserScripts: [String: String] = [
+ "com.apple.Safari":
+ "tell application \"Safari\" to return URL of current tab of front window",
+ "com.google.Chrome":
+ "tell application \"Google Chrome\" to return URL of active tab of front window",
+ "company.thebrowser.Browser":
+ "tell application \"Arc\" to return URL of active tab of front window",
+ "org.mozilla.firefox":
+ "tell application \"Firefox\" to return URL of active tab of front window",
+ "com.microsoft.edgemac":
+ "tell application \"Microsoft Edge\" to return URL of active tab of front window",
+ ]
+
+ private static func browserURL(for app: NSRunningApplication) -> String? {
+ guard let bundleId = app.bundleIdentifier,
+ let script = browserScripts[bundleId] else { return nil }
+ var error: NSDictionary?
+ let result = NSAppleScript(source: script)?.executeAndReturnError(&error)
+ return error == nil ? result?.stringValue : nil
+ }
+}
diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.yml
new file mode 100644
index 00000000..c03dc0ff
--- /dev/null
+++ b/NotchBuddy/project.yml
@@ -0,0 +1,51 @@
+name: NotchBuddy
+options:
+ bundleIdPrefix: fr.louisraille
+ deploymentTarget:
+ macOS: "15.0"
+ xcodeVersion: "27.0"
+ createIntermediateGroups: true
+
+settings:
+ base:
+ SWIFT_VERSION: "6.0"
+ ENABLE_HARDENED_RUNTIME: YES
+ CODE_SIGN_STYLE: Manual
+ CODE_SIGNING_REQUIRED: NO
+ CODE_SIGNING_ALLOWED: NO
+ OTHER_SWIFT_FLAGS: "-strict-concurrency=complete"
+
+targets:
+ NotchBuddy:
+ type: application
+ platform: macOS
+ sources:
+ - path: Sources
+ type: group
+ - path: Assets.xcassets
+ buildPhase: resources
+ - path: Resources/sounds
+ buildPhase: resources
+ type: folder
+ info:
+ path: Resources/Info.plist
+ properties:
+ CFBundleName: Coucou
+ CFBundleDisplayName: Coucou
+ CFBundleIdentifier: fr.louisraille.NotchBuddy
+ CFBundleVersion: "1"
+ CFBundleShortVersionString: "0.1"
+ CFBundlePackageType: APPL
+ LSUIElement: YES
+ NSHighResolutionCapable: YES
+ NSSupportsAutomaticGraphicsSwitching: YES
+ NSAppleEventsUsageDescription: "Pour sauter au terminal et envoyer des mails."
+ NSAccessibilityUsageDescription: "Pour lire le titre de la fenêtre active et l'attacher comme contexte."
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: fr.louisraille.NotchBuddy
+ PRODUCT_NAME: Coucou
+ INFOPLIST_FILE: Resources/Info.plist
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
+ MACOSX_DEPLOYMENT_TARGET: "15.0"
+ ENABLE_SANDBOX: NO
diff --git a/PUBLIER-GITHUB.md b/PUBLIER-GITHUB.md
new file mode 100644
index 00000000..f2bde44d
--- /dev/null
+++ b/PUBLIER-GITHUB.md
@@ -0,0 +1,44 @@
+# Publier Coucou en open source sur GitHub
+
+But : un repo public propre, qu'on peut installer en 30 secondes, avec une première release téléchargeable.
+Le README (anglais), la LICENSE (MIT), CONTRIBUTING.md et les médias (`docs/media/`) sont déjà prêts.
+
+## Règles
+- Ne publie rien tant que les vérifications de l'étape 1 ne sont pas vertes.
+- Ne touche pas au comportement de l'app. Ne corrige pas de bug sans que je te le demande.
+- `_prive/` et `.claude/` ne doivent jamais partir sur GitHub (déjà dans `.gitignore`, vérifie).
+- Garde mon historique git local intact : la publication part d'une branche neuve.
+
+## 1. Vérifications avant publication
+- `gh auth status` : si je ne suis pas connecté, arrête-toi et dis-moi de lancer `gh auth login`.
+- Aucun secret dans les fichiers suivis : cherche `sk-ant-`, `sk_live_`, `sk_test_`, `rk_live`, `whsec_`, `ghp_`, `github_pat_`, `re_`, jetons JWT, URL d'instance n8n, e-mails perso. Rien ne doit sortir à part les textes d'aide des champs de réglages.
+- Aucun chemin perso (`/Users/louis`) dans les fichiers suivis.
+- `xcodegen` puis build Release sans erreur.
+
+## 2. Fichiers GitHub
+Crée :
+- `.github/ISSUE_TEMPLATE/bug_report.md` : champs « What happened / What you expected / How to reproduce / macOS version / Mac model / Coucou version », label `bug`.
+- `.github/ISSUE_TEMPLATE/feature_request.md` : « What would you like Mochi to do? / Why would it be useful? », label `enhancement`.
+- `.github/workflows/build.yml` : sur push et PR, runner `macos-latest`, installe XcodeGen, `xcodegen`, `xcodebuild -scheme NotchBuddy -configuration Release build CODE_SIGNING_ALLOWED=NO`.
+- `.github/workflows/release.yml` : sur tag `v*`, même build, signature ad hoc (`codesign --force --deep -s -`), zip `Coucou.zip` (avec `ditto -c -k --keepParent`), publication dans la release du tag.
+
+## 3. Build de la release
+- Build Release en local, signature ad hoc, `Coucou.zip` avec `ditto`.
+- Lance l'app depuis le zip décompressé pour vérifier qu'elle démarre (coucou, menu, réglages).
+
+## 4. Publication
+1. Remplace `OWNER/REPO` dans `README.md` et dans `docs/*.html` par mon login GitHub (`gh api user --jq .login`) et le nom du repo : `coucou`. Remplace `CONTACT_EMAIL` dans `docs/*.html` par l'adresse que je te donne (demande-la moi si je ne l'ai pas précisée).
+2. Branche neuve sans historique : `git checkout --orphan public`, `git add -A`, vérifie `git status` (ni `_prive/`, ni `.claude/`), commit « Coucou — first public release ».
+3. `gh repo create coucou --public --source . --remote origin --description "A tiny friend that lives in your MacBook's notch and keeps an eye on your Claude Code sessions."`
+4. `git push -u origin public:main`, puis reviens sur ma branche habituelle.
+5. Sujets du repo : `macos`, `notch`, `claude-code`, `claude`, `anthropic`, `swift`, `swiftui`, `menubar-app`, `dynamic-island`, `ai-agents`, `macos-app`, `open-source`.
+6. Tag `v0.1.0`, release « Coucou 0.1.0 » avec `Coucou.zip` et des notes courtes en anglais (fonctionnalités + premier lancement : System Settings → Privacy & Security → « Open Anyway », ou la commande `xattr` du README).
+
+## 5. Site et pages légales (GitHub Pages)
+- Active GitHub Pages sur la branche `main`, dossier `/docs` : `gh api -X POST repos/<login>/coucou/pages -f "source[branch]=main" -f "source[path]=/docs"`.
+- Vérifie que ces pages répondent : `index.html`, `privacy.html`, `terms.html`, `support.html`, `legal.html`.
+- Ajoute en bas du `README.md` une ligne : Website · Privacy · Terms · Support, avec les liens GitHub Pages.
+- Mets l'URL du site comme « Website » du repo : `gh repo edit --homepage https://<login>.github.io/coucou/`.
+
+## 6. Fin
+Donne-moi l'URL du repo, de la release et des pages (confidentialité, assistance) pour App Store Connect, et rappelle-moi d'ajouter l'image de partage (Settings → Social preview) avec `docs/media/coucou.png`.
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..d78243c8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,127 @@
+<div align="center">
+
+<img src="NotchBuddy/Assets.xcassets/AppIcon.appiconset/icon_256x256.png" width="96" alt="Coucou icon">
+
+# Coucou
+
+**A tiny friend that lives in your MacBook's notch and keeps an eye on your Claude Code sessions.**
+
+Approve permissions, answer questions, watch your agents work, drop a file, chat with Claude — all without leaving what you're doing.
+
+![macOS 15+](https://img.shields.io/badge/macOS-15%2B-black?logo=apple)
+![Swift 6](https://img.shields.io/badge/Swift-6-F05138?logo=swift&logoColor=white)
+![SwiftUI](https://img.shields.io/badge/SwiftUI-native-0A84FF)
+![License: MIT](https://img.shields.io/badge/license-MIT-green)
+![GitHub stars](https://img.shields.io/github/stars/Louis-CFM/coucou?style=social)
+
+<img src="docs/media/demo.gif" width="760" alt="Coucou in action">
+
+</div>
+
+---
+
+## Why
+
+Some studios showed off gorgeous notch companions… and never let anyone use them.
+**Coucou is the open version.** Every line of code, every animation, every sound — free to use, read, fork and remix.
+
+Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch, waves hello, follows your cursor with its eyes, gets annoyed when you poke it (and dizzy if you insist), and tells you the moment Claude Code needs you.
+
+## Features
+
+- 🤖 **Claude Code, live** — see every session in your notch: what it reads, edits and runs, step by step. Finished? Mochi does a happy little jump.
+- ✅ **Approve from the notch** — permission requests show up with **Allow / Always / Deny**. Questions come with their answer buttons. One click, back to work.
+- 🧑‍💻 **Jump to the right terminal** — open the exact terminal window of a session.
+- 💬 **Ask Claude anything** — built-in chat, straight from the notch.
+- 📎 **Drop a file on the notch** — Mochi turns into a box and swallows it, then ask a question about it or send it by email (Mail.app).
+- 🪟 **Drag Mochi onto any window** — attach that window as context for Claude.
+- 🔌 **Integrations** — Stripe payments, n8n workflows, GitHub, Vercel deployments, Resend emails, Notion, Cal.com. Each one gets its own little colored Mochi.
+- 🎭 **A real character** — idle breathing, blinks, eyes on a sphere that follow your mouse, emotes, 28 handcrafted sounds, a greeting on launch.
+- 🫥 **Invisible when idle** — hides away when nothing is running, peeks out when you hover the notch.
+- 🔒 **Private by design** — no telemetry, no account. Keys live in your macOS Keychain. The app only talks to the services you plug in.
+
+<table>
+<tr>
+<td><img src="docs/media/claude-code.png" alt="Claude Code session"></td>
+<td><img src="docs/media/stripe.png" alt="Stripe payments"></td>
+</tr>
+<tr>
+<td><img src="docs/media/chat.png" alt="Chat with Claude"></td>
+<td><img src="docs/media/dizzy.png" alt="Too many hits"></td>
+</tr>
+</table>
+
+## Install
+
+### Download
+
+1. Grab the latest `Coucou.zip` from [Releases](https://github.com/Louis-CFM/coucou/releases).
+2. Unzip and move **Coucou.app** to `/Applications`.
+3. First launch: Coucou isn't notarized by Apple (it's a free side project), so macOS will say it can't verify it. Either:
+ - open **System Settings → Privacy & Security**, scroll down and click **Open Anyway**, or
+ - run once in Terminal: `xattr -dr com.apple.quarantine /Applications/Coucou.app`
+
+### Build from source
+
+Requirements: macOS 15+, Xcode 16+, [XcodeGen](https://github.com/yonaskolb/XcodeGen).
+
+```bash
+brew install xcodegen
+git clone https://github.com/Louis-CFM/coucou.git
+cd coucou/NotchBuddy
+xcodegen
+open NotchBuddy.xcodeproj # then ⌘R
+```
+
+## Setup
+
+Click the Coucou icon in the menu bar → **Settings…**
+
+| What | Why | Where the key goes |
+|---|---|---|
+| **Claude Code hooks** | live sessions, approvals, questions | **Install hooks** — Coucou backs up `~/.claude/settings.json`, merges its hooks and shows you the diff before writing anything |
+| **Anthropic API key** | chat and questions about files/windows | Keychain |
+| Stripe, n8n, GitHub, Vercel, Resend, Notion, Cal.com | the integration pills | Keychain, all optional |
+
+If Coucou isn't running, the hook exits immediately: **Claude Code is never blocked.**
+
+## Things to try
+
+| Do this | Mochi does that |
+|---|---|
+| Hover the notch | peeks out and says hi 👋 |
+| Click it | opens |
+| Hover Mochi | blinks, eyes grow |
+| Click Mochi | squish + annoyed |
+| Click 3 times fast | 😵‍💫 dizzy for a few seconds |
+| Drag a file onto the notch | turns into a box and swallows it |
+| Drag Mochi onto a window | attaches it as context |
+
+## How it works
+
+- **Island**: a borderless `NSPanel` hugging the notch, driven by a small state machine (`hidden → petit → home`).
+- **Character**: drawn in SwiftUI `Canvas` + `TimelineView` at 60 fps — squircle body, eyes projected on a sphere, spring animations. No Rive, no Lottie, no images.
+- **Claude Code**: a tiny `nb-hook` script receives hook events and forwards them over a Unix socket to the app. For approvals it waits for your click, then answers the hook.
+- **Integrations**: lightweight pollers, paused when nothing is watching.
+- **Sounds**: 28 short WAVs played through preloaded `AVAudioPlayer`s.
+
+Everything is native Swift 6 / SwiftUI / AppKit with **zero third-party dependencies**.
+
+## Contributing
+
+Issues and PRs are very welcome — new integrations, new emotes, new sounds, bug fixes. See [CONTRIBUTING.md](CONTRIBUTING.md).
+
+## Credits
+
+Built by [Louis Raillé](https://louisraille.fr) with Claude Code.
+Inspired by the notch-companion concepts shared by design studios — this project is independent and not affiliated with any of them.
+
+## License
+
+[MIT](LICENSE) — do whatever you want, just keep the notice.
+
+<div align="center">
+
+**If Mochi made you smile, a ⭐ helps a lot.**
+
+</div>
diff --git a/design/animations/greeting-v2.html b/design/animations/greeting-v2.html
new file mode 100644
index 00000000..7b0c6ec5
--- /dev/null
+++ b/design/animations/greeting-v2.html
@@ -0,0 +1,216 @@
+<!doctype html>
+<html lang="fr">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+<title>Notch Buddy · coucou d'entrée v2 (référence)</title>
+<style>
+:root{box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px);
+ --bg:#E2E4E8;--ink:#16171B;--muted:#5F646D;--panel:#fff;--line:#D1D4DA}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#131417;--ink:#ECEDEF;--muted:#9A9FA8;--panel:#1E2024;--line:#32353B}}
+:root[data-theme="dark"]{--bg:#131417;--ink:#ECEDEF;--muted:#9A9FA8;--panel:#1E2024;--line:#32353B}
+*,*::before,*::after{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter",system-ui,sans-serif}
+.wrap{max-width:1000px;margin:0 auto;padding:26px 20px 40px}
+h1{margin:0;font-size:24px;letter-spacing:-.02em}
+p{margin:6px 0 16px;color:var(--muted);font-size:14px;line-height:1.45;max-width:74ch}
+.stage{background:#07080A;border-radius:18px;overflow:hidden}
+canvas{display:block;width:100%;height:auto}
+.bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:14px}
+button{appearance:none;border:1px solid var(--line);background:var(--panel);color:var(--ink);border-radius:999px;padding:8px 14px;font:inherit;font-size:13.5px;cursor:pointer}
+button.on{background:var(--ink);color:var(--panel);border-color:var(--ink)}
+input[type=range]{flex:1;min-width:200px}
+.t{font-family:"SF Mono",ui-monospace,Menlo,monospace;font-size:13px;min-width:150px}
+.phase{font-size:14px;font-weight:600;min-width:300px}
+</style>
+</head>
+<body>
+<div class="wrap">
+ <h1>Coucou d'entrée v2, avec le Mochi de Louis</h1>
+ <p>Tout est une fonction du temps et de l'instant où la souris quitte le notch. Repère de l'island, en points. « Souris sur le notch » : le coucou se termine et l'island reste ouverte. « Retirer la souris » : l'island se replie en petit tout de suite, même en pleine animation.</p>
+ <div class="stage"><canvas id="c" width="1280" height="440"></canvas></div>
+ <div class="bar">
+ <button id="play" class="on">Pause</button>
+ <button id="restart">Recommencer</button>
+ <button id="slow">Ralenti ×4</button>
+ <button id="hover">Souris sur le notch</button>
+ <button id="leave">Retirer la souris maintenant</button>
+ <button id="snd">Son</button>
+ <span class="t" id="t">t = 0.000 s</span>
+ </div>
+ <div class="bar"><input type="range" id="scrub" min="0" max="6.4" step="0.001" value="0"><span class="phase" id="phase"></span></div>
+</div>
+<script>
+(()=>{
+/* ====================== CONSTANTES (repère island, points) ====================== */
+const W=640, H=220, CX=320;
+const NOTCH={w:184,h:32};
+const BIG={w:640,h:150}; // island ouverte pendant le coucou
+const SMALL={w:NOTCH.w+104,h:32}; // « petit » : notch + les deux oreilles
+const CARD={x:10,y:36,w:620,h:104,r:20};
+const C0={x:320,y:90}; // centre du Mochi pendant le coucou
+const HB=58; // hauteur du corps du Mochi pendant le coucou
+const ASPECT=1.34; // largeur / hauteur du Mochi de Louis
+const EAR={x:27,y:16,hb:17}; // Mochi dans l'oreille gauche du petit
+const MINI=['#E86A6A','#3E86E0','#EFAE5A','#8C73F2'];
+const T={grow:.45, squint0:.60, squint1:.82, dip0:1.25, dip1:1.40, pop0:1.36, pop1:1.52, waveEnd:2.45, content0:2.45, content1:2.58,
+ tuck0:2.58, tuck1:2.80, badge:2.72, down0:2.85, down1:3.20, blink2:3.80, tint0:3.85, tint1:4.15, end:4.60, autoLeave:4.90};
+const COLLAPSE=.34; // durée du repli en petit
+
+/* ====================== OUTILS ====================== */
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)), lerp=(a,b,t)=>a+(b-a)*t, seg=(t,a,b)=>clamp((t-a)/(b-a),0,1);
+const E={out:t=>1-Math.pow(1-t,3),in:t=>t*t*t,inOut:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,
+ back:t=>{const c1=1.70158,c3=c1+1;return 1+c3*Math.pow(t-1,3)+c1*Math.pow(t-1,2)}};
+let seed=7; const rnd=()=>{ seed=(seed*1103515245+12345)&0x7fffffff; return seed/0x7fffffff };
+const RINGS=[.10,.20,.30,.45,.60].map(t0=>({t0,dots:Array.from({length:170},()=>({a:rnd()*Math.PI*2,j:(rnd()-.5)*.22,s:.7+rnd()*.9,al:.45+rnd()*.55}))}));
+const STREAKS=Array.from({length:16},(_,i)=>({a:(i/16)*Math.PI*2+(rnd()-.5)*.3,sp:230+rnd()*260,len:6+rnd()*9,t0:.08+rnd()*.14,col:['#3B9EFF','#F29B38','#FF5A4E','#2EC4A0','#A78BFA'][i%5]}));
+
+/* ====================== POSE DU COUCOU À L'INSTANT t ====================== */
+function greetPose(t){
+ const p={};
+ // island du notch vers la grande taille (0 → 0,5 s, léger dépassement)
+ const gx=seg(t,0,.5), g=Math.sin(Math.PI*gx/2)+.04*Math.sin(Math.PI*gx)*gx;
+ p.iw=lerp(NOTCH.w,BIG.w,g); p.ih=lerp(NOTCH.h,BIG.h,g); p.ir=lerp(12,30,clamp(g,0,1)); p.header=seg(t,.35,.6); p.card=seg(t,.18,.45);
+ // corps : naît minuscule au centre du notch et grandit
+ const gg=E.back(seg(t,.02,T.grow)); p.hb=lerp(3,HB,gg); p.x=C0.x; p.y=lerp(16,C0.y,E.out(seg(t,.02,T.grow)));
+ p.sx=1; p.sy=1; p.tilt=0;
+ // plongeon en avant (1,25 → 1,40) : le corps descend, s'écrase, les yeux roulent vers le bas et disparaissent
+ if(t>=T.dip0&&t<T.pop1){ const k=Math.sin(Math.PI*seg(t,T.dip0,T.pop1)); p.y+=p.hb*.22*k; p.sy=1-.06*k; p.sx=1+.04*k }
+ // coucou : le corps se balance de gauche à droite et penche un peu
+ if(t>=T.pop1&&t<T.tuck1){ const w=t-T.pop1, fade=1-seg(t,T.tuck0,T.tuck1); p.x+=Math.sin(w*2*Math.PI*.9)*p.hb*ASPECT*.05*fade; p.tilt=(Math.sin(w*2*Math.PI*.9+.6)*.05)*fade; p.y+=Math.sin(w*2*Math.PI*1.8)*.8*fade }
+ // il se tasse vers le bas quand les mains rentrent, puis revient
+ if(t>=T.tuck0&&t<T.down1){ const k=Math.sin(Math.PI*seg(t,T.tuck0,T.down1)); p.y+=p.hb*.12*k }
+ // yeux (points)
+ p.eye='dot'; p.open=1; p.eyeRoll=0;
+ if(t>=T.squint0&&t<T.squint1) p.eye='happy';
+ if(t>=T.content0&&t<T.content1) p.eye='content';
+ if(t>=T.down0&&t<T.down1) p.eye='content';
+ if(t>=T.dip0&&t<T.pop1){ p.eyeRoll=Math.sin(Math.PI*seg(t,T.dip0,T.pop1)) } // 0 → 1 → 0 : les yeux glissent vers le bas et sortent du corps
+ const blink=tb=>{ const k=seg(t,tb,tb+.12); return k>0&&k<1?1-Math.sin(Math.PI*k)*.94:1 }; p.open=Math.min(blink(1.95),blink(T.blink2));
+ // regard (-1..1)
+ p.lookX=0; p.lookY=0;
+ if(t>=T.squint1&&t<T.dip0){ p.lookY=-.2 }
+ if(t>=T.pop1&&t<T.content0){ p.lookX=.55; p.lookY=-.45 } // regarde Louis, en haut à droite
+ if(t>=T.content0&&t<T.down1){ p.lookX=-.3; p.lookY=.6 }
+ if(t>=T.down1){ const k=E.inOut(seg(t,T.down1,T.down1+.35)); p.lookX=lerp(-.3,0,k); p.lookY=lerp(.6,0,k) }
+ // mains : 0 = cachées sous le corps, 1 = sorties
+ p.handL=t<T.tuck0?E.back(seg(t,T.pop0,T.pop0+.14)):1-E.in(seg(t,T.tuck0,T.tuck1-.03));
+ p.handR=t<T.tuck0?E.back(seg(t,T.pop0+.04,T.pop0+.18)):1-E.in(seg(t,T.tuck0+.03,T.tuck1));
+ p.wave=t>=T.pop1&&t<T.tuck0?(t-T.pop1):-1;
+ // badge et teinte : SEULEMENT si une tâche tourne (ici oui, pour montrer)
+ p.badge=E.back(seg(t,T.badge,T.badge+.28)); p.tint=.6*E.inOut(seg(t,T.tint0,T.tint1));
+ p.halo=E.out(seg(t,.3,.7)); p.haloBlue=seg(t,T.tint0,T.tint1);
+ p.minis=0;
+ return p;
+}
+/* pose du « petit » */
+function smallPose(){ return {iw:SMALL.w,ih:SMALL.h,ir:14,header:0,card:0,hb:EAR.hb,x:CX-SMALL.w/2+EAR.x,y:EAR.y,sx:1,sy:1,tilt:0,eye:'dot',open:1,eyeRoll:0,lookX:0,lookY:0,handL:0,handR:0,wave:-1,badge:1,tint:.6,halo:.6,haloBlue:1,minis:1} }
+/* pose finale à l'instant t, avec repli déclenché à tc (tc = Infinity si la souris reste) */
+function pose(t,tc){
+ if(t<tc) return greetPose(Math.min(t,T.end+10));
+ const a=greetPose(tc), b=smallPose(), k=seg(t,tc,tc+COLLAPSE), e=E.inOut(k);
+ const p={...a};
+ for(const key of ['iw','ih','ir','x','y','hb','badge','tint','halo','haloBlue']) p[key]=lerp(a[key],b[key],e);
+ p.header=a.header*(1-seg(t,tc,tc+.1)); p.card=a.card*(1-seg(t,tc,tc+.18));
+ p.handL=a.handL*(1-seg(t,tc,tc+.15)); p.handR=a.handR*(1-seg(t,tc,tc+.15)); p.wave=a.wave>=0?a.wave:-1;
+ p.tilt=a.tilt*(1-e); p.sx=lerp(a.sx,1,e); p.sy=lerp(a.sy,1,e); p.eyeRoll=a.eyeRoll*(1-e);
+ const bk=seg(t,tc+.14,tc+.26); p.eye='dot'; p.open=bk>0&&bk<1?1-Math.sin(Math.PI*bk)*.94:1; // clignement pendant le trajet
+ p.lookX=a.lookX*(1-e); p.lookY=a.lookY*(1-e);
+ p.minis=E.back(seg(t,tc+.24,tc+.42));
+ p.fx=1-seg(t,tc,tc+.2); // particules restantes qui s'éteignent
+ return p;
+}
+
+/* ====================== DESSIN ====================== */
+const cv=document.getElementById('c'), X=cv.getContext('2d'), K=cv.width/W;
+function rr(a,b,w,h,r){r=Math.max(0,Math.min(r,w/2,h/2));X.beginPath();X.moveTo(a+r,b);X.arcTo(a+w,b,a+w,b+h,r);X.arcTo(a+w,b+h,a,b+h,r);X.arcTo(a,b+h,a,b,r);X.arcTo(a,b,a+w,b,r);X.closePath()}
+function mochiPath(hw,hh){ const n=3.2, p=new Path2D(); for(let i=0;i<=96;i++){ const a=i/96*Math.PI*2, ca=Math.cos(a), sa=Math.sin(a); const px=hw*Math.sign(ca)*Math.pow(Math.abs(ca),2/n), py=hh*Math.sign(sa)*Math.pow(Math.abs(sa),2/n); i?p.lineTo(px,py):p.moveTo(px,py) } p.closePath(); return p }
+const WHITE0='#FBFBFC', WHITE1='#E7E9EC';
+function whiteFill(x0,y0,x1,y1){ const g=X.createLinearGradient(x0,y0,x1,y1); g.addColorStop(0,WHITE0); g.addColorStop(1,WHITE1); return g }
+function drawHandL(p,hw,hh){ // main gauche : petite boule Ø 0,30 × hauteur du corps
+ const k=p.handL; if(k<=.01) return; const hb=hh*2, r=hb*.15*k;
+ const rest={x:-hw-hb*.22, y:hh*.62}, hide={x:-hw*.35, y:hh*.85};
+ let x=lerp(hide.x,rest.x,k), y=lerp(hide.y,rest.y,k);
+ if(p.wave>=0) y+=Math.sin(p.wave*6)*hb*.02; // petit balancement
+ X.save(); X.translate(x,y); X.fillStyle=whiteFill(r,-r,-r,r); X.beginPath(); X.arc(0,0,r,0,Math.PI*2); X.fill();
+ X.strokeStyle='rgba(0,0,0,.08)'; X.lineWidth=.8; X.stroke(); X.restore() }
+function drawHandR(p,hw,hh){ // main droite : capsule 0,40 × 0,22 × hauteur du corps, penchée vers le haut, qui s'agite
+ const k=p.handR; if(k<=.01) return; const hb=hh*2, L=hb*.40*k, T2=hb*.22*k;
+ const rest={x:hw+hb*.20, y:hh*.20}, hide={x:hw*.35, y:hh*.85};
+ let x=lerp(hide.x,rest.x,k), y=lerp(hide.y,rest.y,k), ang=-0.61; // −35°
+ if(p.wave>=0){ const w=p.wave*2*Math.PI*2.5; ang+=Math.sin(w)*.21; y+=Math.sin(w+.8)*hb*.04; x+=Math.cos(w)*hb*.015 }
+ X.save(); X.translate(x,y); X.rotate(ang); X.fillStyle=whiteFill(L/2,-T2/2,-L/2,T2/2); rr(-L/2,-T2/2,L,T2,T2/2); X.fill();
+ X.strokeStyle='rgba(0,0,0,.08)'; X.lineWidth=.8; X.stroke(); X.restore() }
+function drawMochi(p){
+ const hh=p.hb/2, hw=hh*ASPECT; if(hh<.4) return;
+ // halo doré puis bleu
+ if(p.halo>0){ const c=[lerp(232,59,p.haloBlue),lerp(195,158,p.haloBlue),lerp(154,255,p.haloBlue)].map(v=>v|0); const R=hw*2.4; const hg=X.createRadialGradient(p.x,p.y,hh*.3,p.x,p.y,R); hg.addColorStop(0,`rgba(${c},${.36*p.halo})`); hg.addColorStop(1,`rgba(${c},0)`); X.fillStyle=hg; X.beginPath(); X.arc(p.x,p.y,R,0,Math.PI*2); X.fill() }
+ X.save(); X.translate(p.x,p.y); X.rotate(p.tilt); X.scale(p.sx,p.sy);
+ // mains DERRIÈRE le corps
+ drawHandL(p,hw,hh); drawHandR(p,hw,hh);
+ const path=mochiPath(hw,hh);
+ X.fillStyle=whiteFill(hw*.6,-hh,-hw*.6,hh); X.fill(path);
+ if(p.tint>0){ const tg=X.createLinearGradient(0,hh,0,-hh*.1); tg.addColorStop(0,`rgba(127,180,234,${p.tint})`); tg.addColorStop(1,'rgba(127,180,234,0)'); X.fillStyle=tg; X.fill(path) }
+ // yeux : deux points, écart 0,38 × hauteur, un peu sous le centre
+ X.save(); X.clip(path); X.fillStyle='#16171A'; X.strokeStyle='#16171A';
+ const er=p.hb*.06, sp=p.hb*.19, lx=p.lookX*hw*.42, ly=p.lookY*hh*.28+hh*.12+p.eyeRoll*hh*1.25;
+ for(const sd of[-1,1]){ X.save(); X.translate(sd*sp+lx,ly);
+ if(p.eye==='happy'||p.eye==='content'){ X.lineWidth=er*.95; X.lineCap='round'; X.beginPath(); if(p.eye==='happy') X.arc(0,er*.6,er*1.25,Math.PI*1.15,Math.PI*1.85); else X.arc(0,-er*.5,er*1.25,Math.PI*.15,Math.PI*.85); X.stroke() }
+ else { X.scale(1,Math.max(.12,p.open)); X.beginPath(); X.arc(0,0,er,0,Math.PI*2); X.fill() }
+ X.restore() }
+ X.restore();
+ // badge « travaille »
+ if(p.badge>.01){ X.save(); X.translate(-hw*.78,-hh*.72); X.scale(p.badge,p.badge); const br=hh*.3; X.fillStyle='#000'; X.beginPath(); X.arc(0,0,br+hh*.07,0,Math.PI*2); X.fill(); X.fillStyle='#3BA0F5'; X.beginPath(); X.arc(0,0,br,0,Math.PI*2); X.fill();
+ for(let i=0;i<3;i++){ X.fillStyle='#0B1B3A'; X.beginPath(); X.arc((i-1)*br*.5,0,br*.17,0,Math.PI*2); X.fill() } X.restore() }
+ X.restore() }
+function draw(t,tc){
+ const p=pose(t,tc);
+ X.setTransform(K,0,0,K,0,0); X.clearRect(0,0,W,H); X.fillStyle='#0B0D12'; X.fillRect(0,0,W,H);
+ const ix=CX-p.iw/2; X.fillStyle='#000'; X.beginPath(); X.moveTo(ix,0); X.lineTo(ix+p.iw,0); X.lineTo(ix+p.iw,p.ih-p.ir); X.quadraticCurveTo(ix+p.iw,p.ih,ix+p.iw-p.ir,p.ih); X.lineTo(ix+p.ir,p.ih); X.quadraticCurveTo(ix,p.ih,ix,p.ih-p.ir); X.closePath(); X.fill();
+ // notch physique (repère)
+ X.fillStyle='#050506'; rr(CX-NOTCH.w/2,-12,NOTCH.w,NOTCH.h+12,12); X.fill();
+ X.save(); X.beginPath(); X.rect(ix,0,p.iw,Math.max(p.ih,40)); X.clip();
+ if(p.card>0){ X.save(); X.globalAlpha=p.card; X.fillStyle='#141518'; rr(CARD.x,CARD.y,CARD.w,CARD.h,CARD.r); X.fill(); X.restore()
+ X.save(); rr(CARD.x,CARD.y,CARD.w,CARD.h,CARD.r); X.clip(); const fx=p.fx===undefined?1:p.fx;
+ for(const ring of RINGS){ const k=seg(t,ring.t0,ring.t0+1.35); if(k<=0||k>=1) continue; const rx=lerp(14,380,E.out(k)), ry=rx*.34, fade=(1-k)*(k<.08?k/.08:1)*fx*p.card;
+ for(const d of ring.dots){ const r=1+d.j; X.fillStyle=`rgba(255,255,255,${d.al*fade})`; X.fillRect(C0.x+Math.cos(d.a)*rx*r,C0.y+Math.sin(d.a)*ry*r,d.s,d.s) } }
+ for(const s of STREAKS){ const k=seg(t,s.t0,s.t0+.6); if(k<=0||k>=1) continue; const dist=s.sp*E.out(k)*.9+10;
+ X.strokeStyle=s.col; X.globalAlpha=(1-k)*fx; X.lineWidth=1.6; X.lineCap='round'; X.beginPath(); X.moveTo(C0.x+Math.cos(s.a)*(dist-s.len),C0.y+Math.sin(s.a)*(dist-s.len)*.42); X.lineTo(C0.x+Math.cos(s.a)*dist,C0.y+Math.sin(s.a)*dist*.42); X.stroke(); X.globalAlpha=1 }
+ X.restore() }
+ if(p.header>0){ X.save(); X.globalAlpha=p.header; X.fillStyle='#1D1F23'; rr(18,4,44,26,13); X.fill(); X.fillStyle='#F5F6F8'; X.beginPath(); X.moveTo(33,20); X.lineTo(40,13); X.lineTo(47,20); X.lineTo(47,25); X.lineTo(33,25); X.fill();
+ X.fillStyle='#8E939C'; X.beginPath(); X.arc(82,17,6.5,0,Math.PI*2); X.fill(); X.beginPath(); X.arc(578,17,6,0,Math.PI*2); X.fill(); X.fillStyle='#000'; X.beginPath(); X.arc(578,17,2.4,0,Math.PI*2); X.fill(); X.restore() }
+ // mini-Mochis de l'oreille droite
+ if(p.minis>.01){ const cx=CX+SMALL.w/2-27, cy=16, sp=6; [[-sp,-sp],[sp,-sp],[-sp,sp],[sp,sp]].forEach(([dx,dy],i)=>{ X.save(); X.translate(cx+dx,cy+dy); X.scale(p.minis,p.minis); X.fillStyle=MINI[i]; X.fill(mochiPath(5.3,4)); X.restore() }) }
+ drawMochi(p);
+ X.restore();
+ const ph=t>=tc?'Repli en petit (souris partie)':t<T.grow?'1 · Le notch s\u2019ouvre, le Mochi jaillit':t<T.dip0?'2 · Ondes, yeux plissés de joie, il te regarde':t<T.pop1?'3 · Plongeon en avant, les mains sortent de sous le corps':t<T.tuck0?'4 · COUCOU : main droite qui s\u2019agite, main gauche posée':t<T.tuck1?'5 · Les mains rentrent sous le corps':t<T.down1?'6 · Il se tasse, yeux contents, le badge apparaît':t<T.end?'7 · Clignement, teinte de l\u2019état':'8 · Fin du coucou : reste ouvert tant que la souris est là';
+ return ph;
+}
+
+/* ====================== LECTURE ====================== */
+const Snd={on:false,ctx:null,init(){ if(this.ctx)return; const C=window.AudioContext||window.webkitAudioContext; if(!C)return; this.ctx=new C(); this.g=this.ctx.createGain(); this.g.gain.value=.7; this.g.connect(this.ctx.destination) },
+ tone(f,to,d,g,delay=0){ const c=this.ctx,t=c.currentTime+delay,o=c.createOscillator(),n=c.createGain(); o.frequency.setValueAtTime(f,t); if(to)o.frequency.exponentialRampToValueAtTime(to,t+d*.9); n.gain.setValueAtTime(.0001,t); n.gain.exponentialRampToValueAtTime(g,t+.006); n.gain.exponentialRampToValueAtTime(.0001,t+d); o.connect(n); n.connect(this.g); o.start(t); o.stop(t+d+.05) },
+ cue(n){ if(!this.on)return; this.init(); if(!this.ctx)return; if(this.ctx.state==='suspended')this.ctx.resume();
+ if(n==='open'){ this.tone(300,560,.24,.06); [1568,1976,2349].forEach((f,i)=>this.tone(f,0,.5,.018,.06+i*.05)) }
+ if(n==='greet'){ [523.25,659.25,783.99].forEach((f,i)=>this.tone(f,0,.32,.06,i*.085)) }
+ if(n==='blip') this.tone(1480,0,.07,.035); if(n==='close'){ this.tone(520,300,.2,.05) } } };
+const CUES=[[0,'open'],[T.pop0,'greet'],[T.badge,'blip']];
+let t=0, playing=true, slow=1, hover=false, tc=T.autoLeave, last=performance.now();
+const $=id=>document.getElementById(id);
+function loop(now){ const dt=Math.min(.05,(now-last)/1000); last=now; const prev=t;
+ if(playing){ t+=dt/slow; if(t>Math.min(tc,T.end+1.2)+1.2&&(tc!==Infinity||t>T.end+1.5)){ if(tc!==Infinity){ t=0; tc=hover?Infinity:T.autoLeave } else t=T.end+1.5 }
+ for(const [ct,n] of CUES) if(prev<ct&&t>=ct&&t<tc) Snd.cue(n); if(prev<tc&&t>=tc) Snd.cue('close') }
+ const ph=draw(t,tc); $('t').textContent='t = '+t.toFixed(3)+' s'; $('phase').textContent=ph; $('scrub').value=t; requestAnimationFrame(loop) }
+$('play').onclick=()=>{ playing=!playing; $('play').textContent=playing?'Pause':'Lecture'; $('play').classList.toggle('on',playing) };
+$('restart').onclick=()=>{ t=0; tc=hover?Infinity:T.autoLeave; playing=true; $('play').textContent='Pause'; $('play').classList.add('on') };
+$('slow').onclick=()=>{ slow=slow===1?4:1; $('slow').classList.toggle('on',slow===4) };
+$('hover').onclick=()=>{ hover=!hover; $('hover').classList.toggle('on',hover); if(hover&&t<tc) tc=Infinity };
+$('leave').onclick=()=>{ hover=false; $('hover').classList.remove('on'); if(t<tc) tc=t };
+$('snd').onclick=()=>{ Snd.on=!Snd.on; if(Snd.on)Snd.init(); $('snd').classList.toggle('on',Snd.on) };
+$('scrub').oninput=e=>{ t=+e.target.value; playing=false; $('play').textContent='Lecture'; $('play').classList.remove('on') };
+window.__draw=(tt,tcc=T.autoLeave)=>{ t=tt; tc=tcc; playing=false; return draw(tt,tcc) };
+requestAnimationFrame(loop);
+})();
+</script>
+</body>
+</html>
diff --git a/design/animations/upload-sequence.html b/design/animations/upload-sequence.html
new file mode 100644
index 00000000..b95a3f08
--- /dev/null
+++ b/design/animations/upload-sequence.html
@@ -0,0 +1,303 @@
+<!doctype html>
+<html lang="fr">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+<title>Notch Buddy · séquence de dépôt (référence)</title>
+<style>
+:root{box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px);
+ --bg:#E2E4E8;--ink:#16171B;--muted:#5F646D;--panel:#fff;--line:#D1D4DA;--chip:#EDEFF2}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#131417;--ink:#ECEDEF;--muted:#9A9FA8;--panel:#1E2024;--line:#32353B;--chip:#2A2D32}}
+:root[data-theme="dark"]{--bg:#131417;--ink:#ECEDEF;--muted:#9A9FA8;--panel:#1E2024;--line:#32353B;--chip:#2A2D32}
+*,*::before,*::after{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--ink);font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter",system-ui,sans-serif}
+.wrap{max-width:1000px;margin:0 auto;padding:26px 20px 40px}
+h1{margin:0;font-size:24px;letter-spacing:-.02em}
+p{margin:6px 0 16px;color:var(--muted);font-size:14px;line-height:1.45;max-width:70ch}
+.stage{background:#07080A;border-radius:18px;overflow:hidden;box-shadow:0 20px 40px -24px rgba(0,0,0,.6)}
+canvas{display:block;width:100%;height:auto}
+.bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:14px}
+button{appearance:none;border:1px solid var(--line);background:var(--panel);color:var(--ink);border-radius:999px;padding:8px 14px;font:inherit;font-size:13.5px;cursor:pointer}
+button.on{background:var(--ink);color:var(--panel);border-color:var(--ink)}
+input[type=range]{flex:1;min-width:200px}
+.t{font-family:"SF Mono",ui-monospace,Menlo,monospace;font-size:13px;min-width:170px}
+.phase{font-size:14px;font-weight:600;min-width:260px}
+</style>
+</head>
+<body>
+<div class="wrap">
+ <h1>Séquence de dépôt, référence exacte</h1>
+ <p>Tout est une fonction du temps : le même instant donne toujours la même image. Coordonnées en points, dans le repère de l'island (640 de large, 176 de haut). À porter tel quel dans l'app.</p>
+ <div class="stage"><canvas id="c" width="1280" height="560"></canvas></div>
+ <div class="bar">
+ <button id="play" class="on">Pause</button>
+ <button id="restart">Recommencer</button>
+ <button id="slow">Ralenti ×4</button>
+ <button id="guides">Repères</button>
+ <button id="snd">Son</button>
+ <span class="t" id="t">t = 0.000 s</span>
+ </div>
+ <div class="bar"><input type="range" id="scrub" min="0" max="7.2" step="0.001" value="0"><span class="phase" id="phase"></span></div>
+</div>
+<script>
+(()=>{
+/* ====================== CONSTANTES (repère island, points) ====================== */
+const W=640, H=280; // scène : island 640x176 + 104 sous l'island pour l'approche du curseur
+const ISL_H=176; // hauteur de l'island pendant TOUTE la séquence (pas de saut de hauteur)
+const CARD={x:10,y:36,w:588,h:130,r:20}; // carte / zone de dépôt (laisse 42 à droite pour la colonne d'agents)
+const REST={x:140,y:101}; // position de repos de la boîte
+const D_BOX=62; // diamètre du corps en zone de dépôt
+const FOLLOW={min:CARD.x+50,max:CARD.x+CARD.w-50};
+const TEXT={x:196,y:94}; // « Dépose tes fichiers ici »
+const BAR={x0:46,x1:520,y:118}; // barre de progression
+const CHOOSE={x:60,y:101,d:52}; // place du Mochi dans la vue « choose »
+const LOCK_IN=60, LOCK_OUT=90; // verrouillage sous le fichier
+const MOUTH={ajar:.20,open:.42,max:.50}; // hauteurs de la bouche, en fraction de R
+const GREEN='#34D399', GREEN_D='#1FA87A', GREEN_L='#6EE7B7';
+const T={drop:1.95, suckStart:2.03, suckEnd:2.33, closeEnd:2.42, chew1:2.60, chew2:2.74, chewEnd:2.88,
+ shrinkEnd:3.23, barIn:3.00, progStart:3.25, progEnd:5.05, growStart:5.30, growEnd:5.75, end:7.2};
+/* trajet du curseur (le fichier est sous le curseur) */
+const PATH=[[0.00,600,262],[0.35,470,150],[0.80,330,70],[1.25,210,50],[1.65,140,36],[1.95,140,36]];
+
+/* ====================== OUTILS ====================== */
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)), lerp=(a,b,t)=>a+(b-a)*t;
+const E={out:t=>1-Math.pow(1-t,3),in:t=>t*t*t,inOut:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,
+ back:t=>{const c1=1.70158,c3=c1+1;return 1+c3*Math.pow(t-1,3)+c1*Math.pow(t-1,2)}};
+const seg=(t,a,b)=>clamp((t-a)/(b-a),0,1);
+function cursorAt(t){ for(let i=1;i<PATH.length;i++){ const [t0,x0,y0]=PATH[i-1],[t1,x1,y1]=PATH[i]; if(t<=t1){ const k=E.inOut(seg(t,t0,t1)); return {x:lerp(x0,x1,k),y:lerp(y0,y1,k)} } } const l=PATH[PATH.length-1]; return {x:l[1],y:l[2]} }
+function inZone(p){ return p.x>CARD.x-40&&p.x<CARD.x+CARD.w+40&&p.y<ISL_H+26 }
+// ressort critique-ish à pas fixe
+function spring(s,target,response,damping,dt){ const k=Math.pow(2*Math.PI/response,2), c=2*damping*Math.sqrt(k); const a=k*(target-s.v)-c*s.vel; s.vel+=a*dt; s.v+=s.vel*dt }
+// keyframes [[t, valeur], ...] avec easing sur chaque segment
+function kf(t,keys,ease=E.inOut){ if(t<=keys[0][0])return keys[0][1]; for(let i=1;i<keys.length;i++){ if(t<=keys[i][0]){ const k=seg(t,keys[i-1][0],keys[i][0]); return lerp(keys[i-1][1],keys[i][1],(keys[i][2]||ease)(k)) } } return keys[keys.length-1][1] }
+function progressCurve(u){ if(u<.4) return .6*E.out(u/.4); if(u<.85) return .6+.32*E.inOut((u-.4)/.45); return .92+.08*E.in((u-.85)/.15) }
+
+/* ====================== SIMULATION (pas fixe 1/240 s) ====================== */
+const DT=1/240;
+function newSim(){ return {t:0, bx:{v:REST.x,vel:0}, by:{v:REST.y,vel:0}, tilt:0, mouth:{v:0,vel:0}, locked:false, lockAt:-9, entered:-9, events:[], lastPct:0} }
+let S=newSim();
+function step(s){
+ const t=s.t, c=cursorAt(t), dragging=t<T.drop;
+ if(dragging&&s.entered<0&&inZone(c)){ s.entered=t; s.events.push('enter') }
+ // suivi horizontal + verrouillage
+ if(dragging&&s.entered>=0){
+ const dist=Math.hypot(c.x-s.bx.v,(c.y+14)-s.by.v);
+ const c2=cursorAt(Math.max(0,t-.05)), speed=Math.hypot(c.x-c2.x,c.y-c2.y)/.05;
+ if(!s.locked&&dist<LOCK_IN&&speed<180){ s.locked=true; s.lockAt=t; s.events.push('lock') }
+ if(s.locked&&dist>LOCK_OUT){ s.locked=false }
+ const tx=clamp(c.x,FOLLOW.min,FOLLOW.max), ty=REST.y;
+ if(s.locked){ spring(s.bx,tx,.18,.75,DT); spring(s.by,ty,.18,.75,DT) } else { spring(s.bx,tx,.35,.7,DT); spring(s.by,ty,.35,.7,DT) }
+ }
+ s.tilt=lerp(s.tilt, dragging?clamp(s.bx.vel*.0015,-.18,.18):0, 1-Math.pow(.0005,DT));
+ // bouche
+ let mt=0; if(s.entered>=0&&t<T.suckEnd) mt=s.locked||t>=T.drop?MOUTH.open:MOUTH.ajar;
+ if(t>=T.drop&&t<T.suckEnd) mt=MOUTH.max;
+ if(t>=T.suckEnd) mt=0;
+ if(t>=T.suckEnd) s.mouth.v=Math.max(0,lerp(MOUTH.max,0,E.in(seg(t,T.suckEnd,T.closeEnd)))); else spring(s.mouth,mt,.25,.6,DT);
+ if(s.mouth.v<0) s.mouth.v=0;
+ // sons (événements)
+ if(t>=T.suckEnd&&!s.gulp){ s.gulp=1; s.events.push('gulp') }
+ const pr=progressAt(t); const pc=Math.floor(pr*10); if(t>T.progStart&&pc>s.lastPct){ s.lastPct=pc; s.events.push('tick') }
+ if(t>=T.progEnd&&!s.ok){ s.ok=1; s.events.push('approve') }
+ s.t+=DT;
+}
+function simulateTo(t){ if(t<S.t-1e-9) S=newSim(); while(S.t<t) step(S) }
+function progressAt(t){ return t<T.progStart?0:progressCurve(seg(t,T.progStart,T.progEnd)) }
+
+/* ====================== ÉTAT DÉRIVÉ POUR UN INSTANT ====================== */
+function frame(t){
+ const s=S, c=cursorAt(t), f={t,cursor:c};
+ const entered=s.entered>=0?s.entered:1e9;
+ // morph 0 (rond) -> 1 (boîte) à l'entrée, retour 1 -> 0 pendant le rétrécissement
+ f.morph=t<T.chewEnd? E.back(seg(t,entered,entered+.38)) : 1-E.out(seg(t,T.chewEnd,T.shrinkEnd));
+ f.morph=clamp(f.morph,0,1.08);
+ // position / taille du Mochi
+ let x=s.bx.v, y=s.by.v, d=D_BOX;
+ if(t>=T.chewEnd&&t<T.progStart){ const k=E.inOut(seg(t,T.chewEnd,T.shrinkEnd)); x=lerp(s.bx.v,BAR.x0,k); y=lerp(s.by.v,BAR.y,k); d=lerp(D_BOX,14,k) }
+ if(t>=T.progStart){ const p=progressAt(t); x=lerp(BAR.x0,BAR.x1,p); y=BAR.y; d=14 }
+ if(t>=T.progEnd){ x=BAR.x1; y=BAR.y-8*Math.sin(Math.PI*seg(t,T.progEnd,T.progEnd+.2)) }
+ if(t>=T.growStart){ const k=E.back(seg(t,T.growStart,T.growEnd)); x=lerp(BAR.x1,CHOOSE.x,E.inOut(seg(t,T.growStart,T.growEnd))); y=lerp(BAR.y,CHOOSE.y,E.inOut(seg(t,T.growStart,T.growEnd))); d=lerp(14,CHOOSE.d,k) }
+ f.x=x; f.y=y; f.d=d;
+ // échelle (écrasements)
+ let sx=1, sy=1;
+ if(t>=T.drop&&t<T.suckStart){ const k=E.out(seg(t,T.drop,T.suckStart)); sy=lerp(1,.92,k); sx=lerp(1,1.06,k) }
+ if(t>=T.suckStart&&t<T.suckEnd){ const k=E.inOut(seg(t,T.suckStart,T.suckEnd)); sy=lerp(.92,1.06,k); sx=lerp(1.06,.97,k) }
+ if(t>=T.suckEnd&&t<T.chew1){ sy=kf(t,[[T.suckEnd,1.06],[T.suckEnd+.07,.82,E.out],[T.suckEnd+.2,1.1,E.out],[T.chew1,1]]); sx=kf(t,[[T.suckEnd,.97],[T.suckEnd+.07,1.14,E.out],[T.suckEnd+.2,.95,E.out],[T.chew1,1]]) }
+ if(t>=T.chew1&&t<T.chewEnd){ const k=((t-T.chew1)%.14)/.14; sy=1-.05*Math.sin(Math.PI*k); sx=1+.03*Math.sin(Math.PI*k) }
+ if(t>=T.chewEnd&&t<T.shrinkEnd){ const k=seg(t,T.chewEnd,T.shrinkEnd); sy=1+.12*Math.sin(Math.PI*k); sx=1-.06*Math.sin(Math.PI*k) }
+ if(t>=T.progStart&&t<T.progEnd){ const v=(progressAt(t+.01)-progressAt(t))/.01; const st=clamp(v*.18,0,1); sx=1+.25*st; sy=1-.15*st }
+ if(t>=T.growStart&&t<T.growEnd){ const k=seg(t,T.growStart,T.growEnd); sy=1+.06*Math.sin(Math.PI*k) }
+ f.sx=sx; f.sy=sy; f.tilt=s.tilt;
+ // saut au verrouillage
+ f.hop=s.lockAt>0&&t<T.drop?-5*Math.sin(Math.PI*seg(t,s.lockAt,s.lockAt+.15)):0;
+ f.mouth=s.mouth.v;
+ // yeux
+ f.eye='pill';
+ if(s.locked&&t<T.suckEnd) f.eye='cup';
+ if(t>=T.suckEnd&&t<T.chewEnd+.1) f.eye='content';
+ if(t>=T.progEnd&&t<T.growEnd+.3) f.eye='content';
+ const look=t<T.suckEnd?{x:c.x-x,y:(c.y+10)-y}:t<T.progStart?{x:0,y:0}:{x:40,y:0};
+ f.lookX=clamp(look.x/200,-1,1); f.lookY=clamp(look.y/150,-1,1);
+ // fichier
+ f.fileVisible=t<T.suckEnd; f.suck=seg(t,T.suckStart,T.suckEnd);
+ // contenu
+ f.zoneOver=s.entered>=0&&t<T.chewEnd&&inZone(c);
+ f.zoneAlpha=1-seg(t,T.chewEnd,T.chewEnd+.2);
+ const overlap=clamp(1-Math.abs((x+32)-(TEXT.x-8))/40,0,1)*(x+32>TEXT.x-8?1:0);
+ f.textAlpha=f.zoneAlpha*(x>TEXT.x-40&&t<T.drop?.25:1);
+ f.barReveal=E.out(seg(t,T.barIn,T.barIn+.25))*(1-seg(t,T.growStart,T.growStart+.2));
+ f.barAlpha=seg(t,T.barIn+.05,T.barIn+.25)*(1-seg(t,T.growStart,T.growStart+.2));
+ f.progress=progressAt(t);
+ f.flash=t>=T.progEnd?Math.sin(Math.PI*seg(t,T.progEnd,T.progEnd+.3)):0;
+ f.check=t>=T.progEnd?E.back(seg(t,T.progEnd,T.progEnd+.25)):0;
+ f.greenWash=Math.max(f.zoneOver?.35:0, t>=T.progEnd?.5*seg(t,T.progEnd,T.progEnd+.3)*(1-seg(t,T.growEnd,T.growEnd+.6)):0);
+ f.chooseAlpha=seg(t,T.growStart+.15,T.growEnd);
+ return f;
+}
+
+/* ====================== DESSIN ====================== */
+const cv=document.getElementById('c'), X=cv.getContext('2d'); const K=cv.width/W;
+let guides=false;
+function rr(x,a,b,w,h,r){r=Math.max(0,Math.min(r,w/2,h/2));x.beginPath();x.moveTo(a+r,b);x.arcTo(a+w,b,a+w,b+h,r);x.arcTo(a+w,b+h,a,b+h,r);x.arcTo(a,b+h,a,b,r);x.arcTo(a,b,a+w,b,r);x.closePath()}
+function bodyPath(m,R){ // superellipse : exposant 2.15 (rond Mochi v2) -> 5.5 (boîte)
+ const n=lerp(2.15,5.5,clamp(m,0,1)), rx=R*lerp(1.04,1.0,clamp(m,0,1)), ry=R*lerp(.97,.94,clamp(m,0,1)), p=new Path2D();
+ for(let i=0;i<=96;i++){ const a=i/96*Math.PI*2, ca=Math.cos(a), sa=Math.sin(a); const px=rx*Math.sign(ca)*Math.pow(Math.abs(ca),2/n), py=ry*Math.sign(sa)*Math.pow(Math.abs(sa),2/n); i?p.lineTo(px,py):p.moveTo(px,py) }
+ p.closePath(); return {p,rx,ry};
+}
+function drawEye(shape,w,h){
+ switch(shape){
+ case 'cup': { const hh=h*.55; X.beginPath(); X.moveTo(-w/2,-hh/2); X.lineTo(w/2,-hh/2); X.lineTo(w/2,hh/2-w/2); X.arc(0,hh/2-w/2,w/2,0,Math.PI); X.closePath(); X.fill(); break }
+ case 'content': X.lineWidth=w*.5; X.lineCap='round'; X.beginPath(); X.arc(0,-h*.12,w*.85,Math.PI*.15,Math.PI*.85); X.stroke(); break;
+ default: rr(X,-w/2,-h/2,w,h,w/2); X.fill();
+ }
+}
+function drawMochi(f){
+ const R=f.d/2/1.04, m=f.morph;
+ X.save(); X.translate(f.x,f.y+f.hop); X.rotate(f.tilt); X.scale(f.sx,f.sy);
+ const {p,rx,ry}=bodyPath(m,R);
+ // corps mat : dégradé clair haut-droite -> gris bas-gauche
+ const g=X.createLinearGradient(rx*.7,-ry*.9,-rx*.8,ry*.9); g.addColorStop(0,'#EDEDEF'); g.addColorStop(1,'#C4C5CA'); X.fillStyle=g; X.fill(p);
+ const sh=X.createRadialGradient(rx*.2,-ry*.25,R*.2,0,0,R*1.3); sh.addColorStop(0,'rgba(0,0,0,0)'); sh.addColorStop(.62,'rgba(0,0,0,0)'); sh.addColorStop(1,'rgba(0,0,0,.12)'); X.fillStyle=sh; X.fill(p);
+ // liseré clair du rebord haut (boîte)
+ if(m>.3){ X.save(); X.clip(p); X.strokeStyle=`rgba(255,255,255,${.6*clamp((m-.3)/.7,0,1)})`; X.lineWidth=1.2; X.beginPath(); X.moveTo(-rx*.72,-ry+.9); X.lineTo(rx*.72,-ry+.9); X.stroke(); X.restore() }
+ // bouche : trou en pilule À L'INTÉRIEUR, rebord tout autour, ancré en haut
+ const mh=f.mouth*R*clamp(m,0,1);
+ if(mh>.3){ const mw=2*rx-2*.12*R, mx=-mw/2, my=-ry+.10*R;
+ X.save(); X.clip(p);
+ const ig=X.createLinearGradient(0,my,0,my+mh); ig.addColorStop(0,'#030304'); ig.addColorStop(1,'#101114'); X.fillStyle=ig; rr(X,mx,my,mw,mh,mh/2); X.fill();
+ X.strokeStyle='rgba(255,255,255,.55)'; X.lineWidth=1; X.beginPath(); X.moveTo(mx+mh/2,my+mh+.5); X.lineTo(mx+mw-mh/2,my+mh+.5); X.stroke();
+ if(guides){ X.strokeStyle='#F0F'; X.lineWidth=.5; rr(X,mx,my,mw,mh,mh/2); X.stroke() }
+ X.restore(); f._mouth={x:f.x+mx*f.sx,w:mw*f.sx,y:f.y+f.hop+my*f.sy,h:mh*f.sy} } else f._mouth={x:f.x-rx*.8,w:rx*1.6,y:f.y-ry+.1*R,h:0};
+ // yeux : pilules, rond -> boîte ils descendent et rétrécissent, regard borné dans la boîte
+ X.save(); X.clip(p); X.fillStyle='#0E0F12'; X.strokeStyle='#0E0F12';
+ const mm=clamp(m,0,1), ew=R*.25, eh=R*lerp(.62,.46,mm), ey=R*lerp(.02,.30,mm), sp=R*.30;
+ const lx=f.lookX*R*lerp(.34,.26,mm), ly=f.lookY*R*lerp(.16,.07,mm);
+ for(const sd of[-1,1]){ X.save(); X.translate(sd*sp+lx,ey+ly); drawEye(f.eye,ew,eh); X.restore() }
+ X.restore();
+ if(guides){ X.strokeStyle='#0FF'; X.lineWidth=.5; X.stroke(p) }
+ X.restore();
+}
+function drawFile(f){
+ const c=f.cursor;
+ if(f.suck<=0){ X.save(); X.globalAlpha=.92; drawDoc(c.x,c.y+14,1,1,1); X.restore(); return }
+ // aspiration : entonnoir (bord bas qui se resserre), descend dans la bouche, masqué sous le haut de la bouche
+ const p=E.in(f.suck), m=f._mouth, W0=34, H0=42;
+ const topY=lerp(c.y+14-H0/2, m.y-2, E.inOut(f.suck));
+ const hs=lerp(1.08,.55,E.inOut(f.suck)), Hh=H0*hs, sc=lerp(1,.55,p);
+ X.save(); X.beginPath(); X.rect(0,0,W,m.y+m.h*.5); X.clip();
+ const q=E.out(f.suck); const N=28; for(let i=0;i<N;i++){ const v0=i/N, v1=(i+1)/N; const wsc=lerp(1,lerp(.92,.22*m.w/W0,Math.pow(v0,1.2)),q)*sc;
+ const cx=lerp(c.x,m.x+m.w/2,E.out(f.suck)), yy=topY+v0*Hh, hh=Hh/N+.6; const wob=Math.sin(f.suck*Math.PI*2)*.1*(1-p);
+ X.save(); X.translate(cx,yy); X.rotate(wob); X.beginPath(); X.rect(-W0*wsc/2,0,W0*wsc,hh); X.clip(); X.translate(-cx,-yy);
+ drawDoc(cx,topY+Hh/2,wsc,hs,1,topY,Hh); X.restore() }
+ X.restore();
+ // particules vertes aspirées
+ for(let i=0;i<4;i++){ const a=i/4*Math.PI*2+.6, r0=24; const k=clamp((f.suck-i*.08)/.7,0,1); if(k<=0||k>=1)continue;
+ const sx0=c.x+Math.cos(a)*r0, sy0=c.y+14+Math.sin(a)*r0, ex=m.x+m.w/2, ey=m.y+m.h*.3; const kk=Math.pow(k,.7);
+ X.fillStyle=`rgba(52,211,153,${1-k})`; X.beginPath(); X.arc(lerp(sx0,ex,kk),lerp(sy0,ey,kk)-Math.sin(Math.PI*k)*6,2.2*(1-k*.5),0,Math.PI*2); X.fill() }
+}
+function drawDoc(cx,cy,wsc,hsc,alpha,top,hh){ // icône de document générique (la vraie app utilise l'icône du fichier)
+ const w=34*wsc, h=42*hsc, x=cx-w/2, y=(top!==undefined?top:cy-h/2); const fold=8*Math.min(wsc,hsc);
+ X.save(); X.globalAlpha*=alpha; X.shadowColor='rgba(0,0,0,.45)'; X.shadowBlur=8; X.shadowOffsetY=3;
+ X.fillStyle='#F4F4F6'; X.beginPath(); X.moveTo(x+2,y); X.lineTo(x+w-fold,y); X.lineTo(x+w,y+fold); X.lineTo(x+w,y+h-2); X.quadraticCurveTo(x+w,y+h,x+w-2,y+h); X.lineTo(x+2,y+h); X.quadraticCurveTo(x,y+h,x,y+h-2); X.lineTo(x,y+2); X.quadraticCurveTo(x,y,x+2,y); X.fill();
+ X.shadowColor='transparent'; X.fillStyle='#D5D6DB'; X.beginPath(); X.moveTo(x+w-fold,y); X.lineTo(x+w-fold,y+fold); X.lineTo(x+w,y+fold); X.fill();
+ X.fillStyle='#3B82F6'; rr(X,x+w*.18,y+h*.58,w*.64,h*.16,2); X.fill(); X.restore();
+}
+function drawCursor(c,down){ X.save(); X.translate(c.x,c.y); if(down) X.scale(.88,.88); X.fillStyle='#fff'; X.strokeStyle='#000'; X.lineWidth=1.1; X.lineJoin='round';
+ X.beginPath(); X.moveTo(0,0); X.lineTo(0,16); X.lineTo(4,12.4); X.lineTo(7,19); X.lineTo(9.6,17.8); X.lineTo(6.7,11.4); X.lineTo(11.6,11.4); X.closePath(); X.fill(); X.stroke(); X.restore() }
+function text(s,x,y,size,weight,color,align='left'){ X.font=`${weight} ${size}px -apple-system,BlinkMacSystemFont,"SF Pro Text",system-ui,sans-serif`; X.fillStyle=color; X.textAlign=align; X.textBaseline='middle'; X.fillText(s,x,y) }
+function chip(s,x,y){ X.font='500 11px -apple-system,system-ui,sans-serif'; const w=X.measureText(s).width+16; X.fillStyle='rgba(255,255,255,.07)'; rr(X,x,y-9,w,18,9); X.fill(); text(s,x+8,y,11,500,'#B9BDC4'); return w+6 }
+function draw(t){
+ simulateTo(t); const f=frame(t);
+ X.setTransform(K,0,0,K,0,0); X.clearRect(0,0,W,H);
+ // fond écran + island
+ X.fillStyle='#0B0D12'; X.fillRect(0,0,W,H);
+ X.fillStyle='#000'; rr(X,-30,-30,W+60,ISL_H+30,30); X.fill();
+ // en-tête (simplifié)
+ X.fillStyle='#1D1F23'; rr(X,108,4,44,26,13); X.fill();
+ X.fillStyle='#8E939C'; X.beginPath(); X.moveTo(24,20); X.lineTo(31,13); X.lineTo(38,20); X.lineTo(38,25); X.lineTo(24,25); X.fill();
+ X.beginPath(); X.arc(72,18,7,0,Math.PI*2); X.fill();
+ X.strokeStyle='#F5F6F8'; X.lineWidth=1.8; X.lineCap='round'; X.beginPath(); X.moveTo(130,12); X.lineTo(130,22); X.moveTo(125,17); X.lineTo(135,17); X.stroke();
+ X.fillStyle='#8E939C'; X.beginPath(); X.arc(578,17,6,0,Math.PI*2); X.fill(); X.fillStyle='#000'; X.beginPath(); X.arc(578,17,2.5,0,Math.PI*2); X.fill();
+ // colonne d'agents
+ ['#FF5A4E','#2EC4A0','#F29B38'].forEach((c,i)=>{ X.fillStyle=c; X.beginPath(); X.arc(W-10-21,36+14+i*24,8,0,Math.PI*2); X.fill() });
+ // carte
+ X.save(); rr(X,CARD.x,CARD.y,CARD.w,CARD.h,CARD.r); X.clip();
+ X.fillStyle='#121316'; X.fillRect(CARD.x,CARD.y,CARD.w,CARD.h);
+ if(f.greenWash>0){ const gw=X.createRadialGradient(CARD.x+CARD.w/2,CARD.y+CARD.h*1.3,10,CARD.x+CARD.w/2,CARD.y+CARD.h*1.3,CARD.w*.6); gw.addColorStop(0,`rgba(52,211,153,${f.greenWash})`); gw.addColorStop(1,'rgba(52,211,153,0)'); X.fillStyle=gw; X.fillRect(CARD.x,CARD.y,CARD.w,CARD.h) }
+ X.restore();
+ // bordure pointillée fine
+ if(f.zoneAlpha>0){ X.save(); X.globalAlpha=f.zoneAlpha; X.setLineDash([6,5]); X.lineWidth=1.5; X.strokeStyle=f.zoneOver?'rgba(52,211,153,.55)':'rgba(255,255,255,.14)'; rr(X,CARD.x+.75,CARD.y+.75,CARD.w-1.5,CARD.h-1.5,CARD.r); X.stroke(); X.restore()
+ X.save(); X.globalAlpha=f.textAlpha; text('Dépose tes fichiers ici',TEXT.x,TEXT.y-4,13,500,'#D5D7DB'); let cx=TEXT.x; for(const s of['PDF','Images','Code','Docs']) cx+=chip(s,cx,TEXT.y+18); X.restore() }
+ // barre de progression
+ if(f.barAlpha>0||f.barReveal>0){ X.save(); X.globalAlpha=Math.max(f.barAlpha,.001);
+ text('Envoi de capture.png',BAR.x0,BAR.y-30,12.5,500,'#A9ADB5');
+ if(f.check>0){ X.save(); X.translate(BAR.x1-8,BAR.y-30); X.scale(f.check,f.check); X.fillStyle=GREEN; X.beginPath(); X.arc(0,0,8,0,Math.PI*2); X.fill(); X.strokeStyle='#07130E'; X.lineWidth=2; X.lineCap='round'; X.lineJoin='round'; X.beginPath(); X.moveTo(-3.6,.2); X.lineTo(-1,2.8); X.lineTo(3.8,-2.6); X.stroke(); X.restore() }
+ else { X.font='500 12.5px ui-monospace,"SF Mono",Menlo,monospace'; text(Math.round(f.progress*100)+' %',BAR.x1,BAR.y-30,12.5,500,'#A9ADB5','right') }
+ const L=(BAR.x1-BAR.x0)*f.barReveal; X.fillStyle='rgba(255,255,255,.08)'; rr(X,BAR.x0,BAR.y-3,L,6,3); X.fill();
+ const fx=lerp(BAR.x0,BAR.x1,f.progress); if(fx>BAR.x0+1){ const g=X.createLinearGradient(BAR.x0,0,fx,0); g.addColorStop(0,GREEN_D); g.addColorStop(1,f.flash>0?`rgb(${lerp(52,110,f.flash)|0},${lerp(211,231,f.flash)|0},${lerp(153,183,f.flash)|0})`:GREEN); X.fillStyle=g; rr(X,BAR.x0,BAR.y-3,fx-BAR.x0,6,3); X.fill() }
+ // traînée derrière le point
+ if(t>T.progStart&&t<T.progEnd){ const v=(progressAt(t+.01)-progressAt(t))/.01; const tl=clamp(8+v*40,8,34); const tg=X.createLinearGradient(fx-tl,0,fx,0); tg.addColorStop(0,'rgba(52,211,153,0)'); tg.addColorStop(1,'rgba(110,231,183,.6)'); X.save(); X.filter='blur(3px)'; X.fillStyle=tg; rr(X,fx-tl,BAR.y-4,tl,8,4); X.fill(); X.restore() }
+ X.restore() }
+ // vue « choose »
+ if(f.chooseAlpha>0){ X.save(); X.globalAlpha=f.chooseAlpha; X.translate(0,(1-f.chooseAlpha)*4);
+ text('capture.png est prêt.',100,80,14,600,'#F5F6F8'); text('Tu veux en faire quoi ?',100,100,12.5,400,'#9398A1');
+ X.fillStyle='#F5F6F8'; rr(X,100,113,176,26,13); X.fill(); text('Poser une question dessus',188,126,12.5,500,'#0B0C0E','center');
+ X.fillStyle='rgba(255,255,255,.09)'; rr(X,284,113,128,26,13); X.fill(); text('Envoyer par mail',348,126,12.5,500,'#F1F2F4','center'); X.restore() }
+ // Mochi puis fichier par-dessus (le fichier est masqué sous le haut de la bouche)
+ drawMochi(f);
+ if(f.fileVisible) drawFile(f);
+ drawCursor(f.cursor,t>=T.drop&&t<T.drop+.12);
+ if(guides){ X.strokeStyle='#FF0'; X.lineWidth=.5; X.setLineDash([3,3]); X.beginPath(); X.moveTo(FOLLOW.min,36); X.lineTo(FOLLOW.min,166); X.moveTo(FOLLOW.max,36); X.lineTo(FOLLOW.max,166); X.stroke(); X.setLineDash([]); X.beginPath(); X.arc(f.x,f.y,LOCK_IN,0,Math.PI*2); X.stroke() }
+ // étiquette de phase
+ const ph=t<(S.entered>=0?S.entered:9)?'0 · Le fichier approche':t<T.drop?(S.locked?'2 · Verrouillé : bouche grande ouverte':'1 · La boîte suit le fichier'):t<T.suckStart?'3 · Anticipation':t<T.suckEnd?'4 · Aspiration en entonnoir':t<T.chewEnd?'5 · Gloups + mâchage':t<T.progStart?'6 · Redevient une boule, rétrécit en point':t<T.progEnd?'7 · Progression (fausse)':t<T.growStart?'8 · Succès vert':'9 · Regrandit, vue « choose »';
+ return ph;
+}
+
+/* ====================== LECTURE ====================== */
+const Snd={on:false,ctx:null,
+ init(){ if(this.ctx)return; const C=window.AudioContext||window.webkitAudioContext; if(!C)return; this.ctx=new C(); this.g=this.ctx.createGain(); this.g.gain.value=.7; this.g.connect(this.ctx.destination) },
+ tone(f,to,d,g,delay=0,type='sine'){ const c=this.ctx,t=c.currentTime+delay,o=c.createOscillator(),n=c.createGain(); o.type=type; o.frequency.setValueAtTime(f,t); if(to)o.frequency.exponentialRampToValueAtTime(to,t+d*.9); n.gain.setValueAtTime(.0001,t); n.gain.exponentialRampToValueAtTime(g,t+.006); n.gain.exponentialRampToValueAtTime(.0001,t+d); o.connect(n); n.connect(this.g); o.start(t); o.stop(t+d+.05) },
+ play(e){ if(!this.on)return; this.init(); if(!this.ctx)return; if(this.ctx.state==='suspended')this.ctx.resume();
+ if(e==='enter')this.tone(2100,0,.05,.014); if(e==='lock')this.tone(480,1150,.11,.05);
+ if(e==='gulp'){this.tone(340,120,.16,.11);this.tone(210,80,.22,.09,.1)} if(e==='tick')this.tone(2400,0,.03,.012);
+ if(e==='approve'){this.tone(660,0,.18,.05);this.tone(990,0,.3,.05,.08)} }
+};
+let t=0, playing=true, slow=1, last=performance.now();
+const $=id=>document.getElementById(id);
+function loop(now){ const dt=Math.min(.05,(now-last)/1000); last=now;
+ if(playing){ t+=dt/slow; if(t>T.end){ t=0 } }
+ const evBefore=S.events.length; const ph=draw(t); for(const e of S.events.slice(evBefore)) if(playing) Snd.play(e); if(S.events.length>200) S.events.length=0;
+ $('t').textContent='t = '+t.toFixed(3)+' s'; $('phase').textContent=ph; $('scrub').value=t;
+ requestAnimationFrame(loop) }
+$('play').onclick=()=>{ playing=!playing; $('play').textContent=playing?'Pause':'Lecture'; $('play').classList.toggle('on',playing) };
+$('restart').onclick=()=>{ t=0; S=newSim(); playing=true; $('play').textContent='Pause'; $('play').classList.add('on') };
+$('slow').onclick=()=>{ slow=slow===1?4:1; $('slow').classList.toggle('on',slow===4) };
+$('guides').onclick=()=>{ guides=!guides; $('guides').classList.toggle('on',guides) };
+$('snd').onclick=()=>{ Snd.on=!Snd.on; if(Snd.on)Snd.init(); $('snd').classList.toggle('on',Snd.on) };
+$('scrub').oninput=e=>{ t=+e.target.value; playing=false; $('play').textContent='Lecture'; $('play').classList.remove('on') };
+window.__draw=(tt)=>{ t=tt; playing=false; return draw(tt) };
+requestAnimationFrame(loop);
+})();
+</script>
+</body>
+</html>
diff --git a/design/captures/01_peek.png b/design/captures/01_peek.png
new file mode 100644
index 00000000..0a5918f9
Binary files /dev/null and b/design/captures/01_peek.png differ
diff --git a/design/captures/02_compact.png b/design/captures/02_compact.png
new file mode 100644
index 00000000..6d7127b3
Binary files /dev/null and b/design/captures/02_compact.png differ
diff --git a/design/captures/03_overview.png b/design/captures/03_overview.png
new file mode 100644
index 00000000..54315be8
Binary files /dev/null and b/design/captures/03_overview.png differ
diff --git a/design/captures/04_approval.png b/design/captures/04_approval.png
new file mode 100644
index 00000000..a04376df
Binary files /dev/null and b/design/captures/04_approval.png differ
diff --git a/design/captures/05_question.png b/design/captures/05_question.png
new file mode 100644
index 00000000..9b01b9d7
Binary files /dev/null and b/design/captures/05_question.png differ
diff --git a/design/captures/06_error.png b/design/captures/06_error.png
new file mode 100644
index 00000000..250eb32f
Binary files /dev/null and b/design/captures/06_error.png differ
diff --git a/design/captures/07_finished.png b/design/captures/07_finished.png
new file mode 100644
index 00000000..1de72923
Binary files /dev/null and b/design/captures/07_finished.png differ
diff --git a/design/captures/08_confused.png b/design/captures/08_confused.png
new file mode 100644
index 00000000..d5137203
Binary files /dev/null and b/design/captures/08_confused.png differ
diff --git a/design/captures/09_upload_drag_over.png b/design/captures/09_upload_drag_over.png
new file mode 100644
index 00000000..b73f1b0f
Binary files /dev/null and b/design/captures/09_upload_drag_over.png differ
diff --git a/design/captures/10_uploading.png b/design/captures/10_uploading.png
new file mode 100644
index 00000000..31f6d238
Binary files /dev/null and b/design/captures/10_uploading.png differ
diff --git a/design/captures/11_choose.png b/design/captures/11_choose.png
new file mode 100644
index 00000000..5785f945
Binary files /dev/null and b/design/captures/11_choose.png differ
diff --git a/design/captures/12_mail.png b/design/captures/12_mail.png
new file mode 100644
index 00000000..316419a0
Binary files /dev/null and b/design/captures/12_mail.png differ
diff --git a/design/captures/13_prompt_window_attached.png b/design/captures/13_prompt_window_attached.png
new file mode 100644
index 00000000..86a31b7c
Binary files /dev/null and b/design/captures/13_prompt_window_attached.png differ
diff --git a/design/captures/14_searching.png b/design/captures/14_searching.png
new file mode 100644
index 00000000..3a99eba3
Binary files /dev/null and b/design/captures/14_searching.png differ
diff --git a/design/captures/15_result.png b/design/captures/15_result.png
new file mode 100644
index 00000000..0bd50a8c
Binary files /dev/null and b/design/captures/15_result.png differ
diff --git a/design/captures/16_empty.png b/design/captures/16_empty.png
new file mode 100644
index 00000000..9a72c904
Binary files /dev/null and b/design/captures/16_empty.png differ
diff --git a/design/captures/char_emote_love.png b/design/captures/char_emote_love.png
new file mode 100644
index 00000000..3559a973
Binary files /dev/null and b/design/captures/char_emote_love.png differ
diff --git a/design/captures/char_emote_proud.png b/design/captures/char_emote_proud.png
new file mode 100644
index 00000000..0a3ba1f4
Binary files /dev/null and b/design/captures/char_emote_proud.png differ
diff --git a/design/captures/char_emote_surprised.png b/design/captures/char_emote_surprised.png
new file mode 100644
index 00000000..4589ad4e
Binary files /dev/null and b/design/captures/char_emote_surprised.png differ
diff --git a/design/captures/char_emote_wink.png b/design/captures/char_emote_wink.png
new file mode 100644
index 00000000..13a99df3
Binary files /dev/null and b/design/captures/char_emote_wink.png differ
diff --git a/design/captures/char_emote_yawn.png b/design/captures/char_emote_yawn.png
new file mode 100644
index 00000000..7fe10ca5
Binary files /dev/null and b/design/captures/char_emote_yawn.png differ
diff --git a/design/captures/char_state_approval.png b/design/captures/char_state_approval.png
new file mode 100644
index 00000000..fe9ed446
Binary files /dev/null and b/design/captures/char_state_approval.png differ
diff --git a/design/captures/char_state_dizzy.png b/design/captures/char_state_dizzy.png
new file mode 100644
index 00000000..9b643a0a
Binary files /dev/null and b/design/captures/char_state_dizzy.png differ
diff --git a/design/captures/char_state_error.png b/design/captures/char_state_error.png
new file mode 100644
index 00000000..a08b718b
Binary files /dev/null and b/design/captures/char_state_error.png differ
diff --git a/design/captures/char_state_finished.png b/design/captures/char_state_finished.png
new file mode 100644
index 00000000..178d4052
Binary files /dev/null and b/design/captures/char_state_finished.png differ
diff --git a/design/captures/char_state_idle.png b/design/captures/char_state_idle.png
new file mode 100644
index 00000000..d22c46d8
Binary files /dev/null and b/design/captures/char_state_idle.png differ
diff --git a/design/captures/char_state_question.png b/design/captures/char_state_question.png
new file mode 100644
index 00000000..8d0de8dc
Binary files /dev/null and b/design/captures/char_state_question.png differ
diff --git a/design/captures/char_state_ratelimit.png b/design/captures/char_state_ratelimit.png
new file mode 100644
index 00000000..ff227752
Binary files /dev/null and b/design/captures/char_state_ratelimit.png differ
diff --git a/design/captures/char_state_searching.png b/design/captures/char_state_searching.png
new file mode 100644
index 00000000..47a8cc1e
Binary files /dev/null and b/design/captures/char_state_searching.png differ
diff --git a/design/captures/char_state_sleeping.png b/design/captures/char_state_sleeping.png
new file mode 100644
index 00000000..1ac7d439
Binary files /dev/null and b/design/captures/char_state_sleeping.png differ
diff --git a/design/captures/char_state_thinking.png b/design/captures/char_state_thinking.png
new file mode 100644
index 00000000..679c9fe6
Binary files /dev/null and b/design/captures/char_state_thinking.png differ
diff --git a/design/captures/char_state_working.png b/design/captures/char_state_working.png
new file mode 100644
index 00000000..5133dd75
Binary files /dev/null and b/design/captures/char_state_working.png differ
diff --git a/design/prototype/notch-buddy.html b/design/prototype/notch-buddy.html
new file mode 100644
index 00000000..68d134ed
--- /dev/null
+++ b/design/prototype/notch-buddy.html
@@ -0,0 +1,969 @@
+<!doctype html>
+<html lang="fr">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+<title>Notch Buddy · prototype visuel</title>
+<style>
+:root{
+ box-sizing:border-box;
+ padding-top:env(safe-area-inset-top,0px);
+ padding-bottom:env(safe-area-inset-bottom,0px);
+ --desk:#E2E4E8; --ink:#16171B; --muted:#5F646D; --panel:#FFFFFF; --line:#D1D4DA; --chip:#EDEFF2; --focus:#2F6BFF;
+ --spr:cubic-bezier(.32,1.22,.42,1);
+ --font:-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",system-ui,sans-serif;
+}
+@media (prefers-color-scheme: dark){
+ :root:not([data-theme="light"]){--desk:#131417; --ink:#ECEDEF; --muted:#9A9FA8; --panel:#1E2024; --line:#32353B; --chip:#2A2D32;}
+}
+:root[data-theme="dark"]{--desk:#131417; --ink:#ECEDEF; --muted:#9A9FA8; --panel:#1E2024; --line:#32353B; --chip:#2A2D32;}
+*,*::before,*::after{box-sizing:border-box}
+html{scroll-padding-top:env(safe-area-inset-top,0px)}
+body{margin:0;background:var(--desk);color:var(--ink);font-family:var(--font);-webkit-font-smoothing:antialiased}
+button{font:inherit;color:inherit}
+button:focus-visible,input:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
+
+.top{max-width:1180px;margin:0 auto;padding:28px 24px 14px;display:flex;align-items:flex-end;gap:20px;flex-wrap:wrap}
+.top h1{font-size:30px;line-height:1.05;margin:0;font-weight:700;letter-spacing:-.02em}
+.top p{margin:6px 0 0;color:var(--muted);font-size:15px;max-width:62ch}
+.top .grow{flex:1;min-width:260px}
+.demo-btn{appearance:none;border:0;background:var(--ink);color:var(--desk);padding:12px 20px;border-radius:999px;font-weight:600;font-size:15px;cursor:pointer;display:flex;gap:10px;align-items:center}
+.demo-btn[disabled]{opacity:.55;cursor:default}
+.demo-btn svg{width:14px;height:14px}
+
+.stage-wrap{max-width:1180px;margin:0 auto;padding:0 24px;position:relative}
+.stage-outer{position:relative;width:100%}
+.stage{position:absolute;left:0;top:0;width:1120px;height:700px;transform-origin:0 0}
+.mac{position:absolute;inset:0;background:#050506;border-radius:28px;padding:12px;box-shadow:0 30px 60px -30px rgba(0,0,0,.45),0 0 0 1px rgba(0,0,0,.4)}
+.screen{position:relative;width:100%;height:100%;border-radius:14px;overflow:hidden;background:
+ radial-gradient(1200px 520px at 18% 118%, #22324F 0%, transparent 60%),
+ radial-gradient(900px 500px at 92% -10%, #33224A 0%, transparent 55%),
+ linear-gradient(180deg,#0E1116,#0B0D12);
+ cursor:default;touch-action:none;user-select:none;-webkit-user-select:none}
+.screen .curve{position:absolute;right:-240px;top:40px;width:760px;height:520px;border-radius:50%;
+ background:radial-gradient(closest-side,rgba(255,255,255,.07),rgba(255,255,255,0) 70%);filter:blur(2px)}
+.screen .curve2{position:absolute;left:-200px;top:210px;width:900px;height:900px;border-radius:50%;border:1px solid rgba(255,255,255,.06)}
+.menubar{position:absolute;left:0;right:0;top:0;height:32px;display:flex;align-items:center;justify-content:space-between;padding:0 16px;
+ font-size:13px;color:rgba(255,255,255,.9);background:rgba(18,18,22,.35);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px)}
+.menubar .l,.menubar .r{display:flex;gap:18px;align-items:center}
+.menubar b{font-weight:700}
+.menubar svg{width:15px;height:15px;fill:rgba(255,255,255,.9)}
+.notch{position:absolute;left:50%;top:0;width:184px;height:32px;transform:translateX(-50%);background:#000;border-radius:0 0 12px 12px;z-index:5}
+.notch::after{content:"";position:absolute;left:50%;top:11px;width:8px;height:8px;border-radius:50%;background:#101216;transform:translateX(-50%);box-shadow:inset 0 0 0 1.5px #16191f}
+
+/* windows */
+.win{position:absolute;border-radius:12px;overflow:hidden;box-shadow:0 24px 50px -18px rgba(0,0,0,.7),0 0 0 .5px rgba(255,255,255,.12)}
+.win .tb{height:38px;display:flex;align-items:center;gap:8px;padding:0 14px}
+.tl{width:12px;height:12px;border-radius:50%;display:inline-block}
+.tl.r{background:#FF5F57}.tl.y{background:#FEBC2E}.tl.g{background:#28C840}
+.safari{background:#FFFFFF;color:#1d1d1f}
+.safari .tb{background:#F2F2F4;border-bottom:1px solid #E2E2E6}
+.safari .url{margin:0 auto;background:#E4E4E8;border-radius:8px;padding:5px 60px;font-size:12px;color:#4a4a52}
+.safari .page{padding:16px 20px}
+.safari .brand{font-weight:800;font-size:20px;letter-spacing:-.03em;color:#E0523A}
+.safari .search{margin:10px 0 14px;border:1px solid #E1E1E6;border-radius:999px;padding:9px 16px;font-size:12.5px;color:#45454d;box-shadow:0 4px 14px -8px rgba(0,0,0,.25)}
+.safari .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
+.lst .ph{height:84px;border-radius:10px;margin-bottom:6px}
+.lst b{display:block;font-size:12.5px}
+.lst span{font-size:11.5px;color:#6b6b73}
+.safari.target{box-shadow:0 24px 50px -18px rgba(0,0,0,.7),0 0 0 2px rgba(255,255,255,.55)}
+.attach{position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity .6s ease}
+.safari.attached .attach{opacity:1}
+@property --ang{syntax:"<angle>";inherits:false;initial-value:0deg}
+.attach .ring{position:absolute;inset:0;border-radius:12px;padding:3px;
+ background:conic-gradient(from var(--ang),#FF6B5B,#F7B32B,#2DD4A7,#38BDF8,#A78BFA,#F472B6,#FF6B5B);
+ -webkit-mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);-webkit-mask-composite:xor;mask-composite:exclude;
+ animation:spin 3s linear infinite;filter:saturate(1.2)}
+.attach .wash{position:absolute;inset:0;background:
+ radial-gradient(60% 70% at 0% 0%,rgba(255,107,91,.28),transparent 70%),
+ radial-gradient(60% 70% at 100% 0%,rgba(45,212,167,.26),transparent 70%),
+ radial-gradient(70% 70% at 100% 100%,rgba(167,139,250,.28),transparent 70%),
+ radial-gradient(70% 70% at 0% 100%,rgba(244,114,182,.26),transparent 70%);mix-blend-mode:multiply;animation:breathe 3.2s ease-in-out infinite}
+@keyframes spin{to{--ang:360deg}}
+@keyframes breathe{50%{opacity:.6}}
+.finder{background:rgba(32,33,37,.92);color:#E9E9EC;backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px)}
+.finder .tb{border-bottom:1px solid rgba(255,255,255,.07)}
+.finder .ttl{font-size:12.5px;font-weight:600;margin-left:10px;color:#cfd0d4}
+.files{padding:8px}
+.file{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:7px;font-size:12.5px;cursor:grab}
+.file:hover{background:rgba(255,255,255,.06)}
+.file svg{width:22px;height:26px;flex:none}
+.file.dragging{opacity:.35}
+
+/* island */
+#island{position:absolute;left:50%;top:0;transform:translateX(-50%);width:184px;height:32px;background:#000;z-index:10;
+ border-radius:0 0 14px 14px;transition:width .52s var(--spr),height .52s var(--spr),border-radius .5s var(--spr)}
+#island.closing{transition:width .34s cubic-bezier(.45,0,.2,1),height .34s cubic-bezier(.45,0,.2,1),border-radius .3s ease}
+#island::before,#island::after{content:"";position:absolute;top:0;width:14px;height:14px;pointer-events:none}
+#island::before{left:-14px;background:radial-gradient(circle at 0 100%,transparent 13.5px,#000 14px)}
+#island::after{right:-14px;background:radial-gradient(circle at 100% 100%,transparent 13.5px,#000 14px)}
+#island[data-mode="expanded"]{border-radius:0 0 30px 30px}
+.clip{position:absolute;inset:0;overflow:hidden;border-radius:inherit}
+.botwrap{position:absolute;left:0;top:0;width:10px;height:10px;z-index:4;opacity:0;cursor:pointer;touch-action:none;
+ transition:left .52s var(--spr),top .52s var(--spr),width .52s var(--spr),height .52s var(--spr),opacity .25s ease}
+#island.closing .botwrap{transition:left .34s cubic-bezier(.45,0,.2,1),top .34s cubic-bezier(.45,0,.2,1),width .34s cubic-bezier(.45,0,.2,1),height .34s cubic-bezier(.45,0,.2,1),opacity .2s}
+#island[data-view="uploading"] .botwrap{transition:left .04s linear,top .3s var(--spr),width .3s var(--spr),height .3s var(--spr)}
+.botwrap canvas{position:absolute;inset:0;width:100%;height:100%}
+.botwrap .glow{position:absolute;inset:4%;border-radius:50%;background:radial-gradient(circle,var(--g,#3B9EFF) 0%,transparent 62%);opacity:var(--go,.5);filter:blur(6px);transition:opacity .5s ease,background .5s ease}
+.agent{position:absolute;left:0;top:0;width:10px;height:10px;border-radius:999px;z-index:3;opacity:0;cursor:pointer;
+ transition:left .52s var(--spr) var(--d,0s),top .52s var(--spr) var(--d,0s),width .52s var(--spr) var(--d,0s),height .52s var(--spr) var(--d,0s),
+ background .35s ease,border-color .35s ease,opacity .3s ease,transform .4s var(--spr);border:1px solid transparent}
+#island.closing .agent{transition-duration:.3s;transition-delay:0s}
+.agent canvas{position:absolute;transition:left .52s var(--spr) var(--d,0s),top .52s var(--spr) var(--d,0s),width .52s var(--spr) var(--d,0s),height .52s var(--spr) var(--d,0s)}
+.agent .lbl{position:absolute;left:36px;right:10px;top:50%;transform:translateY(-50%);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;opacity:0;transition:opacity .2s ease}
+.agent.pill{background:var(--bg);border-color:var(--bd)}
+.agent.pill .lbl{opacity:1;transition:opacity .3s ease calc(.22s + var(--d,0s))}
+.hdr{position:absolute;left:0;right:0;top:0;height:34px;display:flex;align-items:center;justify-content:space-between;padding:0 16px;z-index:2;opacity:0;pointer-events:none;transition:opacity .15s}
+#island[data-mode="expanded"] .hdr{opacity:1;pointer-events:auto;transition:opacity .3s ease .3s}
+.tabs{display:flex;gap:6px}
+.tab{appearance:none;border:0;width:26px;height:26px;border-radius:50%;display:grid;place-items:center;background:transparent;cursor:pointer;color:#8E939C}
+.tab.on{background:#1D1F23;color:#F5F6F8}
+.tab svg{width:14px;height:14px}
+.hdr .r{display:flex;align-items:center;gap:12px;font-size:11.5px;color:#7B8089}
+.hdr .snd{appearance:none;border:0;background:transparent;cursor:pointer;color:#8E939C;display:grid;place-items:center;width:24px;height:24px}
+.hdr .snd svg{width:15px;height:15px}
+.cd{position:absolute;left:50%;bottom:0;height:2px;width:0;transform:translateX(-50%);background:rgba(255,255,255,.35);border-radius:2px;z-index:5}
+
+.view{position:absolute;top:36px;left:10px;right:10px;bottom:10px;opacity:0;filter:blur(8px);transform:scale(.97);pointer-events:none;
+ transition:opacity .16s ease,filter .16s ease,transform .16s ease;color:#F5F6F8;font-size:13px}
+.view.on{opacity:1;filter:blur(0);transform:none;pointer-events:auto;transition:opacity .3s ease .16s,filter .3s ease .16s,transform .4s var(--spr) .12s}
+.card{position:absolute;background:#141518;border-radius:20px;overflow:hidden;border:1px solid rgba(255,255,255,.035)}
+.card.full{inset:0 42px 0 0}
+.card.wide{inset:0}
+.card.left{left:0;top:0;bottom:0;width:322px}
+.card.right{left:332px;right:0;top:0;bottom:0}
+.wash::before{content:"";position:absolute;inset:0;pointer-events:none;background:radial-gradient(120% 90% at 50% 130%,var(--w,transparent) 0%,transparent 70%);opacity:.9}
+.wash.red{--w:rgba(244,80,94,.55)} .wash.green{--w:rgba(52,211,153,.5)} .wash.pink{--w:rgba(244,114,182,.55)}
+.wash.amber{--w:rgba(245,165,36,.42)} .wash.cyan{--w:rgba(34,211,238,.38)} .wash.indigo{--w:rgba(99,102,241,.5)} .wash.soft{--w:rgba(255,255,255,.08)}
+.copy{position:relative;height:100%;display:flex;flex-direction:column;justify-content:center;gap:8px;padding:0 18px 0 var(--pl,102px)}
+.who{display:flex;align-items:center;gap:7px;font-size:12px;color:#8E939C}
+.who b{color:#F5F6F8;font-weight:600}
+.who .dot{width:8px;height:8px;border-radius:50%;background:var(--c,#fff);display:inline-block}
+.big{font-size:15px;font-weight:600;letter-spacing:-.01em;color:#F5F6F8;line-height:1.3}
+.sub{color:#9398A1;line-height:1.35}
+.sub.red{color:#FF8D97}
+code{font-family:"SF Mono",ui-monospace,Menlo,monospace;font-size:12px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.06);padding:8px 10px;border-radius:10px;color:#E8E9EC;align-self:flex-start}
+.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
+.btn{appearance:none;border:0;border-radius:999px;white-space:nowrap;padding:7px 13px;background:rgba(255,255,255,.09);color:#F1F2F4;font-size:12.5px;font-weight:500;cursor:pointer;display:inline-flex;gap:7px;align-items:center;transition:background .15s,transform .15s}
+.btn:hover{background:rgba(255,255,255,.15)}
+.btn:active{transform:scale(.96)}
+.btn.primary{background:#F5F6F8;color:#0B0C0E}
+.btn.primary:hover{background:#fff}
+.btn kbd{font-family:inherit;font-size:10.5px;opacity:.55;border:1px solid currentColor;border-radius:4px;padding:0 4px}
+.btn.pressed{transform:scale(.94);background:rgba(255,255,255,.22)}
+.btn.primary.pressed{background:#D9DBDF}
+.ticker{position:absolute;left:112px;right:12px;top:50%;transform:translateY(-50%);height:96px;overflow:hidden;
+ -webkit-mask:linear-gradient(transparent,#000 22%,#000 78%,transparent);mask:linear-gradient(transparent,#000 22%,#000 78%,transparent)}
+.tk-in{position:absolute;left:0;right:0;top:4px}
+.tk-in.roll{transition:transform .45s cubic-bezier(.3,.9,.3,1);transform:translateY(-30px)}
+.ln{height:30px;display:flex;align-items:center;gap:8px;font-size:13px;color:#5F646D;white-space:nowrap;overflow:hidden}
+.ln span{overflow:hidden;text-overflow:ellipsis}
+.ln svg{width:14px;height:14px;flex:none;opacity:.8}
+.ln.cur{color:#F5F6F8;font-size:14px;font-weight:500}
+.ln.cur .txt{background:linear-gradient(90deg,#7c818a 0%,#ffffff 40%,#7c818a 70%);background-size:220% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shim 2.2s linear infinite}
+@keyframes shim{from{background-position:120% 0}to{background-position:-100% 0}}
+.agentline{position:absolute;left:112px;top:14px;right:12px}
+.drop{position:absolute;inset:0 42px 0 0;border-radius:20px;border:1.5px dashed rgba(255,255,255,.14);background:#121316;overflow:hidden;transition:border-color .3s,background .3s}
+.drop::before{content:"";position:absolute;inset:0;background:radial-gradient(120% 100% at 50% 140%,rgba(52,211,153,.6),transparent 70%);opacity:0;transition:opacity .35s}
+.drop.over{border-color:rgba(52,211,153,.55)}
+.drop.over::before{opacity:1}
+.drop .copy{--pl:196px}
+.chips{display:flex;gap:6px;flex-wrap:wrap}
+.chip{font-size:11px;padding:3px 8px;border-radius:999px;background:rgba(255,255,255,.07);color:#B9BDC4;display:inline-flex;gap:6px;align-items:center}
+.chip.ctx{background:rgba(255,255,255,.1);color:#F1F2F4;font-size:11.5px;padding:4px 10px}
+.chip.ctx i{width:7px;height:7px;border-radius:50%;background:linear-gradient(135deg,#FF6B5B,#F7B32B,#2DD4A7,#38BDF8,#A78BFA);display:inline-block}
+.bar{position:absolute;left:36px;right:78px;top:74px;height:6px;border-radius:6px;background:rgba(255,255,255,.08)}
+.bar i{position:absolute;left:0;top:0;bottom:0;width:0;border-radius:6px;background:linear-gradient(90deg,#1FA87A,#34D399)}
+.upl{position:absolute;left:36px;right:78px;top:34px;display:flex;justify-content:space-between;font-size:12.5px;color:#A9ADB5}
+.prompt{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.06);border-radius:14px;padding:6px 6px 6px 12px}
+.prompt input{flex:1;background:transparent;border:0;color:#F5F6F8;font:inherit;font-size:13.5px;outline:none;min-width:0}
+.prompt input::placeholder{color:#6E737C}
+.ibtn{appearance:none;border:0;width:28px;height:28px;border-radius:50%;display:grid;place-items:center;background:rgba(255,255,255,.08);cursor:pointer;color:#C9CCD2;flex:none}
+.ibtn.send{background:#F5F6F8;color:#0B0C0E}
+.ibtn svg{width:14px;height:14px}
+.status{font-size:13.5px}
+.status .txt{background:linear-gradient(90deg,#7c818a 0%,#ffffff 40%,#7c818a 70%);background-size:220% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shim 1.8s linear infinite}
+.res{display:flex;flex-direction:column;gap:4px;margin:2px 0}
+.res div{display:flex;justify-content:space-between;gap:14px;padding:6px 10px;border-radius:10px;background:rgba(255,255,255,.05);font-size:12.5px}
+.res div span{color:#9398A1}
+.res div b{font-weight:600}
+.fine{font-size:11px;color:#6E737C}
+.field{display:flex;gap:8px;align-items:center;background:rgba(255,255,255,.06);border-radius:10px;padding:6px 10px;font-size:12.5px}
+.field span{color:#80858E;width:44px}
+.field input{flex:1;background:transparent;border:0;color:#F5F6F8;font:inherit;outline:none;min-width:0}
+
+/* floating things */
+.floatbot{position:absolute;width:90px;height:90px;margin:-45px 0 0 -45px;z-index:30;pointer-events:none;display:none}
+.floatbot canvas{width:100%;height:100%}
+.fileghost{position:absolute;z-index:30;pointer-events:none;display:none;margin:-22px 0 0 -18px;text-align:center;width:36px}
+.fileghost svg{width:36px;height:44px;filter:drop-shadow(0 8px 12px rgba(0,0,0,.5))}
+.ghost{position:absolute;z-index:40;pointer-events:none;display:none;width:22px;height:22px;margin:-2px 0 0 -3px;transition:transform .12s}
+.ghost.down{transform:scale(.82)}
+.ghost svg{width:22px;height:22px;filter:drop-shadow(0 2px 3px rgba(0,0,0,.5))}
+.demo-tag{position:absolute;right:18px;bottom:16px;z-index:40;font-size:12px;color:rgba(255,255,255,.7);background:rgba(0,0,0,.45);padding:6px 11px;border-radius:999px;display:none}
+
+/* controls */
+.controls{max-width:1180px;margin:22px auto 40px;padding:0 24px;display:grid;grid-template-columns:repeat(12,1fr);gap:14px}
+.grp{background:var(--panel);border:1px solid var(--line);border-radius:18px;padding:16px 16px 14px}
+.grp h2{font-size:14px;margin:0 0 4px;font-weight:650;letter-spacing:-.005em}
+.grp p{margin:0 0 12px;font-size:13px;color:var(--muted);line-height:1.4}
+.g-char{grid-column:span 5}.g-state{grid-column:span 7}.g-emote{grid-column:span 5}.g-sim{grid-column:span 7}.g-set{grid-column:span 12}
+@media (max-width:900px){.g-char,.g-state,.g-emote,.g-sim,.g-set{grid-column:span 12}}
+.seg{display:inline-flex;background:var(--chip);border-radius:12px;padding:3px;gap:2px}
+.seg button{appearance:none;border:0;background:transparent;padding:7px 16px;border-radius:9px;font-size:13.5px;cursor:pointer;color:var(--muted);font-weight:550}
+.seg button.on{background:var(--panel);color:var(--ink);box-shadow:0 1px 3px rgba(0,0,0,.12)}
+.desc{margin-top:10px;font-size:13px;color:var(--muted);min-height:36px;line-height:1.4}
+.btns{display:flex;flex-wrap:wrap;gap:6px}
+.cb{appearance:none;border:1px solid var(--line);background:transparent;border-radius:999px;padding:6px 11px 6px 9px;font-size:13px;cursor:pointer;display:inline-flex;align-items:center;gap:7px;color:var(--ink)}
+.cb:hover{background:var(--chip)}
+.cb.on{background:var(--ink);color:var(--panel);border-color:var(--ink)}
+.cb i{width:9px;height:9px;border-radius:50%;display:inline-block;background:var(--c,#999);box-shadow:0 0 0 1px rgba(0,0,0,.12)}
+.setrow{display:flex;gap:28px;flex-wrap:wrap;align-items:center;font-size:13.5px}
+.setrow label{display:flex;gap:10px;align-items:center}
+.setrow input[type=range]{width:120px}
+.how{max-width:1180px;margin:10px auto 0;padding:0 24px;color:var(--muted);font-size:13.5px;line-height:1.5}
+.how b{color:var(--ink);font-weight:600}
+@media (prefers-reduced-motion: reduce){
+ #island,.botwrap,.agent,.view,.view.on{transition-duration:.01s!important;transition-delay:0s!important}
+}
+</style>
+</head>
+<body>
+<header class="top">
+ <div class="grow">
+ <h1>Notch Buddy</h1>
+ <p>Prototype visuel du compagnon de notch, à valider avant la version Swift. Tout est codé, rien n'est une vidéo.</p>
+ </div>
+ <button class="demo-btn" id="demoBtn"><svg viewBox="0 0 12 12"><path d="M2 1.2v9.6L10.4 6z" fill="currentColor"/></svg><span>Lancer la démo</span></button>
+</header>
+<p class="how"><b>À tester à la main :</b> survole le notch, clique trois fois sur le bonhomme, glisse un fichier du Finder vers le notch, attrape le bonhomme et lâche-le sur Safari. Active le son en bas.</p>
+
+<div class="stage-wrap"><div class="stage-outer" id="stageOuter">
+<div class="stage" id="stage"><div class="mac"><div class="screen" id="screen">
+ <div class="curve"></div><div class="curve2"></div>
+ <div class="menubar">
+ <div class="l"><svg viewBox="0 0 16 16"><path d="M11.2 8.5c0-1.6 1.3-2.4 1.4-2.4-.8-1.1-2-1.3-2.4-1.3-1-.1-2 .6-2.5.6s-1.3-.6-2.2-.6C4.3 4.8 3 5.6 2.4 6.9c-1.3 2.2-.3 5.5.9 7.3.6.9 1.3 1.9 2.2 1.8.9 0 1.2-.6 2.3-.6s1.4.6 2.3.6c1 0 1.6-.9 2.1-1.8.7-1 .9-1.9 1-2-.1 0-1.9-.7-1.9-2.7zM9.5 3.8c.5-.6.8-1.4.7-2.2-.7 0-1.5.5-2 1.1-.4.5-.8 1.3-.7 2.1.8.1 1.5-.4 2-1z"/></svg><b>Finder</b><span>Fichier</span><span>Édition</span><span>Présentation</span></div>
+ <div class="r"><svg viewBox="0 0 16 16"><path d="M8 12.5l1.6-1.8a2.2 2.2 0 00-3.2 0zM4.6 9a4.8 4.8 0 016.8 0l1-1.1a6.3 6.3 0 00-8.8 0zM2.3 6.5a8 8 0 0111.4 0l1-1.1a9.5 9.5 0 00-13.4 0z"/></svg><span>100 %</span><span>mer. 23 sept. 01:06</span></div>
+ </div>
+ <div class="notch"></div>
+
+ <div class="win safari" id="safari" style="left:62px;top:262px;width:560px;height:340px">
+ <div class="tb"><i class="tl r"></i><i class="tl y"></i><i class="tl g"></i><div class="url">escale.fr/lisbonne</div></div>
+ <div class="page">
+ <div class="brand">escale</div>
+ <div class="search">Lisbonne, du 26 oct. au 1er nov., 2 voyageurs</div>
+ <div class="grid">
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#F6C3A4,#E0785A)"></div><b>Alfama, vue sur le Tage</b><span>84 € la nuit</span></div>
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#BFD8F2,#5C8FD6)"></div><b>Príncipe Real, calme</b><span>79 € la nuit</span></div>
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#CDE8C9,#5FA873)"></div><b>Graça, terrasse</b><span>88 € la nuit</span></div>
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#F1E1A9,#D4A33C)"></div><b>Baixa, loft</b><span>112 € la nuit</span></div>
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#E4CCEB,#9B6BC0)"></div><b>Bairro Alto</b><span>96 € la nuit</span></div>
+ <div class="lst"><div class="ph" style="background:linear-gradient(135deg,#C9E6E6,#4AA3A3)"></div><b>Belém, jardin</b><span>101 € la nuit</span></div>
+ </div>
+ </div>
+ <div class="attach"><div class="wash"></div><div class="ring"></div></div>
+ </div>
+
+ <div class="win finder" id="finder" style="left:760px;top:360px;width:280px;height:176px">
+ <div class="tb"><i class="tl r"></i><i class="tl y"></i><i class="tl g"></i><span class="ttl">Téléchargements</span></div>
+ <div class="files">
+ <div class="file" data-name="brief-client.pdf"><svg viewBox="0 0 22 26"><path d="M2 1h12l6 6v17a1 1 0 01-1 1H2a1 1 0 01-1-1V2a1 1 0 011-1z" fill="#F4F4F6"/><path d="M14 1v6h6" fill="#D5D6DB"/><rect x="4" y="15" width="14" height="6" rx="1.5" fill="#E5484D"/></svg><span>brief-client.pdf</span></div>
+ <div class="file" data-name="maquettes-korus.fig"><svg viewBox="0 0 22 26"><path d="M2 1h12l6 6v17a1 1 0 01-1 1H2a1 1 0 01-1-1V2a1 1 0 011-1z" fill="#F4F4F6"/><path d="M14 1v6h6" fill="#D5D6DB"/><rect x="4" y="15" width="14" height="6" rx="1.5" fill="#A259FF"/></svg><span>maquettes-korus.fig</span></div>
+ <div class="file" data-name="notes-episode.md"><svg viewBox="0 0 22 26"><path d="M2 1h12l6 6v17a1 1 0 01-1 1H2a1 1 0 01-1-1V2a1 1 0 011-1z" fill="#F4F4F6"/><path d="M14 1v6h6" fill="#D5D6DB"/><rect x="4" y="15" width="14" height="6" rx="1.5" fill="#6B7280"/></svg><span>notes-episode.md</span></div>
+ </div>
+ </div>
+
+ <div id="island" data-mode="hidden" data-view="overview">
+ <div class="clip">
+ <div class="hdr">
+ <div class="tabs">
+ <button class="tab on" data-go="overview" aria-label="Vue d'ensemble"><svg viewBox="0 0 16 16"><path d="M2.5 7.2L8 2.5l5.5 4.7V13a.8.8 0 01-.8.8H10V10H6v3.8H3.3a.8.8 0 01-.8-.8z" fill="currentColor"/></svg></button>
+ <button class="tab" data-go="prompt" aria-label="Demander à Claude"><svg viewBox="0 0 16 16"><path d="M3 2.5h10a1.5 1.5 0 011.5 1.5v6a1.5 1.5 0 01-1.5 1.5H7l-3.5 3v-3H3A1.5 1.5 0 011.5 10V4A1.5 1.5 0 013 2.5z" fill="currentColor"/></svg></button>
+ <button class="tab" data-go="upload" aria-label="Déposer des fichiers"><svg viewBox="0 0 16 16"><path d="M8 3v10M3 8h10" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg></button>
+ </div>
+ <div class="r"><span id="hdrCount"></span><button class="snd" id="hdrSnd" aria-label="Son"><svg viewBox="0 0 16 16"><path d="M2 6h2.5L8 3v10L4.5 10H2z" fill="currentColor"/><path class="w" d="M10.5 5.5a3.5 3.5 0 010 5M12.3 3.8a6 6 0 010 8.4" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linecap="round"/></svg></button></div>
+ </div>
+
+ <div class="view" data-view="overview">
+ <div class="card left">
+ <div class="agentline"><div class="who"><i class="dot" data-f="dot"></i><b data-f="name">Korus</b><span data-f="tool">Claude Code</span></div></div>
+ <div class="ticker"><div class="tk-in" id="tk">
+ <div class="ln"><svg viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="2" stroke="currentColor" fill="none" stroke-width="1.4"/></svg><span></span></div>
+ <div class="ln cur"><svg viewBox="0 0 16 16"><path d="M4 5l3 3-3 3M8.5 11H12" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="txt"></span></div>
+ <div class="ln"><svg viewBox="0 0 16 16"><rect x="4" y="2" width="9" height="11" rx="1.6" stroke="currentColor" fill="none" stroke-width="1.4"/><path d="M3 5v8.5A1.5 1.5 0 004.5 15H10" stroke="currentColor" fill="none" stroke-width="1.4"/></svg><span></span></div>
+ <div class="ln"><svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="5" stroke="currentColor" fill="none" stroke-width="1.4"/></svg><span></span></div>
+ </div></div>
+ </div>
+ <div class="card right"></div>
+ </div>
+
+ <div class="view" data-view="empty">
+ <div class="card wide wash soft"><div class="copy" style="--pl:118px;flex-direction:row;align-items:center;justify-content:space-between;gap:16px">
+ <div style="display:flex;flex-direction:column;gap:5px"><div class="big">Rien ne tourne pour l'instant.</div><div class="sub">Glisse un fichier ou une fenêtre sur moi, ou pose ta question.</div></div>
+ <button class="btn primary" data-act="ask">Demander à Claude</button>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="approval">
+ <div class="card full wash amber"><div class="copy">
+ <div class="who"><i class="dot" data-f="dot"></i><b data-f="name"></b><span>Claude Code veut lancer une commande</span></div>
+ <code>npx prisma migrate deploy</code>
+ <div class="row"><button class="btn" data-act="deny">Refuser <kbd>N</kbd></button><button class="btn" data-act="always">Toujours autoriser</button><button class="btn primary" data-act="allow">Autoriser <kbd>Y</kbd></button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="question">
+ <div class="card full wash cyan"><div class="copy">
+ <div class="who"><i class="dot" data-f="dot"></i><b data-f="name"></b><span>Claude Code te pose une question</span></div>
+ <div class="big">Quel moteur pour la recherche de cours ?</div>
+ <div class="row"><button class="btn opt" data-act="answer">Postgres full-text</button><button class="btn opt" data-act="answer">Meilisearch</button><button class="btn opt" data-act="answer">Algolia</button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="error">
+ <div class="card full wash red"><div class="copy">
+ <div class="who"><i class="dot" data-f="dot"></i><b data-f="name"></b><span data-f="tool"></span></div>
+ <div class="big">Le workflow s'est arrêté.</div>
+ <div class="sub red">Le nœud Gmail a expiré après 30 s. Relance ou ouvre n8n pour voir l'exécution.</div>
+ <div class="row"><button class="btn primary" data-act="retry">Relancer</button><button class="btn" data-act="open-n8n">Ouvrir dans n8n</button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="finished">
+ <div class="card full wash green"><div class="copy">
+ <div class="who"><i class="dot" data-f="dot"></i><b data-f="name"></b><span>Claude Code a terminé</span></div>
+ <div class="big">Migration appliquée, 14 tests passés.</div>
+ <div class="row"><button class="btn primary" data-act="jump">Voir le terminal</button><button class="btn" data-act="ok">OK</button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="confused">
+ <div class="card full wash pink"><div class="copy" style="--pl:128px">
+ <div class="big">Trop de claques d'un coup.</div>
+ <div class="sub">Je reprends mes esprits et je reviens au travail dans trois secondes.</div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="upload">
+ <div class="drop" id="drop"><div class="copy">
+ <div class="big">Dépose tes fichiers ici</div>
+ <div class="chips"><span class="chip">PDF</span><span class="chip">Images</span><span class="chip">Code</span><span class="chip">Docs</span></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="uploading">
+ <div class="card full wash green">
+ <div class="upl"><span>Envoi de <b data-f="file"></b></span><span id="upPct">0 %</span></div>
+ <div class="bar"><i id="upBar"></i></div>
+ </div>
+ </div>
+
+ <div class="view" data-view="choose">
+ <div class="card full wash soft"><div class="copy" style="--pl:98px">
+ <div class="big"><span data-f="file"></span> est prêt.</div>
+ <div class="sub">Tu veux en faire quoi ?</div>
+ <div class="row"><button class="btn primary" data-act="file-ask">Poser une question dessus</button><button class="btn" data-act="mail">Envoyer par mail</button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="mail">
+ <div class="card full wash soft"><div class="copy" style="--pl:92px;gap:7px">
+ <div class="who"><b>Nouveau mail</b><span>avec <span data-f="file"></span> en pièce jointe</span></div>
+ <div class="field"><span>À</span><input id="mailTo" placeholder="[email protected]" autocomplete="off"></div>
+ <div class="field"><span>Objet</span><input id="mailSubj" value="Le brief, comme promis" autocomplete="off"></div>
+ <div class="row"><button class="btn primary" data-act="send-mail">Envoyer</button><button class="btn" data-act="close">Annuler</button></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="prompt">
+ <div class="card full wash indigo" style="--w:rgba(99,102,241,.22)"><div class="copy" style="--pl:84px;gap:9px">
+ <div class="row" id="ctxChips"></div>
+ <div class="prompt"><input id="promptIn" placeholder="Demande n'importe quoi à Claude…" autocomplete="off">
+ <button class="ibtn" aria-label="Dicter"><svg viewBox="0 0 16 16"><rect x="5.5" y="1.5" width="5" height="8.5" rx="2.5" fill="currentColor"/><path d="M3.5 8a4.5 4.5 0 009 0M8 12.5v2" stroke="currentColor" stroke-width="1.4" fill="none" stroke-linecap="round"/></svg></button>
+ <button class="ibtn send" data-act="send" aria-label="Envoyer"><svg viewBox="0 0 16 16"><path d="M8 13V3M3.5 7.5L8 3l4.5 4.5" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
+ </div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="searching">
+ <div class="card full wash indigo"><div class="copy" style="--pl:84px">
+ <div class="row" data-f="chips"></div>
+ <div class="status"><span class="txt" data-f="status">Claude lit la page et cherche…</span></div>
+ </div></div>
+ </div>
+
+ <div class="view" data-view="result">
+ <div class="card full wash green" style="--w:rgba(52,211,153,.22)"><div class="copy" style="--pl:84px;gap:7px" id="resBox"></div></div>
+ </div>
+
+ <div class="view" data-view="note">
+ <div class="card full wash soft"><div class="copy" style="--pl:98px"><div class="big" data-f="note"></div><div class="sub" data-f="note2"></div></div></div>
+ </div>
+
+ <div class="cd" id="cd"></div>
+ </div>
+ <div class="botwrap" id="botwrap"><div class="glow"></div><canvas id="botc"></canvas></div>
+ </div>
+
+ <div class="floatbot" id="floatbot"><canvas id="floatc"></canvas></div>
+ <div class="fileghost" id="fileghost"><svg viewBox="0 0 22 26"><path d="M2 1h12l6 6v17a1 1 0 01-1 1H2a1 1 0 01-1-1V2a1 1 0 011-1z" fill="#F4F4F6"/><path d="M14 1v6h6" fill="#D5D6DB"/><rect x="4" y="15" width="14" height="6" rx="1.5" fill="#E5484D"/></svg></div>
+ <div class="ghost" id="ghost"><svg viewBox="0 0 22 22"><path d="M4 2l13 11.2-6 .5 3.6 6.4-2.4 1.3-3.6-6.5L4 19z" fill="#fff" stroke="#000" stroke-width="1.2" stroke-linejoin="round"/></svg></div>
+ <div class="demo-tag" id="demoTag">Démo en cours, la souris est simulée</div>
+</div></div></div>
+</div></div>
+
+<section class="controls">
+ <div class="grp g-char">
+ <h2>Personnage</h2>
+ <p>Trois pistes, toutes simples. Même moteur, mêmes états.</p>
+ <div class="seg" id="segPiste"><button data-p="galet">Galet</button><button data-p="mochi" class="on">Mochi</button><button data-p="lueur">Lueur</button></div>
+ <div class="desc" id="pisteDesc"></div>
+ </div>
+ <div class="grp g-state">
+ <h2>États</h2>
+ <p>Chaque état a sa couleur, ses yeux et son badge. Les six derniers sont nouveaux.</p>
+ <div class="btns" id="stateBtns"></div>
+ </div>
+ <div class="grp g-emote">
+ <h2>Émotes</h2>
+ <p>Des réactions courtes qui passent par-dessus l'état en cours.</p>
+ <div class="btns" id="emoteBtns"></div>
+ </div>
+ <div class="grp g-sim">
+ <h2>Simuler des événements</h2>
+ <p>Ce qui arrivera pour de vrai avec Claude Code et n8n branchés.</p>
+ <div class="btns" id="simBtns"></div>
+ </div>
+ <div class="grp g-set">
+ <h2>Réglages</h2>
+ <div class="setrow">
+ <label><input type="checkbox" id="sndOn"> Son</label>
+ <label>Volume <input type="range" id="sndVol" min="0" max="1" step=".05" value=".7"></label>
+ <label>Fermeture auto
+ <span class="seg" id="segClose"><button data-ms="60000" class="on">1 min</button><button data-ms="6000">6 s (test)</button></span>
+ </label>
+ </div>
+ </div>
+</section>
+
+<script>
+(()=>{
+const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
+const NOW=()=>performance.now();
+const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)), lerp=(a,b,t)=>a+(b-a)*t;
+const sleep=ms=>new Promise(r=>setTimeout(r,ms));
+const E={out:t=>1-Math.pow(1-t,3),inOut:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,back:t=>{const c1=1.7,c3=c1+1;return 1+c3*Math.pow(t-1,3)+c1*Math.pow(t-1,2)},lin:t=>t};
+const hexRgb=h=>{h=h.replace('#','');return[parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]};
+const rgba=(c,a)=>`rgba(${c[0]|0},${c[1]|0},${c[2]|0},${a})`;
+const mix=(a,b,t)=>[lerp(a[0],b[0],t),lerp(a[1],b[1],t),lerp(a[2],b[2],t)];
+
+/* ---------------- SON ---------------- */
+const Snd={ctx:null,on:false,vol:.7,
+ init(){ if(this.ctx)return; const C=window.AudioContext||window.webkitAudioContext; if(!C)return; const c=this.ctx=new C();
+ this.master=c.createGain(); this.master.gain.value=this.vol; const comp=c.createDynamicsCompressor(); comp.threshold.value=-18;
+ this.master.connect(comp); comp.connect(c.destination);
+ const len=Math.floor(c.sampleRate*1.3), ir=c.createBuffer(2,len,c.sampleRate);
+ for(let ch=0;ch<2;ch++){const d=ir.getChannelData(ch); for(let i=0;i<len;i++) d[i]=(Math.random()*2-1)*Math.pow(1-i/len,3.4);}
+ const rev=c.createConvolver(); rev.buffer=ir; const wet=c.createGain(); wet.gain.value=.2; rev.connect(wet); wet.connect(this.master);
+ this.bus=c.createGain(); this.bus.connect(this.master); this.bus.connect(rev);
+ const nb=c.createBuffer(1,c.sampleRate,c.sampleRate), nd=nb.getChannelData(0); for(let i=0;i<nd.length;i++) nd[i]=Math.random()*2-1; this.nb=nb;
+ },
+ setVol(v){this.vol=v; if(this.master) this.master.gain.value=v},
+ tone({f=440,to=0,d=.2,type='sine',g=.1,a=.006,delay=0,vib=0,vibf=6,h=0}){ const c=this.ctx,t=c.currentTime+delay;
+ const o=c.createOscillator(); o.type=type; o.frequency.setValueAtTime(f,t); if(to) o.frequency.exponentialRampToValueAtTime(to,t+d*.9);
+ const gn=c.createGain(); gn.gain.setValueAtTime(.0001,t); gn.gain.exponentialRampToValueAtTime(g,t+a); gn.gain.exponentialRampToValueAtTime(.0001,t+d);
+ if(vib){const l=c.createOscillator(),lg=c.createGain(); l.frequency.value=vibf; lg.gain.value=vib; l.connect(lg); lg.connect(o.frequency); l.start(t); l.stop(t+d+.05);}
+ o.connect(gn); gn.connect(this.bus); o.start(t); o.stop(t+d+.05);
+ if(h){const o2=c.createOscillator(); o2.frequency.setValueAtTime(f*h,t); const g2=c.createGain(); g2.gain.setValueAtTime(.0001,t); g2.gain.exponentialRampToValueAtTime(g*.3,t+a); g2.gain.exponentialRampToValueAtTime(.0001,t+d*.35); o2.connect(g2); g2.connect(this.bus); o2.start(t); o2.stop(t+d);}
+ },
+ noise({d=.2,g=.04,f=1500,to=0,q=.9,type='bandpass',delay=0}){ const c=this.ctx,t=c.currentTime+delay;
+ const s=c.createBufferSource(); s.buffer=this.nb; const fl=c.createBiquadFilter(); fl.type=type; fl.Q.value=q; fl.frequency.setValueAtTime(f,t); if(to) fl.frequency.exponentialRampToValueAtTime(to,t+d);
+ const gn=c.createGain(); gn.gain.setValueAtTime(.0001,t); gn.gain.exponentialRampToValueAtTime(g,t+d*.35); gn.gain.exponentialRampToValueAtTime(.0001,t+d);
+ s.connect(fl); fl.connect(gn); gn.connect(this.bus); s.start(t); s.stop(t+d+.05);
+ },
+ play(n){ if(!this.on)return; this.init(); if(!this.ctx)return; if(this.ctx.state==='suspended') this.ctx.resume(); const f=this.lib[n]; if(f) try{f.call(this)}catch(e){} },
+ lib:{
+ peek(){this.tone({f:1320,d:.09,g:.04});this.tone({f:1760,d:.12,g:.035,delay:.07})},
+ open(){this.tone({f:300,to:560,d:.24,g:.06});this.noise({d:.28,g:.018,f:900,to:3200})},
+ close(){this.tone({f:540,to:300,d:.2,g:.05});this.noise({d:.2,g:.014,f:2600,to:800})},
+ hover(){this.tone({f:2100,d:.05,g:.014})},
+ blip(){this.tone({f:1480,d:.07,g:.035})},
+ slap(){this.tone({f:280,to:110,d:.18,type:'triangle',g:.16});this.noise({d:.06,g:.06,f:900,q:.6})},
+ annoyed(){this.tone({f:240,to:185,d:.2,type:'triangle',g:.07,delay:.06})},
+ dizzy(){this.tone({f:640,to:380,d:1,g:.06,vib:45,vibf:9});this.tone({f:960,to:560,d:1,g:.025,vib:70,vibf:7,delay:.06})},
+ greet(){[523.25,659.25,783.99].forEach((f,i)=>this.tone({f,d:.32,g:.06,delay:i*.085,h:4}))},
+ work(){this.tone({f:880,d:.14,g:.028});this.tone({f:1174.7,d:.18,g:.022,delay:.07})},
+ finish(){this.tone({f:783.99,d:.6,g:.08,h:4});this.tone({f:1046.5,d:.9,g:.08,h:4,delay:.11});this.tone({f:1318.5,d:1.1,g:.045,h:3,delay:.22})},
+ error(){this.tone({f:392,d:.35,type:'triangle',g:.09});this.tone({f:311.1,d:.55,type:'triangle',g:.09,delay:.16})},
+ approval(){this.tone({f:987.8,d:.35,g:.07,h:2.76});this.tone({f:987.8,d:.5,g:.07,h:2.76,delay:.18})},
+ question(){this.tone({f:659.3,d:.24,g:.06,h:3});this.tone({f:880,d:.4,g:.06,h:3,delay:.12})},
+ approve(){this.tone({f:660,d:.18,g:.05});this.tone({f:990,d:.3,g:.05,delay:.08,h:3})},
+ gulp(){this.tone({f:340,to:120,d:.16,g:.11});this.tone({f:210,to:80,d:.22,g:.09,delay:.1})},
+ tick(){this.tone({f:2400,d:.03,g:.012})},
+ send(){this.noise({d:.38,g:.04,f:700,to:4200});this.tone({f:600,to:1250,d:.26,g:.035})},
+ love(){this.tone({f:1046.5,d:.32,g:.045,vib:14,vibf:8});this.tone({f:1318.5,d:.5,g:.045,vib:14,vibf:8,delay:.14})},
+ pop(){this.tone({f:480,to:1150,d:.11,g:.07})},
+ proud(){[784,988,1175,1568].forEach((f,i)=>this.tone({f,d:.4,g:.045,delay:i*.06,h:4}))},
+ wink(){this.tone({f:1400,to:1900,d:.09,g:.035})},
+ yawn(){this.tone({f:430,to:250,d:.8,g:.045,vib:9,vibf:4})},
+ attach(){[1568,1976,2349,2637,3136].forEach((f,i)=>this.tone({f,d:.7,g:.022,delay:i*.05}));this.noise({d:.7,g:.02,f:3000,to:6000})},
+ think(){this.tone({f:520,d:.2,g:.03});this.tone({f:620,d:.25,g:.03,delay:.12})},
+ search(){this.tone({f:740,d:.12,g:.025});this.tone({f:990,d:.12,g:.025,delay:.1});this.tone({f:1245,d:.2,g:.025,delay:.2})},
+ rate(){this.tone({f:500,to:420,d:.3,g:.04});this.tone({f:420,to:350,d:.4,g:.04,delay:.18})},
+ sleep(){this.tone({f:330,to:290,d:.5,g:.03})}
+ }
+};
+
+/* ---------------- PERSONNAGE ---------------- */
+const PISTES={
+ galet:{name:'Galet',desc:"Une bille mate avec deux yeux en pilule. Très lisible en tout petit.",shape:'circle',eye:{w:.25,h:.52,sp:.31,p:.02},base:['#F7F8FA','#B5BAC3'],ink:'#121418'},
+ mochi:{name:'Mochi',desc:"Un petit pain de riz aplati, yeux ronds et joues qui rosissent. Le plus mignon, un peu moins neutre.",shape:'mochi',eye:{w:.25,h:.27,sp:.37,p:-.12},base:['#FFFAF5','#DDCCBF'],ink:'#1A1412'},
+ lueur:{name:'Lueur',desc:"Une sphère qui prend la couleur de son état. On sait ce qui se passe sans lire, même de loin.",shape:'orb',eye:{w:.22,h:.46,sp:.29,p:.02},base:['#F2F5F8','#C9D2DC'],ink:'#0D1522'}
+};
+const STATES={
+ idle:{label:'Au repos',col:'#E6E9EE',tint:0,eye:'pill',badge:null,glow:'rgba(255,255,255,.35)',go:.25},
+ working:{label:'Travaille',col:'#3B9EFF',tint:.72,eye:'pill',badge:['dots','#3B9EFF'],glow:'#3B9EFF',go:.55,snd:'work'},
+ finished:{label:'Terminé',col:'#34D399',tint:.35,eye:'happy',badge:['dot','#34D399'],glow:'#34D399',go:.5,snd:'finish'},
+ error:{label:'Erreur',col:'#F4505E',tint:.78,eye:'flat',badge:['dot','#F4505E'],glow:'#F4505E',go:.55,snd:'error'},
+ dizzy:{label:'Sonné',col:'#F472B6',tint:.7,eye:'spiral',badge:null,glow:'#F472B6',go:.55,snd:'dizzy'},
+ thinking:{label:'Réfléchit',col:'#8B5CF6',tint:.72,eye:'pill',badge:['dots','#8B5CF6'],glow:'#8B5CF6',go:.5,look:[.55,.55],snd:'think',nu:1},
+ searching:{label:'Cherche',col:'#6366F1',tint:.72,eye:'pill',badge:['dots','#6366F1'],glow:'#6366F1',go:.55,scan:1,snd:'search',nu:1},
+ approval:{label:'Attend ton feu vert',col:'#F5A524',tint:.78,eye:'wide',badge:['bang','#F5A524'],glow:'#F5A524',go:.6,bounce:1,snd:'approval',nu:1},
+ question:{label:'Pose une question',col:'#22D3EE',tint:.75,eye:'pill',badge:['q','#22D3EE'],glow:'#22D3EE',go:.55,tilt:.17,snd:'question',nu:1},
+ ratelimit:{label:'Limite atteinte',col:'#FB923C',tint:.72,eye:'tired',badge:['dot','#FB923C'],glow:'#FB923C',go:.45,sweat:1,snd:'rate',nu:1},
+ sleeping:{label:'Dort',col:'#94A3B8',tint:.32,eye:'closed',badge:null,glow:'#94A3B8',go:.2,breathe:1,zz:1,snd:'sleep',nu:1}
+};
+const EMOTES={love:{label:'Amour',eye:'heart',snd:'love',c:'#FF4D6D'},surprised:{label:'Surpris',eye:'dot',snd:'pop',c:'#FFFFFF'},proud:{label:'Fier',eye:'star',snd:'proud',c:'#F7B32B'},wink:{label:"Clin d'œil",eye:'wink',snd:'wink',c:'#A78BFA'},yawn:{label:'Bâille',eye:'tired',snd:'yawn',c:'#94A3B8'},happy:{eye:'happy'},annoyed:{eye:'line'}};
+
+function rr(x,X,Y,W,H,R){R=Math.max(0,Math.min(R,W/2,H/2));x.beginPath();x.moveTo(X+R,Y);x.arcTo(X+W,Y,X+W,Y+H,R);x.arcTo(X+W,Y+H,X,Y+H,R);x.arcTo(X,Y+H,X,Y,R);x.arcTo(X,Y,X+W,Y,R);x.closePath()}
+function heart(x,s){x.beginPath();x.moveTo(0,s*.38);x.bezierCurveTo(-s*1.05,-s*.15,-s*.5,-s*.95,0,-s*.38);x.bezierCurveTo(s*.5,-s*.95,s*1.05,-s*.15,0,s*.38);x.closePath()}
+function star(x,ro,ri){x.beginPath();for(let i=0;i<10;i++){const r=i%2?ri:ro,a=-Math.PI/2+i*Math.PI/5;x.lineTo(Math.cos(a)*r,Math.sin(a)*r)}x.closePath()}
+
+class Bot{
+ constructor(canvas,{mini=false,bodyColor=null}={}){
+ this.c=canvas; this.x=canvas.getContext('2d'); this.mini=mini; this.bodyColor=bodyColor?hexRgb(bodyColor):null;
+ this.s={yaw:0,pitch:0,roll:0,tilt:0,open:1,sx:1,sy:1,oy:0,ox:0,tint:0,morph:0,hands:0,blush:0,es:1,badgeS:0};
+ this.tg={...this.s}; this.tw=[]; this.lock={};
+ this.col=[230,233,238]; this.colT=[230,233,238];
+ this.state='idle'; this.cfg=STATES.idle; this.eyeOv=null; this.ovUntil=0; this.badge=null; this.badgeCol='#fff'; this._bk='none'; this._bt=0;
+ this.parts=[]; this.nextBlink=NOW()+1500+Math.random()*2000; this.look={x:0,y:0}; this.t0=NOW()-Math.random()*5000; this.waveUntil=0; this.lastAmb=0; this.last=NOW();
+ const dpr=Math.min(2,window.devicePixelRatio||1); const px=mini?76:230; canvas.width=px*dpr; canvas.height=px*dpr;
+ }
+ anim(p,keys,after){ this.tw=this.tw.filter(t=>t.p!==p); this.tw.push({p,keys,i:0,from:this.s[p],t0:NOW(),after}); this.lock[p]=1 }
+ setState(n,force){ if(!STATES[n])return; if(this.state===n&&!force)return; const prev=this.state; this.state=n; const c=this.cfg=STATES[n];
+ this.colT=hexRgb(c.col); this.tg.tint=c.tint; this.tg.tilt=c.tilt||0; this.setBadge(c.badge);
+ if(n==='finished'){ this.roll(950,1); setTimeout(()=>this.emit('spark',5),500) }
+ else if(n==='error'){ this.anim('ox',[[.08,50,E.out],[-.08,70,E.inOut],[.05,70,E.inOut],[0,90,E.out]]) }
+ else if(n==='approval'){ this.anim('oy',[[-.2,150,E.out],[0,300,E.back]]) }
+ else if(n==='dizzy'){ this.roll(1300,2) }
+ else if(n==='question'){ this.blink() }
+ else if(n==='ratelimit'){ this.emit('sweat',1) }
+ else if(prev!=='idle'||n!=='idle') this.blink();
+ }
+ setBadge(b){ const key=b?b.join():'none'; if(key===this._bk)return; this._bk=key; const tok=++this._bt;
+ this.anim('badgeS',[[0,90,E.inOut]]); setTimeout(()=>{ if(tok!==this._bt)return; this.badge=b?b[0]:null; this.badgeCol=b?b[1]:null; if(b) this.anim('badgeS',[[1,280,E.back]]) },100) }
+ blink(){ if(this.lock.open)return; this.anim('open',[[.06,70,E.inOut],[1,130,E.out]]) }
+ squash(){ this.anim('sy',[[.78,70,E.out],[1.1,130,E.out],[1,170,E.inOut]]); this.anim('sx',[[1.16,70,E.out],[.95,130,E.out],[1,170,E.inOut]]) }
+ roll(d=900,turns=1){ this.s.roll=0; this.anim('roll',[[Math.PI*2*turns,d,E.inOut]],()=>{this.s.roll=0;this.tg.roll=0}) }
+ greet(){ this.anim('hands',[[1,280,E.back]]); this.waveUntil=NOW()+1500; this.emote('happy',1500,true); setTimeout(()=>this.anim('hands',[[0,240,E.inOut]]),1550) }
+ emote(n,d=1800,silent){ const em=EMOTES[n]; if(!em)return; this.eyeOv=em.eye; this.ovUntil=NOW()+d;
+ if(n==='love'){ this.anim('blush',[[1,300,E.out],[1,d-600,E.lin],[0,300,E.inOut]]); this.emit('heart',4); this.anim('oy',[[-.1,160,E.out],[0,300,E.back]]) }
+ if(n==='surprised'){ this.anim('oy',[[-.3,140,E.out],[0,380,E.back]]); this.anim('es',[[1.25,120,E.out],[1,500,E.inOut]]) }
+ if(n==='proud'){ this.emit('star',5); this.anim('tilt',[[-.14,220,E.out],[-.14,d-500,E.lin],[0,280,E.inOut]]) }
+ if(n==='wink'){ this.anim('tilt',[[.12,160,E.out],[.12,d-400,E.lin],[0,240,E.inOut]]) }
+ if(n==='yawn'){ this.anim('sy',[[1.12,500,E.inOut],[1,500,E.inOut]]); this.anim('sx',[[.94,500,E.inOut],[1,500,E.inOut]]); setTimeout(()=>{this.eyeOv='closed';this.emit('z',2)},700) }
+ if(n==='happy'){ this.anim('blush',[[.6,200,E.out],[0,600,E.inOut]]) }
+ if(!silent&&em.snd) Snd.play(em.snd);
+ }
+ emit(type,n){ for(let i=0;i<n;i++) this.parts.push({type,x:(Math.random()-.5)*.9+(type==='z'?.55:0),y:-.7-Math.random()*.2,vx:(Math.random()-.5)*.35+(type==='z'?.18:0),vy:-(.45+Math.random()*.35),age:-i*.14,life:1.3+Math.random()*.5,rot:Math.random()*6,sz:.15+Math.random()*.08}) }
+ update(){
+ const n=NOW(), dt=Math.min(.05,(n-this.last)/1000); this.last=n; const s=this.s, tg=this.tg, c=this.cfg, t=(n-this.t0)/1000;
+ for(const tw of [...this.tw]){ const k=tw.keys[tw.i]; const p=clamp((n-tw.t0)/k[1],0,1); s[tw.p]=tw.from+(k[0]-tw.from)*k[2](p);
+ if(p>=1){ tw.from=k[0]; tw.i++; tw.t0=n; if(tw.i>=tw.keys.length){ this.tw.splice(this.tw.indexOf(tw),1); delete this.lock[tw.p]; this.tg[tw.p]=tw.keys[tw.keys.length-1][0]; if(tw.after) tw.after() } } }
+ let ty=this.look.x*.62, tp=this.look.y*.5;
+ if(c.look){ ty=ty*.35+c.look[0]*.55; tp=tp*.3+c.look[1]*.5 }
+ if(c.scan){ ty=Math.sin(t*2.6)*.6; tp=-.06 }
+ if(this.state==='sleeping'){ ty=0; tp=-.14 }
+ if(this.state==='dizzy'){ ty=Math.sin(t*9)*.25 }
+ tg.yaw=ty; tg.pitch=tp; tg.tilt=c.tilt||0; tg.oy=c.bounce?-Math.abs(Math.sin(t*5.2))*.07:0;
+ tg.sy=c.breathe?1+Math.sin(t*1.8)*.035:1; tg.sx=c.breathe?1-Math.sin(t*1.8)*.02:1;
+ const kLook=1-Math.pow(.0025,dt), kGen=1-Math.pow(.0008,dt);
+ for(const k in tg){ if(this.lock[k])continue; s[k]+=(tg[k]-s[k])*((k==='yaw'||k==='pitch')?kLook:kGen) }
+ this.col=mix(this.col,this.colT,1-Math.pow(.002,dt));
+ if(n>this.nextBlink){ if(this.state!=='sleeping'&&this.state!=='dizzy'){ this.blink(); if(Math.random()<.22) setTimeout(()=>this.blink(),230) } this.nextBlink=n+2200+Math.random()*3200 }
+ if(this.eyeOv&&n>this.ovUntil) this.eyeOv=null;
+ if(!this.mini&&n-this.lastAmb>1300){ this.lastAmb=n; if(c.zz) this.emit('z',1); if(c.sweat&&Math.random()<.5) this.emit('sweat',1) }
+ for(const p of this.parts) p.age+=dt; this.parts=this.parts.filter(p=>p.age<p.life);
+ }
+ draw(){
+ const x=this.x, W=this.c.width, H=this.c.height, s=this.s, P=PISTES[app.piste];
+ x.clearRect(0,0,W,H);
+ const R=W*.3; let rx=R, ry=R; if(P.shape==='mochi'){rx=R*1.14; ry=R*.88}
+ const cx=W/2+s.ox*R, cy=H/2+s.oy*R+(P.shape==='mochi'?R*.06:0);
+ const col=this.col;
+ x.save(); x.translate(cx,cy); x.rotate(s.tilt); x.scale(s.sx,s.sy);
+ const path=new Path2D(), m=s.morph;
+ if(m<.01){ if(P.shape==='mochi'){ for(let i=0;i<=72;i++){const a=i/72*Math.PI*2,ca=Math.cos(a),sa=Math.sin(a); const px=rx*Math.sign(ca)*Math.pow(Math.abs(ca),2/2.7), py=ry*Math.sign(sa)*Math.pow(Math.abs(sa),2/2.7); i?path.lineTo(px,py):path.moveTo(px,py)} path.closePath() } else path.ellipse(0,0,rx,ry,0,0,Math.PI*2) }
+ else { const w=lerp(rx,R*1.02,m), h=lerp(ry,R*.94,m), r=lerp(Math.min(rx,ry),R*.34,m); path.roundRect(-w,-h,2*w,2*h,r) }
+ // body
+ const bc=this.bodyColor;
+ if(P.shape==='orb'&&!bc){
+ const k=Math.max(s.tint,.25); const inner=mix([255,255,255],col,.12*k), outer=mix([214,222,232],col,.9*k);
+ const g=x.createRadialGradient(-rx*.3,-ry*.38,R*.05,0,0,R*1.05); g.addColorStop(0,rgba(inner,1)); g.addColorStop(.55,rgba(mix(inner,outer,.55),1)); g.addColorStop(1,rgba(outer,1));
+ x.save(); if(!this.mini){x.shadowColor=rgba(col,.45*k+.1); x.shadowBlur=R*.55} x.fillStyle=g; x.fill(path); x.restore();
+ } else {
+ let c0,c1; if(bc){ c0=mix(bc,[255,255,255],.35); c1=mix(bc,[0,0,0],.18) } else { c0=hexRgb(P.base[0]); c1=hexRgb(P.base[1]) }
+ const g=x.createLinearGradient(rx*.7,-ry*.85,-rx*.8,ry*.9); g.addColorStop(0,rgba(c0,1)); g.addColorStop(1,rgba(c1,1)); x.fillStyle=g; x.fill(path);
+ if(!bc&&s.tint>.01){ const tg2=x.createLinearGradient(0,ry,0,-ry*.25); tg2.addColorStop(0,rgba(col,.92*s.tint)); tg2.addColorStop(1,rgba(col,0)); x.fillStyle=tg2; x.fill(path) }
+ const sh=x.createRadialGradient(rx*.25,-ry*.32,R*.15,0,0,R*1.25); sh.addColorStop(0,'rgba(255,255,255,0)'); sh.addColorStop(.6,'rgba(0,0,0,0)'); sh.addColorStop(1,'rgba(0,0,0,.2)'); x.fillStyle=sh; x.fill(path);
+ const hl=x.createRadialGradient(rx*.34,-ry*.46,0,rx*.34,-ry*.46,R*.42); hl.addColorStop(0,'rgba(255,255,255,.55)'); hl.addColorStop(1,'rgba(255,255,255,0)'); x.fillStyle=hl; x.fill(path);
+ }
+ // blush
+ const bl=Math.max(s.blush,P.shape==='mochi'?.35:0)*(1-m);
+ if(bl>.01){ x.save(); x.clip(path); const yo=Math.sin(s.yaw)*rx*.8; x.fillStyle=`rgba(255,120,150,${.5*bl})`; for(const sd of[-1,1]){ x.beginPath(); x.ellipse(sd*rx*.55+yo,ry*.2,R*.17,R*.1,0,0,Math.PI*2); x.fill() } x.restore() }
+ // eyes
+ x.save(); x.clip(path); x.fillStyle=P.ink; x.strokeStyle=P.ink;
+ const shape=this.eyeOv||this.cfg.eye;
+ for(const sd of[-1,1]){
+ const yaw=sd*P.eye.sp+s.yaw; let pitch=P.eye.p+s.pitch+s.roll; pitch=((pitch+Math.PI)%(2*Math.PI)+2*Math.PI)%(2*Math.PI)-Math.PI;
+ const cp=Math.cos(pitch); if(Math.cos(yaw)*cp<.04) continue;
+ let px=Math.sin(yaw)*cp*rx, py=-Math.sin(pitch)*ry; if(m>0) py+=ry*.14*m;
+ const fx=lerp(Math.max(.18,Math.cos(yaw)),1,m*.7), fy=lerp(Math.max(.18,cp),1,m*.7);
+ x.save(); x.translate(px,py); x.scale(fx,fy); this.eye(shape,R*P.eye.w*s.es,R*P.eye.h*s.es,s.open,sd,P); x.restore();
+ }
+ x.restore();
+ if(m>.02){ const sw=R*1.5*m, sh=R*.22*m; x.fillStyle=P.ink; rr(x,-sw/2,-R*.94*1+R*.14,sw,sh,sh/2); x.fill() }
+ x.restore();
+ // hands
+ if(s.hands>.01){ const hr=R*.2*s.hands, c0=bc?mix(bc,[255,255,255],.35):hexRgb(P.base[0]), c1=bc?bc:hexRgb(P.base[1]); const tt=NOW()/1000;
+ for(const sd of[-1,1]){ let hx=cx+sd*rx*1.25*s.sx, hy=cy+ry*.42; if(sd===1&&NOW()<this.waveUntil){ hy-=R*.38+Math.sin(tt*13)*R*.16; hx+=Math.cos(tt*13)*R*.06 }
+ const g=x.createLinearGradient(hx+hr,hy-hr,hx-hr,hy+hr); g.addColorStop(0,rgba(c0,1)); g.addColorStop(1,rgba(c1,1)); x.fillStyle=g; x.beginPath(); x.arc(hx,hy,hr,0,Math.PI*2); x.fill() } }
+ // badge
+ if(this.badge&&s.badgeS>.01){ const bs=s.badgeS*(this.mini?1.25:1); const bx=cx-rx*.76*s.sx, by=cy-ry*.72*s.sy; x.save(); x.translate(bx,by); x.scale(bs,bs);
+ const bcol=this.badgeCol;
+ if(this.badge==='dots'&&!this.mini){ const w=R*.74,h=R*.42; x.fillStyle='#000'; rr(x,-w/2-R*.07,-h/2-R*.07,w+R*.14,h+R*.14,(h+R*.14)/2); x.fill(); x.fillStyle=bcol; rr(x,-w/2,-h/2,w,h,h/2); x.fill();
+ const tt=NOW()/1000; for(let i=0;i<3;i++){ const ph=((tt*2.4-i*.22)%1+1)%1; const r=R*.06*(1+.4*Math.max(0,Math.sin(ph*Math.PI*2))); x.fillStyle='rgba(255,255,255,.95)'; x.beginPath(); x.arc((i-1)*R*.19,0,r,0,Math.PI*2); x.fill() } }
+ else if(this.badge==='bang'||this.badge==='q'){ x.fillStyle='#000'; x.beginPath(); x.arc(0,0,R*.3,0,Math.PI*2); x.fill(); x.fillStyle=bcol; x.beginPath(); x.arc(0,0,R*.23,0,Math.PI*2); x.fill();
+ if(!this.mini){ x.fillStyle='#fff'; x.font=`800 ${R*.32}px -apple-system,system-ui,sans-serif`; x.textAlign='center'; x.textBaseline='middle'; x.fillText(this.badge==='bang'?'!':'?',0,R*.02) } }
+ else { x.fillStyle='#000'; x.beginPath(); x.arc(0,0,R*.2,0,Math.PI*2); x.fill(); x.fillStyle=bcol; x.beginPath(); x.arc(0,0,R*.135,0,Math.PI*2); x.fill() }
+ x.restore() }
+ // particules
+ for(const p of this.parts){ if(p.age<0)continue; const k=p.age/p.life, a=k<.2?k/.2:1-(k-.2)/.8; const px=cx+(p.x+p.vx*p.age)*R*1.3, py=cy+(p.y+p.vy*p.age)*R*1.3; const sz=R*p.sz*(1+k*.4);
+ x.save(); x.translate(px,py); x.globalAlpha=clamp(a,0,1);
+ if(p.type==='heart'){ x.fillStyle='#FF4D6D'; x.rotate(Math.sin(p.age*6)*.3); heart(x,sz); x.fill() }
+ else if(p.type==='star'){ x.fillStyle='#F7B32B'; x.rotate(p.rot+p.age*2); star(x,sz,sz*.45); x.fill() }
+ else if(p.type==='spark'){ x.fillStyle='#fff'; x.rotate(p.rot); star(x,sz*.8,sz*.18); x.fill() }
+ else if(p.type==='sweat'){ x.fillStyle='#7CC7FF'; x.beginPath(); x.moveTo(0,-sz); x.quadraticCurveTo(sz*.8,sz*.2,0,sz*.6); x.quadraticCurveTo(-sz*.8,sz*.2,0,-sz); x.fill() }
+ else if(p.type==='z'){ x.fillStyle='rgba(210,220,235,1)'; x.font=`700 ${sz*1.9}px -apple-system,system-ui,sans-serif`; x.fillText('z',0,0) }
+ x.restore() }
+ }
+ eye(shape,w,h,open,sd,P){ const x=this.x, t=NOW()/1000;
+ switch(shape){
+ case 'wide': w*=1.16; h*=1.12; /* fallthrough */
+ case 'pill': { const hh=Math.max(h*open,w*.3); rr(x,-w/2,-hh/2,w,hh,Math.min(w/2,hh/2)); x.fill(); break }
+ case 'dot': x.beginPath(); x.arc(0,0,w*.45,0,Math.PI*2); x.fill(); break;
+ case 'line': x.rotate(-sd*.2); rr(x,-w*.78,-w*.21,w*1.56,w*.42,w*.21); x.fill(); break;
+ case 'flat': rr(x,-w*.72,-w*.2,w*1.44,w*.4,w*.2); x.fill(); break;
+ case 'happy': x.lineWidth=w*.5; x.lineCap='round'; x.beginPath(); x.arc(0,h*.18,w*.82,Math.PI*1.12,Math.PI*1.88); x.stroke(); break;
+ case 'closed': x.lineWidth=w*.36; x.lineCap='round'; x.beginPath(); x.arc(0,-h*.08,w*.78,Math.PI*.15,Math.PI*.85); x.stroke(); break;
+ case 'spiral': { x.lineWidth=w*.22; x.lineCap='round'; x.beginPath(); for(let a=0;a<4.4*Math.PI;a+=.2){ const r=w*.06+a*w*.058, aa=a+t*9*sd; const px=Math.cos(aa)*r, py=Math.sin(aa)*r; a?x.lineTo(px,py):x.moveTo(px,py) } x.stroke(); break }
+ case 'heart': x.fillStyle='#FF4D6D'; heart(x,w*1.2); x.fill(); x.fillStyle=P.ink; break;
+ case 'star': x.fillStyle='#F7B32B'; x.rotate(t*1.5*sd); star(x,w*1.05,w*.46); x.fill(); x.fillStyle=P.ink; break;
+ case 'tired': rr(x,-w/2,-h*.02,w,h*.38,w/2); x.fill(); rr(x,-w*.62,-h*.1,w*1.24,w*.22,w*.11); x.fill(); break;
+ case 'wink': if(sd<0){ rr(x,-w/2,-h/2,w,h,w/2); x.fill() } else { x.lineWidth=w*.5; x.lineCap='round'; x.beginPath(); x.arc(0,h*.18,w*.82,Math.PI*1.12,Math.PI*1.88); x.stroke() } break;
+ default: rr(x,-w/2,-h/2,w,h,w/2); x.fill();
+ }
+ }
+}
+
+/* ---------------- DONNÉES ---------------- */
+const AGENTS={
+ korus:{name:'Korus',tool:'Claude Code',color:'#FF6B5B',short:'Korus',steps:['Lecture du schéma Prisma','Migration de la table factures','Mise à jour des tests','Lancement de la suite de tests','Relecture du diff']},
+ sbe:{name:'SBE Hub',tool:'Claude Code',color:'#2DD4A7',short:'SBE Hub',steps:['Analyse des requêtes lentes','Index sur les cours','Écriture des tests']},
+ brief:{name:'Morning AI Brief',tool:'n8n',color:'#F7B32B',short:'Morning Brief',steps:['Collecte des sources','Résumé par Claude','Envoi Gmail']},
+ ig:{name:'Publication IG',tool:'n8n',color:'#A78BFA',short:'Publication IG',steps:['Rendu du carousel','Planification']},
+ folio:{name:'louisraille.fr',tool:'Claude Code',color:'#38BDF8',short:'Portfolio',steps:['Refonte du scroll','Optimisation des images']}
+};
+const app={piste:'mochi',mode:'hidden',view:'overview',tasks:[],focus:null,present:true,lastMove:NOW(),lastAct:NOW(),hover:false,autoClose:60000,demo:false,pinned:false,pinUntil:0,
+ override:null,pointer:{x:548,y:420},drag:null,ctx:null,upP:0,slaps:[],file:'brief-client.pdf'};
+
+const screen=$('#screen'), island=$('#island'), botwrap=$('#botwrap'), safari=$('#safari');
+const main=new Bot($('#botc')); const floatB=new Bot($('#floatc'));
+const agentEls={}, minis={};
+for(const id in AGENTS){ const a=AGENTS[id], el=document.createElement('div'); el.className='agent'; el.dataset.id=id;
+ const c=hexRgb(a.color); el.style.setProperty('--bg',rgba(c,.13)); el.style.setProperty('--bd',rgba(c,.32));
+ el.innerHTML=`<canvas></canvas><span class="lbl" style="color:${rgba(mix(c,[255,255,255],.25),1)}">${a.short}</span>`;
+ island.appendChild(el); agentEls[id]=el; minis[id]=new Bot(el.querySelector('canvas'),{mini:true,bodyColor:a.color});
+ el.addEventListener('click',e=>{ if(app.demo)return; e.stopPropagation(); focusTask(id) }) }
+
+/* ---------------- LAYOUT ---------------- */
+const NW=184, NH=32, EW=640;
+const VIEWS={
+ overview:{h:196,bot:[64,null,70],ag:'pills'}, empty:{h:150,bot:[70,null,62],ag:'none'},
+ approval:{h:206,bot:[62,null,56],ag:'column'}, question:{h:196,bot:[62,null,56],ag:'column'},
+ error:{h:190,bot:[62,null,58],ag:'column'}, finished:{h:170,bot:[62,null,58],ag:'column'},
+ confused:{h:160,bot:[76,null,66],ag:'column'}, upload:{h:176,bot:[140,null,62],ag:'column'},
+ uploading:{h:150,bot:[0,0,28],ag:'column'}, choose:{h:170,bot:[60,null,52],ag:'column'},
+ mail:{h:210,bot:[56,null,46],ag:'column'}, prompt:{h:156,bot:[52,null,44],ag:'column'},
+ searching:{h:156,bot:[52,null,44],ag:'column'}, result:{h:262,bot:[52,86,44],ag:'column'}, note:{h:136,bot:[60,null,50],ag:'column'}
+};
+function others(){ return app.tasks.filter(t=>t.id!==app.focus) }
+function applyLayout(){
+ let w,h,b,ag;
+ if(app.mode==='hidden'){ w=NW;h=NH;b={cx:46,cy:16,d:6,o:0};ag='none' }
+ else if(app.mode==='peek'){ w=NW+64;h=NH;b={cx:19,cy:16,d:18,o:1};ag='none' }
+ else if(app.mode==='compact'){ w=NW+104;h=NH;b={cx:27,cy:16,d:20,o:1};ag='grid' }
+ else { const V=VIEWS[app.view]; w=EW;h=V.h; let [bx,by,bd]=V.bot; if(app.view==='uploading'){ bx=46+app.upP*(EW-10-42-78-46); by=36+77; } if(by==null) by=36+(h-46)/2; b={cx:bx,cy:by,d:bd,o:1}; ag=V.ag }
+ island.style.width=w+'px'; island.style.height=h+'px'; island.dataset.mode=app.mode; island.dataset.view=app.view;
+ const cs=b.d/.6; Object.assign(botwrap.style,{left:(b.cx-cs/2)+'px',top:(b.cy-cs/2)+'px',width:cs+'px',height:cs+'px',opacity:app.drag&&app.drag.type==='bot'?0:b.o});
+ layoutAgents(ag,w,h);
+ $$('.view').forEach(v=>v.classList.toggle('on',app.mode==='expanded'&&v.dataset.view===app.view));
+ $$('.tab').forEach(t=>t.classList.toggle('on',t.dataset.go===app.view||(t.dataset.go==='overview'&&(app.view==='overview'||app.view==='empty'))));
+ const n=app.tasks.length; $('#hdrCount').textContent=n?`${n} en cours`:'';
+}
+function layoutAgents(mode,w,h){
+ const list=mode==='grid'?app.tasks.filter(t=>t.id!==app.focus):others();
+ for(const id in agentEls){ const el=agentEls[id], cv=el.querySelector('canvas'); const i=list.findIndex(t=>t.id===id);
+ if(i<0||i>3||mode==='none'){ el.style.opacity=0; el.style.pointerEvents='none'; el.classList.remove('pill'); continue }
+ el.style.opacity=1; el.style.pointerEvents='auto'; el.style.setProperty('--d',(i*.035)+'s');
+ let L,T,W,H,cs,cl,ct,pill=false; const n=Math.min(list.length,4);
+ if(mode==='grid'){ const d=9.5, sp=6; const pos=n===1?[[0,0]]:n===2?[[-sp,0],[sp,0]]:n===3?[[-sp,-sp],[sp,-sp],[0,sp]]:[[-sp,-sp],[sp,-sp],[-sp,sp],[sp,sp]];
+ const cx=w-27+pos[i][0], cy=16+pos[i][1]; W=H=d; L=cx-d/2; T=cy-d/2; cs=d/.6; cl=(W-cs)/2; ct=(H-cs)/2 }
+ else if(mode==='column'){ const d=16; const cx=w-10-21, cy=36+14+i*24; W=H=d; L=cx-d/2; T=cy-d/2; cs=d/.6; cl=(W-cs)/2; ct=(H-cs)/2 }
+ else { pill=true; W=132; H=34; const col=i%2,row=Math.floor(i/2), rows=Math.ceil(n/2); const cardX=10+332, cardY=36, cardH=h-46;
+ L=cardX+8+col*(W+8); T=cardY+(cardH-(rows*H+(rows-1)*8))/2+row*(H+8); cs=24/.6; cl=17-cs/2; ct=17-cs/2 }
+ Object.assign(el.style,{left:L+'px',top:T+'px',width:W+'px',height:H+'px'}); Object.assign(cv.style,{left:cl+'px',top:ct+'px',width:cs+'px',height:cs+'px'});
+ el.classList.toggle('pill',pill) }
+}
+function setMode(m,view){ const order={hidden:0,peek:1,compact:2,expanded:3}; const shrinking=order[m]<order[app.mode];
+ island.classList.toggle('closing',shrinking); const was=app.mode; app.mode=m; if(view) app.view=view; applyLayout();
+ if(m==='expanded'&&was!=='expanded'){ Snd.play('open'); main.blink() }
+ if(was==='expanded'&&m!=='expanded'){ Snd.play('close'); app.pinned=false; if(app.ctx&&app.ctx.type==='window'&&!['prompt','searching','result'].includes(app.view)) detach() } }
+function baseMode(){ if(!app.present) return 'hidden'; return app.tasks.length?'compact':'hidden' }
+function expand(view){ app.lastAct=NOW(); if(app.mode==='expanded'){ app.view=view; island.classList.remove('closing'); applyLayout() } else setMode('expanded',view) }
+function collapse(){ app.pinned=false; app.pinUntil=0; if(app.ctx&&app.ctx.type==='window') detach(); app.ctx=null; resetMorph(); setMode(baseMode()) }
+function defaultView(){ return app.tasks.length?'overview':'empty' }
+
+/* ---------------- TÂCHES ---------------- */
+function task(id){ return app.tasks.find(t=>t.id===id) }
+function addTask(id,state='working'){ if(task(id))return; app.tasks.push({id,state,step:0}); minis[id].setState(state,true); if(!app.focus) app.focus=id; sync() }
+function setTask(id,state){ const t=task(id); if(!t)return; t.state=state; minis[id].setState(state); sync() }
+function removeTask(id){ app.tasks=app.tasks.filter(t=>t.id!==id); if(app.focus===id) app.focus=app.tasks[0]?app.tasks[0].id:null; sync(); if(app.mode!=='expanded') setMode(baseMode()) }
+function focusTask(id){ app.focus=id; sync(); expand('overview'); Snd.play('blip') }
+function sync(){
+ const f=task(app.focus); const st=app.override||(f?f.state:'idle'); main.setState(st);
+ const a=f?AGENTS[f.id]:null;
+ $$('[data-f=name]').forEach(e=>e.textContent=a?a.name:''); $$('[data-f=tool]').forEach(e=>e.textContent=a?a.tool:''); $$('[data-f=dot]').forEach(e=>e.style.setProperty('--c',a?a.color:'#fff'));
+ $$('[data-f=file]').forEach(e=>e.textContent=app.file);
+ const g=botwrap.querySelector('.glow'); const S=STATES[st]; g.style.setProperty('--g',S.glow); g.style.setProperty('--go',S.go);
+ if(f) setTicker(f,false);
+ if(app.mode==='expanded'){ if(app.view==='empty'&&app.tasks.length) app.view='overview'; else if(app.view==='overview'&&!app.tasks.length) app.view='empty' }
+ applyLayout();
+}
+const tkEl=$('#tk');
+function setTicker(t,animate){ const st=AGENTS[t.id].steps, L=st.length; const lines=tkEl.querySelectorAll('.ln span');
+ const txt=i=>st[((i%L)+L)%L];
+ const fill=()=>{ lines[0].textContent=txt(t.step-1); lines[1].textContent=txt(t.step); lines[2].textContent=txt(t.step+1); lines[3].textContent=txt(t.step+2) };
+ if(!animate){ fill(); return }
+ tkEl.classList.add('roll'); setTimeout(()=>{ t.step++; tkEl.classList.remove('roll'); fill() },460) }
+setInterval(()=>{ const f=task(app.focus); if(f&&f.state==='working'&&app.mode==='expanded'&&app.view==='overview') setTicker(f,true);
+ for(const t of app.tasks) if(t.id!==app.focus&&t.state==='working'&&Math.random()<.3) t.step++ },2800);
+
+/* ---------------- ALERTES ---------------- */
+function alertView(view,id,state){ addTask(id,'working'); app.focus=id; setTask(id,state); app.present=true; expand(view); app.pinned=['approval','question','error'].includes(view);
+ app.pinUntil=view==='finished'?NOW()+5200:0; Snd.play(STATES[state]&&STATES[state].snd||'blip') }
+function afterDecision(id,state,emote){ setTask(id,state); if(emote) main.emote(emote,900,true); app.pinned=false; setTimeout(()=>{ if(!app.demoHold) collapse() },650) }
+
+/* ---------------- INTERACTIONS ---------------- */
+let hoverT=null;
+function hoverIn(){ app.hover=true; app.lastAct=NOW(); clearTimeout(hoverT);
+ if(app.mode==='hidden'){ setMode('peek'); Snd.play('peek'); setTimeout(()=>main.greet(),120); Snd.play('greet'); hoverT=setTimeout(()=>{ if(app.hover&&app.mode==='peek') expand(defaultView()) },650) }
+ else if(app.mode==='compact'||app.mode==='peek'){ hoverT=setTimeout(()=>{ if(app.hover&&app.mode!=='expanded') expand(defaultView()) },200) } }
+function hoverOut(){ app.hover=false; clearTimeout(hoverT); if(app.mode==='peek') hoverT=setTimeout(()=>{ if(!app.hover&&app.mode==='peek') setMode(baseMode()) },600) }
+island.addEventListener('pointerenter',()=>{ if(!app.demo&&!app.drag) hoverIn() });
+island.addEventListener('pointerleave',()=>{ if(!app.demo) hoverOut() });
+island.addEventListener('pointermove',()=>{ app.lastAct=NOW() });
+
+let botHoverT=null, botHovering=false;
+function botHover(on){ botHovering=on; clearTimeout(botHoverT);
+ if(on){ if(app.mode!=='expanded')return; main.blink(); main.tg.es=1.08; Snd.play('hover'); botHoverT=setTimeout(()=>{ if(botHovering&&!app.override) main.emote('love',2000) },1900) }
+ else main.tg.es=1 }
+botwrap.addEventListener('pointerenter',()=>{ if(!app.demo) botHover(true) });
+botwrap.addEventListener('pointerleave',()=>{ if(!app.demo) botHover(false) });
+
+function botClick(){ if(app.mode!=='expanded'){ expand(defaultView()); return } slap() }
+function slap(){ const n=NOW(); app.slaps=app.slaps.filter(t=>n-t<1700); app.slaps.push(n); Snd.play('slap'); main.squash(); clearTimeout(botHoverT);
+ if(app.slaps.length>=3){ app.slaps=[]; dizzy() } else { main.emote('annoyed',800,true); Snd.play('annoyed'); const g=botwrap.querySelector('.glow'); g.style.setProperty('--g','#A855F7'); g.style.setProperty('--go',.7); setTimeout(()=>{ if(!app.override) sync() },900) } }
+function dizzy(){ app.override='dizzy'; const prev=app.view; sync(); Snd.play('dizzy'); if(app.mode==='expanded'){ app.view='confused'; applyLayout() }
+ setTimeout(()=>{ app.override=null; sync(); main.blink(); if(app.mode==='expanded'&&app.view==='confused'){ app.view=prev==='confused'?defaultView():prev; applyLayout() } },3300) }
+
+/* drag : bonhomme et fichiers */
+function toScreen(cx,cy){ const r=screen.getBoundingClientRect(), k=r.width/1096; return {x:(cx-r.left)/k,y:(cy-r.top)/k} }
+function rectS(el){ const r=el.getBoundingClientRect(), a=toScreen(r.left,r.top), b=toScreen(r.right,r.bottom); return {l:a.x,t:a.y,r:b.x,b:b.y,cx:(a.x+b.x)/2,cy:(a.y+b.y)/2} }
+function inR(p,R,m=0){ return p.x>R.l-m&&p.x<R.r+m&&p.y>R.t-m&&p.y<R.b+m }
+let press=null;
+botwrap.addEventListener('pointerdown',e=>{ if(app.demo)return; e.preventDefault(); e.stopPropagation(); press={type:'bot',p:toScreen(e.clientX,e.clientY)} });
+$$('.file').forEach(f=>f.addEventListener('pointerdown',e=>{ if(app.demo)return; e.preventDefault(); press={type:'file',el:f,p:toScreen(e.clientX,e.clientY)} }));
+window.addEventListener('pointermove',e=>{ if(app.demo)return; const p=toScreen(e.clientX,e.clientY);
+ if(press&&!app.drag&&Math.hypot(p.x-press.p.x,p.y-press.p.y)>7){ if(press.type==='bot') beginBotDrag(); else beginFileDrag(press.el) }
+ if(app.drag) dragMove(p) });
+window.addEventListener('pointerup',e=>{ if(app.demo)return; const p=toScreen(e.clientX,e.clientY);
+ if(app.drag) dragEnd(p); else if(press&&press.type==='bot') botClick(); press=null });
+screen.addEventListener('pointermove',e=>{ if(app.demo)return; app.pointer=toScreen(e.clientX,e.clientY); app.lastMove=NOW();
+ if(!app.present){ app.present=true; if(app.mode==='hidden'&&app.tasks.length) setMode('compact') } });
+
+function beginBotDrag(){ if(app.mode==='hidden')return; app.drag={type:'bot'}; const fb=$('#floatbot'); fb.style.display='block'; floatB.setState(main.state,true); floatB.emote('surprised',700,true); Snd.play('pop'); botHover(false); applyLayout() }
+function beginFileDrag(el){ app.drag={type:'file',el,name:el.dataset.name}; el.classList.add('dragging'); const g=$('#fileghost'); g.style.display='block'; g.style.transform=''; g.style.opacity=1; Snd.play('blip') }
+function islandZone(){ const r=rectS(island); return {l:Math.min(r.l,548-220),r:Math.max(r.r,548+220),t:0,b:Math.max(r.b,60)+26} }
+function dragMove(p){ app.pointer=p;
+ if(app.drag.type==='bot'){ const fb=$('#floatbot'); fb.style.left=p.x+'px'; fb.style.top=p.y+'px'; safari.classList.toggle('target',inR(p,rectS(safari))) }
+ else { const g=$('#fileghost'); g.style.left=p.x+'px'; g.style.top=p.y+'px'; const over=inR(p,islandZone());
+ if(over&&!(app.mode==='expanded'&&app.view==='upload')){ app.hover=true; expand('upload'); main.anim('morph',[[1,380,E.back]]); Snd.play('hover') }
+ $('#drop').classList.toggle('over',over&&app.view==='upload');
+ if(!over&&app.mode==='expanded'&&app.view==='upload'&&p.y>260){ app.hover=false; resetMorph(); collapse() } } }
+function dragEnd(p){ const d=app.drag; app.drag=null;
+ if(d.type==='bot'){ const fb=$('#floatbot'); safari.classList.remove('target');
+ if(inR(p,rectS(safari))){ attach(); }
+ const home=rectS(botwrap); fb.animate([{left:p.x+'px',top:p.y+'px',transform:'scale(1)'},{left:home.cx+'px',top:home.cy+'px',transform:'scale(.25)'}],{duration:420,easing:'cubic-bezier(.4,0,.2,1)'}).onfinish=()=>{ fb.style.display='none'; applyLayout() };
+ setTimeout(applyLayout,380) }
+ else { const g=$('#fileghost'); d.el.classList.remove('dragging');
+ if(inR(p,islandZone())&&app.view==='upload'){ app.file=d.name; sync(); dropFile(p) }
+ else { const home=rectS(d.el); g.animate([{left:p.x+'px',top:p.y+'px'},{left:(home.l+24)+'px',top:home.cy+'px'}],{duration:320,easing:'ease-out'}).onfinish=()=>g.style.display='none'; if(app.view==='upload') collapse() } } }
+function resetMorph(){ if(main.s.morph>.01||main.lock.morph) main.anim('morph',[[0,320,E.back]]) }
+function dropFile(p){ const g=$('#fileghost'), b=rectS(botwrap); $('#drop').classList.remove('over');
+ g.animate([{left:p.x+'px',top:p.y+'px',transform:'scale(1)',opacity:1},{left:b.cx+'px',top:(b.t+8)+'px',transform:'scale(.2)',opacity:.2}],{duration:360,easing:'cubic-bezier(.5,0,.8,.4)'}).onfinish=()=>{ g.style.display='none' };
+ setTimeout(()=>{ Snd.play('gulp'); main.squash(); main.emote('happy',700,true) },330);
+ setTimeout(()=>{ main.anim('morph',[[0,340,E.back]]); app.upP=0; expand('uploading'); runUpload() },950) }
+function runUpload(){ const t0=NOW(), D=2100; let lastTick=0;
+ const step=()=>{ const k=clamp((NOW()-t0)/D,0,1); app.upP=E.inOut(k); $('#upBar').style.width=(app.upP*100)+'%'; $('#upPct').textContent=Math.round(app.upP*100)+' %';
+ if(Math.floor(k*10)>lastTick){ lastTick=Math.floor(k*10); Snd.play('tick') } applyLayout();
+ if(k<1) requestAnimationFrame(step); else { Snd.play('approve'); main.emote('happy',900,true); expand('choose'); app.pinned=true } }; step() }
+
+function attach(){ safari.classList.add('attached'); app.ctx={type:'window',label:'Safari, escale.fr'}; Snd.play('attach'); renderChips(); expand('prompt'); app.pinned=true; main.emote('wink',700,true); if(!app.demo) setTimeout(()=>$('#promptIn').focus(),350) }
+function detach(){ safari.classList.remove('attached') }
+function renderChips(){ const html=app.ctx?`<span class="chip ctx"><i></i>${app.ctx.label}</span>`:''; $('#ctxChips').innerHTML=html; $$('[data-f=chips]').forEach(e=>e.innerHTML=html) }
+function submitPrompt(){ const v=$('#promptIn').value.trim(); if(!v)return; $('#promptIn').value=''; Snd.play('send'); app.override='searching'; sync(); app.pinned=true;
+ $$('[data-f=status]').forEach(e=>e.textContent=app.ctx&&app.ctx.type==='window'?'Claude lit la page et cherche sur le web…':app.ctx&&app.ctx.type==='file'?`Claude lit ${app.file}…`:'Claude cherche sur le web…');
+ expand('searching');
+ setTimeout(()=>{ app.override=null; renderResult(); expand('result'); main.setState('finished',true); Snd.play('finish'); setTimeout(()=>main.emote('proud',1600),900); detach(); app.pinned=false; app.lastAct=NOW(); setTimeout(()=>sync(),2600) },2800) }
+function renderResult(){ const box=$('#resBox'); const isFile=app.ctx&&app.ctx.type==='file';
+ box.innerHTML=isFile?`<div class="big">Ce que dit ${app.file}</div><div class="res"><div><b>Livrable</b><span>Landing page et 3 visuels</span></div><div><b>Deadline</b><span>vendredi 3 octobre</span></div><div><b>Budget</b><span>1 800 € HT</span></div></div><div class="fine">Aperçu fictif. Dans l'app, c'est l'API Claude qui lit le fichier.</div><div class="row"><button class="btn primary" data-act="copy">Copier</button><button class="btn" data-act="close">Fermer</button></div>`
+ :`<div class="big">3 apparts qui collent, sur escale.fr</div><div class="res"><div><b>Príncipe Real, calme</b><span>79 € la nuit</span></div><div><b>Alfama, vue sur le Tage</b><span>84 € la nuit</span></div><div><b>Graça, terrasse</b><span>88 € la nuit</span></div></div><div class="fine">Aperçu fictif. Dans l'app, c'est l'API Claude avec la recherche web.</div><div class="row"><button class="btn primary" data-act="open-first">Ouvrir le premier</button><button class="btn" data-act="close">Fermer</button></div>` }
+function note(a,b,ms=2000){ $$('[data-f=note]').forEach(e=>e.textContent=a); $$('[data-f=note2]').forEach(e=>e.textContent=b||''); expand('note'); app.pinned=true; setTimeout(()=>{ if(app.view==='note'&&!app.demoHold) collapse() },ms) }
+
+island.addEventListener('click',e=>{ const b=e.target.closest('[data-act],[data-go]'); if(!b)return; e.stopPropagation(); app.lastAct=NOW(); act(b.dataset.act||('go-'+b.dataset.go),b) });
+function act(a,b){
+ const f=task(app.focus);
+ switch(a){
+ case 'go-overview': expand(defaultView()); Snd.play('blip'); break;
+ case 'go-prompt': case 'ask': app.ctx=null; renderChips(); expand('prompt'); Snd.play('blip'); if(!app.demo) setTimeout(()=>$('#promptIn').focus(),300); break;
+ case 'go-upload': expand('upload'); main.anim('morph',[[1,380,E.back]]); Snd.play('blip'); break;
+ case 'allow': case 'always': Snd.play('approve'); afterDecision(app.focus,'working','happy'); break;
+ case 'deny': Snd.play('blip'); afterDecision(app.focus,'thinking'); break;
+ case 'answer': Snd.play('approve'); afterDecision(app.focus,'thinking','happy'); break;
+ case 'retry': Snd.play('work'); afterDecision(app.focus,'working','happy'); break;
+ case 'open-n8n': note("J'ouvre l'exécution dans n8n.",'Le workflow reste en erreur tant que tu ne le relances pas.'); break;
+ case 'jump': if(f) removeTask(f.id); note('Je te ramène au terminal de Korus.','Dans l\'app, ça met au premier plan le bon onglet.'); break;
+ case 'ok': if(f) removeTask(f.id); collapse(); break;
+ case 'file-ask': app.ctx={type:'file',label:app.file}; renderChips(); expand('prompt'); if(!app.demo) setTimeout(()=>$('#promptIn').focus(),300); break;
+ case 'mail': expand('mail'); if(!app.demo) setTimeout(()=>$('#mailTo').focus(),300); break;
+ case 'send-mail': { const to=$('#mailTo').value.trim()||'[email protected]'; Snd.play('send'); main.emote('wink',900); note(`Mail envoyé à ${to}.`,`${app.file} est parti en pièce jointe.`,2200); break }
+ case 'send': submitPrompt(); break;
+ case 'open-first': Snd.play('blip'); collapse(); break;
+ case 'copy': Snd.play('blip'); note('Copié.','',1200); break;
+ case 'close': collapse(); break;
+ }
+ if(b){ b.classList.add('pressed'); setTimeout(()=>b.classList.remove('pressed'),160) }
+}
+$('#promptIn').addEventListener('keydown',e=>{ if(e.key==='Enter'){ e.preventDefault(); submitPrompt() } });
+window.addEventListener('keydown',e=>{ if(app.demo||e.target.tagName==='INPUT')return;
+ if(app.view==='approval'&&app.mode==='expanded'){ if(e.key==='y'||e.key==='Y') act('allow',$('[data-act=allow]')); if(e.key==='n'||e.key==='N') act('deny',$('[data-act=deny]')) }
+ if(e.key==='Escape'&&app.mode==='expanded') collapse() });
+$('#hdrSnd').addEventListener('click',e=>{ e.stopPropagation(); setSound(!Snd.on) });
+
+/* ---------------- BOUCLE ---------------- */
+function lookAt(bot,el){ const r=rectS(el); const dx=app.pointer.x-r.cx, dy=app.pointer.y-r.cy; bot.look.x=Math.tanh(dx/260); bot.look.y=-Math.tanh(dy/200) }
+function frame(){
+ const n=NOW();
+ if(app.mode!=='hidden'||main.s.hands>.01){ lookAt(main,botwrap); main.update(); main.draw() }
+ for(const id in minis){ if(agentEls[id].style.opacity==='0')continue; lookAt(minis[id],agentEls[id]); minis[id].update(); minis[id].draw() }
+ if(app.drag&&app.drag.type==='bot'){ const fb=$('#floatbot'); floatB.look.x=0; floatB.look.y=-.3; floatB.update(); floatB.draw() }
+ if(!app.demo){
+ if(app.mode==='expanded'&&!app.pinned&&!app.drag&&n-app.lastAct>app.autoClose) collapse();
+ if(app.pinUntil&&n>app.pinUntil&&app.mode==='expanded'&&app.view==='finished'){ const f=task(app.focus); app.pinUntil=0; if(f&&f.state==='finished') removeTask(f.id); collapse() }
+ if(app.present&&n-app.lastMove>25000&&app.mode!=='expanded'){ app.present=false; setMode('hidden') }
+ }
+ const cd=$('#cd'); if(app.mode==='expanded'&&!app.pinned&&!app.demo){ const win=Math.min(10000,app.autoClose*.6), rem=app.autoClose-(n-app.lastAct); cd.style.width=rem<win?Math.max(0,rem/win*160)+'px':'0px' } else cd.style.width='0px';
+ requestAnimationFrame(frame);
+}
+
+/* ---------------- CONTRÔLES ---------------- */
+function setSound(on){ Snd.on=on; if(on){ Snd.init(); if(Snd.ctx&&Snd.ctx.state==='suspended') Snd.ctx.resume() } $('#sndOn').checked=on; $('#hdrSnd .w').style.opacity=on?1:.2 }
+$('#sndOn').addEventListener('change',e=>setSound(e.target.checked));
+$('#sndVol').addEventListener('input',e=>Snd.setVol(+e.target.value));
+$$('#segClose button').forEach(b=>b.addEventListener('click',()=>{ $$('#segClose button').forEach(x=>x.classList.toggle('on',x===b)); app.autoClose=+b.dataset.ms; app.lastAct=NOW() }));
+function setPiste(p){ app.piste=p; $$('#segPiste button').forEach(b=>b.classList.toggle('on',b.dataset.p===p)); $('#pisteDesc').textContent=PISTES[p].desc }
+$$('#segPiste button').forEach(b=>b.addEventListener('click',()=>{ setPiste(b.dataset.p); if(app.mode==='hidden') expand(defaultView()); main.blink(); Snd.play('blip') }));
+function ensureVisible(){ app.present=true; if(app.mode==='hidden'||app.mode==='peek') expand(defaultView()); app.lastAct=NOW() }
+const stateBox=$('#stateBtns');
+const auto=document.createElement('button'); auto.className='cb on'; auto.innerHTML='<i style="--c:conic-gradient(#3B9EFF,#34D399,#F4505E,#3B9EFF)"></i>Automatique'; stateBox.appendChild(auto);
+auto.addEventListener('click',()=>{ app.override=null; $$('#stateBtns .cb').forEach(x=>x.classList.toggle('on',x===auto)); sync() });
+for(const k in STATES){ const S=STATES[k]; const b=document.createElement('button'); b.className='cb'; b.innerHTML=`<i style="--c:${S.col}"></i>${S.label}`; stateBox.appendChild(b);
+ b.addEventListener('click',()=>{ ensureVisible(); $$('#stateBtns .cb').forEach(x=>x.classList.toggle('on',x===b)); app.override=k; sync(); main.setState(k,true); Snd.play(S.snd||'blip') }) }
+for(const k of ['love','surprised','proud','wink','yawn']){ const em=EMOTES[k]; const b=document.createElement('button'); b.className='cb'; b.innerHTML=`<i style="--c:${em.c}"></i>${em.label}`; $('#emoteBtns').appendChild(b);
+ b.addEventListener('click',()=>{ ensureVisible(); main.emote(k,1900) }) }
+const SIMS=[
+ ['Lancer 3 tâches','#3B9EFF',()=>{ app.present=true; ['korus','sbe','brief'].forEach((id,i)=>setTimeout(()=>addTask(id,i===1?'thinking':'working'),i*260)); setTimeout(()=>{ if(app.mode==='hidden') setMode('compact'); Snd.play('work') },100) }],
+ ['Demande de permission','#F5A524',()=>alertView('approval','korus','approval')],
+ ['Question','#22D3EE',()=>alertView('question','sbe','question')],
+ ['Erreur n8n','#F4505E',()=>alertView('error','brief','error')],
+ ['Tâche terminée','#34D399',()=>alertView('finished','korus','finished')],
+ ['Limite atteinte','#FB923C',()=>{ addTask('folio','working'); app.focus='folio'; setTask('folio','ratelimit'); ensureVisible(); Snd.play('rate') }],
+ ['Utilisateur absent','#94A3B8',()=>{ app.present=false; collapse(); setMode('hidden') }],
+ ['Tout arrêter','#6B7280',()=>{ app.tasks=[]; app.focus=null; app.override=null; sync(); collapse(); setMode('hidden') }]
+];
+for(const [l,c,fn] of SIMS){ const b=document.createElement('button'); b.className='cb'; b.innerHTML=`<i style="--c:${c}"></i>${l}`; b.addEventListener('click',()=>{ if(!app.demo) fn() }); $('#simBtns').appendChild(b) }
+
+/* ---------------- DÉMO ---------------- */
+const ghost=$('#ghost');
+function ghostAt(p){ ghost.style.left=p.x+'px'; ghost.style.top=p.y+'px'; app.pointer={x:p.x,y:p.y}; if(app.drag) dragMove(app.pointer) }
+function move(x,y,d=700){ return new Promise(res=>{ const a={...app.pointer}, t0=NOW(); const st=()=>{ const k=clamp((NOW()-t0)/d,0,1), e=E.inOut(k); ghostAt({x:lerp(a.x,x,e),y:lerp(a.y,y,e)}); if(k<1) requestAnimationFrame(st); else res() }; st() }) }
+async function clickAt(){ ghost.classList.add('down'); await sleep(110); ghost.classList.remove('down') }
+async function clickEl(sel){ const el=typeof sel==='string'?$(sel):sel; if(!el)return; const r=rectS(el); await move(r.cx,r.cy,650); await sleep(120); await clickAt(); el.click(); }
+async function typeIn(el,text,ms=34){ el.value=''; for(const ch of text){ el.value+=ch; if(Math.random()<.5) Snd.play('tick'); await sleep(ms+Math.random()*25) } }
+async function runDemo(){
+ if(app.demo)return; app.demo=true; app.demoHold=true; const btn=$('#demoBtn'); btn.disabled=true; btn.querySelector('span').textContent='Démo en cours…';
+ $('#demoTag').style.display='block'; if(!Snd.on) setSound(true);
+ app.tasks=[]; app.focus=null; app.override=null; app.present=true; detach(); sync(); collapse(); setMode('hidden'); await sleep(300);
+ ghost.style.display='block'; ghostAt({x:720,y:520}); await sleep(500);
+ await move(548,16,1100); hoverIn(); await sleep(1500);
+ ['korus','sbe','brief','ig'].forEach((id,i)=>setTimeout(()=>{ addTask(id,i===1?'thinking':'working'); Snd.play('blip') },i*280)); await sleep(1900);
+ let b=rectS(botwrap); await move(b.cx+60,b.cy+50,700); await move(b.cx,b.cy,600); botHover(true); await sleep(1100);
+ for(let i=0;i<3;i++){ await clickAt(); slap(); await sleep(360) } await sleep(3600); botHover(false);
+ await move(700,470,900); app.hover=false; await sleep(400); collapse(); await sleep(1300);
+ alertView('approval','korus','approval'); await sleep(1500); await clickEl('[data-act=allow]'); await sleep(1500);
+ alertView('question','sbe','question'); await sleep(1400); await clickEl($$('.opt')[1]); await sleep(1500);
+ alertView('error','brief','error'); await sleep(1600); await clickEl('[data-act=retry]'); await sleep(1400);
+ const fe=$$('.file')[0], fr=rectS(fe); await move(fr.l+24,fr.cy,900); await clickAt(); beginFileDrag(fe); await move(760,220,700); await move(548,70,800); await sleep(700);
+ dragEnd(app.pointer); await sleep(3700);
+ await clickEl('[data-act=mail]'); await sleep(700); await clickEl('#mailTo'); await typeIn($('#mailTo'),'[email protected]'); await sleep(300); await clickEl('[data-act=send-mail]'); await sleep(2600);
+ collapse(); await sleep(900);
+ alertView('finished','korus','finished'); await sleep(3400); removeTask('korus'); collapse(); await sleep(1200);
+ b=rectS(botwrap); await move(b.cx,b.cy,900); await sleep(200); ghost.classList.add('down'); beginBotDrag(); const s=rectS(safari); await move(s.cx-40,s.cy-20,1300); ghost.classList.remove('down'); dragEnd(app.pointer); await sleep(900);
+ await clickEl('#promptIn'); await typeIn($('#promptIn'),"Trouve l'appart le moins cher sous 90 € la nuit"); await sleep(350); await clickEl('[data-act=send]'); await sleep(4600);
+ await move(820,500,900); await sleep(1600); collapse(); await sleep(800);
+ ['sbe','brief','ig'].forEach((id,i)=>setTimeout(()=>{ setTask(id,'finished'); setTimeout(()=>removeTask(id),900) },i*500)); await sleep(2800);
+ collapse(); setMode('hidden'); await sleep(900);
+ ghost.style.display='none'; $('#demoTag').style.display='none'; app.demo=false; app.demoHold=false; btn.disabled=false; btn.querySelector('span').textContent='Relancer la démo'; app.lastMove=NOW(); $('#promptIn').value=''; $('#mailTo').value='';
+}
+$('#demoBtn').addEventListener('click',runDemo);
+
+/* ---------------- ÉCHELLE ---------------- */
+function fit(){ const o=$('#stageOuter'); const k=o.clientWidth/1120; $('#stage').style.transform=`scale(${k})`; o.style.height=(700*k)+'px' }
+window.addEventListener('resize',fit); fit();
+setPiste('mochi'); setSound(false); sync(); applyLayout(); requestAnimationFrame(frame);
+window.__app=app; window.__demo=runDemo; window.__main=main; window.__snd=Snd; window.__api={expand,collapse,setMode,addTask,setTask,alertView,sync,applyLayout,removeTask};
+})();
+</script>
+</body>
+</html>
diff --git a/docs/.nojekyll b/docs/.nojekyll
new file mode 100644
index 00000000..e69de29b
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
new file mode 100644
index 00000000..d5986016
--- /dev/null
+++ b/docs/INTEGRATIONS.md
@@ -0,0 +1,158 @@
+# Notch Buddy — intégrations
+
+Règle d'or : **vérifier la doc officielle au moment d'implémenter**. Les formats ci-dessous sont le plan, pas une garantie. Sources à relire :
+- Hooks Claude Code : https://code.claude.com/docs/en/hooks
+- API Claude (Messages, outil de recherche web, modèles) : https://docs.claude.com/en/api/overview
+- API publique n8n : `{URL de l'instance}/api/v1/docs` (playground de l'instance de Louis)
+
+---
+
+## 1. Claude Code (sessions de Louis)
+
+### Architecture
+```
+claude (terminal, VS Code, app Claude)
+ └─ hook "command" ─► nb-hook (petit exécutable Swift, livré avec l'app)
+ └─ socket Unix ─► Notch Buddy.app
+ ◄─ décision (pour PermissionRequest)
+```
+- `nb-hook` : cible séparée dans le projet, copiée dans `~/Library/Application Support/NotchBuddy/bin/nb-hook` au premier lancement.
+- Socket : `~/Library/Application Support/NotchBuddy/nb.sock`.
+- `nb-hook <Event>` lit le JSON du hook sur stdin, ajoute le contexte du terminal (`TERM_PROGRAM`, `ITERM_SESSION_ID`, `TERM_SESSION_ID`, `__CFBundleIdentifier`, le tty trouvé en remontant les processus parents, `cwd`), l'envoie à l'app.
+- **Si l'app ne répond pas en 300 ms, `nb-hook` sort en code 0 sans rien écrire** : Claude Code continue normalement. Jamais de blocage.
+
+### Événements à brancher et état du bonhomme
+| Hook | Effet dans l'app |
+|---|---|
+| `SessionStart` | crée la tâche (nom = dossier), état `idle` |
+| `UserPromptSubmit` | état `thinking`, ligne du défilé = début du prompt |
+| `PreToolUse` | état `working`, ligne = outil + cible (« Edit Invoice.swift », « Bash npm test ») |
+| `PostToolUse` / `PostToolUseFailure` | met à jour la ligne ; un échec reste `working` |
+| `PermissionRequest` | alerte `approval` (voir plus bas) |
+| `Notification` | selon le type : attente d'entrée → `question` si une question est posée, sinon rien ; limite d'usage → `ratelimit` |
+| `Stop` | état `finished` → vue `finished` 5,2 s, résumé = dernière phrase utile de la réponse si disponible |
+| `StopFailure` (si présent dans la doc) | alerte `error` |
+| `SubagentStart` / `SubagentStop` | afficher « + sous-agent » dans le défilé |
+| `SessionEnd` | retire la tâche |
+
+Vérifier dans la doc la liste exacte des événements et leurs champs.
+
+### Approuver depuis le notch
+- Sur `PermissionRequest`, `nb-hook` **attend** la décision de l'app (défaut 110 s, réglable) puis écrit sur stdout le JSON de décision du hook (d'après la doc actuelle : `hookSpecificOutput` avec `decision.behavior` = `allow` ou `deny`). Timeout du hook dans settings.json : décision + 10 s.
+- Pas de réponse avant le délai, ou app fermée → aucune sortie, le terminal affiche sa demande habituelle. Si Louis répond dans le terminal, l'app retire l'alerte au prochain événement de la session.
+- Un bug a été signalé où `deny` était ignoré sur `PermissionRequest` (issue GitHub anthropics/claude-code #19298). **Tester allow et deny** ; si deny ne marche pas, basculer la décision sur `PreToolUse` (`permissionDecision`) pour les outils concernés.
+- « Toujours autoriser » : si la doc permet de renvoyer une règle de permission persistante, l'utiliser. Sinon l'app garde sa propre liste (projet + outil + motif de commande) et répond `allow` automatiquement ensuite. Liste visible et supprimable dans les réglages.
+- Raccourcis Y / N quand la vue `approval` est ouverte.
+
+### Répondre aux questions
+- Si Claude utilise l'outil de question (`AskUserQuestion`), l'intercepter en `PreToolUse` et afficher les options dans la vue `question`.
+- Vérifier dans la doc si un hook peut fournir la réponse. Si oui : clic sur une option = réponse. **Si non** : la vue affiche la question et un bouton « Répondre dans le terminal » qui saute à la session. Ne pas bricoler de frappe clavier simulée.
+
+### Sauter au terminal
+| Contexte capté | Action |
+|---|---|
+| `TERM_PROGRAM=Apple_Terminal` + tty | AppleScript Terminal : sélectionner l'onglet dont le `tty` correspond, activer |
+| `TERM_PROGRAM=iTerm.app` + `ITERM_SESSION_ID` | AppleScript iTerm : sélectionner la session, activer |
+| `TERM_PROGRAM=vscode` | ouvrir le dossier `cwd` dans VS Code ou Cursor (selon `__CFBundleIdentifier`) |
+| Ghostty, Warp, autre | activer l'app |
+| rien (app Claude) | activer l'app Claude |
+Demande l'autorisation Automatisation la première fois (normal).
+
+### Installation des hooks : procédure obligatoire
+1. Lire `~/.claude/settings.json` (le créer s'il n'existe pas).
+2. Copier en `~/.claude/settings.json.bak-AAAAMMJJ-HHMM`.
+3. **Fusionner** : ajouter les hooks Notch Buddy sans toucher aux hooks existants. Chemin de `nb-hook` entre guillemets (il contient un espace).
+4. Montrer le diff à Louis, attendre son OK, écrire.
+5. Bouton « Désinstaller les hooks » dans les réglages qui retire uniquement les entrées Notch Buddy.
+
+---
+
+## 2. n8n (workflows de Louis)
+
+- Réglages : URL de l'instance (probablement `https://n8nlouis.dcsys.tech`, **à confirmer avec Louis**) et clé API n8n (Trousseau). La clé se crée dans n8n : Settings → n8n API.
+- Le Mac joint n8n, pas l'inverse : **polling** toutes les 5 s de l'API publique :
+ - noms des workflows : `GET /api/v1/workflows` (cache 10 min) ;
+ - exécutions récentes : `GET /api/v1/executions` avec filtres de statut et `limit`.
+- Mapping :
+ - exécution en cours → tâche `working` (si l'API expose les exécutions en cours ; sinon n8n n'apparaît qu'aux erreurs et aux succès, c'est acceptable) ;
+ - nouvelle exécution en erreur → alerte `error`, détail = nœud en échec + message (`GET /api/v1/executions/{id}?includeData=true`) ;
+ - succès → mini-bonhomme `finished` 3 s en compact, **sans** ouvrir l'island (sinon trop de bruit), sauf réglage contraire.
+- Boutons :
+ - « Relancer » → endpoint de retry de l'API publique (vérifier sa présence et son chemin dans le playground de l'instance). S'il n'existe pas : ouvrir l'exécution dans n8n.
+ - « Ouvrir dans n8n » → ouvrir `{URL}/workflow/{workflowId}/executions/{executionId}` dans le navigateur par défaut.
+- Réglage « workflows suivis » : tous par défaut, liste à cocher.
+
+---
+
+## 3. Fichiers déposés
+
+- Glisser-déposer natif sur la panel (types `fileURL`). Copier les fichiers dans `~/Library/Application Support/NotchBuddy/inbox/` (c'est la phase `uploading`).
+- Vue `choose` :
+ - **Poser une question dessus** → vue `prompt` avec une pastille du fichier. Envoi à l'API Claude (§5) : PDF en bloc `document`, images en bloc `image`, texte et code (≤ 200 Ko) en texte. Autres types : message « Je ne sais pas lire ce format, mais je peux l'envoyer par mail. »
+ - **Envoyer par mail** → vue `mail` (§6).
+- Nettoyer l'inbox après 7 jours.
+
+---
+
+## 4. Attacher le bonhomme à une fenêtre
+
+1. Au lâcher, trouver la fenêtre sous le point : `CGWindowListCopyWindowInfo(.optionOnScreenOnly)`, première fenêtre de couche 0 qui n'est pas la nôtre et contient le point. Récupérer app, titre, cadre.
+2. Afficher le **halo** : une panel transparente, non cliquable, posée sur le cadre de la fenêtre. Bordure conique arc-en-ciel de 3 pt qui tourne en 3 s (`#FF6B5B → #F7B32B → #2DD4A7 → #38BDF8 → #A78BFA → #F472B6`), voile multicolore en mode multiply qui respire (voir `.attach` du prototype), fondu d'entrée 600 ms. Son `attach`, émote Clin d'œil.
+3. Contexte envoyé à Claude :
+ - capture de la fenêtre avec ScreenCaptureKit (`SCScreenshotManager`), redimensionnée à 1568 px de large max ;
+ - si c'est Safari, Chrome, Arc ou Brave : URL et titre de l'onglet actif via AppleScript.
+4. Vue `prompt` avec la pastille « Safari, escale.fr » (app + domaine), focus sur le champ.
+5. Le halo reste pendant `searching`, disparaît quand le résultat s'affiche ou quand l'island se ferme.
+
+Permissions : Enregistrement de l'écran (capture) et Automatisation (navigateur). Si refusées : on continue sans capture ou sans URL, et on le dit en une ligne dans la vue.
+
+---
+
+## 5. API Claude (recherche)
+
+- `POST https://api.anthropic.com/v1/messages`, en-têtes `x-api-key`, `anthropic-version`, `content-type: application/json` (versions à vérifier dans la doc).
+- Modèle par défaut : `claude-sonnet-5`, réglable dans les réglages. Vérifier la liste des modèles disponibles dans la doc.
+- Outil de recherche web côté serveur de l'API : l'identifiant de type à jour est dans la doc (au moment d'écrire, `web_search_20250305`) ; `max_uses` 5.
+- Prompt système (français) : répondre court, pour un affichage dans le notch, au format JSON strict :
+ ```json
+ { "title": "…", "items": [ { "label": "…", "detail": "…", "url": "…" } ], "note": "…" }
+ ```
+ 3 items maximum. Si le JSON est invalide : afficher le texte brut (3 lignes max) dans la vue `result`.
+- Contenu du message utilisateur : capture (bloc image) + « URL : … / Titre : … / Demande : … », ou fichier (§3) + demande, ou demande seule (onglet Demander).
+- Pendant l'appel : état `searching`, vue `searching`, texte scintillant. Réponse : état `finished`, vue `result`, émote Fier, son `finish`.
+- Boutons du résultat : « Ouvrir » (premier lien), « Copier » (texte), « Fermer ».
+- Erreur réseau ou clé invalide : état `error`, vue `note` avec la raison en une phrase et « Ouvre les réglages pour vérifier la clé ».
+- Micro (bouton du champ) : dictée `SFSpeechRecognizer` en `fr-FR`, sur l'appareil si possible. Optionnel (M9). Si la permission est refusée, masquer le bouton.
+
+---
+
+## 6. Mail (app Mail du Mac)
+
+- Vue `mail` : À (obligatoire, validation d'adresse), Objet (prérempli : nom du fichier), Message (optionnel, une ligne).
+- Envoi uniquement au clic sur « Envoyer », via AppleScript (`NSAppleScript`) sur Mail :
+ ```applescript
+ tell application "Mail"
+ set m to make new outgoing message with properties {subject:"…", content:"…", visible:false}
+ tell m
+ make new to recipient at end of to recipients with properties {address:"…"}
+ make new attachment with properties {file name:(POSIX file "…")} at after the last paragraph of content
+ end tell
+ delay 1
+ send m
+ end tell
+ ```
+ Le `delay` laisse le temps à la pièce jointe d'être prise en compte (comportement connu de Mail). `Info.plist` : `NSAppleEventsUsageDescription`.
+- Succès : vue `note` « Mail envoyé à … », émote Clin d'œil, son `send`. Échec : état `error` avec la raison.
+
+---
+
+## 7. Permissions macOS demandées (récapitulatif pour Louis)
+
+| Permission | Pourquoi | Quand |
+|---|---|---|
+| Automatisation → Mail | envoyer les mails | premier envoi |
+| Automatisation → Terminal / iTerm / navigateur | sauter au bon onglet, lire l'URL | première utilisation |
+| Enregistrement de l'écran | capturer la fenêtre attrapée | première attache |
+| Micro + Reconnaissance vocale (optionnel) | dictée | premier clic sur le micro |
+
+Aucune permission Accessibilité nécessaire.
diff --git a/docs/SPEC.md b/docs/SPEC.md
new file mode 100644
index 00000000..8861f672
--- /dev/null
+++ b/docs/SPEC.md
@@ -0,0 +1,217 @@
+# Notch Buddy — spécification
+
+Toutes les mesures sont en points macOS. Les valeurs viennent de `reference/notch-buddy.html` (constantes `NW`, `NH`, `EW`, `VIEWS`, `STATES`, `EMOTES`, `PISTES`, `AGENTS`, classe `Bot`). En cas de doute, relire le code du prototype.
+
+---
+
+## 1. Fenêtre et notch
+
+- Une `NSPanel` sans bordure : `styleMask [.borderless, .nonactivatingPanel]`, fond transparent, sans ombre, niveau au-dessus de la barre de menus (`.mainMenu + 3` ou équivalent qui passe au-dessus de la barre et des apps plein écran), `collectionBehavior [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary, .ignoresCycle]`.
+- Taille fixe 720 × 320, ancrée en haut au centre de l'écran qui a un notch. L'island est dessinée dedans, collée au bord haut.
+- **Clics traversants** : la zone transparente ne doit jamais bloquer les clics. Toggle `ignoresMouseEvents` à 60 Hz selon que `NSEvent.mouseLocation` est dans la forme de l'island (plus 6 pt de marge) ou pas.
+- La panel peut devenir key uniquement quand un champ texte de l'island a le focus (prompt, mail). Sinon elle ne vole jamais le focus.
+- Détection du notch : `NSScreen.safeAreaInsets.top` > 0 et `auxiliaryTopLeftArea` / `auxiliaryTopRightArea`. Largeur du notch `wN` = largeur écran − les deux zones auxiliaires ; hauteur `hN` = `safeAreaInsets.top`. Le prototype utilise `wN = 184`, `hN = 32` : dans l'app, prendre les vraies valeurs.
+- Pas d'écran avec notch (capot fermé) : afficher sur l'écran principal un faux notch noir de 184 × 24 en haut au centre.
+- Suivi de la souris : polling de `NSEvent.mouseLocation` à chaque frame. Aucune permission nécessaire.
+
+### Forme de l'island
+- Rectangle noir `#000`, coins hauts carrés (il se fond dans le bord de l'écran), coins bas arrondis : 14 pt en hidden/peek/compact, 30 pt en expanded.
+- Deux « oreilles » concaves de 14 pt aux coins hauts, à l'extérieur, pour que la forme coule dans le bord de l'écran (voir `#island::before/::after` du prototype).
+
+## 2. Modes de l'island
+
+| Mode | Largeur | Hauteur | Bonhomme | Agents secondaires |
+|---|---|---|---|---|
+| `hidden` | wN | hN | invisible | invisibles |
+| `peek` | wN + 64 | hN | Ø 18, centre x = 19 | invisibles |
+| `compact` | wN + 104 | hN | Ø 20, centre x = 27 | grille 2×2 dans l'oreille droite |
+| `expanded` | 640 | selon la vue (§5) | selon la vue | selon la vue |
+
+(Ø = diamètre du corps. Le canvas du personnage fait Ø / 0,6 de côté : le corps occupe 60 % du canvas, le reste sert aux particules, mains et badge.)
+
+Grille compact : pastilles Ø 9,5 autour du point (largeur − 27, hN/2), écart ±6. 1 agent : centré. 2 : côte à côte. 3 : deux en haut, un en bas. 4 : carré.
+
+## 3. Règles de comportement (validées par Louis)
+
+1. **Rien ne tourne** → `hidden`. Totalement invisible.
+2. **Souris sur le notch** alors que `hidden` → `peek` immédiatement, le bonhomme sort en faisant coucou (mains + son `peek` + son `greet`). Si la souris reste 650 ms → `expanded` (vue `overview`, ou `empty` s'il n'y a aucune tâche). Si elle part pendant le peek → retour `hidden` après 600 ms.
+3. **Des tâches tournent et Louis est actif** → `compact` : très fin, le bonhomme visible, il suit la souris des yeux partout sur l'écran.
+4. **Survol en compact** → `expanded` après 200 ms. Clic sur le bonhomme en compact → `expanded` tout de suite.
+5. **Fermeture auto** : une fois ouverte, l'island se replie après **60 s sans activité** (mouvement de souris sur l'island, clic, frappe). Quitter l'island ne la ferme pas. Pendant les 10 dernières secondes, un trait de 2 pt en bas au centre (160 pt → 0, blanc 35 %) montre le compte à rebours. `Échap` ferme.
+6. **Louis absent** (aucun mouvement de souris depuis 3 min, réglable) → `hidden`, même avec des tâches. Au premier mouvement → retour `compact` si des tâches tournent.
+7. **Alertes** (permission, question, erreur) : l'island s'ouvre seule sur la vue de l'alerte, **même si Louis est absent**, et reste ouverte (pas de fermeture auto) jusqu'à sa réponse.
+8. **Terminé** : l'island s'ouvre sur la vue `finished` pendant 5,2 s, puis retire la tâche et se replie.
+9. Plusieurs alertes en même temps : file d'attente, une à la fois, l'ordre d'arrivée.
+10. **Focus** : le gros bonhomme représente la tâche en focus (la dernière alerte, sinon la première qui travaille). Les autres tâches sont les mini-bonhommes. Cliquer un mini-bonhomme le met en focus.
+
+## 4. Animations de l'island
+
+- Ouverture / agrandissement : 520 ms, ressort avec léger dépassement, équivalent `cubic-bezier(.32,1.22,.42,1)`. En SwiftUI, partir de `.spring(response: 0.5, dampingFraction: 0.72)` et ajuster à l'œil contre le prototype.
+- Fermeture / rétrécissement : 340 ms, `cubic-bezier(.45,0,.2,1)`, sans dépassement.
+- Largeur, hauteur, rayon, position et taille du bonhomme, position et taille des mini-bonhommes animent **ensemble** (effet « élément partagé » : les mini-bonhommes passent de la grille aux pastilles puis à la colonne sans disparaître).
+- Contenu des vues : sortie 160 ms (opacité 0, flou 8, échelle 0,97) ; entrée 300 ms avec 160 ms de retard (après que le conteneur a commencé à grandir). L'en-tête apparaît avec 300 ms de retard.
+- Mini-bonhommes : décalage de 35 ms par index.
+- Libellés des pastilles : apparaissent 220 ms après le début du mouvement.
+- Au passage en `expanded`, le bonhomme cligne des yeux.
+- Sons : `open` à l'ouverture, `close` à la fermeture.
+
+## 5. Vues (mode expanded, largeur 640)
+
+Structure commune : en-tête de 34 pt (onglets à gauche : Vue d'ensemble, Demander, Déposer ; à droite : « N en cours » + bouton son). Contenu inséré de 36 en haut, 10 à gauche, droite, bas. Cartes : rayon 20, fond `#141518`, bord blanc 3,5 %. Dans les vues autres que `overview`, les mini-bonhommes passent en **colonne** à droite (Ø 16, x = largeur − 31, y = 50 + i × 24) et la carte laisse 42 pt à droite.
+
+Voile de couleur des cartes : dégradé radial depuis le bas (120 % × 90 %, centre 50 % / 130 %), couleur de l'état :
+rouge `rgba(244,80,94,.55)`, vert `rgba(52,211,153,.5)`, rose `rgba(244,114,182,.55)`, ambre `rgba(245,165,36,.42)`, cyan `rgba(34,211,238,.38)`, indigo `rgba(99,102,241,.5)`, neutre `rgba(255,255,255,.08)`.
+
+| Vue | Hauteur | Bonhomme (x, Ø) | Contenu | Capture |
+|---|---|---|---|---|
+| `overview` | 196 | 64, 70 | carte gauche 322 de large : ligne agent + défilé de tâches ; carte droite : pastilles | 03 |
+| `empty` | 150 | 70, 62 | « Rien ne tourne pour l'instant. » + bouton « Demander à Claude » | 16 |
+| `approval` | 206 | 62, 56 | agent + « Claude Code veut lancer une commande », bloc code, Refuser (N), Toujours autoriser, Autoriser (Y) | 04 |
+| `question` | 196 | 62, 56 | agent + question + options en boutons | 05 |
+| `error` | 190 | 62, 58 | agent + outil, titre, détail en rouge `#FF8D97`, Relancer, Ouvrir dans n8n | 06 |
+| `finished` | 170 | 62, 58 | agent + résumé, Voir le terminal, OK | 07 |
+| `confused` | 160 | 76, 66 | « Trop de claques d'un coup. » | 08 |
+| `upload` | 176 | 140, 62 | zone pointillée, « Dépose tes fichiers ici », étiquettes | 09 |
+| `uploading` | 150 | sur la barre, Ø 28 | « Envoi de fichier » + %, barre verte, le bonhomme est le curseur de la barre | 10 |
+| `choose` | 170 | 60, 52 | « fichier est prêt. », Poser une question dessus, Envoyer par mail | 11 |
+| `mail` | 210 | 56, 46 | champs À, Objet (+ Message optionnel), Envoyer, Annuler | 12 |
+| `prompt` | 156 | 52, 44 | pastille de contexte + champ + micro + envoyer | 13 |
+| `searching` | 156 | 52, 44 | contexte + texte scintillant « Claude lit la page et cherche sur le web… » | 14 |
+| `result` | 262 (s'adapte au contenu, max 320) | 52, 44 | titre, 3 lignes de résultat, boutons | 15 |
+| `note` | 136 | 60, 50 | message court (mail envoyé, copié, j'ouvre n8n…), se ferme seul après 2 s | — |
+
+Centre vertical du bonhomme : 36 + (hauteur − 46) / 2, sauf `result` (y = 86).
+
+### Défilé de tâches (overview)
+- Position x = 112 dans la carte, fenêtre de 96 pt avec masque dégradé haut/bas, 4 lignes de 30 pt (précédente, courante, suivante, suivante+1).
+- Ligne courante : 14 pt medium, texte scintillant (dégradé gris → blanc → gris qui balaie en 2,2 s). Autres : 13 pt `#5F646D`, icône 14 pt.
+- Toutes les 2,8 s, si la tâche en focus travaille : tout monte de 30 pt en 450 ms `cubic-bezier(.3,.9,.3,1)`.
+- Dans l'app réelle, les lignes = les dernières actions de la session (outil + cible : « Edit Invoice.swift », « Bash npm test ») ou les nœuds n8n.
+
+### Pastilles (overview)
+- 132 × 34, rayon 17, fond couleur de l'agent à 13 %, bord à 32 %, mini-bonhomme Ø 24 centré à 17 pt du bord gauche, libellé 12 pt couleur de l'agent éclaircie de 25 %. Deux colonnes, écart 8, centrées verticalement dans la carte droite (qui commence à x = 342).
+
+### Boutons
+- Pilule, 12,5 pt medium, fond blanc 9 % (survol 15 %), primaire : fond `#F5F6F8` texte `#0B0C0E`. Appui : échelle 0,94. Raccourcis affichés en petite pastille bordée (Y, N).
+
+## 6. Couleurs des agents (fixes)
+
+| Agent | Couleur |
+|---|---|
+| Korus | `#FF6B5B` |
+| SBE Hub | `#2DD4A7` |
+| Morning AI Brief (n8n) | `#F7B32B` |
+| Publication IG (n8n) | `#A78BFA` |
+| louisraille.fr | `#38BDF8` |
+| Autres | prendre dans cet ordre : `#F472B6`, `#34D399`, `#FB923C`, `#60A5FA`, `#E879F9`, puis boucler |
+
+Nom d'une session Claude Code = nom du dossier de travail (`cwd`), avec une table d'alias réglable (ex. `sbe-hub` → « SBE Hub »). Nom d'un workflow n8n = nom du workflow.
+
+## 7. Le personnage : Mochi
+
+Porter la classe `Bot` du prototype **telle quelle** en Swift (`Canvas` dans `TimelineView(.animation(paused:))`). Constantes Mochi (`PISTES.mochi`) :
+
+- R = 0,3 × côté du canvas. Corps : superellipse d'exposant 2,7, rayons rx = 1,14 R, ry = 0,88 R, décalé de +0,06 R vers le bas.
+- Dégradé du corps : `#FFFAF5` (haut droite) → `#DDCCBF` (bas gauche). Teinte d'état : dégradé linéaire de bas en haut, couleur d'état à 92 % × tint jusqu'à transparent à −0,25 ry. Ombrage radial (bord 20 % noir) et reflet radial blanc 55 % en haut à droite.
+- Joues : deux ellipses rose `rgba(255,120,150,.5 × blush)`, blush minimum 0,35 pour Mochi, suivent le regard.
+- Yeux : encre `#1A1412`, largeur 0,25 R, hauteur 0,27 R, écart angulaire ±0,37 rad, inclinaison verticale −0,12 rad. Projection sur une sphère (yaw, pitch, roll) avec raccourci de perspective et découpe par la silhouette : c'est ce qui donne les roulades (les yeux sortent par le haut et reviennent par le bas).
+- Regard : suit la souris avec retard (`tanh(dx/260)`, `tanh(dy/200)`, lissage exponentiel). Clignement aléatoire toutes les 2,2 à 5,4 s, double clignement 22 % du temps.
+- Mini-bonhommes : même moteur, corps teinté de la couleur de l'agent, badges réduits.
+- Canvas du gros bonhomme : 230 pt × 2 (Retina) ; mini : 76 pt × 2.
+
+### États (`STATES`)
+
+| Clé | Libellé | Couleur | Teinte | Yeux | Badge | Particularité |
+|---|---|---|---|---|---|---|
+| `idle` | Au repos | `#E6E9EE` | 0 | pilule | aucun | |
+| `working` | Travaille | `#3B9EFF` | 0,72 | pilule | pilule « ••• » animée | |
+| `thinking` | Réfléchit | `#8B5CF6` | 0,72 | pilule | « ••• » | regarde en haut à droite |
+| `searching` | Cherche | `#6366F1` | 0,72 | pilule | « ••• » | yeux qui balaient de gauche à droite |
+| `approval` | Attend ton feu vert | `#F5A524` | 0,78 | grands | « ! » | petits sauts en boucle |
+| `question` | Pose une question | `#22D3EE` | 0,75 | pilule | « ? » | tête penchée 0,17 rad |
+| `error` | Erreur | `#F4505E` | 0,78 | plats | point rouge | secousse horizontale à l'entrée |
+| `finished` | Terminé | `#34D399` | 0,35 | contents (arc) | point vert | roulade complète 950 ms + étincelles |
+| `ratelimit` | Limite atteinte | `#FB923C` | 0,72 | fatigués | point orange | gouttes de sueur |
+| `sleeping` | Dort | `#94A3B8` | 0,32 | fermés | aucun | respiration, « z » qui montent |
+| `dizzy` | Sonné | `#F472B6` | 0,7 | spirales | aucun | double roulade 1,3 s |
+
+Halo derrière le bonhomme : dégradé radial couleur de l'état, opacité 0,2 à 0,6 selon l'état (`glow`, `go`), flou 6.
+
+Correspondance avec les vrais événements : voir `INTEGRATIONS.md`. `sleeping` = aucune tâche depuis 10 min et island ouverte manuellement ; `ratelimit` = limite d'usage signalée par Claude Code.
+
+### Émotes (`EMOTES`) et déclencheurs réels
+
+| Émote | Yeux | Extra | Son | Déclencheur |
+|---|---|---|---|---|
+| Amour | cœurs `#FF4D6D` | joues à fond, cœurs qui montent | `love` | souris immobile 1,9 s sur le bonhomme |
+| Surpris | petits points | saut + yeux agrandis | `pop` | quand on l'attrape |
+| Fier | étoiles `#F7B32B` | étoiles, tête en arrière | `proud` | résultat de recherche affiché |
+| Clin d'œil | un œil fermé | tête penchée | `wink` | mail envoyé, fenêtre attrapée |
+| Bâille | fatigués puis fermés | étirement vertical, « z » | `yawn` | juste avant de passer en `sleeping` |
+| Content | arcs | joues | — | après une décision, un fichier avalé |
+| Agacé | fentes inclinées | halo violet `#A855F7` | `annoyed` | une claque |
+
+## 8. Interactions avec le bonhomme
+
+- **Survol** (expanded) : clignement, yeux ×1,08, son `hover`. Immobile 1,9 s → Amour.
+- **Clic** en compact/peek → ouvre. **Clic** en expanded → claque : écrasement (70/130/170 ms), Agacé 800 ms, halo violet, sons `slap` + `annoyed`.
+- **3 clics en moins de 1,7 s** → état `dizzy` pendant 3,3 s, vue `confused`, son `dizzy`, puis retour à la vue et à l'état d'avant.
+- **Glisser** le bonhomme (> 7 pt) : un bonhomme flottant Ø 54 suit le curseur (Surpris + `pop`), celui du notch disparaît. Lâché sur une fenêtre d'une autre app → **attache** (voir INTEGRATIONS §4). Lâché ailleurs → revient dans le notch en 420 ms en rétrécissant.
+- **Glisser un fichier** depuis le Finder vers la zone du notch (±220 pt autour du centre, jusqu'à 26 pt sous l'island) → vue `upload`, le bonhomme se transforme en « bac » (morph 380 ms avec rebond) et regarde le fichier. Contour vert et voile vert quand le fichier est au-dessus.
+- **Déposer** : le fichier file dans le bonhomme (360 ms), `gulp` à 330 ms, écrasement + Content, retour à la forme ronde à 950 ms, vue `uploading` (1,2 à 2,1 s, `tick` tous les 10 %, correspond à la copie dans le dossier de travail de l'app), son `approve`, puis vue `choose`.
+- Plusieurs fichiers : même flux, libellé « 3 fichiers ».
+
+## 9. Sons
+
+Fichiers `assets/sounds/*.wav` (48 kHz stéréo), rendus depuis le moteur du prototype avec un gain ×6. **Volume par défaut du lecteur : 0,12** pour retrouver le niveau du prototype ; le curseur de volume des réglages va de 0 à 0,2. Jouer avec `AVAudioPlayer` préchargés (latence nulle), plusieurs sons peuvent se superposer. Désactivable dans l'en-tête de l'island et dans les réglages (persisté).
+
+| Événement | Son |
+|---|---|
+| peek / coucou | `peek` + `greet` |
+| ouverture / fermeture | `open` / `close` |
+| survol du bonhomme / petit clic UI | `hover` / `blip` |
+| claque / agacé / sonné | `slap` / `annoyed` / `dizzy` |
+| travaille / réfléchit / cherche | `work` / `think` / `search` |
+| permission / question / erreur / limite | `approval` / `question` / `error` / `rate` |
+| terminé | `finish` |
+| décision validée, upload fini | `approve` |
+| fichier avalé / progression | `gulp` / `tick` |
+| envoi (prompt, mail) / attache fenêtre | `send` / `attach` |
+| émotes | `love`, `pop`, `proud`, `wink`, `yawn`, `sleep` |
+
+Pas de son pour les mises à jour silencieuses (défilé de tâches, mini-bonhommes qui changent d'état sauf alerte).
+
+## 10. Barre de menus et réglages
+
+Petit item dans la barre de menus (icône : silhouette du Mochi, monochrome). Menu : Ouvrir le notch, Lancer la démo (⌃⌥⌘D), Réglages…, Debug ▸ (forcer chaque vue, chaque état, chaque émote, ajouter des tâches factices), Quitter.
+
+Fenêtre Réglages (SwiftUI, simple) :
+- Clé API Anthropic (Trousseau), modèle (par défaut voir INTEGRATIONS §5).
+- n8n : URL de l'instance, clé API (Trousseau), intervalle de polling, workflows suivis (tous par défaut).
+- Claude Code : état des hooks (installés / non), bouton Installer / Désinstaller, délai d'attente d'une décision (défaut 110 s).
+- Son on/off, volume. Fermeture auto (défaut 60 s). Délai d'absence (défaut 3 min).
+- Lancer au démarrage (`SMAppService.mainApp`).
+- Alias de noms de projets et couleurs.
+
+## 11. Jalons
+
+Chaque jalon se termine par build + capture + comparaison aux références + commit (voir CLAUDE.md).
+
+- **M0 Base** : vérifier Xcode (`xcodebuild -version`), XcodeGen, `git init`, `project.yml`, app agent qui se lance et affiche le faux contenu. Menu Debug.
+- **M1 Island** : panel, détection du notch, 4 modes, règles §3, clics traversants, animations §4, données factices.
+- **M2 Personnage** : port de `Bot` (Mochi), tous les états et émotes, mini-bonhommes, halo, badges, particules, mains. Pause quand masqué.
+- **M3 Vues** : toutes les vues §5, défilé, pastilles, colonne, élément partagé, voiles. Comparer avec les 16 captures.
+- **M4 Sons** : branchement §9, réglages son.
+- **M5 Claude Code** : hooks, approbations, questions, saut au terminal (INTEGRATIONS §1).
+- **M6 n8n** : polling, erreurs, relance, ouverture (INTEGRATIONS §2).
+- **M7 Fichiers** : glisser-déposer, prompt sur fichier, mail via Mail (INTEGRATIONS §3 et §6).
+- **M8 Fenêtres + recherche** : attache, capture, URL, API Claude avec recherche web, vue résultat (INTEGRATIONS §4 et §5).
+- **M9 Finition** : mode démo (DEMO.md), réglages complets, lancement au démarrage, écran sans notch, mesure CPU/RAM, passe finale de comparaison visuelle.
+
+## 12. Critères d'acceptation
+
+- Côte à côte avec le prototype, Louis ne voit pas de différence sur le personnage, les couleurs, les timings et les sons.
+- Aucun clic perdu à cause de la fenêtre transparente.
+- Une session Claude Code n'est jamais bloquée par l'app (app fermée, plantée ou lente → le terminal prend le relais).
+- Hidden = 0 % CPU ; compact < 3 % ; mémoire < 100 Mo.
+- La démo (⌃⌥⌘D) se filme d'une traite sans intervention.
diff --git a/docs/fr/README-dev.md b/docs/fr/README-dev.md
new file mode 100644
index 00000000..a536e196
--- /dev/null
+++ b/docs/fr/README-dev.md
@@ -0,0 +1,32 @@
+# Coucou
+
+App macOS perso : Mochi, un petit personnage qui vit dans le notch du MacBook. Il montre les sessions Claude Code et les intégrations (Stripe, n8n, GitHub, Vercel, Resend, Notion, Cal.com), permet de discuter avec Claude, de déposer un fichier pour l'envoyer par mail, et il réagit quand on le survole ou qu'on le tape.
+
+## Lancer
+
+```
+cd NotchBuddy
+xcodegen # régénère NotchBuddy.xcodeproj depuis project.yml
+open NotchBuddy.xcodeproj
+```
+
+Puis ⌘R dans Xcode. Les clés API se collent dans Réglages (menu Coucou de la barre de menus), elles vont dans le Trousseau.
+
+## Dossier
+
+| Dossier | Contenu |
+|---|---|
+| `NotchBuddy/Sources/App/` | tout le code Swift |
+| `NotchBuddy/Resources/sounds/` | les 28 sons du notch (WAV) |
+| `NotchBuddy/Assets.xcassets/` | icône de l'app, icône de la barre de menus |
+| `NotchBuddy/project.yml` | définition du projet XcodeGen |
+| `docs/SPEC.md` | comportement, vues, états, sons |
+| `docs/INTEGRATIONS.md` | hooks Claude Code, n8n, API Claude, Mail, fichiers |
+| `docs/historique/` | anciens documents (kit de départ, démo, nettoyage) |
+| `design/prototype/` | prototype HTML d'origine, source de vérité visuelle |
+| `design/captures/` | captures cibles des vues et des états de Mochi |
+| `design/animations/` | séquences de référence (coucou, upload) et leurs images |
+| `video/` | vidéo de présentation et musique |
+| `CLAUDE.md` | règles du projet pour Claude Code |
+
+Identifiant de l'app : `fr.louisraille.NotchBuddy` (à ne pas changer : trousseau, réglages et autorisations en dépendent).
diff --git a/docs/historique/DEMO.md b/docs/historique/DEMO.md
new file mode 100644
index 00000000..8a3bc2d7
--- /dev/null
+++ b/docs/historique/DEMO.md
@@ -0,0 +1,34 @@
+# Notch Buddy — mode démo (pour filmer)
+
+Déclenchement : menu barre de menus → « Lancer la démo », ou ⌃⌥⌘D. Échap ou ⌃⌥⌘D à nouveau : arrêt immédiat, retour à l'état réel.
+
+Principe : pendant la démo, l'app **ignore les vraies données** (hooks et n8n mis en file, rejoués après) et joue un scénario avec des tâches factices. Les moments qui demandent un geste attendent le geste de Louis (avec un délai max, puis la démo continue seule). Aucun repère visuel à l'écran : Louis suit ce script. Le son est forcé à ON pendant la démo.
+
+Données factices (reprises du prototype) :
+- Korus (Claude Code, `#FF6B5B`) : « Lecture du schéma Prisma », « Migration de la table factures », « Mise à jour des tests », « Lancement de la suite de tests », « Relecture du diff ».
+- SBE Hub (Claude Code, `#2DD4A7`) : « Analyse des requêtes lentes », « Index sur les cours », « Écriture des tests ».
+- Morning AI Brief (n8n, `#F7B32B`) : « Collecte des sources », « Résumé par Claude », « Envoi Gmail ».
+- Publication IG (n8n, `#A78BFA`) : « Rendu du carousel », « Planification ».
+
+## Séquence (≈ 60 s)
+
+| # | Ce qui se passe | Déclencheur | Geste de Louis |
+|---|---|---|---|
+| 1 | Island `hidden`. | départ | poser la souris sur le notch |
+| 2 | `peek`, coucou avec les mains, puis ouverture `empty`. | survol (max 4 s) | laisser la souris |
+| 3 | Les 4 tâches arrivent une par une (280 ms d'écart), la vue passe en `overview`, pastilles qui se déroulent. | +1,5 s | — |
+| 4 | Survol du bonhomme : clignement, puis 3 claques → `dizzy`, vue `confused` 3,3 s. | 3 clics (max 8 s) | cliquer 3 fois sur le bonhomme |
+| 5 | Retour `overview`, puis fermeture en `compact`. | +1,5 s après le retour | éloigner la souris |
+| 6 | Alerte permission Korus `npx prisma migrate deploy`. | +1,3 s | cliquer Autoriser (ou Y) |
+| 7 | Alerte question SBE Hub « Quel moteur pour la recherche de cours ? ». | +1,5 s après 6 | cliquer Meilisearch |
+| 8 | Alerte erreur Morning AI Brief « Le nœud Gmail a expiré après 30 s. ». | +1,5 s après 7 | cliquer Relancer |
+| 9 | Dépôt de fichier : upload → uploading → choose. | fichier déposé (max 10 s) | glisser `brief-client.pdf` depuis le Finder vers le notch |
+| 10 | Envoyer par mail → vue `mail`. En démo, l'envoi est **simulé** (aucun mail ne part) : vue `note` « Mail envoyé à [email protected]. ». | clic | cliquer Envoyer par mail, taper l'adresse, Envoyer |
+| 11 | Korus terminé : roulade verte, vue `finished` 3,4 s, puis tâche retirée. | +1,2 s | — |
+| 12 | Attache à une fenêtre : halo arc-en-ciel, vue `prompt`. | bonhomme lâché sur une fenêtre (max 12 s) | attraper le bonhomme dans le notch, le lâcher sur Safari |
+| 13 | Recherche : `searching` 2,8 s puis `result` (réponse factice par défaut, réelle si réglage « démo avec vraie API » activé), émote Fier. | Entrée | taper la demande, Entrée |
+| 14 | Les 3 dernières tâches passent `finished` une par une (500 ms d'écart), island repliée puis `hidden`. | +3 s | éloigner la souris |
+
+Réponse factice de l'étape 13 (si la fenêtre est Safari sur un site de location) : titre « 3 apparts qui collent », lignes « Príncipe Real, calme, 79 € la nuit », « Alfama, vue sur le Tage, 84 € la nuit », « Graça, terrasse, 88 € la nuit ». Pour n'importe quelle autre fenêtre : titre « Ce que je vois dans cette fenêtre » et 3 lignes génériques tirées du titre de la fenêtre.
+
+Pour le tournage, ouvrir `reference/escale-demo.html` dans Safari : c'est la page factice de location du prototype.
diff --git a/docs/historique/KIT-README.md b/docs/historique/KIT-README.md
new file mode 100644
index 00000000..f42823b5
--- /dev/null
+++ b/docs/historique/KIT-README.md
@@ -0,0 +1,36 @@
+# Notch Buddy — kit de construction
+
+Ce dossier contient tout ce qu'il faut pour que Claude Code construise l'app sur ton Mac.
+
+## Ce que tu fais (une fois)
+
+1. **Installe Xcode** depuis l'App Store, ouvre-le une fois et accepte la licence. C'est la seule installation que Claude Code ne peut pas faire à ta place.
+2. **Place ce dossier** où tu veux, par exemple `~/Documents/Projets/notch-buddy`.
+3. **Ouvre Claude Code sur ce dossier** (app Claude, onglet Code, ou `claude` dans un terminal ouvert ici).
+4. Choisis le mode qui accepte les modifications de fichiers automatiquement (sinon il te demandera à chaque fichier).
+5. **Colle le prompt** de `PROMPT.md`.
+
+## Les seuls moments où il te sollicitera
+
+- Coller ta **clé API Anthropic** (à créer sur console.anthropic.com ; l'API est facturée à part de ton abonnement Claude) dans la fenêtre Réglages de l'app.
+- Coller ta **clé API n8n** (dans n8n : Settings → n8n API) et confirmer l'URL de ton instance.
+- Valider le **diff de `~/.claude/settings.json`** avant qu'il ajoute les hooks (une sauvegarde est faite avant).
+- Cliquer les **autorisations macOS** : Automatisation (Mail, Terminal, navigateur) et Enregistrement de l'écran.
+
+## Contenu
+
+| Fichier | Rôle |
+|---|---|
+| `PROMPT.md` | le prompt à coller |
+| `CLAUDE.md` | règles du projet, relues par Claude Code à chaque session |
+| `docs/SPEC.md` | spécification complète et jalons M0 à M9 |
+| `docs/INTEGRATIONS.md` | Claude Code, n8n, API Claude, fichiers, fenêtres, Mail |
+| `docs/DEMO.md` | séquence démo intégrée (⌃⌥⌘D) pour filmer |
+| `reference/notch-buddy.html` | prototype validé, source de vérité visuelle |
+| `reference/escale-demo.html` | page factice à ouvrir dans Safari pendant le tournage |
+| `reference/screens/` | captures cibles (vues et états de Mochi) |
+| `assets/sounds/` | les 28 sons du prototype en WAV |
+
+## Si tu reprends plus tard
+
+Rouvre Claude Code dans ce dossier et dis-lui : « Reprends Notch Buddy là où tu t'es arrêté, relis CLAUDE.md et l'historique git. »
diff --git a/docs/historique/NETTOYAGE-DEMO.md b/docs/historique/NETTOYAGE-DEMO.md
new file mode 100644
index 00000000..bd6f759e
--- /dev/null
+++ b/docs/historique/NETTOYAGE-DEMO.md
@@ -0,0 +1,44 @@
+# Coucou — retirer le mode tournage, le Studio et le menu Debug
+
+La vidéo est faite : tout ce qui servait à la démo et aux fausses vues doit disparaître. L'app ne doit garder que son comportement réel.
+
+## Règles
+- Ne change rien au comportement réel : pollers, hooks Claude Code, coucou, sons, claques et tournis, dépôt de fichier, mail, chat, réglages.
+- **Ne corrige pas les bugs existants**, même si tu les croises en supprimant du code.
+- Garde le Bundle ID `fr.louisraille.NotchBuddy`, les clés du trousseau, les UserDefaults et les chemins `Application Support/NotchBuddy`. Ne lis ni n'écris le trousseau. N'écris pas dans `~/.claude`.
+- Ne touche pas au dossier `notch-buddy-kit/` (c'est la référence).
+- Avant de supprimer quoi que ce soit, cherche tous les appels (`grep -rn`) pour ne rien casser.
+
+## À supprimer
+
+### Mode tournage et Studio 9:16
+- Fichiers `DemoController.swift`, `DemoScenes.swift`, `StudioWindow.swift` (et leurs entrées dans le projet si besoin).
+- Les raccourcis globaux Carbon du mode tournage (⌃⌥⌘D, ⌃⌥0 à 8, ⌃⌥P, Échap) et le « warm up » `_ = DemoController.shared` dans `AppDelegate.setupIsland()`.
+- Menu de la barre de menus : « Filming mode » et « Studio 9:16 », et leurs actions `toggleFilmingMode` / `toggleStudio`.
+- `AppState` : `isDemoMode`, `demoModeActive`, `demoCursorPos`, `demoCursorCarrying`, `demoInputText`, `demoIgnoreMouse`, `demoCursorPressed`.
+- `IslandRootView` : `DemoCursorView` et son utilisation.
+- Les notifications `.demoSetPromptText`, `.demoSubmitPrompt`, `.demoMailTo`, `.demoMailSubject`, `.demoMailBody`, `.demoSendMail` et leurs `onReceive` dans `IslandViewContent`.
+- Les branches démo : `if AppState.shared.isDemoMode { onSuccess…; return }` (mail), la réponse scriptée dans `ClaudeService`, la mise en file des événements dans `HookServer` (et la fonction de rejeu), le test `demoIgnoreMouse` dans `IslandWindowController`.
+- Les gardes `guard !AppState.demoModeActive else { return }` dans tous les pollers (GitHub, Vercel, Resend, Notion, Stripe, n8n, Cal.com).
+- `IslandStateMachine` : `forceHidden()` et `forceCompact()` s'ils ne servaient qu'à la démo.
+- Le fichier `~/Library/Application Support/NotchBuddy/demo-data.json` (ce fichier seulement, rien d'autre dans ce dossier).
+- `DEMO-TOURNAGE.md` à la racine du projet.
+
+### Fausses données
+- `StripePoller.triggerDemo()` et le bouton « Demo » de la carte Stripe dans `IslandViewContent`.
+- `AppState.debugAgents` (les agents « Research » / « Looping »), `addDebugTask()`, `clearDebugTasks()`.
+- La propriété `isFake` des tâches, `purgeFakeTasks()` et le test `guard !task.isFake` sur les pastilles, si plus rien n'en dépend.
+
+### Menu Debug (fausses vues)
+- Le sous-menu « Debug » en entier : Vue ▸, State ▸, Emote ▸, Launch greeting, Simulate mouse enter/leave, Short timers, Slow motion, 3 slaps, Add Korus task, Clear all tasks, Mode ▸, et la simulation de glisser-déposer.
+- Leurs actions `debug…` dans `AppDelegate` et les aides `debug…` dans `IslandWindowController`.
+- `AppState.debugSlowMotion` et son utilisation dans `BotCanvasView` (garder `dt` tel quel).
+
+Le menu de la barre de menus doit finir avec : **Open Coucou**, **Settings…**, **Quit**.
+
+## Vérification
+1. `xcodegen` puis build sans erreur ni nouvel avertissement.
+2. `grep -rn -i "demo\|studio\|isFake\|debugAgents\|debugSlow\|triggerDemo" NotchBuddy/Sources` ne renvoie plus rien (hors « Visual Studio Code »).
+3. Lance l'app : coucou au lancement, petit → grand au clic, pastilles réelles, Stripe/n8n/GitHub qui se mettent à jour, sons, claques et tournis, dépôt de fichier → mail, chat. Tout marche comme avant.
+4. Commit : « Retire le mode tournage, le Studio 9:16 et le menu Debug ».
+5. Résumé final : fichiers supprimés, nombre de lignes retirées, et tout ce que tu as laissé en place parce qu'autre chose en dépendait.
diff --git a/docs/historique/PROMPT-initial.md b/docs/historique/PROMPT-initial.md
new file mode 100644
index 00000000..bd5c8637
--- /dev/null
+++ b/docs/historique/PROMPT-initial.md
@@ -0,0 +1,21 @@
+Copie tout le bloc ci-dessous dans Claude Code, ouvert sur ce dossier.
+
+```
+Tu construis Notch Buddy, mon app macOS perso : un personnage animé (Mochi) qui vit dans le notch de mon MacBook et me montre mes sessions Claude Code et mes workflows n8n.
+
+Tout est dans ce dossier. Dans cet ordre :
+1. Lis CLAUDE.md en entier : ce sont les règles du projet.
+2. Lis docs/SPEC.md, docs/INTEGRATIONS.md et docs/DEMO.md.
+3. Lis le code de reference/notch-buddy.html : c'est le prototype que j'ai validé. Le personnage (classe Bot), les couleurs, les timings et les vues doivent être identiques dans l'app. Regarde les captures de reference/screens/.
+4. Vérifie mon environnement : macOS (sw_vers), Xcode (xcodebuild -version), Homebrew, XcodeGen. S'il manque Xcode, arrête-toi et dis-le moi. Installe XcodeGen toi-même s'il manque.
+
+Ensuite enchaîne les jalons M0 à M9 de docs/SPEC.md sans me demander de validation entre eux. À la fin de chaque jalon : build, lance l'app, capture le notch, compare avec reference/screens/, corrige, commit, et donne-moi un résumé de 3 lignes max.
+
+Tu ne t'arrêtes pour me parler que pour :
+- me faire coller une clé API (ouvre la fenêtre Réglages de l'app) ;
+- me montrer le diff de ~/.claude/settings.json avant d'y ajouter les hooks ;
+- me dire quelle autorisation macOS cliquer ;
+- me demander l'URL de mon instance n8n si tu n'arrives pas à la confirmer.
+
+Avant d'implémenter les hooks Claude Code et l'appel à l'API Claude, vérifie les formats actuels dans la doc officielle (liens dans INTEGRATIONS.md). Réponds-moi en français.
+```
diff --git a/docs/index.html b/docs/index.html
new file mode 100644
index 00000000..ce1e2582
--- /dev/null
+++ b/docs/index.html
@@ -0,0 +1,13 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>A tiny friend in your notch — Coucou</title><link rel="icon" href="media/icon.png"><link rel="stylesheet" href="site.css"></head><body><div class="wrap">
+<header><a href="index.html"><img src="media/icon.png" alt=""></a><span class="name">Coucou</span>
+<nav><a href="index.html" class="on">Home</a><a href="support.html">Support</a><a href="privacy.html">Privacy</a><a href="terms.html">Terms</a><a href="legal.html">Legal</a></nav></header>
+<div class="hero">
+<h1>A tiny friend that lives in your notch</h1>
+<p class="meta" style="font-size:17px">Coucou watches your Claude Code sessions, lets you approve and answer from the notch, and keeps an eye on Stripe, GitHub, Vercel, n8n and more. Free and open source.</p>
+<a class="btn" href="https://github.com/OWNER/REPO/releases/latest">Download for Mac</a><a class="btn ghost" href="https://github.com/OWNER/REPO">View on GitHub</a>
+<img class="demo" src="media/demo.gif" alt="Coucou in action">
+</div>
+<div class="card"><b>Private by design.</b> No account, no analytics, no tracking. Your keys stay in your Keychain. <a href="privacy.html">Read the privacy policy</a>.</div>
+<p class="meta">Requires macOS 15 or later.</p>
+<footer>© 2026 Louis Raillé · Coucou is free and open source (MIT) · <a href="https://github.com/OWNER/REPO">GitHub</a> · <a href="privacy.html">Privacy</a> · <a href="terms.html">Terms</a> · <a href="legal.html">Legal notice</a></footer></div></body></html>
diff --git a/docs/legal.html b/docs/legal.html
new file mode 100644
index 00000000..1ee2b770
--- /dev/null
+++ b/docs/legal.html
@@ -0,0 +1,31 @@
+<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Legal notice — Coucou</title><link rel="icon" href="media/icon.png"><link rel="stylesheet" href="site.css"></head><body><div class="wrap">
+<header><a href="index.html"><img src="media/icon.png" alt=""></a><span class="name">Coucou</span>
+<nav><a href="index.html">Home</a><a href="support.html">Support</a><a href="privacy.html">Privacy</a><a href="terms.html">Terms</a><a href="legal.html" class="on">Legal</a></nav></header>
+<div class="lang"><a href="#fr">Français</a><a href="#en">English</a></div>
+<section id="fr" lang="fr">
+<h1>Mentions légales</h1>
+<div class="meta">Dernière mise à jour : 27 septembre 2026</div>
+<h2>Éditeur</h2>
+<p>Louis Raillé, développeur indépendant, France.<br>Contact : <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a></p>
+<p>Directeur de la publication : Louis Raillé.</p>
+<h2>Hébergement</h2>
+<p>GitHub, Inc. (GitHub Pages)<br>88 Colin P Kelly Jr Street, San Francisco, CA 94107, États-Unis<br><a href="https://github.com">github.com</a></p>
+<h2>Propriété intellectuelle</h2>
+<p>Le code source de Coucou est publié sous <a href="https://github.com/OWNER/REPO/blob/main/LICENSE">licence MIT</a>. Le personnage Mochi, l’icône et les visuels de Coucou appartiennent à leur auteur ; ils peuvent être réutilisés dans le cadre de cette licence. Les marques citées appartiennent à leurs propriétaires respectifs (voir les <a href="terms.html#fr">conditions d’utilisation</a>).</p>
+<h2>Données personnelles</h2>
+<p>Ce site n’utilise ni cookies ni statistiques. L’app ne collecte aucune donnée : voir la <a href="privacy.html#fr">politique de confidentialité</a>.</p>
+</section>
+<hr>
+<section id="en">
+<h1>Legal notice</h1>
+<h2>Publisher</h2>
+<p>Louis Raillé, independent developer, France. Contact: <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a></p>
+<h2>Hosting</h2>
+<p>GitHub, Inc. (GitHub Pages), 88 Colin P Kelly Jr Street, San Francisco, CA 94107, USA.</p>
+<h2>Intellectual property</h2>
+<p>Coucou’s source code is released under the <a href="https://github.com/OWNER/REPO/blob/main/LICENSE">MIT License</a>. Trademarks mentioned belong to their respective owners (see the <a href="terms.html#en">terms</a>).</p>
+<h2>Personal data</h2>
+<p>This site uses no cookies and no analytics. The app collects no data: see the <a href="privacy.html#en">privacy policy</a>.</p>
+</section>
+<footer>© 2026 Louis Raillé · Coucou is free and open source (MIT) · <a href="https://github.com/OWNER/REPO">GitHub</a> · <a href="privacy.html">Privacy</a> · <a href="terms.html">Terms</a> · <a href="legal.html">Legal notice</a></footer></div></body></html>
diff --git a/docs/media/chat.png b/docs/media/chat.png
new file mode 100644
index 00000000..3b24f320
Binary files /dev/null and b/docs/media/chat.png differ
diff --git a/docs/media/claude-code.png b/docs/media/claude-code.png
new file mode 100644
index 00000000..58bfed70
Binary files /dev/null and b/docs/media/claude-code.png differ
diff --git a/docs/media/coucou.png b/docs/media/coucou.png
new file mode 100644
index 00000000..e78ed069
Binary files /dev/null and b/docs/media/coucou.png differ
diff --git a/docs/media/demo.gif b/docs/media/demo.gif
new file mode 100644
index 00000000..21afa1c8
Binary files /dev/null and b/docs/media/demo.gif differ
diff --git a/docs/media/demo.mp4 b/docs/media/demo.mp4
new file mode 100644
index 00000000..bf81ded1
Binary files /dev/null and b/docs/media/demo.mp4 differ
diff --git a/docs/media/dizzy.png b/docs/media/dizzy.png
new file mode 100644
index 00000000..7edbd6a3
Binary files /dev/null and b/docs/media/dizzy.png differ
diff --git a/docs/media/icon.png b/docs/media/icon.png
new file mode 100644
index 00000000..ac0dc576
Binary files /dev/null and b/docs/media/icon.png differ
diff --git a/docs/media/stripe.png b/docs/media/stripe.png
new file mode 100644
index 00000000..ac6d9979
Binary files /dev/null and b/docs/media/stripe.png differ
diff --git a/docs/media/upload.png b/docs/media/upload.png
new file mode 100644
index 00000000..c84966bf
Binary files /dev/null and b/docs/media/upload.png differ
diff --git a/docs/privacy.html b/docs/privacy.html
new file mode 100644
index 00000000..2aff6ede
--- /dev/null
+++ b/docs/privacy.html
@@ -0,0 +1,102 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Privacy Policy — Coucou</title><link rel="icon" href="media/icon.png"><link rel="stylesheet" href="site.css"></head><body><div class="wrap">
+<header><a href="index.html"><img src="media/icon.png" alt=""></a><span class="name">Coucou</span>
+<nav><a href="index.html">Home</a><a href="support.html">Support</a><a href="privacy.html" class="on">Privacy</a><a href="terms.html">Terms</a><a href="legal.html">Legal</a></nav></header>
+<div class="lang"><a href="#en">English</a><a href="#fr">Français</a></div>
+<section id="en">
+<h1>Privacy Policy</h1>
+<div class="meta">Last updated: September 27, 2026</div>
+<div class="card"><b>In short:</b> Coucou has no account, no analytics, no ads and no tracking. The developer receives none of your data. Everything stays on your Mac, except what you choose to send to the services you connect yourself.</div>
+
+<h2>1. Who is responsible</h2>
+<p>Coucou is published by Louis Raillé, an individual developer based in France (“we”). Contact: <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a>.</p>
+
+<h2>2. Data we collect</h2>
+<p><b>None.</b> Coucou does not send any data to us or to any server we operate. There is no telemetry, no crash reporting service, no advertising identifier and no third-party SDK.</p>
+
+<h2>3. Data stored on your Mac</h2>
+<table>
+<tr><th>What</th><th>Where</th><th>Why</th></tr>
+<tr><td>API keys and tokens you enter (Anthropic, Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n)</td><td>macOS Keychain</td><td>To call these services on your behalf</td></tr>
+<tr><td>Preferences (sound, delays, active integrations, shortcut)</td><td>App preferences on your Mac</td><td>To remember your settings</td></tr>
+<tr><td>Files you drop on the notch</td><td>A copy in the app’s own folder on your Mac</td><td>So you can ask a question about them or attach them to an email</td></tr>
+<tr><td>Claude Code session events (project name, current step, permission requests)</td><td>In memory only</td><td>To show them in the notch</td></tr>
+</table>
+<p>You can delete all of this at any time by removing your keys in Settings, then deleting the app and its folder in <code>~/Library/Application Support/NotchBuddy</code> (or the app’s container for the App Store version).</p>
+
+<h2>4. Services you connect yourself</h2>
+<p>Coucou only talks to the services you configure, directly from your Mac, using your own keys. Those services process your data under their own privacy policies:</p>
+<ul>
+<li><b>Anthropic (Claude API)</b> — when you chat with Claude or ask about a file or a window, the text you type, the file content and/or the window context you chose are sent to Anthropic. <a href="https://www.anthropic.com/legal/privacy">Anthropic privacy policy</a>.</li>
+<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> — Coucou reads data from your own accounts (payments, repositories, deployments, emails, pages, bookings, workflow runs) to display them. Nothing is written to them unless you press a button that does so (for example “Retry” on an n8n run).</li>
+</ul>
+<p>We have no access to these requests or their responses.</p>
+
+<h2>5. Claude Code</h2>
+<p>If you install the Claude Code hooks, Claude Code sends session events to Coucou through a local connection on your Mac. These events never leave your computer through Coucou. Before changing <code>~/.claude/settings.json</code>, Coucou makes a dated backup and shows you the changes.</p>
+
+<h2>6. Email</h2>
+<p>When you send a file by email, the message is created and sent by your own Mail app. Coucou never sends email by itself.</p>
+
+<h2>7. macOS permissions</h2>
+<p>Depending on the version and the features you use, macOS may ask you to allow Automation (Mail, Terminal), Accessibility (to read the title of the window you attach) or Screen Recording (to capture a window you attach). These are only used for the feature you triggered and can be revoked at any time in System Settings → Privacy &amp; Security.</p>
+
+<h2>8. Children</h2>
+<p>Coucou is a developer tool and is not directed at children.</p>
+
+<h2>9. Your rights</h2>
+<p>Since we hold no personal data about you, there is nothing for us to access, correct or delete. For data held by a service you connected, please contact that service. If you live in the EU, you can also contact your data protection authority (in France: the <a href="https://www.cnil.fr">CNIL</a>).</p>
+
+<h2>10. Changes</h2>
+<p>If this policy changes, the new version will be published on this page with a new date.</p>
+</section>
+
+<hr>
+<section id="fr" lang="fr">
+<h1>Politique de confidentialité</h1>
+<div class="meta">Dernière mise à jour : 27 septembre 2026</div>
+<div class="card"><b>En bref :</b> Coucou n’a ni compte, ni statistiques, ni publicité, ni pistage. Le développeur ne reçoit aucune de tes données. Tout reste sur ton Mac, sauf ce que tu choisis d’envoyer aux services que tu connectes toi-même.</div>
+
+<h2>1. Responsable</h2>
+<p>Coucou est publié par Louis Raillé, développeur indépendant basé en France. Contact : <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a>.</p>
+
+<h2>2. Données collectées</h2>
+<p><b>Aucune.</b> Coucou n’envoie aucune donnée au développeur ni à un serveur qu’il exploite. Pas de télémétrie, pas de service de rapport de plantage, pas d’identifiant publicitaire, pas de SDK tiers.</p>
+
+<h2>3. Données stockées sur ton Mac</h2>
+<table>
+<tr><th>Quoi</th><th>Où</th><th>Pourquoi</th></tr>
+<tr><td>Clés d’API et jetons saisis (Anthropic, Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n)</td><td>Trousseau macOS</td><td>Appeler ces services pour toi</td></tr>
+<tr><td>Préférences (son, délais, intégrations actives, raccourci)</td><td>Préférences de l’app sur ton Mac</td><td>Garder tes réglages</td></tr>
+<tr><td>Fichiers déposés sur le notch</td><td>Une copie dans le dossier de l’app sur ton Mac</td><td>Pouvoir poser une question dessus ou les joindre à un mail</td></tr>
+<tr><td>Événements des sessions Claude Code (nom du projet, étape en cours, demandes de permission)</td><td>En mémoire uniquement</td><td>Les afficher dans le notch</td></tr>
+</table>
+<p>Tu peux tout supprimer à tout moment : retire tes clés dans les Réglages, puis supprime l’app et son dossier <code>~/Library/Application Support/NotchBuddy</code> (ou le conteneur de l’app pour la version App Store).</p>
+
+<h2>4. Services que tu connectes toi-même</h2>
+<p>Coucou ne communique qu’avec les services que tu configures, directement depuis ton Mac, avec tes propres clés. Ces services traitent tes données selon leur propre politique :</p>
+<ul>
+<li><b>Anthropic (API Claude)</b> : quand tu discutes avec Claude ou poses une question sur un fichier ou une fenêtre, le texte saisi, le contenu du fichier et/ou le contexte de la fenêtre choisie sont envoyés à Anthropic. <a href="https://www.anthropic.com/legal/privacy">Politique de confidentialité d’Anthropic</a>.</li>
+<li><b>Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n</b> : Coucou lit les données de tes propres comptes (paiements, dépôts, déploiements, e-mails, pages, rendez-vous, exécutions de workflows) pour les afficher. Rien n’y est écrit, sauf si tu appuies sur un bouton prévu pour (par exemple « Retry » sur une exécution n8n).</li>
+</ul>
+<p>Le développeur n’a accès ni à ces requêtes ni à leurs réponses.</p>
+
+<h2>5. Claude Code</h2>
+<p>Si tu installes les hooks Claude Code, Claude Code envoie les événements de session à Coucou par une connexion locale sur ton Mac. Coucou ne les fait jamais sortir de ton ordinateur. Avant de modifier <code>~/.claude/settings.json</code>, Coucou en fait une sauvegarde datée et te montre les changements.</p>
+
+<h2>6. E-mail</h2>
+<p>Quand tu envoies un fichier par e-mail, le message est créé et envoyé par ta propre app Mail. Coucou n’envoie jamais d’e-mail de lui-même.</p>
+
+<h2>7. Autorisations macOS</h2>
+<p>Selon la version et les fonctions utilisées, macOS peut te demander d’autoriser l’Automatisation (Mail, Terminal), l’Accessibilité (lire le titre de la fenêtre que tu attaches) ou l’Enregistrement de l’écran (capturer une fenêtre que tu attaches). Elles ne servent qu’à la fonction que tu as déclenchée et se retirent à tout moment dans Réglages Système → Confidentialité et sécurité.</p>
+
+<h2>8. Enfants</h2>
+<p>Coucou est un outil pour développeurs, il ne s’adresse pas aux enfants.</p>
+
+<h2>9. Tes droits</h2>
+<p>Le développeur ne détenant aucune donnée personnelle te concernant, il n’y a rien à consulter, corriger ou supprimer de son côté. Pour les données détenues par un service que tu as connecté, contacte ce service. Tu peux aussi saisir la <a href="https://www.cnil.fr">CNIL</a>.</p>
+
+<h2>10. Modifications</h2>
+<p>En cas de changement, la nouvelle version sera publiée sur cette page avec une nouvelle date.</p>
+</section>
+<footer>© 2026 Louis Raillé · Coucou is free and open source (MIT) · <a href="https://github.com/OWNER/REPO">GitHub</a> · <a href="privacy.html">Privacy</a> · <a href="terms.html">Terms</a> · <a href="legal.html">Legal notice</a></footer></div></body></html>
diff --git a/docs/site.css b/docs/site.css
new file mode 100644
index 00000000..66ba0e0a
--- /dev/null
+++ b/docs/site.css
@@ -0,0 +1,29 @@
+:root{--bg:#0e0f12;--card:#16171b;--ink:#f3f4f6;--dim:#a1a6b0;--line:#26282e;--accent:#8ab4ff}
+@media (prefers-color-scheme: light){:root{--bg:#fafafa;--card:#fff;--ink:#16171b;--dim:#5f646d;--line:#e6e7ea;--accent:#2f6fe0}}
+*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
+body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.65 -apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",sans-serif}
+a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}
+.wrap{max-width:760px;margin:0 auto;padding:32px 20px 80px}
+header{display:flex;align-items:center;gap:12px;margin-bottom:36px;flex-wrap:wrap}
+header img{width:40px;height:40px;border-radius:10px}
+header .name{font-weight:700;font-size:18px}
+nav{margin-left:auto;display:flex;gap:16px;flex-wrap:wrap;font-size:14px}
+nav a{color:var(--dim)}nav a.on{color:var(--ink);font-weight:600}
+h1{font-size:32px;line-height:1.2;margin:0 0 6px}
+h2{font-size:20px;margin:36px 0 8px}
+h3{font-size:16px;margin:22px 0 4px}
+.meta{color:var(--dim);font-size:14px;margin-bottom:24px}
+.lang{display:inline-flex;border:1px solid var(--line);border-radius:999px;overflow:hidden;font-size:13px;margin-bottom:20px}
+.lang a{padding:4px 12px;color:var(--dim)}.lang a:first-child{border-right:1px solid var(--line)}
+.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px 20px;margin:16px 0}
+ul{padding-left:20px}li{margin:4px 0}
+table{width:100%;border-collapse:collapse;font-size:15px;margin:10px 0}
+td,th{border-bottom:1px solid var(--line);padding:8px 6px;text-align:left;vertical-align:top}
+th{color:var(--dim);font-weight:600}
+code{background:var(--card);border:1px solid var(--line);border-radius:6px;padding:1px 6px;font-size:14px;word-break:break-all}
+hr{border:0;border-top:1px solid var(--line);margin:56px 0 32px}
+footer{color:var(--dim);font-size:13px;margin-top:56px;border-top:1px solid var(--line);padding-top:18px}
+.hero{text-align:center;margin:10px 0 30px}.hero img.demo{width:100%;border-radius:14px;border:1px solid var(--line);margin-top:22px}
+.btn{display:inline-block;background:var(--ink);color:var(--bg);padding:10px 18px;border-radius:999px;font-weight:600;margin:6px}
+.btn.ghost{background:transparent;color:var(--ink);border:1px solid var(--line)}
+@media (max-width:560px){h1{font-size:26px}nav{margin-left:0;width:100%}}
diff --git a/docs/support.html b/docs/support.html
new file mode 100644
index 00000000..a8f50604
--- /dev/null
+++ b/docs/support.html
@@ -0,0 +1,48 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Support — Coucou</title><link rel="icon" href="media/icon.png"><link rel="stylesheet" href="site.css"></head><body><div class="wrap">
+<header><a href="index.html"><img src="media/icon.png" alt=""></a><span class="name">Coucou</span>
+<nav><a href="index.html">Home</a><a href="support.html" class="on">Support</a><a href="privacy.html">Privacy</a><a href="terms.html">Terms</a><a href="legal.html">Legal</a></nav></header>
+<div class="lang"><a href="#en">English</a><a href="#fr">Français</a></div>
+<section id="en">
+<h1>Support</h1>
+<div class="meta">Something wrong, or an idea for Mochi? Here’s how to get help.</div>
+<div class="card">
+<b>Report a bug or request a feature:</b> <a href="https://github.com/OWNER/REPO/issues">open an issue on GitHub</a> (fastest).<br>
+<b>Email:</b> <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a>
+</div>
+<h2>FAQ</h2>
+<h3>macOS says it can’t verify the app (GitHub download)</h3>
+<p>Open System Settings → Privacy &amp; Security, scroll down and click <b>Open Anyway</b>. Or run once: <code>xattr -dr com.apple.quarantine /Applications/Coucou.app</code>. The App Store version doesn’t have this step.</p>
+<h3>Mochi doesn’t show my Claude Code sessions</h3>
+<p>Open Settings → Claude Code → <b>Install hooks</b>, review the changes, confirm, then start a new Claude Code session.</p>
+<h3>The chat doesn’t answer</h3>
+<p>Add your Anthropic API key in Settings. API usage is billed by Anthropic, separately from a Claude subscription.</p>
+<h3>An integration pill stays grey</h3>
+<p>Check its key in Settings → Integrations. Up to 4 integrations can be shown at once.</p>
+<h3>No sound</h3>
+<p>Check the speaker icon in the notch header and the volume in Settings.</p>
+<h3>How do I uninstall?</h3>
+<p>Settings → Claude Code → <b>Uninstall</b> (removes only Coucou’s hooks), then quit the app and move it to the Trash. Optionally delete <code>~/Library/Application Support/NotchBuddy</code>.</p>
+</section>
+<hr>
+<section id="fr" lang="fr">
+<h1>Assistance</h1>
+<div class="card">
+<b>Signaler un bug ou proposer une idée :</b> <a href="https://github.com/OWNER/REPO/issues">ouvre une issue sur GitHub</a> (le plus rapide).<br>
+<b>E-mail :</b> <a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a>
+</div>
+<h2>Questions fréquentes</h2>
+<h3>macOS dit qu’il ne peut pas vérifier l’app (téléchargement GitHub)</h3>
+<p>Réglages Système → Confidentialité et sécurité, en bas : <b>Ouvrir quand même</b>. Ou une fois dans le Terminal : <code>xattr -dr com.apple.quarantine /Applications/Coucou.app</code>. La version App Store n’a pas cette étape.</p>
+<h3>Mochi n’affiche pas mes sessions Claude Code</h3>
+<p>Réglages → Claude Code → <b>Install hooks</b>, vérifie les changements, confirme, puis lance une nouvelle session Claude Code.</p>
+<h3>Le chat ne répond pas</h3>
+<p>Ajoute ta clé d’API Anthropic dans les Réglages. L’API est facturée par Anthropic, à part d’un abonnement Claude.</p>
+<h3>Une pastille d’intégration reste grise</h3>
+<p>Vérifie sa clé dans Réglages → Intégrations. Jusqu’à 4 intégrations s’affichent en même temps.</p>
+<h3>Pas de son</h3>
+<p>Vérifie l’icône haut-parleur dans l’en-tête du notch et le volume dans les Réglages.</p>
+<h3>Comment désinstaller ?</h3>
+<p>Réglages → Claude Code → <b>Uninstall</b> (retire seulement les hooks de Coucou), puis quitte l’app et mets-la à la corbeille. Tu peux aussi supprimer <code>~/Library/Application Support/NotchBuddy</code>.</p>
+</section>
+<footer>© 2026 Louis Raillé · Coucou is free and open source (MIT) · <a href="https://github.com/OWNER/REPO">GitHub</a> · <a href="privacy.html">Privacy</a> · <a href="terms.html">Terms</a> · <a href="legal.html">Legal notice</a></footer></div></body></html>
diff --git a/docs/terms.html b/docs/terms.html
new file mode 100644
index 00000000..6f082d85
--- /dev/null
+++ b/docs/terms.html
@@ -0,0 +1,76 @@
+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Terms of Use — Coucou</title><link rel="icon" href="media/icon.png"><link rel="stylesheet" href="site.css"></head><body><div class="wrap">
+<header><a href="index.html"><img src="media/icon.png" alt=""></a><span class="name">Coucou</span>
+<nav><a href="index.html">Home</a><a href="support.html">Support</a><a href="privacy.html">Privacy</a><a href="terms.html" class="on">Terms</a><a href="legal.html">Legal</a></nav></header>
+<div class="lang"><a href="#en">English</a><a href="#fr">Français</a></div>
+<section id="en">
+<h1>Terms of Use</h1>
+<div class="meta">Last updated: September 27, 2026</div>
+
+<h2>1. The app</h2>
+<p>Coucou is a free macOS app published by Louis Raillé. Its source code is available on <a href="https://github.com/OWNER/REPO">GitHub</a> under the MIT License. By downloading or using Coucou, you accept these terms.</p>
+
+<h2>2. Licence</h2>
+<ul>
+<li><b>Source code:</b> governed by the <a href="https://github.com/OWNER/REPO/blob/main/LICENSE">MIT License</a>.</li>
+<li><b>Mac App Store version:</b> your use is also governed by Apple’s <a href="https://www.apple.com/legal/internet-services/itunes/dev/stdeula/">Licensed Application End User License Agreement</a>. If these terms and Apple’s agreement conflict, Apple’s agreement prevails for the App Store version.</li>
+</ul>
+
+<h2>3. Your keys and third-party services</h2>
+<p>Coucou works with services you connect yourself (Anthropic, Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n). You are responsible for your accounts, your keys, complying with those services’ terms, and any costs they charge you — for example Anthropic API usage, which is billed by Anthropic.</p>
+
+<h2>4. Claude Code</h2>
+<p>Coucou can show and answer Claude Code permission requests. Approving a request from the notch has the same effect as approving it in your terminal: you remain responsible for what you allow Claude Code to do.</p>
+
+<h2>5. No warranty</h2>
+<p>Coucou is provided “as is”, without warranty of any kind. To the extent permitted by law, the developer is not liable for any damage arising from its use, including data loss, unexpected actions approved through the app, or charges from third-party services. Nothing in these terms limits rights you have under mandatory consumer protection law.</p>
+
+<h2>6. Trademarks</h2>
+<p>Claude and Claude Code are trademarks of Anthropic, PBC. Mac, macOS and Mac App Store are trademarks of Apple Inc. Stripe, GitHub, Vercel, Resend, Notion, Cal.com and n8n are trademarks of their respective owners. Coucou is an independent project and is not affiliated with, endorsed or sponsored by any of them.</p>
+
+<h2>7. Changes and termination</h2>
+<p>These terms may be updated; the new version will be published here with a new date. You can stop using Coucou at any time by deleting it.</p>
+
+<h2>8. Governing law</h2>
+<p>These terms are governed by French law, without prejudice to the mandatory rules of the country where you live.</p>
+
+<h2>9. Contact</h2>
+<p><a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a></p>
+</section>
+
+<hr>
+<section id="fr" lang="fr">
+<h1>Conditions d’utilisation</h1>
+<div class="meta">Dernière mise à jour : 27 septembre 2026</div>
+
+<h2>1. L’app</h2>
+<p>Coucou est une app macOS gratuite publiée par Louis Raillé. Son code source est disponible sur <a href="https://github.com/OWNER/REPO">GitHub</a> sous licence MIT. En téléchargeant ou en utilisant Coucou, tu acceptes ces conditions.</p>
+
+<h2>2. Licence</h2>
+<ul>
+<li><b>Code source :</b> régi par la <a href="https://github.com/OWNER/REPO/blob/main/LICENSE">licence MIT</a>.</li>
+<li><b>Version Mac App Store :</b> ton utilisation est aussi régie par le <a href="https://www.apple.com/legal/internet-services/itunes/dev/stdeula/">contrat de licence utilisateur final standard d’Apple</a>. En cas de contradiction, le contrat d’Apple prévaut pour la version App Store.</li>
+</ul>
+
+<h2>3. Tes clés et les services tiers</h2>
+<p>Coucou fonctionne avec des services que tu connectes toi-même (Anthropic, Stripe, GitHub, Vercel, Resend, Notion, Cal.com, n8n). Tu es responsable de tes comptes, de tes clés, du respect des conditions de ces services et des frais qu’ils te facturent, par exemple l’utilisation de l’API d’Anthropic, facturée par Anthropic.</p>
+
+<h2>4. Claude Code</h2>
+<p>Coucou peut afficher les demandes de permission de Claude Code et y répondre. Autoriser une demande depuis le notch a le même effet que l’autoriser dans ton terminal : tu restes responsable de ce que tu permets à Claude Code de faire.</p>
+
+<h2>5. Absence de garantie</h2>
+<p>Coucou est fourni « en l’état », sans garantie d’aucune sorte. Dans les limites permises par la loi, le développeur n’est pas responsable des dommages liés à son utilisation, notamment une perte de données, une action autorisée par erreur via l’app ou des frais facturés par un service tiers. Rien dans ces conditions ne limite les droits que te garantit le droit de la consommation.</p>
+
+<h2>6. Marques</h2>
+<p>Claude et Claude Code sont des marques d’Anthropic, PBC. Mac, macOS et Mac App Store sont des marques d’Apple Inc. Stripe, GitHub, Vercel, Resend, Notion, Cal.com et n8n sont des marques de leurs propriétaires respectifs. Coucou est un projet indépendant, sans lien avec eux et ni approuvé ni sponsorisé par eux.</p>
+
+<h2>7. Modifications et fin</h2>
+<p>Ces conditions peuvent évoluer ; la nouvelle version sera publiée ici avec une nouvelle date. Tu peux arrêter d’utiliser Coucou à tout moment en le supprimant.</p>
+
+<h2>8. Droit applicable</h2>
+<p>Ces conditions sont régies par le droit français, sans préjudice des règles impératives du pays où tu résides.</p>
+
+<h2>9. Contact</h2>
+<p><a href="mailto:CONTACT_EMAIL">CONTACT_EMAIL</a></p>
+</section>
+<footer>© 2026 Louis Raillé · Coucou is free and open source (MIT) · <a href="https://github.com/OWNER/REPO">GitHub</a> · <a href="privacy.html">Privacy</a> · <a href="terms.html">Terms</a> · <a href="legal.html">Legal notice</a></footer></div></body></html>