This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/*.pbxproj, **/*.xcworkspacedata, **/*.entitlements, **/*.plist, **/*.lock, **/*.toml, **/*.nsh, **/*.css, **/*.gif, **/*.png, **/*.ico, **/*.wav, **/*.mp4, **/*.html, **/*.yml, design/**, docs/media/**, NotchBuddy/Assets.xcassets/**, NotchBuddy/NotchBuddy.xcodeproj/**, NotchBuddy/Resources/**, scripts/**, windows/scripts/**, windows/dev/**, windows/hook/**, windows/src-tauri/icons/**, windows/src-tauri/nsis/**, windows/src-tauri/capabilities/**
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
docs/
  .nojekyll
  INTEGRATIONS.md
  SPEC.md
NotchBuddy/
  Sources/
    App/
      AppDelegate.swift
      AppLog.swift
      AppState.swift
      BotCanvasView.swift
      BotEngine.swift
      CalcomPoller.swift
      ClaudeService.swift
      FileDropView.swift
      GithubPoller.swift
      GreetingCanvasView.swift
      HookServer.swift
      IslandRootView.swift
      IslandScreenGeometry.swift
      IslandStateMachine.swift
      IslandTypes.swift
      IslandViewContent.swift
      IslandWindowController.swift
      N8nPoller.swift
      NotchBuddyApp.swift
      NotionPoller.swift
      ResendPoller.swift
      SafeWebURL.swift
      SettingsView.swift
      SoundEngine.swift
      StripePoller.swift
      UploadCanvasView.swift
      UploadSequenceEngine.swift
      VercelPoller.swift
      WindowContextCapture.swift
windows/
  src/
    core/
      anim.ts
      bridge.ts
      layout.ts
      sound.ts
      state.ts
    island/
      fsm.ts
      hooks.ts
      integrations.ts
      island.ts
    mochi/
      engine.ts
      greeting.ts
      minibots.ts
    settings/
      main.ts
    upload/
      canvas.ts
      sequence.ts
    views/
      chat.ts
      dom.ts
      icons.ts
      integrations.ts
      ticker.ts
      upload.ts
      views.ts
    main.ts
  src-tauri/
    src/
      claude.rs
      files.rs
      hooks.rs
      integrations.rs
      island.rs
      lib.rs
      log.rs
      main.rs
      pipe.rs
      secrets.rs
      settings.rs
      tray.rs
      win_user.rs
    build.rs
    tauri.conf.json
  package.json
  README.md
  tsconfig.json
  vite.config.ts
.gitattributes
CHANGELOG.md
CLAUDE.md
CONTRIBUTING.md
LICENSE
LICENSE-ASSETS.md
README.md
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path="docs/.nojekyll">

</file>

<file path="docs/INTEGRATIONS.md">
# 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` (version GitHub) ou `~/Library/Containers/fr.louisraille.Coucou/Data/nb.sock` (version App Store). Dossier en 0700, socket en 0600. Connexions du même utilisateur seulement (vérification `getpeereid`). 1 Mio et 5 s maximum par message, 32 connexions simultanées.
- `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, seulement s'il est en http ou https ; sinon le bouton est grisé), « 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.
</file>

<file path="docs/SPEC.md">
# 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 (Mac de bureau, écran externe ou capot fermé) : afficher sur l'écran principal une barre noire de 80 pt au repos (`hidden`), avec Mochi visible au centre et son animation en pause ; 240 pt en `compact`, en haut au centre. Hauteur plafonnée à 24 pt et à celle de la barre de menus ; personnage et pastilles adaptés à cette hauteur. Le salut se replie vers les dimensions réelles de la barre compacte. La zone de survol au repos ne déborde pas sous la barre. Les vues ouvertes gardent leur largeur de 640 pt.
- 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.
</file>

<file path="NotchBuddy/Sources/App/AppDelegate.swift">
final class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem?
private(set) var islandController: IslandWindowController?
⋮----
func applicationDidFinishLaunching(_ notification: Notification) {
⋮----
private func setupMenuBarItem() {
⋮----
let menu = NSMenu()
⋮----
@objc private func openIsland() {
⋮----
private var settingsWindow: NSWindow?
⋮----
@objc private func openSettings() {
⋮----
let win = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 480, height: 540),
⋮----
private func setupIsland() {
</file>

<file path="NotchBuddy/Sources/App/AppLog.swift">
func escapedForLog(_ s: String) -> String {
⋮----
let v = sc.value
⋮----
/// Appends one timestamped line to `~/Library/Logs/NotchBuddy/<fileName>`.
/// - Log directory is created at mode 0700.
/// - Log file is set to mode 0600 on first creation and after each rotation.
/// - File is rotated (truncated) when it reaches 1 MB.
func appendAppLog(_ fileName: String, _ message: String,
⋮----
let fm = FileManager.default
let logsDir = fm.urls(for: .libraryDirectory, in: .userDomainMask)[0]
⋮----
let logFile = logsDir.appendingPathComponent(fileName)
let f = DateFormatter(); f.dateFormat = timestampFormat
let line = "\(f.string(from: Date())) \(escapedForLog(message))\n"
⋮----
let maxLogBytes = 1_048_576
⋮----
let size = (try? fm.attributesOfItem(atPath: logFile.path)[.size] as? Int) ?? 0
</file>

<file path="NotchBuddy/Sources/App/AppState.swift">
static let integrationAgents: [AgentTask] = [
⋮----
static let toggleableIntegrationIds: [String] = [
⋮----
final class AppState: ObservableObject {
static let shared = AppState()
⋮----
@Published var mode: IslandMode = .hidden
@Published var view: IslandView = .overview
⋮----
@Published var tasks: [AgentTask] = []
@Published var focusId: String? = nil
⋮----
@Published var stateOverride: BotState? = nil
⋮----
var notchWidth:  CGFloat = IslandConst.notchWidth
var notchHeight: CGFloat = IslandConst.notchHeight
var hasNotch = true
⋮----
var lastExternalApp: NSRunningApplication? = nil
⋮----
@Published var isDraggingBot: Bool = false
⋮----
var mousePosition: CGPoint = .zero
var lastMouseMove: Date = .now
var lastActivity: Date = .now
var isPresent: Bool = true
⋮----
var isPinned: Bool = false
⋮----
@Published var uploadProgress: Double = 0
⋮----
var uploadStartTime: Date?
var uploadDuration: Double = 2.4
⋮----
@Published var fileDragOver: Bool = false
⋮----
@Published var soundEnabled: Bool = true {
⋮----
@Published var soundVolume: Double = 0.12 {
⋮----
@Published var promptContext: PromptContext? = nil
⋮----
@Published var droppedFile: DroppedFile? = nil
⋮----
@Published var noteMessage: String? = nil
⋮----
@Published var autoCloseInterval: TimeInterval = 15 {
⋮----
var absenceInterval: TimeInterval = 3 * 60 {
⋮----
var greetThresholdSeconds: TimeInterval = 120 {
⋮----
@Published var hotkeyEnabled: Bool = false {
⋮----
var hotkeyFlags: UInt = NSEvent.ModifierFlags([.command, .shift]).rawValue {
⋮----
var hotkeyCode: UInt16 = 45 {
⋮----
@Published var vercelProjectFilter: Set<String> = [] {
⋮----
@Published var n8nWorkflowFilter: Set<String> = [] {
⋮----
@Published var activeIntegrations: Set<String> = ["integration_resend", "integration_n8n", "integration_vercel", "integration_github"] {
⋮----
@Published var searchResult: SearchResult? = nil
⋮----
@Published var vercelDeployments: [VercelDeployment] = []
⋮----
@Published var resendEmails: [ResendEmail] = []
@Published var resendTotal: Int? = nil
⋮----
@Published var githubStats: GitHubStats? = nil
⋮----
@Published var stripePayments: [StripePayment] = []
@Published var stripeBalance: Int = 0
@Published var stripeDisplayBalance: Int = 0
@Published var stripeCurrency: String = "eur"
@Published var stripeLoaded: Bool = false
@Published var stripeError: String? = nil
⋮----
@Published var calcomBookings: [CalcomBooking] = []
@Published var calcomLoaded: Bool = false
@Published var calcomError: String? = nil
⋮----
@Published var notionPages: [NotionPage] = []
@Published var notionLoaded: Bool = false
@Published var notionError: String? = nil
⋮----
@Published var chatHistory: [ChatMessage] = []
⋮----
@Published var pendingApproval: ApprovalInfo? = nil
⋮----
private init() {
let ud = UserDefaults.standard
⋮----
var focusTask: AgentTask? {
⋮----
var effectiveState: BotState {
⋮----
func addTask(_ task: AgentTask) {
⋮----
func removeTask(id: String) {
⋮----
func updateTask(id: String, state: BotState) {
⋮----
func setFocus(_ id: String) {
⋮----
func syncMode() {
⋮----
func syncView() {
⋮----
func loadIntegrationTasks() {
⋮----
let shouldLoad = task.id == "integration_claude" || activeIntegrations.contains(task.id)
let loaded = tasks.contains(where: { $0.id == task.id })
⋮----
func toggleIntegration(_ id: String) {
⋮----
enum PromptContext {
⋮----
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?
⋮----
struct VercelDeployment: Identifiable {
let id: String
let projectName: String
let url: String
let state: String
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)
⋮----
struct ResendEmail: Identifiable {
⋮----
let to: [String]
let subject: String
⋮----
let lastEvent: String
⋮----
var recipientShort: String {
⋮----
var isDelivered: Bool { lastEvent == "delivered" }
⋮----
struct GitHubStats {
let totalRepos: Int
let totalStars: Int
⋮----
struct StripePayment: Identifiable, Equatable {
⋮----
let amount: Int
let currency: String
let description: String?
⋮----
let status: String
⋮----
var amountFormatted: String { String(format: "%.2f", Double(amount) / 100.0) }
var isSuccess: Bool { status == "succeeded" }
⋮----
struct CalcomBooking: Identifiable, Equatable {
let id: Int
let title: String
let startTime: Date
let endTime: Date
⋮----
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)
⋮----
// MARK: - Notion
⋮----
struct NotionPage: Identifiable {
⋮----
let emoji: String?
let lastEditedAt: Date
⋮----
let diff = Date().timeIntervalSince(lastEditedAt)
⋮----
enum ChatRole { case user, assistant }
⋮----
struct ChatMessage: Identifiable {
let id = UUID()
let role: ChatRole
let content: String
</file>

<file path="NotchBuddy/Sources/App/BotCanvasView.swift">
struct BotCanvasView: View {
@ObservedObject var state: AppState
var particleOverhang: CGFloat = 0
⋮----
@StateObject private var engine = BotEngine()
⋮----
var body: some View {
⋮----
let now = timeline.date.timeIntervalSinceReferenceDate
let dtRaw = min(0.05, now - engine.lastTime)
let dt = dtRaw
⋮----
let dur: CGFloat = target > 0.5 ? 550 : 650
⋮----
private func lookX(state: AppState, size: CGSize) -> CGFloat {
let screen = NSScreen.main ?? NSScreen.screens[0]
⋮----
let botScreenX = screen.frame.midX - islandW / 2 + botCx
⋮----
private func lookY(state: AppState, size: CGSize) -> CGFloat {
⋮----
let actualH: CGFloat = (state.mode == .expanded && state.view == .prompt)
⋮----
struct MiniBotCanvasView: View {
let task: AgentTask
@StateObject private var engine: BotEngine
⋮----
init(task: AgentTask) {
⋮----
let e = BotEngine()
⋮----
let dt = min(0.05, now - engine.lastTime)
⋮----
func cgColorFromHex(_ hex: String) -> CGColor? {
let h = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#"))
⋮----
let r = CGFloat((val >> 16) & 0xFF) / 255
let g = CGFloat((val >> 8)  & 0xFF) / 255
let b = CGFloat( val        & 0xFF) / 255
⋮----
static func from(_ hex: String) -> CGColor {
</file>

<file path="NotchBuddy/Sources/App/BotEngine.swift">
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 }
⋮----
struct TweenKey {
let target: CGFloat
let duration: CGFloat
let ease: (CGFloat) -> CGFloat
⋮----
struct Tween {
let property: String
var keys: [TweenKey]
var keyIndex: Int = 0
var from: CGFloat
var startTime: Double
var onComplete: (() -> Void)? = nil
⋮----
struct Particle {
enum ParticleType { case heart, star, spark, sweat, z }
var type: ParticleType
var x, y, vx, vy: CGFloat
var age: Double
var life: Double
var rot: CGFloat
var size: CGFloat
⋮----
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?
let tilt: CGFloat
let sound: String?
⋮----
enum EyeShape: String {
⋮----
enum BadgeType {
⋮----
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)
static let baseBottom = CGColor(red: 0.769, green: 0.773, blue: 0.792, alpha: 1)
static let ink        = CGColor(red: 0.102, green: 0.082, blue: 0.071, alpha: 1)
static let miniInk    = CGColor(red: 0.063, green: 0.075, blue: 0.102, alpha: 1)
⋮----
let BotStates: [BotState: BotStateCfg] = [
⋮----
final class BotEngine: ObservableObject {
var isMini: Bool = false
var bodyColor: CGColor? = nil
⋮----
var yaw:    CGFloat = 0
var pitch:  CGFloat = 0
var roll:   CGFloat = 0
var tilt:   CGFloat = 0
var open:   CGFloat = 1
var sx:     CGFloat = 1
var sy:     CGFloat = 1
var oy:     CGFloat = 0
var ox:     CGFloat = 0
var tint:   CGFloat = 0
var morph:  CGFloat = 0
var hands:  CGFloat = 0
var blush:  CGFloat = 0
var es:     CGFloat = 1
var badgeS: CGFloat = 0
⋮----
var tgYaw:    CGFloat = 0
var tgPitch:  CGFloat = 0
var tgTilt:   CGFloat = 0
var tgSy:     CGFloat = 1
var tgSx:     CGFloat = 1
var tgEs:     CGFloat = 1
⋮----
var particleOverhang: CGFloat = 0
⋮----
var slotH: CGFloat = 0
var slotHTarget: CGFloat = 0
var slotHVel: CGFloat = 0
var isChewing: Bool = false
⋮----
var col:  (CGFloat, CGFloat, CGFloat) = (0.902, 0.914, 0.933)
var colT: (CGFloat, CGFloat, CGFloat) = (0.902, 0.914, 0.933)
⋮----
var state: BotState = .idle
var cfg: BotStateCfg = BotStates[.idle]!
⋮----
var eyeOverride: EyeShape? = nil
var eyeOverrideUntil: Double = 0
var permanentEye: EyeShape? = nil
var permanentEmote: BotEmote? = nil
var miniNextBehavior: Double = 0
⋮----
var badge: BadgeType? = nil
var badgeKey: String = "none"
var badgeToken: Int = 0
⋮----
var tweens: [String: Tween] = [:]
var locks:  Set<String> = []
⋮----
var particles: [Particle] = []
⋮----
var lookX: CGFloat = 0
var lookY: CGFloat = 0
⋮----
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
var greetToken: Int = 0
var lastAmbient: Double = 0
⋮----
var slapTimes: [Double] = []
⋮----
var miniLookTarget: CGPoint = .zero
var miniLookNextTime: Double = 0
⋮----
func setState(_ newState: BotState, force: Bool = false) {
⋮----
let prev = state
⋮----
func setBadge(_ b: BadgeType?) {
let key = badgeString(b)
⋮----
let tok = badgeToken + 1
⋮----
func blink() {
⋮----
func squash() {
⋮----
func gulp() {
⋮----
func slap() {
⋮----
let now = CACurrentMediaTime()
⋮----
func doMiniBehaviorLoop() {
⋮----
let now2 = CACurrentMediaTime()
⋮----
func doRoll(duration: CGFloat, turns: CGFloat) {
⋮----
func greet() {
⋮----
let tok = greetToken
⋮----
func interruptGreet() {
⋮----
func setPermanentEmote(_ emote: BotEmote?) {
⋮----
func triggerEmote(_ emote: BotEmote, duration: Double = 1.8, silent: Bool = false) {
⋮----
func emit(_ type: Particle.ParticleType, count: Int) {
⋮----
let isZ = type == .z
let p = Particle(
⋮----
func update(dt: Double) {
⋮----
let dtCG = CGFloat(dt)
⋮----
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)
⋮----
let t = CGFloat(now - t0)
var ty: CGFloat = lookX * 0.62
var tp: CGFloat = lookY * 0.5
⋮----
let wt = CGFloat(now - waveStart)
⋮----
let bounce = cfg.bounces ? -abs(sin(t * 5.2)) * 0.07 : CGFloat(0)
⋮----
let amp: CGFloat = isMini ? 0.07 : 0.035
⋮----
let kLook = CGFloat(1 - pow(0.0025, dt))
let kGen  = CGFloat(1 - pow(0.0008, dt))
⋮----
let slotOmega: CGFloat = 2 * .pi / 0.25
let slotZeta: CGFloat = 0.6
let slotAcc = slotOmega * slotOmega * (slotHTarget - slotH)
⋮----
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
⋮----
let cy = H / 2 + particleOverhang / 2 + oy * R + R * 0.06
⋮----
var ctx = context
⋮----
let bodyPath = mochiPath(rx: rx, ry: ry, morph: morph, R: R)
⋮----
let blushVal = max(blush, tint * 0.5) * (1 - morph)
⋮----
let hW = R * 1.80 * morph
let hH = slotH * R * morph
let hX = -hW / 2
⋮----
let boxTop = -R * (0.88 + 0.06 * morph)
let hY = boxTop + R * 0.08 * morph
⋮----
var boxCtx = ctx
⋮----
var rim = Path()
⋮----
let hR = min(hW / 2, hH / 2)
var hole = Path()
⋮----
let lipR = min(hR, (hW - 2) / 2)
var lip = Path()
⋮----
func drawHandsBehind(context: GraphicsContext, size: CGSize) {
⋮----
let W = size.width, H = size.height
⋮----
let bodyH = 2 * ry
⋮----
let hew = 0.30 * ry * hands
let heh = 0.26 * ry * hands
⋮----
let hwB = rx * sx
let hhB = ry * sy
⋮----
let isWaving = now >= waveStart && waveStart > 0 && now < waveUntil
⋮----
var localX: CGFloat
var localY: CGFloat
var handRot: CGFloat = 0
⋮----
let rise = min(1.0, wt / 0.18)
let riseEased: CGFloat = 1 - pow(1 - rise, 3)
⋮----
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
⋮----
let cosT = cos(tilt), sinT = sin(tilt)
let worldX = cx + cosT * localX - sinT * localY
let worldY = cy + sinT * localX + cosT * localY
⋮----
var handCtx = context
⋮----
let handRect = CGRect(x: -hew, y: -heh, width: hew * 2, height: heh * 2)
var handPath = Path()
⋮----
let c0 = mix3(cgColorToTuple(bc), (1, 1, 1), 0.35)
let c1 = cgColorToTuple(bc)
⋮----
let c0 = cgColorToTuple(MochiConst.baseTop)
let c1 = cgColorToTuple(MochiConst.baseBottom)
⋮----
func drawHandsAndExtras(context: GraphicsContext, size: CGSize) {
⋮----
private func mochiPath(rx: CGFloat, ry: CGFloat, morph: CGFloat, R: CGFloat) -> Path {
let n = 72
let expN: CGFloat = 2.0 / 2.7
⋮----
let tw = R * 1.0
let th = R * 0.94
let tr = R * 0.42
var path = Path()
⋮----
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
⋮----
let rr = rrPoint(ca: ca, sa: sa, W: tw, H: th, cr: tr)
⋮----
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)
⋮----
let dot  = ca * cx + sa * cy
let disc = dot * dot - (cx*cx + cy*cy - cr*cr)
⋮----
let t = dot + sqrt(disc)
⋮----
let px = ca * t, py = sa * t
⋮----
let t = (ky * H) / sa
⋮----
let x = ca * t
⋮----
let t = (kx * W) / ca
⋮----
let y = sa * t
⋮----
private func drawBody(ctx: inout GraphicsContext, path: Path, R: CGFloat, rx: CGFloat, ry: CGFloat) {
⋮----
let effectiveTint = tint * (1 - morph)
⋮----
let tc = colorFromTuple(col)
⋮----
private func drawBlush(ctx: inout GraphicsContext, path: Path, rx: CGFloat, ry: CGFloat, R: CGFloat, blush: CGFloat) {
⋮----
let yOffset = sin(yaw) * rx * 0.8
⋮----
let bx = CGFloat(sd) * rx * 0.55 + yOffset
let by = ry * 0.2
var ellipse = Path()
⋮----
private func drawEyes(ctx: inout GraphicsContext, path: Path, R: CGFloat, rx: CGFloat, ry: CGFloat) {
var shape = eyeOverride ?? cfg.eye
⋮----
let eyeYaw   = CGFloat(sd) * MochiConst.eyeSp + yaw
var eyePitch = MochiConst.eyeP + pitch + roll
⋮----
let cp = cos(eyePitch)
⋮----
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
⋮----
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())
⋮----
let hh = max(h * open, w * 0.3)
var p = Path()
⋮----
var a: CGFloat = 0
⋮----
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
⋮----
let heartPath = heartShape(size: w * 1.2)
⋮----
let starPath = starShape(outer: w * 1.05, inner: w * 0.46)
⋮----
var p1 = Path()
⋮----
var p2 = Path()
⋮----
let cr = min(w / 2, hh / 2)
⋮----
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
⋮----
let phase = (now * 2.4).truncatingRemainder(dividingBy: 1)
let dotR = R * 0.22 * (1 + 0.25 * sin(phase * .pi * 2))
var outer = Path()
⋮----
var dot = Path()
⋮----
let pw: CGFloat = R * 0.72
let ph: CGFloat = R * 0.36
var pill = Path()
⋮----
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 ring = Path()
⋮----
var inner = Path()
⋮----
let text = badge == .bang(col) ? "!" : "?"
⋮----
private func drawParticles(context: GraphicsContext, size: CGSize, R: CGFloat, cx: CGFloat, cy: CGFloat) {
⋮----
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
⋮----
var drop = Path()
⋮----
func anim(_ key: String, keys: [TweenKey], onComplete: (() -> Void)? = nil) {
let current = getProperty(key)
⋮----
private func setTarget(key: String, value: CGFloat) {
⋮----
private func setProperty(_ key: String, value: CGFloat) {
⋮----
private func getProperty(_ key: String) -> CGFloat {
⋮----
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) {
⋮----
private func mix3(_ a: (CGFloat,CGFloat,CGFloat), _ b: (CGFloat,CGFloat,CGFloat), _ t: CGFloat) -> (CGFloat,CGFloat,CGFloat) {
⋮----
private func mixColor(_ a: (CGFloat,CGFloat,CGFloat), _ b: (CGFloat,CGFloat,CGFloat), _ t: CGFloat) -> (CGFloat,CGFloat,CGFloat) {
⋮----
private func colorFromTuple(_ t: (CGFloat,CGFloat,CGFloat)) -> Color {
⋮----
private func badgeString(_ b: BadgeType?) -> String {
⋮----
func hex(_ c: CGColor) -> String {
⋮----
private func emoteEyeShape(_ e: BotEmote) -> EyeShape {
⋮----
private func heartShape(size s: CGFloat) -> Path {
⋮----
private func starShape(outer ro: CGFloat, inner ri: CGFloat) -> Path {
⋮----
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)
</file>

<file path="NotchBuddy/Sources/App/CalcomPoller.swift">
final class CalcomPoller: @unchecked Sendable {
static let shared = CalcomPoller()
private var timer: DispatchSourceTimer?
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
func pollNow() { poll() }
⋮----
private func poll() {
⋮----
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)
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let msg: String
⋮----
let parsed = rawList.compactMap { self.parseBooking($0) }
⋮----
private func parseBooking(_ b: [String: Any]) -> CalcomBooking? {
let id: Int
⋮----
let title  = (b["title"] as? String) ?? "Meeting"
let status = (b["status"] as? String) ?? "accepted"
⋮----
let iso = ISO8601DateFormatter()
⋮----
var startTime = iso.date(from: startStr)
⋮----
let iso2 = ISO8601DateFormatter(); iso2.formatOptions = [.withInternetDateTime]
⋮----
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
</file>

<file path="NotchBuddy/Sources/App/ClaudeService.swift">
enum Keychain {
static let service = "fr.louisraille.NotchBuddy"
⋮----
static func save(key: String, value: String) {
⋮----
let lookup: [String: Any] = [
⋮----
let item: [String: Any] = [
⋮----
static func load(key: String) -> String? {
let query: [String: Any] = [
⋮----
var result: AnyObject?
⋮----
static func delete(key: String) {
⋮----
final class KeychainStore: @unchecked Sendable {
static let shared = KeychainStore()
private var cache: [String: String] = [:]
private let lock = NSLock()
⋮----
private static let allKeys = [
⋮----
private init() {
⋮----
func get(_ key: String) -> String? {
⋮----
func set(_ key: String, value: String) {
⋮----
func remove(_ key: String) {
let had = lock.withLock { () -> Bool in
let exists = cache[key] != nil
⋮----
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") }
⋮----
private var conversationMessages: [[String: Any]] = []
⋮----
func clearConversation() {
⋮----
private let systemPrompt = """
⋮----
private let webSearchTools: [[String: Any]] = [
⋮----
func chat(query: String, context: PromptContext?, state: AppState) async {
⋮----
var userContent: [[String: Any]] = []
⋮----
var text = "Context — App: \(app), Window: \(title)"
⋮----
let body: [String: Any] = [
⋮----
let data = try await callAPI(body: body, key: key, beta: "web-search-2025-03-05")
⋮----
func search(query: String, context: PromptContext?, state: AppState) async {
⋮----
var text = "App: \(appName)\nWindow title: \(title)"
⋮----
let system = """
⋮----
let tools: [[String: Any]] = [
⋮----
let result = try await callAPI(body: body, key: key, beta: "web-search-2025-03-05")
⋮----
private func callAPI(body: [String: Any], key: String, beta: String? = nil) async throws -> Data {
var request = URLRequest(url: endpoint)
⋮----
let msg = String(data: data, encoding: .utf8) ?? "unknown error"
⋮----
private func handleChatResult(_ data: Data, state: AppState) async {
⋮----
private func handleResult(_ data: Data, state: AppState) async {
⋮----
let cleanText: String
⋮----
let title  = parsed["title"] as? String ?? "Result"
let note   = parsed["note"] as? String
var items: [ResultItem] = []
⋮----
let lines = cleanText.components(separatedBy: "\n").filter { !$0.isEmpty }.prefix(3)
⋮----
private func showError(_ message: String, state: AppState) async {
⋮----
// MARK: - File content block builder
⋮----
private func readFileAsBlock(url: URL) -> [String: Any]? {
⋮----
let ext = url.pathExtension.lowercased()
let base64 = data.base64EncodedString()
</file>

<file path="NotchBuddy/Sources/App/FileDropView.swift">
final class FileDropNSView: NSView {
var onDragEntered: ((CGPoint) -> Void)?
var onDragUpdated: ((CGPoint) -> Void)?
var onDragExited:  (() -> Void)?
var onFilesDropped: (([URL]) -> Void)?
⋮----
override init(frame: NSRect) {
⋮----
required init?(coder: NSCoder) { fatalError() }
⋮----
override func hitTest(_ point: NSPoint) -> NSView? { nil }
⋮----
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
⋮----
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
⋮----
override func draggingExited(_ sender: NSDraggingInfo?) { onDragExited?() }
⋮----
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
⋮----
enum FileDropHandler {
⋮----
static func handle(urls: [URL], state: AppState) async {
⋮----
let name = url.lastPathComponent
⋮----
let dur = 2.4
⋮----
let inbox = HookServer.supportDir.appendingPathComponent("inbox")
⋮----
let dest = inbox.appendingPathComponent(name)
⋮----
let preProgress = USC.T_PROG_START - USC.T_DROP
⋮----
var lastTens = 0
let progStart = Date().addingTimeInterval(preProgress)
⋮----
let approxP = min(1.0, max(0, Date().timeIntervalSince(progStart) / dur))
let tens = Int(approxP * 10)
</file>

<file path="NotchBuddy/Sources/App/GithubPoller.swift">
final class GithubPoller: @unchecked Sendable {
static let shared = GithubPoller()
private var timer: DispatchSourceTimer?
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
private func poll() {
⋮----
private func fetchUser(token: String) {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let publicRepos  = (json["public_repos"]       as? Int) ?? 0
let privateOwned = (json["owned_private_repos"] as? Int)
⋮----
let totalRepos = publicRepos + privateOwned
⋮----
private func fetchStars(token: String, totalRepos: Int) {
⋮----
var req = URLRequest(url: url, timeoutInterval: 15)
⋮----
let totalStars = repos.reduce(0) { $0 + ((($1["stargazers_count"] as? Int) ?? 0)) }
</file>

<file path="NotchBuddy/Sources/App/GreetingCanvasView.swift">
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
static let autoLeave:Double = 4.90
static let COLLAPSE: Double = 0.34
⋮----
private let GC0     = CGPoint(x: 320, y: 90)
private let GHB:    CGFloat = 58
private let GASP:   CGFloat = 1.34
private let GEAR_X: CGFloat = 40
private let GEAR_HB:CGFloat = 17
private let GCARD   = CGRect(x: 10, y: 36, width: 620, height: 104)
private let GCARD_R:CGFloat = 20
⋮----
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 {
⋮----
static func back(_ t: Double)  -> Double {
let c1=1.70158, c3=c1+1
⋮----
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 }
⋮----
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
⋮----
var iw, ih: Double
⋮----
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 {
⋮----
let rings = [0.10, 0.20, 0.30, 0.45, 0.60].map { t0 in
⋮----
let cols = ["#3B9EFF","#F29B38","#FF5A4E","#2EC4A0","#A78BFA"]
let streaks = (0..<16).map { i in
⋮----
private func greetPose(_ t: Double, compact: IslandRestingLayout) -> GreetPose {
⋮----
let gx = gSeg(t, 0, 0.5)
let g  = sin(.pi*gx/2) + 0.04*sin(.pi*gx)*gx
let iw = gLerp(Double(compact.width - 160), 640, g)
let ih = gLerp(Double(compact.height), 150, g)
⋮----
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(Double(compact.botCenterY), Double(GC0.y), GE.out(gSeg(t, 0.02, GT.grow)))
var sx = 1.0, sy = 1.0, tilt = 0.0
⋮----
let k = sin(.pi*gSeg(t, GT.dip0, GT.pop1))
⋮----
let w = t - GT.pop1
let fade = 1 - gSeg(t, GT.tuck0, GT.tuck1)
⋮----
var eye: GEyeType = .dot
⋮----
var eyeRoll = 0.0
⋮----
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))
⋮----
var lookX = 0.0, lookY = 0.0
⋮----
let k = GE.inOut(gSeg(t, GT.down1, GT.down1+0.35))
⋮----
let handL = t < GT.tuck0
⋮----
let handR = t < GT.tuck0
⋮----
let wave = (t >= GT.pop1 && t < GT.tuck0) ? t - GT.pop1 : -1.0
⋮----
private func smallPose(_ compact: IslandRestingLayout) -> GreetPose {
let sw = Double(compact.width)
⋮----
private func pose(_ t: Double, tc: Double, compact: IslandRestingLayout) -> GreetPose {
⋮----
let a = greetPose(tc, compact: compact)
let b = smallPose(compact)
let e = GE.inOut(gSeg(t, tc, tc + GT.COLLAPSE))
var p = a
⋮----
let bk = gSeg(t, tc+0.14, tc+0.26)
⋮----
private func gHex(_ hex: String, alpha: CGFloat = 1) -> CGColor {
let h = hex.trimmingCharacters(in: CharacterSet(charactersIn:"#"))
let v = UInt64(h, radix: 16) ?? 0
⋮----
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))
⋮----
private func mochiPath(hw: CGFloat, hh: CGFloat) -> CGPath {
let n: CGFloat = 3.2
let path = CGMutablePath()
let steps = 96
⋮----
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)
⋮----
private func whiteFill(_ ctx: CGContext, _ path: CGPath,
⋮----
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)
⋮----
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)
⋮----
let circ = CGPath(ellipseIn: CGRect(x: -r, y: -r, width: r*2, height: r*2), transform: nil)
⋮----
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
⋮----
let w = p.wave*2 * .pi*2.5
⋮----
let cap = CGMutablePath()
⋮----
private func drawMochi(_ ctx: CGContext, p: GreetPose) {
let hh = CGFloat(p.hb/2), hw = hh*GASP; guard hh > 0.4 else { return }
⋮----
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)
⋮----
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)
⋮----
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)
⋮----
let mpath = mochiPath(hw: hw, hh: hh)
⋮----
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)
⋮----
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
⋮----
let bs = CGFloat(p.badge)
let br = hh*0.3
⋮----
private func drawParticles(_ ctx: CGContext, t: Double, tc: Double, p: GreetPose) {
⋮----
let fx = p.fx
⋮----
let k = gSeg(t, ring.t0, ring.t0 + 1.35)
⋮----
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)
⋮----
let r: CGFloat = 1 + CGFloat(dot.j)
⋮----
let dx = CGFloat(GC0.x) + cos(CGFloat(dot.a))*rx*r
let dy = CGFloat(GC0.y) + sin(CGFloat(dot.a))*ry*r
⋮----
let k = gSeg(t, s.t0, s.t0 + 0.6)
⋮----
let dist = CGFloat(s.sp * GE.out(k) * 0.9 + 10)
let alpha = CGFloat((1-k) * fx)
⋮----
let a = CGFloat(s.a)
⋮----
private func drawHeader(_ ctx: CGContext, alpha: Double) {
⋮----
private let miniColors = ["#E86A6A","#3E86E0","#EFAE5A","#8C73F2"]
⋮----
private func drawMinis(_ ctx: CGContext, alpha: Double, compact: IslandRestingLayout) {
⋮----
let cx = 320 - compact.width/2 + compact.miniGridCenterX
let cy = compact.botCenterY
let sp: CGFloat = 6 * compact.miniGridScale
let offsets: [(CGFloat, CGFloat)] = [(-sp,-sp),(sp,-sp),(-sp,sp),(sp,sp)]
⋮----
let scale = CGFloat(alpha) * compact.miniGridScale
⋮----
private func drawGreeting(_ ctx: CGContext, size: CGSize, t: Double, tc: Double, compact: IslandRestingLayout) {
let p = pose(t, tc: tc, compact: compact)
⋮----
struct GreetingCanvasView: View {
@ObservedObject var state: AppState
⋮----
@State private var startDate = Date()
@State private var tc: Double = .infinity
@State private var greetFired = false
⋮----
@State private var soundWork1: DispatchWorkItem? = nil
@State private var soundWork2: DispatchWorkItem? = nil
@State private var doneWork:   DispatchWorkItem? = nil
⋮----
var body: some View {
⋮----
let t = timeline.date.timeIntervalSince(startDate)
⋮----
let t = Date().timeIntervalSince(startDate)
⋮----
private func fireGreetComplete() {
⋮----
private func scheduleWorks() {
func schedule(_ delay: Double, _ block: @escaping () -> Void) -> DispatchWorkItem {
let item = DispatchWorkItem(block: block)
⋮----
private func cancelWorks() {
</file>

<file path="NotchBuddy/Sources/App/HookServer.swift">
static let shared = HookServer()
⋮----
static var supportDir: URL {
⋮----
static var socketPath: String {
⋮----
static var hookScriptPath: String { supportDir.appendingPathComponent("nb-hook").path }
⋮----
private static let maxPayload = 1_048_576
private static let receiveTimeoutSeconds: Int = 5
private static let maxConnections = 32
⋮----
private var serverFD: Int32 = -1
private let connectionLock = NSLock()
private var connectionCount = 0
private var pendingApprovalFD: Int32 = -1
private var activeSessionId: String? = nil
⋮----
func start() {
⋮----
let dir = Self.supportDir
⋮----
private func serverThread() {
let path = Self.socketPath
⋮----
let maxSunPathBytes = MemoryLayout<sockaddr_un>.size - MemoryLayout<sa_family_t>.size - 1
⋮----
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
⋮----
var addr = sockaddr_un()
⋮----
let cpath = Array(path.utf8CString)
⋮----
let bindRC = withUnsafePointer(to: &addr) { ptr in
⋮----
let clientFD = Darwin.accept(fd, nil, nil)
⋮----
var euid: uid_t = 0
var egid: gid_t = 0
⋮----
let count = connectionCount
⋮----
private func handleClient(fd: Int32) {
⋮----
var tv = timeval(tv_sec: Self.receiveTimeoutSeconds, tv_usec: 0)
⋮----
var raw = Data()
var buf = [UInt8](repeating: 0, count: 4096)
⋮----
let n = recv(fd, &buf, buf.count, 0)
⋮----
let eventName = payload["hook_event_name"] as? String ?? ""
⋮----
// MARK: - Event → AppState
// All Claude Code events route to the permanent "integration_claude" task.
⋮----
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") ||
⋮----
let focused = state.focusId == "integration_claude"
⋮----
let tool = payload["tool_name"] as? String ?? "Tool"
let input = payload["tool_input"] as? [String: Any] ?? [:]
let step = frenchStep(tool: tool, input: input)
⋮----
let message = payload["message"] as? String ?? ""
let lower = message.lowercased()
⋮----
private func expandIfNeeded(to view: IslandView) {
⋮----
let isAlert: Bool
⋮----
private func processPermissionRequest(fd: Int32, payload: [String: Any]) {
⋮----
let cwd       = payload["cwd"]        as? String ?? ""
let rawName   = URL(fileURLWithPath: cwd).lastPathComponent
⋮----
var command = tool
⋮----
let old = pendingApprovalFD
⋮----
let captured = fd
⋮----
func sendApprovalDecision(_ decision: String) {
let fd = pendingApprovalFD
⋮----
let json: String
⋮----
private func upsertTask(projectName: String, cwd: String = "") {
⋮----
private func setPillBadge(id: String, badge: PillBadge) {
⋮----
private func clearPillBadge(id: String) {
⋮----
private func clearSession() {
⋮----
private func appendStep(id: String, step: String) {
⋮----
private func aliasProjectName(_ name: String) -> String {
let aliases: [String: String] = [
⋮----
private func frenchStep(tool: String, input: [String: Any]) -> String {
let labels: [String: String] = [
⋮----
let label = labels[tool] ?? tool
⋮----
let short = String(cmd.prefix(40))
⋮----
private func nbLog(_ message: String) {
⋮----
private func sendLine(fd: Int32, text: String) {
let bytes = Array((text + "\n").utf8)
⋮----
var sent = 0
⋮----
let n = Darwin.send(fd, buffer.baseAddress! + sent, buffer.count - sent, 0)
⋮----
let settingsURL = FileManager.default.homeDirectoryForCurrentUser
⋮----
let data = try buildHooksData()
⋮----
/// Writes the hooks to disk (call after user confirms preview).
⋮----
let formatter = DateFormatter()
⋮----
let stamp = formatter.string(from: Date())
let backupURL = settingsURL.deletingLastPathComponent()
⋮----
var settings: [String: Any] = [:]
⋮----
let hookPath = Self.hookScriptPath
⋮----
var existing = hooks[event] as? [[String: Any]] ?? []
⋮----
let newData = try JSONSerialization.data(withJSONObject: settings, options: [.prettyPrinted, .sortedKeys])
⋮----
let data = try buildHooksData(claudeURL: claudeURL)
⋮----
let coucouDir = claudeURL.appendingPathComponent("coucou")
⋮----
let wrapperURL = coucouDir.appendingPathComponent("nb-hook")
⋮----
let pyURL = coucouDir.appendingPathComponent("nb-hook.py")
⋮----
let settingsURL = claudeURL.appendingPathComponent("settings.json")
⋮----
let backupURL = claudeURL.appendingPathComponent("settings.json.bak-\(formatter.string(from: Date()))")
⋮----
let hookPath = claudeURL.appendingPathComponent("coucou/nb-hook").path
let quotedCmd = "/bin/sh \"\(hookPath.replacingOccurrences(of: "\"", with: "\\\""))\""
let events: [(String, Int)] = [
⋮----
var hooks = settings["hooks"] as? [String: Any] ?? [:]
</file>

<file path="NotchBuddy/Sources/App/IslandRootView.swift">
struct IslandRootView: View {
@EnvironmentObject var state: AppState
⋮----
var body: some View {
⋮----
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
⋮----
@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
⋮----
private var earOffset: CGFloat { max(0, -islandTopRadius) }
⋮----
let uploadActive = state.mode == .expanded
⋮----
let greetingActive = state.mode == .expanded && state.view == .greeting
⋮----
let shrinking = modeOrder(newMode) < modeOrder(oldMode)
let anim = shrinking ? closeEase : openSpring
⋮----
let cr  = newMode == .expanded ? IslandConst.expandedCorner : IslandConst.roundedCorner
let tr: CGFloat = 0
⋮----
let uploadViews: Set<IslandView> = [.upload, .uploading, .choose]
⋮----
private func modeOrder(_ m: IslandMode) -> Int {
⋮----
struct IslandShape: Shape {
var width: CGFloat
var height: CGFloat
var cornerRadius: CGFloat
var topRadius: CGFloat
⋮----
var animatableData: AnimatablePair<AnimatablePair<AnimatablePair<CGFloat, CGFloat>, CGFloat>, CGFloat> {
⋮----
func path(in rect: CGRect) -> Path {
let cr = max(0, cornerRadius)
var p  = Path()
⋮----
let tr = min(topRadius, min(width / 2, height / 2))
⋮----
let er = -topRadius
⋮----
struct BotPlacement: View {
⋮----
let islandW: CGFloat
let islandH: CGFloat
⋮----
let canvasSize = diameter / 0.6
let overhang: CGFloat = 40
let isUploading = state.view == .uploading
⋮----
let elapsed: Double = {
⋮----
let t = min(1.0, max(0, elapsed / state.uploadDuration))
⋮----
let uploadCx = 36 + CGFloat(t * (2 - t)) * 526
⋮----
private func botGlowColor(_ s: BotState) -> Color {
⋮----
private func botGlowOpacity(_ s: BotState) -> Double {
⋮----
func botPosition(mode: IslandMode, view: IslandView, islandW: CGFloat, islandH: CGFloat, uploadProgress: Double, hasNotch: Bool = true) -> (CGFloat, CGFloat, CGFloat, Double) {
let resting = IslandRestingLayout(width: islandW, height: islandH)
⋮----
let layout = IslandConst.viewLayouts[view]!
let diameter = layout.botDiameter
⋮----
let cx = 36 + CGFloat(uploadProgress) * 526
⋮----
let cx = layout.botX
let cy: CGFloat
⋮----
let headerBottom: CGFloat = 42
let cardH: CGFloat = 84
⋮----
struct CountdownBar: View {
⋮----
@State private var barWidth: CGFloat = 0
@State private var timer: Timer? = nil
⋮----
private func startTimer() {
⋮----
private func updateBar() {
⋮----
let autoClose = state.autoCloseInterval
let window = min(10.0, autoClose * 0.6)
let elapsed = Date.now.timeIntervalSince(state.lastActivity)
let remaining = autoClose - elapsed
⋮----
struct IslandContentView: View {
⋮----
let active = state.view == v
⋮----
let isTall = v == .prompt || (v == .mail && active)
let anim: Animation = active
⋮----
struct IslandHeader: View {
⋮----
struct TabButton: View {
let icon: String
let view: IslandView
⋮----
var preAction: (() -> Void)? = nil
@State private var isHovered = false
⋮----
private var isOn: Bool {
⋮----
struct CompactMiniGrid: View {
⋮----
private var others: [AgentTask] {
⋮----
let cols = [GridItem(.fixed(12), spacing: 4), GridItem(.fixed(12), spacing: 4)]
⋮----
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
</file>

<file path="NotchBuddy/Sources/App/IslandScreenGeometry.swift">
struct IslandScreenGeometry {
static let fallbackNotchWidth: CGFloat = 184
private static let noNotchWidth: CGFloat = 80
private static let noNotchHeight: CGFloat = 24
⋮----
let hasNotch: Bool
let width: CGFloat
let height: CGFloat
⋮----
init(screenWidth: CGFloat, safeAreaTop: CGFloat,
⋮----
let measuredWidth = screenWidth - left - right
⋮----
struct IslandRestingLayout {
⋮----
var botDiameter: CGFloat { min(20, max(0, height - 6)) }
var botCenterY: CGFloat { height / 2 }
var miniGridScale: CGFloat { min(1, max(0, height - 4) / 28) }
var miniGridCenterX: CGFloat { width - 40 }
</file>

<file path="NotchBuddy/Sources/App/IslandStateMachine.swift">
final class IslandStateMachine {
⋮----
enum State: Equatable {
⋮----
private(set) var state: State = .hidden
⋮----
var onTransition: ((State, State) -> Void)?
⋮----
var homeToPetitDelay: TimeInterval = 15
⋮----
var petitToHiddenDelay: TimeInterval = 60
⋮----
var greetAutoCollapseDelay: TimeInterval = 0.6
⋮----
var greetHoverCollapseDelay: TimeInterval = 10
⋮----
private var petitHideWork: DispatchWorkItem?
private var homeCollapseWork: DispatchWorkItem?
private var greetCollapseWork: DispatchWorkItem?
⋮----
func launch() {
⋮----
func mouseEntered() {
⋮----
func mouseLeft() {
⋮----
func click() {
⋮----
func greetComplete() {
⋮----
private func scheduleGreetCollapse(delay: TimeInterval) {
⋮----
let item = DispatchWorkItem { [weak self] in
⋮----
func reveal() {
⋮----
private func schedulePetitHide() {
⋮----
private func scheduleHomeCollapse() {
⋮----
func cancelTimers() {
⋮----
private func transition(to new: State) {
⋮----
let old = state
</file>

<file path="NotchBuddy/Sources/App/IslandTypes.swift">
enum IslandMode: String, CaseIterable {
⋮----
enum IslandView: String, CaseIterable {
⋮----
enum BotState: String, CaseIterable {
⋮----
enum BotEmote: String, CaseIterable {
⋮----
struct ApprovalInfo: Sendable {
var sessionId: String
var tool: String
var command: String
⋮----
enum PillBadge { case approval, finished, error }
⋮----
struct AgentTask: Identifiable, Equatable {
var id: String
var name: String
var color: String
var state: BotState
var stepIndex: Int = 0
var steps: [String]
var source: AgentSource
var isIntegration: Bool = false
var emote: BotEmote? = nil
var miniEye: EyeShape? = nil
var pillBadge: PillBadge? = nil
var sessionCwd: String?  = nil
⋮----
enum AgentSource: Equatable {
⋮----
struct ViewLayout {
let height: CGFloat
let botX: CGFloat
let botY: CGFloat?
let botDiameter: CGFloat
let agentMode: AgentLayoutMode
⋮----
enum AgentLayoutMode {
⋮----
enum IslandConst {
static let notchWidth: CGFloat  = IslandScreenGeometry.fallbackNotchWidth
static let notchHeight: CGFloat = 32
static let expandedWidth: CGFloat = 640
static let earRadius: CGFloat   = 14
static let roundedCorner: CGFloat = 14
static let expandedCorner: CGFloat = 22
⋮----
static let viewLayouts: [IslandView: ViewLayout] = [
⋮----
static let projectColors: [String: String] = [
⋮----
static let fallbackColors = ["#22C55E", "#EAB308", "#60A5FA", "#E879F9"]
⋮----
struct IntegrationMeta {
let id: String
let name: String
let color: String
⋮----
static let allIntegrations: [IntegrationMeta] = [
⋮----
static func colorForProject(_ name: String) -> String {
let key = name.lowercased().trimmingCharacters(in: .whitespaces)
⋮----
static let washColors: [IslandView: String] = [
</file>

<file path="NotchBuddy/Sources/App/IslandViewContent.swift">
struct IslandViewContent: View {
let view: IslandView
@ObservedObject var state: AppState
⋮----
var body: some View {
⋮----
struct OverviewView: View {
⋮----
@State private var showingN8nDetail = false
⋮----
var agent: AgentTask? { state.focusTask }
⋮----
private func openAgentTarget(_ task: AgentTask?) {
⋮----
let vscodeBundleId = "com.microsoft.VSCode"
⋮----
struct EmptyStateView: View {
⋮----
struct ApprovalView: View {
⋮----
var approval: ApprovalInfo? { state.pendingApproval }
⋮----
struct QuestionView: View {
⋮----
struct ErrorView: View {
⋮----
struct FinishedView: View {
⋮----
let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2", "net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
let activated = terminalBundleIds.compactMap { id in
⋮----
struct ConfusedView: View {
⋮----
struct UploadView: View {
⋮----
@State private var dashPhase: CGFloat = 0
@State private var breathAngle: Double = 0
⋮----
@State private var animTimer: Timer? = nil
⋮----
private var borderOpacity: Double {
let breathe = 0.11 + 0.04 * (sin(breathAngle) * 0.5 + 0.5)
⋮----
private func startTimer() {
⋮----
private func stopTimer() {
⋮----
struct UploadingView: View {
⋮----
private let barLeft: CGFloat  = 26
private let barWidth: CGFloat = 526
private let barTop: CGFloat   = 58
⋮----
let elapsed: Double = {
⋮----
let t        = min(1.0, max(0, elapsed / state.uploadDuration))
let progress = CGFloat(t * (2 - t))
let fillWidth = max(0, barWidth * progress)
let isDone   = state.uploadProgress >= 0.999
⋮----
struct ChooseView: View {
⋮----
let fileName = state.droppedFile?.name ?? "file"
⋮----
@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
⋮----
private func sendMail() {
⋮----
let subj = subject.isEmpty ? (state.droppedFile?.name ?? "File") : subject
⋮----
let apiKey  = KeychainStore.shared.get("resend-api-key")
let fromAddr = KeychainStore.shared.get("resend-from")
⋮----
let recipient = to
let msgBody  = bodyText
let fileURL  = state.droppedFile?.url
⋮----
let ok = await sendViaResend(apiKey: apiKey, from: fromAddr,
⋮----
// API key set but no sender — guide user instead of silent fallback
⋮----
// No Resend — fallback to Mail
⋮----
var items: [Any] = [bodyText.isEmpty ? " " : bodyText]
⋮----
func asEscape(_ s: String) -> String {
⋮----
let bodyLines = bodyText.isEmpty ? [""] : bodyText.components(separatedBy: "\n")
let bodyExpr = bodyLines.map { "\"\(asEscape($0))\"" }.joined(separator: " & linefeed & ")
⋮----
let attachBlock: String
⋮----
let escapedPath = asEscape(url.path)
⋮----
let script = """
⋮----
var err: NSDictionary?
⋮----
@State private var text: String = ""
@FocusState private var focused: Bool
⋮----
private func sendMessage() {
let query = text.trimmingCharacters(in: .whitespacesAndNewlines)
⋮----
let message: ChatMessage
⋮----
var label: String {
⋮----
let openURL = safeWebURL(result.items.first?.url)
⋮----
let text = result.items.map { "\($0.label): \($0.detail)" }.joined(separator: "\n")
⋮----
// MARK: - Integration card (overview left card when an integration pill is focused)
⋮----
let task: AgentTask
@Binding var showingDetail: Bool
@ObservedObject private var appState = AppState.shared
⋮----
private var isConfigured: Bool {
⋮----
let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude/settings.json")
⋮----
let cmd = $0["command"] as? String
⋮----
private var openURL: URL? {
⋮----
private var vsCodeSessionActive: Bool {
⋮----
private var n8nHasActivity: Bool {
⋮----
private var vercelHasActivity: Bool {
⋮----
private var resendHasData: Bool {
⋮----
private var githubHasData: Bool {
⋮----
private var stripeHasData: Bool {
⋮----
private var calcomHasData: Bool {
⋮----
private var notionHasData: Bool {
⋮----
let stripeErr = task.id == "integration_stripe" ? appState.stripeError
⋮----
let dot = stripeErr != nil ? Color(hex: "#F4505E")
⋮----
let label = stripeErr ?? (isConfigured ? "Connected · loading…" : "Key not configured")
⋮----
let success = task.state == .finished
let accent  = success ? Color(hex: "#22C55E") : Color(hex: "#F4505E")
⋮----
private func openVSCode() {
let ids = ["com.microsoft.VSCode", "com.microsoft.VSCodeInsiders", "com.vscodium.codium"]
let appURL = ids.compactMap { NSWorkspace.shared.urlForApplication(withBundleIdentifier: $0) }.first
⋮----
let deployments: [VercelDeployment]
let onOpenDetail: () -> Void
⋮----
let accent = Color(hex: first.isSuccess ? "#22C55E" : "#F4505E")
⋮----
let accent = Color(hex: dep.isSuccess ? "#22C55E" : "#F4505E")
⋮----
let deployment: VercelDeployment
let onClose: () -> Void
⋮----
private var accent: Color { Color(hex: deployment.isSuccess ? "#22C55E" : "#F4505E") }
⋮----
let emails: [ResendEmail]
let total: Int?
⋮----
let accent = Color(hex: first.isDelivered ? "#22C55E" : "#F4505E")
⋮----
let accent = Color(hex: email.isDelivered ? "#22C55E" : "#F4505E")
⋮----
let stats: GitHubStats
⋮----
private func formatCount(_ n: Int) -> String {
⋮----
let icon: String
let color: String
let label: String
let value: String
⋮----
private var balanceFormatted: String {
⋮----
let payment: StripePayment
⋮----
let accent = payment.isSuccess ? Color(hex: "#22C55E") : Color(hex: "#F4505E")
⋮----
@State private var selectedBooking: CalcomBooking? = nil
@State private var displayMonth: Date = Date()
@State private var displayHalf: Int = 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!))"
⋮----
@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"
⋮----
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?] = []
⋮----
private var visibleWeeks: [[Date?]] {
let all = allWeeks
let splitAt = 2
⋮----
private func hasBookings(_ d: Date) -> Bool {
let c = cal.dateComponents([.year, .month, .day], from: d)
⋮----
private func goBack() {
⋮----
private func goForward() {
⋮----
let week: [Date?]
let hasBookings: (Date) -> Bool
let isToday: (Date) -> Bool
⋮----
private var weekLabel: String {
⋮----
let f = DateFormatter(); f.dateFormat = "dd/MM"
⋮----
let day: Date
let hasEvents: Bool
let isToday: Bool
⋮----
let date: Date
⋮----
let onSelect: (CalcomBooking) -> Void
let onBack: () -> Void
⋮----
private var dayLabel: String {
let f = DateFormatter(); f.dateFormat = "EEEE d MMMM"; return f.string(from: date)
⋮----
let booking: CalcomBooking
⋮----
let text: String
var size: CGFloat = 11
var truncate: Bool = false
var lines: Int = 1
⋮----
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 }
⋮----
let task: AgentTask?
⋮----
@State private var rowA: String = "…"
@State private var rowB: String = "…"
@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 ?? []
⋮----
// Row A: completed row — always rendered at phase=1 + completedScale
⋮----
// Row B: current step → animates diagonally up-left, phase 0→1, scale 1→completedScale
⋮----
// Row C: incoming new step — slides in from below at phase=0
⋮----
let idx = task?.stepIndex ?? -1
⋮----
let newIdx = task.stepIndex
⋮----
private func tickerAnimate(to newIdx: Int) {
⋮----
// Old completed (rowA): fades + slides further up
⋮----
// Current (rowB): moves diagonally up-left + shrinks to completed size
⋮----
// New current (rowC): slides in from below
⋮----
let phase: Double   // 0 = current (shimmer, large), 1 = completed (dim, scaled down by caller)
⋮----
// Icon: chevron fades out first half, checkmark fades in second half
⋮----
let t = tl.date.timeIntervalSinceReferenceDate
let p = CGFloat(t.truncatingRemainder(dividingBy: 2.2) / 2.2)
⋮----
let phase = p * 1.2 - 0.1
⋮----
@State private var swapping = false
⋮----
private var others: [AgentTask] {
⋮----
private var displayTasks: [AgentTask] {
⋮----
private let columns = [
⋮----
@Binding var swapping: Bool
let onTap: () -> Void
@State private var isHovered = false
⋮----
private var displayName: String {
⋮----
let badge: PillBadge
let taskColor: String
⋮----
private var badgeColor: Color {
⋮----
private var icon: String {
⋮----
var others: [AgentTask] {
⋮----
enum Wash { case red, green, pink, amber, cyan, indigo, soft }
⋮----
let wash: Wash?
let content: (() -> Content)?
⋮----
var washColor: Color {
⋮----
let context: PromptContext
@State private var glowing = false
⋮----
let placeholder: String
@Binding var text: String
⋮----
let title: String
let kbd: String?
let action: () -> Void
⋮----
func makeBody(configuration: Configuration) -> some View {
⋮----
private var claudeConnected: Bool {
let url = FileManager.default.homeDirectoryForCurrentUser
⋮----
private var apiConnected: Bool {
⋮----
let ok: Bool
⋮----
func lighter(by amount: Double) -> Color {
</file>

<file path="NotchBuddy/Sources/App/IslandWindowController.swift">
private var islandPanel: IslandPanel!
private var state: AppState { AppState.shared }
⋮----
let fsm = IslandStateMachine()
⋮----
private var wasInIsland = false
private var frameTimer: Timer?
private var keyMonitor: Any?
private var viewSubscription: AnyCancellable?
⋮----
private var confusedRecoveryTimer: DispatchWorkItem?
⋮----
private var finishedPinTimer: DispatchWorkItem?
⋮----
private var hoverTimer: DispatchWorkItem?
private var botHoverTimer: DispatchWorkItem?
private var botHovering: Bool = false
private var lastLoveTime: Double = 0
private var botHoverStartPos: CGPoint = .zero
⋮----
private var attachDragStart: NSPoint? = nil
private var pendingIslandClick = false
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
⋮----
private var notchW: CGFloat = IslandConst.notchWidth
private var notchH: CGFloat = IslandConst.notchHeight
private var hasNotch = true
⋮----
let screen = Self.notchScreen() ?? NSScreen.main!
let geometry = Self.screenGeometry(for: screen)
let nW = geometry.width
let nH = geometry.height
⋮----
let panelW: CGFloat = 720
let panelH: CGFloat = 320
let sf = screen.frame
let panel = IslandPanel(
⋮----
private func setupPanel(screen: NSScreen) {
⋮----
let contentSize = panel.contentRect(forFrameRect: panel.frame).size
⋮----
let container = NSView(frame: NSRect(origin: .zero, size: contentSize))
⋮----
let hosting = NSHostingView(rootView: IslandRootView().environmentObject(AppState.shared))
⋮----
let dropView = FileDropNSView(frame: NSRect(origin: .zero, size: contentSize))
⋮----
let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
⋮----
private func wireFSM() {
⋮----
private func startPolling() {
⋮----
private func pollFrame() {
⋮----
let mouse = NSEvent.mouseLocation
⋮----
let pf = panel.frame
let local = CGPoint(x: mouse.x - pf.minX, y: mouse.y - pf.minY)
⋮----
let islandRect = panel.currentIslandFrame(nw: notchW, nh: notchH)
⋮----
let hoverRect = !hasNotch && state.mode != .expanded
⋮----
let inIsland = hoverRect.contains(local)
⋮----
let shouldAcceptMouse = inIsland || inAttachDrag || attachDragStart != nil
⋮----
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
⋮----
let overBot = state.mode == .expanded && state.stateOverride == nil && isBotHit(local)
⋮----
let m = NSEvent.mouseLocation
let dist = hypot(m.x - botHoverStartPos.x, m.y - botHoverStartPos.y)
⋮----
private var lastMouse: CGPoint = .zero
⋮----
private func botHoverIn(mousePos: CGPoint) {
⋮----
private func botHoverOut() {
⋮----
private func scheduleLoveTimer() {
⋮----
let item = DispatchWorkItem { [weak self] in
⋮----
private func scheduleHover(after delay: TimeInterval, action: @escaping () -> Void) {
⋮----
let item = DispatchWorkItem(block: action)
⋮----
private func modeLevel(_ m: IslandMode) -> Int {
⋮----
func setMode(_ mode: IslandMode) {
let prev = state.mode
⋮----
let shrinking = modeLevel(mode) < modeLevel(prev)
let anim: Animation = shrinking
⋮----
func expand(to view: IslandView) {
⋮----
func collapse() {
⋮----
let hadPendingClick = self.pendingIslandClick
let wasDragging     = self.inAttachDrag
⋮----
let pressed = event.modifierFlags.intersection([.command, .control, .option, .shift]).rawValue
⋮----
// MARK: - Drag ghost window (Mochi follows cursor during drag)
⋮----
// Same size as compact bot: diameter=20 → canvasSize≈33, scale 2× for grab comfort
let canvasSize: CGFloat = 40 / 0.6      // ~67
⋮----
let s = dragGhostSize
⋮----
let panel = NSPanel(
⋮----
let hosting = NSHostingView(
⋮----
// Fade + scale-in handled by GhostBotView SwiftUI animation;
// also fade in the window itself for extra smoothness
⋮----
// Direct follow — bot is "held", no trailing lag
⋮----
let captured = old
⋮----
let hosting = NSHostingView(rootView:
⋮----
let screenMaxY = screen.frame.maxY
let cgPoint = CGPoint(x: screenPoint.x, y: screenMaxY - screenPoint.y)
⋮----
let ourBundle = Bundle.main.bundleIdentifier ?? ""
⋮----
let pid = info[kCGWindowOwnerPID as String] as? pid_t ?? 0
⋮----
let screen = window?.screen ?? NSScreen.main
⋮----
let screenMaxY = screen?.frame.maxY ?? NSScreen.main!.frame.maxY
⋮----
let panelH = window?.frame.height ?? 320
let panelW = window?.frame.width  ?? 720
let islandLeft = (panelW - IslandConst.expandedWidth) / 2
⋮----
let prevView = state.view
⋮----
let recovery = DispatchWorkItem { [weak self] in
⋮----
let fallback = self.state.tasks.isEmpty ? IslandView.empty : .overview
⋮----
let s = AppState.shared
⋮----
let islandH: CGFloat
⋮----
let base: CGFloat = 240
let perMsg: CGFloat = 40
⋮----
let islandMinX = (panelW - islandW) / 2
⋮----
let radius = (diameter / 0.6) / 2
⋮----
let botX = islandMinX + cx
let botY = panelH - cy
let dx = windowPoint.x - botX
let dy = windowPoint.y - botY
⋮----
let visibleMenuBarHeight = screen.frame.maxY - screen.visibleFrame.maxY
⋮----
let menuBarHeight = visibleMenuBarHeight > 0
⋮----
var notchWidth:  CGFloat = IslandConst.notchWidth
var notchHeight: CGFloat = IslandConst.notchHeight
⋮----
override var canBecomeKey:  Bool { true }
override var canBecomeMain: Bool { false }
⋮----
override func constrainFrameRect(_ frameRect: NSRect, to screen: NSScreen?) -> NSRect {
⋮----
func currentIslandFrame(nw: CGFloat, nh: CGFloat) -> CGRect {
⋮----
let h: CGFloat
⋮----
let canvasSize: CGFloat
@State private var scale: CGFloat = 0.35
⋮----
var body: some View {
⋮----
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 openFullSettings = Notification.Name("notchBuddy.openFullSettings")
static let hookReveal       = Notification.Name("notchBuddy.hookReveal")
⋮----
static let greetComplete    = Notification.Name("notchBuddy.greetComplete")
static let greetingHover    = Notification.Name("notchBuddy.greetingHover")
static let greetingInterrupt = Notification.Name("notchBuddy.greetingInterrupt")
⋮----
let layout = IslandConst.viewLayouts[view]!
</file>

<file path="NotchBuddy/Sources/App/N8nPoller.swift">
final class N8nPoller: @unchecked Sendable {
static let shared = N8nPoller()
private var timer: DispatchSourceTimer?
private var lastExecutionId: String = ""
⋮----
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
// MARK: - Poll list endpoint
⋮----
private func poll() {
⋮----
let base = rawBase.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
let endpoints = [
⋮----
private func tryList(_ urls: [String], apiKey: String, base: String, idx: Int) {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let items: [[String: Any]]
⋮----
let id: String
⋮----
let status = first["status"] as? String ?? ""
let isTerminal = ["success", "error", "crashed", "canceled", "failed"].contains(status)
⋮----
let success = status == "success"
⋮----
let detailUrls = [
⋮----
private func fetchDetail(_ urls: [String], apiKey: String, success: Bool, idx: Int) {
⋮----
let name = self.extractWorkflowName(from: json)
let detail = self.parseDetail(from: json, success: success)
⋮----
private func extractWorkflowName(from json: [String: Any]) -> String {
⋮----
private func parseDetail(from json: [String: Any], success: Bool) -> String? {
⋮----
private func parseErrorDetail(resultData: [String: Any]) -> String? {
⋮----
let msg = error["message"] as? String ?? ""
⋮----
private func parseSuccessDetail(resultData: [String: Any]) -> String? {
⋮----
let count = items.count
let header = "→ \(lastNode) · \(count) item\(count == 1 ? "" : "s")"
⋮----
// Preview first item's JSON keys (up to 4)
⋮----
let lines = jsonObj.prefix(4).map { "\($0.key): \(fmtValue($0.value))" }
⋮----
private func fmtValue(_ v: Any) -> String {
⋮----
// MARK: - Dispatch to main
⋮----
private func dispatch(success: Bool, name: String, detail: String?) {
⋮----
private func handleExecution(success: Bool, name: String, detail: String?) {
let state = AppState.shared
⋮----
// Apply workflow filter (empty = all workflows)
⋮----
let focused = state.focusId == "integration_n8n"
⋮----
private func n8nLog(_ message: String) {
</file>

<file path="NotchBuddy/Sources/App/NotchBuddyApp.swift">
struct NotchBuddyApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
⋮----
var body: some Scene {
</file>

<file path="NotchBuddy/Sources/App/NotionPoller.swift">
final class NotionPoller: @unchecked Sendable {
static let shared = NotionPoller()
private var timer: DispatchSourceTimer?
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
func pollNow() { poll() }
⋮----
private func poll() {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let body: [String: Any] = [
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let msg: String
⋮----
let pages = results.compactMap { self.parsePage($0) }
⋮----
private func parsePage(_ obj: [String: Any]) -> NotionPage? {
⋮----
let objType = obj["object"] as? String ?? "page"
⋮----
var title = "Untitled"
⋮----
var emoji: String? = nil
⋮----
let iso = ISO8601DateFormatter()
⋮----
var lastEdited = iso.date(from: editedStr)
⋮----
let iso2 = ISO8601DateFormatter(); iso2.formatOptions = [.withInternetDateTime]
⋮----
let pageURL = (obj["url"] as? String) ?? "https://notion.so"
</file>

<file path="NotchBuddy/Sources/App/ResendPoller.swift">
final class ResendPoller: @unchecked Sendable {
static let shared = ResendPoller()
private var timer: DispatchSourceTimer?
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
private func poll() {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let total = (json["total"] as? Int) ?? (json["count"] as? Int)
let emails = rawList.compactMap { self.parseEmail($0) }
⋮----
private func parseEmail(_ d: [String: Any]) -> ResendEmail? {
⋮----
let to: [String]
⋮----
let subject   = (d["subject"]    as? String) ?? ""
let lastEvent = (d["last_event"] as? String) ?? ""
⋮----
let formatter = ISO8601DateFormatter()
⋮----
let date = formatter.date(from: createdAt)
</file>

<file path="NotchBuddy/Sources/App/SafeWebURL.swift">
func safeWebURL(_ string: String?) -> URL? {
</file>

<file path="NotchBuddy/Sources/App/SettingsView.swift">
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 = ""
@State private var hookNeedsUpdate: Bool = HookServer.hooksNeedUpdate()
⋮----
// 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> {
⋮----
var body: some View {
⋮----
// MARK: API
⋮----
// MARK: Integrations
⋮----
let task = AgentTask.integrationAgents.first { $0.id == id }!
let isOn = state.activeIntegrations.contains(id)
let atMax = state.activeIntegrations.count >= 4 && !isOn
⋮----
// MARK: Hotkey
⋮----
private func toggleStartup(_ on: Bool) {
⋮----
private func pickClaudeFolder(prompt: String) -> URL? {
let panel = NSOpenPanel()
⋮----
let realHomePath = getpwuid(getuid()).flatMap { String(cString: $0.pointee.pw_dir, encoding: .utf8) }
⋮----
private func installHooksAppStore() {
⋮----
let alert = NSAlert()
⋮----
private func uninstallHooksAppStore() {
⋮----
private func installHooks() {
⋮----
private func confirmInstall() {
⋮----
private func uninstallHooks() {
⋮----
private func saveIntegrations() {
⋮----
private func saveKey(_ key: String, value: String) {
⋮----
private func loadVercelProjects() {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let names: [String]
⋮----
private func loadN8nWorkflows() {
⋮----
let base = rawBase.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
let urls = ["\(base)/api/v1/workflows?limit=100", "\(base)/rest/workflows?limit=100"]
⋮----
private func fetchN8nWorkflows(urls: [String], apiKey: String, idx: Int) {
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let items: [[String: Any]]
⋮----
let names = items.compactMap { $0["name"] as? String }.sorted()
⋮----
struct IntegrationFilterRow: View {
let label: String
let items: [String]
@Binding var filter: Set<String>
let loading: Bool
let onLoad: () -> Void
⋮----
struct ShortcutRecorderButton: View {
@Binding var flags: UInt
@Binding var code: UInt16
@State private var isRecording = false
⋮----
var token: Any?
⋮----
let mods = event.modifierFlags.intersection([.command, .control, .option, .shift])
⋮----
private var shortcutLabel: String {
let f = NSEvent.ModifierFlags(rawValue: flags)
var s = ""
⋮----
private func keyChar(_ c: UInt16) -> String {
let map: [UInt16: String] = [
</file>

<file path="NotchBuddy/Sources/App/SoundEngine.swift">
final class SoundEngine {
static let shared = SoundEngine()
⋮----
var enabled: Bool = true
var volume: Float = 0.12 {
⋮----
private var players: [String: [AVAudioPlayer]] = [:]
⋮----
private init() {
⋮----
private func preload() {
let names = ["peek","open","close","hover","blip","slap","annoyed","dizzy","greet",
⋮----
var pool: [AVAudioPlayer] = []
⋮----
func play(_ name: String) {
⋮----
let player = pool.first { !$0.isPlaying } ?? pool[0]
</file>

<file path="NotchBuddy/Sources/App/StripePoller.swift">
final class StripePoller: @unchecked Sendable {
static let shared = StripePoller()
private var timer: DispatchSourceTimer?
private var lastChargeId: String = ""
⋮----
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
// MARK: - Poll
⋮----
func pollNow() { poll() }
⋮----
private func poll() {
⋮----
private func fetchBalance(key: String) {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let creds = Data("\(key):".utf8).base64EncodedString()
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let errMsg: String
⋮----
let available = json["available"] as? [[String: Any]] ?? []
let pending   = json["pending"]   as? [[String: Any]] ?? []
let allBuckets = available + pending
⋮----
let amount = allBuckets.compactMap { $0["amount"] as? Int }.reduce(0, +)
⋮----
let state = AppState.shared
⋮----
private func fetchCharges(key: String) {
⋮----
let parsed = rawList.compactMap { self.parseCharge($0) }
⋮----
private func parseCharge(_ c: [String: Any]) -> StripePayment? {
⋮----
let ts   = (c["created"] as? TimeInterval) ?? 0
let desc = c["description"] as? String
⋮----
private func handleCharges(_ payments: [StripePayment]) {
⋮----
// Sync display balance (balance may have already arrived; use it)
⋮----
let focused = state.focusId == "integration_stripe"
</file>

<file path="NotchBuddy/Sources/App/UploadCanvasView.swift">
struct UploadCanvasView: View {
@ObservedObject var state: AppState
@State private var fileIcon: NSImage? = nil
⋮----
private var engine: UploadSequenceEngine { .shared }
⋮----
var body: some View {
⋮----
let f = engine.frame(at: tl.date)
let wallTime = tl.date.timeIntervalSinceReferenceDate
⋮----
private func loadIcon(url: URL) {
let img = NSWorkspace.shared.icon(forFile: url.path)
⋮----
private func chooseOverlay(f: USFrame) -> some View {
⋮----
private func drawScene(ctx: GraphicsContext, f: USFrame, wallTime: Double = 0) {
var c = ctx
⋮----
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
⋮----
let gx = USC.CARD_X + USC.CARD_W/2
let gy = USC.CARD_Y + USC.CARD_H
let gGrad = Gradient(stops: [
⋮----
var borderCtx = c
⋮----
let borderColor = f.zoneOver
⋮----
let inset = CGRect(x: USC.CARD_X+0.75, y: USC.CARD_Y+0.75,
⋮----
let dashPhase = CGFloat(wallTime * 20)
⋮----
private func drawDropText(ctx: inout GraphicsContext, f: USFrame) {
var tCtx = ctx
⋮----
let label = Text("Drop your files here")
⋮----
let chips = ["PDF","Images","Code","Docs"]
var cx = USC.TEXT_X
⋮----
let chipText = Text(chip).font(.system(size:11, weight:.medium)).foregroundColor(Color(hex:"#B9BDC4"))
⋮----
let estW = Double(chip.count) * 6.5 + 16
⋮----
private func drawProgressBar(ctx: inout GraphicsContext, f: USFrame) {
var pCtx = ctx
⋮----
let x0 = USC.BAR_X0, x1 = USC.BAR_X1, by = USC.BAR_Y
let barLen = (x1-x0) * f.barReveal
⋮----
let name = state.droppedFile?.name ?? "file"
let label = Text("Uploading \(name)")
⋮----
var ckCtx = pCtx
⋮----
var circle = Path(); circle.addEllipse(in: CGRect(x:-8,y:-8,width:16,height:16))
⋮----
var ck = Path()
⋮----
let pct = Text("\(Int(f.progress*100)) %")
⋮----
let fx = usLerp(USC.BAR_X0, USC.BAR_X1, f.progress)
⋮----
let flashGreen = Color(
⋮----
let fillGrad = Gradient(stops: [
⋮----
let v = (usProgressAt(f.t+0.01, progStart:USC.T_PROG_START, progEnd:f.progEnd)
⋮----
let tl = max(8, min(34, 8 + v*40))
let tGrad = Gradient(stops:[
⋮----
var glowCtx = pCtx
⋮----
private func drawChooseView(ctx: inout GraphicsContext, f: USFrame) {
var cCtx = ctx
⋮----
let titleText = Text("\(name) is ready.")
⋮----
let subText = Text("What do you want to do with it?")
⋮----
let btn1 = Text("Ask a question about it")
⋮----
let btn2 = Text("Send by email")
⋮----
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))
⋮----
let bodyGrad = Gradient(stops:[
⋮----
let shadowGrad = Gradient(stops:[
⋮----
let rimAlpha = max(0, min(1, (mc-0.3)/0.7))
var rimCtx = c
⋮----
var rim = Path()
⋮----
let mh = f.mouth * R * mc
⋮----
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
⋮----
let holeGrad = Gradient(stops:[
⋮----
let holePath = roundedRect(CGRect(x:mxO, y:myO, width:CGFloat(mw), height:CGFloat(mh)), r:Double(mhr))
⋮----
var lip = Path()
⋮----
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
⋮----
var ec = eCtx
⋮----
private func drawEyeShape(ctx: inout GraphicsContext, shape: USEyeShape, w: CGFloat, h: CGFloat) {
let ink = Color(red:0.055,green:0.059,blue:0.071)
⋮----
var p = Path()
⋮----
let hh = h * 0.55
⋮----
private func drawFile(ctx: inout GraphicsContext, f: USFrame) {
let cx = f.cursorX, cy = f.cursorY + 14
⋮----
var fc = ctx; fc.opacity = 0.92
⋮----
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
⋮----
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
⋮----
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))
⋮----
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))
⋮----
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
⋮----
var body = Path()
⋮----
var foldPath = Path()
⋮----
private func drawDocCG(cg: CGContext, cx: Double, cy: Double, wsc: Double, hsc: Double, fileIcon: NSImage?) {
⋮----
let fold = 8.0*min(wsc,hsc)
⋮----
let rect = CGRect(x:x, y:y, width:w, height:h)
⋮----
let bp = CGMutablePath()
⋮----
let fp = CGMutablePath()
⋮----
func usBodyPath(m: Double, R: Double) -> (path: Path, rx: Double, ry: Double) {
⋮----
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()
⋮----
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)
⋮----
func roundedRect(_ rect: CGRect, r rr: Double) -> Path {
let r = max(0, min(rr, Double(rect.width)/2, Double(rect.height)/2))
</file>

<file path="NotchBuddy/Sources/App/UploadSequenceEngine.swift">
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
static let FOLLOW_MAX: Double = 580
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
⋮----
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
⋮----
static let ENTRY_T_REF: Double = T_DROP - 0.40
⋮----
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 }
⋮----
func usSqueezeY(_ t: Double) -> Double {
let t0=USC.T_SUCK_END, t1=t0+0.07, t2=t0+0.20, t3=USC.T_CHEW1
⋮----
func usSqueezeX(_ t: Double) -> Double {
⋮----
func usProgressCurve(_ u: Double) -> Double {
⋮----
func usProgressAt(_ t: Double, progStart: Double, progEnd: Double) -> Double {
⋮----
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
⋮----
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
var gulp:    Bool = false
var ok:      Bool = false
var lastPct: Int = 0
⋮----
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
⋮----
final class UploadSequenceEngine {
static let shared = UploadSequenceEngine()
⋮----
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
private var dropWallTime:  Double? = nil
⋮----
private var sim = USSimState()
⋮----
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
⋮----
func enterZone(x: CGFloat, y: CGFloat) {
let now = Date().timeIntervalSinceReferenceDate
⋮----
func updateCursor(x: CGFloat, y: CGFloat) {
⋮----
let dt = now - prevCursorTime
⋮----
let dx = Double(x) - prevCursorX, dy = Double(y) - prevCursorY
⋮----
func exitZone() {
⋮----
func performDrop(uploadDuration ud: Double) {
⋮----
func deactivate() {
⋮----
func tRef(at date: Date) -> Double {
⋮----
let now = date.timeIntervalSinceReferenceDate
⋮----
let elapsed = max(0, now - entryWallTime)
⋮----
func frame(at date: Date) -> USFrame {
⋮----
let t = tRef(at: date)
⋮----
private func simulateTo(_ tTarget: Double) {
⋮----
let dt = min(USC.DT, tTarget - sim.t)
⋮----
private func stepOnce(dt: Double) {
let isDragging = (dropWallTime == nil)
⋮----
let dist = hypot(cursorX - sim.bx.v, (cursorY + 14) - sim.by.v)
⋮----
let tx = max(USC.FOLLOW_MIN, min(USC.FOLLOW_MAX, cursorX))
⋮----
let tiltTarget = isDragging ? max(-0.18, min(0.18, sim.bx.vel * 0.0015)) : 0.0
⋮----
let t = sim.t
⋮----
var mt = 0.0
⋮----
private func computeFrame(t: Double) -> USFrame {
var f = USFrame()
⋮----
let entered    = sim.entered >= 0 ? sim.entered : 1e9
⋮----
let pt = isDragging ? min(t, USC.T_DROP - USC.DT) : t
⋮----
var morph: Double
⋮----
var x = sim.bx.v, y = sim.by.v, d = USC.D_BOX
⋮----
let k = usEInOut(usSeg(pt, USC.T_CHEW_END, USC.T_SHRINK_END))
⋮----
let p = usProgressAt(pt, progStart: USC.T_PROG_START, progEnd: progEnd)
⋮----
var sx = 1.0, sy = 1.0
⋮----
let k = usEOut(usSeg(pt, USC.T_DROP, USC.T_SUCK_START))
⋮----
let k = usEInOut(usSeg(pt, USC.T_SUCK_START, USC.T_SUCK_END))
⋮----
let k = ((pt-USC.T_CHEW1).truncatingRemainder(dividingBy: 0.14)) / 0.14
⋮----
let k = usSeg(pt, USC.T_CHEW_END, USC.T_SHRINK_END)
⋮----
let v = (usProgressAt(pt+0.01, progStart: USC.T_PROG_START, progEnd: progEnd)
⋮----
let st = max(0, min(1, v*0.18))
⋮----
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
⋮----
let hoverGreen = f.zoneOver ? 0.22 : 0.0
var uploadGreen = 0.0
⋮----
let baseGreen = f.progress * 0.50
⋮----
let flashExtra = pt >= progEnd ? 0.20 * sin(.pi * usSeg(pt, progEnd, progEnd + 0.40)) : 0
⋮----
let fadeOut = 1.0 - usSeg(pt, growEnd, growEnd + 0.60)
⋮----
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
</file>

<file path="NotchBuddy/Sources/App/VercelPoller.swift">
final class VercelPoller: @unchecked Sendable {
static let shared = VercelPoller()
private var timer: DispatchSourceTimer?
private var lastDeploymentId: String = ""
⋮----
private init() {}
⋮----
func start() {
⋮----
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
⋮----
// MARK: - Poll
⋮----
private func poll() {
⋮----
var req = URLRequest(url: url, timeoutInterval: 10)
⋮----
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
⋮----
let terminal = ["READY", "ERROR", "CANCELED"]
let parsed = rawList
⋮----
private func parseDeployment(_ d: [String: Any]) -> VercelDeployment? {
⋮----
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
⋮----
let branch = meta?["githubCommitRef"] as? String
⋮----
private func handleDeployments(_ deployments: [VercelDeployment]) {
let appState = AppState.shared
⋮----
let filter = appState.vercelProjectFilter
let filtered = filter.isEmpty ? deployments : deployments.filter { filter.contains($0.projectName) }
⋮----
let focused = appState.focusId == "integration_vercel"
</file>

<file path="NotchBuddy/Sources/App/WindowContextCapture.swift">
enum WindowContextCapture {
⋮----
static func captureActive(from app: NSRunningApplication? = NSWorkspace.shared.frontmostApplication) -> PromptContext? {
⋮----
let pid = app.processIdentifier
let axApp = AXUIElementCreateApplication(pid)
⋮----
var title = ""
var windowRef: CFTypeRef?
⋮----
// swiftlint:disable force_cast
let axWindow = windowRef as! AXUIElement
var titleRef: CFTypeRef?
⋮----
// --- Browser URL ---
let url = browserURL(for: app)
⋮----
// MARK: - Private
⋮----
private static let browserScripts: [String: String] = [
⋮----
private static func browserURL(for app: NSRunningApplication) -> String? {
⋮----
var error: NSDictionary?
let result = NSAppleScript(source: script)?.executeAndReturnError(&error)
</file>

<file path="windows/src/core/anim.ts">
export type EaseFn = (t: number) => number;
⋮----
export const lerp = (a: number, b: number, t: number)
export const clamp = (v: number, lo: number, hi: number)
export const seg = (t: number, a: number, b: number)
⋮----
export function cubicBezier(x1: number, y1: number, x2: number, y2: number): EaseFn
⋮----
const cx = (t: number)
const cy = (t: number)
⋮----
export class Spring
⋮----
constructor(value: number, response = 0.5, damping = 0.72)
⋮----
configure(response: number, damping: number)
⋮----
set(value: number)
⋮----
get settled(): boolean
⋮----
step(dt: number)
⋮----
export class Tracked
⋮----
constructor(value: number)
⋮----
get value(): number
⋮----
get animating(): boolean
⋮----
jump(v: number)
⋮----
springTo(v: number, response = 0.5, damping = 0.72)
⋮----
curveTowards(v: number, durationMs = 340, now = performance.now())
⋮----
step(dt: number, now = performance.now())
</file>

<file path="windows/src/core/bridge.ts">
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import type { Settings } from "./state";
⋮----
async function call<T>(cmd: string, args?: Record<string, unknown>): Promise<T | null>
⋮----
export interface BootInfo {
  settings: Settings;
  screen: { x: number; y: number; width: number; height: number; scale: number };
  version: string;
  hookPath: string;
}
⋮----
export interface IntegrationUpdate {
  id: string;
  data: Record<string, unknown>;
  error: string | null;
  event: { success: boolean; label: string; detail: string | null } | null;
}
⋮----
export type ChatContext =
  | { kind: "file"; name: string; path: string }
  | { kind: "window"; appName: string; title: string; url?: string };
⋮----
export interface DroppedFile {
  name: string;
  path: string;
  size: number;
}
⋮----
export interface HookStatus {
  installed: boolean;
  settingsPath: string;
  hookPath: string;
  hookReady: boolean;
}
⋮----
export interface HookPreview {
  diff: string;
  backup: string;
  settingsPath: string;
  fingerprint: string;
}
⋮----
async function callOrThrow<T>(cmd: string, args?: Record<string, unknown>): Promise<T>
⋮----
export type BridgeEvent =
  | { name: "cursor"; payload: { x: number; y: number } }
  | { name: "tray"; payload: string }
  | { name: "hook"; payload: Record<string, unknown> }
  | { name: "screen-changed"; payload: null };
⋮----
export interface DragDropPayload {
  type: "enter" | "over" | "drop" | "leave";
  paths?: string[];
}
⋮----
export async function onDragDrop(handler: (e: DragDropPayload) => void)
⋮----
export async function onEvent<T>(name: string, handler: (payload: T) => void)
</file>

<file path="windows/src/core/layout.ts">
export type IslandMode = "hidden" | "compact" | "expanded";
⋮----
export type IslandViewName =
  | "overview"
  | "empty"
  | "approval"
  | "question"
  | "error"
  | "finished"
  | "confused"
  | "upload"
  | "uploading"
  | "choose"
  | "mail"
  | "prompt"
  | "searching"
  | "result"
  | "note"
  | "settings"
  | "greeting";
⋮----
export type BotStateName =
  | "idle"
  | "working"
  | "thinking"
  | "searching"
  | "approval"
  | "question"
  | "error"
  | "finished"
  | "ratelimit"
  | "sleeping"
  | "dizzy";
⋮----
export type BotEmoteName = "love" | "surprised" | "proud" | "wink" | "yawn" | "happy" | "annoyed";
⋮----
export type AgentLayoutMode = "none" | "grid" | "pills" | "column";
⋮----
export interface ViewLayout {
  height: number;
  botX: number;
  botY: number | null;
  botDiameter: number;
  agentMode: AgentLayoutMode;
}
⋮----
export function chatPromptHeight(messageCount: number): number
⋮----
export function islandSize(
  mode: IslandMode,
  view: IslandViewName,
  chatCount = 0,
):
⋮----
export interface BotPlacement {
  cx: number;
  cy: number;
  diameter: number;
  opacity: number;
}
⋮----
export function botPosition(
  mode: IslandMode,
  view: IslandViewName,
  islandH: number,
  uploadProgress = 0,
): BotPlacement
⋮----
export function botGlowColor(s: BotStateName): string
⋮----
export function botGlowOpacity(s: BotStateName): number
⋮----
export function colorForProject(name: string): string
⋮----
export type Wash = "red" | "green" | "pink" | "amber" | "cyan" | "indigo" | "soft" | null;
⋮----
export function washRGBA(wash: Wash): string
</file>

<file path="windows/src/core/sound.ts">
export type SoundName = (typeof SOUND_NAMES)[number];
⋮----
class SoundEngine
⋮----
preload(): Promise<void>
⋮----
resume()
⋮----
idle()
⋮----
setVolume(v: number)
⋮----
setEnabled(on: boolean)
⋮----
play(name: SoundName | string)
</file>

<file path="windows/src/core/state.ts">
import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";
import type { EyeShape } from "../mochi/engine";
⋮----
export type AgentSource = "claudeCode" | "n8n";
export type PillBadge = "approval" | "finished" | "error";
⋮----
export interface AgentTask {
  id: string;
  name: string;
  color: string;
  state: BotStateName;
  stepIndex: number;
  steps: string[];
  source: AgentSource;
  isIntegration: boolean;
  emote?: BotEmoteName | null;
  miniEye?: EyeShape | null;
  pillBadge?: PillBadge | null;
  sessionCwd?: string | null;
}
⋮----
export interface ApprovalInfo {
  requestId: string;
  sessionId: string;
  tool: string;
  command: string;
}
⋮----
export interface ChatMessage {
  id: number;
  role: "user" | "assistant";
  content: string;
}
⋮----
export type PromptContext =
  | { kind: "window"; appName: string; title: string; url?: string }
  | { kind: "file"; name: string; path?: string };
⋮----
export interface ResultItem {
  label: string;
  detail: string;
  url?: string;
}
⋮----
export interface SearchResult {
  title: string;
  items: ResultItem[];
  note?: string;
}
⋮----
const task = (
  id: string, name: string, color: string, source: AgentSource,
): AgentTask => (
⋮----
export interface IntegrationInfo {
  data: Record<string, unknown>;
  error: string | null;
  loaded: boolean;
  configured: boolean;
}
⋮----
export interface Settings {
  soundEnabled: boolean;
  soundVolume: number;
  autoCloseInterval: number;
  absenceInterval: number;
  activeIntegrations: string[];
  screen: "primary" | "cursor";
  autostart: boolean;
  hooksInstalled: boolean;
  model: string;
}
⋮----
type Listener = () => void;
⋮----
class AppState
⋮----
subscribe(fn: Listener): () => void
⋮----
notify()
⋮----
get focusTask(): AgentTask | null
⋮----
get effectiveState(): BotStateName
⋮----
get otherTasks(): AgentTask[]
⋮----
setFocus(id: string)
⋮----
updateTask(id: string, state: BotStateName)
⋮----
appendStep(id: string, step: string)
⋮----
setPillBadge(id: string, badge: PillBadge | null)
⋮----
loadIntegrationTasks()
⋮----
toggleIntegration(id: string)
⋮----
defaultView(): IslandViewName
</file>

<file path="windows/src/island/fsm.ts">
export type FsmState = "hidden" | "petit" | "home" | "coucou";
⋮----
export class IslandStateMachine
⋮----
launch()
⋮----
mouseEntered()
⋮----
mouseLeft()
⋮----
click()
⋮----
greetComplete()
⋮----
reveal()
⋮----
forceHome()
⋮----
forcePetit()
⋮----
forceHidden()
⋮----
private schedulePetitHide()
⋮----
private scheduleHomeCollapse()
⋮----
private scheduleGreetCollapse(delay: number)
⋮----
private clear(which: "petitHide" | "homeCollapse" | "greetCollapse")
⋮----
cancelTimers()
⋮----
private transition(next: FsmState)
</file>

<file path="windows/src/island/hooks.ts">
import { Bridge, onEvent } from "../core/bridge";
import { Sound } from "../core/sound";
import { State } from "../core/state";
import type { Island } from "./island";
⋮----
interface HookPayload {
  hook_event_name?: string;
  request_id?: string;
  session_id?: string;
  cwd?: string;
  message?: string;
  prompt?: string;
  tool_name?: string;
  tool_input?: Record<string, unknown>;
}
⋮----
function aliasProjectName(name: string): string
⋮----
function lastPathComponent(p: string): string
⋮----
/** frenchStep() — same labels as the macOS app. */
⋮----
function stepLabel(tool: string, input: Record<string, unknown>): string
⋮----
const str = (k: string)
⋮----
function approvalTarget(tool: string, input: Record<string, unknown>): string
⋮----
function upsert(projectName: string, cwd: string)
⋮----
function clearSession()
⋮----
export function registerHookHandlers(island: Island)
⋮----
function handleHook(island: Island, payload: HookPayload)
⋮----
const surface = (view: Parameters<Island["alert"]>[0], isAlert: boolean) =>
⋮----
// One card, one request. A second one must never quietly replace the first
// — that would leave a human staring at request B while request A waits for
// a decision nobody can give. Hand it straight back to the terminal.
⋮----
// The relay's short ack window closes in 800 ms; everything below this
// line is synchronous, so the card really is up by the time it lands.
</file>

<file path="windows/src/island/integrations.ts">
import { onEvent, Bridge, type IntegrationUpdate } from "../core/bridge";
import { Sound } from "../core/sound";
import { State } from "../core/state";
import type { Island } from "./island";
⋮----
export function registerIntegrationHandlers(island: Island)
⋮----
export async function refreshConfigured()
⋮----
function handle(island: Island, update: IntegrationUpdate)
</file>

<file path="windows/src/island/island.ts">
import { Tracked, Spring, clamp } from "../core/anim";
import { Bridge, IS_TAURI, onDragDrop } from "../core/bridge";
import {
  EXPANDED_CORNER, EXPANDED_W, NOTCH_W, PANEL_H, PANEL_W,
  ROUNDED_CORNER, VIEW_LAYOUTS, botGlowColor, botGlowOpacity, botPosition, chatPromptHeight,
  islandSize,
  type IslandMode, type IslandViewName,
} from "../core/layout";
import { Sound } from "../core/sound";
import { State } from "../core/state";
import { BotEngine, hexToRGB } from "../mochi/engine";
import { Greeting } from "../mochi/greeting";
import { createMiniBot, pruneMiniBots, syncMiniBotStates, tickMiniBots } from "../mochi/minibots";
import { UploadCanvas } from "../upload/canvas";
import { USC, UploadSeq } from "../upload/sequence";
import { buildHeader, buildViews, type ViewActions, type ViewHost } from "../views/views";
import { h } from "../views/dom";
import { IslandStateMachine } from "./fsm";
⋮----
const modeOrder = (m: IslandMode)
⋮----
export class Island
⋮----
constructor(root: HTMLElement)
⋮----
private build()
⋮----
private wireFsm()
⋮----
launch()
⋮----
private setMode(mode: IslandMode)
⋮----
private get uploadActive(): boolean
⋮----
private stopSequenceIfLeaving(view: IslandViewName)
⋮----
expand(view: IslandViewName)
⋮----
setView(view: IslandViewName)
⋮----
collapse()
⋮----
alert(view: IslandViewName)
⋮----
reveal()
⋮----
dropPin()
⋮----
private onDragDrop(e:
⋮----
private swallow(path: string)
⋮----
private stepSequence()
⋮----
private targetSize():
⋮----
private animateGeometry(shrinking: boolean)
⋮----
private applyGeometry()
⋮----
private islandRect():
⋮----
private updateWindowCollapsed()
⋮----
private wireInput()
⋮----
onCursor(x: number, y: number)
⋮----
private isBotHit(x: number, y: number): boolean
⋮----
private botHoverIn(x: number, y: number)
⋮----
private scheduleLove()
⋮----
private cancelBotHover()
⋮----
private handleDizzy()
⋮----
ensureRunning()
⋮----
private updateBotTargets()
⋮----
private drawBot(dt: number)
⋮----
private lookX(): number
⋮----
private lookY(): number
⋮----
private updateCountdown(nowMs: number)
⋮----
private syncDom()
⋮----
applySettings()
⋮----
get panelSize()
⋮----
get chatHeight()
</file>

<file path="windows/src/mochi/engine.ts">
import { Ease, lerp, type EaseFn } from "../core/anim";
import { Sound } from "../core/sound";
import type { BotEmoteName, BotStateName } from "../core/layout";
⋮----
export type EyeShape =
  | "pill" | "wide" | "dot" | "line" | "flat" | "happy" | "closed"
  | "spiral" | "heart" | "star" | "tired" | "wink" | "cup";
⋮----
export type BadgeKind = "dots" | "bang" | "question" | "dot";
⋮----
export interface Badge {
  kind: BadgeKind;
  color: RGB;
}
⋮----
export type RGB = readonly [number, number, number];
⋮----
export type TweenKey = readonly [target: number, durationMs: number, ease: EaseFn];
⋮----
interface Tween {
  prop: PropKey;
  keys: TweenKey[];
  index: number;
  from: number;
  startMs: number;
  onComplete?: () => void;
}
⋮----
type PropKey =
  | "yaw" | "pitch" | "roll" | "tilt" | "open" | "sx" | "sy"
  | "oy" | "ox" | "tint" | "morph" | "hands" | "blush" | "es" | "badgeS";
⋮----
interface BotStateCfg {
  color: RGB;
  tint: number;
  eye: EyeShape;
  badge: Badge | null;
  bounces: boolean;
  scans: boolean;
  breathes: boolean;
  zz: boolean;
  sweat: boolean;
  look: readonly [number, number] | null;
  tilt: number;
}
⋮----
interface Particle {
  type: "heart" | "star" | "spark" | "sweat" | "z";
  x: number; y: number; vx: number; vy: number;
  age: number; life: number; rot: number; size: number;
}
⋮----
const now = ()
⋮----
export function hexToRGB(hex: string): RGB
⋮----
const rgba = (c: RGB, a = 1)
⋮----
const mix3 = (a: RGB, b: RGB, t: number): RGB
⋮----
function roundRectPath(x: CanvasRenderingContext2D, X: number, Y: number, W: number, H: number, R: number)
⋮----
function heartPath(x: CanvasRenderingContext2D, s: number)
⋮----
function starPath(x: CanvasRenderingContext2D, ro: number, ri: number)
⋮----
export class BotEngine
⋮----
setState(next: BotStateName, force = false)
⋮----
setBadge(b: Badge | null)
⋮----
blink()
⋮----
squash()
⋮----
gulp()
⋮----
slap()
⋮----
doRoll(durationMs: number, turns: number)
⋮----
greet()
⋮----
interruptGreet()
⋮----
setPermanentEmote(emote: BotEmoteName | null)
⋮----
triggerEmote(emote: BotEmoteName, duration = 1.8)
⋮----
emit(type: Particle["type"], count: number)
⋮----
animateMorph(target: number, durationMs?: number)
⋮----
resetMorph()
⋮----
get busy(): boolean
⋮----
anim(prop: PropKey, keys: TweenKey[], onComplete?: () => void)
⋮----
update(dt: number)
⋮----
private doMiniBehaviorLoop()
⋮----
draw(x: CanvasRenderingContext2D, W: number, H: number)
⋮----
private bodyPath(rx: number, ry: number, R: number): Path2D
⋮----
private drawBody(x: CanvasRenderingContext2D, body: Path2D, R: number, rx: number, ry: number)
⋮----
private drawEyes(x: CanvasRenderingContext2D, body: Path2D, R: number, rx: number, ry: number)
⋮----
private drawEyeShape(
    x: CanvasRenderingContext2D, shape: EyeShape,
    w: number, h: number, sd: number, ink: string,
)
⋮----
private drawMouth(x: CanvasRenderingContext2D, body: Path2D, R: number)
⋮----
private drawHandsBehind(
    x: CanvasRenderingContext2D,
    R: number, rx: number, ry: number, cx: number, cy: number,
)
⋮----
private drawBadge(x: CanvasRenderingContext2D, badge: Badge, R: number, cx: number, cy: number)
⋮----
private drawParticles(x: CanvasRenderingContext2D, R: number, cx: number, cy: number)
⋮----
function rrPoint(ca: number, sa: number, W: number, H: number, cr: number):
</file>

<file path="windows/src/mochi/greeting.ts">
import { Sound } from "../core/sound";
import { COMPACT_W, NOTCH_H, NOTCH_W } from "../core/layout";
⋮----
const clamp = (v: number, a: number, b: number)
const lerp = (a: number, b: number, t: number)
const seg = (t: number, a: number, b: number)
⋮----
type EyeType = "dot" | "happy" | "content";
⋮----
interface Pose {
  hb: number; x: number; y: number; sx: number; sy: number; tilt: number;
  eye: EyeType; open: number; eyeRoll: number;
  lookX: number; lookY: number;
  handL: number; handR: number; wave: number;
  badge: number; tint: number; halo: number; haloBlue: number; minis: number; fx: number;
  header: number; card: number;
  iw: number; ih: number;
}
⋮----
function greetPose(t: number): Pose
⋮----
const blink = (tb: number) =>
⋮----
function smallPose(): Pose
⋮----
function pose(t: number, tc: number): Pose
⋮----
interface RingDot { a: number; j: number; s: number; al: number }
interface Ring { t0: number; dots: RingDot[] }
interface Streak { a: number; sp: number; len: number; t0: number; col: string }
⋮----
const rnd = () =>
⋮----
function rr(x: CanvasRenderingContext2D, X: number, Y: number, W: number, H: number, R: number)
⋮----
function mochiPath(hw: number, hh: number): Path2D
⋮----
function whiteFill(
  x: CanvasRenderingContext2D, path: Path2D,
  x0: number, y0: number, x1: number, y1: number,
)
⋮----
function drawHandL(x: CanvasRenderingContext2D, hw: number, hh: number, p: Pose)
⋮----
function drawHandR(x: CanvasRenderingContext2D, hw: number, hh: number, p: Pose)
⋮----
function drawMochi(x: CanvasRenderingContext2D, p: Pose)
⋮----
function drawParticles(x: CanvasRenderingContext2D, t: number, p: Pose)
⋮----
function drawMinis(x: CanvasRenderingContext2D, alpha: number)
⋮----
export class Greeting
⋮----
start()
⋮----
hover()
⋮----
interrupt()
⋮----
get elapsed(): number
⋮----
get done(): boolean
⋮----
private fire()
⋮----
private cancelTimers()
⋮----
draw(x: CanvasRenderingContext2D)
</file>

<file path="windows/src/mochi/minibots.ts">
import { BotEngine, hexToRGB } from "./engine";
import type { AgentTask } from "../core/state";
⋮----
interface MiniBot {
  canvas: HTMLCanvasElement;
  engine: BotEngine;
  cssSize: number;
  taskId: string;
}
⋮----
export function createMiniBot(task: AgentTask, bodySize: number): HTMLElement
⋮----
export function releaseMiniBot(canvas: HTMLCanvasElement)
⋮----
export function pruneMiniBots()
⋮----
export function syncMiniBotStates(tasks: AgentTask[])
⋮----
export function tickMiniBots(dt: number)
⋮----
export const miniBotCount = ()
</file>

<file path="windows/src/settings/main.ts">
import { Bridge, onEvent, type HookStatus } from "../core/bridge";
import { DEFAULT_SETTINGS, type Settings } from "../core/state";
import { h, clear } from "../views/dom";
⋮----
async function save()
⋮----
function toggle(on: boolean, onChange: (v: boolean) => void): HTMLElement
⋮----
function statusDot(ok: boolean): HTMLElement
⋮----
function renderDiff(text: string): HTMLElement
⋮----
function claudeSection(status: HookStatus): HTMLElement
⋮----
const rebuild = async () =>
⋮----
function draw()
⋮----
async function showPreview(install: boolean)
⋮----
function apiSection(hasKey: boolean): HTMLElement
⋮----
async function refresh()
⋮----
interface IntegrationDef {
  id: string;
  name: string;
  color: string;
  fields: { key: string; label: string; placeholder: string; secret: boolean }[];
}
⋮----
function integrationsSection(present: Record<string, boolean>): HTMLElement
⋮----
function updateNote()
⋮----
function generalSection(): HTMLElement
⋮----
async function main()
</file>

<file path="windows/src/upload/canvas.ts">
import { State } from "../core/state";
import {
  USC, eIn, eInOut, eOut, lerp, progressAt,
  type UploadEyeShape, type UploadFrame,
} from "./sequence";
⋮----
function rr(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number)
⋮----
function bodyPath(ctx: CanvasRenderingContext2D, m: number, R: number):
⋮----
function text(
  ctx: CanvasRenderingContext2D,
  s: string,
  x: number,
  y: number,
  font: string,
  color: string,
  align: CanvasTextAlign = "left",
)
⋮----
export interface UploadCanvasActions {
  ask(): void;
  cancel(): void;
}
⋮----
ask(): void;
⋮----
cancel(): void;
⋮----
export class UploadCanvas
⋮----
constructor(actions: UploadCanvasActions)
⋮----
const mk = (x: number, w: number, onclick: () => void) =>
⋮----
draw(f: UploadFrame, wallTime: number)
⋮----
private drawScene(ctx: CanvasRenderingContext2D, f: UploadFrame, wallTime: number)
⋮----
private drawDropText(ctx: CanvasRenderingContext2D, f: UploadFrame)
⋮----
private drawProgressBar(ctx: CanvasRenderingContext2D, f: UploadFrame)
⋮----
private drawChoose(ctx: CanvasRenderingContext2D, f: UploadFrame)
⋮----
private drawMochi(ctx: CanvasRenderingContext2D, f: UploadFrame)
⋮----
private drawFile(ctx: CanvasRenderingContext2D, f: UploadFrame)
⋮----
function drawEye(ctx: CanvasRenderingContext2D, shape: UploadEyeShape, w: number, h: number)
⋮----
function drawDoc(ctx: CanvasRenderingContext2D, cx: number, cy: number, wsc: number, hsc: number)
</file>

<file path="windows/src/upload/sequence.ts">
export const eOut = (t: number)
export const eIn = (t: number)
export const eInOut = (t: number)
export const eBack = (t: number) =>
⋮----
export const seg = (t: number, a: number, b: number)
export const lerp = (a: number, b: number, t: number)
⋮----
function squeezeY(t: number): number
⋮----
function squeezeX(t: number): number
⋮----
export function uploadProgressCurve(u: number): number
⋮----
export function progressAt(t: number, progStart: number, progEnd: number): number
⋮----
class USSpring
⋮----
constructor(public v: number)
⋮----
step(target: number, response: number, damping: number, dt: number)
⋮----
export type UploadEyeShape = "pill" | "cup" | "content";
⋮----
export interface MouthRect {
  x: number;
  y: number;
  w: number;
  h: number;
}
⋮----
export interface UploadFrame {
  t: number;
  cursorX: number;
  cursorY: number;
  morph: number;
  x: number;
  y: number;
  d: number;
  sx: number;
  sy: number;
  tilt: number;
  hop: number;
  mouth: number;
  mouthRect: MouthRect;
  eye: UploadEyeShape;
  lookX: number;
  lookY: number;
  fileVisible: boolean;
  suck: number;
  zoneOver: boolean;
  zoneAlpha: number;
  textAlpha: number;
  barReveal: number;
  barAlpha: number;
  progress: number;
  flash: number;
  check: number;
  greenWash: number;
  chooseAlpha: number;
  progEnd: number;
  growStart: number;
  growEnd: number;
}
⋮----
function restFrame(): UploadFrame
⋮----
class UploadSequence
⋮----
get progEnd()
get growStart()
get growEnd()
⋮----
private now(): number
⋮----
enterZone(x: number, y: number)
⋮----
updateCursor(x: number, y: number)
⋮----
exitZone()
⋮----
performDrop(uploadDuration: number)
⋮----
deactivate()
⋮----
private tRef(): number
⋮----
get dropped(): boolean
⋮----
sinceDrop(): number | null
⋮----
frame(): UploadFrame
⋮----
private simulateTo(target: number)
⋮----
private stepOnce(dt: number)
⋮----
private computeFrame(t: number): UploadFrame
</file>

<file path="windows/src/views/chat.ts">
import { h, svg, clear } from "./dom";
import { ICONS } from "./icons";
import { Bridge, type ChatContext } from "../core/bridge";
import { Sound } from "../core/sound";
import { State, type ChatMessage } from "../core/state";
import type { ViewHost } from "./views";
⋮----
function bubble(message: ChatMessage): HTMLElement
⋮----
function typingDots(): HTMLElement
⋮----
function contextChip(label: string): HTMLElement
⋮----
export function buildPrompt(onHeightChange: () => void): ViewHost
⋮----
async function submit()
⋮----
sync()
focus()
</file>

<file path="windows/src/views/dom.ts">
type Attrs = Record<string, string | number | boolean | EventListener | undefined>;
type Child = Node | string | null | undefined | false;
⋮----
export function h<K extends keyof HTMLElementTagNameMap>(
  tag: K,
  attrs: Attrs = {},
  ...children: Child[]
): HTMLElementTagNameMap[K]
⋮----
export function svg(path: string, size = 14, opts:
⋮----
export function clear(el: Element)
⋮----
export function dot(color: string, size = 7): HTMLElement
</file>

<file path="windows/src/views/icons.ts">

</file>

<file path="windows/src/views/integrations.ts">
import { h, svg, clear, dot } from "./dom";
import { ICONS } from "./icons";
import { State, type AgentTask } from "../core/state";
import { Bridge } from "../core/bridge";
⋮----
export function timeAgo(value: unknown): string
⋮----
function header(color: string, name: string, kind: string, extra?: Node): HTMLElement
⋮----
function listRow(accent: string, first: boolean, ...children: Node[]): HTMLElement
⋮----
function get(id: string): Record<string, unknown>
⋮----
function arr(id: string, key: string): Record<string, unknown>[]
⋮----
function idleCard(task: AgentTask, openSettings: () => void): HTMLElement
⋮----
function vercelCard(onDetail: () => void): HTMLElement
⋮----
function vercelDetail(onBack: () => void): HTMLElement
⋮----
function resendCard(): HTMLElement
⋮----
function statRow(icon: string, color: string, label: string, value: string): HTMLElement
⋮----
function githubCard(): HTMLElement
⋮----
const fmt = (n: number) => (n >= 1000 ? `$
⋮----
function stripeCard(): HTMLElement
⋮----
function notionCard(): HTMLElement
⋮----
function calcomCard(): HTMLElement
⋮----
function n8nCard(task: AgentTask, onDetail: () => void, openSettings: () => void): HTMLElement
⋮----
function n8nDetail(task: AgentTask, onBack: () => void): HTMLElement
⋮----
export interface IntegrationCardHooks {
  detailOpen: boolean;
  openDetail(): void;
  closeDetail(): void;
  openSettings(): void;
}
⋮----
openDetail(): void;
closeDetail(): void;
openSettings(): void;
⋮----
export function hasIntegrationData(id: string): boolean
⋮----
export function renderIntegrationCard(task: AgentTask, hooks: IntegrationCardHooks): HTMLElement
</file>

<file path="windows/src/views/ticker.ts">
import { h, svg } from "./dom";
import { ICONS } from "./icons";
import { cubicBezier, clamp, lerp } from "../core/anim";
import type { AgentTask } from "../core/state";
⋮----
interface Row {
  el: HTMLElement;
  chevron: SVGElement;
  check: SVGElement;
  shimmer: HTMLElement;
  dim: HTMLElement;
  text: string;
}
⋮----
function makeRow(): Row
⋮----
function setText(row: Row, text: string)
⋮----
/**
 * Places a row. `phase` 0 = current (shimmering, full size), 1 = completed
 * (dim, shifted up-left and scaled down) — same crossfades as the Swift view.
 */
function place(row: Row, y: number, phase: number, opacity: number)
⋮----
export class Ticker
⋮----
private a = makeRow(); // completed
private b = makeRow(); // current
private c = makeRow(); // incoming
⋮----
constructor()
⋮----
private rest()
⋮----
get animating(): boolean
⋮----
sync(task: AgentTask | null)
⋮----
tick(nowMs: number)
</file>

<file path="windows/src/views/upload.ts">
import { h, clear } from "./dom";
import { State } from "../core/state";
import type { ViewActions, ViewHost } from "./views";
⋮----
function dashedFrame(): SVGSVGElement
⋮----
export function buildUpload(): ViewHost
⋮----
sync()
⋮----
export function buildUploading(): ViewHost
⋮----
export function buildChoose(actions: ViewActions): ViewHost
</file>

<file path="windows/src/views/views.ts">
import { h, svg, clear, dot } from "./dom";
import { ICONS } from "./icons";
import { Ticker } from "./ticker";
import { State, type AgentTask } from "../core/state";
import { washRGBA, type IslandViewName, type Wash } from "../core/layout";
import { createMiniBot, pruneMiniBots } from "../mochi/minibots";
import { buildPrompt } from "./chat";
import { buildChoose, buildUpload, buildUploading } from "./upload";
import { renderIntegrationCard, type IntegrationCardHooks } from "./integrations";
⋮----
export interface ViewActions {
  setView(v: IslandViewName): void;
  collapse(): void;
  setFocus(id: string): void;
  openTerminal(): void;
  openTarget(): void;
  openUrl(url: string): void;
  decide(d: "allow" | "deny"): void;
  toggleSound(): void;
  setVolume(v: number): void;
  setAutoClose(seconds: number): void;
  openSettingsWindow(): void;
  blip(): void;
}
⋮----
setView(v: IslandViewName): void;
collapse(): void;
setFocus(id: string): void;
openTerminal(): void;
⋮----
openTarget(): void;
openUrl(url: string): void;
decide(d: "allow" | "deny"): void;
toggleSound(): void;
setVolume(v: number): void;
setAutoClose(seconds: number): void;
openSettingsWindow(): void;
blip(): void;
⋮----
export interface ViewHost {
  el: HTMLElement;
  sync(): void;
  focus?(): void;
  tick?(nowMs: number): void;
}
⋮----
sync(): void;
⋮----
focus?(): void;
⋮----
tick?(nowMs: number): void;
⋮----
function card(wash: Wash, ...children: (Node | string)[]): HTMLElement
⋮----
function btn(
  label: string,
  kind: "primary" | "secondary",
  onClick: () => void,
  kbd?: string,
): HTMLElement
⋮----
function agentWho(task: AgentTask | null, label: string): HTMLElement
⋮----
function stack(padLeft: number, padRight: number, ...children: Node[]): HTMLElement
⋮----
export function buildHeader(actions: ViewActions): ViewHost
⋮----
function go(v: IslandViewName)
⋮----
sync()
⋮----
function buildOverview(actions: ViewActions): ViewHost
⋮----
get detailOpen()
openDetail()
closeDetail()
⋮----
tick(nowMs: number)
⋮----
// VS Code with a live Claude Code session keeps the ticker; every other
// pill shows its own card, exactly like IntegrationCardView.
⋮----
function buildPill(task: AgentTask, actions: ViewActions): HTMLElement
⋮----
function lighten(hex: string, amount: number): string
⋮----
// ── Empty ─────────────────────────────────────────────────────────────────────
⋮----
function buildEmpty(actions: ViewActions): ViewHost
⋮----
return
⋮----
function buildApproval(actions: ViewActions): ViewHost
⋮----
function buildQuestion(): ViewHost
⋮----
function buildError(actions: ViewActions): ViewHost
⋮----
function buildFinished(actions: ViewActions): ViewHost
⋮----
function buildConfused(): ViewHost
⋮----
function buildNote(): ViewHost
⋮----
// ── In-island settings ────────────────────────────────────────────────────────
⋮----
function buildSettings(actions: ViewActions): ViewHost
⋮----
function buildPlaceholder(title: string, sub: string): ViewHost
⋮----
export function buildViews(
  actions: ViewActions,
  onChatHeightChange: () => void,
): Map<IslandViewName, ViewHost>
</file>

<file path="windows/src/main.ts">
import { Bridge, IS_TAURI, onEvent } from "./core/bridge";
import { Sound } from "./core/sound";
import { State, type Settings } from "./core/state";
import { Island } from "./island/island";
import { registerHookHandlers } from "./island/hooks";
import { registerIntegrationHandlers, refreshConfigured } from "./island/integrations";
⋮----
async function main()
⋮----
const setPaused = (on: boolean) =>
</file>

<file path="windows/src-tauri/src/claude.rs">
use std::sync::Mutex;
⋮----
use crate::secrets;
⋮----
pub struct Chat {
⋮----
impl Chat {
pub fn reset(&self) {
self.messages.lock().unwrap().clear();
⋮----
fn is_empty(&self) -> bool {
self.messages.lock().unwrap().is_empty()
⋮----
fn push(&self, message: Value) {
self.messages.lock().unwrap().push(message);
⋮----
fn pop(&self) {
self.messages.lock().unwrap().pop();
⋮----
fn snapshot(&self) -> Vec<Value> {
self.messages.lock().unwrap().clone()
⋮----
pub enum ChatContext {
⋮----
pub struct ChatReply {
⋮----
pub async fn send(
⋮----
.ok_or_else(|| "API key missing. Open settings.".to_string())?;
⋮----
if chat.is_empty() {
⋮----
if let Some(block) = file_block(path) {
content.push(block);
⋮----
content.push(json!({ "type": "text", "text": format!("File: {name}") }));
⋮----
let mut text = format!("Context — App: {app_name}, Window: {title}");
⋮----
text.push_str(&format!(", URL: {url}"));
⋮----
content.push(json!({ "type": "text", "text": text }));
⋮----
content.push(json!({ "type": "text", "text": query }));
⋮----
chat.push(json!({ "role": "user", "content": content }));
⋮----
let body = json!({
⋮----
let response = match call(&key, &body).await {
⋮----
chat.pop();
return Err(err);
⋮----
if response.get("stop_reason").and_then(Value::as_str) == Some("refusal") {
⋮----
.get("stop_details")
.and_then(|d| d.get("explanation"))
.and_then(Value::as_str)
.unwrap_or("Claude declined this one.");
return Err(why.to_string());
⋮----
let Some(blocks) = response.get("content").and_then(Value::as_array).cloned() else {
⋮----
return Err("Unexpected API response.".into());
⋮----
chat.push(json!({ "role": "assistant", "content": blocks.clone() }));
⋮----
.iter()
.filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(Value::as_str))
⋮----
.join("\n")
.trim()
.to_string();
⋮----
if text.is_empty() {
return Err("No response text.".into());
⋮----
Ok(ChatReply { text })
⋮----
async fn call(key: &str, body: &Value) -> Result<Value, String> {
⋮----
.timeout(std::time::Duration::from_secs(90))
.build()
.map_err(|e| e.to_string())?;
⋮----
.post(ENDPOINT)
.header("x-api-key", key)
.header("anthropic-version", ANTHROPIC_VERSION)
.header("anthropic-beta", FALLBACK_BETA)
.header("content-type", "application/json")
.json(body)
.send()
⋮----
.map_err(|e| format!("Network error: {e}"))?;
⋮----
let status = response.status();
let text = response.text().await.map_err(|e| e.to_string())?;
if !status.is_success() {
⋮----
.ok()
.and_then(|v| {
v.get("error")
.and_then(|e| e.get("message"))
⋮----
.map(str::to_string)
⋮----
.unwrap_or_else(|| text.chars().take(200).collect());
return Err(format!("Claude API {status}: {detail}"));
⋮----
serde_json::from_str(&text).map_err(|e| format!("Bad API response: {e}"))
⋮----
fn file_block(path: &str) -> Option<Value> {
⋮----
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_lowercase();
⋮----
let media_type = match ext.as_str() {
"pdf" => Some(("document", "application/pdf")),
"jpg" | "jpeg" => Some(("image", "image/jpeg")),
"png" => Some(("image", "image/png")),
"gif" => Some(("image", "image/gif")),
"webp" => Some(("image", "image/webp")),
⋮----
let bytes = std::fs::read(path).ok()?;
return Some(json!({
⋮----
let len = std::fs::metadata(path).ok()?.len();
⋮----
let text = std::fs::read_to_string(path).ok()?;
Some(json!({ "type": "text", "text": format!("File contents:\n{text}") }))
⋮----
pub(crate) fn base64_for(bytes: &[u8]) -> String {
base64(bytes)
⋮----
fn base64(bytes: &[u8]) -> String {
⋮----
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
⋮----
out.push(TABLE[(n >> 18) as usize & 63] as char);
out.push(TABLE[(n >> 12) as usize & 63] as char);
out.push(if chunk.len() > 1 { TABLE[(n >> 6) as usize & 63] as char } else { '=' });
out.push(if chunk.len() > 2 { TABLE[n as usize & 63] as char } else { '=' });
⋮----
mod tests {
use super::base64;
⋮----
fn base64_matches_rfc4648_vectors() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"foob"), "Zm9vYg==");
assert_eq!(base64(b"fooba"), "Zm9vYmE=");
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
</file>

<file path="windows/src-tauri/src/files.rs">
use serde::Serialize;
⋮----
use crate::settings;
⋮----
pub struct DroppedFile {
⋮----
pub fn inbox_dir() -> PathBuf {
settings::local_dir().join("inbox")
⋮----
pub fn ingest(source: &str) -> Result<DroppedFile, String> {
⋮----
let meta = std::fs::metadata(src).map_err(|e| format!("cannot read {source}: {e}"))?;
if meta.is_dir() {
return Err("Folders can't be dropped yet.".into());
⋮----
let dir = inbox_dir();
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
⋮----
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "file".into());
⋮----
let mut dest = dir.join(&name);
if dest.exists() {
let stem = src.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
let ext = src.extension().map(|s| format!(".{}", s.to_string_lossy())).unwrap_or_default();
⋮----
let candidate = dir.join(format!("{stem} ({i}){ext}"));
if !candidate.exists() {
⋮----
std::fs::copy(src, &dest).map_err(|e| format!("cannot copy: {e}"))?;
⋮----
if let Ok(file) = std::fs::File::options().write(true).open(&dest) {
let _ = file.set_modified(SystemTime::now());
⋮----
sweep(&dir);
⋮----
Ok(DroppedFile {
⋮----
path: dest.to_string_lossy().to_string(),
size: meta.len(),
⋮----
fn sweep(dir: &Path) {
⋮----
for entry in entries.flatten() {
let Ok(meta) = entry.metadata() else { continue };
let Ok(copied) = meta.modified() else { continue };
if now.duration_since(copied).map(|age| age > KEEP_FOR).unwrap_or(false) {
let _ = std::fs::remove_file(entry.path());
⋮----
mod tests {
⋮----
fn ingest_copies_and_never_overwrites() {
let tmp = std::env::temp_dir().join(format!("coucou-test-{}", std::process::id()));
std::fs::create_dir_all(&tmp).unwrap();
let source = tmp.join("note.txt");
std::fs::write(&source, b"hello").unwrap();
⋮----
let first = ingest(source.to_str().unwrap()).unwrap();
assert_eq!(first.name, "note.txt");
assert_eq!(std::fs::read(&first.path).unwrap(), b"hello");
⋮----
std::fs::write(&source, b"second").unwrap();
let second = ingest(source.to_str().unwrap()).unwrap();
assert_ne!(first.path, second.path);
⋮----
assert_eq!(std::fs::read(&second.path).unwrap(), b"second");
⋮----
assert!(ingest(tmp.to_str().unwrap()).is_err());
⋮----
let old_source = tmp.join("ancient.txt");
std::fs::write(&old_source, b"old").unwrap();
⋮----
.write(true)
.open(&old_source)
.unwrap()
.set_modified(long_ago)
.unwrap();
let aged = ingest(old_source.to_str().unwrap()).unwrap();
assert!(
</file>

<file path="windows/src-tauri/src/hooks.rs">
use serde::Serialize;
⋮----
use windows::Win32::System::SystemInformation::GetLocalTime;
⋮----
use crate::settings;
⋮----
pub struct HookStatus {
⋮----
pub struct HookPreview {
⋮----
fn home() -> PathBuf {
⋮----
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."))
⋮----
pub fn settings_path() -> PathBuf {
home().join(".claude").join("settings.json")
⋮----
fn read_settings() -> Result<Value, String> {
let path = settings_path();
⋮----
Ok(bytes) => parse_settings(&bytes, &path.display().to_string()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(json!({})),
⋮----
Err(err) => Err(format!("Can't read {}: {err}", path.display())),
⋮----
fn parse_settings(bytes: &[u8], path: &str) -> Result<Value, String> {
⋮----
let text = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
if text.iter().all(u8::is_ascii_whitespace) {
return Ok(json!({}));
⋮----
Ok(v) if v.is_object() => Ok(v),
Ok(_) => Err(format!("{path} isn't a JSON object — Coucou won't touch it.")),
Err(err) => Err(format!(
⋮----
fn read_settings_lossy() -> Value {
read_settings().unwrap_or_else(|_| json!({}))
⋮----
fn hook_command(event: &str) -> String {
let exe = settings::hook_exe_path().to_string_lossy().replace('\\', "/");
format!("\"{exe}\" {event}")
⋮----
fn entry_is_ours(entry: &Value) -> bool {
⋮----
.get("hooks")
.and_then(Value::as_array)
.map(|hooks| {
hooks.iter().any(|h| {
h.get("command")
.and_then(Value::as_str)
.map(|c| c.contains(MARKER))
.unwrap_or(false)
⋮----
/// Settings with Coucou's hooks added; everything else is left untouched.
fn merged(existing: &Value) -> Value {
⋮----
fn merged(existing: &Value) -> Value {
let mut root = existing.as_object().cloned().unwrap_or_default();
⋮----
.and_then(Value::as_object)
.cloned()
.unwrap_or_else(Map::new);
⋮----
.get(*event)
⋮----
.unwrap_or_default();
list.retain(|entry| !entry_is_ours(entry));
list.push(json!({
⋮----
hooks.insert((*event).to_string(), Value::Array(list));
⋮----
root.insert("hooks".into(), Value::Object(hooks));
⋮----
fn without_ours(existing: &Value) -> Value {
⋮----
let Some(hooks) = root.get("hooks").and_then(Value::as_object).cloned() else {
⋮----
match value.as_array() {
⋮----
list.iter().filter(|e| !entry_is_ours(e)).cloned().collect();
if !kept.is_empty() {
out.insert(event, Value::Array(kept));
⋮----
out.insert(event, value);
⋮----
if out.is_empty() {
root.remove("hooks");
⋮----
root.insert("hooks".into(), Value::Object(out));
⋮----
fn pretty(v: &Value) -> String {
serde_json::to_string_pretty(v).unwrap_or_default()
⋮----
fn stamp() -> String {
let t = unsafe { GetLocalTime() };
format!(
⋮----
fn backup_path() -> PathBuf {
let p = settings_path();
p.with_file_name(format!("settings.json.bak-{}", stamp()))
⋮----
fn fingerprint(bytes: &[u8]) -> String {
⋮----
hash = hash.wrapping_mul(0x1000_0000_01b3);
⋮----
format!("{hash:016x}")
⋮----
fn current_fingerprint() -> String {
match std::fs::read(settings_path()) {
Ok(bytes) => fingerprint(&bytes),
Err(_) => fingerprint(b""),
⋮----
// ── Public API ────────────────────────────────────────────────────────────────
⋮----
pub fn status() -> HookStatus {
let current = read_settings_lossy();
⋮----
.values()
.filter_map(Value::as_array)
.flatten()
.any(entry_is_ours)
⋮----
.unwrap_or(false);
⋮----
settings_path: settings_path().to_string_lossy().to_string(),
hook_ready: hook_path.exists(),
hook_path: hook_path.to_string_lossy().to_string(),
⋮----
pub fn preview(install: bool) -> Result<HookPreview, String> {
let current = read_settings()?;
let next = if install { merged(&current) } else { without_ours(&current) };
Ok(HookPreview {
diff: unified_diff(&pretty(&current), &pretty(&next)),
backup: backup_path().to_string_lossy().to_string(),
⋮----
fingerprint: current_fingerprint(),
⋮----
pub fn write(install: bool, fingerprint: &str) -> Result<String, String> {
⋮----
let dir = path.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
⋮----
if current_fingerprint() != fingerprint {
return Err(format!(
⋮----
let backup = backup_path();
if path.exists() {
std::fs::copy(&path, &backup).map_err(|e| format!("backup failed: {e}"))?;
⋮----
let mut text = pretty(&next);
text.push('\n');
⋮----
let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));
std::fs::write(&temp, text.as_bytes()).map_err(|e| format!("write failed: {e}"))?;
⋮----
return Err(format!("write failed: {err}"));
⋮----
Ok(backup.to_string_lossy().to_string())
⋮----
pub fn ensure_hook_exe(app: &AppHandle) {
⋮----
let Some(dir) = dest.parent() else { return };
if std::fs::create_dir_all(dir).is_err() {
⋮----
if let Ok(p) = app.path().resolve("coucou-hook.exe", tauri::path::BaseDirectory::Resource) {
candidates.push(p);
⋮----
if let Some(parent) = exe.parent() {
⋮----
candidates.push(parent.join("coucou-hook.exe"));
candidates.push(parent.join("../release/coucou-hook.exe"));
⋮----
candidates.push(parent.join("_up_/target/release/coucou-hook.exe"));
⋮----
let tried: Vec<String> = candidates.iter().map(|p| p.display().to_string()).collect();
let Some(src) = candidates.into_iter().find(|p| p.exists()) else {
crate::log::line(format!(
⋮----
(Ok(a), Ok(b)) => a.len() == b.len() && a.modified().ok() == b.modified().ok(),
⋮----
if !dest.exists() {
crate::log::line(format!("could not install coucou-hook.exe: {err}"));
⋮----
fn unified_diff(before: &str, after: &str) -> String {
let a: Vec<&str> = before.lines().collect();
let b: Vec<&str> = after.lines().collect();
let (n, m) = (a.len(), b.len());
⋮----
let mut lcs = vec![vec![0usize; m + 1]; n + 1];
for i in (0..n).rev() {
for j in (0..m).rev() {
⋮----
lcs[i + 1][j].max(lcs[i][j + 1])
⋮----
out.push(format!("  {}", a[i]));
⋮----
out.push(format!("- {}", a[i]));
⋮----
out.push(format!("+ {}", b[j]));
⋮----
.iter()
.enumerate()
.filter(|(_, l)| l.starts_with('+') || l.starts_with('-'))
.map(|(i, _)| i)
.collect();
if changed.is_empty() {
return "No change.".into();
⋮----
let mut keep = vec![false; out.len()];
⋮----
let lo = idx.saturating_sub(3);
let hi = (idx + 4).min(out.len());
⋮----
for (idx, line) in out.iter().enumerate() {
⋮----
result.push_str(line);
result.push('\n');
⋮----
result.push_str("  …\n");
⋮----
mod tests {
⋮----
fn a_utf8_bom_is_stripped_not_treated_as_corruption() {
⋮----
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(br#"{"model":"opus","hooks":{}}"#);
let parsed = parse_settings(&bytes, WHERE).expect("a BOM must not defeat the parser");
assert_eq!(parsed["model"], "opus");
⋮----
fn unreadable_content_is_an_error_never_an_empty_object() {
⋮----
assert!(
⋮----
fn empty_and_whitespace_files_start_from_nothing() {
assert_eq!(parse_settings(b"", WHERE).unwrap(), json!({}));
assert_eq!(parse_settings(b"
⋮----
fn merging_keeps_every_other_setting_and_every_foreign_hook() {
⋮----
let after = merged(&existing);
assert_eq!(after["model"], "claude-opus-5");
assert_eq!(after["theme"], "dark");
assert_eq!(after["enabledPlugins"], serde_json::json!(["a", "b"]));
⋮----
let pre = after["hooks"]["PreToolUse"].as_array().unwrap();
⋮----
assert!(pre.iter().any(entry_is_ours), "our own hook was not added");
assert!(after["hooks"]["SomeEventWeDoNotTouch"].is_array());
⋮----
let cleaned = without_ours(&after);
assert_eq!(cleaned, existing);
⋮----
fn a_fingerprint_notices_any_change() {
assert_eq!(fingerprint(b"{}"), fingerprint(b"{}"));
assert_ne!(fingerprint(b"{}"), fingerprint(b"{ }"));
assert_ne!(fingerprint(b""), fingerprint(b"{}"));
⋮----
/// Everything filesystem-shaped lives in one test on purpose: it points
    /// USERPROFILE at a temp directory, and that is process-wide.
⋮----
/// USERPROFILE at a temp directory, and that is process-wide.
    #[test]
fn writing_backs_up_preserves_and_refuses_a_changed_file() {
let tmp = std::env::temp_dir().join(format!("coucou-hooks-{}", std::process::id()));
⋮----
std::fs::create_dir_all(tmp.join(".claude")).unwrap();
⋮----
assert!(path.starts_with(&tmp), "the test must not touch the real home");
⋮----
bytes.extend_from_slice(original.as_bytes());
std::fs::write(&path, &bytes).unwrap();
⋮----
// Install.
let plan = preview(true).expect("a BOM must not stop the preview");
assert!(plan.diff.contains("coucou-hook"), "the diff must show what changes");
let backup = write(true, &plan.fingerprint).expect("install should succeed");
⋮----
assert_eq!(std::fs::read(&backup).unwrap(), bytes);
⋮----
let after: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
⋮----
assert_eq!(after["tui"]["x"], 1);
⋮----
assert!(pre.iter().any(|e| serde_json::to_string(e).unwrap().contains("other-tool.exe")));
assert!(status().installed);
⋮----
let stale = preview(false).unwrap();
std::fs::write(&path, br#"{"model":"someone-else-edited-this"}"#).unwrap();
let err = write(false, &stale.fingerprint).unwrap_err();
assert!(err.contains("changed since the preview"), "got: {err}");
let untouched: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(untouched["model"], "someone-else-edited-this");
⋮----
std::fs::write(&path, b"{ broken").unwrap();
assert!(preview(true).is_err());
assert!(write(true, "whatever").is_err());
assert_eq!(std::fs::read(&path).unwrap(), b"{ broken");
</file>

<file path="windows/src-tauri/src/integrations.rs">
use std::sync::Mutex;
use std::time::Duration;
⋮----
use serde::Serialize;
⋮----
use crate::island::WINDOW_LABEL;
use crate::log;
use crate::secrets;
⋮----
pub struct IntegrationUpdate {
⋮----
pub struct IntegrationEvent {
⋮----
fn emit(app: &AppHandle, update: IntegrationUpdate) {
let _ = app.emit_to(WINDOW_LABEL, "integration", update);
⋮----
fn client() -> reqwest::Client {
⋮----
.timeout(TIMEOUT)
.build()
.unwrap_or_default()
⋮----
/// Set from the tray's Pause item. While it is on, nothing reaches the network:
⋮----
pub fn set_paused(on: bool) {
PAUSED.store(on, Ordering::Relaxed);
⋮----
pub fn start(app: AppHandle) {
spawn(app.clone(), "integration_n8n", 3, 15, poll_n8n);
spawn(app.clone(), "integration_vercel", 5, 30, poll_vercel);
spawn(app.clone(), "integration_stripe", 6, 30, poll_stripe);
spawn(app.clone(), "integration_resend", 6, 60, poll_resend);
spawn(app.clone(), "integration_github", 7, 300, poll_github);
spawn(app.clone(), "integration_calcom", 8, 300, poll_calcom);
spawn(app, "integration_notion", 9, 300, poll_notion);
⋮----
fn enabled(app: &AppHandle, id: &str) -> bool {
⋮----
.map(|shared| {
let settings = shared.settings.lock().unwrap();
settings.active_integrations.iter().any(|x| x == id)
⋮----
.unwrap_or(false)
⋮----
fn spawn<F, Fut>(app: AppHandle, id: &'static str, delay_secs: u64, every_secs: u64, poll: F)
⋮----
ticker.tick().await;
⋮----
if PAUSED.load(Ordering::Relaxed) || !enabled(&app, id) {
⋮----
poll(app.clone()).await;
⋮----
pub async fn poll_once(app: AppHandle, id: &str) {
⋮----
"integration_stripe" => poll_stripe(app).await,
"integration_github" => poll_github(app).await,
"integration_vercel" => poll_vercel(app).await,
"integration_n8n" => poll_n8n(app).await,
"integration_resend" => poll_resend(app).await,
"integration_notion" => poll_notion(app).await,
"integration_calcom" => poll_calcom(app).await,
⋮----
struct Seen(Mutex<std::collections::HashMap<&'static str, String>>);
⋮----
std::sync::LazyLock::new(|| Seen(Mutex::new(std::collections::HashMap::new())));
⋮----
/// Returns true the first time a given id is seen (and false on the very first
/// load, which only fills the card).
⋮----
/// load, which only fills the card).
fn is_new(key: &'static str, id: &str) -> bool {
⋮----
fn is_new(key: &'static str, id: &str) -> bool {
let mut map = SEEN.0.lock().unwrap();
match map.insert(key, id.to_string()) {
⋮----
fn status_error(code: u16, unauthorised_hint: &str) -> String {
⋮----
401 => "Invalid API key (401)".into(),
403 => unauthorised_hint.into(),
_ => format!("API error {code}"),
⋮----
async fn poll_stripe(app: AppHandle) {
⋮----
let auth = format!("Basic {}", crate::claude::base64_for(format!("{key}:").as_bytes()));
let http = client();
⋮----
.get("https://api.stripe.com/v1/balance")
.header("Authorization", &auth)
.send()
⋮----
Ok(r) if r.status().is_success() => {
let json: Value = r.json().await.unwrap_or(json!({}));
⋮----
if let Some(arr) = json.get(k).and_then(Value::as_array) {
buckets.extend(arr.iter().cloned());
⋮----
.first()
.and_then(|b| b.get("currency"))
.and_then(Value::as_str)
.unwrap_or("eur")
.to_string();
⋮----
.iter()
.filter_map(|b| b.get("amount").and_then(Value::as_i64))
.sum();
⋮----
let code = r.status().as_u16();
emit(&app, IntegrationUpdate {
⋮----
data: json!({}),
error: Some(status_error(code, "Use a secret key (sk_live_… not pk_live_…)")),
⋮----
error: Some(format!("No connection: {e}")),
⋮----
.get("https://api.stripe.com/v1/charges?limit=3")
⋮----
if !response.status().is_success() {
⋮----
let json: Value = response.json().await.unwrap_or(json!({}));
⋮----
.get("data")
.and_then(Value::as_array)
.map(|list| {
list.iter()
.filter_map(|c| {
⋮----
.get("description")
⋮----
.or_else(|| {
c.get("billing_details")
.and_then(|b| b.get("name"))
⋮----
.map(str::to_string);
Some(json!({
⋮----
.collect()
⋮----
.unwrap_or_default();
⋮----
.and_then(|p| p.get("id"))
⋮----
.unwrap_or("")
⋮----
let event = if !newest.is_empty() && is_new("stripe", &newest) {
⋮----
.map(str::to_string)
.unwrap_or_else(|| {
let cents = payments[0].get("amount").and_then(Value::as_i64).unwrap_or(0);
format!("{:.2}", cents as f64 / 100.0)
⋮----
Some(IntegrationEvent { success: true, label, detail: None })
⋮----
data: json!({ "balance": amount, "currency": currency, "payments": payments }),
⋮----
async fn poll_github(app: AppHandle) {
⋮----
.get("https://api.github.com/user")
.header("Authorization", format!("Bearer {token}"))
.header("Accept", "application/vnd.github+json")
.header("User-Agent", "Coucou")
⋮----
error: Some(status_error(response.status().as_u16(), "Token lacks the needed scope")),
⋮----
let public = json.get("public_repos").and_then(Value::as_i64).unwrap_or(0);
⋮----
.get("owned_private_repos")
.or_else(|| json.get("total_private_repos"))
.and_then(Value::as_i64)
.unwrap_or(0);
⋮----
.get("https://api.github.com/user/repos?per_page=100&affiliation=owner&sort=pushed")
⋮----
Ok(r) if r.status().is_success() => r
⋮----
.ok()
.and_then(|v| v.as_array().cloned())
⋮----
.filter_map(|r| r.get("stargazers_count").and_then(Value::as_i64))
.sum()
⋮----
.unwrap_or(0),
⋮----
data: json!({ "totalRepos": public + private, "totalStars": stars }),
⋮----
async fn poll_vercel(app: AppHandle) {
⋮----
let response = client()
.get("https://api.vercel.com/v6/deployments?limit=5")
⋮----
.header("Accept", "application/json")
⋮----
error: Some(status_error(response.status().as_u16(), "Token lacks access")),
⋮----
.get("deployments")
⋮----
.filter_map(|d| {
let state = d.get("state")?.as_str()?;
if !terminal.contains(&state) {
⋮----
let meta = d.get("meta");
⋮----
meta.and_then(|m| keys.iter().find_map(|k| m.get(*k).and_then(Value::as_str)))
⋮----
let event = deployments.first().and_then(|latest| {
let id = latest.get("id")?.as_str()?;
if !is_new("vercel", id) {
⋮----
let success = latest.get("state")?.as_str()? == "READY";
Some(IntegrationEvent {
⋮----
label: latest.get("projectName")?.as_str()?.to_string(),
⋮----
data: json!({ "deployments": deployments }),
⋮----
async fn poll_resend(app: AppHandle) {
⋮----
.get("https://api.resend.com/emails?limit=100")
.header("Authorization", format!("Bearer {key}"))
⋮----
error: Some(status_error(response.status().as_u16(), "Key lacks access")),
⋮----
.get("total")
.or_else(|| json.get("count"))
.and_then(Value::as_i64);
⋮----
.take(5)
.filter_map(|e| {
let to = match e.get("to") {
Some(Value::Array(a)) => a.clone(),
Some(Value::String(s)) => vec![Value::String(s.clone())],
_ => vec![],
⋮----
data: json!({ "emails": emails, "total": total }),
⋮----
async fn poll_notion(app: AppHandle) {
⋮----
.post("https://api.notion.com/v1/search")
⋮----
.header("Notion-Version", "2022-06-28")
.header("Content-Type", "application/json")
.json(&json!({
⋮----
error: Some(status_error(response.status().as_u16(), "Integration lacks access")),
⋮----
.get("results")
⋮----
.map(|list| list.iter().filter_map(parse_notion_page).collect())
⋮----
data: json!({ "pages": pages }),
⋮----
fn parse_notion_page(obj: &Value) -> Option<Value> {
let id = obj.get("id")?.as_str()?;
let is_database = obj.get("object").and_then(Value::as_str) == Some("database");
⋮----
let mut title = "Untitled".to_string();
⋮----
.get("title")
⋮----
.and_then(|a| a.first())
.and_then(|t| t.get("plain_text"))
⋮----
if !text.is_empty() {
title = text.to_string();
⋮----
} else if let Some(props) = obj.get("properties").and_then(Value::as_object) {
for prop in props.values() {
if prop.get("type").and_then(Value::as_str) != Some("title") {
⋮----
.get("icon")
.filter(|i| i.get("type").and_then(Value::as_str) == Some("emoji"))
.and_then(|i| i.get("emoji"))
.and_then(Value::as_str);
⋮----
async fn poll_calcom(app: AppHandle) {
⋮----
.get("https://api.cal.com/v2/bookings?status=upcoming")
⋮----
.header("cal-api-version", "2024-08-13")
⋮----
.filter_map(|b| {
⋮----
.get("start")
.or_else(|| b.get("startTime"))
.and_then(Value::as_str)?;
let attendee = b.get("attendees").and_then(Value::as_array).and_then(|a| a.first());
⋮----
.get("responses")
.and_then(|r| r.get("notes"))
.and_then(|n| n.get("value"))
⋮----
.or_else(|| b.get("description").and_then(Value::as_str))
.filter(|s| !s.is_empty());
⋮----
data: json!({ "bookings": bookings }),
⋮----
async fn poll_n8n(app: AppHandle) {
⋮----
let base = raw_base.trim_end_matches('/').to_string();
⋮----
format!("{base}/api/v1/executions?limit=1&includeData=false"),
format!("{base}/rest/executions?limit=1&includeData=false"),
⋮----
let Ok(response) = http.get(url).header("X-N8N-API-KEY", &key).header("Accept", "application/json").send().await
⋮----
log::line(format!("n8n list HTTP {}", response.status()));
⋮----
Value::Object(o) => o.get("data").and_then(Value::as_array).cloned(),
Value::Array(a) => Some(a.clone()),
⋮----
if items.is_some() {
⋮----
let Some(first) = items.and_then(|list| list.into_iter().next()) else { return };
let id = match first.get("id") {
Some(Value::String(s)) => s.clone(),
Some(Value::Number(n)) => n.to_string(),
⋮----
let status = first.get("status").and_then(Value::as_str).unwrap_or("");
if !["success", "error", "crashed", "canceled", "failed"].contains(&status) {
⋮----
if !is_new("n8n", &id) {
⋮----
format!("{base}/api/v1/executions/{id}?includeData=true"),
format!("{base}/api/v1/executions/{id}"),
format!("{base}/rest/executions/{id}?includeData=true"),
format!("{base}/rest/executions/{id}"),
⋮----
let mut name = "Workflow".to_string();
⋮----
.get("workflowData")
.and_then(|w| w.get("name"))
⋮----
.or_else(|| json.get("name").and_then(Value::as_str))
.unwrap_or("Workflow")
⋮----
detail = n8n_detail(&json, success);
⋮----
log::line(format!("n8n execution {id} {status} · {name}"));
⋮----
data: json!({ "workflow": name, "status": status }),
⋮----
event: Some(IntegrationEvent { success, label: name, detail }),
⋮----
fn n8n_detail(json: &Value, success: bool) -> Option<String> {
let result = json.get("data")?.get("resultData")?;
⋮----
if let Some(error) = result.get("error") {
let message = error.get("message").and_then(Value::as_str).unwrap_or("");
if let Some(node) = error.get("node").and_then(|n| n.get("name")).and_then(Value::as_str) {
if !node.is_empty() {
return Some(format!("{node}\n{message}"));
⋮----
return Some(message.to_string());
⋮----
let runs = result.get("runData")?.as_object()?;
⋮----
.as_array()
⋮----
.and_then(|r| r.get("error"))
.and_then(|e| e.get("message"))
⋮----
let last_node = result.get("lastNodeExecuted")?.as_str()?;
⋮----
.get("runData")?
.get(last_node)?
.as_array()?
.first()?
.get("data")?
.get("main")?
⋮----
.as_array()?;
let count = items.len();
let header = format!("→ {last_node} · {count} item{}", if count == 1 { "" } else { "s" });
⋮----
.and_then(|i| i.get("json"))
.and_then(Value::as_object)
.map(|obj| {
obj.iter()
.take(4)
.map(|(k, v)| format!("{k}: {}", fmt_value(v)))
⋮----
.join("\n")
⋮----
Some(match fields {
Some(f) => format!("{header}\n{f}"),
⋮----
fn fmt_value(v: &Value) -> String {
⋮----
Value::String(s) => s.chars().take(50).collect(),
Value::Array(a) => format!("[{}]", a.len()),
Value::Object(_) => "{…}".into(),
other => other.to_string(),
</file>

<file path="windows/src-tauri/src/island.rs">
use std::time::Duration;
⋮----
use serde::Serialize;
⋮----
use windows::core::BOOL;
use windows::Win32::Foundation::LPARAM;
use windows::Win32::System::Ole::RevokeDragDrop;
⋮----
pub struct CursorPayload {
⋮----
pub struct ScreenInfo {
⋮----
pub struct IslandRect {
⋮----
pub struct PollGate {
⋮----
impl PollGate {
pub fn new() -> Self {
⋮----
pub fn set_rect(&self, rect: IslandRect) {
*self.rect.lock().unwrap() = rect;
⋮----
pub fn forget_ignore_state(&self) {
self.ignoring.store(false, Ordering::Relaxed);
⋮----
pub fn set_active(&self, on: bool) {
let mut guard = self.active.lock().unwrap();
⋮----
self.cv.notify_all();
⋮----
fn wait_until_active(&self) {
⋮----
guard = self.cv.wait(guard).unwrap();
⋮----
fn is_active(&self) -> bool {
*self.active.lock().unwrap()
⋮----
pub fn window(app: &AppHandle) -> Option<WebviewWindow> {
app.get_webview_window(WINDOW_LABEL)
⋮----
fn cursor_physical() -> Option<(f64, f64)> {
⋮----
unsafe { GetCursorPos(&mut p).ok()? };
Some((p.x as f64, p.y as f64))
⋮----
pub fn unblock_webview_drops(app: &AppHandle) {
⋮----
let Some(win) = app.get_webview_window(label) else { continue };
let Some(hwnd) = hwnd_of(&win) else { continue };
⋮----
let _ = EnumChildWindows(Some(hwnd), Some(revoke_render_widget), LPARAM(0));
⋮----
unsafe extern "system" fn revoke_render_widget(hwnd: HWND, _: LPARAM) -> BOOL {
⋮----
let len = unsafe { GetClassNameW(hwnd, &mut name) };
⋮----
let _ = unsafe { RevokeDragDrop(hwnd) };
⋮----
true.into()
⋮----
fn left_button_down() -> bool {
unsafe { (GetAsyncKeyState(VK_LBUTTON.0 as i32) as u16 & 0x8000) != 0 }
⋮----
fn monitor_contains(m: &Monitor, x: f64, y: f64) -> bool {
let p = m.position();
let s = m.size();
⋮----
fn target_monitor(app: &AppHandle, pref: &str) -> Option<Monitor> {
let monitors = app.available_monitors().ok()?;
⋮----
if let Some((cx, cy)) = cursor_physical() {
if let Some(m) = monitors.iter().find(|m| monitor_contains(m, cx, cy)) {
return Some(m.clone());
⋮----
app.primary_monitor()
.ok()
.flatten()
.or_else(|| monitors.into_iter().next())
⋮----
pub fn screen_info(app: &AppHandle, pref: &str) -> ScreenInfo {
match target_monitor(app, pref) {
⋮----
let scale = m.scale_factor();
⋮----
pub fn apply_geometry(app: &AppHandle, pref: &str, collapsed: bool) {
let Some(win) = window(app) else { return };
let Some(m) = target_monitor(app, pref) else { return };
⋮----
let mp = *m.position();
let ms = *m.size();
⋮----
let pw = (lw * scale).round().max(1.0) as u32;
let ph = (lh * scale).round().max(1.0) as u32;
⋮----
let _ = win.set_size(PhysicalSize::new(pw, ph));
let _ = win.set_position(PhysicalPosition::new(x, y));
⋮----
let _ = win.set_always_on_top(true);
⋮----
fn hwnd_of(win: &WebviewWindow) -> Option<HWND> {
let raw = win.hwnd().ok()?.0 as isize;
⋮----
Some(HWND(raw as *mut _))
⋮----
pub fn make_non_activating(win: &WebviewWindow) {
let Some(hwnd) = hwnd_of(win) else { return };
⋮----
let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
⋮----
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, want);
⋮----
pub fn set_activating(win: &WebviewWindow, activating: bool) {
⋮----
fn current_screen_key(app: &AppHandle) -> Option<(i32, i32, u32, u32, u64)> {
⋮----
.map(|s| s.settings.lock().unwrap().screen.clone())
.unwrap_or_else(|| "primary".into());
let m = target_monitor(app, &pref)?;
⋮----
let size = m.size();
Some((p.x, p.y, size.width, size.height, m.scale_factor().to_bits()))
⋮----
pub fn spawn_cursor_poll(app: AppHandle, gate: Arc<PollGate>) {
⋮----
gate.wait_until_active();
⋮----
while gate.is_active() {
⋮----
ticks = ticks.wrapping_add(1);
⋮----
let now = current_screen_key(&app);
if now.is_some() && now != last_screen {
let first = last_screen.is_none();
⋮----
crate::log::line("display layout changed — repositioning".to_string());
let _ = app.emit_to(WINDOW_LABEL, "screen-changed", ());
⋮----
let Some(win) = window(&app) else { continue };
let Ok(origin) = win.outer_position() else { continue };
let scale = win.scale_factor().unwrap_or(1.0);
let Some((cx, cy)) = cursor_physical() else { continue };
⋮----
let size = match win.inner_size() {
⋮----
if (x - last.0).abs() < 1.0 && (y - last.1).abs() < 1.0 {
⋮----
let r = *gate.rect.lock().unwrap();
⋮----
let down = left_button_down();
⋮----
let handle = app.clone();
let _ = app.run_on_main_thread(move || unblock_webview_drops(&handle));
⋮----
if gate.ignoring.load(Ordering::Relaxed) == accept {
gate.ignoring.store(!accept, Ordering::Relaxed);
let _ = win.set_ignore_cursor_events(!accept);
⋮----
let _ = win.emit("cursor", CursorPayload { x, y });
⋮----
pub fn set_ignore_cursor(app: &AppHandle, ignore: bool) {
if let Some(win) = window(app) {
let _ = win.set_ignore_cursor_events(ignore);
</file>

<file path="windows/src-tauri/src/lib.rs">
mod claude;
mod files;
mod hooks;
mod integrations;
mod island;
mod log;
mod pipe;
mod secrets;
mod settings;
mod tray;
mod win_user;
⋮----
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::sync::atomic::Ordering;
⋮----
use serde::Serialize;
⋮----
use files::DroppedFile;
⋮----
use pipe::Pending;
use settings::Settings;
⋮----
pub struct Shared {
⋮----
pub struct BootInfo {
⋮----
fn boot(app: AppHandle, shared: State<Shared>) -> BootInfo {
let mut settings = shared.settings.lock().unwrap().clone();
⋮----
version: env!("CARGO_PKG_VERSION").to_string(),
hook_path: settings::hook_exe_path().to_string_lossy().to_string(),
⋮----
fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {
⋮----
let mut current = shared.settings.lock().unwrap();
⋮----
*current = settings.clone();
⋮----
eprintln!("[coucou] could not save settings: {err}");
⋮----
let manager = app.autolaunch();
let result = if settings.autostart { manager.enable() } else { manager.disable() };
⋮----
eprintln!("[coucou] autostart: {err}");
⋮----
let collapsed = shared.gate.collapsed.load(Ordering::Relaxed);
⋮----
let _ = app.emit("settings-changed", settings);
⋮----
fn set_collapsed(app: AppHandle, shared: State<Shared>, collapsed: bool) {
let pref = shared.settings.lock().unwrap().screen.clone();
shared.gate.collapsed.store(collapsed, Ordering::Relaxed);
⋮----
shared.gate.forget_ignore_state();
shared.gate.set_active(!collapsed);
⋮----
fn set_island_rect(shared: State<Shared>, x: f64, y: f64, width: f64, height: f64) {
shared.gate.set_rect(island::IslandRect { x, y, w: width, h: height });
⋮----
fn focus_window(app: AppHandle, focused: bool) {
⋮----
let _ = win.set_focus();
⋮----
fn reposition(app: AppHandle, shared: State<Shared>) {
⋮----
fn open_url(url: String) {
if !(url.starts_with("http://") || url.starts_with("https://")) {
⋮----
.args(["url.dll,FileProtocolHandler", &url])
.creation_flags(CREATE_NO_WINDOW)
.spawn();
⋮----
fn open_in_vscode(path: Option<String>) -> bool {
⋮----
if let Some(code) = find_on_path("code") {
⋮----
if let Some(p) = path.as_deref().filter(|p| !p.is_empty()) {
cmd.arg(p);
⋮----
if cmd.creation_flags(CREATE_NO_WINDOW).spawn().is_ok() {
⋮----
let _ = Command::new("explorer").arg(p).spawn();
⋮----
fn find_on_path(stem: &str) -> Option<std::path::PathBuf> {
let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
⋮----
for ext in exts.split(';').filter(|e| !e.is_empty()) {
let candidate = dir.join(format!("{stem}{}", ext.to_lowercase()));
if candidate.is_file() {
return Some(candidate);
⋮----
fn quit_app(app: AppHandle) {
app.exit(0);
⋮----
fn set_paused(paused: bool) {
⋮----
fn hooks_status() -> HookStatus {
⋮----
fn hooks_preview(install: bool) -> Result<HookPreview, String> {
⋮----
fn hooks_apply(
⋮----
current.clone()
⋮----
let _ = app.emit("settings-changed", updated);
Ok(backup)
⋮----
fn approval_decision(app: AppHandle, request_id: String, decision: String) {
⋮----
fn approval_ack(app: AppHandle, request_id: String) {
⋮----
fn approval_decline(app: AppHandle, request_id: String) {
⋮----
async fn chat_send(
⋮----
let model = shared.settings.lock().unwrap().model.clone();
⋮----
fn chat_reset(chat: State<Chat>) {
chat.reset();
⋮----
fn ingest_file(path: String) -> Result<DroppedFile, String> {
⋮----
fn secret_present(key: String) -> bool {
⋮----
fn secret_set(key: String, value: String) -> Result<(), String> {
⋮----
fn secret_clear(key: String) -> Result<(), String> {
⋮----
fn open_n8n() {
⋮----
open_url(url);
⋮----
async fn refresh_integration(app: AppHandle, id: String) {
⋮----
fn log_line(message: String) {
log::line(format!("ui  {message}"));
⋮----
fn settings_page_url(app: &AppHandle) -> WebviewUrl {
⋮----
if let Some(mut base) = app.config().build.dev_url.clone() {
base.set_path("/settings.html");
⋮----
WebviewUrl::App("settings.html".into())
⋮----
fn create_settings_window(app: &AppHandle) {
let url = settings_page_url(app);
⋮----
.additional_browser_args(BROWSER_ARGS)
.title("Settings — Coucou")
.inner_size(560.0, 680.0)
.min_inner_size(460.0, 480.0)
.resizable(true)
.visible(false)
.center()
.build()
⋮----
let hidden = win.clone();
win.on_window_event(move |event| {
⋮----
api.prevent_close();
let _ = hidden.hide();
⋮----
Err(err) => log::line(format!("settings window failed: {err}")),
⋮----
pub fn show_settings_window(app: &AppHandle) {
let Some(win) = app.get_webview_window("settings") else {
⋮----
let _ = win.unminimize();
let _ = win.show();
⋮----
fn open_settings_window(app: AppHandle) {
show_settings_window(&app);
⋮----
pub fn run() {
⋮----
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
let _ = app.emit_to(island::WINDOW_LABEL, "tray", "open".to_string());
⋮----
.plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None))
.manage(Shared {
settings: Mutex::new(loaded.clone()),
gate: gate.clone(),
⋮----
.manage(Pending::default())
.manage(Chat::default())
.invoke_handler(tauri::generate_handler![
⋮----
.setup(move |app| {
let handle = app.handle().clone();
⋮----
create_settings_window(&handle);
⋮----
gate.collapsed.store(false, Ordering::Relaxed);
gate.set_active(true);
island::spawn_cursor_poll(handle.clone(), gate.clone());
⋮----
log::line(format!("--- Coucou {} started ---", env!("CARGO_PKG_VERSION")));
⋮----
pipe::start(handle.clone());
integrations::start(handle.clone());
Ok(())
⋮----
.run(tauri::generate_context!())
.expect("error while running Coucou");
</file>

<file path="windows/src-tauri/src/log.rs">
use std::io::Write;
⋮----
use windows::Win32::System::SystemInformation::GetLocalTime;
⋮----
use crate::settings;
⋮----
pub fn line(message: impl AsRef<str>) {
let t = unsafe { GetLocalTime() };
let stamp = format!(
⋮----
if std::fs::create_dir_all(&dir).is_err() {
⋮----
let path = dir.join("coucou.log");
⋮----
if std::fs::metadata(&path).map(|m| m.len() > 1_000_000).unwrap_or(false) {
⋮----
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(file, "{stamp} {}", message.as_ref());
</file>

<file path="windows/src-tauri/src/main.rs">
fn main() {
</file>

<file path="windows/src-tauri/src/pipe.rs">
use std::collections::HashMap;
⋮----
use std::sync::Mutex;
use std::time::Duration;
⋮----
use tokio::sync::mpsc;
⋮----
use crate::island::WINDOW_LABEL;
use crate::log;
⋮----
pub enum Reply {
⋮----
pub struct Pending(pub Mutex<HashMap<String, mpsc::Sender<Reply>>>);
⋮----
pub fn pipe_name() -> String {
⋮----
.unwrap_or_else(|| std::env::var("USERNAME").unwrap_or_else(|_| "user".into()));
format!(r"\\.\pipe\coucou-{key}")
⋮----
pub fn start(app: AppHandle) {
⋮----
let name = pipe_name();
// first_pipe_instance also means we refuse to join a pipe somebody else
// already owns under our name, rather than serving on top of it.
let mut server = match ServerOptions::new().first_pipe_instance(true).create(&name) {
⋮----
log::line(format!("cannot open the relay pipe: {err}"));
⋮----
if server.connect().await.is_err() {
⋮----
// Hand the connected instance to a task and listen on a fresh one.
let next = match ServerOptions::new().create(&name) {
⋮----
log::line(format!("cannot reopen the relay pipe: {err}"));
⋮----
let app = app.clone();
tauri::async_runtime::spawn(async move { handle(app, connected).await });
⋮----
async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {
⋮----
match pipe.read(&mut chunk).await {
⋮----
buf.extend_from_slice(&chunk[..n]);
if buf.contains(&b'\n') || buf.len() > MAX_PAYLOAD {
⋮----
let line = match buf.iter().position(|b| *b == b'\n') {
⋮----
if !payload.is_object() {
⋮----
.get("hook_event_name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
⋮----
log::line(format!("hook {event}"));
let _ = app.emit_to(WINDOW_LABEL, "hook", payload);
let _ = pipe.disconnect();
⋮----
let id = format!("{}-{}", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed));
⋮----
pending.0.lock().unwrap().insert(id.clone(), tx);
⋮----
payload["request_id"] = json!(id);
log::line(format!("hook PermissionRequest id={id}"));
⋮----
let decision = wait_for_decision(&id, &mut rx).await;
app.state::<Pending>().0.lock().unwrap().remove(&id);
⋮----
let _ = pipe.write_all(format!("{d}\n").as_bytes()).await;
let _ = pipe.flush().await;
⋮----
async fn wait_for_decision(id: &str, rx: &mut mpsc::Receiver<Reply>) -> Option<String> {
match tokio::time::timeout(ACK_TIMEOUT, rx.recv()).await {
⋮----
log::line(format!("hook id={id} answered {d}"));
return Some(d);
⋮----
log::line(format!("hook id={id} not shown — terminal takes over"));
⋮----
log::line(format!("hook id={id} island never acknowledged — terminal takes over"));
⋮----
match tokio::time::timeout(DECISION_TIMEOUT, rx.recv()).await {
⋮----
Some(d)
⋮----
log::line(format!("hook id={id} released without a decision"));
⋮----
log::line(format!("hook id={id} timed out — terminal takes over"));
⋮----
fn send(app: &AppHandle, request_id: &str, reply: Reply, keep: bool) {
⋮----
let mut map = pending.0.lock().unwrap();
if keep { map.get(request_id).cloned() } else { map.remove(request_id) }
⋮----
let _ = tx.try_send(reply);
⋮----
None => log::line(format!("reply for id={request_id} — no pending request")),
⋮----
pub fn acknowledge(app: &AppHandle, request_id: &str) {
send(app, request_id, Reply::Ack, true);
⋮----
pub fn decline(app: &AppHandle, request_id: &str) {
log::line(format!("decline id={request_id}"));
send(app, request_id, Reply::Decline, false);
⋮----
pub fn answer(app: &AppHandle, request_id: &str, decision: &str) {
⋮----
log::line(format!("decision id={request_id} {word}"));
send(app, request_id, Reply::Decision(word.to_string()), false);
</file>

<file path="windows/src-tauri/src/secrets.rs">
use keyring::Entry;
⋮----
fn entry(key: &str) -> Option<Entry> {
if !KNOWN_KEYS.contains(&key) {
⋮----
Entry::new(SERVICE, key).ok()
⋮----
pub fn get(key: &str) -> Option<String> {
entry(key)?.get_password().ok().filter(|v| !v.is_empty())
⋮----
pub fn set(key: &str, value: &str) -> Result<(), String> {
let entry = entry(key).ok_or_else(|| format!("unknown key {key}"))?;
if value.is_empty() {
let _ = entry.delete_credential();
return Ok(());
⋮----
entry.set_password(value).map_err(|e| e.to_string())
⋮----
pub fn clear(key: &str) -> Result<(), String> {
⋮----
match entry.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
⋮----
pub fn present(key: &str) -> bool {
get(key).is_some()
</file>

<file path="windows/src-tauri/src/settings.rs">
use std::path::PathBuf;
⋮----
pub struct Settings {
⋮----
fn default_model() -> String {
crate::claude::DEFAULT_MODEL.to_string()
⋮----
impl Default for Settings {
fn default() -> Self {
⋮----
active_integrations: vec![
⋮----
screen: "primary".into(),
⋮----
model: default_model(),
⋮----
pub fn config_dir() -> PathBuf {
⋮----
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
base.join("Coucou")
⋮----
pub fn local_dir() -> PathBuf {
⋮----
pub fn hook_exe_path() -> PathBuf {
local_dir().join("bin").join("coucou-hook.exe")
⋮----
fn settings_path() -> PathBuf {
config_dir().join("settings.json")
⋮----
pub fn load() -> Settings {
match std::fs::read(settings_path()) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
⋮----
pub fn save(settings: &Settings) -> std::io::Result<()> {
let dir = config_dir();
⋮----
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(settings_path(), json)
</file>

<file path="windows/src-tauri/src/tray.rs">
use tauri::tray::TrayIconBuilder;
⋮----
use crate::island::WINDOW_LABEL;
⋮----
pub fn build(app: &AppHandle) -> tauri::Result<()> {
⋮----
.tooltip("Coucou")
.menu(&menu)
.on_menu_event(|app: &AppHandle, event| match event.id.as_ref() {
"quit" => app.exit(0),
⋮----
let _ = app.emit_to(WINDOW_LABEL, "tray", id.to_string());
⋮----
if let Some(icon) = app.default_window_icon().cloned() {
builder = builder.icon(icon);
⋮----
builder.build(app)?;
Ok(())
</file>

<file path="windows/src-tauri/src/win_user.rs">
use windows::core::PWSTR;
⋮----
use windows::Win32::Security::Authorization::ConvertSidToStringSidW;
⋮----
pub fn current_user_sid() -> Option<String> {
⋮----
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).ok()?;
⋮----
let _ = GetTokenInformation(token, TokenUser, None, 0, &mut needed);
⋮----
let _ = CloseHandle(token);
⋮----
let mut buf = vec![0u8; needed as usize];
let ok = GetTokenInformation(
⋮----
Some(buf.as_mut_ptr().cast()),
⋮----
.is_ok();
⋮----
let user = &*(buf.as_ptr() as *const TOKEN_USER);
⋮----
ConvertSidToStringSidW(user.User.Sid, &mut text).ok()?;
let sid = text.to_string().ok();
let _ = LocalFree(Some(HLOCAL(text.0 as *mut _)));
</file>

<file path="windows/src-tauri/build.rs">
fn main() {
</file>

<file path="windows/src-tauri/tauri.conf.json">
{
  "$schema": "https://schema.tauri.app/config/2",
  "productName": "Coucou",
  "version": "0.1.1",
  "identifier": "fr.louisraille.coucou",
  "build": {
    "beforeDevCommand": "npm run dev",
    "devUrl": "http://localhost:1420",
    "beforeBuildCommand": "npm run build",
    "frontendDist": "../dist"
  },
  "app": {
    "withGlobalTauri": false,
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost",
      "devCsp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' ipc: http://ipc.localhost ws://localhost:1420 http://localhost:1420"
    },
    "windows": [
      {
        "label": "island",
        "title": "Coucou",
        "url": "index.html",
        "width": 240,
        "height": 6,
        "resizable": false,
        "decorations": false,
        "transparent": true,
        "shadow": false,
        "alwaysOnTop": true,
        "skipTaskbar": true,
        "focus": false,
        "visible": true,
        "center": false,
        "maximizable": false,
        "minimizable": false,
        "closable": false,
        "dragDropEnabled": true,
        "additionalBrowserArgs": "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection --autoplay-policy=no-user-gesture-required"
      }
    ]
  },
  "bundle": {
    "active": true,
    "targets": ["nsis"],
    "icon": [
      "icons/32x32.png",
      "icons/128x128.png",
      "icons/128x128@2x.png",
      "icons/icon.ico"
    ],
    "resources": { "../target/release/coucou-hook.exe": "coucou-hook.exe" },
    "copyright": "© Louis Raille",
    "category": "DeveloperTool",
    "shortDescription": "Mochi lives at the top of your screen",
    "longDescription": "Coucou puts Mochi at the top of your screen: it shows your Claude Code sessions and a few integrations, and lets you approve, answer, chat and drop files without leaving what you are doing.",
    "windows": {
      "nsis": {
        "installMode": "currentUser",
        "languages": ["English", "French"],
        "installerHooks": "nsis/hooks.nsh"
      }
    }
  }
}
</file>

<file path="windows/package.json">
{
  "name": "coucou-windows",
  "private": true,
  "version": "0.1.1",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview",
    "icons": "node scripts/gen-icons.mjs",
    "tauri": "tauri",
    "predev": "cargo build --release -p coucou-hook",
    "prebuild": "cargo build --release -p coucou-hook",
    "pack": "tauri build && node scripts/pack.mjs"
  },
  "devDependencies": {
    "@tauri-apps/cli": "^2",
    "typescript": "^5.6.0",
    "vite": "^6"
  },
  "dependencies": {
    "@tauri-apps/api": "^2"
  }
}
</file>

<file path="windows/README.md">
<div align="center">

<img src="src-tauri/icons/128x128.png" width="96" alt="Coucou icon">

# Coucou for Windows

**Mochi doesn't get a notch on a PC — so it lives at the top of your screen instead.**

Approve Claude Code permissions, watch your session work, drop a file, chat with Claude, keep an eye on your services — without leaving what you're doing.

![Windows 10/11](https://img.shields.io/badge/Windows-10%2F11-0078D4?logo=windows)
![Tauri 2](https://img.shields.io/badge/Tauri-2-FFC131?logo=tauri&logoColor=black)
![Rust](https://img.shields.io/badge/Rust-backend-000?logo=rust)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

</div>

<img src="screenshots/greeting.png" width="640" alt="Mochi waving hello at launch">

---

## Install

The downloadable installer is **temporarily unavailable**. Microsoft Defender
wrongly flags the unsigned installer as malware (`Trojan:Win32/Wacatac.H!ml`, a
machine-learning false positive). A report is under review at Microsoft, and the
installer will be published again once it is cleared and code-signed.

Until then, [build it yourself](#build-it-yourself): it takes a few minutes and
installs for the current user only — no admin prompt.

## Using it

<img src="screenshots/compact.png" width="292" alt="The compact island, with the integration pills as mini Mochis">
<img src="screenshots/overview.png" width="640" alt="The overview: the focused integration on the left, the other pills on the right">
<img src="screenshots/approval.png" width="640" alt="A Claude Code permission request, with Deny and Allow">
<img src="screenshots/chat.png" width="640" alt="Chatting with Claude from the island">
<img src="screenshots/drop.png" width="640" alt="Mochi turned into a box, waiting for a file">

| What you do | What happens |
|---|---|
| Move the mouse to the very top-centre of the screen | Mochi peeks out |
| Click the small island | It opens |
| Click Mochi | It gets annoyed. Three times in a row and it goes dizzy |
| Rest the pointer on Mochi for two seconds | Hearts |
| Drag a file onto the island | Mochi turns into a box, swallows it, then offers to answer questions about it |
| `Esc` | Closes the island |
| Tray icon | Open, Settings…, Pause, Quit |

Everything else happens on its own: a Claude Code permission request opens the
island with **Deny / Allow**, a finished session shows what it did, and
your integrations sit in the coloured pills next to Mochi.

## Claude Code

<img src="screenshots/settings.png" width="562" alt="The settings window">

Open **Settings… → Claude Code → Install hooks…**. You get the exact diff of what
will change in `%USERPROFILE%\.claude\settings.json`, the path of the dated backup
that will be taken, and nothing is written until you click. Your own hooks are
never touched, and uninstalling removes only Coucou's entries.

The relay is a tiny executable, `coucou-hook.exe`, copied to
`%LOCALAPPDATA%\Coucou\bin\` at launch. It is given 300 ms to reach Coucou and
exits cleanly if the app is closed, slow or crashed — **a Claude Code session is
never blocked or slowed down by Coucou.** If nobody answers a permission request
in time, Coucou stays quiet and Claude Code asks in the terminal as usual.

It works from any terminal — Windows Terminal, PowerShell, VS Code, Git Bash.

## Chat and keys

**Settings… → Claude** takes your Anthropic API key. Keys live in the **Windows
Credential Manager**, never on disk and never in the interface — the island can
only ask whether a key exists. Same for every integration key.

No telemetry. The only network requests Coucou makes are to the services you
configure yourself.

## Build it yourself

You need [Rust](https://rustup.rs), [Node 20+](https://nodejs.org), and the
**MSVC build tools** (Visual Studio Build Tools with "Desktop development with
C++"). WebView2 ships with Windows 10/11.

```powershell
cd windows
npm install
npm run tauri dev      # live-reloading development build
npm run pack           # builds the installer and drops it in windows/release/
```

`npm run dev` alone serves the front end in an ordinary browser, which is enough
to work on the island's looks. It also serves `dev/upload-preview.html`, which
replays the whole file-drop choreography on a loop — the one part of the UI that
otherwise needs a real drag from Explorer to see. Neither page ships in the app.

`npm run pack` leaves two files in `windows/release/`, the same names the release
workflow publishes:

```
Coucou-Windows-X.Y.Z-setup.exe    the versioned installer
Coucou-Windows-setup.exe          the same file under the rolling name
```

Installing is optional — `target/release/coucou.exe` runs on its own. There is no
window in the taskbar and no console: the island at the top of the screen and the
Mochi in the notification area are the whole app, and Quit lives in its menu.

The 28 sounds are the macOS app's own files; they are never duplicated in this
folder. The path is declared once, in `SOUNDS_DIR` at the top of
`vite.config.ts` — when they move to `shared/sounds/`, change that one line.

The app icon and the tray icon are drawn in code, like Mochi itself:

```powershell
npm run icons          # regenerates src-tauri/icons from scripts/gen-icons.mjs
```

### Layout

```
windows/
  src/                 island front end (TypeScript, no framework)
    mochi/             Mochi and the launch greeting, in Canvas 2D
    island/            state machine, hooks, integrations
    views/             every island view
    settings/          the settings window
  src-tauri/           Rust backend: window, named pipe, Claude API, pollers
  hook/                coucou-hook.exe, the Claude Code relay
  scripts/             icon generator
```

### Log

`%LOCALAPPDATA%\Coucou\coucou.log` — hook events, permission decisions, poller
problems. It stays on your machine.

## What's different from the Mac version

- No notch, so the island lives at the top centre of the screen and retracts into
  the top edge instead of hiding in a notch.
- Permission approval works from **any** terminal; the Mac build only listens to
  VS Code sessions.
- Not in this version: sending a file by email, dragging Mochi onto a window to
  attach it as context, and jumping to a specific terminal window — "Open
  terminal" opens the working folder in VS Code when `code` is on your `PATH`.
- Cal.com shows the next bookings as a list rather than the Mac's calendar.
</file>

<file path="windows/tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitOverride": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["vite/client"]
  },
  "include": ["src"]
}
</file>

<file path="windows/vite.config.ts">
import { defineConfig, type Plugin } from "vite";
import { existsSync, mkdirSync, readdirSync, copyFileSync, createReadStream } from "node:fs";
import { resolve, join, extname } from "node:path";
⋮----
function sharedSounds(): Plugin
⋮----
configureServer(server)
closeBundle()
</file>

<file path=".gitattributes">
docs/** linguist-documentation
design/** linguist-documentation
</file>

<file path="CHANGELOG.md">
# Changelog

## Unreleased

- Compact island on screens without a notch (#22) — thanks @Kamasoutra
- Only web links (http/https) open from the notch; other kinds of links from Claude or integrations are ignored (#16) — thanks @Cris1670
- Hook socket limited to your own user account, with size and time limits; logs no longer keep commands, n8n data or full URLs, and stay under 1 MB (#16) — thanks @Cris1670 and @Vignesh-Thangamariappan
</file>

<file path="CLAUDE.md">
# Coucou — guide for AI coding agents

Coucou is a native macOS app: Mochi, a small animated character living in the MacBook notch, shows Claude Code sessions and a few integrations, and lets the user approve, answer, chat and drop files from the notch.

## Where things are
- `NotchBuddy/Sources/App/` — all Swift code. `NotchBuddy/Resources/sounds/` — the 28 WAV sounds. `NotchBuddy/project.yml` — XcodeGen project (never edit the `.xcodeproj` by hand).
- `docs/SPEC.md`, `docs/INTEGRATIONS.md` — behaviour, views, states, integrations (in French).
- `design/prototype/notch-buddy.html` — original prototype, the visual source of truth. `design/captures/` — target screenshots.
- `docs/*.html` — the GitHub Pages site (privacy, terms, support, legal notice).

## Build
```
cd NotchBuddy && xcodegen && xcodebuild -scheme NotchBuddy -configuration Debug build
```

## Rules
- Swift 6, SwiftUI + AppKit. No third-party dependencies unless truly unavoidable. The character is drawn in code (`Canvas` + `TimelineView`), no Rive/Lottie/images.
- Secrets live in the Keychain, never on disk or in git.
- No telemetry. Network calls only to services the user configured.
- Never block Claude Code: if the app doesn't answer, the hook exits immediately.
- Never overwrite `~/.claude/settings.json`: dated backup, merge, show the diff, write only after the user confirms.
- Never send an email or approve a Claude Code permission without an explicit click.
- Performance: 0 % CPU when the island is hidden.
- Keep the bundle identifier `fr.louisraille.NotchBuddy` (Keychain items, preferences and permissions depend on it).
- Visual changes must match the prototype and the screenshots in `design/captures/`.
</file>

<file path="CONTRIBUTING.md">
# 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`.

Check resting island dimensions on screens with and without a notch:

```bash
bash scripts/test-screen-geometry.sh
```

## 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.
</file>

<file path="LICENSE">
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.
</file>

<file path="LICENSE-ASSETS.md">
# Coucou — name, character and artwork

Copyright (c) 2026 Louis Raillé. All rights reserved, except as stated below.

The [MIT License](LICENSE) covers the **source code** of Coucou. It does **not** cover the brand and the artwork listed here, which remain the property of Louis Raillé:

- the names **“Coucou”** and **“Mochi”**;
- the **Mochi character** — its design, look, expressions and animations as a character;
- the **app icon** and **menu bar icon** (`NotchBuddy/Assets.xcassets/`);
- the **sounds** (`NotchBuddy/Resources/sounds/`);
- the **images, GIFs and videos** in `docs/media/` and `design/`.

## What you can do

- Build and run Coucou from this repository, for yourself, as it is.
- Fork it and contribute back with pull requests.
- Show, review, write or talk about Coucou (articles, videos, posts), including screenshots and the demo media.

## What you can't do without written permission

- Publish or distribute an app, a fork or a derivative work under the name “Coucou” or “Mochi”, or with the Coucou icon, the Mochi character or the Coucou sounds — on the App Store, on GitHub releases, or anywhere else.
- Use any of these assets commercially, or in a way that suggests your project is Coucou or is made or endorsed by its author.

If you fork Coucou to ship your own app, that's welcome under the MIT License: just give it **your own name, icon, character and sounds**.

## Questions or permission requests

Open an issue on [GitHub](https://github.com/Louis-CFM/coucou/issues) or write to raillelouis@gmail.com.
</file>

<file path="README.md">
<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 Mac's notch — or at the top of your screen on Windows — and keeps an eye on your Claude Code sessions.**

Approve permissions, 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)
![Windows 10/11](https://img.shields.io/badge/Windows-10%2F11-0078D4?logo=windows&logoColor=white)
![Swift 6](https://img.shields.io/badge/Swift-6-F05138?logo=swift&logoColor=white)
![SwiftUI](https://img.shields.io/badge/SwiftUI-native-0A84FF)
![Tauri 2](https://img.shields.io/badge/Tauri-2-FFC131?logo=tauri&logoColor=black)
![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** — Claude Code permission requests show up with **Allow / Deny**. One click, back to work.
- 🧑‍💻 **Jump to the right terminal** — open the exact terminal window of a session *(macOS)*.
- 💬 **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 *(email: macOS, Mail.app)*.
- 🪟 **Drag Mochi onto any window** — attach that window as context for Claude *(macOS)*.
- 🔌 **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 (the top edge of the screen on Windows).
- 🖥️ **Any Mac, notch or not** — on an iMac, a Mac mini, or a MacBook with its lid closed on an external display, Mochi sits in a small bar at the top of the screen.
- 🔒 **Private by design** — no telemetry, no account. Keys live in your macOS Keychain or Windows Credential Manager. 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 for macOS

1. Grab the latest `Coucou.zip` from [Releases](https://github.com/Louis-CFM/coucou/releases).
2. Unzip and move **Coucou.app** to `/Applications`.
3. Launch. This build isn't notarized by Apple yet, so the first time macOS says it can't verify the developer: open **System Settings → Privacy & Security**, scroll down and click **Open Anyway** (only once).

### Windows

The Windows installer is **temporarily unavailable**. Microsoft Defender wrongly
flags the unsigned installer as malware; a false-positive report is under review
at Microsoft and the installer will come back once it is cleared and signed.
Until then you can [build it from source](#build-from-source).

There is no notch on a PC, so the island slides out of the top edge of the screen
instead of hiding inside one. See [`windows/README.md`](windows/README.md) for the
rest of the differences.

### Build from source

**macOS** — 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
```

**Windows** — requirements: [Rust](https://rustup.rs), Node 20+, MSVC build tools.

```powershell
git clone https://github.com/Louis-CFM/coucou.git
cd coucou/windows
npm install
npm run pack                # installer lands in windows/release/
```

## Setup

Click the Coucou icon in the menu bar (macOS) or in the system tray (Windows) → **Settings…**

| What | Why | Where the key goes |
|---|---|---|
| **Claude Code hooks** | live sessions and approvals | **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 | Keychain / Windows Credential Manager |
| Stripe, n8n, GitHub, Vercel, Resend, Notion, Cal.com | the integration pills | Keychain / Windows Credential Manager, 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 (top edge on Windows) | 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 island | turns into a box and swallows it |
| Drag Mochi onto a window *(macOS)* | attaches it as context |

## How it works

**macOS**

- **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.

The macOS app is native Swift 6 / SwiftUI / AppKit with **zero third-party dependencies**.

**Windows**

- A [Tauri 2](https://tauri.app) app (Rust + TypeScript): the island is a transparent, always-on-top window that never steals focus, Mochi is drawn in Canvas 2D with the same shapes, timings and sounds as on the Mac.
- Claude Code hooks go through a tiny `coucou-hook.exe` and a named pipe; keys live in Windows Credential Manager.
- Details and differences in [`windows/README.md`](windows/README.md).

## 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

- **Code:** [MIT](LICENSE) — use it, fork it, learn from it, just keep the copyright notice.
- **Name, Mochi character, icon, sounds and media:** © Louis Raillé, all rights reserved — see [LICENSE-ASSETS.md](LICENSE-ASSETS.md). Shipping your own fork? Give it your own name and character.

<div align="center">

**If Mochi made you smile, a ⭐ helps a lot.**

[Website](https://louis-cfm.github.io/coucou/) · [Privacy](https://louis-cfm.github.io/coucou/privacy.html) · [Terms](https://louis-cfm.github.io/coucou/terms.html) · [Support](https://louis-cfm.github.io/coucou/support.html)

</div>
</file>

</files>
