🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots 📖
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
chore: merge dev into desktop
Luis Ortiz61512a4d5230
diff --cc AGENTS.mdindex bbd16f2,d5e0bc4..3a177cc--- a/AGENTS.md+++ b/AGENTS.md@@@ -128,1263 -193,80 +135,1356 @@@ Extraction walks up from the target ele- Nearest heading- Sibling interactive elements in the same container (max 10)+ ## Narration transcript (`core/capture/voice/`)++ Attribution is a guess, so the words are kept independently of it. `assignSegments` returns a+ `TranscriptLine` for **every** segment the transcriber returned — the ones a step took, the ones+ nothing claimed (`stepId: null`), and the ones `rejectReason` threw away, with the reason on the+ line. `runNarrationPipeline` collects them into `NarrationResult.transcript`, stamped with the audio+ slice's `audioEpochMs`, and `applyNarration` in the background writes that to the `transcripts`+ table (Dexie `version(4)`) *before* it applies anything to steps — a recording where nothing was+ attributed is exactly the case this exists for, and it writes no step at all, so `saveTranscript`+ announces itself on the guides channel rather than relying on `applyNarrationToSteps` to do it.++ `VOICE_RESULT` carries an explicit `final` flag, and `applyNarration` reports `idle` and settles the+ pending promise only on that flag. It used to infer finality from `transcribingGuideId`, which the+ background sets *after* `stopVoiceCapture` resolves — but the host calls `deliver()` synchronously+ whenever there is nothing left to transcribe (no steps, or every second already flushed), so the+ result could arrive first, be read as a mid-recording flush, and leave the panel spinning on+ `'transcribing'` forever. That is why the guide claims the transcription and calls+ `markNarrationPending()` *before* awaiting the host, and releases both if the host refuses.++ One row per transcribed slice, because mid-recording flushes land separately from the tail.+ `flushedUpToSeconds` in the voice host guarantees the slices never overlap, so `mergeTranscripts`+ (`core/guides/transcript.ts`) can order them by wall clock with nothing to de-duplicate. The+ `epochMs` on each row is what makes that possible: a flush slice's seconds are relative to its own+ start, not the recording's.++ `Step.narratedDescription` holds what narration heard, verbatim. `applyNarrationToSteps` writes it,+ and only `deleteTranscripts` clears it, so an edit replaces `description` and leaves it, and `restoreNarratedDescription`+ can put the spoken text back with its `narration` source. That is the whole answer to "an edit+ overwrote what I said": the step editor offers the restore only while the two actually differ.++ The dashboard's transcript panel is the answer to the other half. It shares the side-panel column-with version history, so the store keeps them mutually exclusive, and the TopNav button only appears++with version history, so the store keeps them mutually exclusive, and the top bar's button only appears+ when `hasTranscript` says there is one — which is re-read on every guide reload, because transcription+ is still running when the dashboard opens after a recording. An unattributed line offers to append+ itself to the nearest step: `nearestStepId` looks **forward** first, since onboarding asks users to+ say what they are about to do and then do it. Accepting that writes the step onto the line+ (flagged `addedByHand`) as well as into the description, so the line reads as+ used from then on and a second visit to the panel cannot append the same words twice.+ `addTranscriptLineToStep` does both writes in one Dexie transaction, and re-reads the line inside it:+ done separately, a throw between them left the words in the step with the line still reading unused,+ and a double click appended them twice. Restoring that+ step's spoken original deletes the appended sentence, so `restoreNarratedDescription` releases the+ lines it just wiped out and they return to unused — otherwise the panel would claim a step still+ carries words it no longer has, with no way left to re-add them. Only hand-added lines are released;+ an attribution narration made itself is a record of what the pipeline decided and stays put.++ Privacy is the cost of keeping this. A verbatim transcript is more sensitive than per-step text —+ smart blur cannot reach speech, so a password read aloud lands in it as plain text. It is therefore+ local-only: never in an exported guide, deletable on its own from the panel — which also clears+ `narratedDescription` from the steps and from the snapshots that copied them, so “gone for good” is+ true — and swept by `permanentlyDeleteGuide` alongside snapshots. Clearing `narratedDescription` is+ not enough on its own: a step narration wrote holds the same words in `description`, and descriptions+ go into every export while transcripts go into none, so `forgetSpokenWords` also puts any step still+ sourced `narration` back on its rule-based text (`buildFallbackDescription`, source `heuristic`), and+ strips the sentences an `addedByHand` line pushed into a step — those are stamped `manual`, so the+ source alone would have left verbatim speech behind. A description the user or the AI wrote is+ otherwise left alone. `mergeGuideInto` re-keys transcripts onto the+ guide it merges into and records the redirect in the `guideMerges` table (Dexie `version(5)`, swept by+ `permanentlyDeleteGuide`), and+ `saveTranscript` resolves the owning guide before it writes — by the guide a line's step now sits on,+ or by walking that redirect chain — because an insert-recording deletes its staging guide before+ narration lands, and a slice where nothing was attributed has no step to resolve through. The+ redirect is a table and not module state in `core/guides/service.ts` on purpose: the only path that+ reads it is the tail transcription after a merge, and MV3 evicts the background worker after about 30+ seconds idle, so an in-memory redirect dropped the transcript with no error and no retry. Stripping the spoken text rewrites the stored+ snapshot steps, so `deleteTranscripts` recomputes each `contentHash` too, or version history would+ stop collapsing two identical saves into one row. Nothing was added to any export path, and nothing+ should be.++ What is *not* recoverable: speech the energy gate never detected, and a mis-transcription. Both need+ the audio, and the audio is released at `recorder.stop()`. Keeping it is still a separate bet (see+ the voice-over section) — what the transcript buys is the paid-for text that used to be thrown away+ between the API response and the step write.++## Element Metadata++`ElementMeta` describes the thing the user acted on, and it is written by more than one kind of+capture. `source` says which — `dom` in the extension, `ax` on macOS, `uia` on Windows. It is absent+on records captured before the field existed, so read it through `elementSource(meta)`, which+defaults to `dom`.++The identity fields are shared, and every source populates them:++| Field | DOM | macOS AX | Windows UIAutomation |+|---|---|---|---|+| `role` | `role` attribute, else tag name | `AXRole` | `ControlType` |+| `name` | `name` attribute | `AXIdentifier` | `AutomationId` |+| `textContent` | trimmed text | `AXValue` / `AXSelectedText` | `Value` |+| `ariaLabel` | `aria-label` | `AXTitle` / `AXDescription` | `Name` |+| `placeholder` | `placeholder` | `AXPlaceholderValue` | — |+| `altText` | `img.alt` | `AXHelp` | `HelpText` |+| `rect` | `getBoundingClientRect()` | `AXPosition` + `AXSize` | `BoundingRectangle` |++The mapping is chosen so the shared precedence in `buildFallbackDescription` — `ariaLabel`,+`placeholder`, `textContent`, `altText`, `name`, `role` — picks the right string without anyone+branching on `source`. That is why the accessible name lands in `ariaLabel` rather than `name`:+`name` sits near the bottom of that list, and a control's accessible name should beat its value.+`name` therefore holds the stable machine identifier instead, which is what a future desktop replay+will want. A description never quotes one that reads as an identifier — no spaces, and a digit, a+separator or a camel-case join, like `fl-post-111` or `SaveButton` — because that is an id attribute,+not something a reader can find on screen. UIAutomation has no placeholder property in the API surface we bind, so that field stays+null there.++A fourth source, `screen`, knows only where the click landed: it fills `rect` with a fixed box around+the click point, `clickPoint`, `devicePixelRatio`, `app` and `window`, and leaves every identity field+null.++`tag`, `cssSelector`, `href` and `dataTestId` are DOM-only and absent elsewhere. `app` and `window`+are the reverse — desktop only — and so are `ancestors` and `children`, the role and name of up to+four elements above the target and twelve directly inside it, filled only when the target has no+name of its own. `inputType` is mostly DOM-only, but a desktop typing step sets it to+`password` when the field says so, because that is the one input type a screen capture can learn.++Guide Me is the one place a `source` check is correct, through `isReplayable`. It replays against a+live DOM, so a step is replayable only when its source is `dom` — or absent, which means it predates+the field and was therefore a DOM capture. The old test was "does the step have an `elementMeta` at+all", which was true before desktop existed and is now true of every desktop step; it left a Guide+Me button on guides that can never be replayed. The button is not rendered at all when nothing is+replayable, rather than rendered disabled, because on desktop it could never become enabled.++Consumers must not branch on `source`. Read the shared fields first and treat the DOM-only ones as+refinements: `buildFallbackDescription` reaches the same wording through `role === 'checkbox'` that+it reaches through `tag === 'input' && inputType === 'checkbox'`. Guide Me is the exception by+nature — it replays against a live DOM, so `finder.ts` scores `cssSelector` only when present and+falls back to `*` without a tag.++## Desktop Shell++`apps/desktop` is an Electron app that consumes `@mimik/core` the same way the extension does.++| Piece | File | Purpose |+|---|---|---|+| Main | `src/main/index.ts` | Window, tray, single-instance lock, start-at-login |+| Updater | `src/main/updater.ts` | `electron-updater`, only ever runs when `app.isPackaged` |+| Preload | `src/preload/index.ts` | `window.mimik` over `contextBridge`, context isolation on |+| Renderer | `src/renderer/` | Vite app; aliases `@mimik/core` at the package source |++Electron rather than Tauri because `core/export/video-export.ts` needs WebCodecs, which is+unreliable in the system webviews Tauri uses — WebKitGTK in particular.++Closing the window hides it; the app keeps running in the tray and only exits through Quit or+`before-quit`. Start-at-login is stored by the OS via `app.setLoginItemSettings`, so there is no+settings file to keep in sync, and `openAsHidden` pairs with the `wasOpenedAsHidden` check in+`ready-to-show` so a login launch does not steal focus.++A loading screen covers the gap between launch and the window being ready: a 400 × 300 frameless,+transparent window, centred and above everything, with the mascot winking, the name and a sweeping+bar. It opens first thing in `whenReady`, and the main window's `ready-to-show` closes it and shows+the window — but only once the splash has been on screen for 1.5 s, one sweep of the bar, and never+later than 3 s if the splash itself fails to paint. The floor is counted from the splash appearing,+not from it being created: in dev its page took as long to load as the app's, so a floor counted+from creation had expired before the splash painted and it was closed unseen.++That load time was the shapes import. `mascot()` took the geometry from `@mimik/ui`, and in dev,+where nothing is bundled, importing the package entry loads every module in the package — the same+work the app window does. The splash and the overlay therefore import+`@mimik/ui/common/lib/mascot-shapes` directly, the one deep import besides `env` and `global.css`+that the lint allows; it is plain data, so it cannot drag the package in with it. A launch at login skips it, for the same reason `openAsHidden`+exists — that launch must not put anything on screen. `splash.html` draws the mascot with the+overlay's `mascot()` builder, so the drawing still comes from the one set of shapes.++The window also hides the moment a capture begins — Start in the sheet, the tray's area editor, or the+start shortcut — so Mimik never records itself, and it comes back when the guide is finished, or on+Cancel when it was open beforehand. Its renderer keeps full speed while hidden, because it is the+one writing every step. The tray icon carries a red dot for as long as a recording runs, and clicking+it then finishes the recording rather than opening the window.+++The YAML loader in `electron.vite.config.ts` writes the word "import" inside locale strings as++`\u0069mport`. electron-vite's CommonJS shim is inserted after whatever its pattern takes for the last++`import` statement, and the phrase "file to import" in a locale string was taken for one, which put++the shim inside the string and broke the main build. JavaScript reads the escape back as the same++word.+++`pnpm dev:desktop` runs it, `pnpm build:desktop` compiles, `pnpm pack:desktop` produces an unpacked+app in `apps/desktop/dist`. The root script calls it with `run`, because `pnpm --filter … pack` is+pnpm's own command: it wrote a tarball of the package and never built the app. `electron-builder.yml`+targets dmg/zip, nsis and AppImage/deb, and `executableName` must stay set or the binary inherits the+scoped package name.++The app icon is the extension's, `public/icon.svg`, so the two products share one mark.+`resources/icon.png` is it at 1024 px, which electron-builder turns into the macOS and Linux icons,+and `resources/icon.ico` holds 16 to 256 px drawn from the vector rather than scaled down from the+large one, so the taskbar sizes stay sharp. The main window sets it too, which is what puts it in the+taskbar in dev and on Linux. They are renders, so a change to the SVG means redrawing both:+`rsvg-convert -w 1024 -h 1024 public/icon.svg -o apps/desktop/resources/icon.png`, and each ICO size+the same way combined with `magick`.++## Desktop Capture Primitives++`apps/desktop/src/main/capture` holds the five things a desktop capture needs. One comes from+Electron, three are prebuilt npm packages, and only the last is a crate we maintain.++| Primitive | Source | Native |+|---|---|---|+| Displays, DPI, cursor | Electron `screen` | no |+| Screenshot of a display | `node-screenshots` | prebuilt |+| Focused foreign window | `@mimik/capture-native` on Windows, `get-windows` elsewhere | ours / prebuilt |+| Global clicks and keys | `uiohook-napi` | prebuilt |+| Control under a point | `@mimik/capture-native` | ours |++Screenshots do not go through Electron's `desktopCapturer`. That route asks the xdg desktop portal+on Wayland and fails outright when the portal does not answer, and it was returning frames that+decoded to nothing on Windows. `node-screenshots` talks to each platform's own capture API, so it+has a Wayland path and needs no portal. Monitor identifiers there have nothing to do with Electron+display ids, so the monitor is resolved from a point inside the display's bounds rather than matched+by id.++Anything richer than these four — the accessibility tree in particular — has no prebuilt package+worth taking, so it is an addon of our own in `packages/capture-native`.++**On Linux, input and window lookup are X11 only; screenshots are not.** `uiohook-napi` links+`libX11`/`libXtst` and hooks through `XRecord`, with no Wayland path; on a Wayland session the hook+starts and then silently delivers nothing. `get-windows` shells out to `xwininfo`, also X11. Both are+gated on `XDG_SESSION_TYPE` and refuse up front with `reason: 'unsupported-session'` rather than+appearing to work. Screenshots work on both, so a Wayland machine can still exercise the capture and+export path even though it cannot record clicks. Linux also needs `xwininfo` and `xprop` on `PATH`.+macOS and Windows are unaffected.++`pnpm --filter @mimik/desktop check:capture` builds and exercises every primitive, printing `ok`,+`n/a` for a platform limit, or `FAIL`. Only `FAIL` sets a non-zero exit, so the check is meaningful+on a machine where half the primitives cannot work.++## Desktop Accessibility Addon++`packages/capture-native` is a napi-rs addon exposing one thing: `elementAtPoint(x, y)`, the+accessibility metadata for whatever control sits under a screen point. Nothing else belongs in it.+Displays, screenshots, window lookup and the input hook are all covered by prebuilt npm packages+already, and the accessibility tree is the only primitive with no usable package behind it — the+candidates on npm either ship no prebuilt binaries at all, bind the wrong API, or are unmaintained,+and an addon compiled from source at install time would need a full C++ toolchain on every user's+machine.++Rust rather than C++ because `node-gyp` cannot cross-compile and `cargo` can. `pnpm --filter+@mimik/capture-native build:windows` produces `capture-native.win32-x64-msvc.node` on a Linux+machine through `cargo-xwin`, which downloads the Windows SDK headers and import libraries itself.++`activeWindow()` is the focused window on Windows and `windowAt(x, y)` the top-level window under a+point, and they replaced `get-windows` there. That package+downloads its Windows binary in an install script, pnpm only runs the scripts `onlyBuiltDependencies`+names, and without the binary `activeWindow()` returns nothing and throws nothing — so every Window+mode capture quietly fell back to the whole screen and no guide was ever named after its app.+`get-windows` still serves macOS, where the binary is in the package, and Linux, where it shells out+to `xprop`, and it stays the Windows fallback when the addon is missing.++The lookup is the foreground window with its visible frame, `DWMWA_EXTENDED_FRAME_BOUNDS`, rather+than `GetWindowRect`, whose rectangle includes the invisible resize border and would put a strip of+whatever is behind the window into every crop. A popup is framed as the application it belongs to:+when the foreground window covers no more than 80% of the largest monitor and of the whole desktop by+area, and it is a menu, dialog, dropdown, tooltip, owned, tool or captionless popup window, the+largest visible, uncloaked, unowned window of the same process that has a system menu and any caption+style is used instead. The app+name is the executable's `FileDescription`, falling back to its file name, which is what+`get-windows` reported, so guide names do not change between the two paths. `window.rs` holds the+popup and screen-coverage rules without COM or user32, so they are tested on Linux beside `hit.rs`.++Windows only. `is_supported()` answers false everywhere else and `elementAtPoint` resolves to null,+so the app, the checks and the recording pipeline all behave the same as when the binary is simply+missing. macOS is the same shape of work against `AXUIElementCopyAttributeValue` and is not done.++The implementation is `IUIAutomation::ElementFromPoint` and six property reads, plus a walk of the+control view when the element has no name. Named elements skip the walk, because every step of it is+another cross-process call into the application being recorded.++The hit test alone is not the answer. It returns whatever the application's provider says is at the+point, and some providers answer with a layer rather than a control: the Windows 11 search panel+reports a pane called "CoreInput" covering every result, so each click on a result was named after+it. Whenever the hit has children, its whole subtree is fetched with `FindAllBuildCache`, the+rectangles cached so the lookup is one cross-process call rather than one per element, and the+smallest element whose rectangle holds the point is used instead, skipping Chrome's tab-drag layer+(`TabDragContextImpl`), which covers the tab strip and would otherwise win every click there. A tie keeps the outer element,+since `FindAll` lists a parent before its children and the parent is the control. A text field is+left alone, because narrowing it would land on the text run inside and turn "Enter" into "Click".+`smallest_under` in `hit.rs` is that rule with no COM in it, which is why it is the one part of the+addon with tests that run on Linux. COM is initialised+multi-threaded once per worker thread and the `IUIAutomation` instance is cached in a thread local,+because the call runs on the libuv threadpool through `AsyncTask` rather than on the main thread —+a cross-process UIAutomation call against a busy application blocks for as long as that application+takes to answer, and blocking Electron's main thread there would freeze the overlay mid-recording.+Rectangles come back in physical pixels, so the caller converts the point with `dipToScreenPoint` on+the way in and the rectangle with `screenToDipRect` on the way out, the same convention+`focusedWindow` follows.++`ControlType` is translated to the ARIA-ish role vocabulary the rest of the app already speaks, so+`role === 'checkbox'` means the same thing whether it came from a DOM attribute or from+`UIA_CheckBoxControlTypeId`. An unmapped control type yields a null role rather than an invented+name.++`focusedElement()` is the second call. The remaining three — `keyLabel`, `resolveKey` and+`clearDeadKey` — are the keyboard, and unlike the first two they are synchronous, because+resolving a scancode against a keyboard layout is a local call with nothing to wait on. It reports `isPassword` alongside the usual fields, and the value is discarded at the+addon boundary when that flag is set, so a password never reaches our data even though UIAutomation+already withholds it.++## Overlays We Put In The Page++Five things draw into a page someone else owns: the hover ring, the blur picker, the blur panel, the+Guide Me overlay and the recording notification. All five are the same construction — an element+carrying `data-mimik-ignore` with a closed shadow root and one `<style>` — and `createOverlayRoot`+builds it.++Both attributes are load-bearing and neither fails loudly. Without `data-mimik-ignore` the overlay+becomes a capture target and a blur candidate, so recording the page records our own chrome; with an+open shadow root the page's CSS reaches in and restyles it. Five hand-written copies meant five+chances to forget one, and three of the five had no test at all. One function has one test, and it+asserts both invariants by construction: a closed root reads back as `null` through `host.shadowRoot`,+which is the assertion for `mode: 'closed'`.++Reading the attribute back is `isMimikElement`, in `capture/dom/element-utils.ts`. The blur picker+had grown a private copy of it, identical line for line.++## Boundaries The Linter Holds++`biome.json` covers `src`, `packages/core`, `packages/ui`, `apps/desktop` and `scripts`. `packages/ui` was+missing from that list for a long time and nobody noticed, which is how forty-odd files reached it+unchecked; adding it produced forty-one fixes on the first run.++A `noRestrictedImports` override forbids anything under `packages/**` from importing `@/lib/*`,+`@/ui/*`, `@/entrypoints/*`, `#imports` or any path through `apps/`. Shared code may never depend on+an app. It is the rule that keeps `packages/ui` genuinely shared rather than quietly coupled to one+surface, and it is also the licence seam: an MIT package that imports from a copyleft app is no+longer MIT.++One boundary the linter does **not** hold, and it bites: main-process code may only take `type`+imports from `@mimik/core`. The renderer aliases the package to its source and bundles it, while+`electron-vite`'s `externalizeDepsPlugin` leaves it external in main, so a value import resolves at+runtime to a path with no file and the app dies on launch with `ERR_MODULE_NOT_FOUND`. That is why+`capture/screenshot.ts` keeps its own three-line `clamp` rather than importing core's: deduplicating+a one-liner is not worth a cross-boundary dependency that does not work.++## Code Layout++`packages/ui/src` is grouped by feature, not by the surface that first used a file: `ai`,+`annotation`, `branding`, `common`, `export`, `guide`, `history`, `library`, `navigation` and `search`. Inside a+feature, components sit in `components/`, hooks in `hooks/`, plain functions in `lib/`, a store+slice in `store/`, and a `types.ts` only when several files share a type. `components/ui` holds the+shadcn primitives as the generator writes them, and `stores/` merges the slices.++The apps take the same shape one surface at a time. Each of `src/ui/sidepanel`, `fullview`,+`onboarding`, `mic-permission`, `shared` and `apps/desktop/src/renderer` keeps its components side by+side, its functions in `lib/` and its hooks in `hooks/`. `src/lib` is already a lib folder, so a+module there that held several functions became a folder named after it — `browser-api/`, `port/`,+`offscreen/`, `update-notice/` — and the voice pieces share `voice/`. An entry script such as+`overlay.ts` or `check-storage.ts` keeps only its dispatch and imports the rest from a folder of the+same name.++A file exports one thing — a component, a hook or a function — and is named after it. A hook or a+`lib/` function may keep one private helper that nothing else calls; a component file keeps none, so+its helpers live in `lib/`. Constants, types and objects of functions may sit beside the export they+serve. That rule holds in all four roots: `packages/ui/src`, `src/ui`, `src/lib` and+`apps/desktop/src/renderer`.++Exports are named. A default export can be imported under any name, so one component can read+differently at every import site; a named one is found by the same search everywhere. WXT+entrypoints and the config files keep their defaults because the framework reads them, and the one+`React.lazy` maps a named export onto the `default` it needs.++The apps import from `'@mimik/ui'` and nowhere deeper, except `@mimik/ui/env`,+`@mimik/ui/global.css` and `@mimik/ui/common/lib/mascot-shapes`, the mascot's geometry, which pages+that must load instantly take without the rest of the package. `src/index.ts` is the one file allowed to re-export. Inside the package every+import is relative — it never names itself, through the entry or otherwise, so it cannot cycle+through its own index. The extension build was diffed against the baseline from before the entry+existed: the content script came out byte-identical, and the whole build within a few hundred bytes.++State that several functions share lives in a `{ current }` holder — `localVoiceHost`, the offscreen+document's `creating` promise, `lastVoice` in `port/state.ts` — because an imported `let` is+read-only in the module that imports it, so a getter and setter pair could not be split without one.+The UI package's env adapter is the same idea for functions: `tabs`, `panel` and `messages` are+objects of accessors over the one configured adapter, which leaves `configureUi` its only export.++The linter holds it. `noRestrictedImports` rejects a deep `@mimik/ui/*` import from the apps and any+`@mimik/ui` import from inside `packages/`. `noBarrelFile`, `useComponentExportOnlyModules` and+`noDefaultExport` cover the four roots, with the shadcn primitives excused from the second since they+export their `*Variants` beside the component. `scripts/check-exports.mjs` runs after Biome in+`pnpm lint` and catches what no Biome rule can: a second exported function, a helper declared in a+component file, a second private helper anywhere else, and any re-export outside the package entry.++Three things break quietly when files move here. The root `tsconfig.json` declares its own `paths`,+which replace the ones in `.wxt/tsconfig.json` rather than extending them, so the bare `@mimik/ui`+entry has to be listed in the root config and in `apps/desktop/tsconfig.json` alike. A `vi.mock`+path is a string the refactoring tools do not rewrite; a stale one mocks nothing without failing,+and once a module is split each mock has to name the file its function now lives in —+`vi.mock('@/lib/browser-api/local-storage')`, not the folder. And `sideEffects` in the package's+`package.json` names `common/lib/dayjs-locale.ts`, because that file registers the dayjs locales by+importing them; renaming it without updating the entry lets a bundler drop the translations.++## Which Client Is Running++`configureCore` carries a `client`, `extension` or `desktop`, and `client()` reads it back. Shared+code that must genuinely behave differently asks at runtime rather than taking a prop for it, which+is how the surfaces stay one codebase instead of two dressed as one.++The distinction worth holding: a **prop** is right when the app supplies behaviour the shared code+could not know — `onStartCapture` opens a capture sheet on one surface and a side panel on the+other, and neither belongs in `packages/ui`. `client()` is right when shared code decides for+itself, with nothing to pass down.++The rule that keeps `packages/ui` from becoming a filing problem is simpler than a taxonomy:+anything in it belongs to **both** surfaces. Asking which surface owns a file there means it is in+the wrong place, and it should live in `apps/desktop` or in the extension's `src/ui`. That is why+`CaptureSheet`, the capture settings and the overlay have never been shared — they are not shared+components filed badly, they are the parts of the desktop that have no counterpart at all.++## Desktop Storage++The desktop app reuses `@mimik/core/guides` for everything except the screenshot bytes — Electron's+Chromium provides IndexedDB, so `MimikDB`, the service layer and the Dexie migrations all carry over+with no rewrite. A screenshot row holds a `src` instead of a `blob` when the bytes live on disk, and+the service hydrates one into the other on read, so the distinction stops at the storage layer.+`MimikDB` takes an optional database name so a check can open a throwaway store instead of the+user's `mimik` one.++Core reaches the surface through `configureCore`, so every desktop entry point imports+`src/renderer/core-env.ts` for its side effect, exactly as the extension imports `src/lib/core-env.ts`+— the app window, the overlay and the splash alike. The desktop adapter backs settings with+`window.localStorage` and translates through the same six locale files the extension ships.++Which one is the App language setting under General — the language picked there, or the system's+when it is left on "Same as the system" — resolved by `appLocale` from `navigator.language`, matching+a region to its language (`pt-PT` to `pt-BR`) and falling back to English. A key a locale lacks falls+back to English on its own rather than showing the key. The value is read synchronously when+`core-env` loads, so changing it stores it, reloads every window through `mimik:app:relocalise`, and+reopens the settings on General in the window that asked. The extension has no picker, because+`browser.i18n` follows the browser's own language and cannot be switched at runtime.++The main process translates the tray, its menu and the dialogs through `mainI18n`, which bundles the+same six locale files. It cannot use core's `translate`, since main may only take types from core,+so it keeps its own dozen-line lookup, with the same English fallback per key. Main has no+`localStorage`, so it cannot read the chosen language: it starts on the system's, matched to a+supported language, and the app window reports the one it resolved as soon as `core-env` loads,+through `mimik:app:locale`, which also rebuilds the tray menu. Picking a language reloads every+window, so the report follows the choice.++The overlay and the splash have no React, but they read strings through `i18n.t` like everything+else, and wherever the extension already names a thing they use its key: the card's header is+`recording.recording` / `recording.capturePaused`, its Remove button `recording.deleteStep`, its+badges `stepSource.*`, its step line+`export.stepLabel`, and the area editor's buttons `common.cancel` and `annotationEditor.done`. They+had been hand-typed English — "Remove this step", "Paused", "Writing step description…" — so one+action read differently in the side panel and on the card, and a desktop key existed for half of+them that nothing read. Copy the extension has no counterpart for (the card's tips, "Starting…",+"Capturing step N") is still written in the overlay.++`pnpm --filter @mimik/desktop check:storage` runs four checks across two hidden `BrowserWindow`s:- the v1 to v2 upgrade against a real v1 store, `MimikDB` opening at v2 with all four tables, a guide++the upgrade from a real v1 store to the current version, `MimikDB` opening at v5 with all seven tables, a guide+written through the core service, and that same guide read back from a second renderer process with+its screenshot `Blob` intact. Results come back over a tagged `console-message` rather than IPC, so+the check windows need no `nodeIntegration` and no production preload channel. `window-all-closed`+is a no-op there, or destroying the first window would quit the app before the second one ran.++Two surfaces sharing a guide means two windows of the same app. The extension and the desktop app+are separate origins with separate stores; moving a guide between them is the portable format's job.++## Capture Area and Controls++The capture region is a screen-coordinate rectangle that survives restarts in+`capture-region.json` under `app.getPath('userData')`. `clampToDisplays` runs on every load and save,+so a region stored against a monitor that is no longer attached lands back inside a real work area+instead of off-screen, and nothing smaller than 60 × 30 is storable, so a single toolbar or a narrow+sidebar can be the whole area.++`CaptureOverlay` owns three kinds of window, all frameless, transparent and `alwaysOnTop` at+`screen-saver` level. The controls are a card docked to the bottom-right of the work area, not a bar+across the middle of the screen, because the middle is where the work being recorded happens:++| Window | When | Input |+|---|---|---|+| Editor, one per display | `editing` | interactive — drag to draw, move or resize |+| Boundary, sized to the region | `armed`, `recording`, `paused`, `region` mode only | click-through |+| Controls bar | `armed`, `recording`, `paused` | interactive |++The boundary only exists in `region` mode, because the other two modes have no fixed rectangle to+draw. `overlay.ignores(point)` keeps clicks on the card from becoming steps — without it, pressing+Pause in whole-screen mode would capture pressing Pause.++The card carries what the extension's recording view carries, shrunk to sit over someone else's work:+state, step count, the screenshot just taken, its title, and two actions. Showing the capture is the+point — it is the only way to tell mid-recording that a step landed on the right thing, and without it+a wrong capture mode is discovered after twenty steps rather than after one. Main already holds that+screenshot's URL when it tells the overlay a step was captured, so the card reads it over the same+`mimik-screenshot://` scheme the app window uses and no image data crosses IPC. The preview shows the+whole capture, letterboxed, rather than filling its box: a tall area cropped to fill a wide box showed+only its top, magnified, which looked like the wrong screenshot when it was the right one.++Under the title the card says where the words came from, with the same Basic and AI badges the guide+uses. The renderer sends `mimik:capture:described` when the AI text arrives, and main updates the+step it is holding. There is no "writing" line, shimmer or collapsed pill — a step used to go through+two loaders, one for the screenshot and a second for the description.++The one loader is the camera mascot printing a photo, over the whole of the preview, title and badge+rows so the card keeps its height, and it covers the description as well as the screenshot. The+recorder's `progress` hook reports a fraction and how long the next stretch should take: from the+press to 90% over the screenshot delay plus an estimated grab, and 100% once the step is written.+Main scales that to 45% when an AI description is coming, eases on to 95% over 3.5 s while the model+writes, and sends 100% when it lands. The card eases a registered `--p` across each stretch, never+backwards within one capture, which pushes the photo out of a slot under the camera and develops the+real screenshot in it from 40%. The step lands once, with the AI title and badge; the Basic title+never flashes first. A description that has not arrived after 8 s lands the step as Basic, and the+AI text still replaces it in place when it comes. Landing fires the flash and grows the photo,+through the Web Animations API, from where it was printed into the preview's own rectangle; the+title and badge fade in once it arrives. Nothing of the previous step shows while this runs, which is what the old veil was for: with a+delay set, the last screenshot showing through read as the new step taken with the old picture.+Reduced motion skips the grow. A title that wraps onto its second line takes that line from the+screenshot rather than from the screen: the preview is 150 px less whatever the title adds beyond+one line, which the card measures after every render, so the card is one height while capturing and+once any step lands, and the order stays the extension's — screenshot, title, badge row. A Remove button on the+preview drops the step just taken: main keeps the recording's steps in order, asks the renderer to+delete the last one and puts the card back on the one before, so a wrong capture is undone where it+was noticed. The Ready and waiting states name the start/stop and capture-now shortcuts, read from the+settings, because the card is the one place someone looks while deciding how to begin. The header+names the capture mode while arming and recording, since a wrong mode is what spoils a whole guide;+while paused the mode picker says it instead. A pause before the first step shows the camera mascot+resting, with "Nothing is recorded while paused.", rather than a card that is only a header and+buttons.++Everything the card draws arrives as one `OverlayView` — state, region, step, mode, busy, starting+and the shortcut labels — through `view()` and `onUpdate`, rather than five positional arguments that+every new field would have lengthened.++All three roles are one HTML file and one stylesheet, told apart only by `body.editor`,+`body.boundary` and `body.controls`, so an id is shared across three documents. The card's rules are+scoped under `body.controls` for that reason: an unscoped `#hint` already existed for the region+editor, absolutely positioned and dark, and it silently captured the card's hint the first time both+used the name. `check:overlay` asserts the card's hint computes to `position: static`, which is the+cheapest way to catch the next collision.++The card sizes itself. The renderer reports `scrollHeight` after every render and main moves the+window to match, so a long step title or a collapse does not need a table of per-state pixel heights.+That only works because `body.controls` overrides the shared `height: 100%`: a body pinned to the+window's height reports the window's height back, and the card could never grow.+Collapsing turns it into a pill; the mode picker appears only while paused, since a mode cannot+usefully change between one click and the next, and it is what made the old bar 452 px wide.++Editing puts a full-display window on **every** display rather than only the one holding the region,+which is what makes moving the region to another monitor work: each editor converts client to screen+coordinates with its own display origin, and whichever one you draw on wins. Outside editing the+boundary shrinks to the region itself and takes `setIgnoreMouseEvents`, so recording never swallows a+click. The boundary is solid and steady while recording, dashed and grey while paused. It used to pulse,+which read as something wrong with the area rather than as "recording" — the card already says that.++The editor draws the area the way the screenshot crop tool draws its frame, so one rectangle means+one thing across the app: the outside dimmed with the same navy, purple corner brackets as the+resize grips, and invisible grips along the four edges. The edge itself is a white line with a purple+dash over it, because the area sits over whatever is on screen and a single colour disappears+against half of it — white on a light app, purple on a dark one. Its Cancel and Done live in the+standard action bar at the top, with Esc and Enter doing the same.++Where editing returns depends on where it began. From the Ready state or the tray it arms as before.+From a recording, Done carries on recording: picking Area on the paused card and pressing Enter+resumes straight away, because drawing the area is the last thing between the person and the next+step. Cancel goes back to the pause after restoring the mode that was active before Area was picked,+and the tray's editor during a recording returns to that recording either way. Picking Area mid-recording used to only save the setting, so the next steps were+cropped to whatever area was stored last with no way to draw one, and the editor's Esc sent `cancel`,+which ends a recording.++Overlays must not appear in their own capture. `setContentProtection(true)` is what keeps them out,+and **it is applied after the window is shown, never at creation**: on Windows it sets a display+affinity on the native handle, and a handle that has not been realised yet does not take it. Setting+it in the constructor looked correct and silently did nothing, which put the recording card inside the+screenshots it was displaying.++`overlay.withHidden(fn)` is the fallback for Linux, where content protection is a no-op. It hides+every visible overlay for the duration of `fn` and restores exactly the ones it hid, reapplying+protection on the way back. Hiding a window is visible as a blink once per captured step, so it is+used only where nothing else works. It waits 60 ms after hiding before running `fn`, since a grab+taken straight after `hide()` can beat the compositor and still contain the card. Grabs can overlap —+a click that closes a typing session starts two — so overlapping calls share one hide and the+windows come back when the last of them finishes. `setOpacity(0)` is+not an alternative: it stopped captures happening at all.++Anything the card hides is hidden with the `hidden` property, and `body.controls [hidden]` forces+`display: none` because several of those elements are flex containers whose author rule outranks the+browser's default for `[hidden]`. Without it the instructions stayed on screen behind the first+screenshot and collapsing never hid the buttons.++The card's icons come from `lucide`, the vanilla build of the same icon set `lucide-react` gives the+rest of the app, so a pause or a check is one drawing everywhere. The React package is not used here+because the overlay renderer has no React and importing an icon component pulls the runtime in with+it; `lucide` has no dependencies and hands back an `SVGElement`. Copying path data out of either+package is not the alternative — that silently pins the overlay to whatever the icons looked like on+the day it was written.++The mascot's geometry lives once, in `packages/ui/src/common/lib/mascot-shapes.ts`. `MascotIcon` renders it+as React with Tailwind classes so it themes with tokens; the overlay builds the same paths as DOM nodes+with CSS variables, because that renderer has neither React nor Tailwind. The camera-holding variant+is the same mascot dropped by `CAMERA_MASCOT_DROP` with `CAMERA_MASCOT_PARTS` over it, rendered by+`CameraMascot` in the extension's recording view and by `cameraMascot` on the card. Two renderers, one set of+coordinates — copying the paths into the overlay would have made it the fifth copy of this drawing in+the repository.++The footer is always the same two slots: the transient action on the left, the one that moves the+recording forward on the right, filled. That filled button is `--deep` in every state. A paused+variant that filled it with `--accent` was tried and removed: the design system reserves the accent+for icons, links, focus rings, toggles and meters and never for a button fill, and the header+already says "Paused" beside a stopped dot, so the colour was carrying no information the card did+not already show. Close then Start while armed, Pause then Finish while+recording, Resume then Finish while paused. Finish keeps the right-hand slot for the whole recording+so it never moves under the cursor.++A capture is in flight from the moment the grab starts until the capture queue is empty again, and+`overlay.setBusy` spans exactly that: the grab sets it and the recorder's `drained` hook clears it.+Finish is disabled while it holds, so a recording cannot be finalised between the screenshot and the+row that points at it. It is cleared on the queue emptying rather than on a step being written because+not every grab ends in a step — a typing session whose field turns out to hold no text is grabbed at+the moment it closes and then dropped, and clearing only on a write left the card saying "Capturing+step 4…" with Finish disabled for the rest of the recording.++`pnpm --filter @mimik/desktop check:overlay` asserts persistence, clamping, one editor per display,+controls clearing the region, whole-screen mode dropping the boundary, clicks on the bar being+ignored, and the state changes — driving Start and Pause through a real renderer+click so the preload and IPC path is covered rather than the main-process methods alone. Start is+asserted twice: the intro window opens over the capture area with the card saying "Starting…" and no+start reaching the host, and then, once the real animation has finished, the recording begins. The+card's states are asserted from the rendered DOM — the waiting prompt, the badge moving from Basic to+AI with the title shown throughout, the printer at a reported percentage and waiting for the AI description before the step lands, and the Remove command. On Linux it+runs under `xvfb-run` when available (`xorg-server-xvfb`), so the check does not throw always-on-top+windows over whatever you are doing.++Everything under `out/main` stays flat: `chunkFileNames` is pinned alongside `entryFileNames` because+main-process code resolves `../renderer` and `../preload` from `__dirname`, and a shared chunk landing+in `out/main/chunks/` silently breaks every one of those paths.++## Desktop Capture Pipeline++A desktop capture produces an ordinary `Guide` with ordinary `Step` and `Screenshot` rows. There is+no desktop step type and no desktop guide type, so every exporter reads them without knowing where+they came from.++The work splits across the process boundary the way the extension splits across content script and+service worker. `DesktopRecorder` in main owns the global input hook, discards clicks outside the+capture region or while paused, and serialises the rest through a single promise chain so two clicks+cannot interleave. For each click it hides the overlays, grabs the display, crops to what the capture+mode frames, and writes the result to disk. `DesktopCaptureSink` in the renderer+implements `CaptureSink` and writes through `@mimik/core/guides/service`, exactly as the extension's+`step-pipeline.ts` does.++The two surfaces reach that write by different routes but build the screenshot row the same way, so+`screenshotForElement` owns it. It turns an `ElementMeta` and whatever holds the bytes — a `Blob` in+the extension, a `src` on the desktop — into a row with the bounds in CSS pixels, the pixel ratio,+the click point, and the dashed target scaled by that ratio. Scaling the target is the part worth+having once: a rectangle multiplied in one surface and not the other puts the dashed box on the wrong+thing, and nothing about that fails a build. The description queue is shared too, as below. The rest+of the two paths genuinely differs — voice narration and the input finalisation exist only in the+extension, and the application name only on the desktop.++Main cannot `invoke` a renderer, so `ask()` sends a request with a generated reply channel and waits+for `ipcMain.once` on it, with a timeout. The preload's `onRequest` is the other half. A handler that throws+answers with `{ error }`, and `ask()` rejects with that message rather than resolving with it. It used+to resolve, so a guide that failed to be created came back as the guide id `{ error: … }`: the start+dialog's `catch` never ran and the recording went on writing steps to no guide. Guide creation+and step writes both ride it, because both need IndexedDB, which only the renderer has.++Screenshot bytes never cross the process boundary. Main writes each capture to a PNG under+`screenshots/` in `app.getPath('userData')` and sends the renderer only an id, a URL and the pixel+size, so the message stays small and no image data rides an IPC channel. The renderer stores that URL+on the row and the service fetches it back into a `Blob` on read, which is why every consumer still+sees the shape it always did. A large binary crossing IPC is the one thing this avoids: the buffer a+native capture hands back points at memory the capture library still owns, and it does not reliably+survive the trip.++The renderer reads those files over a registered `mimik-screenshot://` scheme rather than being given+filesystem access. Main decides what that scheme will serve, the id has to look like a uuid, and+context isolation stays on. The scheme is declared privileged before the app is ready, or `fetch`+inside the renderer refuses it, and any entry point that reads a guide has to register the handler,+which includes the checks.++Files outlive the rows that point at them, because deleting a guide only removes database rows. The+renderer sends every known screenshot id to main at startup and main deletes any file not in that- set, so an interrupted delete costs disk until the next launch rather than forever.++set, so an interrupted delete costs disk until the next launch rather than forever. A known id is a++row's own id or the file its `src` names, because duplicating a guide copies the rows under new ids++while they keep pointing at the original files; counting row ids alone deleted a copy's screenshots++the first time the original was deleted and the app restarted.++A failed screenshot does not cost the step. The extension already worked this way: when the grab or+the crop throws, the step is written with its element and description and no screenshot row, and+the guide shows the image placeholder with its upload button. On the desktop the error used to reach+the capture queue, which logged it and wrote nothing, so the click vanished without a word; the card+now lands the step with an empty preview instead of printing a picture that does not exist.++A click is the press, not the release. The hook listens for `mousedown`, and the element lookup and+the display grab both start in that handler rather than when the capture queue reaches the step.+By the release the application has already acted — the new tab exists and its close button is under+the pointer, the popup the pointer was on has closed, the skipped ad has become the next button —+and every one of those read back as a confidently wrong step name. Starting them in the queue was+the same mistake with a longer delay, because a click that lands while the previous step is still+being written waits for it. A press that turns into a drag is therefore a click as well.++The display is grabbed first and cropped last. `grabDisplay` takes the whole display under the click+and hands back a function that crops it, and the frame is chosen only afterwards, so neither a+window lookup nor a delay sits between the press and the picture.++A click frames the window **under the pointer**, looked up at the press through `windowAt`, not the+window in front. The foreground moves only once the clicked application has handled the press, so a+foreground read soon after it still names the application clicked before — with two windows side by+side, every switch between them read the other one, whose rectangle does not hold the click, and the+step fell back to the whole screen. The window under the pointer is the one being clicked by+definition. Typing and key steps have no pointer to go by, so they still read the focused window,+after the grab and at least the settle delay after the key, which runs beside the grab and costs the+screenshot nothing.++The card itself is not focusable, so clicking Pause or Finish never makes the app frontmost and never+changes what active-window mode will frame next. The region editors stay focusable because they read+Enter and Escape; the card has no keyboard of its own to lose.++What a capture frames is `captureMode`'s decision, and `frameFor` owns it: the window's bounds, the+whole display under the cursor, or the drawn region. The window rectangle is resolved on+every click rather than once at Start, so a window that moves or is resized between steps is followed+with no extra work, and it falls back to the whole display whenever the lookup fails or reports a+rectangle that does not contain the click. Active-window mode therefore degrades to whole-screen+rather than erroring, which is also what a Wayland session gets.++Window bounds come back in the platform's own coordinates. Windows reports physical pixels while+every rectangle elsewhere in the app is in DIP, so `focusedWindow` converts through `screenToDipRect`+before returning — without it a high-DPI machine crops a rectangle scaled by its own DPI factor.++`elementSource` is `'uia'` when the accessibility lookup answered and `'screen'` when it did not.+A `screen` step still knows the click point, a fixed target box around it, the display scale factor+and the foreground app and window title; it just knows nothing about the control. That is what every+step degrades to where the addon has no build, where the lookup times out, and on every platform but+Windows.++The lookup starts on the press and is awaited after the grab, so it overlaps the settle delay and+the screenshot instead of adding to them. That it runs early is not only for speed:+the control has to be read before the click takes effect, or a menu that has opened or a button that+has vanished is what answers. It is the mirror of the focused-window read, which has to happen late+for the same reason — the window the click moved to the front is the one being photographed, but the+control the click landed on is the one that was there before. It is capped at 1500 ms and a miss is+`null`, never an error — a slow or unresponsive foreign application costs a step its metadata, not+the recording.++A desktop step zooms toward the click, never into it. `screenshotForElement` takes a `zoom` mode:+`element` writes `bounds` and is what the extension keeps, `click` writes an explicit+`edits.viewport`, and `none` writes neither.++The extension's rule cannot serve both. `resolveViewport` pads `bounds` by `PAD_RATIO` of the image+but never beyond `MAX_PAD_MULTIPLE` times the element, which suits a page where a control is a real+fraction of the viewport and collapses on a screen grab: a 30 px window button against 2560 px gives+a crop a few hundred pixels wide, which the card then stretches. Magnification past 1:1 cannot look+good, because the detail is not in the file.++So the zoom is a level between 1 and 5 in steps of 0.25, `snapZoom` holds it there, and+`clickZoomViewport` divides the frame by it and centres the result on the click, clamped inside the+edges. The level itself is `autoZoom`'s: the capture's width over the guide column's, so every step+renders its content at the same size however it was framed. A 2560 px screen grab at 1.5× scaling+gives 2.25, a 1200 px window gives 1, and a small one gives 1 — the same button is the same size on+every page of the guide, which a fixed fraction of the frame cannot do. The level is stored beside+the region in `edits.zoomLevel`, so it can be re-derived or overridden later without recapturing.++A setting only seeds new recordings, so the guide view carries its own Zoom control and `rezoomEdits`+rewrites the steps already captured. It recomputes from `clickPoint` and the frame, which every row+already holds, so nothing is re-captured and nothing is lost. A guide therefore stores no zoom of its+own — the level lives per screenshot and the control simply rewrites each one.++Version history does not report a zoom. `snapshot-diff` counts a changed `edits.viewport` as a crop,+and zoom writes that same field, so re-zooming a guide read back as "3 images cropped" — the history+describing the app's own framing as the user's edit. The diff now counts it only when `zoomLevel` is+absent on one side or the other, which is exactly when a person set the region. Cropping a step by+hand still registers, including when it replaces an app-set zoom.++Which steps it may touch is `edits.zoomLevel` itself: present means the app chose the region, absent+means a person did. `AnnotationEditor` clears it whenever the crop tool writes a new viewport, so a+hand-cropped step survives every later re-zoom. `rezoomEdits` returns null for those, and for a step+already at the wanted level, so the pass writes only what changes.++`edits.zoomAuto` says whether that level came from Automatic or was picked, because the number alone+cannot: a 1200 px window on Automatic and the same window at a picked 1.5× store the same level. The+guide's Zoom control reads it back through `currentZoom` and names the choice on its button and tick+— Automatic, a level, or nothing when the steps disagree — where it used to say only "Zoom" and open+on Automatic whatever the guide held, which read as the setting having been ignored. A step saved+before the flag existed counts as Automatic when its level equals the automatic one for its width,+and picking a level equal to that is still written, so the flag follows the choice. The crop tool+clears it along with the level.++`guideActions` on `AppFrame` is the slot it mounts into, in the top bar beside Edit and Export and+under the same `exportData` guard, so the control appears exactly when the rest of the guide toolbar does. The+extension passes nothing.++The control is a plain `SelectTrigger`, never `asChild` around a `Button`. `SelectTrigger` renders+its own chevron beside whatever children it is given, so with `asChild` the `Slot` receives two+children and throws `React.Children.only`, which unmounts the whole renderer — a blank window with+the guide's name still in the title bar, and nothing in the console of the app itself. `Button` is+not a `forwardRef` either. Anywhere a Radix trigger needs to look like a button, style the trigger.++`zoomLevel` in capture settings overrides the automatic choice; `null` means derive it. Main cannot+value-import core, so `settings.ts` carries its own three-line `snapZoom` rather than the one in+`record.ts` — the same constraint that keeps `clamp` local in `capture/screenshot.ts`. The renderer+has no such limit and reads `MIN_ZOOM`, `MAX_ZOOM` and `ZOOM_STEP` from core to build the picker, so+the list of levels cannot drift from the snapping.++It goes in `edits.viewport` rather than `bounds` because `resolveViewport` returns that verbatim, so+the region is exactly what was computed rather than what the padding rule makes of it, and+`resolveFrameViewport` gives the video exporter the same starting frame before it eases toward+`edits.target`. The mode is written into the data rather than branched on `client()`, so a desktop+guide frames the same way in whatever opens it, exports included, and nothing shared changes for the+extension. `check:pipeline` asserts the viewport sits inside the frame at between 1× and 2×.++`targetRect` decides what the dashed target in the screenshot encloses. The control's own rectangle+wins when there is one, which is the whole point of reading the accessibility tree; it falls back to+a 28 px box around the click when there is no element, when the rectangle covers more than half the+frame, or when it does not fit inside the frame. Without those two guards an unsupported application+returns its top-level window and the target outlines the entire screenshot.++Typing is one step, and the text in it is read rather than reconstructed. The keyboard hook decides+only *when* a typing session starts and ends; what was typed comes from the focused element's value+in the accessibility tree. That is the whole reason there is no+keycode table, no layout handling, no dead-key state and no IME composition tracking in this+codebase — the machinery those need exists to answer a question we do not ask.++A session opens on any key that is not a modifier, not `Enter`, `Tab` or `Escape`, and not held with+`Ctrl`, `Alt` or `Meta`, and every such key also appends to a buffer of what was typed. It closes on any of those, on a click, on pause, on stop, or after 1000 ms+with no keys. `Shift` plus a letter still counts as typing, which is why modifiers are tested+individually rather than as a set.++When the value is read depends on what closed the session. The idle timeout and `Enter`, `Tab` or+`Escape` read it then, because the field still has focus and the last keys are only in the live+value. A click, pause, stop or capture-now reads a snapshot instead: 400 ms after each key the+focused element is read again, because by the time a click closes the session the focus has moved+to whatever was clicked — a search suggestion, say — and a read then finds no text field and drops+the step. A key typed after the snapshot makes its value stale, so the snapshot still says which+field it was but the text comes from the keystroke buffer. No snapshot at all, a click within+400 ms of the first key, falls back to reading at the close.++Whichever read it is starts when the session closes, and so does the typing step's grab, which+follows the field read so it frames the right display. Neither waits for the queue. `Enter` in a+browser's address bar is why: by the time a queued read ran, the page had navigated, focus had+moved to the document, and the step named the new tab page and photographed its wallpaper.++Closing a session does not guarantee a step. The focused element is read first, and nothing is+written unless it is a text field with something to show for it. A password field is the exception+in the other direction: it reports no value by design, and the step is written anyway with no+`inputValue`, worded "Type password" rather than naming any contents.++Keys that are not typing get their own step, unless `recordKeys` is off. A shortcut always does; `Enter`, `Tab` and `Escape` do+only when no typing session was open, because the `Enter` that submits a field is part of that+field's step rather than a step of its own. Auto-repeat is collapsed the way a double click is —+`isRepeatKey` drops the same keycode within 500 ms, so holding a key down is one step.++Naming the key is the only place a keyboard layout is consulted. `keyLabel` maps the hook's scancode+through `MapVirtualKeyExW` against the **foreground window's** layout, so the same physical key reads+as `Q` on QWERTY and `A` on AZERTY, which is what the application being recorded will have acted on.+`ToUnicodeEx` is deliberately not used: it would name punctuation too, but it mutates the thread's+dead-key state as a side effect, and a shortcut only needs the letter, digit or named key. A key that+maps to none of those yields no label and therefore no step, rather than a step nobody can follow.++Two sources compete for the text and `typedTextFor` picks between them. The field's value wins+by default, because it is what is actually on screen and it survives caret movement, selection and+autocomplete. It is always read — a switch to use only the keystroke buffer was taken out, because it+existed for edge cases nobody would set on purpose. The+keystroke buffer wins in three cases: the focused element reports no value, the value is empty, or+the field holds more than was typed by a margin that depends on its type — 24 characters for a+document, 120 for anything else. That last rule is what makes rich text work — in a word processor+the "field" is the whole document, so its value is the entire text rather than the sentence just+typed, and the buffer is the only thing that knows which part is new. A document gets the small+margin because holding text beyond this session is what a document normally does, while a single+field holding far more than was typed is the exception. A non-text role yields nothing at all, so a keypress in a file manager is not a+step.++Building that buffer is the only place a keystroke becomes a character. `resolveKey` runs+`ToUnicodeEx` against the foreground layout with the modifier state the hook reported and the real+caps-lock state, and appends what comes back; `Backspace` removes one. Dead keys fall out of this+for free: `ToUnicodeEx` returns nothing for the accent itself and the composed character for the key+after it, because it keeps that state per thread and every keystroke goes through the same one. The+cost is that the state is real and can be left armed, so `clearDeadKey` flushes it whenever a+session ends.++Values are stripped of `\uFFF9`–`\uFFFD`, `\uFEFF` and `\u200B` before use. Accessibility+implementations use those to mark annotations and inline objects, and they arrive as invisible+garbage in the middle of otherwise ordinary text.++`DesktopRecorder` takes its region, its overlay hiding and its sink positionally, and everything+else — the display grab, the settings, the overlay hit test, the element lookup and the focused+field — through one optional hooks object, so `check:pipeline` replaces exactly the ones it needs+and names them at the call site. The grab defaults to `captureDisplay`, and `check:pipeline` feeds+it a generated frame instead. The crop arithmetic, the sink, the step write and all+four document exporters then run without a working screen-capture path, which matters because a real+grab depends on the machine it runs on. Whether a real grab works is `check:capture`'s question, not+this one's.++`pnpm --filter @mimik/desktop check:pipeline` captures two clicks into a throwaway guide, then+asserts the steps landed on the guide, the screenshot is cropped to the region, the description came+from the shared heuristic, and HTML, Markdown, PDF and DOCX all export non-empty. A stubbed element+lookup covers the two things the addon feeds: the metadata reaching the written step, and+`targetRect` preferring the control's rectangle while rejecting an oversized or overflowing one. It then loads the+real `index.html` and asserts that window answers a capture request and navigates to the finished+guide, because the checks otherwise run against their own renderer and never exercise the entry+point the user actually gets.++The renderer answers those requests from `capture-host.ts`, imported for its side effect by+`main.tsx`. Nothing else registers the sink, so dropping that import silently costs every capture a+fifteen second timeout and no visible error.++Stopping a recording names the guide before the window is told, so the view opens on a titled guide+rather than the placeholder the extension fills in with AI. Desktop has no AI title, so the name+comes from the recorded application, or a generic one where no application was identified. Without+it the guide screen waits forever on a title that is never written.++**Every AI request goes through the main process.** A renderer is an ordinary web origin, so a+`fetch` to `api.anthropic.com` is blocked by CORS and throws — which reads as a rejected key when it+is really a request that never left. The extension never hits this because it validates in the+background service worker, where `host_permissions` exempts it, and that is the thing the desktop had+no equivalent of. `CoreEnv` therefore carries an optional `fetch` and core calls it through+`coreFetch`, so `validateApiKey`, `getAIDescription` and `generateGuideMeta` all route through+whatever the surface supplies. The desktop supplies a wrapper over `mimik:ai:fetch`, which runs+Electron's `net.fetch` in main. It refuses any url that is not `http:` or `https:`, because the- renderer names the url and main is the one holding the network.++renderer names the url and main is the one holding the network. A text, JSON or event-stream++response comes back as text and anything else as base64, which the renderer decodes into bytes:++voice-over audio went through the same path as JSON and arrived as mangled text. The voice-over++client calls `coreFetch` for that reason rather than the global `fetch`, which a renderer origin++cannot use against a provider.++Ask AI and Generate description reach the model through `messages.send`, which the extension answers+from its background worker. The desktop has no worker, and its adapter's `send` used to throw for+everything, so both failed with "generation failed" before any request was made. It now calls the+same two functions the worker calls — `rewriteSelection` and `generateDescriptionOnDemand`, which+moved into core's `guide-description.ts` with `resolveGuideMetaInputs`, the inputs both surfaces name+a guide from — and still refuses the messages that only mean something in a browser.++A failed key check says which failure it was. `reason: 'network'` is worded "could not reach the+provider", not "rejected" — the two are indistinguishable to a user and only one of them is their+key's fault.++Descriptions and the guide's name are written by the user's own provider key when there is one, and+by rule when there is not. `getAIDescription` takes a serialised context string rather than a+`DOMContext`, because the desktop has no DOM to hand it: `serializeScreenContext` writes the same+shape of thing from the application, the window title, the control's role and name, and the value,+which is what UIAutomation knows. No screenshot is ever sent.++The desktop has its own step prompt, `SCREEN_STEP_DESCRIPTION_PROMPT`, which `getAIDescription` takes+in place of the extension's. The shared one said "a browser workflow… on a web page", and handed a+UIAutomation role it wrote "Click "Downloads (pinned)" in the treeview". The desktop prompt speaks of+a desktop application and tells the model to name a control by its label and never by a technical+type. The context reads the role as words, `tree item` rather than `treeitem`, and carries the step+before this one, read when the queue reaches the step so it is that step's AI text when there is one.++A guide is named from where each step happened as well as what it did: `guideMetaSteps` gives each+step a `place`, its URL in the extension and its application and window on the desktop, which had+sent an empty address and left the model to invent one — a File Explorer guide came back as a+Microsoft Edge one. The naming prompt says either kind of place may appear and names only what the+steps name.++The key, model and endpoint are read once, by `resolveAiCredentials` in core's `keys.ts`, which the+extension's descriptions, guide naming and rewrite and the desktop's all call; there had been four+copies of the same read and default-model fallback. The steps a guide is named from are+`guideMetaSteps` in `meta.ts` — the actions only, the first ten and last five past fifteen — for the+same reason.++A step is written with its heuristic description immediately and, when a provider key is saved,+with `aiPending` set; then it is rewritten when the model answers. Saving a key is what enabling AI+means here, so without one the flag is never set and nothing on the card claims a description is+coming. With one, the flag is cleared **whichever way the request goes** — a miss and a failure both+clear it — because a pending flag that only clears on success is the same trap as a title+placeholder that only resolves with AI.++The rewrite goes through the extension's own queue, `description-queue.ts` in core: one request at a+time, 45 s each at most. The desktop fired every description on its own, with no limit and nothing+waiting for them at Finish, so a hung request left a step on "Writing…" for good and a guide could be+named before its last descriptions landed. Finish now runs the extension's Stop sequence through+`settleDescriptions` — wait up to 20 s for the queue, then clear any flag still set — before the name+is written, and main waits 45 s for that rather than 15.++A failure also says why, in the extension's words. `describeStep` classifies the error with core's+`describeAiFailure` and sends the reason and provider with `mimik:capture:described`; main keeps it+on the overlay view, and the card shows `aiFailureNotice` — the headline and action the side panel's+`AiStatus` shows, such as "OpenAI rejected your API key. Check your key in Settings." — above its+buttons, where the side panel shows it above Finish, until the next recording starts. It used to be+`catch { return null }`, so a rejected key and no network both looked exactly like having no key.+`aiFailureKey` and `aiActionKey` moved from the side panel into `capture/ai/errors.ts` for it.++Stopping a recording names the guide twice. The application name lands first so the view never opens+on a placeholder, and `generateGuideMeta` replaces it if a key is configured. Ordering it that way+means the guide is always named, and the AI title is an improvement rather than a prerequisite.++Step descriptions are only as good as the element lookup. `buildFallbackDescription` picks the verb+from the role — a text field is entered, a combo box, radio button or menu item is selected, anything+else is clicked — and quotes the name it finds. A desktop typing step quotes what was typed instead,+`Type "…"`, collapsed to one line and cut at 200 characters, because the text is the instruction+and the field is usually obvious from the screenshot; the extension still names the field. The name+is the accessible name first; a text field+then falls back to its placeholder and help text but never its value, which is what was typed into+it, and the machine identifier is used only when it does not read as one. An element with no name of its own borrows one: a group or pane from the first named control+inside it, anything else from its nearest named ancestor, stopping at the window, because naming+the window as the click target would be wrong. Chrome's internal window class names and bare numbers+on panes are discarded, since the accessibility tree reports both as names, and invisible format+characters are stripped from every name — web pages wrap words in direction isolates and+zero-width marks that the PDF font draws as boxes. When nothing is left the+step reads "Click here" rather than "Click treeitem" — the control type is not a name. A+`screen`-sourced recording, with no lookup at all, is every step reading "Click here".++The AI rewrite runs only when a provider key is saved, which is what enabling AI means here, and+the step it rewrites is marked `ai` so the badge says so.++## Feature Hooks++A cluster of `useState` that moves as one thing is a hook, not a pile of state in a component.+`ExportPreviewModal` held fourteen, of which eleven were two jobs wearing one coat: `useGuideExport`+owns the document preview and every download, `useVideoPreview` owns the encode, its progress, its+container and the deferral past twenty-five steps. The modal keeps three — the options, the tab, and+nothing else.++The shape repeats wherever an async job meets a component: `data`, `loading`, `error`, `progress`+spread across four `useState` and one long effect. `useGuideDescription`, `useSnapshots`,+`useSettingsAutosave`, `useEditHistory` and `useTextStyle` are the same extraction, and+`useAiSettings` and `useKeyCheck` were already it before the pattern had a name.++What stays a `useState` is state one component owns and nothing else reads: a dialog's open flag, an+input draft, a hover. Grouping those into a hook adds indirection and removes nothing. The test is+whether the values change together and are read together, not how many there are.++`useSettingsAutosave` is the odd one: it holds no settings at all. The fields stay in the view+because each is bound to its own control; what the hook owns is the machinery around them — the+snapshot, the diff, the debounce, the flush on unmount and the saved badge — which is the part that+was subtle and the part nobody should have to read twice.++`AnnotationEditor` went from twenty-eight states to sixteen across three hooks — `useEditHistory`,+`useTextStyle` and `usePointerGesture`, the last holding everything the pointer is doing right now:+the shape being drawn, the crop being dragged, the hover and grab cursors and the floating toolbar's+anchor. What is left is genuinely interdependent canvas state.++How it was done matters more than the count. A regex pass over the style names rewrote object keys+and type members as well as reads and broke the file's syntax; it was reverted and redone as a list+of exact string replacements. Every later cluster was done the same way. A file this size does not+take a search and replace.++## Fullview Store++One Zustand store, four slices — `library`, `search`, `guide`, `editor` — each living in its+feature's `store/` folder and merged in `stores/fullview.ts`. `useFullview` sits beside it in+`stores/use-fullview.ts` and wraps `useShallow`, which is what makes the+object-returning selectors all over the fullview safe rather than a re-render trap.++Slices rather than separate stores because one cross-domain write genuinely exists: opening a+different guide has to close the editor and its history panel. As a flat store that lived inside+`setGuideExportData` as three stray field resets and was invisible. As a slice it is+`{ guideExportData, ...CLOSED_EDITOR }`, with `CLOSED_EDITOR` owned and named by the editor slice —+the coupling still happens, it just says so. Four separate stores would have made it a subscription+between stores, which is worse.++Two things in here are deliberate and look wrong at a glance. `flushFocusedField` reaches for+`document.activeElement` from inside the store, because leaving edit mode has to commit whatever is+in the focused input before the component unmounts and the keystrokes are lost. `scrollToStep` sets+an id and clears it 100 ms later, because it is a signal rather than state — the alternative is an+event emitter beside the store for one interaction.++## Desktop Home Screen++**A guide looks the same everywhere; getting to one does not have to.** Viewing, editing, annotating+and exporting live in `packages/ui` and both surfaces mount the same components, so a step card reads+identically in a browser panel and in a desktop window. Everything before the guide is free to differ,+because the products differ: the extension records a tab, has no capture mode to choose and lives in+400 px of browser chrome, while the desktop records the operating system in a window five times as+wide and has to pick between three framings first. Forcing those two shells together makes both worse.+Divergence inside the guide is a bug; divergence in how you reach it is not.++The frame around the dashboard is the exception that proves it. `AppFrame` is the extension's own+dashboard frame, in `packages/ui` and mounted by both surfaces, because it is navigation rather than+capture and there was nothing about it worth diverging on. It is a sidebar and a top bar. The sidebar+holds the mascot, Start Capture, All Guides, Starred and Trash with their counts, and Settings at the+foot. The top bar holds search on the left and the page's own actions on the right — sort and the+list or grid switch on the library, and Zoom, Edit, Version history and Export on a guide. Neither+repeats a title: the highlighted sidebar item says where you are, and a guide's title is the heading+over its steps. A breadcrumb and a heading saying "All Guides" were both tried and both only said the+same thing twice.++The sidebar collapses to icons on its own when Version history is open or the window is under+1100 px, because a 232 px sidebar, the guide column and the history panel do not fit side by side in+a 1280 px window, and the extension's tab loses 400 px whenever the browser's side panel is open.+Collapsing it by hand is remembered in `localStorage`; expanding it by hand holds for the session+even where it would otherwise collapse. `useSidebarCollapse` owns that rule.++`AppFrame` takes only a `Route` and reads the rest from `useFullview`, which `GuideContent` already+fills, so the export data arrives with no desktop wiring at all. What differs is passed in:+`onStartCapture` opens `CaptureSheet` on the desktop and the side panel in the extension, and+`onSettings` opens the settings dialog on the desktop and the options page in the extension, which+is what `settingsExternal` marks with an external-link icon. Start Capture is in the sidebar on every+page, where it used to sit only above the All Guides list. The first shared header brought+`SearchModal`, `ExportPreviewModal`, `VideoStepPlayer` and two search components with it — each+needed exactly two import rewrites, `#imports` to `@mimik/core/env` and `@/core/*` to+`@mimik/core/*`, because nothing in them was ever extension-specific beyond how WXT resolves a+module.+++The guide page's top bar also holds Duplicate, and Transcript when the guide has a narration++transcript, which only an extension recording produces. The library's controls hold Import, beside++sort and view, and dropping a `.mimik` file anywhere on the library opens the same dialog, because++the file lives in the store where both reach it. Duplicate is also an item in the card menu, which++the list and grid share.+++`SearchModal` listens for Ctrl or ⌘ with K itself. The listener used to live in the extension's+`FullViewApp`, so the desktop mounted the same dialog and the shortcut did nothing there. The search+box shows ⌘K on a Mac and Ctrl K everywhere else.++A page of the library never scrolls. `usePageFit` fits as many columns as the width allows, none+narrower than 300 px and at most six, and as many rows of cards or list rows as fit between the top+of the library and the pager pinned to the bottom of the window, and that is the page size. A fixed+three columns in a capped width left most of a wide window empty, and a fixed nine per page pushed+the taller cards and rows past the bottom of it. The list view is capped at `max-w-6xl`, since a row+that spans a wide window is mostly empty line. Each card is the first step's screenshot at 16:9,+cropped the way the guide shows it — zoomed toward the click on the desktop, around the element in+the extension — then where the guide happened, its title on up to two lines, and its step count and+date, with a star on the picture when it is starred. Where it happened is the most common site among+its steps, with its favicon, or the application the first step names, with a letter tile; the tile+never asks for a favicon, because that request would send the application's name to a favicon+service. `loadCardData` reads both for the page being shown. The list view is the same card laid+flat: a 16:9 thumbnail, the title, one line of description, and where it happened with the step+count and date, with the star and the card's menu always visible. A guide with nothing to show has+the mascot's eyes on navy in place of a picture, and every card keeps the line for where it+happened even when it is empty, so an untitled guide lines up with the rest.++Going back to the library from a guide shows it as it was left. The page, the guide count and the+page fit live in the store or beside the hook rather than in the component, which unmounts while a guide is open,+so the grid paints at once on the same page and refreshes behind it. Thumbnails pass `cache` to+`ScreenshotView`, which keeps the drawn image under the same key it already used to skip redraws —+id, blob size, annotations and target — in a map of the last 48, so a card does not redraw its+screenshot through a canvas every time the library opens. The guide's own screenshots do not cache,+since editing changes them constantly. Dates follow the app language through `formatDate`; Chinese was missing from its map+and read in English.++Pressing Start Capture opens `CaptureSheet` rather than arming immediately. Esc closes it, as it does+every dialog; the sheet is a panel of its own rather than the shared dialog, so it listens for the key+itself. The sheet is where the+capture mode is chosen, because the mode decides what every screenshot in the guide will frame and+that is worth one deliberate choice before recording rather than a control discovered afterwards.+Picking a mode writes `captureMode` straight through to `capture-settings.json`, so the sheet reopens+on whatever was used last and the recording bar's own picker reads the same value.++The sheet holds the mode and nothing else. `keepClicksBeyondArea` was tried there and taken out: read+beside a rectangle the user has just chosen, an option that falls back to the whole screen reads as+undoing that choice, when what it really decides is whether a click outside the rectangle is dropped+or kept. It stays in Settings, where there is room to say so. Nothing in the sheet is editable in two+places.++Starting in Area mode opens the region editor first and arming happens when the rectangle is+confirmed. The other two modes arm directly, because they have no rectangle to draw.++The "+" between two steps opens the same sheet, titled "Capture more steps" and saying which step the+new ones follow. The extension's dialog there picks a browser tab to record in, and on the desktop it+could only ever say that no tab was open, so `GuideContent` takes an `onCaptureMore` and the desktop+answers it with the sheet — the choice a desktop recording needs is the mode. The recording itself is+the extension's: the steps land in a staging guide, which the library hides, and Finish settles its+descriptions, snapshots the guide and merges them in with `mergeGuideInto` at the "+", leaving the+guide's name alone. The card numbers them from where they will land. `check:pipeline` asserts the+merge puts the steps at the "+", removes the staging guide and keeps the title.++Routing is `useRoute` and `navigate` from `@mimik/ui`, not a hand-rolled `hashchange` listener. The desktop had one+matching `#guide/<id>`, which is the same scheme the shared router already parses, so adopting it+cost nothing and bought Starred and Trash the routes the sidebar needs.++## Capture Settings++The settings that only a desktop capture needs live in `capture-settings.json` beside the region,+read by main rather than by core, because none of them mean anything to the extension.++| Setting | Default | Effect |+|---|---|---|+| `captureMode` | `window` | What each screenshot frames: the focused window, the whole screen, or a drawn area |+| `screenshotDelayMs` | 0, capped at 2000 | Extra wait between the click and the grab |+| `keepClicksBeyondArea` | off | Whether clicks beyond the capture area are recorded at all, in `region` mode only |+| `recordKeys` | off | Whether a shortcut or a named key becomes a step; off by default, since a guide is clicks and typing |+| `recordTyping` | on | Whether typing becomes a step |+| `typingDebounceMs` | 1000, clamped to 200–5000 | Quiet time that closes a typing session |+| `zoomLevel` | automatic | How far a step zooms toward the click: `null` derives it, or 1–5 in 0.25 steps |+| `shortcuts` | three accelerators | Global keys for start/stop, pause/resume and capture now |++`normaliseSettings` runs on every read and write, so an out-of-range delay clamps and an unknown+mode falls back rather than reaching the recorder, and a key it no longer knows is dropped. It also reads three+settings under the names an earlier build saved them as, so a file written before the rename keeps+its choices; the next save writes only the current names.++No pointer is drawn into a step. Recordings once stored an arrow at the click point in+`edits.cursor`, behind a "Show the cursor" switch, and every exporter drew it — but the guide view+rebuilt the edits it renders from the annotations and the target alone, so the app itself never+showed it and the switch read as broken. The dashed target already says what was clicked, so the+pointer went rather than being wired through: the setting, the mark and the drawing are gone, and an+`edits.cursor` left on an older step is ignored everywhere, exports included. That is also what the+extension has always done, where the target's colour is the only click mark to set.++The brand colour is not in that file. It is `targetColor` in the renderer's settings storage, set+from the Export Branding section with the extension's own card, because the renderer is where both readers+are: the+capture sink stamps it on each step's dashed target, and `branding.ts` takes it as the accent of+every export. Setting it on the desktop therefore recolours exports too, which is what it does in+the extension. The two surfaces keep separate stores, so neither one's choice reaches the other.++The mouse button decides the action: the right button records as `auxclick` and everything else as+`click`, so a right click reads as "Right-click …" rather than being indistinguishable from a left+one. Middle clicks fall in with left, which is no worse than before and avoids claiming a wheel+press was a context menu.++A double click is one action, so it is one step. `isRepeatClick` drops a press that lands within+500 ms of the one before it, and the clock is reset on every press rather than on every capture, so a+burst of clicks stays suppressed until there is a real gap. The rule is time only, deliberately: it+takes its timestamps as arguments rather than reading the clock, so it is exercised without a mouse.++The cost is that two deliberate presses on different controls less than 500 ms apart become one step.+Matching on position as well would separate them, and that was tried and dropped: a position check+needs a distance tolerance, and one that fits a 1× display is wrong on a 2× one, while time alone+needs no tuning.++A click outside the capture area, when that setting keeps it, is still framed by the area: the area is+what the guide is about, and a step that suddenly shows the whole screen reads as a mistake. The grab+comes from the display the area is on rather than the one the click landed on, so the crop is right+across monitors. `shouldCapture` is exported for that+decision rather than being inline in the hook handler, so the rule is testable on its own. It only+filters in `region` mode; the other two modes frame every click by construction.++`check:pipeline` covers all five: clamping and persistence round-trip through the real file, an+unknown mode falls back, the opt-in rule holds in four positions, a double click collapses to one step, `frameFor` returns the right+rectangle for all three modes including both window fallbacks, and a 400 ms delay measurably slows the+grab. It restores whatever+settings were on disk when it finishes.++## Desktop Settings++Five sections behind one left nav: General, Capturing, AI descriptions, Export Branding, Shortcuts, and+the dialog opens on General, the first, as desktop settings conventionally do. General holds three cards named+for what they hold — Language, Startup and Updates — rather than one card named after the section,+which put "General" in the list and again as the pane's only heading. Startup and Updates are the+tray menu's own "Start at login" and "Check for updates", in the tray's words and through the same+`setOpenAtLogin` and `checkForUpdates`, so the tray and the settings cannot disagree; the update check+does nothing in an unpackaged build, where the updater never runs. The split is the+same one that decides where a file lives. Capturing and Shortcuts describe things the extension has+no concept of, so they are written in `apps/desktop` against `capture-settings.json`. AI descriptions+and Branding are identical on both surfaces, so `AiSettings` and `BrandingSettings` live in+`packages/ui` and both apps mount them. `AiSettings` takes a `validate` function — the desktop passes+core's `validateApiKey` directly, and the extension goes through its background messaging, which is+the only part that differs.++`BrandingSettings` is the extension's Brand colour card and Branding card — the colour of the click+highlight and export accent, the logo, the footer line and the attribution — lifted out of+`SettingsView` as they were, with `useBrandingSettings` holding the four values and saving each change+as it happens, the way `useAiSettings` does. The desktop had neither at first: the logo, footer and+attribution were written off as having no desktop meaning, though every desktop export reads them+through `loadBranding`, and the colour was rebuilt in Capturing under a name of its own, "Marker+colour", so one setting read as two features in two places. A setting both surfaces have is the+extension's card, in the extension's order, under the extension's words.++The default logo those exports fall back to is `public/mimik-mark.png`, the extension's own file. The+desktop renderer takes `public/` as its `publicDir`, so the file sits beside the page in dev and in the+build, and its `assetUrl` resolves a path relative to the page rather than to the disk root — a+leading slash on a `file://` page is `file:///mimik-mark.png`. Neither held before, and the fetch+failing quietly returned no logo, so no desktop export ever had one. `check:pipeline` fetches it.++Every card is `SettingsCard` from `packages/ui`: the border, radius, padding, white face and 28px icon+header, with an optional hint under the title and an optional control beside it. The extension's AI,+Brand colour, Export Branding, Voice narration and Smart blur cards and the desktop's `Card` all use+it; they had been six hand-copied frames, one of them the desktop's. The desktop `Card` only adds the+divided rows inside. Rows inside a+desktop card are `Row`: label and a one-line hint on the left, the control on the right, divided+from the next row, or the control underneath with `stack` when it is too wide to sit beside the+label. The AI card keeps the stacked 11px labels it needs in 400px of side panel — the two are never+on screen at once, and matching them would mean branching that shared component on `client()`.+Capturing is two cards: Screenshots, and Typing and keys.++Each kind of value has one control, and it shows the value rather than hiding it behind a click. A+choice among a few is `Segmented`, a row of buttons with the chosen one filled; that is the capture+mode and the zoom, which offers Automatic, 1×, 1.5×, 2×, 3×, 4× and 5× and adds the stored level as one more+button when an older build saved one in between. An on/off is `Switch`, the same switch the AI card's+own-server toggle is, moved into `packages/ui` so the two cannot drift. A duration is `Slider`, a+native range input tinted with `accent-accent` beside a chip reading the value in ms or seconds,+because a number field hid what the default was and drew spinner arrows on Windows. A setting that cannot apply is disabled rather than hidden, so the rows+do not jump: outside clicks without Area mode and the typing pause without typing.+Every change is applied to the page before main answers, or a slider dragged across its range would+lag a round trip behind the pointer.++Settings opens as a dialog over the library, not as a page. It is the shared `Dialog` laid out the+way the export preview lays out its own: a title bar with the close button, the section list down+the left and the section scrolling beside it, 880 px wide and at most 650 px tall. As a page it+replaced the library, and on a wide window its content, which tops out around 620 px, sat in a field+of empty space. The dialog also covers the sidebar, which is why no navigation prop exists: one used+to close the old pane when All Guides, Starred or Trash navigated underneath it.+`SettingsPanel`, the body, mounts only while the dialog is open, so it reads the settings each time it+opens and shows a mode the capture sheet or the recording card changed in the meantime.++`AiSettings` is the extension's own AI card, lifted out of `SettingsView` rather than rewritten. A+parallel implementation was tried first and the wording immediately drifted — the extension said+"API key verified", the copy said "134 models available", and the spend warning was missing+altogether, because the extension shows the verdict, the model list and the warning as three+separate things and the copy collapsed them into one line. Two implementations of the same screen+diverge by default; one does not.++What moved with it: `KeyStatusNote`, `KeyWarningNote`, `ModelList` and `SecretInput`, one file each+under `ai/components`, and `useKeyCheck` in `ai/hooks`. The hook takes its validator as an argument, which is the only part+that genuinely differs — the extension goes through background messaging because a service worker is+what has `host_permissions`, and the desktop calls `validateApiKey` directly on top of the main+process fetch.++The rest of `SettingsView` stayed put. Voice narration, smart blur and the microphone picker have no+desktop meaning, and it reaches into `@/lib/browser-api/`. It mounts `BrandingSettings` where its own+two cards were and passes the autosave's `queue` as `onChange`, which is only there to raise the+Saved badge — the card has already written the value. Splitting it did mean the+autosave had to change shape: the AI fields left the parent's snapshot, so `AiSettings` reports its+own changes through `onChange` and both halves queue into the same debounced flush. `SettingsView`+still keeps the provider and key in state for one reason — `resolveVoiceApiKey` falls back to the AI+key when no voice key is set — and it updates them from the patches the card sends up.++The shortcut recorder reads a keystroke and writes an Electron accelerator. It refuses a bare key,+because a global accelerator with no modifier takes that key from every application on the machine,+and it ignores a modifier pressed alone, because `Shift` is not a shortcut. `accelerator()` is a+pure function over the event so it is tested without a keyboard.++## Capture Shortcuts++Three global accelerators, stored in `capture-settings.json` beside everything else: start/stop,+pause/resume, and capture now. They default to `Alt+Shift+R`, `Alt+Shift+P` and `Alt+Shift+C`,+because a global accelerator is taken from **every** application on the machine for as long as it is+registered: `Ctrl+Shift+R` would break reload everywhere, and `Ctrl+Alt+<letter>` is AltGr on most+non-US layouts, so it would eat characters people actually type. `Alt+Shift` held with another key+is rare in applications and does not trigger the Windows layout switch, which fires only on+`Alt+Shift` pressed and released alone. Function keys were the first choice and are wrong: laptops+increasingly do not have a usable row.++That is also why only start/stop is bound all the time. Pause/resume and capture-now can do nothing+outside a recording, so `shortcutMap` returns them as null until one is running and `applyShortcuts`+rebinds on every state change. An empty accelerator string clears the binding rather than restoring+the default, so a shortcut can be turned off; a missing one falls back.++Registration is the part that cannot be trusted. `globalShortcut.register` returns false when+another application already owns the key and throws on an accelerator Electron cannot parse, so+`bindShortcuts` catches both and hands back the list it could not take rather than failing the+launch over a key clash.++**Rebinding must never happen inside a shortcut's own handler.** Unregistering the accelerator that+is currently firing hangs the main process on Windows — the app goes to "not responding" with no+error anywhere. Two things keep that from happening: `bindShortcuts` returns immediately when the+wanted set matches what is already bound, which covers pause and resume since both count as+recording, and `applyShortcuts` defers the work with `setImmediate` so it is never on the handler's+stack whatever the set turns out to be. Pausing from the card worked throughout, because that path+reaches the rebind through IPC rather than from inside a global shortcut.++Start/stop goes straight from hidden to recording rather than arming first, because a shortcut whose+job is to start recording should not need a second press. The stored region is used as it stands,+which is what makes that possible in `region` mode.++Starting, from the card or the shortcut, plays the extension's start animation first, and the+recording begins when it ends. The overlay opens a click-through, content-protected window over what+is about to be framed — the region, the focused window or the display, the same `frameFor` decision a+capture makes — and that window calls core's `showStartNotification`, so both surfaces run one+animation from one module. The host hears `start` only after the animation's `animationend`, which+is the ordering the extension uses too: nothing clicked during it is recorded, so the animation never+lands in a step, including on Linux where content protection does nothing. Closing the card during it+cancels the start. A six-second limit ends a stalled intro rather than leaving the recording unstarted.++Capture-now writes an ordinary click step at the cursor. There is no separate action for it: the+point of pressing it is that the cursor is already on the thing worth capturing.++The keystroke that drives a shortcut must not also be recorded as one. Without that check, pausing a+recording writes "Press Alt+Shift+P on Mimik" as a step, which is both wrong and confusing, and+resuming writes another. `isBoundShortcut` compares a keystroke against each configured accelerator+before `captureKey` writes anything, and it compares by parts rather than by string so+`Shift+Alt+P` and `Alt+Shift+P` are the same shortcut. `CommandOrControl` resolves to Control+everywhere but macOS.+## Export Formats| Format | Generator | Details |@@@ -1393,17 -275,10 +1493,18 @@@| PDF | `core/export/pdf-export.ts` | jsPDF, A4 portrait, auto page breaks || Markdown | `core/export/markdown-export.ts` | Standard MD with base64 image data URLs || DOCX | `core/export/docx-export.ts` | Lazy-imported, Word-compatible |- | Video | `core/export/video-export.ts` | WebCodecs via mediabunny (lazy), mp4/H.264 with WebM/VP9 fallback |+ | Mimik bundle | `core/transfer/bundle.ts` | `.mimik` zip: manifest + flattened screenshots + README.md. Re-importable; the others are one-way |+ | Video | `core/export/video-export.ts` | WebCodecs via mediabunny (lazy), mp4/H.264 with WebM/VP9 fallback, optional voice-over || GIF | `core/export/gif-export.ts` | gifenc (lazy), same frame timeline as the video; user picks Small/Medium/Large from `GIF_SPECS` |+The preview player is told the container rather than assuming one. `pickContainer` answers `mp4`+only when the machine can encode H.264 and falls back to WebM/VP9 otherwise, so a hardcoded+`type: 'video/mp4'` on the player describes the file wrongly on any machine without an H.264+encoder — a VM without GPU acceleration, typically. The export itself succeeds and the chapter list+fills in, so the only symptom is a black frame reading 0:00 / 0:00. `VideoStepPlayer` now takes the+mime alongside the url and `ExportPreviewModal` reads it off the blob. `check:pipeline` asserts the+blob's type matches the extension, which is the pairing that was wrong.+Video frames reuse `renderScreenshot`, so the auto-crop, click-target outline, annotations andredactions are already baked in. Each step holds 1.5s wide, eases into a crop around the targetover 0.73s, holds 3s close, and consecutive steps cross-dissolve over 0.33s at 30fps. Capability@@@ -1479,7 -419,21 +1656,21 @@@ Font: Poppins (loaded via `@fontsource/- **DOM context** sent as text to AI instead of screenshots — 15-30x cheaper per step- **Hover ring** (`lib/hover-ring.ts`) is a closed-Shadow-DOM host marked `data-mimik-ignore`, shared by recording and the blur picker (purple). Recording reads the user's `targetColor` so the live ring matches the dashed target baked into screenshots. Never drawn on `iframe`/`embed`/`object` — a capture inside a subframe can't hide the top frame's ring- **Content script injection** pings first, falls back to `chrome.scripting.executeScript()` for tabs without the script+ - **`PAUSED` is a real machine state**, not a flag. It carries a `pauseReason` (`'blur' | 'manual'`) and deliberately does not handle `USER_ACTION`, so nothing can advance `stepCount` while the UI says capture is paused. `CaptureSession.syncWithBackground` only starts on `RECORDING`, so a frame that loads mid-pause stays idle instead of silently resuming. Background step writes are gated on `RECORDING` too, for a frame that missed the stop broadcast+ - **Pausing also stops the microphone.** `pauseCapture` flushes and stops narration when it was live, and `resumeCapture` restarts it — otherwise speech during the pause is transcribed and attributed to the step captured after the resume. The mic toggle locks while paused, since narration cannot start outside `RECORDING`+ - **The restart has to outlive the flush.** Stopping narration leaves the phase on `'transcribing'` for a whole API round-trip, and `canStartNarrationNow` refuses that phase, so a single attempt on resume always failed and the mic never came back while the panel went on showing narration as enabled. `restartNarrationOnceTranscriptionSettles` retries while `isNarrationSettling()` holds, up to `NARRATION_RESTART_ATTEMPTS` waits on `whenNarrationSettled()`, then calls `reportNarrationLost` so the panel stops claiming the mic is on. It stops *immediately* when the phase is anything else: a start that failed on its own 8s timeout leaves the phase `'idle'`, and retrying there would call `startVoiceCapture` a second time, get `already-recording`, and `closeVoiceHost()` a host that had just started. It is deliberately *not* awaited by `resumeCapture` — the panel is waiting on that reply — so its rejection is caught rather than left unhandled+ - **`narrationWasLive` lives in the machine context**, not a module variable, because the worker can be evicted while the recording sits paused. Per the note above, a snapshot persisted before the key existed restores it as `undefined`, so it is read as `=== true`. Its *source* cannot be the module-level `phase` either, which an eviction resets to `'idle'`: `pauseCapture` calls `isNarrationLive()`, which asks the host when the phase says nothing, and counts `'transcribing'` as live so a second pause during the first one's flush does not lose the flag+ - **`claimTranscription`/`releaseTranscription` are a matched pair** and every path that reports `'transcribing'` uses them, `recoverNarration` included — a claim without `markNarrationPending` made `whenNarrationSettled()` resolve instantly and burned both restart attempts in one tick. They count outstanding transcriptions rather than holding one slot, because a pause followed by a stop claims twice; `releaseTranscription` returns whether it owned the claim, so a failed stop cannot report an error over a terminal `idle`+ - **Pausing waits for the frames to drain.** `broadcastStopCaptureAndFlush` is answered only once each content script's queue is idle, because `CaptureController.stop()` enqueues the input session's finalize. `handleFinalizeInputStep` is therefore gated on "not IDLE" rather than `RECORDING`: it only ever completes a step the user finished before pausing, and `enterBlurMode` awaits the flush before opening the overlay so that screenshot cannot catch it+ - **Navigation listeners treat `PAUSED` as live** (`navigation.ts:isLive`). `URL_CHANGED` has to keep flowing or the first step after a resume is stamped with the pre-pause URL, which Guide Me then replays to; injection has to keep running or a tab opened mid-pause is deaf to the resume broadcast+ - **Blur mode pauses via that state**, and a top frame booting into `PAUSED`/`'blur'` re-opens the overlay, so a navigation mid-blur still has a Done button. `exitBlurMode` and the panel's Resume both broadcast `DISMISS_BLUR` before resuming, which closes the overlay but keeps the masks the user just picked; only the end of a recording sends `CLEAR_BLUR` to remove them+ - **Smart blur cannot reach** iframes, shadow DOM, canvas/image text, `::before`/`::after`, `<select>`/`<option>`, or attribute-only values like `title`/`alt`; it runs in the top frame only, and a matching input blurs as a whole field. SVG `<text>` *is* blurred. These limits are documented in all five READMEs and *partly* pinned by `core/blur/__tests__/scanner.test.ts` — shadow DOM, `select`/`option`, attribute-only values and whole-field input blur have assertions; canvas/image text, `::before`/`::after` and top-frame-only do not (the last lives in `content.ts`, not the scanner). Move the READMEs with any scanner change+ - **Paused-ness is read from the state value, never from `pauseReason`.** A snapshot persisted before `PAUSED` existed has no `pauseReason` key, so it restores as `undefined` — and `undefined !== null` read as paused, which left the panel offering Resume while the machine was still `RECORDING`. `getStateUpdate` normalises the reason to `null`; the reason only picks the wording. The same applies to any context key added later: a restored snapshot will not have it+ - **`BlurManager.start()` re-checks `active` after awaiting the presets.** A stop landing inside that await tore down a panel that did not exist yet, and the pending `start()` then mounted it with `active` already `false`, so nothing could ever close it. Any new `await` before the panel mounts needs the same guard- **xstate snapshot** persisted to sessionStorage so the state machine survives service worker restarts- **Recording notification** uses `animationend` event (not hardcoded delays) for timing-- **Font loading** uses `@fontsource/poppins` (CSP-safe, no CDN dependency)+- **Font loading** uses `@fontsource/poppins` (CSP-safe, no CDN dependency) everywhere, the HTML export included: `export/poppins.ts` inlines the same package's latin and latin-ext woff2 files for 400, 600 and 700 through Vite's `?inline` into `@font-face` rules, about 56 KB. The export used to link Google Fonts, which failed in the desktop's Document preview under its `default-src 'self'` policy and sent every reader's address to Google when the file was opened; the desktop policy now allows `font-src 'self' data:` for the embedded faces. The PDF is still drawn in Helvetica, since jsPDF takes TTF and the package ships only web formats- **Cross-context sync** via BroadcastChannel — star/delete events update other views without full reload+ - **Bundle export flattens before it ships** — `redact` annotations are drawn at render time, so `screenshot.blob` still holds the unblurred capture. `flattenScreenshot` burns redactions into the pixels and drops the annotation, and bakes an *explicit* crop (rebasing annotations and resolving `bounds` into an explicit target). The automatic zoom-to-target crop stays as data. Anything that ships a screenshot outside the browser must go through the renderer+ - **Guide titles are single-line**, normalised by `sanitizeGuideTitle` on every write path: `updateGuideTitle`, `importGuide`, `revertToSnapshot` and the AI meta path. Each renderer downstream already assumed it. The HTML and PDF covers clamp to `MAX_TITLE_LINES`, their running headers to one line, the video cover card wraps to two, the sidepanel truncates, and Markdown writes `# <title>`, where a newline ends the heading and spills the rest into the body. A fifth write path needs the same call. `MAX_TITLE_LENGTH` bounds the AI-generated title only (`core/capture/ai/meta.ts`); a typed title is deliberately uncapped, since every renderer above already clamps and a silent stop at 70 characters gave the user no reason for it+ - **Imports re-mint every id** — `importGuide` mints new guide/step/screenshot ids in one Dexie transaction. Reusing the ids in the file would let a shared guide overwrite one the recipient recorded. It also clears `aiPending`, which no background job will ever resolve for an imported stepdiff --cc apps/desktop/electron.vite.config.tsindex 9dc0910,0000000..5bbe18cmode 100644,000000..100644--- a/apps/desktop/electron.vite.config.ts+++ b/apps/desktop/electron.vite.config.ts@@@ -1,79 -1,0 +1,80 @@@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { defineConfig, externalizeDepsPlugin } from 'electron-vite';+import type { PluginOption } from 'vite';+import { load } from 'js-yaml';+import react from '@vitejs/plugin-react';+import tailwindcss from '@tailwindcss/vite';++const core = resolve(__dirname, '../../packages/core/src');+const locales = resolve(__dirname, '../../src/locales');++function yaml(): PluginOption {+ return {+ name: 'mimik-yaml',+ transform(_code: string, id: string) {+ if (!id.endsWith('.yml')) return null;- return { code: `export default ${JSON.stringify(load(readFileSync(id, 'utf8')))}`, map: null };++ const json = JSON.stringify(load(readFileSync(id, 'utf8'))).replace(/import/g, '\\u0069mport');++ return { code: `export default ${json}`, map: null };+ },+ };+}++export default defineConfig({+ main: {+ plugins: [externalizeDepsPlugin(), yaml()],+ resolve: { alias: { '@mimik/locales': locales } },+ build: {+ outDir: resolve(__dirname, 'out/main'),+ rollupOptions: {+ input: {+ index: resolve(__dirname, 'src/main/index.ts'),+ 'check-capture': resolve(__dirname, 'scripts/check-capture.ts'),+ 'check-storage': resolve(__dirname, 'scripts/check-storage.ts'),+ 'check-overlay': resolve(__dirname, 'scripts/check-overlay.ts'),+ 'check-pipeline': resolve(__dirname, 'scripts/check-pipeline.ts'),+ },+ output: { entryFileNames: '[name].js', chunkFileNames: '[name].js' },+ },+ },+ },+ preload: {+ plugins: [externalizeDepsPlugin()],+ build: {+ outDir: resolve(__dirname, 'out/preload'),+ rollupOptions: {+ input: {+ index: resolve(__dirname, 'src/preload/index.ts'),+ overlay: resolve(__dirname, 'src/preload/overlay.ts'),+ },+ output: { format: 'cjs', entryFileNames: '[name].cjs' },+ },+ },+ },+ renderer: {+ root: resolve(__dirname, 'src/renderer'),+ publicDir: resolve(__dirname, '../../public'),+ plugins: [yaml(), react(), tailwindcss()],+ resolve: {+ alias: {+ '@mimik/core': core,+ '@mimik/ui': resolve(__dirname, '../../packages/ui/src'),+ '@/core': core,+ '@mimik/locales': locales,+ },+ },+ build: {+ outDir: resolve(__dirname, 'out/renderer'),+ emptyOutDir: true,+ rollupOptions: {+ input: {+ index: resolve(__dirname, 'src/renderer/index.html'),+ 'check-storage': resolve(__dirname, 'src/renderer/check-storage.html'),+ overlay: resolve(__dirname, 'src/renderer/overlay.html'),+ splash: resolve(__dirname, 'src/renderer/splash.html'),+ 'check-pipeline': resolve(__dirname, 'src/renderer/check-pipeline.html'),+ },+ },+ },+ },+});diff --cc apps/desktop/src/main/ai-fetch.tsindex 899db48,0000000..b678445mode 100644,000000..100644--- a/apps/desktop/src/main/ai-fetch.ts+++ b/apps/desktop/src/main/ai-fetch.ts@@@ -1,46 -1,0 +1,49 @@@+import { ipcMain, net } from 'electron';++export interface AiRequest {+ url: string;+ method?: string;+ headers?: Record<string, string>;+ body?: string;+}++export interface AiResponse {+ status: number;+ statusText: string;+ headers: Record<string, string>;+ body: string;++ encoding: 'text' | 'base64';+}++const ALLOWED = new Set(['http:', 'https:']);++export function allowedEndpoint(url: string): boolean {+ try {+ return ALLOWED.has(new URL(url).protocol);+ } catch {+ return false;+ }+}++export function registerAiFetch(): void {+ ipcMain.handle('mimik:ai:fetch', async (_event, request: AiRequest): Promise<AiResponse> => {+ if (!allowedEndpoint(request.url)) throw new Error('unsupported url');+ const response = await net.fetch(request.url, {+ method: request.method ?? 'GET',+ headers: request.headers,+ body: request.body,+ });+ const headers: Record<string, string> = {};+ response.headers.forEach((value, key) => {+ headers[key] = value;+ });++ const textual = /^text\/|json|xml|event-stream/.test(response.headers.get('content-type') ?? '');+ return {+ status: response.status,+ statusText: response.statusText,+ headers,- body: await response.text(),++ body: textual ? await response.text() : Buffer.from(await response.arrayBuffer()).toString('base64'),++ encoding: textual ? 'text' : 'base64',+ };+ });+}diff --cc apps/desktop/src/renderer/check-storage/migration.tsindex dc498bc,0000000..11c389emode 100644,000000..100644--- a/apps/desktop/src/renderer/check-storage/migration.ts+++ b/apps/desktop/src/renderer/check-storage/migration.ts@@@ -1,33 -1,0 +1,33 @@@+import { MimikDB } from '@mimik/core/guides/db';+import Dexie from 'dexie';+import type { CheckResult } from './types';++const MIGRATION_DB = 'mimik-migration-check';++export async function migration(): Promise<CheckResult> {+ await Dexie.delete(MIGRATION_DB);++ const v1 = new Dexie(MIGRATION_DB);+ v1.version(1).stores({+ guides: 'id, createdAt, updatedAt, starred, deletedAt',+ steps: 'id, guideId, index',+ screenshots: 'id, stepId',+ });+ await v1.open();+ await v1.table('guides').add({ id: 'legacy', title: 'Written at v1', createdAt: 1, updatedAt: 1, stepIds: [] });+ v1.close();++ const upgraded = new MimikDB(MIGRATION_DB);+ await upgraded.open();+ const survivor = await upgraded.guides.get('legacy');+ const snapshotCount = await upgraded.snapshots.count();+ const verno = upgraded.verno;+ upgraded.close();+ await Dexie.delete(MIGRATION_DB);++ return {- name: 'v1 to v2 migration',- ok: verno === 2 && survivor?.title === 'Written at v1' && snapshotCount === 0,++ name: 'v1 to current migration',++ ok: verno === 5 && survivor?.title === 'Written at v1' && snapshotCount === 0,+ detail: `reopened at v${verno}, v1 row ${survivor ? 'survived' : 'lost'}, snapshots table readable`,+ };+}diff --cc apps/desktop/src/renderer/check-storage/open.tsindex cd9df20,0000000..79dab69mode 100644,000000..100644--- a/apps/desktop/src/renderer/check-storage/open.ts+++ b/apps/desktop/src/renderer/check-storage/open.ts@@@ -1,13 -1,0 +1,13 @@@+import { db } from '@mimik/core/guides/db';+import type { CheckResult } from './types';++export async function open(): Promise<CheckResult> {+ await db.open();+ const tables = db.tables.map((t) => t.name).sort();- const expected = ['guides', 'screenshots', 'snapshots', 'steps'];++ const expected = ['guideMerges', 'guides', 'screenshots', 'snapshots', 'steps', 'transcripts', 'voiceClips'];+ return {+ name: 'MimikDB opens',- ok: db.verno === 2 && expected.every((t) => tables.includes(t)),++ ok: db.verno === 5 && expected.every((t) => tables.includes(t)),+ detail: `v${db.verno}, tables: ${tables.join(', ')}`,+ };+}diff --cc apps/desktop/src/renderer/core-env.tsindex 007da28,0000000..cba4230mode 100644,000000..100644--- a/apps/desktop/src/renderer/core-env.ts+++ b/apps/desktop/src/renderer/core-env.ts@@@ -1,60 -1,0 +1,67 @@@+import { configureCore } from '@mimik/core/env';+import type { Settings, SettingsKey } from '@mimik/core/guides/types';+import { type Messages, translate } from '@mimik/core/i18n/translate';+import de from '@mimik/locales/de.yml';+import en from '@mimik/locales/en.yml';+import es from '@mimik/locales/es.yml';+import fr from '@mimik/locales/fr.yml';+import ptBR from '@mimik/locales/pt-BR.yml';+import zhCN from '@mimik/locales/zh-CN.yml';+import { type AppLocale, appLocale } from './lib/app-locale';++async function mainFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ const headers: Record<string, string> = {};+ new Headers(init?.headers).forEach((value, key) => {+ headers[key] = value;+ });+ const reply = (await window.mimik.ai.fetch({+ url,+ method: init?.method ?? 'GET',+ headers,+ body: typeof init?.body === 'string' ? init.body : undefined,- })) as { status: number; statusText: string; headers: Record<string, string>; body: string };- return new Response(reply.body, { status: reply.status, statusText: reply.statusText, headers: reply.headers });++ })) as {++ status: number;++ statusText: string;++ headers: Record<string, string>;++ body: string;++ encoding: 'text' | 'base64';++ };++ const body = reply.encoding === 'base64' ? Uint8Array.from(atob(reply.body), (c) => c.charCodeAt(0)) : reply.body;++ return new Response(body, { status: reply.status, statusText: reply.statusText, headers: reply.headers });+}++const MESSAGES: Record<AppLocale, Messages> = {+ en: en as Messages,+ de: de as Messages,+ es: es as Messages,+ fr: fr as Messages,+ 'pt-BR': ptBR as Messages,+ 'zh-CN': zhCN as Messages,+};++const locale = appLocale(window.localStorage.getItem('appLanguage')?.replace(/^"|"$/g, ''), navigator.language);+window.mimik?.locale(locale);++configureCore({+ client: 'desktop',+ fetch: mainFetch,+ t: (key, substitutions) => {+ const text = translate(MESSAGES[locale], key, substitutions);+ return text === key ? translate(MESSAGES.en, key, substitutions) : text;+ },+ assetUrl: (path) => new URL(path.replace(/^\//, ''), document.baseURI).href,+ storage: {+ get: async <K extends SettingsKey>(keys: readonly K[]) => {+ const out: Record<string, unknown> = {};+ for (const key of keys) {+ const raw = window.localStorage.getItem(key);+ if (raw !== null) out[key] = JSON.parse(raw);+ }+ return out as Partial<Pick<Settings, K>>;+ },+ set: async (items: Partial<Settings>) => {+ for (const [key, value] of Object.entries(items)) window.localStorage.setItem(key, JSON.stringify(value));+ },+ },+});diff --cc packages/core/src/capture/ai/__tests__/description.test.tsindex 0000000,eb376d3..505b2eemode 000000,100644..100644--- a/packages/core/src/capture/ai/__tests__/description.test.ts+++ b/packages/core/src/capture/ai/__tests__/description.test.ts@@@ -1,0 -1,63 +1,64 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ const { generateTextMock } = vi.hoisted(() => ({ generateTextMock: vi.fn() }));++ vi.mock('ai', () => ({ generateText: generateTextMock }));++ vi.mock('../provider', () => ({ createModel: () => ({ id: 'test-model' }) }));+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/core/env', async (importOriginal) => ({++ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: vi.fn().mockResolvedValue({ aiLanguage: 'en' }) },+ }));+-import { localStorage } from '@/lib/browser-api';-import type { DOMContext } from '../../dom/context';++import { localStorage } from '@/core/env';++import { type DOMContext, serializeDOMContext } from '../../dom/context';+ import { getAIDescription } from '../description';++ function makeContext(overrides: Partial<DOMContext> = {}): DOMContext {+ return {+ page: { title: 'Settings', path: '/settings' },+ container: null,+ heading: null,+ siblings: [],+ target: { tag: 'button', role: null, name: 'Update profile', value: null, action: 'click' },+ ...overrides,+ };+ }++ async function promptFor(aiLanguage: string, context = makeContext()): Promise<string> {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage });- await getAIDescription(context, 'openai', 'gpt-4o-mini', 'key');++ await getAIDescription(serializeDOMContext(context), 'openai', 'gpt-4o-mini', 'key');+ return generateTextMock.mock.calls[0][0].prompt as string;+ }++ describe('getAIDescription', () => {+ beforeEach(() => {+ generateTextMock.mockReset();+ generateTextMock.mockResolvedValue({ text: 'Click Update profile' });+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage: 'en' });+ });++ it('leaves no placeholder unfilled', async () => {+ expect(await promptFor('en')).not.toMatch(/\{\{\w+\}\}/);+ });++ it('gives the model examples in the configured language', async () => {+ const prompt = await promptFor('fr');+ expect(prompt).toContain('Cliquer sur le bouton Submit');+ expect(prompt).not.toContain('Click the Submit button');+ });++ it('writes the language instruction in that language too', async () => {+ expect(await promptFor('de')).toContain('WICHTIG');+ });++ it('appends no language instruction for English', async () => {+ expect(await promptFor('en')).not.toContain('IMPORTANT: Write the output in');+ });++ it('does not let page text act as a replacement pattern', async () => {+ const prompt = await promptFor('en', makeContext({ page: { title: 'Save $& and $` now', path: '/x' } }));+ expect(prompt).toContain('Save $& and $` now');+ });+ });diff --cc packages/core/src/capture/ai/__tests__/examples.test.tsindex 0000000,4c073b0..4c073b0mode 000000,100644..100644--- a/packages/core/src/capture/ai/__tests__/examples.test.ts+++ b/packages/core/src/capture/ai/__tests__/examples.test.tsdiff --cc packages/core/src/capture/ai/__tests__/locale.test.tsindex 0000000,3bfbe95..3bfbe95mode 000000,100644..100644--- a/packages/core/src/capture/ai/__tests__/locale.test.ts+++ b/packages/core/src/capture/ai/__tests__/locale.test.tsdiff --cc packages/core/src/capture/ai/__tests__/meta.test.tsindex 5c29eed,2fd7eed..8fb69db--- a/packages/core/src/capture/ai/__tests__/meta.test.ts+++ b/packages/core/src/capture/ai/__tests__/meta.test.ts@@@ -14,9 -13,14 +14,15 @@@ vi.mock('ai', () => (vi.mock('../provider', () => ({ createModel: () => ({ id: 'test-model' }) }));-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/core/env', async (importOriginal) => ({++ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: vi.fn().mockResolvedValue({ aiLanguage: 'en' }) },+ }));+-import { localStorage } from '@/lib/browser-api';-import { generateGuideMeta, parseGuideMeta } from '../meta';++import { localStorage } from '@/core/env';+import { generateGuideMeta, guideMetaSteps, parseGuideMeta } from '../meta';-const steps = [{ description: 'Click Directory', url: 'https://admin.okta.com/users' }];+const steps = [{ description: 'Click Directory', place: 'https://admin.okta.com/users' }];const UNSUPPORTED = new Error('response_format json_schema is not supported by this model');@@@ -188,23 -196,36 +198,57 @@@ describe('parseGuideMeta', () =>});});+describe('guideMetaSteps', () => {+ it('places a desktop step by its application and window, since it has no address', () => {+ const step = (over: Partial<Step>): Step => ({+ id: 'step',+ guideId: 'guide',+ index: 0,+ description: 'Click "Downloads"',+ action: 'click',+ url: '',+ timestamp: 0,+ ...over,+ });+ expect(+ guideMetaSteps([+ step({ app: { name: 'File Explorer' }, window: { title: 'Downloads' } }),+ step({ url: 'https://example.com/a' }),+ ]).map((entry) => entry.place),+ ).toEqual(['File Explorer — Downloads', 'https://example.com/a']);+ });+});+++ describe('guide meta prompt', () => {+ beforeEach(() => {+ generateObjectMock.mockReset();+ generateObjectMock.mockResolvedValue({ object: { title: 'A title', description: 'A description.' } });+ });++ async function promptFor(aiLanguage: string): Promise<string> {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage });+ await generateGuideMeta(steps, 'openai', 'gpt-4o-mini', 'key');+ return generateObjectMock.mock.calls[0][0].prompt as string;+ }++ it('leaves no placeholder unfilled', async () => {+ expect(await promptFor('en')).not.toMatch(/\{\{\w+\}\}/);+ });++ it('gives the model examples in the configured language', async () => {+ const prompt = await promptFor('fr');+ expect(prompt).toContain('Configurer les notifications Slack');+ expect(prompt).not.toContain('Configure Slack Notification Preferences');+ });++ it('follows the description language, not the UI language', async () => {+ const prompt = await promptFor('de');+ expect(prompt).toContain('Spesenabrechnung in Workday einreichen');+ });++ it('does not let step text act as a replacement pattern', async () => {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage: 'en' });- await generateGuideMeta([{ description: 'Click $& then $`', url: 'https://example.com' }], 'openai', 'm', 'key');++ await generateGuideMeta([{ description: 'Click $& then $`', place: 'https://example.com' }], 'openai', 'm', 'key');+ expect(generateObjectMock.mock.calls[0][0].prompt).toContain('Click $& then $`');+ });+ });diff --cc packages/core/src/capture/ai/__tests__/prompt-render.test.tsindex 0000000,a0abbac..7e76ff8mode 000000,100644..100644--- a/packages/core/src/capture/ai/__tests__/prompt-render.test.ts+++ b/packages/core/src/capture/ai/__tests__/prompt-render.test.ts@@@ -1,0 -1,119 +1,120 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ const { generateTextMock, generateObjectMock } = vi.hoisted(() => ({+ generateTextMock: vi.fn(),+ generateObjectMock: vi.fn(),+ }));++ vi.mock('ai', () => ({+ generateText: generateTextMock,+ generateObject: generateObjectMock,+ jsonSchema: (schema: unknown) => schema,+ }));++ vi.mock('../provider', () => ({ createModel: () => ({ id: 'test-model' }) }));+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/core/env', async (importOriginal) => ({++ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: vi.fn().mockResolvedValue({ aiLanguage: 'en' }) },+ }));+-import { localStorage } from '@/lib/browser-api';-import type { DOMContext } from '../../dom/context';++import { localStorage } from '@/core/env';++import { type DOMContext, serializeDOMContext } from '../../dom/context';+ import { getAIDescription } from '../description';+ import { resolveExamples } from '../examples';+ import { generateGuideMeta } from '../meta';+ import { AI_LANGUAGES, type AILanguageCode } from '../prompts';++ const CONTEXT: DOMContext = {+ page: { title: 'Settings', path: '/settings' },+ container: null,+ heading: null,+ siblings: [],+ target: { tag: 'button', role: null, name: 'Update profile', value: null, action: 'click' },+ };+-const STEPS = [{ description: 'Click Directory', url: 'https://admin.okta.com/users' }];++const STEPS = [{ description: 'Click Directory', place: 'https://admin.okta.com/users' }];++ async function stepPrompt(aiLanguage: string): Promise<string> {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage });+ generateTextMock.mockReset();+ generateTextMock.mockResolvedValue({ text: 'ok' });- await getAIDescription(CONTEXT, 'openai', 'gpt-4o-mini', 'key');++ await getAIDescription(serializeDOMContext(CONTEXT), 'openai', 'gpt-4o-mini', 'key');+ return generateTextMock.mock.calls[0][0].prompt as string;+ }++ async function metaPrompt(aiLanguage: string): Promise<string> {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage });+ generateObjectMock.mockReset();+ generateObjectMock.mockResolvedValue({ object: { title: 'T', description: 'D' } });+ await generateGuideMeta(STEPS, 'openai', 'gpt-4o-mini', 'key');+ return generateObjectMock.mock.calls[0][0].prompt as string;+ }++ const CODES = AI_LANGUAGES.map((l) => l.code) as readonly AILanguageCode[];++ const EXPECTED: Record<AILanguageCode, { step: string; title: string }> = {+ en: { step: 'Click the Submit button', title: 'Configure Slack Notification Preferences' },+ es: { step: 'Hacer clic en el botón Submit', title: 'Configurar las notificaciones de Slack' },+ fr: { step: 'Cliquer sur le bouton Submit', title: 'Configurer les notifications Slack' },+ de: { step: 'Auf die Schaltfläche Submit klicken', title: 'Slack-Benachrichtigungen konfigurieren' },+ 'pt-BR': { step: 'Clicar no botão Submit', title: 'Configurar as notificações do Slack' },+ 'zh-CN': { step: '点击 Submit 按钮', title: '配置 Slack 通知偏好' },+ };++ describe.each(CODES)('rendered prompts for %s', (code) => {+ beforeEach(() => {+ vi.mocked(localStorage.get).mockResolvedValue({ aiLanguage: code });+ });++ it('fills every placeholder in both prompts', async () => {+ expect(await stepPrompt(code)).not.toMatch(/\{\{\w+\}\}/);+ expect(await metaPrompt(code)).not.toMatch(/\{\{\w+\}\}/);+ });++ it('carries this language own examples', async () => {+ expect(await stepPrompt(code)).toContain(EXPECTED[code].step);+ expect(await metaPrompt(code)).toContain(EXPECTED[code].title);+ });++ it('renders every example bullet without a nested quote collision', async () => {+ for (const prompt of [await stepPrompt(code), await metaPrompt(code)]) {+ for (const line of prompt.split('\n')) {+ if (line.startsWith('- ')) expect(line).not.toMatch(/^- ".*".*"/);+ }+ }+ });++ it('keeps UI labels and product names untranslated in the examples', async () => {+ const step = await stepPrompt(code);+ expect(step).toContain('Submit');+ expect(step).toContain('Settings');+ const meta = await metaPrompt(code);+ expect(meta).toContain('claude-code');+ expect(meta).toContain('Workday');+ });++ it('states the never-translate rule in both prompts', async () => {+ expect(await stepPrompt(code)).toContain('Never translate');+ expect(await metaPrompt(code)).toContain('Never translate');+ });++ it('appends a native-language instruction, or none at all for English', async () => {+ const step = await stepPrompt(code);+ if (code === 'en') {+ expect(step).not.toContain('IMPORTANT: Write the output in');+ expect(step).not.toContain('IMPORTANTE');+ } else {+ expect(step).not.toContain('Write the output in');+ expect(await metaPrompt(code)).not.toContain('Write the output in');+ }+ });++ it('never leaks another language examples', async () => {+ const step = await stepPrompt(code);+ for (const other of CODES) {+ if (other === code) continue;+ expect(step).not.toContain(resolveExamples(other).steps[0]);+ }+ });+ });diff --cc packages/core/src/capture/ai/__tests__/text.test.tsindex 0000000,fde7198..fde7198mode 000000,100644..100644--- a/packages/core/src/capture/ai/__tests__/text.test.ts+++ b/packages/core/src/capture/ai/__tests__/text.test.tsdiff --cc packages/core/src/capture/ai/description.tsindex 10642d9,8d0c114..85c47a4--- a/packages/core/src/capture/ai/description.ts+++ b/packages/core/src/capture/ai/description.ts@@@ -1,10 -1,14 +1,12 @@@import { generateText } from 'ai';-import { localStorage } from '@/lib/browser-api';-import type { DOMContext } from '../dom/context';-import { serializeDOMContext } from '../dom/context';+import { localStorage } from '@/core/env';+ import { formatExamples, resolveExamples } from './examples';import { getLanguageSuffix, STEP_DESCRIPTION_PROMPT } from './prompts';import { createModel } from './provider';+ import { unwrapQuotes } from './text';export async function getAIDescription(- domContext: DOMContext,+ context: string,provider: string,model: string,apiKey: string,@@@ -13,10 -16,15 +15,13 @@@): Promise<string | null> {const settings = await localStorage.get(['aiLanguage']);const locale = (settings.aiLanguage as string) || 'en';- const context = serializeDOMContext(domContext);- const prompt = STEP_DESCRIPTION_PROMPT.replace('{{examples}}', formatExamples(resolveExamples(locale).steps)).replace(- '{{context}}',- () => context,- );++ const prompt = template++ .replace('{{examples}}', formatExamples(resolveExamples(locale).steps))++ .replace('{{context}}', () => context);const { text } = await generateText({model: createModel(provider, model, apiKey, baseUrl),- prompt: template.replace('{{context}}', context) + getLanguageSuffix(locale),+ prompt: prompt + getLanguageSuffix(locale),maxOutputTokens: 50,});- return text.trim().replace(/^"|"$/g, '') || null;+ return unwrapQuotes(text) || null;}diff --cc packages/core/src/capture/ai/examples.tsindex 0000000,bb5367f..bb5367fmode 000000,100644..100644--- a/packages/core/src/capture/ai/examples.ts+++ b/packages/core/src/capture/ai/examples.tsdiff --cc packages/core/src/capture/ai/locale.tsindex 0000000,61c55fd..61c55fdmode 000000,100644..100644--- a/packages/core/src/capture/ai/locale.ts+++ b/packages/core/src/capture/ai/locale.tsdiff --cc packages/core/src/capture/ai/meta.tsindex e0cbd00,37fc252..c05f153--- a/packages/core/src/capture/ai/meta.ts+++ b/packages/core/src/capture/ai/meta.ts@@@ -1,10 -1,11 +1,13 @@@import { generateObject, generateText, jsonSchema } from 'ai';+import { localStorage } from '@/core/env';+import { actionSteps } from '@/core/guides/blocks';+ import { MAX_TITLE_LENGTH, sanitizeGuideTitle } from '@/core/guides/title';-import { localStorage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import type { Step } from '@/core/guides/types';+import { logger } from '@/core/logger';+ import { formatExamples, resolveExamples } from './examples';import { GUIDE_META_JSON_SUFFIX, GUIDE_META_PROMPT, getLanguageSuffix } from './prompts';import { createModel } from './provider';+ import { unwrapQuotes } from './text';export interface GuideMeta {title: string;@@@ -64,10 -63,14 +65,14 @@@ export async function generateGuideMeta): Promise<GuideMeta | null> {if (steps.length === 0) return null;- const formatted = steps.map((s, i) => `${i + 1}. [${s.url}] ${s.description}`).join('\n');+ const formatted = steps.map((s, i) => `${i + 1}. [${s.place}] ${s.description}`).join('\n');const settings = await localStorage.get(['aiLanguage']);const locale = (settings.aiLanguage as string) || 'en';- const prompt = GUIDE_META_PROMPT.replace('{{steps}}', formatted) + getLanguageSuffix(locale);+ const examples = resolveExamples(locale);+ const prompt =+ GUIDE_META_PROMPT.replace('{{titleExamples}}', formatExamples(examples.titles))+ .replace('{{descriptionExamples}}', formatExamples(examples.descriptions))+ .replace('{{steps}}', () => formatted) + getLanguageSuffix(locale);const aiModel = createModel(provider, model, apiKey, baseUrl);try {diff --cc packages/core/src/capture/ai/prompts.tsindex 686e463,a204904..76d9b9b--- a/packages/core/src/capture/ai/prompts.ts+++ b/packages/core/src/capture/ai/prompts.ts@@@ -30,20 -15,17 +29,17 @@@ export const GUIDE_META_PROMPT = `ThesWrite a title and a description for this workflow.-TITLE: specific and descriptive. Mention the application or website name and the specific task performed. Reference specific pages, features, or items that were interacted with. MUST be under 60 characters.+TITLE: specific and descriptive. Mention the application or website name and the specific task performed. Reference specific pages, features, or items that were interacted with. Only name applications, websites and items that appear in the steps. MUST be under 60 characters.Examples of good titles:- - "Review claude-code Pull Requests"- - "Configure Slack Notification Preferences"- - "Submit Expense Report in Workday"- - "Create Repository in GitHub Organization"- - "Export a Budget to PDF in Excel"+ {{titleExamples}}-DESCRIPTION: one or two sentences stating what the workflow accomplishes and who would follow it. Do not repeat the title. Do not list the individual steps. Do not mention any UI element that does not appear in the steps above.+DESCRIPTION: one or two sentences stating what the workflow accomplishes and who would follow it. Do not repeat the title. Do not list the individual steps. Do not mention any application, website or UI element that does not appear in the steps above.Examples of good descriptions:- - "Reset a locked-out user's password from the Okta admin panel. For IT support staff."- - "Configure which Slack channels send desktop notifications, and set a do-not-disturb schedule."`;+ {{descriptionExamples}}++ Copy application names, page names, and UI labels exactly as they appear in the steps. Never translate them.`;export const GUIDE_META_JSON_SUFFIX = `diff --cc packages/core/src/capture/ai/text.tsindex 0000000,a680d3a..a680d3amode 000000,100644..100644--- a/packages/core/src/capture/ai/text.ts+++ b/packages/core/src/capture/ai/text.tsdiff --cc packages/core/src/capture/dom/__tests__/frame-placement.test.tsindex 0000000,240bd86..240bd86mode 000000,100644..100644--- a/packages/core/src/capture/dom/__tests__/frame-placement.test.ts+++ b/packages/core/src/capture/dom/__tests__/frame-placement.test.tsdiff --cc packages/core/src/capture/dom/frame-placement.tsindex 0000000,873f831..873f831mode 000000,100644..100644--- a/packages/core/src/capture/dom/frame-placement.ts+++ b/packages/core/src/capture/dom/frame-placement.tsdiff --cc packages/core/src/capture/voice/__tests__/transcript-lines.test.tsindex 0000000,06459c8..06459c8mode 000000,100644..100644--- a/packages/core/src/capture/voice/__tests__/transcript-lines.test.ts+++ b/packages/core/src/capture/voice/__tests__/transcript-lines.test.tsdiff --cc packages/core/src/export/__tests__/video-export-encode.test.tsindex c24dd90,cd47dd8..31f47e3--- a/packages/core/src/export/__tests__/video-export-encode.test.ts+++ b/packages/core/src/export/__tests__/video-export-encode.test.ts@@@ -92,6 -109,28 +109,29 @@@ vi.mock('@/core/export/video-support',};});+ const renderVoiceover = vi.hoisted(() => vi.fn());++ vi.mock('@/core/export/voiceover/render', () => ({ renderVoiceover }));++ vi.mock('@/core/export/voiceover/audio', async () => {+ const actual = await vi.importActual<typeof import('@/core/export/voiceover/audio')>('@/core/export/voiceover/audio');+ return {+ ...actual,+ pickVoiceContainer: vi.fn(async (containers: ('mp4' | 'webm')[]) => {+ for (const container of containers) {+ const codec = container === 'mp4' ? ('aac' as const) : ('opus' as const);+ if (voice.codecs.includes(codec)) return { container, codec };+ }+ return null;+ }),+ };+ });+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/core/env', async (importOriginal) => ({++ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: vi.fn(async () => voice.settings), set: vi.fn(async () => undefined) },+ }));+vi.mock('@/core/screenshot/render', () => ({renderScreenshot: vi.fn(async () => new Blob(['webp'])),}));diff --cc packages/core/src/export/markdown-export.tsindex 51b970c,cad347d..683bc12--- a/packages/core/src/export/markdown-export.ts+++ b/packages/core/src/export/markdown-export.ts@@@ -1,6 -1,7 +1,7 @@@-import { i18n } from '#imports';+import { i18n } from '@/core/env';import { blobToBase64, extractDomain, formatDate } from '@/core/export/utils';import { actionSteps, isBlock, stepNumbers, variantLabel } from '@/core/guides/blocks';+ import { sanitizeGuideTitle } from '@/core/guides/title';import type { Guide, Screenshot, Step } from '@/core/guides/types';import { renderScreenshot } from '@/core/screenshot/render';diff --cc packages/core/src/export/options.tsindex 0165607,a194ff1..0a2326f--- a/packages/core/src/export/options.ts+++ b/packages/core/src/export/options.ts@@@ -1,4 -1,7 +1,7 @@@+import { localStorage } from '@/core/env';+ import type { BundleUrlMode } from '@/core/transfer/bundle';-import { localStorage } from '@/lib/browser-api';++ export type { BundleUrlMode };export type ImageScale = 'small' | 'medium' | 'large';diff --cc packages/core/src/export/video-export.tsindex 5d5f2b1,4165e7a..d663e6e--- a/packages/core/src/export/video-export.ts+++ b/packages/core/src/export/video-export.ts@@@ -1,4 -1,4 +1,4 @@@- import { i18n } from '@/core/env';-import { i18n } from '#imports';++import { i18n, localStorage } from '@/core/env';import type { Branding } from '@/core/export/branding';import { dataUrlToBytes, fitLogo, loadBranding } from '@/core/export/branding';import type { ExportOptions } from '@/core/export/options';@@@ -14,16 -15,23 +15,22 @@@ importSTEP_SECONDS,STEP_ZOOM_TRANSITION_SEC,STEP_ZOOMED_OUT_SEC,+ TRANSITION_SECONDS,+ uniformTimeline,+ type VideoContainer,+ type VideoTimeline,+ VOICE_LEAD_SEC,+ voiceTimeline,} from '@/core/export/video-support';+ import { COVER_SEGMENT, stepNarration } from '@/core/export/voiceover/script';import { actionSteps, calloutAccent, isBlock } from '@/core/guides/blocks';import type { BlockType, Guide, Screenshot, Step } from '@/core/guides/types';++import { logger } from '@/core/logger';import type { Ctx } from '@/core/screenshot/draw';import { drawRoundedRect, TARGET_RADIUS, TARGET_STROKE } from '@/core/screenshot/draw';import { clamp, resolveFrameViewport, resolveTarget } from '@/core/screenshot/geometry';import { renderScreenshot } from '@/core/screenshot/render';-import { localStorage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';- const TRANSITION_DURATION_SEC = 0.33;- const COVER_SECONDS = 3;const KEY_FRAME_INTERVAL_SEC = 2;const ZOOM_MIN = 1;diff --cc packages/core/src/export/voiceover/__tests__/audio.test.tsindex 0000000,d17def5..d17def5mode 000000,100644..100644--- a/packages/core/src/export/voiceover/__tests__/audio.test.ts+++ b/packages/core/src/export/voiceover/__tests__/audio.test.tsdiff --cc packages/core/src/export/voiceover/__tests__/client.test.tsindex 0000000,79bc4d3..79bc4d3mode 000000,100644..100644--- a/packages/core/src/export/voiceover/__tests__/client.test.ts+++ b/packages/core/src/export/voiceover/__tests__/client.test.tsdiff --cc packages/core/src/export/voiceover/__tests__/config.test.tsindex 0000000,8e3a141..8e3a141mode 000000,100644..100644--- a/packages/core/src/export/voiceover/__tests__/config.test.ts+++ b/packages/core/src/export/voiceover/__tests__/config.test.tsdiff --cc packages/core/src/export/voiceover/__tests__/script.test.tsindex 0000000,834cfe0..834cfe0mode 000000,100644..100644--- a/packages/core/src/export/voiceover/__tests__/script.test.ts+++ b/packages/core/src/export/voiceover/__tests__/script.test.tsdiff --cc packages/core/src/export/voiceover/audio.tsindex 0000000,20bf39c..20bf39cmode 000000,100644..100644--- a/packages/core/src/export/voiceover/audio.ts+++ b/packages/core/src/export/voiceover/audio.tsdiff --cc packages/core/src/export/voiceover/cache.tsindex 0000000,7deaa41..240c2bemode 000000,100644..100644--- a/packages/core/src/export/voiceover/cache.ts+++ b/packages/core/src/export/voiceover/cache.ts@@@ -1,0 -1,43 +1,43 @@@+ import { db } from '@/core/guides/db';-import { logger } from '@/lib/logger';++import { logger } from '@/core/logger';++ const MAX_CLIPS = 500;++ export async function clipKey(provider: string, voiceId: string, modelId: string, text: string): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));+ const hash = Array.from(new Uint8Array(digest))+ .slice(0, 16)+ .map((byte) => byte.toString(16).padStart(2, '0'))+ .join('');+ return `${provider}:${voiceId}:${modelId}:${hash}`;+ }++ export async function readClip(id: string): Promise<ArrayBuffer | null> {+ try {+ const row = await db.voiceClips.get(id);+ return row?.bytes ?? null;+ } catch (error) {+ logger.error('[voiceover] cache read failed', error);+ return null;+ }+ }++ export async function writeClip(id: string, bytes: ArrayBuffer): Promise<void> {+ try {+ await db.voiceClips.put({ id, bytes, createdAt: Date.now() });+ const count = await db.voiceClips.count();+ if (count > MAX_CLIPS) {+ const stale = await db.voiceClips+ .orderBy('createdAt')+ .limit(count - MAX_CLIPS)+ .primaryKeys();+ await db.voiceClips.bulkDelete(stale);+ }+ } catch (error) {+ logger.error('[voiceover] cache write failed', error);+ }+ }++ export async function clearClips(): Promise<void> {+ await db.voiceClips.clear();+ }diff --cc packages/core/src/export/voiceover/client.tsindex 0000000,6b107e1..1929de2mode 000000,100644..100644--- a/packages/core/src/export/voiceover/client.ts+++ b/packages/core/src/export/voiceover/client.ts@@@ -1,0 -1,94 +1,95 @@@++import { coreFetch } from '@/core/env';+ import type { VoiceoverConfig } from './config';+ import { type VoiceoverProviderKey, type VoiceoverVoice, voiceoverProvider } from './providers';++ const ERROR_BODY_LIMIT = 200;+ const REQUEST_TIMEOUT_MS = 60_000;++ export interface SpeechRequest {+ url: string;+ headers: Record<string, string>;+ body: string;+ }++ function authHeaders(provider: VoiceoverProviderKey, apiKey: string): Record<string, string> {+ return provider === 'elevenlabs' ? { 'xi-api-key': apiKey } : { Authorization: `Bearer ${apiKey}` };+ }++ export function speechRequest(config: VoiceoverConfig, text: string): SpeechRequest {+ const base = voiceoverProvider(config.provider).defaultBaseUrl;+ const headers = { ...authHeaders(config.provider, config.apiKey), 'Content-Type': 'application/json' };++ if (config.provider === 'elevenlabs') {+ return {+ url: `${base}/text-to-speech/${encodeURIComponent(config.voiceId)}?output_format=mp3_44100_128`,+ headers,+ body: JSON.stringify({ text, model_id: config.modelId }),+ };+ }++ return {+ url: `${base}/audio/speech`,+ headers,+ body: JSON.stringify({ model: config.modelId, voice: config.voiceId, input: text, response_format: 'mp3' }),+ };+ }++ function timeout(signal?: AbortSignal): AbortSignal {+ const limit = AbortSignal.timeout(REQUEST_TIMEOUT_MS);+ return signal ? AbortSignal.any([signal, limit]) : limit;+ }++ export async function synthesizeSpeech(+ config: VoiceoverConfig,+ text: string,+ signal?: AbortSignal,+ ): Promise<ArrayBuffer> {+ const request = speechRequest(config, text);- const response = await fetch(request.url, {++ const response = await coreFetch(request.url, {+ method: 'POST',+ headers: request.headers,+ body: request.body,+ signal: timeout(signal),+ });++ if (!response.ok) {+ const label = voiceoverProvider(config.provider).label;+ if (response.status === 401 || response.status === 403) {+ throw new Error(`${label} rejected the API key (${response.status})`);+ }+ const body = await response.text().catch(() => '');+ throw new Error(`${label} returned ${response.status}: ${body.slice(0, ERROR_BODY_LIMIT)}`);+ }++ return response.arrayBuffer();+ }++ export function parseVoices(body: unknown): VoiceoverVoice[] {+ if (typeof body !== 'object' || body === null) return [];+ const list = (body as { voices?: unknown }).voices;+ if (!Array.isArray(list)) return [];+ return list+ .map((entry) => {+ if (typeof entry !== 'object' || entry === null) return null;+ const { voice_id: id, name } = entry as { voice_id?: unknown; name?: unknown };+ if (typeof id !== 'string' || !id) return null;+ return { id, name: typeof name === 'string' && name ? name : id };+ })+ .filter((voice): voice is VoiceoverVoice => voice !== null);+ }++ export async function fetchVoices(+ provider: VoiceoverProviderKey,+ apiKey: string,+ signal?: AbortSignal,+ ): Promise<VoiceoverVoice[]> {+ const config = voiceoverProvider(provider);+ if (!config.catalog) return config.voices;+- const response = await fetch(`${config.defaultBaseUrl}/voices`, {++ const response = await coreFetch(`${config.defaultBaseUrl}/voices`, {+ headers: authHeaders(provider, apiKey),+ signal: timeout(signal),+ });+ if (!response.ok) throw new Error(`${config.label} returned ${response.status}`);+ return parseVoices(await response.json().catch(() => null));+ }diff --cc packages/core/src/export/voiceover/config.tsindex 0000000,db4e9f5..db4e9f5mode 000000,100644..100644--- a/packages/core/src/export/voiceover/config.ts+++ b/packages/core/src/export/voiceover/config.tsdiff --cc packages/core/src/export/voiceover/providers.tsindex 0000000,2da6edd..2da6eddmode 000000,100644..100644--- a/packages/core/src/export/voiceover/providers.ts+++ b/packages/core/src/export/voiceover/providers.tsdiff --cc packages/core/src/export/voiceover/render.tsindex 0000000,d8f9bdc..a1707d4mode 000000,100644..100644--- a/packages/core/src/export/voiceover/render.ts+++ b/packages/core/src/export/voiceover/render.ts@@@ -1,0 -1,74 +1,74 @@@-import { logger } from '@/lib/logger';++import { logger } from '@/core/logger';+ import { decodeClip } from './audio';+ import { clipKey, readClip, writeClip } from './cache';+ import { synthesizeSpeech } from './client';+ import type { VoiceoverConfig } from './config';+ import type { VoiceoverSegment } from './script';++ export interface VoiceoverControls {+ signal?: AbortSignal;+ onProgress?: (done: number, total: number) => void;+ }++ const RETRY_DELAY_MS = 1500;++ function aborted(error: unknown): boolean {+ return error instanceof DOMException && error.name === 'AbortError';+ }++ function wait(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, ms);+ signal?.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ reject(new DOMException('Voiceover was aborted', 'AbortError'));+ },+ { once: true },+ );+ });+ }++ async function clipBytes(+ segment: VoiceoverSegment,+ config: VoiceoverConfig,+ signal?: AbortSignal,+ ): Promise<ArrayBuffer> {+ const key = await clipKey(config.provider, config.voiceId, config.modelId, segment.text);+ const cached = await readClip(key);+ if (cached) return cached;++ let bytes: ArrayBuffer;+ try {+ bytes = await synthesizeSpeech(config, segment.text, signal);+ } catch (error) {+ if (aborted(error)) throw error;+ logger.error('[voiceover] synthesis retrying', error);+ await wait(RETRY_DELAY_MS, signal);+ bytes = await synthesizeSpeech(config, segment.text, signal);+ }++ await writeClip(key, bytes);+ return bytes;+ }++ export async function renderVoiceover(+ segments: VoiceoverSegment[],+ config: VoiceoverConfig,+ controls: VoiceoverControls = {},+ ): Promise<Map<number, AudioBuffer>> {+ const { signal, onProgress } = controls;+ const clips = new Map<number, AudioBuffer>();+ let done = 0;++ onProgress?.(0, segments.length);++ for (const segment of segments) {+ if (signal?.aborted) throw new DOMException('Voiceover was aborted', 'AbortError');+ clips.set(segment.index, await decodeClip(await clipBytes(segment, config, signal)));+ onProgress?.(++done, segments.length);+ }++ return clips;+ }diff --cc packages/core/src/export/voiceover/script.tsindex 0000000,a3e2bf5..a3e2bf5mode 000000,100644..100644--- a/packages/core/src/export/voiceover/script.ts+++ b/packages/core/src/export/voiceover/script.tsdiff --cc packages/core/src/guides/__tests__/duplicate.test.tsindex 0000000,9ec4d54..9ec4d54mode 000000,100644..100644--- a/packages/core/src/guides/__tests__/duplicate.test.ts+++ b/packages/core/src/guides/__tests__/duplicate.test.tsdiff --cc packages/core/src/guides/__tests__/import-guide.test.tsindex 0000000,a158254..a158254mode 000000,100644..100644--- a/packages/core/src/guides/__tests__/import-guide.test.ts+++ b/packages/core/src/guides/__tests__/import-guide.test.tsdiff --cc packages/core/src/guides/__tests__/screenshot-ids.test.tsindex 0000000,0000000..3f20c0cnew file mode 100644--- /dev/null+++ b/packages/core/src/guides/__tests__/screenshot-ids.test.ts@@@ -1,0 -1,0 +1,20 @@@++import 'fake-indexeddb/auto';++import { afterEach, describe, expect, it } from 'vitest';++import { db } from '../db';++import { allScreenshotIds } from '../service';++++afterEach(async () => {++ await db.screenshots.clear();++});++++describe('allScreenshotIds', () => {++ it('keeps the file a copied row still points at, not only the row ids', async () => {++ await db.screenshots.bulkAdd([++ { id: 'a1', stepId: 's1', src: 'mimik-screenshot://a1', mimeType: 'image/png', width: 1, height: 1 },++ { id: 'b2', stepId: 's2', src: 'mimik-screenshot://a1', mimeType: 'image/png', width: 1, height: 1 },++ { id: 'c3', stepId: 's3', blob: new Blob(['x']), mimeType: 'image/png', width: 1, height: 1 },++ ]);++ await db.screenshots.delete('a1');++ expect((await allScreenshotIds()).sort()).toEqual(['a1', 'b2', 'c3']);++ });++});diff --cc packages/core/src/guides/__tests__/spoken-original.test.tsindex 0000000,8475a12..8475a12mode 000000,100644..100644--- a/packages/core/src/guides/__tests__/spoken-original.test.ts+++ b/packages/core/src/guides/__tests__/spoken-original.test.tsdiff --cc packages/core/src/guides/__tests__/title.test.tsindex 0000000,fa621c5..fa621c5mode 000000,100644..100644--- a/packages/core/src/guides/__tests__/title.test.ts+++ b/packages/core/src/guides/__tests__/title.test.tsdiff --cc packages/core/src/guides/__tests__/transcript.test.tsindex 0000000,1e17a23..1e17a23mode 000000,100644..100644--- a/packages/core/src/guides/__tests__/transcript.test.ts+++ b/packages/core/src/guides/__tests__/transcript.test.tsdiff --cc packages/core/src/guides/db.tsindex 2bd65b4,433c72e..2f64c64--- a/packages/core/src/guides/db.ts+++ b/packages/core/src/guides/db.ts@@@ -1,14 -1,17 +1,17 @@@import Dexie, { type EntityTable } from 'dexie';- import type { Guide, Snapshot, Step, StoredScreenshot } from './types';-import type { Guide, GuideMerge, GuideTranscript, Screenshot, Snapshot, Step, VoiceClip } from './types';++import type { Guide, GuideMerge, GuideTranscript, Snapshot, Step, StoredScreenshot, VoiceClip } from './types';export class MimikDB extends Dexie {guides!: EntityTable<Guide, 'id'>;steps!: EntityTable<Step, 'id'>;- screenshots!: EntityTable<Screenshot, 'id'>;+ screenshots!: EntityTable<StoredScreenshot, 'id'>;snapshots!: EntityTable<Snapshot, 'id'>;+ voiceClips!: EntityTable<VoiceClip, 'id'>;+ transcripts!: EntityTable<GuideTranscript, 'id'>;+ guideMerges!: EntityTable<GuideMerge, 'id'>;- constructor() {- super('mimik');+ constructor(name = 'mimik') {+ super(name);this.version(1).stores({guides: 'id, createdAt, updatedAt, starred, deletedAt',steps: 'id, guideId, index',diff --cc packages/core/src/guides/dexie-store.tsindex aac9ab3,ecd033e..7728db0--- a/packages/core/src/guides/dexie-store.ts+++ b/packages/core/src/guides/dexie-store.ts@@@ -1,15 -1,18 +1,20 @@@-import { i18n } from '#imports';+ import { buildFallbackDescription } from '@/core/capture/step-description';import type { NarrationUpdate } from '@/core/capture/voice/narration-updates';+ import type { NarrationTranscript } from '@/core/capture/voice/types';+import { i18n } from '@/core/env';import type { ScreenshotEdits } from '@/core/screenshot/types';+ import type { ParsedBundle } from '@/core/transfer/parse';import { db } from './db';+import { getMostCommonDomain } from './domain';import { hashPayload } from './snapshot-hash';+ import { sanitizeGuideTitle } from './title';import type {BlockType,CalloutVariant,DescriptionSource,+ ElementMeta,Guide,+ GuideTranscript,Screenshot,Snapshot,Step,@@@ -325,11 -593,7 +627,17 @@@ export async function getGuideDomain(gureturn getMostCommonDomain(steps);}-export async function saveScreenshot(screenshot: Screenshot): Promise<void> {+export async function allScreenshotIds(): Promise<string[]> {- return (await db.screenshots.toCollection().primaryKeys()) as string[];++ const ids = new Set<string>();++ await db.screenshots.each((row) => {++ ids.add(row.id);++ const file = row.src ? URL.parse(row.src)?.hostname : undefined;++ if (file) ids.add(file);++ });++ return [...ids];+}++export async function saveScreenshot(screenshot: StoredScreenshot): Promise<void> {await db.screenshots.add(screenshot);}@@@ -443,46 -714,3 +758,54 @@@ export async function revertToSnapshot(if (undo) notifyGuidesChanged({ type: 'mutated' });return undo;}++export const dexieStore = {+ createGuide,+ getGuide,+ getGuides,+ getStarredGuides,+ getTrashedGuides,+ updateGuideTitle,+ updateGuideDescription,+ addStepToGuide,+ toggleStar,+ softDeleteGuide,+ restoreGuide,+ permanentlyDeleteGuide,+ reorderSteps,+ createStep,+ mergeGuideInto,+ insertBlock,+ updateCallout,+ updateStepDescription,+ applyNarrationToSteps,+ applyAiDescription,+ clearStepAiPending,+ getStep,+ updateStepInputValue,+ updateStepCapture,+ getStepsForGuide,+ findExistingStepIds,+ deleteSteps,+ deleteStep,+ getGuideDomain,+ allScreenshotIds,+ saveScreenshot,+ replaceScreenshot,+ updateScreenshotEdits,+ deleteScreenshot,+ getScreenshotsForSteps,+ getFirstScreenshot,+ createSnapshot,+ getSnapshots,+ renameSnapshot,+ revertToSnapshot,++ duplicateGuide,++ importGuide,++ saveTranscript,++ getTranscripts,++ hasTranscript,++ deleteTranscripts,++ addTranscriptLineToStep,++ restoreNarratedDescription,+};diff --cc packages/core/src/guides/service.tsindex 6010c36,0000000..a370562mode 100644,000000..100644--- a/packages/core/src/guides/service.ts+++ b/packages/core/src/guides/service.ts@@@ -1,55 -1,0 +1,65 @@@+import type { GuideStore } from './store';+import { store } from './store';++export type { GuideChangeEvent } from './dexie-store';+export { onGuidesChanged } from './dexie-store';+export { configureStore, resetStore } from './store';+export type { GuideStore };++export const createGuide: GuideStore['createGuide'] = (...args) => store.createGuide(...args);+export const getGuide: GuideStore['getGuide'] = (...args) => store.getGuide(...args);+export const getGuides: GuideStore['getGuides'] = (...args) => store.getGuides(...args);+export const getStarredGuides: GuideStore['getStarredGuides'] = (...args) => store.getStarredGuides(...args);+export const getTrashedGuides: GuideStore['getTrashedGuides'] = (...args) => store.getTrashedGuides(...args);+export const updateGuideTitle: GuideStore['updateGuideTitle'] = (...args) => store.updateGuideTitle(...args);+export const updateGuideDescription: GuideStore['updateGuideDescription'] = (...args) =>+ store.updateGuideDescription(...args);+export const addStepToGuide: GuideStore['addStepToGuide'] = (...args) => store.addStepToGuide(...args);+export const toggleStar: GuideStore['toggleStar'] = (...args) => store.toggleStar(...args);+export const softDeleteGuide: GuideStore['softDeleteGuide'] = (...args) => store.softDeleteGuide(...args);+export const restoreGuide: GuideStore['restoreGuide'] = (...args) => store.restoreGuide(...args);+export const permanentlyDeleteGuide: GuideStore['permanentlyDeleteGuide'] = (...args) =>+ store.permanentlyDeleteGuide(...args);+export const reorderSteps: GuideStore['reorderSteps'] = (...args) => store.reorderSteps(...args);+export const createStep: GuideStore['createStep'] = (...args) => store.createStep(...args);+export const mergeGuideInto: GuideStore['mergeGuideInto'] = (...args) => store.mergeGuideInto(...args);+export const insertBlock: GuideStore['insertBlock'] = (...args) => store.insertBlock(...args);+export const updateCallout: GuideStore['updateCallout'] = (...args) => store.updateCallout(...args);+export const updateStepDescription: GuideStore['updateStepDescription'] = (...args) =>+ store.updateStepDescription(...args);+export const applyNarrationToSteps: GuideStore['applyNarrationToSteps'] = (...args) =>+ store.applyNarrationToSteps(...args);+export const applyAiDescription: GuideStore['applyAiDescription'] = (...args) => store.applyAiDescription(...args);+export const clearStepAiPending: GuideStore['clearStepAiPending'] = (...args) => store.clearStepAiPending(...args);+export const getStep: GuideStore['getStep'] = (...args) => store.getStep(...args);+export const updateStepInputValue: GuideStore['updateStepInputValue'] = (...args) =>+ store.updateStepInputValue(...args);+export const updateStepCapture: GuideStore['updateStepCapture'] = (...args) => store.updateStepCapture(...args);+export const getStepsForGuide: GuideStore['getStepsForGuide'] = (...args) => store.getStepsForGuide(...args);+export const findExistingStepIds: GuideStore['findExistingStepIds'] = (...args) => store.findExistingStepIds(...args);+export const deleteSteps: GuideStore['deleteSteps'] = (...args) => store.deleteSteps(...args);+export const deleteStep: GuideStore['deleteStep'] = (...args) => store.deleteStep(...args);+export const getGuideDomain: GuideStore['getGuideDomain'] = (...args) => store.getGuideDomain(...args);+export const allScreenshotIds: GuideStore['allScreenshotIds'] = (...args) => store.allScreenshotIds(...args);+export const saveScreenshot: GuideStore['saveScreenshot'] = (...args) => store.saveScreenshot(...args);+export const replaceScreenshot: GuideStore['replaceScreenshot'] = (...args) => store.replaceScreenshot(...args);+export const updateScreenshotEdits: GuideStore['updateScreenshotEdits'] = (...args) =>+ store.updateScreenshotEdits(...args);+export const deleteScreenshot: GuideStore['deleteScreenshot'] = (...args) => store.deleteScreenshot(...args);+export const getScreenshotsForSteps: GuideStore['getScreenshotsForSteps'] = (...args) =>+ store.getScreenshotsForSteps(...args);+export const getFirstScreenshot: GuideStore['getFirstScreenshot'] = (...args) => store.getFirstScreenshot(...args);+export const createSnapshot: GuideStore['createSnapshot'] = (...args) => store.createSnapshot(...args);+export const getSnapshots: GuideStore['getSnapshots'] = (...args) => store.getSnapshots(...args);+export const renameSnapshot: GuideStore['renameSnapshot'] = (...args) => store.renameSnapshot(...args);+export const revertToSnapshot: GuideStore['revertToSnapshot'] = (...args) => store.revertToSnapshot(...args);++export const duplicateGuide: GuideStore['duplicateGuide'] = (...args) => store.duplicateGuide(...args);++export const importGuide: GuideStore['importGuide'] = (...args) => store.importGuide(...args);++export const saveTranscript: GuideStore['saveTranscript'] = (...args) => store.saveTranscript(...args);++export const getTranscripts: GuideStore['getTranscripts'] = (...args) => store.getTranscripts(...args);++export const hasTranscript: GuideStore['hasTranscript'] = (...args) => store.hasTranscript(...args);++export const deleteTranscripts: GuideStore['deleteTranscripts'] = (...args) => store.deleteTranscripts(...args);++export const addTranscriptLineToStep: GuideStore['addTranscriptLineToStep'] = (...args) =>++ store.addTranscriptLineToStep(...args);++export const restoreNarratedDescription: GuideStore['restoreNarratedDescription'] = (...args) =>++ store.restoreNarratedDescription(...args);diff --cc packages/core/src/guides/title.tsindex 0000000,e1b1a8d..e1b1a8dmode 000000,100644..100644--- a/packages/core/src/guides/title.ts+++ b/packages/core/src/guides/title.tsdiff --cc packages/core/src/guides/transcript.tsindex 0000000,20fce1f..20fce1fmode 000000,100644..100644--- a/packages/core/src/guides/transcript.ts+++ b/packages/core/src/guides/transcript.tsdiff --cc packages/core/src/guides/types.tsindex 97c5901,f7eccaf..9237c74--- a/packages/core/src/guides/types.ts+++ b/packages/core/src/guides/types.ts@@@ -89,9 -92,7 +97,8 @@@ export interface SettingsguideMeStep: Step | null;guideMeBlocked: number | null;guideMeManual: boolean;- mimikBlurMode: boolean;onboardingCompleted: boolean;+ appLanguage: string;}export type SettingsKey = keyof Settings;@@@ -114,21 -109,31 +121,41 @@@ export interface ElementMetarect: { x: number; y: number; width: number; height: number };devicePixelRatio: number;clickPoint?: { x: number; y: number };+ tag?: string;+ cssSelector?: string;+ href?: string | null;+ inputType?: string | null;+ dataTestId?: string | null;+ app?: { name: string; id?: string };+ window?: { title: string | null };+ ancestors?: ElementNode[];+ children?: ElementNode[];+}++export function elementSource(meta: ElementMeta): ElementSource {+ return meta.source ?? 'dom';}+ export interface GuideTranscript {+ id: string;+ guideId: string;+ epochMs: number;+ createdAt: number;+ lines: TranscriptLine[];+ }++ export interface GuideMerge {+ id: string;+ targetGuideId: string;+ mergedAt: number;+ }++ export interface VoiceClip {+ id: string;+ bytes: ArrayBuffer;+ createdAt: number;+ }+export interface Snapshot {id: string;guideId: string;diff --cc packages/core/src/transfer/__tests__/bundle.test.tsindex 0000000,1dc543b..1dc543bmode 000000,100644..100644--- a/packages/core/src/transfer/__tests__/bundle.test.ts+++ b/packages/core/src/transfer/__tests__/bundle.test.tsdiff --cc packages/core/src/transfer/__tests__/flatten.test.tsindex 0000000,ed1040b..ed1040bmode 000000,100644..100644--- a/packages/core/src/transfer/__tests__/flatten.test.ts+++ b/packages/core/src/transfer/__tests__/flatten.test.tsdiff --cc packages/core/src/transfer/__tests__/parse.test.tsindex 0000000,1de967c..1de967cmode 000000,100644..100644--- a/packages/core/src/transfer/__tests__/parse.test.ts+++ b/packages/core/src/transfer/__tests__/parse.test.tsdiff --cc packages/core/src/transfer/__tests__/round-trip.test.tsindex 0000000,9c1a5f0..9c1a5f0mode 000000,100644..100644--- a/packages/core/src/transfer/__tests__/round-trip.test.ts+++ b/packages/core/src/transfer/__tests__/round-trip.test.tsdiff --cc packages/core/src/transfer/__tests__/scrub.test.tsindex 0000000,4cc68e1..4cc68e1mode 000000,100644..100644--- a/packages/core/src/transfer/__tests__/scrub.test.ts+++ b/packages/core/src/transfer/__tests__/scrub.test.tsdiff --cc packages/core/src/transfer/bundle.tsindex 0000000,018a1a8..018a1a8mode 000000,100644..100644--- a/packages/core/src/transfer/bundle.ts+++ b/packages/core/src/transfer/bundle.tsdiff --cc packages/core/src/transfer/flatten.tsindex 0000000,f0594a1..f0594a1mode 000000,100644..100644--- a/packages/core/src/transfer/flatten.ts+++ b/packages/core/src/transfer/flatten.tsdiff --cc packages/core/src/transfer/parse.tsindex 0000000,554e382..554e382mode 000000,100644..100644--- a/packages/core/src/transfer/parse.ts+++ b/packages/core/src/transfer/parse.tsdiff --cc packages/core/src/transfer/schema.tsindex 0000000,b8eca8f..30749fcmode 000000,100644..100644--- a/packages/core/src/transfer/schema.ts+++ b/packages/core/src/transfer/schema.ts@@@ -1,0 -1,318 +1,318 @@@-import { i18n } from '#imports';++import { i18n } from '@/core/env';+ import type {+ BlockType,+ CalloutVariant,+ DescriptionSource,+ ElementMeta,+ ScreenshotBounds,+ Step,+ } from '@/core/guides/types';+ import type { Annotation, ScreenshotEdits } from '@/core/screenshot/types';++ export const BUNDLE_VERSION = 1;++ export const BUNDLE_EXTENSION = 'mimik';+ export const BUNDLE_MIME = 'application/zip';+ export const MANIFEST_PATH = 'manifest.json';+ export const SCREENSHOT_DIR = 'screenshots';+ export const README_PATH = 'README.md';++ export type BundleStep = Omit<Step, 'guideId' | 'aiPending' | 'screenshotId'>;++ export interface BundleScreenshot {+ id: string;+ stepId: string;+ file: string;+ mimeType: string;+ width: number;+ height: number;+ bounds?: ScreenshotBounds;+ pixelRatio?: number;+ clickPoint?: { x: number; y: number };+ edits?: ScreenshotEdits;+ }++ export interface BundleManifest {+ version: number;+ exportedAt: number;+ guide: {+ title: string;+ description?: string;+ createdAt: number;+ };+ sourceDomain: string | null;+ redacted: {+ screenshots: boolean;+ inputValues: boolean;+ urls: 'full' | 'path' | 'origin';+ };+ steps: BundleStep[];+ screenshots: BundleScreenshot[];+ }++ export type BundleErrorKind = 'unreadable' | 'not-a-bundle' | 'unsupported-version' | 'empty';++ export class BundleError extends Error {+ readonly kind: BundleErrorKind;++ constructor(kind: BundleErrorKind, message: string) {+ super(message);+ this.name = 'BundleError';+ this.kind = kind;+ }+ }++ const isObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++ const str = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined);+ const num = (value: unknown): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;++ const MAX_DIMENSION = 32_768;+ const MAX_POINTS = 20_000;++ const bounded = (value: unknown): number | undefined => {+ const n = num(value);+ if (n === undefined) return undefined;+ return Math.max(-MAX_DIMENSION, Math.min(MAX_DIMENSION, n));+ };++ const positive = (value: unknown): number | undefined => {+ const n = num(value);+ if (n === undefined || n <= 0) return undefined;+ return Math.min(n, MAX_DIMENSION);+ };++ const SAFE_SCHEMES = ['http:', 'https:'];++ export function safeUrl(value: unknown): string {+ const raw = str(value)?.trim();+ if (!raw) return '';+ try {+ return SAFE_SCHEMES.includes(new URL(raw).protocol) ? raw : '';+ } catch {+ return '';+ }+ }++ const SAFE_IMAGE_TYPES = ['image/webp', 'image/png', 'image/jpeg', 'image/gif'];++ function bounds(value: unknown): ScreenshotBounds | undefined {+ if (!isObject(value)) return undefined;+ const x = bounded(value.x);+ const y = bounded(value.y);+ const width = bounded(value.width);+ const height = bounded(value.height);+ if (x === undefined || y === undefined || width === undefined || height === undefined) return undefined;+ return { x, y, width, height };+ }++ function point(value: unknown): { x: number; y: number } | undefined {+ if (!isObject(value)) return undefined;+ const x = bounded(value.x);+ const y = bounded(value.y);+ return x === undefined || y === undefined ? undefined : { x, y };+ }++ const DESCRIPTION_SOURCES: DescriptionSource[] = ['narration', 'ai', 'heuristic', 'manual'];+ const BLOCK_TYPES: BlockType[] = ['heading', 'callout'];+ const CALLOUT_VARIANTS: CalloutVariant[] = ['info', 'warning', 'error', 'success', 'custom'];++ const oneOf = <T extends string>(value: unknown, allowed: T[]): T | undefined =>+ typeof value === 'string' && (allowed as string[]).includes(value) ? (value as T) : undefined;++ function annotations(value: unknown): Annotation[] | undefined {+ if (!Array.isArray(value)) return undefined;+ const kept = value.filter((a): a is Annotation => {+ if (!isObject(a) || typeof a.id !== 'string' || typeof a.type !== 'string') return false;+ switch (a.type) {+ case 'redact':+ return [a.x, a.y, a.w, a.h].every((n) => bounded(n) !== undefined);+ case 'box':+ case 'ellipse':+ case 'target':+ return [a.x, a.y, a.w, a.h].every((n) => bounded(n) !== undefined) && typeof a.color === 'string';+ case 'arrow':+ return [a.x1, a.y1, a.x2, a.y2].every((n) => bounded(n) !== undefined) && typeof a.color === 'string';+ case 'text':+ return (+ bounded(a.x) !== undefined &&+ bounded(a.y) !== undefined &&+ typeof a.text === 'string' &&+ typeof a.color === 'string' &&+ positive(a.size) !== undefined+ );+ case 'freehand':+ return (+ Array.isArray(a.points) &&+ a.points.length >= 2 &&+ a.points.length % 2 === 0 &&+ a.points.length <= MAX_POINTS &&+ a.points.every((n) => bounded(n) !== undefined) &&+ typeof a.color === 'string'+ );+ default:+ return false;+ }+ });+ return kept.length > 0 ? kept : undefined;+ }++ function edits(value: unknown): ScreenshotEdits | undefined {+ if (!isObject(value)) return undefined;+ const result: ScreenshotEdits = {};+ const viewport = bounds(value.viewport);+ if (viewport) result.viewport = viewport;+ if (value.target === null) result.target = null;+ else {+ const rect = bounds(value.target);+ if (rect && isObject(value.target)) {+ result.target = {+ ...rect,+ color: str((value.target as Record<string, unknown>).color) ?? '#4F46E5',+ border: oneOf((value.target as Record<string, unknown>).border, ['dashed', 'solid'] as const) ?? 'dashed',+ };+ }+ }+ const list = annotations(value.annotations);+ if (list) result.annotations = list;+ const alt = str(value.alt);+ if (alt) result.alt = alt;+ return Object.keys(result).length > 0 ? result : undefined;+ }++ function parseStep(value: unknown, index: number, stripInputValues: boolean): BundleStep | null {+ if (!isObject(value)) return null;+ const id = str(value.id);+ if (!id) return null;++ const step: BundleStep = {+ id,+ index: num(value.index) ?? index,+ description: str(value.description) ?? '',+ action: str(value.action) ?? 'click',+ url: safeUrl(value.url),+ timestamp: num(value.timestamp) ?? 0,+ };++ const source = oneOf(value.descriptionSource, DESCRIPTION_SOURCES);+ if (source) step.descriptionSource = source;+ const blockType = oneOf(value.blockType, BLOCK_TYPES);+ if (blockType) step.blockType = blockType;+ const variant = oneOf(value.calloutVariant, CALLOUT_VARIANTS);+ if (variant) step.calloutVariant = variant;+ const color = str(value.calloutColor);+ if (color) step.calloutColor = color;+ const inputValue = str(value.inputValue);+ if (inputValue !== undefined && !stripInputValues) step.inputValue = inputValue;+ const meta = parseElementMeta(value.elementMeta);+ if (meta) step.elementMeta = meta;++ return step;+ }++ function parseElementMeta(value: unknown): ElementMeta | null {+ if (!isObject(value)) return null;+ const tag = str(value.tag);+ const cssSelector = str(value.cssSelector);+ if (!tag || !cssSelector) return null;++ const nullableStr = (v: unknown): string | null => str(v) ?? null;++ return {+ tag,+ cssSelector,+ textContent: nullableStr(value.textContent),+ ariaLabel: nullableStr(value.ariaLabel),+ placeholder: nullableStr(value.placeholder),+ altText: nullableStr(value.altText),+ name: nullableStr(value.name),+ role: nullableStr(value.role),+ href: safeUrl(value.href) || null,+ inputType: nullableStr(value.inputType),+ dataTestId: nullableStr(value.dataTestId),+ rect: bounds(value.rect) ?? { x: 0, y: 0, width: 0, height: 0 },+ devicePixelRatio: positive(value.devicePixelRatio) ?? 1,+ ...(point(value.clickPoint) ? { clickPoint: point(value.clickPoint) } : {}),+ };+ }++ function safeEntryPath(file: string): boolean {+ return file.startsWith(`${SCREENSHOT_DIR}/`) && !file.includes('..') && !file.includes('\\');+ }++ function parseScreenshot(value: unknown): BundleScreenshot | null {+ if (!isObject(value)) return null;+ const id = str(value.id);+ const stepId = str(value.stepId);+ const file = str(value.file);+ const width = positive(value.width);+ const height = positive(value.height);+ if (!id || !stepId || !file || !safeEntryPath(file) || width === undefined || height === undefined) return null;++ const declaredType = str(value.mimeType);+ const shot: BundleScreenshot = {+ id,+ stepId,+ file,+ mimeType: declaredType && SAFE_IMAGE_TYPES.includes(declaredType) ? declaredType : 'image/webp',+ width,+ height,+ };++ const rect = bounds(value.bounds);+ if (rect) shot.bounds = rect;+ const ratio = positive(value.pixelRatio);+ if (ratio !== undefined) shot.pixelRatio = Math.min(ratio, 8);+ const click = point(value.clickPoint);+ if (click) shot.clickPoint = click;+ const editState = edits(value.edits);+ if (editState) shot.edits = editState;++ return shot;+ }++ export function parseManifest(raw: unknown): BundleManifest {+ if (!isObject(raw)) throw new BundleError('not-a-bundle', 'manifest is not an object');++ const version = num(raw.version);+ if (version === undefined) throw new BundleError('not-a-bundle', 'manifest has no version');+ if (version > BUNDLE_VERSION) {+ throw new BundleError('unsupported-version', `manifest version ${version} is newer than ${BUNDLE_VERSION}`);+ }++ const guide = isObject(raw.guide) ? raw.guide : null;+ if (!guide) throw new BundleError('not-a-bundle', 'manifest has no guide');++ const redacted = isObject(raw.redacted) ? raw.redacted : {};+ const stripInputValues = redacted.inputValues === true;++ const steps = (Array.isArray(raw.steps) ? raw.steps : [])+ .map((value, i) => parseStep(value, i, stripInputValues))+ .filter((step): step is BundleStep => step !== null);+ if (steps.length === 0) throw new BundleError('empty', 'manifest has no usable steps');++ const stepIds = new Set(steps.map((s) => s.id));+ const screenshots = (Array.isArray(raw.screenshots) ? raw.screenshots : [])+ .map(parseScreenshot)+ .filter((shot): shot is BundleScreenshot => shot !== null && stepIds.has(shot.stepId));++ return {+ version,+ exportedAt: num(raw.exportedAt) ?? Date.now(),+ guide: {+ title: str(guide.title)?.trim() || i18n.t('fullview.untitledGuide'),+ ...(str(guide.description) ? { description: str(guide.description) } : {}),+ createdAt: num(guide.createdAt) ?? Date.now(),+ },+ sourceDomain: str(raw.sourceDomain) ?? null,+ redacted: {+ screenshots: redacted.screenshots === true,+ inputValues: stripInputValues,+ urls: oneOf(redacted.urls, ['full', 'path', 'origin'] as const) ?? 'full',+ },+ steps: steps.sort((a, b) => a.index - b.index),+ screenshots,+ };+ }diff --cc packages/core/src/transfer/scrub.tsindex 0000000,410c798..410c798mode 000000,100644..100644--- a/packages/core/src/transfer/scrub.ts+++ b/packages/core/src/transfer/scrub.tsdiff --cc packages/ui/src/ai/components/SecretInput.tsxindex 9908f9c,0000000..f42056amode 100644,000000..100644--- a/packages/ui/src/ai/components/SecretInput.tsx+++ b/packages/ui/src/ai/components/SecretInput.tsx@@@ -1,42 -1,0 +1,54 @@@+import { i18n } from '@mimik/core/env';- import { Eye, EyeOff } from 'lucide-react';++import { Eye, EyeOff, X } from 'lucide-react';+import { useState } from 'react';+import { Input } from '../../components/ui/input';++export function SecretInput({+ value,+ onChange,+ placeholder,+ className,+ buttonClassName,+}: {+ value: string;+ onChange: (next: string) => void;+ placeholder?: string;+ className?: string;+ buttonClassName?: string;+}) {+ const [revealed, setRevealed] = useState(false);+ const Icon = revealed ? EyeOff : Eye;++ const iconButton = `top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors ${buttonClassName ?? ''}`;+ return (+ <div className="relative flex-1 min-w-0">+ <Input+ type={revealed ? 'text' : 'password'}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}- className={`pr-8 ${className ?? ''}`}++ className={`${value ? 'pr-14' : 'pr-8'} ${className ?? ''}`}+ />++ {value && (++ <button++ type="button"++ onClick={() => onChange('')}++ aria-label={i18n.t('settings.clearKey')}++ title={i18n.t('settings.clearKey')}++ className={`absolute right-8 ${iconButton}`}++ >++ <X size={13} />++ </button>++ )}+ <button+ type="button"+ onClick={() => setRevealed((on) => !on)}+ aria-pressed={revealed}+ aria-label={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}+ title={i18n.t(revealed ? 'settings.hideKey' : 'settings.showKey')}- className={`absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors ${buttonClassName ?? ''}`}++ className={`absolute right-2 ${iconButton}`}+ >+ <Icon size={13} />+ </button>+ </div>+ );+}diff --cc packages/ui/src/export/components/ExportPreviewModal.tsxindex a43e4c0,52376e9..f28c310--- a/packages/ui/src/export/components/ExportPreviewModal.tsx+++ b/packages/ui/src/export/components/ExportPreviewModal.tsx@@@ -1,5 -1,10 +1,6 @@@-import { FileCode, FileDown, FileImage, FileText, Loader2, Package, TriangleAlert, Video, Volume2 } from 'lucide-react';-import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';-import { i18n } from '#imports';-import { downloadBlob, downloadText, safeFilename } from '@/core/export/download';-import { exportGuideAsHTML } from '@/core/export/html-export';+import { i18n } from '@mimik/core/env';import {+ BUNDLE_URL_MODES,DEFAULT_EXPORT_OPTIONS,type ExportOptions,GIF_QUALITIES,@@@ -7,23 -12,38 +8,31 @@@loadExportOptions,saveExportOptions,VIDEO_RESOLUTIONS,-} from '@/core/export/options';-import { exportGuideAsPDF } from '@/core/export/pdf-export';-import { paginatePreview, withPreviewStyles } from '@/core/export/preview';-import type { VideoChapter, VoiceoverSkip } from '@/core/export/video-export';-import { COVER_SECONDS, canExportVideo, STEP_SECONDS } from '@/core/export/video-support';-import { hasVoiceoverKey, VOICEOVER_SETTINGS } from '@/core/export/voiceover/config';-import type { Guide, Screenshot, Step } from '@/core/guides/types';-import { BUNDLE_EXTENSION } from '@/core/transfer/schema';-import { localStorage } from '@/lib/browser-api';-import { Button } from '@/ui/components/ui/button';-import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog';-import {- encodeProgress,- MUX_PROGRESS_SHARE,- muxProgress,- narrateProgress,- VOICE_PROGRESS_SHARE,-} from '@/ui/fullview/export-progress';--const VideoStepPlayer = lazy(() => import('@/ui/fullview/VideoStepPlayer'));+} from '@mimik/core/export/options';+import { paginatePreview } from '@mimik/core/export/preview';++import type { VoiceoverSkip } from '@mimik/core/export/video-export';+import { STEP_SECONDS } from '@mimik/core/export/video-support';+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';- import { FileCode, FileDown, FileImage, FileText, Loader2, Video } from 'lucide-react';++import { FileCode, FileDown, FileImage, FileText, Loader2, Package, TriangleAlert, Video, Volume2 } from 'lucide-react';+import { lazy, Suspense, useEffect, useState } from 'react';+import { Switch } from '../../common/components/Switch';+import { Button } from '../../components/ui/button';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../../components/ui/dialog';+import { type ExportFormat, useGuideExport } from '../hooks/use-guide-export';+import { useVideoPreview } from '../hooks/use-video-preview';++import { useVoiceoverReady } from '../hooks/use-voiceover-ready';-const VIDEO_AUTOPLAY_STEP_LIMIT = 25;+const VideoStepPlayer = lazy(() => import('./VideoStepPlayer').then((m) => ({ default: m.VideoStepPlayer })));- const _VIDEO_AUTOPLAY_STEP_LIMIT = 25;const IMAGE_SCALES: ImageScale[] = ['small', 'medium', 'large'];+ const VOICEOVER_SKIP_MESSAGES = {+ failed: 'exportPreview.voiceoverFailed',+ noAudioCodec: 'exportPreview.voiceoverNoAudioCodec',+ noKey: 'exportPreview.voiceoverNoKeySkip',+ nothingToSay: 'exportPreview.voiceoverNothingToSay',+ } as const satisfies Record<VoiceoverSkip['reason'], string>;+interface ExportPreviewModalProps {open: boolean;onOpenChange: (open: boolean) => void;@@@ -42,8 -79,139 +51,12 @@@ export function ExportPreviewModal({ opif (open) loadExportOptions().then(setOptions);}, [open]);- const doc = useGuideExport({ active: open && mode === 'document', guide, steps, screenshots, options });- const video = useVideoPreview({ active: open && mode === 'video', guide, steps, screenshots, options });- useEffect(() => {- if (!open) return;- let active = true;- localStorage.get([...VOICEOVER_SETTINGS]).then((stored) => {- if (active) setVoiceoverReady(hasVoiceoverKey(stored));- });- return () => {- active = false;- };- }, [open]);-- useEffect(() => {- let active = true;- canExportVideo().then((supported) => {- if (active) setVideoSupported(supported);- });- return () => {- active = false;- };- }, []);-- const videoPending = steps.length > VIDEO_AUTOPLAY_STEP_LIMIT && !videoRequested;- const typedStepCount = steps.filter((step) => step.inputValue && screenshots.has(step.id)).length;- const { cover, stepDescriptions, resolution, screenshots: withScreenshots, stepUrls, imageScale } = options;++ const voiceoverReady = useVoiceoverReady(open);+ const voiceover = options.voiceover && voiceoverReady;- const voiceShare = voiceover ? VOICE_PROGRESS_SHARE : 0;- const muxShare = voiceover ? MUX_PROGRESS_SHARE : 0;-- const previewOptions = useMemo<ExportOptions>(- () => ({ ...DEFAULT_EXPORT_OPTIONS, cover, screenshots: withScreenshots, stepUrls, imageScale, stepDescriptions }),- [cover, withScreenshots, stepUrls, imageScale, stepDescriptions],- );-- useEffect(() => {- if (!open) setVideoRequested(false);- }, [open]);-- useEffect(() => {- if (!open || mode !== 'document') return;- let cancelled = false;- setRendering(true);- const timer = setTimeout(async () => {- const html = await exportGuideAsHTML(guide, steps, screenshots, previewOptions);- if (cancelled) return;- setPreview(withPreviewStyles(html));- setRendering(false);- }, 200);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [open, mode, guide, steps, screenshots, previewOptions]);-- useEffect(() => {- if (!open || mode !== 'video' || videoPending) return;- const controller = new AbortController();- let url: string | null = null;- setVideoError(null);- setVideoProgress(0);- setVoiceProgress(null);- setNarratedSeconds(null);- setVoiceoverError(null);- const timer = setTimeout(async () => {- let allClipsLanded = false;- try {- const { exportGuideAsVideo } = await import('@/core/export/video-export');- const {- blob,- chapters,- extension,- voiceoverError: failed,- } = await exportGuideAsVideo(- guide,- steps,- screenshots,- { cover, stepDescriptions, resolution, voiceover },- {- signal: controller.signal,- onProgress: (encoded, frames) => {- if (controller.signal.aborted) return;- setVoiceProgress(null);- setVideoProgress(- encodeProgress(encoded, frames, allClipsLanded ? voiceShare : 0, allClipsLanded ? muxShare : 0),- );- },- onVoiceProgress: (done, total) => {- if (controller.signal.aborted) return;- allClipsLanded = done === total;- setVoiceProgress(done < total ? { done, total } : null);- setVideoProgress(narrateProgress(done, total, voiceShare));- },- onMuxProgress: (done, total) => {- if (controller.signal.aborted) return;- setVideoProgress(muxProgress(done, total, muxShare));- },- },- );- if (controller.signal.aborted) return;- url = URL.createObjectURL(blob);- setVideoType(extension === 'webm' ? 'video/webm' : 'video/mp4');- setVideoChapters(chapters);- setVoiceoverError(failed ?? null);- setNarratedSeconds(- voiceover && !failed && chapters.length > 0- ? chapters[chapters.length - 1].end + (cover ? COVER_SECONDS : 0)- : null,- );- setVideoUrl(url);- } catch (error) {- if (controller.signal.aborted || (error instanceof DOMException && error.name === 'AbortError')) return;- setVideoError(error instanceof Error ? error.message : String(error));- }- }, 200);- return () => {- controller.abort();- clearTimeout(timer);- if (url) URL.revokeObjectURL(url);- setVideoUrl(null);- };- }, [- open,- mode,- guide,- steps,- screenshots,- cover,- stepDescriptions,- resolution,- voiceover,- voiceShare,- muxShare,- videoPending,- ]);++ const doc = useGuideExport({ active: open && mode === 'document', guide, steps, screenshots, options, voiceover });++ const video = useVideoPreview({ active: open && mode === 'video', guide, steps, screenshots, options, voiceover });++ const voiceoverError = video.voiceoverError ?? doc.voiceoverError;++ const typedStepCount = steps.filter((step) => step.inputValue && screenshots.has(step.id)).length;const update = (patch: Partial<ExportOptions>) => {const next = { ...options, ...patch };@@@ -73,7 -312,8 +86,8 @@@{ key: 'html', icon: FileCode, label: i18n.t('exportMenu.html') },{ key: 'markdown', icon: FileText, label: i18n.t('exportMenu.markdown') },{ key: 'gif', icon: FileImage, label: i18n.t('exportMenu.gif') },- ...(videoSupported ? [{ key: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),+ ...(video.supported ? [{ key: 'video' as const, icon: Video, label: i18n.t('exportMenu.video') }] : []),+ { key: 'bundle', icon: Package, label: i18n.t('exportMenu.bundle') },];return (@@@ -148,6 -396,55 +162,55 @@@</div>)}- {videoSupported && (++ {video.supported && (+ <div className="pt-3 border-t border-border">+ <div className="text-[12px] font-semibold text-foreground mb-2">{i18n.t('exportPreview.audio')}</div>+ <div className="flex gap-1.5">+ <button+ type="button"+ aria-pressed={!voiceover}+ onClick={() => update({ voiceover: false })}+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-2 rounded-lg border text-[11px] leading-none transition-colors ${+ voiceover+ ? 'border-border text-muted-foreground hover:border-accent hover:text-foreground'+ : 'border-accent text-accent'+ }`}+ >+ <span className="leading-none">{i18n.t('exportPreview.audioSilent')}</span>+ </button>+ <button+ type="button"+ aria-pressed={voiceover}+ disabled={!voiceoverReady}+ onClick={() => update({ voiceover: true })}+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-2 rounded-lg border text-[11px] leading-none transition-colors disabled:opacity-45 disabled:cursor-not-allowed disabled:hover:border-border disabled:hover:text-muted-foreground ${+ voiceover+ ? 'border-accent text-accent'+ : 'border-border text-muted-foreground hover:border-accent hover:text-foreground'+ }`}+ >+ <span className="leading-none">{i18n.t('exportPreview.audioNarrated')}</span>+ <Volume2 size={11} className="shrink-0 block" />+ </button>+ </div>++ {!voiceoverReady && (+ <div className="mt-1.5 px-0.5 text-[10px] text-muted-foreground leading-snug">+ {i18n.t('exportPreview.voiceoverNoKey')}+ </div>+ )}++ {voiceover && voiceoverError && (+ <div+ className="mt-1.5 rounded-lg px-2.5 py-2 text-[10px] leading-snug text-destructive bg-destructive/10"+ role="alert"+ >+ {i18n.t(VOICEOVER_SKIP_MESSAGES[voiceoverError.reason])}+ </div>+ )}+ </div>+ )}+<div className="pt-3 border-t border-border"><div className="text-[12px] font-semibold text-foreground mb-2">{i18n.t('exportPreview.gifQuality')}</div><div className="flex gap-1.5">@@@ -168,9 -465,79 +231,71 @@@</div></div>+ <div className="pt-3 border-t border-border">+ <div className="text-[12px] font-semibold text-foreground">{i18n.t('exportPreview.bundle')}</div>+ <div className="text-[10px] text-muted-foreground leading-snug mt-0.5">+ {i18n.t('exportPreview.bundleHint')}+ </div>++ <div className="flex items-start justify-between gap-3 mt-3">+ <div>+ <div className="text-[12px] font-semibold text-foreground">+ {i18n.t('exportPreview.bundleStripInputs')}+ </div>+ <div className="text-[10px] text-muted-foreground leading-snug">+ {i18n.t('exportPreview.bundleStripInputsHint')}+ </div>+ </div>- <button- type="button"- aria-label={i18n.t('exportPreview.bundleStripInputs')}- aria-pressed={options.bundleStripInputs}- onClick={() => update({ bundleStripInputs: !options.bundleStripInputs })}- className={`w-9 h-5 rounded-full transition-colors relative shrink-0 mt-0.5 ${- options.bundleStripInputs ? 'bg-accent' : 'bg-border'- }`}- >- <span- className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${- options.bundleStripInputs ? 'translate-x-4' : 'translate-x-0'- }`}++ <div className="mt-0.5 flex shrink-0">++ <Switch++ checked={options.bundleStripInputs}++ label={i18n.t('exportPreview.bundleStripInputs')}++ onChange={(next) => update({ bundleStripInputs: next })}+ />- </button>++ </div>+ </div>++ <div className="mt-3">+ <div className="text-[12px] font-semibold text-foreground mb-2">+ {i18n.t('exportPreview.bundleUrls')}+ </div>+ <div className="flex gap-1.5">+ {BUNDLE_URL_MODES.map((value) => (+ <button+ key={value}+ type="button"+ onClick={() => update({ bundleUrls: value })}+ className={`flex-1 px-2 py-1.5 rounded-lg border text-[11px] transition-colors ${+ options.bundleUrls === value+ ? 'border-accent text-accent'+ : 'border-border text-muted-foreground hover:border-accent hover:text-foreground'+ }`}+ >+ {i18n.t(`exportPreview.url_${value}`)}+ </button>+ ))}+ </div>+ </div>++ <p className="text-[10px] text-muted-foreground leading-snug mt-3">+ {i18n.t('exportPreview.bundleRedactionNote')}+ </p>++ {typedStepCount > 0 && (+ <p className="flex items-start gap-1.5 text-[10px] leading-snug mt-2 text-foreground">+ <TriangleAlert size={12} className="shrink-0 mt-px text-accent" />+ <span>+ {typedStepCount === 1+ ? i18n.t('exportPreview.bundleTypedWarning', [String(typedStepCount)])+ : i18n.t('exportPreview.bundleTypedWarningPlural', [String(typedStepCount)])}+ </span>+ </p>+ )}+ </div>+<div className="pt-3 border-t border-border space-y-1.5">{formats.map(({ key, icon: Icon, label }) => {- const cancellable = exporting === key && (key === 'video' || key === 'gif');+ const cancellable = doc.running === key && (key === 'video' || key === 'gif');return (<Buttonkey={key}@@@ -254,15 -621,28 +379,28 @@@<div className="text-[12px] font-semibold text-foreground">{i18n.t('exportPreview.videoFailed')}</div>- <div className="mt-1 text-[11px] text-muted-foreground leading-snug">{videoError}</div>+ <div className="mt-1 text-[11px] text-muted-foreground leading-snug">{video.error}</div></div>- ) : videoUrl ? (+ ) : video.url ? (<Suspense fallback={null}>- <VideoStepPlayer key={video.url} src={video.url} type={video.mime} chapters={video.chapters} />+ <VideoStepPlayer- key={videoUrl}- src={videoUrl}- type={videoType}- chapters={videoChapters}- narrated={voiceover && !voiceoverError}++ key={video.url}++ src={video.url}++ type={video.mime}++ chapters={video.chapters}++ narrated={voiceover && !video.voiceoverError}+ /></Suspense>) : (<div className="flex flex-col items-center gap-2 bg-card border border-border rounded-xl px-4 py-3">- <div className="text-[11px] text-muted-foreground">{i18n.t('exportPreview.encodingVideo')}</div>+ <div className="text-[11px] text-muted-foreground">- {voiceProgress++ {video.narrating+ ? i18n.t('exportPreview.narrating', [- String(voiceProgress.done + 1),- String(voiceProgress.total),++ String(video.narrating.done + 1),++ String(video.narrating.total),+ ])+ : i18n.t('exportPreview.encodingVideo')}+ </div><div className="h-1.5 w-40 overflow-hidden rounded-full bg-border"><divclassName="h-full rounded-full bg-accent transition-[width] duration-150"diff --cc packages/ui/src/export/components/PlayerBody.tsxindex 944ecd7,0000000..6973bb3mode 100644,000000..100644--- a/packages/ui/src/export/components/PlayerBody.tsx+++ b/packages/ui/src/export/components/PlayerBody.tsx@@@ -1,76 -1,0 +1,93 @@@+import { i18n } from '@mimik/core/env';+import type { VideoChapter } from '@mimik/core/export/video-export';- import { FullscreenButton, MediaProvider, PlayButton, useMediaRemote, useMediaState } from '@vidstack/react';- import { ChevronLeft, ChevronRight, Maximize, Minimize, Pause, Play } from 'lucide-react';++import {++ FullscreenButton,++ MediaProvider,++ MuteButton,++ PlayButton,++ useMediaRemote,++ useMediaState,++} from '@vidstack/react';++import { ChevronLeft, ChevronRight, Maximize, Minimize, Pause, Play, Volume2, VolumeX } from 'lucide-react';+import { activeIndex } from '../lib/active-index';+import { formatClock } from '../lib/format-clock';+import { StepList } from './StepList';++const RATES = [1, 1.25, 1.5, 2];+- export function PlayerBody({ chapters }: { chapters: VideoChapter[] }) {++export function PlayerBody({ chapters, narrated }: { chapters: VideoChapter[]; narrated: boolean }) {+ const remote = useMediaRemote();+ const time = useMediaState('currentTime');+ const duration = useMediaState('duration');+ const rate = useMediaState('playbackRate');+ const paused = useMediaState('paused');+ const fullscreen = useMediaState('fullscreen');++ const muted = useMediaState('muted');++ const index = activeIndex(chapters, time);+ const seekTo = (seconds: number) => remote.seek(Math.max(0, seconds + 0.01));+ const jump = (i: number) => chapters[i] && seekTo(chapters[i].start);++ return (+ <>+ <div className="relative min-w-0 flex-1">+ <MediaProvider className="size-full [&_video]:size-full [&_video]:object-contain" />++ <div className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/85 to-transparent px-3 pb-2.5 pt-8 text-white">+ <PlayButton className="rounded-md p-1 hover:bg-white/15">+ {paused ? <Play size={16} fill="currentColor" /> : <Pause size={16} fill="currentColor" />}+ </PlayButton>++ <button+ type="button"+ disabled={index <= 0}+ onClick={() => jump(index - 1)}+ aria-label={i18n.t('videoPlayer.previousStep')}+ className="rounded-md p-1 hover:bg-white/15 disabled:opacity-35 disabled:hover:bg-transparent"+ >+ <ChevronLeft size={16} />+ </button>+ <button+ type="button"+ disabled={index < 0 || index >= chapters.length - 1}+ onClick={() => jump(index + 1)}+ aria-label={i18n.t('videoPlayer.nextStep')}+ className="rounded-md p-1 hover:bg-white/15 disabled:opacity-35 disabled:hover:bg-transparent"+ >+ <ChevronRight size={16} />+ </button>++ <span className="font-mono text-[11px] tabular-nums text-white/75">+ {formatClock(time)} / {formatClock(duration)}+ </span>++ <span className="flex-1" />++ <button+ type="button"+ onClick={() => remote.changePlaybackRate(RATES[(RATES.indexOf(rate) + 1) % RATES.length])}+ aria-label={i18n.t('videoPlayer.speed')}+ className="rounded-md px-1.5 py-1 font-mono text-[11px] tabular-nums hover:bg-white/15"+ >+ {rate}x+ </button>+++ <MuteButton++ className="rounded-md p-1 hover:bg-white/15"++ aria-label={muted ? i18n.t('videoPlayer.unmute') : i18n.t('videoPlayer.mute')}++ >++ {muted ? <VolumeX size={16} /> : <Volume2 size={16} />}++ </MuteButton>+++ <FullscreenButton className="rounded-md p-1 hover:bg-white/15">+ {fullscreen ? <Minimize size={16} /> : <Maximize size={16} />}+ </FullscreenButton>+ </div>+ </div>+- {chapters.length > 0 && <StepList chapters={chapters} index={index} onJump={jump} />}++ {chapters.length > 0 && (++ <StepList chapters={chapters} index={index} narrated={narrated} playing={!paused} onJump={jump} />++ )}+ </>+ );+}diff --cc packages/ui/src/export/components/SpokenMark.tsxindex 0000000,0000000..ccc0b52new file mode 100644--- /dev/null+++ b/packages/ui/src/export/components/SpokenMark.tsx@@@ -1,0 -1,0 +1,17 @@@++import { i18n } from '@mimik/core/env';++++const WAVE_BARS = [3, 7, 4, 8, 5];++++export function SpokenMark({ talking }: { talking: boolean }) {++ return (++ <span role="img" aria-label={i18n.t('videoPlayer.spoken')} className="mt-1 flex shrink-0 items-center gap-[2px]">++ {WAVE_BARS.map((height, i) => (++ <span++ key={height}++ className={`w-[2px] rounded-[1px] ${talking ? 'animate-talk bg-lavender' : 'bg-lavender/70'}`}++ style={{ height: `${height}px`, animationDelay: talking ? `${i * 90}ms` : undefined }}++ />++ ))}++ </span>++ );++}diff --cc packages/ui/src/export/components/StepList.tsxindex 88f5cbd,0000000..858d5afmode 100644,000000..100644--- a/packages/ui/src/export/components/StepList.tsx+++ b/packages/ui/src/export/components/StepList.tsx@@@ -1,48 -1,0 +1,54 @@@+import { i18n } from '@mimik/core/env';+import type { StepKind, VideoChapter } from '@mimik/core/export/video-export';+import { useEffect, useRef } from 'react';+import { formatClock } from '../lib/format-clock';++import { SpokenMark } from './SpokenMark';++const KIND_DOT: Record<StepKind, string> = {+ click: 'bg-accent',+ type: 'bg-violet-light',+ key: 'bg-violet',+ navigate: 'bg-lavender',+ note: 'bg-muted-foreground',+};++export function StepList({+ chapters,+ index,++ narrated,++ playing,+ onJump,+}: {+ chapters: VideoChapter[];+ index: number;++ narrated: boolean;++ playing: boolean;+ onJump: (n: number) => void;+}) {+ const list = useRef<HTMLElement>(null);++ useEffect(() => {+ list.current?.querySelectorAll('button')[index]?.scrollIntoView({ block: 'nearest' });+ }, [index]);++ return (+ <aside ref={list} className="w-[228px] shrink-0 overflow-y-auto border-l border-white/10 bg-deep">+ <div className="px-3 pb-2 pt-3 font-mono text-[9px] uppercase tracking-[0.1em] text-white/45">+ {i18n.t('videoPlayer.stepCount', [String(chapters.length)])}+ </div>+ {chapters.map((chapter, i) => (+ <button+ key={chapter.stepId}+ type="button"+ onClick={() => onJump(i)}+ className={`flex w-full items-start gap-2.5 border-l-2 px-3 py-1.5 text-left transition-colors ${i === index ? 'border-l-accent bg-white/10' : 'border-l-transparent hover:bg-white/5'}`}+ >+ <span className={`mt-1.5 size-1.5 shrink-0 rounded-full ${KIND_DOT[chapter.kind]}`} />+ <span className="min-w-0 flex-1 text-[10.5px] leading-snug text-white/80">{chapter.title}</span>++ {narrated && chapter.spoken && <SpokenMark talking={playing && i === index} />}+ <span className="pt-0.5 font-mono text-[9px] tabular-nums text-white/40">{formatClock(chapter.start)}</span>+ </button>+ ))}+ </aside>+ );+}diff --cc packages/ui/src/export/components/VideoStepPlayer.tsxindex fd65214,0000000..ff8e17cmode 100644,000000..100644--- a/packages/ui/src/export/components/VideoStepPlayer.tsx+++ b/packages/ui/src/export/components/VideoStepPlayer.tsx@@@ -1,29 -1,0 +1,30 @@@+import type { VideoChapter } from '@mimik/core/export/video-export';+import { FRAME_FILL } from '@mimik/core/export/video-support';+import { MediaPlayer } from '@vidstack/react';+import type { VideoMime } from '../types';+import { PlayerBody } from './PlayerBody';++interface VideoStepPlayerProps {+ src: string;+ type: VideoMime;+ chapters: VideoChapter[];++ narrated?: boolean;+}+- export function VideoStepPlayer({ src, type, chapters }: VideoStepPlayerProps) {++export function VideoStepPlayer({ src, type, chapters, narrated = false }: VideoStepPlayerProps) {+ return (+ <MediaPlayer+ src={{ src, type }}- autoPlay- muted++ autoPlay={!narrated}++ muted={!narrated}+ playsInline+ load="eager"+ viewType="video"+ streamType="on-demand"+ className="flex size-full"+ style={{ backgroundColor: FRAME_FILL }}+ >- <PlayerBody chapters={chapters} />++ <PlayerBody chapters={chapters} narrated={narrated} />+ </MediaPlayer>+ );+}diff --cc packages/ui/src/export/hooks/use-guide-export.tsindex 54eb79f,0000000..787ea20mode 100644,000000..100644--- a/packages/ui/src/export/hooks/use-guide-export.ts+++ b/packages/ui/src/export/hooks/use-guide-export.ts@@@ -1,89 -1,0 +1,133 @@@+import { downloadBlob, downloadText, safeFilename } from '@mimik/core/export/download';+import { exportGuideAsHTML } from '@mimik/core/export/html-export';- import type { ExportOptions } from '@mimik/core/export/options';++import { DEFAULT_EXPORT_OPTIONS, type ExportOptions } from '@mimik/core/export/options';+import { exportGuideAsPDF } from '@mimik/core/export/pdf-export';+import { withPreviewStyles } from '@mimik/core/export/preview';++import type { VoiceoverSkip } from '@mimik/core/export/video-export';+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';- import { useEffect, useRef, useState } from 'react';++import { BUNDLE_EXTENSION } from '@mimik/core/transfer/schema';++import { useEffect, useMemo, useRef, useState } from 'react';++import { exportProgress, MUX_PROGRESS_SHARE, VOICE_PROGRESS_SHARE } from '../lib/export-progress';+- export type ExportFormat = 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';++export type ExportFormat = 'bundle' | 'docx' | 'gif' | 'html' | 'markdown' | 'pdf' | 'video';++export interface GuideExport {+ html: string;+ rendering: boolean;+ running: ExportFormat | null;+ progress: number;++ voiceoverError: VoiceoverSkip | null;+ run: (format: ExportFormat) => Promise<void>;+ cancel: () => void;+}++interface Params {+ active: boolean;+ guide: Guide;+ steps: Step[];+ screenshots: Map<string, Screenshot>;+ options: ExportOptions;++ voiceover: boolean;+}+- export function useGuideExport({ active, guide, steps, screenshots, options }: Params): GuideExport {++export function useGuideExport({ active, guide, steps, screenshots, options, voiceover }: Params): GuideExport {+ const [html, setHtml] = useState('');+ const [rendering, setRendering] = useState(false);+ const [running, setRunning] = useState<ExportFormat | null>(null);+ const [progress, setProgress] = useState(0);++ const [voiceoverError, setVoiceoverError] = useState<VoiceoverSkip | null>(null);+ const abort = useRef<AbortController | null>(null);+++ const { cover, screenshots: withScreenshots, stepUrls, imageScale, stepDescriptions } = options;++ const previewOptions = useMemo<ExportOptions>(++ () => ({ ...DEFAULT_EXPORT_OPTIONS, cover, screenshots: withScreenshots, stepUrls, imageScale, stepDescriptions }),++ [cover, withScreenshots, stepUrls, imageScale, stepDescriptions],++ );+++ useEffect(() => {+ if (!active) return;+ let cancelled = false;+ setRendering(true);+ const timer = setTimeout(async () => {- const built = await exportGuideAsHTML(guide, steps, screenshots, options);++ const built = await exportGuideAsHTML(guide, steps, screenshots, previewOptions);+ if (cancelled) return;+ setHtml(withPreviewStyles(built));+ setRendering(false);+ }, 200);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };- }, [active, guide, steps, screenshots, options]);++ }, [active, guide, steps, screenshots, previewOptions]);++ const run = async (format: ExportFormat) => {+ setRunning(format);+ try {+ if (format === 'html') {+ const built = await exportGuideAsHTML(guide, steps, screenshots, options);+ downloadText(built, safeFilename(guide.title, 'html'), 'text/html');+ } else if (format === 'pdf') {+ downloadBlob(await exportGuideAsPDF(guide, steps, screenshots, options), safeFilename(guide.title, 'pdf'));+ } else if (format === 'docx') {+ const { exportGuideAsDOCX } = await import('@mimik/core/export/docx-export');+ downloadBlob(await exportGuideAsDOCX(guide, steps, screenshots, options), safeFilename(guide.title, 'docx'));+ } else if (format === 'markdown') {+ const { exportGuideAsMarkdown } = await import('@mimik/core/export/markdown-export');+ const md = await exportGuideAsMarkdown(guide, steps, screenshots);+ downloadText(md, safeFilename(guide.title, 'md'), 'text/markdown');- } else {++ } else if (format === 'bundle') {++ const { exportGuideAsBundle } = await import('@mimik/core/transfer/bundle');++ const blob = await exportGuideAsBundle(guide, steps, screenshots, {++ stripInputValues: options.bundleStripInputs,++ urls: options.bundleUrls,++ });++ downloadBlob(blob, safeFilename(guide.title, BUNDLE_EXTENSION));++ } else if (format === 'gif') {+ const controller = new AbortController();+ abort.current = controller;+ setProgress(0);- const encode =- format === 'gif'- ? (await import('@mimik/core/export/gif-export')).exportGuideAsGif- : (await import('@mimik/core/export/video-export')).exportGuideAsVideo;- const built = await encode(guide, steps, screenshots, options, {++ const { exportGuideAsGif } = await import('@mimik/core/export/gif-export');++ const built = await exportGuideAsGif(guide, steps, screenshots, options, {+ signal: controller.signal,+ onProgress: (encoded, frames) => setProgress(frames > 0 ? encoded / frames : 0),+ });+ downloadBlob(built.blob, safeFilename(guide.title, built.extension));++ } else {++ const controller = new AbortController();++ abort.current = controller;++ setProgress(0);++ const voiceShare = voiceover ? VOICE_PROGRESS_SHARE : 0;++ const muxShare = voiceover ? MUX_PROGRESS_SHARE : 0;++ let allClipsLanded = false;++ const { exportGuideAsVideo } = await import('@mimik/core/export/video-export');++ const built = await exportGuideAsVideo(++ guide,++ steps,++ screenshots,++ { ...options, voiceover },++ {++ signal: controller.signal,++ onProgress: (encoded, frames) =>++ setProgress(++ exportProgress.encode(encoded, frames, allClipsLanded ? voiceShare : 0, allClipsLanded ? muxShare : 0),++ ),++ onVoiceProgress: (done, total) => {++ allClipsLanded = done === total;++ setProgress(exportProgress.narrate(done, total, voiceShare));++ },++ onMuxProgress: (done, total) => setProgress(exportProgress.mux(done, total, muxShare)),++ },++ );++ setVoiceoverError(built.voiceoverError ?? null);++ downloadBlob(built.blob, safeFilename(guide.title, built.extension));+ }+ } catch (error) {+ if (!(error instanceof DOMException && error.name === 'AbortError')) throw error;+ } finally {+ abort.current = null;+ setRunning(null);+ }+ };+- return { html, rendering, running, progress, run, cancel: () => abort.current?.abort() };++ return { html, rendering, running, progress, voiceoverError, run, cancel: () => abort.current?.abort() };+}diff --cc packages/ui/src/export/hooks/use-video-preview.tsindex 8fd4288,0000000..4c9964fmode 100644,000000..100644--- a/packages/ui/src/export/hooks/use-video-preview.ts+++ b/packages/ui/src/export/hooks/use-video-preview.ts@@@ -1,96 -1,0 +1,131 @@@+import type { ExportOptions } from '@mimik/core/export/options';- import type { VideoChapter } from '@mimik/core/export/video-export';++import type { VideoChapter, VoiceoverSkip } from '@mimik/core/export/video-export';+import { canExportVideo } from '@mimik/core/export/video-support';+import type { Guide, Screenshot, Step } from '@mimik/core/guides/types';+import { useEffect, useState } from 'react';-++import { exportProgress, MUX_PROGRESS_SHARE, VOICE_PROGRESS_SHARE } from '../lib/export-progress';+import type { VideoMime } from '../types';++const AUTOPLAY_STEP_LIMIT = 25;++export interface VideoPreview {+ supported: boolean;+ url: string | null;+ mime: VideoMime;+ chapters: VideoChapter[];+ progress: number;++ narrating: { done: number; total: number } | null;++ voiceoverError: VoiceoverSkip | null;+ error: string | null;+ deferred: boolean;+ request: () => void;+}++interface Params {+ active: boolean;+ guide: Guide;+ steps: Step[];+ screenshots: Map<string, Screenshot>;+ options: ExportOptions;++ voiceover: boolean;+}+- export function useVideoPreview({ active, guide, steps, screenshots, options }: Params): VideoPreview {++export function useVideoPreview({ active, guide, steps, screenshots, options, voiceover }: Params): VideoPreview {+ const [supported, setSupported] = useState(false);+ const [url, setUrl] = useState<string | null>(null);+ const [mime, setMime] = useState<VideoMime>('video/mp4');+ const [chapters, setChapters] = useState<VideoChapter[]>([]);+ const [progress, setProgress] = useState(0);++ const [narrating, setNarrating] = useState<{ done: number; total: number } | null>(null);++ const [voiceoverError, setVoiceoverError] = useState<VoiceoverSkip | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [requested, setRequested] = useState(false);++ const { cover, stepDescriptions, resolution } = options;+ const deferred = steps.length > AUTOPLAY_STEP_LIMIT && !requested;++ useEffect(() => {+ let alive = true;+ canExportVideo().then((can) => {+ if (alive) setSupported(can);+ });+ return () => {+ alive = false;+ };+ }, []);++ useEffect(() => {+ if (!active) setRequested(false);+ }, [active]);++ useEffect(() => {+ if (!active || deferred) return;+ const controller = new AbortController();++ const voiceShare = voiceover ? VOICE_PROGRESS_SHARE : 0;++ const muxShare = voiceover ? MUX_PROGRESS_SHARE : 0;+ let made: string | null = null;+ setError(null);+ setProgress(0);++ setNarrating(null);++ setVoiceoverError(null);+ const timer = setTimeout(async () => {++ let allClipsLanded = false;+ try {+ const { exportGuideAsVideo } = await import('@mimik/core/export/video-export');+ const built = await exportGuideAsVideo(+ guide,+ steps,+ screenshots,- { cover, stepDescriptions, resolution },++ { cover, stepDescriptions, resolution, voiceover },+ {+ signal: controller.signal,+ onProgress: (encoded, frames) => {- if (!controller.signal.aborted) setProgress(frames > 0 ? encoded / frames : 0);++ if (controller.signal.aborted) return;++ setNarrating(null);++ setProgress(++ exportProgress.encode(encoded, frames, allClipsLanded ? voiceShare : 0, allClipsLanded ? muxShare : 0),++ );++ },++ onVoiceProgress: (done, total) => {++ if (controller.signal.aborted) return;++ allClipsLanded = done === total;++ setNarrating(done < total ? { done, total } : null);++ setProgress(exportProgress.narrate(done, total, voiceShare));++ },++ onMuxProgress: (done, total) => {++ if (!controller.signal.aborted) setProgress(exportProgress.mux(done, total, muxShare));+ },+ },+ );+ if (controller.signal.aborted) return;+ made = URL.createObjectURL(built.blob);+ setMime(built.blob.type === 'video/webm' ? 'video/webm' : 'video/mp4');+ setChapters(built.chapters);++ setVoiceoverError(built.voiceoverError ?? null);+ setUrl(made);+ } catch (err) {+ if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')) return;+ setError(err instanceof Error ? err.message : String(err));+ }+ }, 200);+ return () => {+ controller.abort();+ clearTimeout(timer);+ if (made) URL.revokeObjectURL(made);+ setUrl(null);+ };- }, [active, deferred, guide, steps, screenshots, cover, stepDescriptions, resolution]);++ }, [active, deferred, guide, steps, screenshots, cover, stepDescriptions, resolution, voiceover]);+- return { supported, url, mime, chapters, progress, error, deferred, request: () => setRequested(true) };++ return {++ supported,++ url,++ mime,++ chapters,++ progress,++ narrating,++ voiceoverError,++ error,++ deferred,++ request: () => setRequested(true),++ };+}diff --cc packages/ui/src/export/hooks/use-voiceover-ready.tsindex 0000000,0000000..9eac625new file mode 100644--- /dev/null+++ b/packages/ui/src/export/hooks/use-voiceover-ready.ts@@@ -1,0 -1,0 +1,18 @@@++import { localStorage } from '@mimik/core/env';++import { hasVoiceoverKey, VOICEOVER_SETTINGS } from '@mimik/core/export/voiceover/config';++import { useEffect, useState } from 'react';++++export function useVoiceoverReady(open: boolean): boolean {++ const [ready, setReady] = useState(false);++ useEffect(() => {++ if (!open) return;++ let active = true;++ localStorage.get([...VOICEOVER_SETTINGS]).then((stored) => {++ if (active) setReady(hasVoiceoverKey(stored));++ });++ return () => {++ active = false;++ };++ }, [open]);++ return ready;++}diff --cc packages/ui/src/export/lib/__tests__/export-progress.test.tsindex 0000000,0000000..eed7d74new file mode 100644--- /dev/null+++ b/packages/ui/src/export/lib/__tests__/export-progress.test.ts@@@ -1,0 -1,0 +1,57 @@@++import { describe, expect, it } from 'vitest';++import { exportProgress, MUX_PROGRESS_SHARE, VOICE_PROGRESS_SHARE } from '../export-progress';++++describe('VOICE_PROGRESS_SHARE', () => {++ it('leaves narration a visible head of the bar and encoding the majority', () => {++ expect(VOICE_PROGRESS_SHARE).toBe(0.3);++ });++});++++describe('exportProgress.narrate', () => {++ it('fills only the head of the bar, since encoding still has to run', () => {++ expect(exportProgress.narrate(0, 10, 0.3)).toBe(0);++ expect(exportProgress.narrate(5, 10, 0.3)).toBeCloseTo(0.15, 6);++ expect(exportProgress.narrate(10, 10, 0.3)).toBeCloseTo(0.3, 6);++ });++++ it('stays at zero when there is nothing to synthesise, rather than dividing by zero', () => {++ expect(exportProgress.narrate(0, 0, 0.3)).toBe(0);++ });++});++++describe('MUX_PROGRESS_SHARE', () => {++ it('keeps a slice back for writing the audio track, which runs after the last frame', () => {++ expect(MUX_PROGRESS_SHARE).toBe(0.1);++ });++});++++describe('exportProgress.encode', () => {++ it('starts where narration left off so the bar never goes backwards', () => {++ expect(exportProgress.encode(0, 300, 0.3)).toBeCloseTo(0.3, 6);++ expect(exportProgress.encode(150, 300, 0.3)).toBeCloseTo(0.65, 6);++ expect(exportProgress.encode(300, 300, 0.3)).toBeCloseTo(1, 6);++ });++++ it('owns the whole bar when nothing was narrated', () => {++ expect(exportProgress.encode(0, 300, 0)).toBe(0);++ expect(exportProgress.encode(150, 300, 0)).toBeCloseTo(0.5, 6);++ expect(exportProgress.encode(300, 300, 0)).toBeCloseTo(1, 6);++ });++++ it('stops short of the end when an audio track still has to be written', () => {++ expect(exportProgress.encode(300, 300, 0.3, 0.1)).toBeCloseTo(0.9, 6);++ expect(exportProgress.encode(150, 300, 0.3, 0.1)).toBeCloseTo(0.6, 6);++ });++});++++describe('exportProgress.mux', () => {++ it('fills the tail the encode left behind', () => {++ expect(exportProgress.mux(0, 40, 0.1)).toBeCloseTo(0.9, 6);++ expect(exportProgress.mux(20, 40, 0.1)).toBeCloseTo(0.95, 6);++ expect(exportProgress.mux(40, 40, 0.1)).toBeCloseTo(1, 6);++ });++++ it('picks up exactly where a narrated encode stopped', () => {++ expect(exportProgress.mux(0, 40, 0.1)).toBeCloseTo(exportProgress.encode(300, 300, 0.3, 0.1), 6);++ });++});diff --cc packages/ui/src/export/lib/export-progress.tsindex 0000000,0000000..954bdb1new file mode 100644--- /dev/null+++ b/packages/ui/src/export/lib/export-progress.ts@@@ -1,0 -1,0 +1,15 @@@++export const VOICE_PROGRESS_SHARE = 0.3;++++export const MUX_PROGRESS_SHARE = 0.1;++++export const exportProgress = {++ narrate(done: number, total: number, share: number): number {++ return total > 0 ? (done / total) * share : 0;++ },++ encode(encoded: number, frames: number, share: number, tail = 0): number {++ return share + (frames > 0 ? encoded / frames : 0) * (1 - share - tail);++ },++ mux(done: number, total: number, tail: number): number {++ return 1 - tail + (total > 0 ? done / total : 0) * tail;++ },++};diff --cc packages/ui/src/guide/components/GuideContent.tsxindex 008cd2c,4720f52..dea4998--- a/packages/ui/src/guide/components/GuideContent.tsx+++ b/packages/ui/src/guide/components/GuideContent.tsx@@@ -6,30 -7,31 +6,33 @@@ import { getMostCommonDomain } from '@mimport {deleteStep,getGuide,- getScreenshotsForSteps,+ hasTranscript,onGuidesChanged,updateGuideDescription,updateGuideTitle,updateStepDescription,-} from '@/core/guides/service';-import type { SnapshotLike } from '@/core/guides/snapshot-diff';-import { sanitizeGuideTitle, stripTitleLineBreaks } from '@/core/guides/title';-import type { Guide, Screenshot, Snapshot, Step } from '@/core/guides/types';-import type { ScreenshotEdits } from '@/core/screenshot/types';-import { localStorage, openSidebar } from '@/lib/browser-api';-import { logger } from '@/lib/logger';-import { sendMessage } from '@/lib/messaging';-import { formatDate, getMostCommonDomain } from '@/lib/utils';-import { useFullview } from '@/stores/fullview';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';-import AnnotationEditor from '@/ui/shared/AnnotationEditor';-import { useAskAi } from '@/ui/shared/AskAi';-import FaviconImg from '@/ui/shared/FaviconImg';-import { guideDescriptionErrorMessage } from '@/ui/shared/guide-description-error';-import Toast from '@/ui/shared/Toast';-import GuideStepList from './components/GuideStepList';-import TranscriptPanel from './components/TranscriptPanel';-import VersionHistoryPanel from './components/VersionHistoryPanel';+} from '@mimik/core/guides/service';+import type { SnapshotLike } from '@mimik/core/guides/snapshot-diff';++import { sanitizeGuideTitle, stripTitleLineBreaks } from '@mimik/core/guides/title';+import type { Guide, Screenshot, Snapshot, Step } from '@mimik/core/guides/types';+import { logger } from '@mimik/core/logger';+import type { ScreenshotEdits } from '@mimik/core/screenshot/types';+import { History, Loader2, Play, Sparkles } from 'lucide-react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { TypeAnimation } from 'react-type-animation';+import { useAskAi } from '../../ai/hooks/use-ask-ai';+import { useGuideDescription } from '../../ai/hooks/use-guide-description';+import { AnnotationEditor } from '../../annotation/components/AnnotationEditor';+import { FaviconImg } from '../../common/components/FaviconImg';+import { Toast } from '../../common/components/Toast';+import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';+import { messages, panel, tabs } from '../../env';++import { TranscriptPanel } from '../../history/components/TranscriptPanel';+import { VersionHistoryPanel } from '../../history/components/VersionHistoryPanel';+import { useFullview } from '../../stores/use-fullview';+import { buildPreview } from '../lib/build-preview';+import type { PreviewData } from '../types';+import { GuideStepList } from './GuideStepList';interface GuideContentProps {guideId: string;@@@ -75,10 -103,11 +84,11 @@@ export function GuideContent({ guideIdconst [editingTool, setEditingTool] = useState<'annotate' | 'redact' | 'crop' | 'target'>('annotate');const [preview, setPreview] = useState<Snapshot | null>(null);const [previewData, setPreviewData] = useState<PreviewData | null>(null);- const [description, setDescription] = useState('');- const [generating, setGenerating] = useState(false);- const [hasApiKey, setHasApiKey] = useState(false);- const [descriptionError, setDescriptionError] = useState<string | null>(null);+ const applyDescription = useCallback((next: string) => {+ setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: next } } : prev));+ }, []);+ const desc = useGuideDescription(guideId, applyDescription);+ const [dataVersion, setDataVersion] = useState(0);const titleRef = useRef('');const appliedInitialRef = useRef(false);const editingDescriptionRef = useRef(false);@@@ -121,21 -154,55 +135,26 @@@}, []);const handleTitleBlur = useCallback(async () => {- if (!data || title === data.guide.title) return;- await updateGuideTitle(guideId, title);- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, title } } : prev));- document.title = `${title} — ${i18n.t('app_name')}`;- }, [data, guideId, title]);+ const next = sanitizeGuideTitle(title);+ if (next !== title) {+ setTitle(next);+ setGuideTitle(next);+ }+ if (!data || next === data.guide.title) return;+ await updateGuideTitle(guideId, next);+ setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, title: next } } : prev));+ document.title = `${next} — ${i18n.t('app_name')}`;+ }, [data, guideId, title, setGuideTitle]);const handleGuideDescriptionBlur = useCallback(async () => {- if (data && description !== (data.guide.description ?? '')) {- await updateGuideDescription(guideId, description);- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description } } : prev));+ if (data && desc.text !== (data.guide.description ?? '')) {+ await updateGuideDescription(guideId, desc.text);+ setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: desc.text } } : prev));}editingDescriptionRef.current = false;- }, [data, guideId, description]);+ }, [data, guideId, desc.text]);- const commitGuideDescription = useCallback(- (next: string) => {- setDescription(next);- void updateGuideDescription(guideId, next);- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: next } } : prev));- },- [guideId],- );-- const askAi = useAskAi(description, commitGuideDescription, hasApiKey);-- const handleGenerateDescription = useCallback(async () => {- setGenerating(true);- setDescriptionError(null);- try {- const result = await sendMessage('generateGuideDescription', { guideId });- if (result.error) {- setDescriptionError(guideDescriptionErrorMessage(result.error));- return;- }- const generated = result.description;- if (!generated) return;- setDescription(generated);- setData((prev) => (prev ? { ...prev, guide: { ...prev.guide, description: generated } } : prev));- } catch {- setDescriptionError(guideDescriptionErrorMessage('generation-failed'));- } finally {- setGenerating(false);- }- }, [guideId]);+ const askAi = useAskAi(desc.text, desc.commit, desc.hasApiKey);const handleDescriptionChange = useCallback(async (stepId: string, description: string) => {await updateStepDescription(stepId, description, 'manual');diff --cc packages/ui/src/guide/components/StepCard.tsxindex 2b622c1,474de95..e1a8218--- a/packages/ui/src/guide/components/StepCard.tsx+++ b/packages/ui/src/guide/components/StepCard.tsx@@@ -1,19 -1,17 +1,19 @@@+import { i18n } from '@mimik/core/env';- import { replaceScreenshot } from '@mimik/core/guides/service';++import { replaceScreenshot, restoreNarratedDescription } from '@mimik/core/guides/service';+import type { Screenshot, Step } from '@mimik/core/guides/types';+import { logger } from '@mimik/core/logger';+import { imageDimensions, renderScreenshot } from '@mimik/core/screenshot/render';- import { Check, Copy, Loader2, Trash2 } from 'lucide-react';+ import { Check, Copy, Loader2, Trash2, Undo2 } from 'lucide-react';import { useEffect, useState } from 'react';-import { i18n } from '#imports';-import { replaceScreenshot, restoreNarratedDescription } from '@/core/guides/service';-import type { Screenshot, Step } from '@/core/guides/types';-import { imageDimensions, renderScreenshot } from '@/core/screenshot/render';-import { logger } from '@/lib/logger';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';-import { useAskAi } from '@/ui/shared/AskAi';-import ConfirmDialog from '@/ui/shared/ConfirmDialog';-import { DragGrip, type DragHandleProps, useCardDrag } from '@/ui/shared/card-drag';-import ImagePlaceholder from '@/ui/shared/ImagePlaceholder';-import ScreenshotView from '@/ui/shared/ScreenshotView';-import StepSourceBadge from '@/ui/shared/StepSourceBadge';+import { useAskAi } from '../../ai/hooks/use-ask-ai';+import { ConfirmDialog } from '../../common/components/ConfirmDialog';+import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';+import { useCardDrag } from '../hooks/use-card-drag';+import type { DragHandleProps } from '../types';+import { DragGrip } from './DragGrip';+import { ImagePlaceholder } from './ImagePlaceholder';+import { ScreenshotView } from './ScreenshotView';+import { StepSourceBadge } from './StepSourceBadge';interface StepCardProps {step: Step;diff --cc packages/ui/src/guide/components/__tests__/step-card-restore.test.tsxindex 0000000,d061f30..6a8d4bdmode 000000,100644..100644--- a/packages/ui/src/guide/components/__tests__/step-card-restore.test.tsx+++ b/packages/ui/src/guide/components/__tests__/step-card-restore.test.tsx@@@ -1,0 -1,93 +1,94 @@@+ // @vitest-environment jsdom++++import type { Step } from '@mimik/core/guides/types';+ import { fireEvent, render, screen, waitFor } from '@testing-library/react';+ import { describe, expect, it, vi } from 'vitest';-import type { Step } from '@/core/guides/types';-import { TooltipProvider } from '@/ui/components/ui/tooltip';++import { TooltipProvider } from '../../../components/ui/tooltip';++ const restoreNarratedDescription = vi.fn();+-vi.mock('@/core/guides/service', () => ({++vi.mock('@mimik/core/guides/service', () => ({+ replaceScreenshot: vi.fn(),+ restoreNarratedDescription: (...args: unknown[]) => restoreNarratedDescription(...args),+ }));-vi.mock('@/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));++vi.mock('@mimik/core/screenshot/render', () => ({ imageDimensions: vi.fn(), renderScreenshot: vi.fn() }));+-import StepCard from '../StepCard';++import { StepCard } from '../StepCard';++ const SPOKEN = 'Open the billing tab on the left';++ function step(overrides: Partial<Step>): Step {+ return {+ id: 's1',+ guideId: 'g1',+ index: 0,+ description: SPOKEN,+ action: 'click',+ url: 'https://a.test',+ timestamp: 1,+ ...overrides,+ };+ }++ function renderCard(current: Step, readOnly = false, onChanged = vi.fn()) {+ return render(+ <TooltipProvider>+ <StepCard+ step={current}+ number={1}+ screenshot={undefined}+ readOnly={readOnly}+ onDescriptionChange={vi.fn()}+ onDelete={vi.fn()}+ onChanged={onChanged}+ />+ </TooltipProvider>,+ );+ }++ const restoreButton = () => screen.queryByRole('button', { name: 'editor.restoreSpoken' });++ describe('restoring what the step said', () => {+ it('is offered once an edit has moved the text away from the narration', () => {+ renderCard(step({ description: 'Click Billing', narratedDescription: SPOKEN, descriptionSource: 'manual' }));+ expect(restoreButton()).toBeTruthy();+ });++ it('is not offered while the text still matches the narration', () => {+ renderCard(step({ description: SPOKEN, narratedDescription: SPOKEN, descriptionSource: 'narration' }));+ expect(restoreButton()).toBeNull();+ });++ it('is not offered on a step narration never touched', () => {+ renderCard(step({ description: 'Click Billing', descriptionSource: 'ai' }));+ expect(restoreButton()).toBeNull();+ });++ it('is not offered while the card is read-only', () => {+ renderCard(step({ description: 'Click Billing', narratedDescription: SPOKEN }), true);+ expect(restoreButton()).toBeNull();+ });++ it('is not offered while a description is still being written', () => {+ renderCard(step({ description: 'Click Billing', narratedDescription: SPOKEN, aiPending: true }));+ expect(restoreButton()).toBeNull();+ });++ it('puts the spoken text back and tells the page to reload', async () => {+ restoreNarratedDescription.mockResolvedValue(SPOKEN);+ const onChanged = vi.fn();+ renderCard(+ step({ description: 'Click Billing', narratedDescription: SPOKEN, descriptionSource: 'manual' }),+ false,+ onChanged,+ );++ const button = restoreButton();+ expect(button).toBeTruthy();+ fireEvent.click(button as HTMLElement);++ await waitFor(() => expect(onChanged).toHaveBeenCalled());+ expect(restoreNarratedDescription).toHaveBeenCalledWith('s1');+ expect(screen.getByDisplayValue(SPOKEN)).toBeTruthy();+ });+ });diff --cc packages/ui/src/guide/store/editor-slice.tsindex 6ca375c,0000000..35d2be1mode 100644,000000..100644--- a/packages/ui/src/guide/store/editor-slice.ts+++ b/packages/ui/src/guide/store/editor-slice.ts@@@ -1,32 -1,0 +1,49 @@@+import type { StateCreator } from 'zustand';++export interface EditorSlice {+ editing: boolean;+ setEditing: (editing: boolean) => void;+ historyOpen: boolean;+ setHistoryOpen: (open: boolean) => void;+ historyRefreshKey: number;+ bumpHistoryRefresh: () => void;++ transcriptOpen: boolean;++ setTranscriptOpen: (open: boolean) => void;++ hasTranscript: boolean;++ setHasTranscript: (has: boolean) => void;+}+- export const CLOSED_EDITOR = { editing: false, historyOpen: false, historyRefreshKey: 0 } as const;++export const CLOSED_EDITOR = {++ editing: false,++ historyOpen: false,++ historyRefreshKey: 0,++ transcriptOpen: false,++ hasTranscript: false,++} as const;++function flushFocusedField() {+ const el = document.activeElement;+ if (el instanceof HTMLTextAreaElement || el instanceof HTMLInputElement) el.blur();+}++export const createEditorSlice: StateCreator<EditorSlice, [], [], EditorSlice> = (set) => ({+ editing: false,+ setEditing: (editing) => {+ if (!editing) flushFocusedField();+ set({ editing });+ },+ historyOpen: false,+ setHistoryOpen: (historyOpen) => {+ if (historyOpen) flushFocusedField();- set({ historyOpen });++ set(historyOpen ? { historyOpen, transcriptOpen: false } : { historyOpen });+ },+ historyRefreshKey: 0,+ bumpHistoryRefresh: () => set((s) => ({ historyRefreshKey: s.historyRefreshKey + 1 })),++ transcriptOpen: false,++ setTranscriptOpen: (transcriptOpen) => {++ if (transcriptOpen) flushFocusedField();++ set(transcriptOpen ? { transcriptOpen, historyOpen: false } : { transcriptOpen });++ },++ hasTranscript: false,++ setHasTranscript: (hasTranscript) => set({ hasTranscript }),+});diff --cc packages/ui/src/history/components/TranscriptPanel.tsxindex 0000000,554f53d..b593824mode 000000,100644..100644--- a/packages/ui/src/history/components/TranscriptPanel.tsx+++ b/packages/ui/src/history/components/TranscriptPanel.tsx@@@ -1,0 -1,252 +1,245 @@@-import { Check, Copy, Download, Plus, Trash2, X } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { i18n } from '#imports';-import { downloadText, safeFilename } from '@/core/export/download';-import { stepNumbers } from '@/core/guides/blocks';-import { addTranscriptLineToStep, deleteTranscripts, getTranscripts } from '@/core/guides/service';++import { i18n } from '@mimik/core/env';++import { downloadText, safeFilename } from '@mimik/core/export/download';++import { stepNumbers } from '@mimik/core/guides/blocks';++import { addTranscriptLineToStep, deleteTranscripts, getTranscripts } from '@mimik/core/guides/service';+ import {+ countUnused,+ formatOffset,+ mergeTranscripts,+ nearestStepId,+ type TimelineLine,+ transcriptToText,+ withLiveSteps,-} from '@/core/guides/transcript';-import type { Step } from '@/core/guides/types';-import { logger } from '@/lib/logger';-import { useFullview } from '@/stores/fullview';-import { Button } from '@/ui/components/ui/button';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';-import ConfirmDialog from '@/ui/shared/ConfirmDialog';++} from '@mimik/core/guides/transcript';++import type { Step } from '@mimik/core/guides/types';++import { logger } from '@mimik/core/logger';++import { Check, Copy, Download, Plus, Trash2, X } from 'lucide-react';++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';++import { ConfirmDialog } from '../../common/components/ConfirmDialog';++import { Button } from '../../components/ui/button';++import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';++import { useFullview } from '../../stores/use-fullview';++import { transcriptPill } from '../lib/transcript-pill';++ interface TranscriptPanelProps {+ guideId: string;+ guideTitle: string;+ steps: Step[];+ readOnly?: boolean;+ refreshKey?: number;+ onClose: () => void;+ onChanged?: () => void;+ }+-function pill(active: boolean): string {- return `px-2 py-0.5 rounded-full text-[10px] font-semibold border ${- active- ? 'bg-secondary border-border text-foreground'- : 'border-transparent text-muted-foreground hover:text-foreground'- }`;-}--export default function TranscriptPanel({++export function TranscriptPanel({+ guideId,+ guideTitle,+ steps,+ readOnly,+ refreshKey,+ onClose,+ onChanged,+ }: TranscriptPanelProps) {+ const scrollToStep = useFullview((s) => s.scrollToStep);+ const [lines, setLines] = useState<TimelineLine[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [unusedOnly, setUnusedOnly] = useState(false);+ const [copied, setCopied] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const refreshRef = useRef(refreshKey);++ const load = useCallback(async () => {+ try {+ setLines(mergeTranscripts(await getTranscripts(guideId)));+ } catch (err) {+ logger.error(' Transcript could not be read', err);+ setError(i18n.t('transcript.loadError'));+ } finally {+ setLoading(false);+ }+ }, [guideId]);++ useEffect(() => {+ const silent = refreshRef.current === refreshKey;+ refreshRef.current = refreshKey;+ if (!silent) {+ setLoading(true);+ setError(null);+ }+ void load();+ }, [load, refreshKey]);++ const numbers = useMemo(() => stepNumbers(steps), [steps]);++ const timeline = useMemo(() => withLiveSteps(lines, steps), [lines, steps]);++ const unused = countUnused(timeline);+ const shown = timeline.map((line, index) => ({ line, index })).filter(({ line }) => !unusedOnly || !line.stepId);++ const handleCopyAll = async () => {+ try {+ await navigator.clipboard.writeText(transcriptToText(timeline, numbers));+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch (err) {+ logger.error(' Transcript could not be copied', err);+ }+ };++ const handleDownload = () => {+ downloadText(transcriptToText(timeline, numbers), safeFilename(`${guideTitle} transcript`, 'txt'), 'text/plain');+ };++ const handleDelete = async () => {+ setConfirmDelete(false);+ await deleteTranscripts(guideId);+ setLines([]);+ onChanged?.();+ };++ const targetFor = (line: TimelineLine, index: number): string | null => line.stepId ?? nearestStepId(timeline, index);++ const handleAddToStep = async (line: TimelineLine, index: number) => {+ const targetId = targetFor(line, index);+ if (!targetId) return;+ if (!(await addTranscriptLineToStep(line.rowId, line.lineIndex, targetId, line.text))) return;+ await load();+ onChanged?.();+ };++ return (+ <aside className="w-72 shrink-0 border-l border-border pl-4 flex flex-col gap-1">+ <div className="flex items-center gap-2 h-10">+ <button+ type="button"+ onClick={onClose}+ aria-label={i18n.t('common.close')}+ className="p-1 text-muted-foreground hover:text-foreground"+ >+ <X size={14} />+ </button>+ <span className="text-[13px] font-semibold text-foreground">{i18n.t('transcript.title')}</span>+ </div>++ {error && (+ <p role="alert" className="text-[11px] text-destructive py-2">+ {error}+ </p>+ )}++ {loading ? (+ <p className="text-[11px] text-muted-foreground py-2">{i18n.t('common.loading')}</p>+ ) : lines.length === 0 ? (+ <p className="text-[11px] text-muted-foreground py-2">{i18n.t('transcript.empty')}</p>+ ) : (+ <>+ <div className="flex items-center gap-1 pb-1">+ <button+ type="button"+ aria-pressed={!unusedOnly}- className={pill(!unusedOnly)}++ className={transcriptPill(!unusedOnly)}+ onClick={() => setUnusedOnly(false)}+ >+ {i18n.t('transcript.filterAll', [String(lines.length)])}+ </button>+ <button+ type="button"+ aria-pressed={unusedOnly}- className={pill(unusedOnly)}++ className={transcriptPill(unusedOnly)}+ onClick={() => setUnusedOnly(true)}+ >+ {i18n.t('transcript.filterUnused', [String(unused)])}+ </button>+ </div>++ <p className="text-[10px] leading-snug text-muted-foreground pb-1">{i18n.t('transcript.privacyNote')}</p>++ {readOnly && unused > 0 && (+ <p className="text-[10px] leading-snug text-accent pb-1">{i18n.t('transcript.readOnlyHint')}</p>+ )}++ <ul className="flex flex-col gap-2 overflow-y-auto pr-1">+ {shown.map(({ line, index }) => {+ const number = line.stepId ? numbers.get(line.stepId) : undefined;+ const targetId = targetFor(line, index);+ const suggestion = targetId ? numbers.get(targetId) : undefined;+ return (+ <li key={`${line.atMs}-${index}`} className="flex flex-col gap-0.5">+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] font-semibold tabular-nums text-muted-foreground">+ {formatOffset(line.offsetSeconds)}+ </span>+ {number ? (+ <button+ type="button"+ onClick={() => line.stepId && scrollToStep(line.stepId)}+ className="text-[9px] font-bold uppercase tracking-wide rounded px-1 py-[2px] bg-success/10 text-success"+ >+ {i18n.t('transcript.usedInStep', [String(number)])}+ </button>+ ) : (+ <span className="text-[9px] font-bold uppercase tracking-wide rounded px-1 py-[2px] border border-border text-muted-foreground">+ {line.rejectReason ? i18n.t('transcript.filteredOut') : i18n.t('transcript.notUsed')}+ </span>+ )}+ {!readOnly && !number && suggestion && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => void handleAddToStep(line, index)}+ aria-label={i18n.t('transcript.addToStep', [String(suggestion)])}+ className="ml-auto p-0.5 rounded text-muted-foreground hover:text-accent"+ >+ <Plus size={12} />+ </button>+ </TooltipTrigger>+ <TooltipContent>{i18n.t('transcript.addToStep', [String(suggestion)])}</TooltipContent>+ </Tooltip>+ )}+ </div>+ <p className="text-[11px] leading-snug text-foreground">{line.text}</p>+ </li>+ );+ })}+ </ul>++ <div className="flex items-center gap-1 pt-2 mt-auto">+ <Button size="sm" variant="ghost" onClick={() => void handleCopyAll()} className="h-7 px-2 text-[11px]">+ {copied ? <Check size={12} className="text-success" /> : <Copy size={12} />}+ {i18n.t('transcript.copyAll')}+ </Button>+ <Button size="sm" variant="ghost" onClick={handleDownload} className="h-7 px-2 text-[11px]">+ <Download size={12} />+ {i18n.t('transcript.download')}+ </Button>+ {!readOnly && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => setConfirmDelete(true)}+ aria-label={i18n.t('transcript.delete')}+ className="ml-auto p-1 rounded-md text-muted-foreground hover:text-destructive"+ >+ <Trash2 size={13} />+ </button>+ </TooltipTrigger>+ <TooltipContent>{i18n.t('transcript.delete')}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </>+ )}++ <ConfirmDialog+ open={confirmDelete}+ heading={i18n.t('transcript.confirmDelete')}+ destructive+ onConfirm={() => void handleDelete()}+ onCancel={() => setConfirmDelete(false)}+ />+ </aside>+ );+ }diff --cc packages/ui/src/history/components/__tests__/transcript-panel.test.tsxindex 0000000,1deaabd..2762707mode 000000,100644..100644--- a/packages/ui/src/history/components/__tests__/transcript-panel.test.tsx+++ b/packages/ui/src/history/components/__tests__/transcript-panel.test.tsx@@@ -1,0 -1,182 +1,183 @@@+ // @vitest-environment jsdom++++import type { GuideTranscript, Step } from '@mimik/core/guides/types';+ import { fireEvent, render, screen, waitFor } from '@testing-library/react';+ import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { GuideTranscript, Step } from '@/core/guides/types';-import { TooltipProvider } from '@/ui/components/ui/tooltip';++import { TooltipProvider } from '../../../components/ui/tooltip';++ const getTranscripts = vi.fn();+ const addTranscriptLineToStep = vi.fn();+ const deleteTranscripts = vi.fn();+-vi.mock('@/core/guides/service', () => ({++vi.mock('@mimik/core/guides/service', () => ({+ getTranscripts: (...args: unknown[]) => getTranscripts(...args),+ addTranscriptLineToStep: (...args: unknown[]) => addTranscriptLineToStep(...args),+ deleteTranscripts: (...args: unknown[]) => deleteTranscripts(...args),+ }));+-import TranscriptPanel from '../TranscriptPanel';++import { TranscriptPanel } from '../TranscriptPanel';++ const EPOCH = 1_700_000_000_000;++ function step(id: string, index: number): Step {+ return {+ id,+ guideId: 'g1',+ index,+ description: 'Clicked something',+ action: 'click',+ url: 'https://a.test',+ timestamp: 1,+ };+ }++ function transcript(lines: Array<[number, string, string | null, string | null]>): GuideTranscript {+ return {+ id: 't1',+ guideId: 'g1',+ epochMs: EPOCH,+ createdAt: 1,+ lines: lines.map(([start, text, stepId, rejectReason]) => ({+ start,+ end: start + 1,+ text,+ stepId,+ rejectReason,+ })),+ };+ }++ function renderPanel(rows: GuideTranscript[], steps: Step[], readOnly = false) {+ getTranscripts.mockResolvedValue(rows);+ return render(+ <TooltipProvider>+ <TranscriptPanel+ guideId="g1"+ guideTitle="Test Guide"+ steps={steps}+ readOnly={readOnly}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />+ </TooltipProvider>,+ );+ }++ beforeEach(() => {+ getTranscripts.mockReset();+ addTranscriptLineToStep.mockReset();+ deleteTranscripts.mockReset();+ });++ describe('TranscriptPanel', () => {+ it('marks a line whose step was deleted as unused and offers it to a live step', async () => {+ renderPanel(+ [+ transcript([+ [1, 'first line', 's1', null],+ [3, 'orphaned line', 'gone', null],+ [5, 'third line', 's3', null],+ ]),+ ],+ [step('s1', 0), step('s3', 1)],+ );++ await screen.findByText('orphaned line');+ expect(screen.getByText('transcript.filterUnused[1]')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'transcript.addToStep[2]' })).toBeTruthy();+ });++ it('appends an unused line to the step that follows it', async () => {+ addTranscriptLineToStep.mockResolvedValue('Clicked something and then some');+ renderPanel(+ [+ transcript([+ [1, 'click save', 's1', null],+ [3, 'stray thought', null, null],+ [5, 'now the dialog', 's3', null],+ ]),+ ],+ [step('s1', 0), step('s3', 1)],+ );++ fireEvent.click(await screen.findByRole('button', { name: 'transcript.addToStep[2]' }));++ await waitFor(() =>+ expect(addTranscriptLineToStep).toHaveBeenCalledWith(expect.any(String), 1, 's3', 'stray thought'),+ );+ });++ it('records the attribution, so reopening cannot append the same line twice', async () => {+ addTranscriptLineToStep.mockResolvedValue('Clicked something and then some');+ const seeded = transcript([+ [1, 'click save', 's1', null],+ [3, 'stray thought', null, null],+ [5, 'now the dialog', 's3', null],+ ]);+ const attached = {+ ...seeded,+ lines: seeded.lines.map((l, i) => (i === 1 ? { ...l, stepId: 's3' } : l)),+ };+ getTranscripts.mockResolvedValueOnce([seeded]).mockResolvedValue([attached]);++ render(+ <TooltipProvider>+ <TranscriptPanel+ guideId="g1"+ guideTitle="Test Guide"+ steps={[step('s1', 0), step('s3', 1)]}+ onClose={vi.fn()}+ onChanged={vi.fn()}+ />+ </TooltipProvider>,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'transcript.addToStep[2]' }));++ await waitFor(() => expect(addTranscriptLineToStep).toHaveBeenCalledWith(seeded.id, 1, 's3', 'stray thought'));+ await waitFor(() => expect(screen.queryByRole('button', { name: /transcript.addToStep/ })).toBeNull());+ expect(addTranscriptLineToStep).toHaveBeenCalledTimes(1);+ });++ it('keeps a filtered line visible with its own tag', async () => {+ renderPanel([transcript([[1, 'Thanks for watching', null, 'blocklist:thanks for watching']])], [step('s1', 0)]);++ await screen.findByText('Thanks for watching');+ expect(screen.getByText('transcript.filteredOut')).toBeTruthy();+ });++ it('says so when nothing was narrated', async () => {+ renderPanel([], [step('s1', 0)]);+ expect(await screen.findByText('transcript.empty')).toBeTruthy();+ });++ it('does not offer the irreversible delete while the guide is read-only', async () => {+ renderPanel([transcript([[1, 'a line', 's1', null]])], [step('s1', 0)], true);++ await screen.findByText('a line');+ expect(screen.queryByRole('button', { name: 'transcript.delete' })).toBeNull();+ expect(screen.queryByRole('button', { name: /transcript.addToStep/ })).toBeNull();+ });++ it('says why there is no way to add a line while read-only', async () => {+ renderPanel(+ [+ transcript([+ [1, 'click save', 's1', null],+ [3, 'stray thought', null, null],+ ]),+ ],+ [step('s1', 0)],+ true,+ );++ expect(await screen.findByText('transcript.readOnlyHint')).toBeTruthy();+ });++ it('stays quiet about editing when every line is already used', async () => {+ renderPanel([transcript([[1, 'click save', 's1', null]])], [step('s1', 0)], true);++ await screen.findByText('click save');+ expect(screen.queryByText('transcript.readOnlyHint')).toBeNull();+ });+ });diff --cc packages/ui/src/history/lib/transcript-pill.tsindex 0000000,0000000..875ffbanew file mode 100644--- /dev/null+++ b/packages/ui/src/history/lib/transcript-pill.ts@@@ -1,0 -1,0 +1,7 @@@++export function transcriptPill(active: boolean): string {++ return `px-2 py-0.5 rounded-full text-[10px] font-semibold border ${++ active++ ? 'bg-secondary border-border text-foreground'++ : 'border-transparent text-muted-foreground hover:text-foreground'++ }`;++}diff --cc packages/ui/src/library/components/CardMenu.tsxindex 1edbd22,1eec9d4..24c354d--- a/packages/ui/src/library/components/CardMenu.tsx+++ b/packages/ui/src/library/components/CardMenu.tsx@@@ -1,8 -1,33 +1,8 @@@+import { i18n } from '@mimik/core/env';- import { MoreVertical, RotateCcw, Star, StarOff, Trash2 } from 'lucide-react';+ import { Copy, MoreVertical, RotateCcw, Star, StarOff, Trash2 } from 'lucide-react';import { useEffect, useRef, useState } from 'react';-import { i18n } from '#imports';-import { formatDate } from '@/lib/utils';-import { useFullview } from '@/stores/fullview';-import ScreenshotView from '@/ui/shared/ScreenshotView';-import { navigate } from '../router';-interface GuideGridViewProps {- category: 'all' | 'starred' | 'trash';- onStar: (e: React.MouseEvent, id: string) => void;- onTrash: (e: React.MouseEvent, id: string) => void;- onRestore: (e: React.MouseEvent, id: string) => void;- onPermanentDelete: (e: React.MouseEvent, id: string) => void;- onDuplicate: (e: React.MouseEvent, id: string) => void;-}--function MimikEyes() {- return (- <div className="w-full h-full flex items-center justify-center bg-primary">- <svg width="120" height="50" viewBox="0 0 120 50" fill="none">- <path d="M15 30 Q27 14 39 30" stroke="#C7D2FE" strokeWidth="5" strokeLinecap="round" fill="none" />- <path d="M81 30 Q93 14 105 30" stroke="#C7D2FE" strokeWidth="5" strokeLinecap="round" fill="none" />- <path d="M39 44 Q60 54 81 44" stroke="#C7D2FE" strokeWidth="3.5" strokeLinecap="round" fill="none" />- </svg>- </div>- );-}--function CardMenu({+export function CardMenu({guideId,starred,category,diff --cc packages/ui/src/library/components/GuideGridView.tsxindex 21f9df8,0000000..44228e4mode 100644,000000..100644--- a/packages/ui/src/library/components/GuideGridView.tsx+++ b/packages/ui/src/library/components/GuideGridView.tsx@@@ -1,100 -1,0 +1,103 @@@+import { i18n } from '@mimik/core/env';+import { formatDate } from '@mimik/core/export/utils';+import { Star } from 'lucide-react';+import { FaviconImg } from '../../common/components/FaviconImg';+import { ScreenshotView } from '../../guide/components/ScreenshotView';+import { navigate } from '../../navigation/lib/navigate';+import { useFullview } from '../../stores/use-fullview';+import { CardMenu } from './CardMenu';+import { MimikEyes } from './MimikEyes';++interface GuideGridViewProps {+ columns: number;+ category: 'all' | 'starred' | 'trash';+ onStar: (e: React.MouseEvent, id: string) => void;+ onTrash: (e: React.MouseEvent, id: string) => void;+ onRestore: (e: React.MouseEvent, id: string) => void;+ onPermanentDelete: (e: React.MouseEvent, id: string) => void;++ onDuplicate: (e: React.MouseEvent, id: string) => void;+}++export function GuideGridView({+ columns,+ category,+ onStar,+ onTrash,+ onRestore,+ onPermanentDelete,++ onDuplicate,+}: GuideGridViewProps) {+ const { guides, thumbnails, places } = useFullview((s) => ({+ guides: s.guides,+ thumbnails: s.thumbnails,+ places: s.places,+ }));++ return (+ <div className="grid gap-[18px]" style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}>+ {guides.map((guide) => {+ const thumb = thumbnails.get(guide.id);+ const place = places.get(guide.id);+ return (+ <div+ key={guide.id}+ onClick={() => navigate({ page: 'guide', guideId: guide.id })}+ className="group rounded-xl bg-card cursor-pointer hover:shadow-md transition-shadow border border-border relative"+ >+ <div className="relative aspect-video overflow-hidden rounded-t-xl border-b border-secondary">+ {thumb ? (+ <ScreenshotView+ screenshot={thumb}+ alt={guide.title}+ crop+ cache+ frameRatio={16 / 9}+ className="!rounded-none !border-0"+ readOnly+ />+ ) : (+ <MimikEyes />+ )}+ {guide.starred && (+ <span className="absolute right-2 top-2 flex items-center justify-center w-[26px] h-[26px] rounded-lg bg-card/90 shadow-sm text-foreground">+ <Star size={13} fill="currentColor" />+ </span>+ )}+ </div>+ <div className="px-3.5 pt-3 pb-3.5 flex flex-col gap-1.5">+ <span className="flex items-center gap-1.5 min-w-0 h-4 text-[11.5px] text-muted-foreground">+ {place && (+ <>+ <FaviconImg domain={place.name} size={16} letterOnly={place.kind === 'app'} />+ <span className="truncate">{place.name}</span>+ </>+ )}+ </span>+ <div className="flex items-start gap-2">+ <p className="flex-1 min-w-0 min-h-10 text-sm font-semibold leading-5 text-foreground line-clamp-2">+ {guide.title}+ </p>+ <CardMenu+ guideId={guide.id}+ starred={guide.starred}+ category={category}+ onStar={onStar}+ onTrash={onTrash}+ onRestore={onRestore}+ onPermanentDelete={onPermanentDelete}++ onDuplicate={onDuplicate}+ />+ </div>+ <p className="text-xs text-muted-foreground">+ {guide.stepIds.length !== 1+ ? i18n.t('fullview_stepCountPlural', [String(guide.stepIds.length)])+ : i18n.t('fullview_stepCount', [String(guide.stepIds.length)])}{' '}+ · {formatDate(guide.updatedAt)}+ </p>+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --cc packages/ui/src/library/components/GuideListView.tsxindex 562afab,0000000..10dfb17mode 100644,000000..100644--- a/packages/ui/src/library/components/GuideListView.tsx+++ b/packages/ui/src/library/components/GuideListView.tsx@@@ -1,101 -1,0 +1,110 @@@+import { i18n } from '@mimik/core/env';+import { formatDate } from '@mimik/core/export/utils';+import { Star } from 'lucide-react';+import { FaviconImg } from '../../common/components/FaviconImg';+import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';+import { ScreenshotView } from '../../guide/components/ScreenshotView';+import { navigate } from '../../navigation/lib/navigate';+import { useFullview } from '../../stores/use-fullview';+import { CardMenu } from './CardMenu';+import { MimikEyes } from './MimikEyes';++interface GuideListViewProps {+ category: 'all' | 'starred' | 'trash';+ onStar: (e: React.MouseEvent, id: string) => void;+ onTrash: (e: React.MouseEvent, id: string) => void;+ onRestore: (e: React.MouseEvent, id: string) => void;+ onPermanentDelete: (e: React.MouseEvent, id: string) => void;++ onDuplicate: (e: React.MouseEvent, id: string) => void;+}+- export function GuideListView({ category, onStar, onTrash, onRestore, onPermanentDelete }: GuideListViewProps) {++export function GuideListView({++ category,++ onStar,++ onTrash,++ onRestore,++ onPermanentDelete,++ onDuplicate,++}: GuideListViewProps) {+ const { guides, thumbnails, places } = useFullview((s) => ({+ guides: s.guides,+ thumbnails: s.thumbnails,+ places: s.places,+ }));++ return (+ <div className="flex flex-col gap-2.5">+ {guides.map((guide) => {+ const thumb = thumbnails.get(guide.id);+ const place = places.get(guide.id);+ return (+ <div+ key={guide.id}+ onClick={() => navigate({ page: 'guide', guideId: guide.id })}+ className="flex items-center gap-4 px-3 py-2.5 rounded-xl border border-border bg-card cursor-pointer transition-shadow hover:shadow-md"+ >+ <div className="relative w-32 aspect-video shrink-0 overflow-hidden rounded-md border border-secondary [&_svg]:w-16 [&_svg]:h-auto">+ {thumb ? (+ <ScreenshotView+ screenshot={thumb}+ alt={guide.title}+ crop+ cache+ frameRatio={16 / 9}+ className="!rounded-none !border-0"+ readOnly+ />+ ) : (+ <MimikEyes />+ )}+ </div>+ <div className="flex-1 min-w-0 flex flex-col gap-1">+ <p className="text-sm font-semibold truncate text-foreground">{guide.title}</p>+ {guide.description && <p className="text-xs text-muted-foreground truncate">{guide.description}</p>}+ <p className="flex items-center gap-1.5 min-w-0 text-[11.5px] text-muted-foreground">+ {place && (+ <>+ <FaviconImg domain={place.name} size={16} letterOnly={place.kind === 'app'} />+ <span className="truncate">{place.name}</span>+ <span>·</span>+ </>+ )}+ <span className="shrink-0">+ {guide.stepIds.length !== 1+ ? i18n.t('fullview_stepCountPlural', [String(guide.stepIds.length)])+ : i18n.t('fullview_stepCount', [String(guide.stepIds.length)])}{' '}+ · {formatDate(guide.updatedAt)}+ </span>+ </p>+ </div>+ <div className="flex items-center gap-0.5">+ {category !== 'trash' && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={(e) => onStar(e, guide.id)}+ className="p-1.5 rounded-lg transition-colors text-foreground hover:bg-secondary"+ >+ <Star size={15} fill={guide.starred ? 'currentColor' : 'none'} />+ </button>+ </TooltipTrigger>+ <TooltipContent>{guide.starred ? i18n.t('common_unstar') : i18n.t('common_star')}</TooltipContent>+ </Tooltip>+ )}+ <CardMenu+ guideId={guide.id}+ starred={guide.starred}+ category={category}+ onStar={onStar}+ onTrash={onTrash}+ onRestore={onRestore}+ onPermanentDelete={onPermanentDelete}++ onDuplicate={onDuplicate}+ />+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --cc packages/ui/src/library/components/ImportGuideModal.tsxindex 0000000,9981b4e..d46e9damode 000000,100644..100644--- a/packages/ui/src/library/components/ImportGuideModal.tsx+++ b/packages/ui/src/library/components/ImportGuideModal.tsx@@@ -1,0 -1,165 +1,165 @@@++import { i18n } from '@mimik/core/env';++import { importGuide } from '@mimik/core/guides/service';++import { logger } from '@mimik/core/logger';++import type { ParsedBundle } from '@mimik/core/transfer/parse';++import { BundleError } from '@mimik/core/transfer/schema';+ import { AlertTriangle, FileWarning, Loader2, Package } from 'lucide-react';+ import { useEffect, useState } from 'react';-import { i18n } from '#imports';-import { importGuide } from '@/core/guides/service';-import type { ParsedBundle } from '@/core/transfer/parse';-import { BundleError } from '@/core/transfer/schema';-import { logger } from '@/lib/logger';-import { Button } from '@/ui/components/ui/button';-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog';++import { Button } from '../../components/ui/button';++import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../../components/ui/dialog';++ interface ImportGuideModalProps {+ file: File | null;+ onClose: () => void;+ onImported: (guideId: string) => void;+ }++ const errorKeys: Record<string, string> = {+ unreadable: 'import.errorUnreadable',+ 'not-a-bundle': 'import.errorNotABundle',+ 'unsupported-version': 'import.errorVersion',+ empty: 'import.errorEmpty',+ };+-export default function ImportGuideModal({ file, onClose, onImported }: ImportGuideModalProps) {++export function ImportGuideModal({ file, onClose, onImported }: ImportGuideModalProps) {+ const [bundle, setBundle] = useState<ParsedBundle | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [cover, setCover] = useState<string | null>(null);+ const [importing, setImporting] = useState(false);++ useEffect(() => {+ if (!file) return;+ let active = true;+ let url: string | null = null;++ setBundle(null);+ setError(null);+ setCover(null);++ (async () => {+ try {- const { readBundle } = await import('@/core/transfer/parse');++ const { readBundle } = await import('@mimik/core/transfer/parse');+ const parsed = await readBundle(file);+ if (!active) return;+ setBundle(parsed);++ const first = parsed.manifest.screenshots[0];+ const image = first ? parsed.images.get(first.file) : undefined;+ if (image) {+ url = URL.createObjectURL(image);+ setCover(url);+ }+ } catch (err) {+ if (!active) return;+ const kind = err instanceof BundleError ? err.kind : 'unreadable';+ setError(i18n.t(errorKeys[kind] as never));+ logger.error(' Bundle could not be read', err);+ }+ })();++ return () => {+ active = false;+ if (url) URL.revokeObjectURL(url);+ };+ }, [file]);++ const handleImport = async () => {+ if (!bundle) return;+ setImporting(true);+ try {+ onImported(await importGuide(bundle));+ } catch (err) {+ setError(i18n.t('import.errorFailed'));+ logger.error(' Import failed', err);+ } finally {+ setImporting(false);+ }+ };++ const manifest = bundle?.manifest;+ const stepCount = manifest?.steps.length ?? 0;++ const notes = manifest+ ? [+ manifest.redacted.screenshots ? i18n.t('import.noteRedacted') : null,+ manifest.redacted.inputValues ? i18n.t('import.noteInputs') : null,+ manifest.redacted.urls === 'path' ? i18n.t('import.noteUrls') : null,+ manifest.redacted.urls === 'origin' ? i18n.t('import.noteUrlsOrigin') : null,+ ].filter((note): note is string => note !== null)+ : [];++ return (+ <Dialog open={file !== null} onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-[460px]">+ <DialogHeader>+ <DialogTitle className="text-[15px] font-bold flex items-center gap-2">+ <Package size={16} className="text-accent" />+ {i18n.t('import.title')}+ </DialogTitle>+ <DialogDescription className="sr-only">{i18n.t('import.dialogDescription')}</DialogDescription>+ </DialogHeader>++ {error ? (+ <div className="flex items-start gap-2.5 rounded-lg border border-border bg-secondary/50 px-3.5 py-3">+ <FileWarning size={16} className="text-muted-foreground shrink-0 mt-0.5" />+ <p className="text-[13px] text-foreground leading-snug">{error}</p>+ </div>+ ) : !manifest ? (+ <div className="flex items-center gap-2 py-6 justify-center text-[13px] text-muted-foreground">+ <Loader2 size={14} className="animate-spin" />+ {i18n.t('import.reading')}+ </div>+ ) : (+ <div className="space-y-3">+ {cover && (+ <img+ src={cover}+ alt=""+ className="w-full rounded-lg border border-border object-cover max-h-40 bg-secondary"+ />+ )}++ <div>+ <div className="text-[15px] font-semibold text-foreground leading-snug">{manifest.guide.title}</div>+ <div className="text-[12px] text-muted-foreground mt-0.5">+ {stepCount === 1+ ? i18n.t('fullview.stepCount', [String(stepCount)])+ : i18n.t('fullview.stepCountPlural', [String(stepCount)])}+ {manifest.sourceDomain ? ` · ${manifest.sourceDomain}` : ''}+ </div>+ </div>++ {manifest.sourceDomain && (+ <div className="flex items-start gap-2.5 rounded-lg border border-border bg-secondary/50 px-3.5 py-2.5">+ <AlertTriangle size={14} className="text-accent shrink-0 mt-0.5" />+ <p className="text-[12px] text-muted-foreground leading-snug">+ {i18n.t('import.guideMeHint', [manifest.sourceDomain])}+ </p>+ </div>+ )}++ {notes.length > 0 && (+ <ul className="space-y-1 pl-1">+ {notes.map((note) => (+ <li key={note} className="text-[11.5px] text-muted-foreground leading-snug">+ · {note}+ </li>+ ))}+ </ul>+ )}+ </div>+ )}++ <div className="flex justify-end gap-2 pt-1">+ <Button size="sm" variant="ghost" onClick={onClose} className="border border-border">+ {i18n.t('import.cancel')}+ </Button>+ <Button size="sm" disabled={!manifest || importing} onClick={handleImport}>+ {importing && <Loader2 size={14} className="animate-spin" />}+ {i18n.t('import.confirm')}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+ }diff --cc packages/ui/src/library/components/LibraryContent.tsxindex b7737ab,0000000..36f493fmode 100644,000000..100644--- a/packages/ui/src/library/components/LibraryContent.tsx+++ b/packages/ui/src/library/components/LibraryContent.tsx@@@ -1,218 -1,0 +1,291 @@@+import { i18n } from '@mimik/core/env';+import {++ duplicateGuide,+ type GuideChangeEvent,+ getGuides,+ getStarredGuides,+ getTrashedGuides,+ onGuidesChanged,+ permanentlyDeleteGuide,+ restoreGuide,+ softDeleteGuide,+ toggleStar,+} from '@mimik/core/guides/service';+import type { Guide } from '@mimik/core/guides/types';- import { ChevronLeft, ChevronRight } from 'lucide-react';++import { logger } from '@mimik/core/logger';++import { ChevronLeft, ChevronRight, Upload } from 'lucide-react';+import { useCallback, useEffect, useRef, useState } from 'react';++import { navigate } from '../../navigation/lib/navigate';+import { useFullview } from '../../stores/use-fullview';+import { usePageFit } from '../hooks/use-page-fit';++import { bundleFrom } from '../lib/bundle-from';+import { loadCardData } from '../lib/load-card-data';+import { sortGuides } from '../lib/sort-guides';+import { ConfirmDeleteModal } from './ConfirmDeleteModal';+import { EmptyMascot } from './EmptyMascot';+import { GuideGridView } from './GuideGridView';+import { GuideListView } from './GuideListView';++import { ImportGuideModal } from './ImportGuideModal';++interface LibraryContentProps {+ category: 'all' | 'starred' | 'trash';+}++const emptyConfig: Record<string, { titleKey: string; subKey: string }> = {+ all: { titleKey: 'library_noGuidesTitle', subKey: 'library_noGuidesSub' },+ starred: { titleKey: 'library_noStarredTitle', subKey: 'library_noStarredSub' },+ trash: { titleKey: 'library_trashEmptyTitle', subKey: 'library_trashEmptySub' },+};++export function LibraryContent({ category }: LibraryContentProps) {+ const {+ setGuides,+ updateGuide,+ setThumbnails,+ setPlaces,+ sort,+ display,+ total,+ setTotal,+ page,+ pageKey,+ setPage,++ importFile,++ setImportFile,+ setCounts,+ } = useFullview((s) => ({+ setGuides: s.setGuides,+ updateGuide: s.updateGuide,+ setThumbnails: s.setThumbnails,+ setPlaces: s.setPlaces,+ sort: s.sort,+ display: s.display,+ total: s.total,+ setTotal: s.setTotal,+ page: s.page,+ pageKey: s.pageKey,+ setPage: s.setPage,++ importFile: s.importFile,++ setImportFile: s.setImportFile,+ setCounts: s.setCounts,+ }));++ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);++ const [dragging, setDragging] = useState(false);++ const [duplicateFailed, setDuplicateFailed] = useState(false);++ const dragDepth = useRef(0);++ const allGuidesRef = useRef<Guide[]>([]);+ const rootRef = useRef<HTMLDivElement>(null);+ const { columns, pageSize } = usePageFit(rootRef, display);+ const key = `${category}:${sort}`;+ const shownRef = useRef({ page, pageKey });+ shownRef.current = { page, pageKey };++ const refreshCounts = useCallback(async () => {+ const [all, starred, trashed] = await Promise.all([getGuides(), getStarredGuides(), getTrashedGuides()]);+ setCounts({ all: all.length, starred: starred.length, trash: trashed.length });+ }, [setCounts]);++ const loadGuides = useCallback(async () => {+ const [all, starred, trashed] = await Promise.all([getGuides(), getStarredGuides(), getTrashedGuides()]);+ setCounts({ all: all.length, starred: starred.length, trash: trashed.length });++ const current = category === 'starred' ? starred : category === 'trash' ? trashed : all;+ allGuidesRef.current = current;+ setTotal(current.length);++ const lastPage = Math.max(0, Math.ceil(current.length / pageSize) - 1);+ const shown = shownRef.current.pageKey === key ? Math.min(shownRef.current.page, lastPage) : 0;+ const paged = sortGuides(current, sort).slice(shown * pageSize, (shown + 1) * pageSize);+ setGuides(paged);+ setPage(shown, key);++ const cards = await loadCardData(paged);+ setThumbnails(cards.thumbnails);+ setPlaces(cards.places);+ }, [category, sort, key, pageSize, setTotal, setPage, setCounts, setGuides, setThumbnails, setPlaces]);++ useEffect(() => {+ loadGuides();+ }, [loadGuides]);++ useEffect(+ () =>+ onGuidesChanged((event: GuideChangeEvent) => {+ if (event.type === 'starred') {+ updateGuide(event.id, { starred: event.starred });+ refreshCounts();+ } else {+ loadGuides();+ }+ }),+ [refreshCounts, loadGuides, updateGuide],+ );++ const totalPages = Math.ceil((total ?? 0) / pageSize);++ const applyPage = useCallback(+ async (newPage: number) => {+ const sorted = sortGuides(allGuidesRef.current, sort);+ const start = newPage * pageSize;+ const paged = sorted.slice(start, start + pageSize);+ setGuides(paged);+ setPage(newPage, key);++ const cards = await loadCardData(paged);+ setThumbnails(cards.thumbnails);+ setPlaces(cards.places);+ },+ [sort, key, pageSize, setPage, setGuides, setThumbnails, setPlaces],+ );++ const handleStar = async (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ const guide = allGuidesRef.current.find((g) => g.id === id);+ if (guide) updateGuide(id, { starred: !guide.starred });+ await toggleStar(id);+ await refreshCounts();+ };+ const handleTrash = async (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ await softDeleteGuide(id);+ await loadGuides();+ };++ const handleDuplicate = async (e: React.MouseEvent, id: string) => {++ e.stopPropagation();++ setDuplicateFailed(false);++ try {++ if (!(await duplicateGuide(id))) throw new Error('guide not found');++ } catch (err) {++ logger.error(' Duplicate guide failed', err);++ setDuplicateFailed(true);++ return;++ }++ await loadGuides();++ await refreshCounts();++ };+ const handleRestore = async (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ await restoreGuide(id);+ await loadGuides();+ };+ const handlePermanentDelete = (e: React.MouseEvent, id: string) => {+ e.stopPropagation();+ setDeleteTarget(id);+ };+ const confirmPermanentDelete = async () => {+ if (!deleteTarget) return;+ setDeleteTarget(null);+ await permanentlyDeleteGuide(deleteTarget);+ await loadGuides();+ };+++ const handleDragEnter = (e: React.DragEvent) => {++ if (!e.dataTransfer.types.includes('Files')) return;++ dragDepth.current += 1;++ setDragging(true);++ };++ const handleDragLeave = () => {++ dragDepth.current = Math.max(0, dragDepth.current - 1);++ if (dragDepth.current === 0) setDragging(false);++ };++ const handleDrop = (e: React.DragEvent) => {++ e.preventDefault();++ dragDepth.current = 0;++ setDragging(false);++ setImportFile(bundleFrom(e.dataTransfer.files));++ };+++ const showPagination = total !== null && total > pageSize;++ return (- <div ref={rootRef} className={`flex-1 flex flex-col ${display === 'list' ? 'w-full max-w-6xl mx-auto' : ''}`}>++ <div++ ref={rootRef}++ className={`relative flex-1 flex flex-col ${display === 'list' ? 'w-full max-w-6xl mx-auto' : ''}`}++ onDragEnter={handleDragEnter}++ onDragLeave={handleDragLeave}++ onDragOver={(e) => {++ if (e.dataTransfer.types.includes('Files')) e.preventDefault();++ }}++ onDrop={handleDrop}++ >++ {dragging && (++ <div className="absolute inset-0 z-20 flex items-center justify-center rounded-xl border-2 border-dashed border-accent bg-secondary/90 pointer-events-none">++ <div className="flex items-center gap-2 text-[13px] font-semibold text-accent">++ <Upload size={16} />++ {i18n.t('import.dropHere')}++ </div>++ </div>++ )}++ {duplicateFailed && (++ <p role="alert" className="text-xs mb-3 text-center text-destructive">++ {i18n.t('library_duplicateFailed')}++ </p>++ )}+ {total === null ? (+ <p className="text-sm py-12 text-center text-purple">{i18n.t('common_loading')}</p>+ ) : total === 0 ? (+ <div className="text-center py-20 flex flex-col items-center">+ <EmptyMascot category={category} />+ <p className="text-lg font-medium text-foreground mt-4">{i18n.t(emptyConfig[category].titleKey as any)}</p>+ <p className="text-sm text-muted-foreground mt-1">{i18n.t(emptyConfig[category].subKey as any)}</p>+ </div>+ ) : display === 'list' ? (+ <GuideListView+ category={category}+ onStar={handleStar}+ onTrash={handleTrash}+ onRestore={handleRestore}+ onPermanentDelete={handlePermanentDelete}++ onDuplicate={handleDuplicate}+ />+ ) : (+ <GuideGridView+ columns={columns}+ category={category}+ onStar={handleStar}+ onTrash={handleTrash}+ onRestore={handleRestore}+ onPermanentDelete={handlePermanentDelete}++ onDuplicate={handleDuplicate}+ />+ )}++ {showPagination && (+ <div className="sticky bottom-0 mt-auto flex items-center justify-center gap-3 pt-6 pb-2 bg-background">+ <button+ onClick={() => applyPage(page - 1)}+ disabled={page === 0}+ className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors disabled:opacity-30 disabled:pointer-events-none"+ >+ <ChevronLeft size={15} />+ </button>+ <span className="text-xs font-medium text-muted-foreground">+ {i18n.t('fullview_pageOf', [String(page + 1), String(totalPages)])}+ </span>+ <button+ onClick={() => applyPage(page + 1)}+ disabled={page >= totalPages - 1}+ className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors disabled:opacity-30 disabled:pointer-events-none"+ >+ <ChevronRight size={15} />+ </button>+ </div>+ )}+ <ConfirmDeleteModal+ open={deleteTarget !== null}+ onClose={() => setDeleteTarget(null)}+ onConfirm={confirmPermanentDelete}+ />++ <ImportGuideModal++ file={importFile}++ onClose={() => setImportFile(null)}++ onImported={(guideId) => {++ setImportFile(null);++ navigate({ page: 'guide', guideId });++ }}++ />+ </div>+ );+}diff --cc packages/ui/src/library/components/LibraryTools.tsxindex 2d5f2e1,0000000..989b5f6mode 100644,000000..100644--- a/packages/ui/src/library/components/LibraryTools.tsx+++ b/packages/ui/src/library/components/LibraryTools.tsx@@@ -1,80 -1,0 +1,101 @@@+import { i18n } from '@mimik/core/env';- import { ArrowDownWideNarrow, ChevronDown, LayoutGrid, LayoutList } from 'lucide-react';++import { BUNDLE_EXTENSION } from '@mimik/core/transfer/schema';++import { ArrowDownWideNarrow, ChevronDown, LayoutGrid, LayoutList, Upload } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { Tooltip, TooltipContent, TooltipTrigger } from '../../components/ui/tooltip';+import { useFullview } from '../../stores/use-fullview';++import { bundleFrom } from '../lib/bundle-from';+import type { SortKey } from '../types';++const sortLabelKeys: Record<SortKey, string> = {+ recent: 'sort_recentFirst',+ oldest: 'sort_oldestFirst',+ alpha: 'sort_alphaAZ',+ steps: 'sort_mostSteps',+};++export function LibraryTools() {- const { sort, setSort, display, setDisplay } = useFullview((s) => ({++ const { sort, setSort, display, setDisplay, setImportFile } = useFullview((s) => ({+ sort: s.sort,+ setSort: s.setSort,+ display: s.display,+ setDisplay: s.setDisplay,++ setImportFile: s.setImportFile,+ }));+ const [sortOpen, setSortOpen] = useState(false);+ const sortRef = useRef<HTMLDivElement>(null);++ const fileRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const handler = (e: MouseEvent) => {+ if (sortRef.current && !sortRef.current.contains(e.target as Node)) setSortOpen(false);+ };+ document.addEventListener('mousedown', handler);+ return () => document.removeEventListener('mousedown', handler);+ }, []);++ return (+ <div className="flex items-center gap-2">++ <input++ ref={fileRef}++ type="file"++ accept={`.${BUNDLE_EXTENSION}`}++ className="hidden"++ onChange={(e) => {++ setImportFile(bundleFrom(e.target.files));++ e.target.value = '';++ }}++ />++ <button++ onClick={() => fileRef.current?.click()}++ className="flex items-center gap-1.5 text-[13px] font-medium text-muted-foreground px-3 h-8 rounded-lg border border-border bg-card hover:border-violet hover:text-purple transition-colors"++ >++ <Upload size={13} />++ {i18n.t('import.button')}++ </button>+ <div ref={sortRef} className="relative">+ <button+ onClick={() => setSortOpen(!sortOpen)}+ className="flex items-center gap-1.5 text-[13px] font-medium text-muted-foreground px-3 h-8 rounded-lg border border-border bg-card hover:border-violet hover:text-purple transition-colors"+ >+ <ArrowDownWideNarrow size={13} />+ {i18n.t(sortLabelKeys[sort] as any)}+ <ChevronDown size={10} className="ml-0.5" />+ </button>+ {sortOpen && (+ <div className="absolute right-0 top-full mt-1 bg-card border border-border rounded-lg shadow-lg py-1 z-10 min-w-[140px]">+ {(Object.keys(sortLabelKeys) as SortKey[]).map((key) => (+ <button+ key={key}+ onClick={() => {+ setSort(key);+ setSortOpen(false);+ }}+ className={`w-full text-left text-[13px] font-medium px-3 py-2 transition-colors ${+ sort === key+ ? 'text-foreground bg-secondary'+ : 'text-muted-foreground hover:bg-secondary/50 hover:text-foreground'+ }`}+ >+ {i18n.t(sortLabelKeys[key] as any)}+ </button>+ ))}+ </div>+ )}+ </div>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ onClick={() => setDisplay(display === 'list' ? 'grid' : 'list')}+ className="flex items-center justify-center w-8 h-8 rounded-lg border border-border bg-card text-muted-foreground hover:border-violet hover:text-purple transition-colors"+ >+ {display === 'list' ? <LayoutGrid size={15} /> : <LayoutList size={15} />}+ </button>+ </TooltipTrigger>+ <TooltipContent align="end">+ {display === 'list' ? i18n.t('sort_gridView') : i18n.t('sort_listView')}+ </TooltipContent>+ </Tooltip>+ </div>+ );+}diff --cc packages/ui/src/library/lib/bundle-from.tsindex 0000000,0000000..f63758dnew file mode 100644--- /dev/null+++ b/packages/ui/src/library/lib/bundle-from.ts@@@ -1,0 -1,0 +1,7 @@@++import { BUNDLE_EXTENSION } from '@mimik/core/transfer/schema';++++export function bundleFrom(list: FileList | null): File | null {++ const files = Array.from(list ?? []);++ if (files.length === 0) return null;++ return files.find((f) => f.name.toLowerCase().endsWith(`.${BUNDLE_EXTENSION}`)) ?? files[0];++}diff --cc packages/ui/src/library/store/library-slice.tsindex 228cd05,0000000..decc105mode 100644,000000..100644--- a/packages/ui/src/library/store/library-slice.ts+++ b/packages/ui/src/library/store/library-slice.ts@@@ -1,50 -1,0 +1,54 @@@+import type { Guide, Screenshot } from '@mimik/core/guides/types';+import type { StateCreator } from 'zustand';+import type { GuidePlace, LibraryDisplay, SortKey } from '../types';++const DISPLAY_KEY = 'mimik-display';++export interface LibrarySlice {+ guides: Guide[];+ setGuides: (guides: Guide[]) => void;+ updateGuide: (id: string, patch: Partial<Guide>) => void;+ thumbnails: Map<string, Screenshot>;+ setThumbnails: (thumbnails: Map<string, Screenshot>) => void;+ places: Map<string, GuidePlace>;+ setPlaces: (places: Map<string, GuidePlace>) => void;+ sort: SortKey;+ setSort: (sort: SortKey) => void;+ display: LibraryDisplay;+ setDisplay: (display: LibraryDisplay) => void;+ total: number | null;+ setTotal: (total: number) => void;+ page: number;+ pageKey: string;+ setPage: (page: number, pageKey: string) => void;++ importFile: File | null;++ setImportFile: (file: File | null) => void;+ counts: { all: number; starred: number; trash: number };+ setCounts: (counts: { all: number; starred: number; trash: number }) => void;+}++export const createLibrarySlice: StateCreator<LibrarySlice, [], [], LibrarySlice> = (set) => ({+ guides: [],+ setGuides: (guides) => set({ guides }),+ updateGuide: (id, patch) => set((s) => ({ guides: s.guides.map((g) => (g.id === id ? { ...g, ...patch } : g)) })),+ thumbnails: new Map(),+ setThumbnails: (thumbnails) => set({ thumbnails }),+ places: new Map(),+ setPlaces: (places) => set({ places }),+ sort: 'recent',+ setSort: (sort) => set({ sort }),+ display: localStorage.getItem(DISPLAY_KEY) === 'list' ? 'list' : 'grid',+ setDisplay: (display) => {+ localStorage.setItem(DISPLAY_KEY, display);+ set({ display });+ },+ total: null,+ setTotal: (total) => set({ total }),+ page: 0,+ pageKey: '',+ setPage: (page, pageKey) => set({ page, pageKey }),++ importFile: null,++ setImportFile: (importFile) => set({ importFile }),+ counts: { all: 0, starred: 0, trash: 0 },+ setCounts: (counts) => set({ counts }),+});diff --cc packages/ui/src/navigation/components/TopBar.tsxindex e36078a,c633a0c..7978f47--- a/packages/ui/src/navigation/components/TopBar.tsx+++ b/packages/ui/src/navigation/components/TopBar.tsx@@@ -1,27 -1,46 +1,30 @@@-import {- Check,- ChevronRight,- Copy,- Download,- FileText,- History,- MessageSquareQuote,- Pencil,- Search,- Star,- Trash2,-} from 'lucide-react';+import { i18n } from '@mimik/core/env';- import { createSnapshot } from '@mimik/core/guides/service';++import { createSnapshot, duplicateGuide } from '@mimik/core/guides/service';+import { logger } from '@mimik/core/logger';- import { Check, Download, History, Pencil, Search } from 'lucide-react';++import { Check, Copy, Download, History, MessageSquareQuote, Pencil, Search } from 'lucide-react';+import type { ReactNode } from 'react';- import { useState } from 'react';+ import { useEffect, useRef, useState } from 'react';-import { i18n } from '#imports';-import { createSnapshot, duplicateGuide } from '@/core/guides/service';-import { logger } from '@/lib/logger';-import { useFullview } from '@/stores/fullview';-import { Button } from '@/ui/components/ui/button';-import MascotIcon from '@/ui/shared/MascotIcon';-import ExportPreviewModal from './ExportPreviewModal';-import type { Route } from './router';-import { navigate } from './router';+import { Button } from '../../components/ui/button';+import { ExportPreviewModal } from '../../export/components/ExportPreviewModal';+import { LibraryTools } from '../../library/components/LibraryTools';+import { useFullview } from '../../stores/use-fullview';++import { navigate } from '../lib/navigate';+import type { Route } from '../types';-interface TopNavProps {+interface TopBarProps {route: Route;+ guideActions?: ReactNode;}-const DUPLICATE_SETTLE_MS = 700;+const NAV_CONTROL =+ 'h-8 rounded-lg border border-border bg-card text-[13px] text-foreground hover:bg-secondary hover:text-accent';-const navItems = [- { key: 'all' as const, labelKey: 'fullview_allGuides' as const, icon: FileText },- { key: 'starred' as const, labelKey: 'fullview_starred' as const, icon: Star },- { key: 'trash' as const, labelKey: 'fullview_trash' as const, icon: Trash2 },-];+const SEARCH_KEY = navigator.userAgent.includes('Mac') ? '⌘K' : 'Ctrl K';-const NAV_CONTROL = 'h-8 rounded-lg border border-border bg-card text-foreground hover:bg-secondary hover:text-accent';++const DUPLICATE_SETTLE_MS = 700;+-export default function TopNav({ route }: TopNavProps) {+export function TopBar({ route, guideActions }: TopBarProps) {const {- counts,- guideTitle,- guideStepCount,guideExportData: exportData,setSearchOpen,editing,@@@ -29,7 -48,13 +32,10 @@@historyOpen,setHistoryOpen,bumpHistoryRefresh,+ transcriptOpen,+ setTranscriptOpen,+ hasTranscript,} = useFullview((s) => ({- counts: s.counts,- guideTitle: s.guideTitle,- guideStepCount: s.guideStepCount,guideExportData: s.guideExportData,setSearchOpen: s.setSearchOpen,editing: s.editing,@@@ -54,49 -115,138 +96,87 @@@};return (- <header className="sticky top-0 z-30 flex items-center gap-3 px-7 h-16 shrink-0 bg-card border-b border-border">- <Button- size="sm"- variant="ghost"- onClick={() => setSearchOpen(true)}- className={`w-72 justify-start ${NAV_CONTROL}`}- >- <Search size={14} className="shrink-0 text-muted-foreground" />- <span className="flex-1 text-left text-muted-foreground">{i18n.t('fullview_searchPlaceholder')}</span>- <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-md bg-secondary text-muted-foreground">- {SEARCH_KEY}- </span>- </Button>+ <>- <header className="flex items-center gap-5 px-7 h-16 shrink-0 bg-card border-b border-border">- {/* Brand */}- <button- onClick={() => navigate({ page: 'library', category: 'all' })}- className="flex items-center gap-2 mr-4 cursor-pointer h-full"++ <header className="sticky top-0 z-30 flex items-center gap-3 px-7 h-16 shrink-0 bg-card border-b border-border">++ <Button++ size="sm"++ variant="ghost"++ onClick={() => setSearchOpen(true)}++ className={`w-72 justify-start ${NAV_CONTROL}`}+ >- <div className="mb-1">- <MascotIcon size={22} />- </div>- <span className="text-[15px] font-bold tracking-tight text-foreground">{i18n.t('app_name')}</span>- </button>-- {route.page === 'guide'- ? guideTitle && (- <>- <ChevronRight size={14} className="text-foreground opacity-25" />- {guideTitle === i18n.t('fullview_untitledGuide') && guideStepCount > 0 ? (- <span className="flex items-center gap-1">- {[0, 1, 2].map((i) => (- <span- key={i}- className="w-[5px] h-[5px] rounded-full bg-foreground animate-bounce"- style={{ animationDelay: `${i * 150}ms`, animationDuration: '1.2s' }}- />- ))}- </span>- ) : (- <span className="text-[13px] font-medium truncate max-w-sm text-foreground">{guideTitle}</span>- )}- </>- )- : navItems.map((item) => {- const active = route.page === 'library' && route.category === item.key;- const count = counts[item.key];- return (- <button- key={item.key}- onClick={() => navigate({ page: 'library', category: item.key })}- className={`flex items-center gap-1.5 text-[13px] h-8 px-3 rounded-md transition-all- ${active ? 'bg-primary text-primary-foreground font-semibold' : 'text-foreground font-medium hover:bg-secondary'}`}- >- <item.icon size={13.5} />- {i18n.t(item.labelKey)}- {count > 0 && (- <span- className={`text-[11px] ml-0.5 ${active ? 'text-primary-foreground/70' : 'text-muted-foreground'}`}- >- {count}- </span>- )}- </button>- );- })}++ <Search size={14} className="shrink-0 text-muted-foreground" />++ <span className="flex-1 text-left text-muted-foreground">{i18n.t('fullview_searchPlaceholder')}</span>++ <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-md bg-secondary text-muted-foreground">++ {SEARCH_KEY}++ </span>++ </Button>- <div className="ml-auto flex items-center gap-2">- {route.page === 'library' && <LibraryTools />}- {route.page === 'guide' && exportData && (- <>- {guideActions}- <Button size="sm" variant="ghost" onClick={() => toggleEditing(exportData.guideId)} className={NAV_CONTROL}>- {editing ? <Check size={14} /> : <Pencil size={14} />}- {editing ? i18n.t('editor.done') : i18n.t('editor.edit')}- </Button>- <Button size="sm" variant="ghost" onClick={() => setHistoryOpen(!historyOpen)} className={NAV_CONTROL}>- <History size={14} />- {i18n.t('editor.versionHistory')}- </Button>- {!editing && (- <Button size="sm" onClick={() => setExportOpen(true)} className="h-8 rounded-lg text-[13px]">- <Download size={14} />- {i18n.t('common.export')}- {/* Right side */}- <div className="ml-auto flex items-center gap-3">- <Button- size="sm"- variant="ghost"- onClick={() => setSearchOpen(true)}- className={`w-52 justify-start ${NAV_CONTROL}`}- >- <Search size={14} className="shrink-0 text-muted-foreground" />- <span className="flex-1 text-left text-muted-foreground">{i18n.t('fullview_searchPlaceholder')}</span>- <span className="text-[10px] font-semibold px-1.5 py-0.5 rounded-md bg-secondary text-muted-foreground">- ⌘K- </span>- </Button>++ <div className="ml-auto flex items-center gap-2">++ {route.page === 'library' && <LibraryTools />}+ {route.page === 'guide' && exportData && (+ <>++ {guideActions}+ <Button+ size="sm"+ variant="ghost"+ onClick={() => toggleEditing(exportData.guideId)}+ className={NAV_CONTROL}+ >+ {editing ? <Check size={14} /> : <Pencil size={14} />}+ {editing ? i18n.t('editor.done') : i18n.t('editor.edit')}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setHistoryOpen(!historyOpen)} className={NAV_CONTROL}>+ <History size={14} />+ {i18n.t('editor.versionHistory')}</Button>- )}- <ExportPreviewModal- open={exportOpen}- onOpenChange={setExportOpen}- guide={exportData.guide}- steps={exportData.steps}- screenshots={exportData.screenshots}- />- </>- )}- </div>- </header>+ {hasTranscript && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setTranscriptOpen(!transcriptOpen)}+ className={NAV_CONTROL}+ >+ <MessageSquareQuote size={14} />+ {i18n.t('transcript.title')}+ </Button>+ )}+ {!editing && (+ <>+ <Button+ size="sm"+ variant="ghost"+ disabled={duplicating}+ onClick={() => handleDuplicate(exportData.guideId)}+ className={NAV_CONTROL}+ >+ <Copy size={14} />+ {i18n.t('library.duplicate')}+ </Button>- <Button size="sm" onClick={() => setExportOpen(true)} className="h-8 rounded-lg">++ <Button size="sm" onClick={() => setExportOpen(true)} className="h-8 rounded-lg text-[13px]">+ <Download size={14} />+ {i18n.t('common.export')}+ </Button>+ </>+ )}+ <ExportPreviewModal+ open={exportOpen}+ onOpenChange={setExportOpen}+ guide={exportData.guide}+ steps={exportData.steps}+ screenshots={exportData.screenshots}+ />+ </>+ )}+ </div>+ </header>+ {duplicateFailed && (+ <p+ role="alert"+ className="text-xs py-2 px-7 text-center shrink-0 bg-card border-b border-border text-destructive"+ >+ {i18n.t('library.duplicateFailed')}+ </p>+ )}+ </>);}diff --cc packages/ui/src/navigation/components/__tests__/topbar-duplicate.test.tsxindex 0000000,1dd3ba1..b386bfamode 000000,100644..100644--- a/packages/ui/src/navigation/components/__tests__/topbar-duplicate.test.tsx+++ b/packages/ui/src/navigation/components/__tests__/topbar-duplicate.test.tsx@@@ -1,0 -1,170 +1,172 @@@+ // @vitest-environment jsdom+ import { fireEvent, render, screen } from '@testing-library/react';+ import { act } from 'react';+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++ const duplicateGuide = vi.fn();+ const navigate = vi.fn();+-vi.mock('@/core/guides/service', () => ({++vi.mock('@mimik/core/guides/service', () => ({+ createSnapshot: vi.fn().mockResolvedValue(null),+ duplicateGuide: (...args: unknown[]) => duplicateGuide(...args),+ }));+-vi.mock('../router', () => ({++vi.mock('../../lib/navigate', () => ({+ navigate: (...args: unknown[]) => navigate(...args),+ }));+-vi.mock('../ExportPreviewModal', () => ({ default: () => null }));++vi.mock('../../../export/components/ExportPreviewModal', () => ({ ExportPreviewModal: () => null }));++++vi.mock('../../../library/components/LibraryTools', () => ({ LibraryTools: () => null }));++ const storeState = {+ counts: { all: 1, starred: 0, trash: 0 },+ guideTitle: 'LONG ORIGINAL',+ guideStepCount: 12,+ guideExportData: { guideId: 'g1', guide: {}, steps: [], screenshots: new Map() },+ setSearchOpen: vi.fn(),+ editing: false,+ setEditing: vi.fn(),+ historyOpen: false,+ setHistoryOpen: vi.fn(),+ bumpHistoryRefresh: vi.fn(),+ transcriptOpen: false,+ setTranscriptOpen: vi.fn(),+ hasTranscript: false,+ };+-vi.mock('@/stores/fullview', () => ({++vi.mock('../../../stores/use-fullview', () => ({+ useFullview: (selector: (s: typeof storeState) => unknown) => selector(storeState),+ }));+-import TopNav from '../TopNav';++import { TopBar } from '../TopBar';++ const route = { page: 'guide', guideId: 'g1' } as const;++ function duplicateButton(): HTMLButtonElement {+ const btn = screen.getAllByRole('button').find((b) => /duplicat|duplicar|副本|dupliz/i.test(b.textContent ?? ''));+ if (!btn) throw new Error('Duplicate button not rendered');+ return btn as HTMLButtonElement;+ }++ async function settleMicrotasks() {+ await act(async () => {+ await Promise.resolve();+ });+ }++ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ duplicateGuide.mockReset().mockResolvedValue('copy-1');+ navigate.mockReset();+ });++ afterEach(() => {+ vi.useRealTimers();+ });+-describe('TopNav duplicate', () => {++describe('TopBar duplicate', () => {+ it('navigates into the copy it just made', async () => {- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();++ expect(duplicateGuide).toHaveBeenCalledWith('g1');+ expect(navigate).toHaveBeenCalledWith({ page: 'guide', guideId: 'copy-1' });+ });++ it('makes one copy from a fast multi-click, not a chain of copies of copies', async () => {- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ fireEvent.click(duplicateButton());+ fireEvent.click(duplicateButton());+ await settleMicrotasks();++ expect(duplicateGuide).toHaveBeenCalledTimes(1);+ });++ it('keeps the button disabled across the navigation, then releases it', async () => {- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ expect(duplicateButton().disabled).toBe(true);++ await act(async () => {+ vi.advanceTimersByTime(700);+ });+ expect(duplicateButton().disabled).toBe(false);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ expect(duplicateGuide).toHaveBeenCalledTimes(2);+ });++ it('re-enables immediately when the copy could not be made, and says so', async () => {+ duplicateGuide.mockRejectedValue(new Error('boom'));- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();++ expect(navigate).not.toHaveBeenCalled();+ expect(duplicateButton().disabled).toBe(false);+ expect(screen.getByRole('alert')).toBeTruthy();+ });++ it('reports a guide that was not there, which resolves null rather than throwing', async () => {+ duplicateGuide.mockResolvedValue(null);- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();++ expect(navigate).not.toHaveBeenCalled();+ expect(screen.getByRole('alert')).toBeTruthy();+ });++ it('does not carry the message onto another guide, since the nav never unmounts', async () => {+ duplicateGuide.mockRejectedValue(new Error('boom'));- const { rerender } = render(<TopNav route={route} />);++ const { rerender } = render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ expect(screen.getByRole('alert')).toBeTruthy();+- rerender(<TopNav route={{ page: 'guide', guideId: 'g2' } as const} />);++ rerender(<TopBar route={{ page: 'guide', guideId: 'g2' } as const} />);++ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('does not bring the message back when you return to the guide that failed', async () => {+ duplicateGuide.mockRejectedValue(new Error('boom'));- const { rerender } = render(<TopNav route={route} />);++ const { rerender } = render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ expect(screen.getByRole('alert')).toBeTruthy();+- rerender(<TopNav route={{ page: 'library', category: 'all' } as const} />);- rerender(<TopNav route={route} />);++ rerender(<TopBar route={{ page: 'library', category: 'all' } as const} />);++ rerender(<TopBar route={route} />);++ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('clears the message when a later attempt succeeds', async () => {+ duplicateGuide.mockRejectedValueOnce(new Error('boom'));- render(<TopNav route={route} />);++ render(<TopBar route={route} />);++ fireEvent.click(duplicateButton());+ await settleMicrotasks();+ expect(screen.getByRole('alert')).toBeTruthy();++ duplicateGuide.mockResolvedValue('copy-1');+ fireEvent.click(duplicateButton());+ await settleMicrotasks();++ expect(screen.queryByRole('alert')).toBeNull();+ });+ });diff --cc src/blur/__tests__/manager.test.tsindex 0000000,867853f..867853fmode 000000,100644..100644--- a/src/blur/__tests__/manager.test.ts+++ b/src/blur/__tests__/manager.test.tsdiff --cc src/blur/__tests__/restore.test.tsindex 0000000,919f121..919f121mode 000000,100644..100644--- a/src/blur/__tests__/restore.test.ts+++ b/src/blur/__tests__/restore.test.tsdiff --cc src/blur/manager.tsindex 33ce6e2,f701994..e5483c5--- a/src/blur/manager.ts+++ b/src/blur/manager.ts@@@ -13,18 -21,23 +13,24 @@@ export class BlurManagerprivate picker = new ElementPicker();private panel: BlurPanel | null = null;private active = false;+ private generation = 0;+ constructor(private detector: BlurDetector = new BlurScanner()) {}+async start() {if (this.active) return;this.active = true;+ const generation = ++this.generation;+injectBlurStyles();const presets = await this.loadPresets();+ if (!this.active || generation !== this.generation) return;+const activeKeys = (Object.entries(presets) as [PresetKey, boolean][]).filter(([, on]) => on).map(([k]) => k);- this.scanner.start(activeKeys);+ this.detector.start(activeKeys);+ this.panel?.unmount();this.panel = new BlurPanel(presets);this.panel.mount();@@@ -32,9 -45,8 +38,8 @@@}stop() {- if (!this.active) return;- this.teardown();+ if (this.active) this.teardown();- this.scanner.stop();+ this.detector.stop();removeBlurStyles();}diff --cc src/blur/restore.tsindex 0000000,866410f..866410fmode 000000,100644..100644--- a/src/blur/restore.ts+++ b/src/blur/restore.tsdiff --cc src/capture/__tests__/session-sync.test.tsindex 0000000,2b882ae..3a7731cmode 000000,100644..100644--- a/src/capture/__tests__/session-sync.test.ts+++ b/src/capture/__tests__/session-sync.test.ts@@@ -1,0 -1,147 +1,147 @@@+ // @vitest-environment jsdom+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { CaptureState } from '@/core/capture/machine';+ import type { GetStateResponse } from '@/lib/messaging';-import { CaptureState } from '../machine';++ const sendMessage = vi.fn();+ const startCapture = vi.fn((_guideId: string, _isTopFrame: boolean) => ({ stop: vi.fn() }));++ vi.mock('@/lib/messaging', () => ({ sendMessage: (...args: unknown[]) => sendMessage(...args) }));+ vi.mock('../events/handlers', () => ({+ startCapture: (guideId: string, isTopFrame: boolean) => startCapture(guideId, isTopFrame),+ }));+ const stopAnswering = vi.fn();+ const answerChildFrames = vi.fn(() => stopAnswering);-vi.mock('../dom/frame-placement', () => ({ answerChildFrames: () => answerChildFrames() }));-vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@/core/capture/dom/frame-placement', () => ({ answerChildFrames: () => answerChildFrames() }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++ async function bootFrame(state: GetStateResponse, onSynced?: (s: GetStateResponse) => void) {+ sendMessage.mockResolvedValue(state);+ const { CaptureSession } = await import('../session');+ const session = new CaptureSession(onSynced);+ await vi.waitFor(() => expect(sendMessage).toHaveBeenCalled());+ await Promise.resolve();+ return session;+ }++ const recording: GetStateResponse = {+ state: CaptureState.RECORDING,+ stepCount: 2,+ currentGuideId: 'guide-1',+ pauseReason: null,+ };++ const pausedForBlur: GetStateResponse = {+ state: CaptureState.PAUSED,+ stepCount: 2,+ currentGuideId: 'guide-1',+ pauseReason: 'blur',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('CaptureSession boot sync', () => {+ it('starts capturing when the background is RECORDING', async () => {+ const session = await bootFrame(recording);++ expect(startCapture).toHaveBeenCalledWith('guide-1', true);+ expect(session.isActive).toBe(true);+ });++ it('does not start capturing when the background is PAUSED', async () => {+ const session = await bootFrame(pausedForBlur);++ expect(startCapture).not.toHaveBeenCalled();+ expect(session.isActive).toBe(false);+ });++ it('hands the paused state to the caller so the blur overlay can re-open', async () => {+ const onSynced = vi.fn();+ await bootFrame(pausedForBlur, onSynced);++ expect(onSynced).toHaveBeenCalledWith(pausedForBlur);+ });++ it('stays idle when the background is IDLE', async () => {+ const session = await bootFrame({+ state: CaptureState.IDLE,+ stepCount: 0,+ currentGuideId: null,+ pauseReason: null,+ });++ expect(startCapture).not.toHaveBeenCalled();+ expect(session.isActive).toBe(false);+ });+ });++ describe('CaptureSession answering child frames', () => {+ async function idleSession() {+ vi.useFakeTimers();+ sendMessage.mockReturnValue(new Promise(() => {}));+ const { CaptureSession } = await import('../session');+ return new CaptureSession();+ }++ afterEach(() => {+ vi.useRealTimers();+ });++ it('answers nobody before a recording starts', async () => {+ await idleSession();++ expect(answerChildFrames).not.toHaveBeenCalled();+ });++ it('keeps answering past a stop, so a child can still place its last typing step', async () => {+ const session = await idleSession();+ session.start('guide-1');+ session.stop();++ await vi.advanceTimersByTimeAsync(1000);+ expect(stopAnswering).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(2000);+ expect(stopAnswering).toHaveBeenCalledTimes(1);+ });++ it('keeps a single responder across a pause and resume', async () => {+ const session = await idleSession();+ session.start('guide-1');+ session.stop();+ await vi.advanceTimersByTimeAsync(500);+ session.start('guide-1');++ await vi.advanceTimersByTimeAsync(5000);+ expect(answerChildFrames).toHaveBeenCalledTimes(1);+ expect(stopAnswering).not.toHaveBeenCalled();+ });++ it('counts the grace from the last stop, not an earlier one', async () => {+ const session = await idleSession();+ session.start('guide-1');+ session.stop();+ await vi.advanceTimersByTimeAsync(500);+ session.start('guide-1');+ await vi.advanceTimersByTimeAsync(500);+ session.stop();++ await vi.advanceTimersByTimeAsync(1500);+ expect(stopAnswering).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(600);+ expect(stopAnswering).toHaveBeenCalledTimes(1);+ });++ it('stops answering at once when disposed', async () => {+ const session = await idleSession();+ session.start('guide-1');+ session.dispose();+ expect(stopAnswering).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(5000);+ expect(stopAnswering).toHaveBeenCalledTimes(1);+ });+ });diff --cc src/capture/events/__tests__/input-session-i18n.test.tsindex 0000000,de8f811..98bd385mode 000000,100644..100644--- a/src/capture/events/__tests__/input-session-i18n.test.ts+++ b/src/capture/events/__tests__/input-session-i18n.test.ts@@@ -1,0 -1,81 +1,85 @@@+ // @vitest-environment jsdom+ import { beforeEach, describe, expect, it, vi } from 'vitest';+-const sendMessageMock = vi.fn().mockResolvedValue({ stepId: 'step-1' });-vi.mock('@/lib/messaging', () => ({ sendMessage: (...args: unknown[]) => sendMessageMock(...args) }));-++const updateInputStep = vi.fn().mockResolvedValue({ updated: true });++const sink = {++ captureStep: vi.fn().mockResolvedValue({ stepId: 'step-1' }),++ updateInputStep,++ finalizeInputStep: vi.fn().mockResolvedValue({ updated: true }),++} as unknown as CaptureSink;++++import type { CaptureSink } from '@/core/capture/sink';+ import { InputSession } from '../input-session';++ function field(value: string, label = 'Email'): HTMLInputElement {+ const input = document.createElement('input');+ input.setAttribute('aria-label', label);+ input.value = value;+ document.body.appendChild(input);+ return input;+ }++ function lastUpdate(): { description: string; inputValue?: string } {- const calls = sendMessageMock.mock.calls.filter(([name]) => name === 'updateInputStep');- return calls.at(-1)?.[1] as { description: string; inputValue?: string };++ return updateInputStep.mock.calls.at(-1)?.[0] as { description: string; inputValue?: string };+ }++ function session(): InputSession {- const s = new InputSession('guide-1');++ const s = new InputSession('guide-1', sink);+ s.stepId = 'step-1';+ return s;+ }++ describe('InputSession describes typing through i18n', () => {+ beforeEach(() => {- sendMessageMock.mockClear();++ updateInputStep.mockClear();+ document.body.innerHTML = '';+ });++ it('asks for the typed-value message with the value first and the label second', () => {+ session().update(field('bonjour'));+ expect(lastUpdate().description).toBe('steps.typeValueInto[bonjour,Email]');+ });++ it('asks for the cleared-field message with just the label', () => {+ session().update(field(''));+ expect(lastUpdate().description).toBe('steps.clearField[Email]');+ });++ it('sends the typed value alongside the description, for redaction on export', () => {+ session().update(field('bonjour'));+ expect(lastUpdate().inputValue).toBe('bonjour');+ });++ it('sends no value for a cleared field', () => {+ session().update(field(''));+ expect(lastUpdate().inputValue).toBeUndefined();+ });++ it('describes a password field without echoing the value', () => {+ const input = document.createElement('input');+ input.type = 'password';+ input.setAttribute('aria-label', 'Password');+ input.value = 'hunter2';+ document.body.appendChild(input);++ session().update(input);+ const update = lastUpdate();+ expect(update.description).toBe('steps.typeSecret');+ expect(update.description).not.toContain('hunter2');+ expect(update.inputValue).toBeUndefined();+ });++ it('describes a blurred field without echoing the value', () => {+ const wrapper = document.createElement('div');+ wrapper.setAttribute('data-mimik-blur', '');+ const input = field('bonjour', 'Notes');+ wrapper.appendChild(input);+ document.body.appendChild(wrapper);++ session().update(input);+ const update = lastUpdate();+ expect(update.description).toBe('steps.typeInto[Notes]');+ expect(update.description).not.toContain('bonjour');+ expect(update.inputValue).toBeUndefined();+ });+ });diff --cc src/capture/events/handlers.tsindex 0e90983,5b54d74..d7c07ea--- a/src/capture/events/handlers.ts+++ b/src/capture/events/handlers.ts@@@ -11,12 -14,9 +11,13 @@@ importisSensitiveField,isTextField,isTooLarge,-} from '../dom/element-utils';-import { locateFrame, placeInTab } from '../dom/frame-placement';-import { isReplayedClick, replayClick, replayInit, shouldInterceptClick } from './click-intercept';+} from '@/core/capture/dom/element-utils';++import { locateFrame, placeInTab } from '@/core/capture/dom/frame-placement';+import { isReplayedClick, replayClick, replayInit, shouldInterceptClick } from '@/core/capture/events/click-intercept';+import type { CaptureSink } from '@/core/capture/sink';+import { DEFAULT_TARGET_COLOR } from '@/core/screenshot/types';+import { localStorage } from '@/lib/browser-api/local-storage';+import { HoverRing } from '@/lib/hover-ring';import { InputSession } from './input-session';const DEDUP_MS = 300;@@@ -107,11 -106,12 +108,12 @@@ class CaptureControllerprivate capture(action: string, target: HTMLElement, point?: { x: number; y: number }) {const atEvent = freezeRect(target);return async () => {+ const placement = locateFrame();const elementMeta = extractElementMeta(target, atEvent);- await sendMessage('captureStep', {+ await this.sink.captureStep({guideId: this.guideId,action,- elementMeta: point ? { ...elementMeta, clickPoint: point } : elementMeta,+ elementMeta: placeInTab(point ? { ...elementMeta, clickPoint: point } : elementMeta, await placement),domContext: extractDOMContext(target, action),});};diff --cc src/capture/events/input-session.tsindex ea200d6,1194b94..923d82c--- a/src/capture/events/input-session.ts+++ b/src/capture/events/input-session.ts@@@ -1,9 -1,10 +1,10 @@@+import { logger } from '@mimik/core/logger';import { i18n } from '#imports';-import { logger } from '@/lib/logger';-import { sendMessage } from '@/lib/messaging';-import { extractDOMContext } from '../dom/context';-import { extractElementMeta, type FrozenRect, freezeRect } from '../dom/element-meta';-import { getFieldLabel, getFieldValue, isRedactedField, isSensitiveField } from '../dom/element-utils';-import { locateFrame, placeInTab } from '../dom/frame-placement';+import { extractDOMContext } from '@/core/capture/dom/context';+import { extractElementMeta, type FrozenRect, freezeRect } from '@/core/capture/dom/element-meta';+import { getFieldLabel, getFieldValue, isRedactedField, isSensitiveField } from '@/core/capture/dom/element-utils';++import { locateFrame, placeInTab } from '@/core/capture/dom/frame-placement';+import type { CaptureSink } from '@/core/capture/sink';export class InputSession {stepId: string | null = null;@@@ -25,10 -23,12 +26,12 @@@async start(target: HTMLElement, atEvent?: FrozenRect) {this.atEvent = atEvent;+ const placement = locateFrame();+ const elementMeta = extractElementMeta(target, atEvent);- const res = await sendMessage('captureStep', {+ const res = await this.sink.captureStep({guideId: this.guideId,action: 'input',- elementMeta: extractElementMeta(target, atEvent),+ elementMeta: placeInTab(elementMeta, await placement),domContext: extractDOMContext(target, 'input'),});if ('stepId' in res) {@@@ -49,10 -49,10 +52,10 @@@return;}const val = getFieldValue(target);- const desc = val ? `Type "${val}" in ${label}` : `Clear ${label}`;+ const desc = val ? i18n.t('steps.typeValueInto', [val, label]) : i18n.t('steps.clearField', [label]);- sendMessage('updateInputStep', { stepId: this.stepId, description: desc, inputValue: val || undefined }).catch(- (err) => logger.warn('Failed to update input step', err),- );+ this.sink+ .updateInputStep({ stepId: this.stepId, description: desc, inputValue: val || undefined })+ .catch((err) => logger.warn('Failed to update input step', err));}async finalize() {@@@ -63,9 -63,11 +66,11 @@@this.stepId = null;this.target = null;this.atEvent = undefined;+ const placement = locateFrame();+ const elementMeta = extractElementMeta(target, atEvent);- await sendMessage('finalizeInputStep', {+ await this.sink.finalizeInputStep({stepId,- elementMeta: extractElementMeta(target, atEvent),+ elementMeta: placeInTab(elementMeta, await placement),domContext: extractDOMContext(target, 'input'),});}diff --cc src/capture/session.tsindex bc7c65e,bcd0fa3..d28a648--- a/src/capture/session.ts+++ b/src/capture/session.ts@@@ -1,8 -1,11 +1,11 @@@-import { logger } from '@/lib/logger';+import { logger } from '@mimik/core/logger';++import { answerChildFrames } from '@/core/capture/dom/frame-placement';+import { CaptureState } from '@/core/capture/machine';- import { sendMessage } from '@/lib/messaging';+ import { type GetStateResponse, sendMessage } from '@/lib/messaging';-import { answerChildFrames } from './dom/frame-placement';import { type CaptureHandle, startCapture } from './events/handlers';-import { CaptureState } from './machine';+ const FRAME_ANSWER_GRACE_MS = 2000;+export class CaptureSession {private capture: CaptureHandle | null = null;private activeGuideId: string | null = null;diff --cc src/entrypoints/background/__tests__/guide-meta.test.tsindex f02e1d5,32426e3..fe6c1f1--- a/src/entrypoints/background/__tests__/guide-meta.test.ts+++ b/src/entrypoints/background/__tests__/guide-meta.test.ts@@@ -16,12 -17,10 +17,13 @@@ constlocalStorageGetMock: vi.fn(),updateGuideDescriptionMock: vi.fn(),updateGuideTitleMock: vi.fn(),+ whenNarrationSettledMock: vi.fn(),}));-vi.mock('@/core/capture/ai/meta', () => ({ generateGuideMeta: generateGuideMetaMock }));+vi.mock('@/core/capture/ai/meta', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/core/capture/ai/meta')>()),+ generateGuideMeta: generateGuideMetaMock,+}));vi.mock('@/core/guides/service', () => ({clearStepAiPending: clearStepAiPendingMock,@@@ -31,14 -30,12 +33,16 @@@updateGuideTitle: updateGuideTitleMock,}));-vi.mock('@/lib/browser-api', () => ({ localStorage: { get: localStorageGetMock } }));+vi.mock('@/core/env', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: localStorageGetMock },+}));+ vi.mock('../voice', () => ({ whenNarrationSettled: whenNarrationSettledMock }));++import { generateDescriptionOnDemand } from '@/core/capture/ai/guide-description';import { AI_PROVIDERS } from '@/core/capture/ai/models';-import { generateDescriptionOnDemand, generateGuideMetaOnStop } from '../guide-meta';+import { generateGuideMetaOnStop } from '../guide-meta';const GUIDE_ID = 'guide-1';diff --cc src/entrypoints/background/__tests__/narration-settle.test.tsindex 0000000,63b55dc..a61451amode 000000,100644..100644--- a/src/entrypoints/background/__tests__/narration-settle.test.ts+++ b/src/entrypoints/background/__tests__/narration-settle.test.ts@@@ -1,0 -1,132 +1,140 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ const ensureVoiceHost = vi.fn();+ const queryMicPermission = vi.fn();+ const startVoiceCapture = vi.fn();+ const stopVoiceCapture = vi.fn();+ const hasVoiceHost = vi.fn();+ const closeVoiceHostIfIdle = vi.fn();+ const storageGet = vi.fn();+-vi.mock('@/lib/offscreen', () => ({- supportsVoice: () => true,++vi.mock('@/lib/offscreen/supports-voice', () => ({ supportsVoice: () => true }));++vi.mock('@/lib/offscreen/ensure-voice-host', () => ({+ ensureVoiceHost: (...args: unknown[]) => ensureVoiceHost(...args),++}));++vi.mock('@/lib/offscreen/query-mic-permission', () => ({+ queryMicPermission: (...args: unknown[]) => queryMicPermission(...args),++}));++vi.mock('@/lib/offscreen/start-voice-capture', () => ({+ startVoiceCapture: (...args: unknown[]) => startVoiceCapture(...args),++}));++vi.mock('@/lib/offscreen/stop-voice-capture', () => ({+ stopVoiceCapture: (...args: unknown[]) => stopVoiceCapture(...args),- hasVoiceHost: (...args: unknown[]) => hasVoiceHost(...args),++}));++vi.mock('@/lib/offscreen/has-voice-host', () => ({ hasVoiceHost: (...args: unknown[]) => hasVoiceHost(...args) }));++vi.mock('@/lib/offscreen/close-voice-host-if-idle', () => ({+ closeVoiceHostIfIdle: (...args: unknown[]) => closeVoiceHostIfIdle(...args),- closeVoiceHost: vi.fn(),- flushVoiceCapture: vi.fn(),- openMicPermissionPage: vi.fn(),- registerVoicePanelRelay: vi.fn(),+ }));++vi.mock('@/lib/offscreen/close-voice-host', () => ({ closeVoiceHost: vi.fn() }));++vi.mock('@/lib/offscreen/flush-voice-capture', () => ({ flushVoiceCapture: vi.fn() }));++vi.mock('@/lib/offscreen/open-mic-permission-page', () => ({ openMicPermissionPage: vi.fn() }));++vi.mock('@/lib/offscreen/register-voice-panel-relay', () => ({ registerVoicePanelRelay: vi.fn() }));+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/lib/browser-api/local-storage', () => ({+ localStorage: { get: (...args: unknown[]) => storageGet(...args), set: vi.fn() },- onMessage: vi.fn(),+ }));++vi.mock('@/lib/browser-api/on-message', () => ({ onMessage: vi.fn() }));+-vi.mock('@/lib/port', () => ({ broadcastVoiceToPanel: vi.fn() }));++vi.mock('@/lib/port/broadcast-voice-to-panel', () => ({ broadcastVoiceToPanel: vi.fn() }));+-vi.mock('@/lib/voice-narration', () => ({++vi.mock('@/lib/voice/read-transcription-settings', () => ({+ readTranscriptionSettings: () => Promise.resolve({ provider: 'openai', apiKey: 'sk-test' }),- narrateRecording: vi.fn(),+ }));++vi.mock('@/lib/voice/narrate-recording', () => ({ narrateRecording: vi.fn() }));++ vi.mock('@/core/guides/service', () => ({+ saveTranscript: vi.fn().mockResolvedValue(undefined),+ applyNarrationToSteps: vi.fn().mockResolvedValue(undefined),+ findExistingStepIds: vi.fn().mockResolvedValue([]),+ getStepsForGuide: vi.fn().mockResolvedValue([]),+ }));++ vi.mock('../deferred-descriptions', () => ({ discardDeferred: vi.fn() }));+ vi.mock('../describe-unnarrated', () => ({ describeStepNow: vi.fn(), describeUnnarratedSteps: vi.fn() }));++ import {+ applyNarration,+ getVoiceUpdate,+ startVoiceNarration,+ stopVoiceNarration,+ whenNarrationSettled,+ } from '../voice';++ const EMPTY_RESULT = {+ descriptions: [],+ transcript: { epochMs: 1_700_000_000_000, lines: [] },+ stats: {+ batches: 0,+ failedBatches: 0,+ droppedBatches: 0,+ forcedSplits: 0,+ verbatimSegments: 0,+ splitSegments: 0,+ rejectedSegments: 0,+ },+ };++ async function beginRecording(): Promise<void> {+ await startVoiceNarration(undefined);+ expect(getVoiceUpdate().phase).toBe('recording');+ }++ beforeEach(() => {+ storageGet.mockReset().mockResolvedValue({ voiceEnabled: true, voiceProvider: 'openai', voiceApiKey: 'sk-test' });+ ensureVoiceHost.mockReset().mockResolvedValue(true);+ queryMicPermission.mockReset().mockResolvedValue({ state: 'granted' });+ startVoiceCapture.mockReset().mockResolvedValue({ started: true });+ hasVoiceHost.mockReset().mockResolvedValue(true);+ closeVoiceHostIfIdle.mockReset().mockResolvedValue(undefined);+ stopVoiceCapture.mockReset();+ });++ describe('a narration that has nothing left to transcribe', () => {+ it('settles when the host delivers the result before the stop call resolves', async () => {+ const deliversResultBeforeResolving = async () => {+ await applyNarration('g1', EMPTY_RESULT, true);+ return { ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 };+ };+ stopVoiceCapture.mockImplementation(deliversResultBeforeResolving);++ await beginRecording();+ await stopVoiceNarration('g1');++ expect(getVoiceUpdate().phase).toBe('idle');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('settles when the result arrives after the stop call resolves', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 });++ await beginRecording();+ await stopVoiceNarration('g1');+ expect(getVoiceUpdate().phase).toBe('transcribing');++ await applyNarration('g1', EMPTY_RESULT, true);++ expect(getVoiceUpdate().phase).toBe('idle');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('does not leave the panel transcribing when the host refuses the stop', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: false, reason: 'no-audio', error: 'No microphone audio was captured' });++ await beginRecording();+ await stopVoiceNarration('g1');++ expect(getVoiceUpdate().phase).toBe('error');+ await expect(whenNarrationSettled()).resolves.toBeUndefined();+ });++ it('keeps a mid-recording flush from ending the transcription', async () => {+ stopVoiceCapture.mockResolvedValue({ ok: true, audioEpochMs: 1_700_000_000_000, durationSeconds: 4 });++ await beginRecording();+ await stopVoiceNarration('g1');++ await applyNarration('g1', EMPTY_RESULT, false);++ expect(getVoiceUpdate().phase).toBe('transcribing');+ });+ });diff --cc src/entrypoints/background/__tests__/navigation.test.tsindex 0000000,6d6359a..4cf7534mode 000000,100644..100644--- a/src/entrypoints/background/__tests__/navigation.test.ts+++ b/src/entrypoints/background/__tests__/navigation.test.ts@@@ -1,0 -1,112 +1,114 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';+ import { createActor } from 'xstate';+ import { captureMachine } from '@/core/capture/machine';++ let actor: ReturnType<typeof createActor<typeof captureMachine>>;++ const { listeners, capture } = vi.hoisted(() => {+ const map = new Map<string, (...args: unknown[]) => unknown>();+ return {+ listeners: map,+ capture: (name: string) => (fn: (...args: unknown[]) => unknown) => map.set(name, fn),+ };+ });++ const injectContentScript = vi.fn();+ const sendMessageToTab = vi.fn();+-vi.mock('@/lib/browser-api', () => ({- onNavigationCompleted: capture('navigated'),- onHistoryStateUpdated: capture('pushState'),- onTabActivated: capture('tabActivated'),- onTabUpdated: capture('tabUpdated'),++vi.mock('@/lib/browser-api/on-navigation-completed', () => ({ onNavigationCompleted: capture('navigated') }));++vi.mock('@/lib/browser-api/on-history-state-updated', () => ({ onHistoryStateUpdated: capture('pushState') }));++vi.mock('@/lib/browser-api/on-tab-activated', () => ({ onTabActivated: capture('tabActivated') }));++vi.mock('@/lib/browser-api/on-tab-updated', () => ({ onTabUpdated: capture('tabUpdated') }));++vi.mock('@/lib/browser-api/get-tab', () => ({+ getTab: (id: number) => Promise.resolve({ id, url: 'https://app.test' }),++}));++vi.mock('@/lib/browser-api/send-message-to-tab', () => ({+ sendMessageToTab: (...args: unknown[]) => sendMessageToTab(...args),+ }));++ vi.mock('../actor', () => ({ getActor: () => actor, waitUntilReady: () => Promise.resolve() }));+ vi.mock('../tab-manager', () => ({+ injectContentScript: (id: number) => injectContentScript(id),+ isInjectableTab: () => true,+ }));-vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++ import { registerNavigationListeners } from '../navigation';++ beforeEach(() => {+ vi.clearAllMocks();+ listeners.clear();+ actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://app.test/a' });+ registerNavigationListeners();+ });++ function url() {+ return actor.getSnapshot().context.currentUrl;+ }++ describe('URL tracking', () => {+ it('follows a navigation while recording', async () => {+ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });+ expect(url()).toBe('https://app.test/b');+ });++ it('follows a navigation while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });++ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });++ expect(url()).toBe('https://app.test/b');+ });++ it('follows an SPA route change while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });++ await listeners.get('pushState')?.({ frameId: 0, url: 'https://app.test/c' });++ expect(url()).toBe('https://app.test/c');+ });++ it('ignores a subframe navigation', async () => {+ await listeners.get('navigated')?.({ frameId: 3, url: 'https://ads.test' });+ expect(url()).toBe('https://app.test/a');+ });++ it('ignores navigation once the recording has ended', async () => {+ actor.send({ type: 'STOP_RECORDING' });++ await listeners.get('navigated')?.({ frameId: 0, url: 'https://app.test/b' });++ expect(url()).toBe('');+ });+ });++ describe('content script injection', () => {+ it('injects into a tab activated while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabActivated')?.({ tabId: 4 });++ expect(injectContentScript).toHaveBeenCalledWith(4);+ });++ it('injects into a tab that finishes loading while paused', async () => {+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'blur' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabUpdated')?.(5, { status: 'complete' }, { id: 5, url: 'https://app.test' });++ expect(injectContentScript).toHaveBeenCalledWith(5);+ });++ it('does not inject once the recording has ended', async () => {+ actor.send({ type: 'STOP_RECORDING' });+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));++ await listeners.get('tabActivated')?.({ tabId: 4 });++ expect(injectContentScript).not.toHaveBeenCalled();+ });+ });diff --cc src/entrypoints/background/__tests__/pause.test.tsindex 0000000,396afe5..0d44fcamode 000000,100644..100644--- a/src/entrypoints/background/__tests__/pause.test.ts+++ b/src/entrypoints/background/__tests__/pause.test.ts@@@ -1,0 -1,209 +1,209 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';+ import { createActor } from 'xstate';+ import { CaptureState, captureMachine } from '@/core/capture/machine';++ let actor: ReturnType<typeof createActor<typeof captureMachine>>;+ let voicePhase = 'idle';+ let activeTab: { id?: number; url?: string } | undefined;++ const { calls, record } = vi.hoisted(() => {+ const seq: string[] = [];+ return {+ calls: seq,+ record: (name: string) => () => {+ seq.push(name);+ return Promise.resolve();+ },+ };+ });++ vi.mock('../actor', () => ({ getActor: () => actor }));++ vi.mock('../tab-manager', () => ({+ broadcastDismissBlur: record('dismissBlur'),+ broadcastClearBlur: record('clearBlur'),+ broadcastStopCaptureAndFlush: record('flush'),+ broadcastStartCapture: record('startCapture'),+ injectContentScript: record('inject'),+ isInjectableTab: (tab: { url?: string }) => !!tab.url?.startsWith('https://'),+ }));++ vi.mock('../voice', () => ({+ getVoiceUpdate: () => ({ type: 'VOICE_UPDATE', phase: voicePhase }),+ isNarrationLive: () => Promise.resolve(voicePhase === 'recording'),+ isNarrationSettling: () => voicePhase === 'transcribing',+ reportNarrationLost: vi.fn(),+ stopVoiceNarration: record('stopNarration'),+ whenNarrationSettled: () => Promise.resolve(),+ }));+-vi.mock('@/lib/browser-api', () => ({ getActiveTab: () => Promise.resolve(activeTab) }));++vi.mock('@/lib/browser-api/get-active-tab', () => ({ getActiveTab: () => Promise.resolve(activeTab) }));++ import { pauseCapture, resumeCapture, resumeFromPause } from '../pause';++ beforeEach(() => {+ calls.length = 0;+ voicePhase = 'idle';+ activeTab = { id: 7, url: 'https://app.test' };+ actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://app.test' });+ });++ describe('pauseCapture', () => {+ it('pauses the machine with its reason and flushes the frames', async () => {+ await expect(pauseCapture('manual')).resolves.toBe(true);++ expect(actor.getSnapshot().value).toBe(CaptureState.PAUSED);+ expect(actor.getSnapshot().context.pauseReason).toBe('manual');+ expect(calls).toContain('flush');+ });++ it('refuses when nothing is recording, without touching the frames', async () => {+ actor.send({ type: 'STOP_RECORDING' });++ await expect(pauseCapture('manual')).resolves.toBe(false);+ expect(calls).toEqual([]);+ });++ it('refuses a second pause', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await expect(pauseCapture('blur')).resolves.toBe(false);+ expect(actor.getSnapshot().context.pauseReason).toBe('manual');+ expect(calls).toEqual([]);+ });++ it('stops narration when it was live', async () => {+ voicePhase = 'recording';++ await pauseCapture('blur');++ expect(calls).toContain('stopNarration');+ });++ it('leaves narration alone when it was not running', async () => {+ await pauseCapture('manual');++ expect(calls).not.toContain('stopNarration');+ });++ it('flushes before returning', async () => {+ await pauseCapture('blur');++ expect(calls).toContain('flush');+ expect(calls.indexOf('flush')).toBeGreaterThanOrEqual(0);+ });+ });++ describe('resumeCapture', () => {+ it('returns to RECORDING and clears the reason', async () => {+ await pauseCapture('manual');++ await expect(resumeCapture()).resolves.toBe(true);++ expect(actor.getSnapshot().value).toBe(CaptureState.RECORDING);+ expect(actor.getSnapshot().context.pauseReason).toBeNull();+ });++ it('refuses when the recording is not paused', async () => {+ await expect(resumeCapture()).resolves.toBe(false);+ expect(calls).toEqual([]);+ });++ it('keeps the same guide, so steps continue in one recording', async () => {+ const guideId = actor.getSnapshot().context.currentGuideId;+ await pauseCapture('manual');++ await resumeCapture();++ expect(actor.getSnapshot().context.currentGuideId).toBe(guideId);+ });++ it('injects the active tab before restarting capture', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await resumeCapture();++ expect(calls).toEqual(['inject', 'startCapture']);+ });++ it('skips injection on a tab that cannot take a content script', async () => {+ await pauseCapture('manual');+ activeTab = { id: 9, url: 'chrome://extensions' };+ calls.length = 0;++ await resumeCapture();++ expect(calls).toEqual(['startCapture']);+ });++ it('restarts narration only when the pause stopped it', async () => {+ voicePhase = 'recording';+ await pauseCapture('manual');+ const onResume = vi.fn().mockResolvedValue(true);++ await resumeCapture(onResume);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(onResume).toHaveBeenCalledOnce();+ });++ it('does not restart narration the user never had on', async () => {+ await pauseCapture('manual');+ const onResume = vi.fn().mockResolvedValue(true);++ await resumeCapture(onResume);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(onResume).not.toHaveBeenCalled();+ });++ it('does not restart narration twice across two pause cycles', async () => {+ voicePhase = 'recording';+ await pauseCapture('manual');+ const first = vi.fn().mockResolvedValue(true);+ await resumeCapture(first);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(first).toHaveBeenCalledOnce();++ voicePhase = 'idle';+ await pauseCapture('manual');+ const second = vi.fn().mockResolvedValue(true);+ await resumeCapture(second);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(second).not.toHaveBeenCalled();+ });+ });++ describe('resumeFromPause', () => {+ it('dismisses the overlay and never clears the masks', async () => {+ await pauseCapture('blur');+ calls.length = 0;++ await expect(resumeFromPause()).resolves.toBe(true);++ expect(calls).toContain('dismissBlur');+ expect(calls).not.toContain('clearBlur');+ });++ it('dismisses before unpausing, so no frame captures with the panel up', async () => {+ await pauseCapture('manual');+ calls.length = 0;++ await resumeFromPause();++ expect(calls.indexOf('dismissBlur')).toBeLessThan(calls.indexOf('startCapture'));+ });++ it('still dismisses when there is nothing to resume', async () => {+ calls.length = 0;++ await expect(resumeFromPause()).resolves.toBe(false);++ expect(calls).toEqual(['dismissBlur']);+ });+ });diff --cc src/entrypoints/background/__tests__/paused-steps.test.tsindex 0000000,85db71c..8391959mode 000000,100644..100644--- a/src/entrypoints/background/__tests__/paused-steps.test.ts+++ b/src/entrypoints/background/__tests__/paused-steps.test.ts@@@ -1,0 -1,99 +1,102 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';+ import { CaptureState } from '@/core/capture/machine';+ import type { ElementMeta } from '@/core/guides/types';++ let state: string = CaptureState.RECORDING;++ const send = vi.fn();+ const updateStepDescription = vi.fn();+ const stepsUpdate = vi.fn();++const updateStepCapture = vi.fn();+ const captureVisibleTab = vi.fn();++ vi.mock('../actor', () => ({+ getActor: () => ({+ getSnapshot: () => ({ value: state, context: { stepCount: 0, currentGuideId: 'guide-1', currentUrl: '/' } }),+ send,+ }),+ }));++ vi.mock('@/core/guides/service', () => ({+ addStepToGuide: vi.fn(),+ clearStepAiPending: vi.fn(),+ createStep: vi.fn(),++ getStep: vi.fn(),+ saveScreenshot: vi.fn(),++ updateStepCapture: (...args: unknown[]) => updateStepCapture(...args),+ updateStepDescription: (...args: unknown[]) => updateStepDescription(...args),+ }));++ vi.mock('@/core/guides/db', () => ({+ db: { steps: { update: (...args: unknown[]) => stepsUpdate(...args), get: vi.fn() } },+ }));+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/lib/browser-api/capture-visible-tab', () => ({+ captureVisibleTab: (...args: unknown[]) => captureVisibleTab(...args),- localStorage: { get: vi.fn().mockResolvedValue({}) },+ }));++vi.mock('@/lib/browser-api/local-storage', () => ({ localStorage: { get: vi.fn().mockResolvedValue({}) } }));+-vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+ vi.mock('../voice', () => ({ getVoiceUpdate: () => ({ phase: 'idle' }), flushNarrationForStep: vi.fn() }));+ vi.mock('../ai-description', () => ({ generateAiDescription: vi.fn() }));-vi.mock('../description-queue', () => ({ queueDescription: vi.fn() }));++vi.mock('@/core/capture/ai/description-queue', () => ({ queueDescription: vi.fn() }));+ vi.mock('../deferred-descriptions', () => ({ deferDescription: vi.fn(), shouldQueueAiDescription: () => false }));+ vi.mock('@/core/capture/ai/keys', () => ({ AI_KEY_SETTINGS: [], resolveAiKey: () => ({ apiKey: undefined }) }));++ const meta = { rect: { x: 0, y: 0, width: 10, height: 10 }, devicePixelRatio: 1 } as ElementMeta;++ beforeEach(() => {+ vi.clearAllMocks();+ state = CaptureState.RECORDING;+ });++ describe('step writes while PAUSED', () => {+ it('ignores a captureStep', async () => {+ const { handleCaptureStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ const res = await handleCaptureStep({ guideId: 'guide-1', action: 'click', elementMeta: meta });++ expect(res).toEqual({ ignored: true });+ expect(send).not.toHaveBeenCalled();+ expect(captureVisibleTab).not.toHaveBeenCalled();+ });++ it('ignores an input step update', async () => {+ const { handleUpdateInputStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ await handleUpdateInputStep('step-1', 'Type secret');++ expect(updateStepDescription).not.toHaveBeenCalled();+ });++ it('still finalizes an input step, so the typed text is not lost', async () => {+ captureVisibleTab.mockRejectedValue(new Error('no tab in this harness'));+ const { handleFinalizeInputStep } = await import('../step-pipeline');+ state = CaptureState.PAUSED;++ await handleFinalizeInputStep('step-1', meta, undefined);++ expect(captureVisibleTab).toHaveBeenCalled();- expect(stepsUpdate).toHaveBeenCalledWith('step-1', { elementMeta: meta });++ expect(updateStepCapture).toHaveBeenCalledWith('step-1', meta, undefined);+ });++ it('refuses a finalize once the recording has ended', async () => {+ const { handleFinalizeInputStep } = await import('../step-pipeline');+ state = CaptureState.IDLE;++ await handleFinalizeInputStep('step-1', meta, undefined);++ expect(captureVisibleTab).not.toHaveBeenCalled();- expect(stepsUpdate).not.toHaveBeenCalled();++ expect(updateStepCapture).not.toHaveBeenCalled();+ });++ it('still writes an input step update while RECORDING', async () => {+ const { handleUpdateInputStep } = await import('../step-pipeline');++ await handleUpdateInputStep('step-1', 'Type hello');++ expect(updateStepDescription).toHaveBeenCalledWith('step-1', 'Type hello');+ });+ });diff --cc src/entrypoints/background/__tests__/state-update.test.tsindex 0000000,77e902d..204513fmode 000000,100644..100644--- a/src/entrypoints/background/__tests__/state-update.test.ts+++ b/src/entrypoints/background/__tests__/state-update.test.ts@@@ -1,0 -1,74 +1,74 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';+ import { createActor } from 'xstate';+ import { CaptureState, captureMachine } from '@/core/capture/machine';++ const sessionGet = vi.fn();+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/lib/browser-api/session-storage', () => ({+ sessionStorage: {+ get: (key: string) => sessionGet(key),+ set: vi.fn(),+ remove: vi.fn(),+ },+ }));+-vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++ function legacyRecordingSnapshot() {+ const actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ const persisted = JSON.parse(JSON.stringify(actor.getPersistedSnapshot()));+ delete persisted.context.pauseReason;+ return persisted;+ }++ function pausedSnapshot() {+ const actor = createActor(captureMachine);+ actor.start();+ actor.send({ type: 'START_RECORDING', url: 'https://example.com' });+ actor.send({ type: 'PAUSE_CAPTURE', reason: 'manual' });+ return JSON.parse(JSON.stringify(actor.getPersistedSnapshot()));+ }++ async function loadActor(snapshot: unknown) {+ vi.resetModules();+ sessionGet.mockResolvedValue({ machineSnapshot: snapshot });+ const mod = await import('../actor');+ await mod.initActor();+ return mod;+ }++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('getStateUpdate', () => {+ it('reports a legacy RECORDING snapshot as recording, not paused', async () => {+ const { getStateUpdate } = await loadActor(legacyRecordingSnapshot());++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.RECORDING);+ expect(update.pauseReason).toBeNull();+ });++ it('carries the pause reason when the machine really is paused', async () => {+ const { getStateUpdate } = await loadActor(pausedSnapshot());++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.PAUSED);+ expect(update.pauseReason).toBe('manual');+ });++ it('starts idle when there is no snapshot to restore', async () => {+ const { getStateUpdate } = await loadActor(undefined);++ const update = getStateUpdate();++ expect(update.state).toBe(CaptureState.IDLE);+ expect(update.pauseReason).toBeNull();+ expect(update.currentGuideId).toBeNull();+ });+ });diff --cc src/entrypoints/background/__tests__/tab-manager.test.tsindex 0000000,a8e93d8..c039875mode 000000,100644..100644--- a/src/entrypoints/background/__tests__/tab-manager.test.ts+++ b/src/entrypoints/background/__tests__/tab-manager.test.ts@@@ -1,0 -1,87 +1,87 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ const queryTabs = vi.fn();+ const sendMessageToTab = vi.fn();+-vi.mock('@/lib/browser-api', () => ({- executeScript: vi.fn(),- queryTabs: (...args: unknown[]) => queryTabs(...args),++vi.mock('@/lib/browser-api/execute-script', () => ({ executeScript: vi.fn() }));++vi.mock('@/lib/browser-api/query-tabs', () => ({ queryTabs: (...args: unknown[]) => queryTabs(...args) }));++vi.mock('@/lib/browser-api/send-message-to-tab', () => ({+ sendMessageToTab: (tabId: number, msg: unknown) => sendMessageToTab(tabId, msg),+ }));+-vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++ import {+ broadcastClearBlur,+ broadcastDismissBlur,+ broadcastStopCaptureAndFlush,+ isInjectableTab,+ } from '../tab-manager';++ function typesSent(): string[] {+ return sendMessageToTab.mock.calls.map(([, msg]) => (msg as { type: string }).type);+ }++ beforeEach(() => {+ vi.clearAllMocks();+ queryTabs.mockResolvedValue([+ { id: 1, url: 'https://a.test' },+ { id: 2, url: 'https://b.test' },+ ]);+ sendMessageToTab.mockResolvedValue(undefined);+ });++ describe('blur broadcasts', () => {+ it('dismiss asks every tab to close the overlay and keep the masks', async () => {+ await broadcastDismissBlur();+ expect(typesSent()).toEqual(['DISMISS_BLUR', 'DISMISS_BLUR']);+ });++ it('clear asks every tab to remove the masks', async () => {+ await broadcastClearBlur();+ expect(typesSent()).toEqual(['CLEAR_BLUR', 'CLEAR_BLUR']);+ });+ });++ describe('broadcastStopCaptureAndFlush', () => {+ it('waits for every tab to answer before resolving', async () => {+ let answered = 0;+ sendMessageToTab.mockImplementation(+ () =>+ new Promise((resolve) => {+ setTimeout(() => {+ answered++;+ resolve(undefined);+ }, 5);+ }),+ );++ await broadcastStopCaptureAndFlush();++ expect(answered).toBe(2);+ expect(typesSent()).toEqual(['STOP_CAPTURE', 'STOP_CAPTURE']);+ });++ it('resolves even when a tab never answers', async () => {+ sendMessageToTab.mockImplementation(() => new Promise(() => {}));+ await expect(broadcastStopCaptureAndFlush()).resolves.toBeUndefined();+ });++ it('resolves when a tab rejects', async () => {+ sendMessageToTab.mockRejectedValue(new Error('no receiving end'));+ await expect(broadcastStopCaptureAndFlush()).resolves.toBeUndefined();+ });+ });++ describe('isInjectableTab', () => {+ it.each([+ ['https://example.com', true],+ ['http://localhost:3000', true],+ ['chrome://extensions', false],+ ['chrome-extension://abc/fullview.html', false],+ ['about:blank', false],+ ['', false],+ ])('%s → %s', (url, expected) => {+ expect(isInjectableTab({ url })).toBe(expected);+ });+ });diff --cc src/entrypoints/background/guide-meta.tsindex 03a7aab,d949a6b..63c67b3--- a/src/entrypoints/background/guide-meta.ts+++ b/src/entrypoints/background/guide-meta.ts@@@ -1,11 -1,57 +1,17 @@@+import { logger } from '@mimik/core/logger';import { i18n } from '#imports';+import { resolveGuideMetaInputs } from '@/core/capture/ai/guide-description';+ import { AI_KEY_SETTINGS, resolveAiKey } from '@/core/capture/ai/keys';import { generateGuideMeta } from '@/core/capture/ai/meta';-import { AI_PROVIDERS } from '@/core/capture/ai/models';-import { actionSteps } from '@/core/guides/blocks';-import {- clearStepAiPending,- getGuideDomain,- getStepsForGuide,- updateGuideDescription,- updateGuideTitle,-} from '@/core/guides/service';-import { localStorage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';-import type { GenerateGuideDescriptionResponse, GuideDescriptionError } from '@/lib/messaging';-import { drainDescriptions } from './description-queue';+import { settleDescriptions } from '@/core/capture/ai/settle-descriptions';++import { localStorage } from '@/core/env';+import { getGuideDomain, updateGuideDescription, updateGuideTitle } from '@/core/guides/service';import { whenNarrationSettled } from './voice';-type ResolveFailure = Extract<GuideDescriptionError, 'no-api-key' | 'no-steps'>;--type GuideMetaInputs =- | {- ok: true;- steps: { description: string; url: string }[];- provider: string;- model: string;- apiKey: string;- baseUrl?: string;- }- | { ok: false; reason: ResolveFailure };-+ async function hasAiKey(): Promise<boolean> {+ return Boolean(resolveAiKey(await localStorage.get([...AI_KEY_SETTINGS])).apiKey);+ }+-async function resolveGuideMetaInputs(guideId: string): Promise<GuideMetaInputs> {- const settings = await localStorage.get(['aiApiKeys', 'aiApiKey', 'aiProvider', 'aiModel', 'aiBaseUrl']);- const { provider, apiKey } = resolveAiKey(settings);- if (!apiKey) return { ok: false, reason: 'no-api-key' };-- const steps = actionSteps(await getStepsForGuide(guideId));- const described = steps.filter((s) => s.description).map((s) => ({ description: s.description, url: s.url }));- if (described.length === 0) return { ok: false, reason: 'no-steps' };-- return {- ok: true,- steps: described.length > 15 ? [...described.slice(0, 10), ...described.slice(-5)] : described,- provider,- model: (settings.aiModel as string) || AI_PROVIDERS[provider].defaultModel,- apiKey,- baseUrl: settings.aiBaseUrl as string | undefined,- };-}-async function applyFallbackTitle(guideId: string) {const domain = await getGuideDomain(guideId);await updateGuideTitle(@@@ -16,10 -62,23 +22,21 @@@export async function settlePendingDescriptions(guideId: string) {await whenNarrationSettled();- await drainDescriptions(guideId);- const pending = (await getStepsForGuide(guideId)).filter((s) => s.aiPending);- await Promise.all(pending.map((s) => clearStepAiPending(s.id)));+ await settleDescriptions(guideId);}+ async function applyFallbackTitleThenSettle(guideId: string) {+ const titled = applyFallbackTitle(guideId).catch((err) => logger.error('Fallback title write failed', err));+ await settlePendingDescriptions(guideId).catch((err) => logger.error('Settling step descriptions failed', err));+ await titled;+ }+export async function generateGuideMetaOnStop(guideId: string) {+ if (!(await hasAiKey().catch(() => false))) {+ await applyFallbackTitleThenSettle(guideId);+ return;+ }+try {await settlePendingDescriptions(guideId);const inputs = await resolveGuideMetaInputs(guideId);diff --cc src/entrypoints/background/index.tsindex 6939eba,f9444de..08b8517--- a/src/entrypoints/background/index.ts+++ b/src/entrypoints/background/index.ts@@@ -16,21 -12,31 +16,29 @@@ importmergeGuideInto,} from '@/core/guides/service';import type { Step } from '@/core/guides/types';-import {- getActiveTab,- localStorage,- sendMessageToTab,- setSidePanelBehavior,- toggleSidebar,- updateTab,-} from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import { getActiveTab } from '@/lib/browser-api/get-active-tab';+import { localStorage } from '@/lib/browser-api/local-storage';+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';+import { setSidePanelBehavior } from '@/lib/browser-api/set-side-panel-behavior';+import { toggleSidebar } from '@/lib/browser-api/toggle-sidebar';+import { updateTab } from '@/lib/browser-api/update-tab';import { onMessage } from '@/lib/messaging';-import { broadcastStateToPanel, setupPortListener } from '@/lib/port';+import { broadcastStateToPanel } from '@/lib/port/broadcast-state-to-panel';+import { setupPortListener } from '@/lib/port/setup-port-listener';+ import { TabMessage } from '@/lib/tab-messages';-import { recordUpdate } from '@/lib/update-notice';+import { recordUpdate } from '@/lib/update-notice/record-update';import { getActor, getStateUpdate, initActor, initActorFallback, waitUntilReady } from './actor';-import { generateDescriptionOnDemand, generateGuideMetaOnStop, settlePendingDescriptions } from './guide-meta';+import { generateGuideMetaOnStop, settlePendingDescriptions } from './guide-meta';import { registerNavigationListeners } from './navigation';+ import { pauseCapture, resumeFromPause } from './pause';import { handleCaptureStep, handleFinalizeInputStep, handleUpdateInputStep } from './step-pipeline';- import { broadcastStartCapture, broadcastStopCapture, showNotificationOnTab } from './tab-manager';+ import {+ broadcastClearBlur,+ broadcastStartCapture,+ broadcastStopCapture,+ isInjectableTab,+ showNotificationOnTab,+ } from './tab-manager';import {canStartNarrationNow,getVoiceUpdate,diff --cc src/entrypoints/background/navigation.tsindex 4736a94,1301624..9f51ece--- a/src/entrypoints/background/navigation.ts+++ b/src/entrypoints/background/navigation.ts@@@ -1,11 -1,13 +1,11 @@@+import { logger } from '@mimik/core/logger';- import { CaptureState } from '@/core/capture/machine';+ import { type CaptureSnapshot, CaptureState } from '@/core/capture/machine';-import {- getTab,- onHistoryStateUpdated,- onNavigationCompleted,- onTabActivated,- onTabUpdated,- sendMessageToTab,-} from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import { getTab } from '@/lib/browser-api/get-tab';+import { onHistoryStateUpdated } from '@/lib/browser-api/on-history-state-updated';+import { onNavigationCompleted } from '@/lib/browser-api/on-navigation-completed';+import { onTabActivated } from '@/lib/browser-api/on-tab-activated';+import { onTabUpdated } from '@/lib/browser-api/on-tab-updated';+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';import { TabMessage } from '@/lib/tab-messages';import { getActor, waitUntilReady } from './actor';import { injectContentScript, isInjectableTab } from './tab-manager';diff --cc src/entrypoints/background/pause.tsindex 0000000,0ceed7f..1316adbmode 000000,100644..100644--- a/src/entrypoints/background/pause.ts+++ b/src/entrypoints/background/pause.ts@@@ -1,0 -1,75 +1,75 @@@++import { logger } from '@mimik/core/logger';+ import { CaptureState, type PauseReason } from '@/core/capture/machine';-import { getActiveTab } from '@/lib/browser-api';-import { logger } from '@/lib/logger';++import { getActiveTab } from '@/lib/browser-api/get-active-tab';+ import { getActor } from './actor';+ import {+ broadcastDismissBlur,+ broadcastStartCapture,+ broadcastStopCaptureAndFlush,+ injectContentScript,+ isInjectableTab,+ } from './tab-manager';+ import {+ isNarrationLive,+ isNarrationSettling,+ reportNarrationLost,+ stopVoiceNarration,+ whenNarrationSettled,+ } from './voice';++ const NARRATION_RESTART_ATTEMPTS = 6;++ export type NarrationStarter = () => Promise<boolean> | boolean;++ export async function pauseCapture(reason: PauseReason): Promise<boolean> {+ const actor = getActor();+ if (actor.getSnapshot().value !== CaptureState.RECORDING) return false;++ const narrationWasLive = (await isNarrationLive()) || isNarrationSettling();+ actor.send({ type: 'PAUSE_CAPTURE', reason, narrationWasLive });++ const guideId = actor.getSnapshot().context.currentGuideId;+ await broadcastStopCaptureAndFlush();+ if (narrationWasLive && guideId) await stopVoiceNarration(guideId);+ return true;+ }++ export async function resumeCapture(tryStartNarration?: NarrationStarter): Promise<boolean> {+ const actor = getActor();+ if (actor.getSnapshot().value !== CaptureState.PAUSED) return false;++ const narrationWasLive = actor.getSnapshot().context.narrationWasLive === true;+ actor.send({ type: 'RESUME_CAPTURE' });++ const guideId = actor.getSnapshot().context.currentGuideId;+ if (guideId) {+ const activeTab = await getActiveTab();+ if (activeTab?.id && isInjectableTab(activeTab)) await injectContentScript(activeTab.id);+ await broadcastStartCapture(guideId);+ }++ if (narrationWasLive && tryStartNarration) {+ void restartNarrationOnceTranscriptionSettles(tryStartNarration).catch((error: unknown) =>+ logger.error('voice: narration could not be restarted after the pause', error),+ );+ }+ return true;+ }++ export async function restartNarrationOnceTranscriptionSettles(tryStartNarration: NarrationStarter): Promise<boolean> {+ for (let attempt = 0; attempt < NARRATION_RESTART_ATTEMPTS; attempt++) {+ if (await tryStartNarration()) return true;+ if (!isNarrationSettling()) {+ reportNarrationLost();+ return false;+ }+ await whenNarrationSettled();+ }+ reportNarrationLost();+ return false;+ }++ export async function resumeFromPause(tryStartNarration?: NarrationStarter): Promise<boolean> {+ await broadcastDismissBlur();+ return resumeCapture(tryStartNarration);+ }diff --cc src/entrypoints/background/step-pipeline.tsindex fc7804d,25cf399..4ca453b--- a/src/entrypoints/background/step-pipeline.ts+++ b/src/entrypoints/background/step-pipeline.ts@@@ -110,9 -124,10 +118,10 @@@ export async function handleCaptureStep}export async function handleUpdateInputStep(stepId: string, description: string, inputValue?: string) {+ if (!isRecording()) return;await updateStepDescription(stepId, description);if (inputValue !== undefined) {- await db.steps.update(stepId, { inputValue });+ await updateStepInputValue(stepId, inputValue);}}@@@ -121,10 -136,13 +130,11 @@@ export async function handleFinalizeInpelementMeta: ElementMeta,domContext: DOMContext | undefined,) {+ if (!isRecordingOrPaused()) return;const screenshotId = await takeScreenshot(stepId, elementMeta);- const updates: Partial<Step> = { elementMeta };- if (screenshotId) updates.screenshotId = screenshotId;- await db.steps.update(stepId, updates);+ await updateStepCapture(stepId, elementMeta, screenshotId);- const guideId = (await db.steps.get(stepId))?.guideId;+ const guideId = (await getStep(stepId))?.guideId;if (domContext && guideId) {queueDescription(guideId, () => tryAIDescription(stepId, domContext));}diff --cc src/entrypoints/background/tab-manager.tsindex 1ef7c18,a534d73..a56a00b--- a/src/entrypoints/background/tab-manager.ts+++ b/src/entrypoints/background/tab-manager.ts@@@ -1,8 -1,6 +1,8 @@@-import { executeScript, queryTabs, sendMessageToTab } from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import { logger } from '@mimik/core/logger';+import { executeScript } from '@/lib/browser-api/execute-script';+import { queryTabs } from '@/lib/browser-api/query-tabs';+import { sendMessageToTab } from '@/lib/browser-api/send-message-to-tab';- import { TabMessage } from '@/lib/tab-messages';+ import { TabMessage, type TabMessageType } from '@/lib/tab-messages';export function isInjectableTab(tab: { url?: string; pendingUrl?: string }): boolean {const url = tab.url || tab.pendingUrl || '';diff --cc src/entrypoints/background/voice.tsindex 3337aa5,1767d9b..f3b9403--- a/src/entrypoints/background/voice.ts+++ b/src/entrypoints/background/voice.ts@@@ -2,27 -1,27 +2,29 @@@ import { logger } from '@mimik/core/logimport { CaptureState } from '@/core/capture/machine';import { hasVoiceApiKey, VOICE_KEY_SETTINGS } from '@/core/capture/voice/api-key';import { narrationUpdates } from '@/core/capture/voice/narration-updates';- import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide } from '@/core/guides/service';+ import { applyNarrationToSteps, findExistingStepIds, getStepsForGuide, saveTranscript } from '@/core/guides/service';-import { localStorage, onMessage as onRuntimeMessage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import { localStorage } from '@/lib/browser-api/local-storage';+import { onMessage as onRuntimeMessage } from '@/lib/browser-api/on-message';+import { closeVoiceHost } from '@/lib/offscreen/close-voice-host';+import { closeVoiceHostIfIdle } from '@/lib/offscreen/close-voice-host-if-idle';+import { ensureVoiceHost } from '@/lib/offscreen/ensure-voice-host';+import { flushVoiceCapture } from '@/lib/offscreen/flush-voice-capture';++import { getVoiceStatus } from '@/lib/offscreen/get-voice-status';+import { hasVoiceHost } from '@/lib/offscreen/has-voice-host';+import { openMicPermissionPage } from '@/lib/offscreen/open-mic-permission-page';+import { queryMicPermission } from '@/lib/offscreen/query-mic-permission';+import { registerVoicePanelRelay } from '@/lib/offscreen/register-voice-panel-relay';+import { startVoiceCapture } from '@/lib/offscreen/start-voice-capture';+import { stopVoiceCapture } from '@/lib/offscreen/stop-voice-capture';+import { supportsVoice } from '@/lib/offscreen/supports-voice';+import { broadcastVoiceToPanel } from '@/lib/port/broadcast-voice-to-panel';+import type { PanelVoiceUpdate, VoicePhase } from '@/lib/port/types';+import { handedOffPcm } from '@/lib/voice/handed-off-pcm';+import { isVoiceMessageFor } from '@/lib/voice/is-voice-message-for';++import { isVoiceStatus } from '@/lib/voice/is-voice-status';+import { narrateRecording, type VoiceRecording } from '@/lib/voice/narrate-recording';+import { readTranscriptionSettings } from '@/lib/voice/read-transcription-settings';import {- closeVoiceHost,- closeVoiceHostIfIdle,- ensureVoiceHost,- flushVoiceCapture,- getVoiceStatus,- hasVoiceHost,- openMicPermissionPage,- queryMicPermission,- registerVoicePanelRelay,- startVoiceCapture,- stopVoiceCapture,- supportsVoice,-} from '@/lib/offscreen';-import type { VoicePhase } from '@/lib/port';-import { broadcastVoiceToPanel, type PanelVoiceUpdate } from '@/lib/port';-import {- isVoiceMessageFor,VOICE_BACKGROUND_TARGET,type VoiceErrorEvent,type VoiceEvent,diff --cc src/entrypoints/content.tsindex a0bd8bf,cf0c679..82dc780--- a/src/entrypoints/content.ts+++ b/src/entrypoints/content.ts@@@ -1,13 -1,13 +1,15 @@@+import '@/lib/core-env';+import '@/lib/ui-env';+import { logger } from '@mimik/core/logger';import { defineContentScript } from 'wxt/utils/define-content-script';import { browser } from '#imports';-import { BlurManager } from '@/core/blur/manager';-import { shouldReopenBlur } from '@/core/blur/restore';-import { CaptureSession } from '@/core/capture/session';+import { BlurManager } from '@/blur/manager';++import { shouldReopenBlur } from '@/blur/restore';+import { CaptureSession } from '@/capture/session';import { updateUrl } from '@/core/capture/spa-nav';import { showStartNotification } from '@/core/capture/start-notification';-import { GuideMeController } from '@/core/guideme/content';-import { logger } from '@/lib/logger';+import { GuideMeController } from '@/guideme/content';+ import { sendMessage } from '@/lib/messaging';import { TabMessage } from '@/lib/tab-messages';const CLEANUP_EVENT = `mimik_cleanup_${browser.runtime.id}`;diff --cc src/lib/messaging.tsindex 285c72f,dc00718..7b6dce0--- a/src/lib/messaging.ts+++ b/src/lib/messaging.ts@@@ -1,15 -1,8 +1,16 @@@import { defineExtensionMessaging } from '@webext-core/messaging';-import type { DOMContext } from '@/core/capture/dom/context';+import type { GenerateGuideDescriptionResponse } from '@/core/capture/ai/guide-description';+import type { RewriteError, RewriteSelectionResponse } from '@/core/capture/ai/rewrite';- import type { CaptureStateValue } from '@/core/capture/machine';+ import type { CaptureStateValue, PauseReason } from '@/core/capture/machine';+import type {+ CaptureStepData,+ CaptureStepResponse,+ FinalizeInputStepData,+ FinalizeInputStepResponse,+ UpdateInputStepData,+ UpdateInputStepResponse,+} from '@/core/capture/sink';+ import type { VoiceoverProviderKey } from '@/core/export/voiceover/providers';-import type { ElementMeta } from '@/core/guides/types';export interface GetStateResponse {state: CaptureStateValue;diff --cc src/lib/port/types.tsindex 9313dd3,0000000..8594625mode 100644,000000..100644--- a/src/lib/port/types.ts+++ b/src/lib/port/types.ts@@@ -1,32 -1,0 +1,33 @@@+import type { browser } from '#imports';+import type { AiFailureReason } from '@/core/capture/ai/errors';- import type { CaptureStateValue } from '@/core/capture/machine';++import type { CaptureStateValue, PauseReason } from '@/core/capture/machine';+import type { VoiceErrorReason } from '@/lib/voice/voice-message';++export interface PanelStateUpdate {+ type: 'STATE_UPDATE';+ state: CaptureStateValue;+ stepCount: number;+ currentGuideId: string | null;++ pauseReason: PauseReason | null;+}++export type VoicePhase = 'idle' | 'recording' | 'transcribing' | 'error';++export interface PanelVoiceUpdate {+ type: 'VOICE_UPDATE';+ phase: VoicePhase;+ reason?: VoiceErrorReason;+ error?: string;+ narrated?: number;+}++export interface PanelAiUpdate {+ type: 'AI_UPDATE';+ reason: AiFailureReason;+ status?: number;+ provider: string;+}++export type PortMessage = PanelStateUpdate | PanelVoiceUpdate | PanelAiUpdate;++export type Port = ReturnType<typeof browser.runtime.connect>;diff --cc src/lib/voice/__tests__/voice-host-final.test.tsindex 0000000,72d29fe..b318cd4mode 000000,100644..100644--- a/src/lib/voice/__tests__/voice-host-final.test.ts+++ b/src/lib/voice/__tests__/voice-host-final.test.ts@@@ -1,0 -1,113 +1,110 @@@+ import { beforeEach, describe, expect, it, vi } from 'vitest';++ const sendMessage = vi.fn();+ const narrateRecording = vi.fn();+-vi.mock('../browser-api', () => ({- getExtensionURL: (path: string) => path,- onMessage: vi.fn(),- sendMessage: (...args: unknown[]) => sendMessage(...args),-}));++vi.mock('../../browser-api/get-extension-url', () => ({ getExtensionURL: (path: string) => path }));++vi.mock('../../browser-api/send-message', () => ({ sendMessage: (...args: unknown[]) => sendMessage(...args) }));+-vi.mock('../logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++vi.mock('@mimik/core/logger', () => ({ logger: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++ const recorderState = {+ recording: false,+ audioEpochMs: 1_700_000_000_000 as number | null,+ sampleRate: 16000,+ sampleCount: 16000,+ durationSeconds: 1,+ };++ vi.mock('../mic-recorder', () => ({+ MicRecorder: class {+ get recording() {+ return recorderState.recording;+ }+ get audioEpochMs() {+ return recorderState.audioEpochMs;+ }+ get sampleRate() {+ return recorderState.sampleRate;+ }+ get sampleCount() {+ return recorderState.sampleCount;+ }+ get durationSeconds() {+ return recorderState.durationSeconds;+ }+ stop() {+ recorderState.recording = false;+ return {+ pcm: new Int16Array(recorderState.sampleCount),+ sampleRate: recorderState.sampleRate,+ audioEpochMs: recorderState.audioEpochMs,+ durationSeconds: recorderState.durationSeconds,+ };+ }+ snapshot() {+ return this.stop();+ }+ release() {}+ },+ }));+-vi.mock('../voice-narration', async (importOriginal) => {- const actual = await importOriginal<typeof import('../voice-narration')>();++vi.mock('../narrate-recording', async (importOriginal) => {++ const actual = await importOriginal<typeof import('../narrate-recording')>();+ return { ...actual, narrateRecording: (...args: unknown[]) => narrateRecording(...args) };+ });+-import { createVoiceHost } from '../voice-host';-import { VOICE_BACKGROUND_TARGET, VoiceMessage } from '../voice-messages';++import { createVoiceHost } from '../create-voice-host';++import { VOICE_BACKGROUND_TARGET, VoiceMessage } from '../voice-message';++ const SETTINGS = { provider: 'openai', apiKey: 'sk-test' };++ function deliveredResults(): Array<{ final: boolean }> {+ return sendMessage.mock.calls+ .map(([event]) => event as { type: string; target: string; final: boolean })+ .filter((event) => event.type === VoiceMessage.VOICE_RESULT && event.target === VOICE_BACKGROUND_TARGET);+ }++ beforeEach(() => {+ sendMessage.mockReset().mockResolvedValue(undefined);+ narrateRecording.mockReset();+ recorderState.recording = true;+ recorderState.audioEpochMs = 1_700_000_000_000;+ recorderState.sampleCount = 160000;+ recorderState.durationSeconds = 10;+ });++ describe('the final flag on a delivered narration result', () => {+ it('is true when a stop has no steps to attribute to', async () => {+ const host = createVoiceHost();++ await host.handle({+ type: VoiceMessage.VOICE_STOP,+ target: 'voice-offscreen',+ guideId: 'g1',+ steps: [],+ settings: SETTINGS,+ } as never);++ expect(deliveredResults().map((event) => event.final)).toEqual([true]);+ });++ it('is false for a mid-recording flush', async () => {+ narrateRecording.mockResolvedValue({+ descriptions: [{ stepId: 's1', text: 'Open billing' }],+ transcript: { epochMs: 1_700_000_000_000, lines: [{ start: 0, end: 1, text: 'Open billing', stepId: 's1' }] },+ stats: {},+ });+ const host = createVoiceHost();++ await host.handle({+ type: VoiceMessage.VOICE_FLUSH,+ target: 'voice-offscreen',+ guideId: 'g1',+ step: { stepId: 's1', timestamp: 1_700_000_005_000 },+ settings: SETTINGS,+ } as never);++ expect(deliveredResults().map((event) => event.final)).toEqual([false]);+ });+ });diff --cc src/locales/de.ymlindex 0ec156c,9abe55c..63a5580--- a/src/locales/de.yml+++ b/src/locales/de.yml@@@ -461,24 -441,21 +508,26 @@@ onboardingopenMimik: Mimik öffnensteps:- pressKey: "$1 auf $2 drücken"- toggleCheckbox: "$1 umschalten"- selectRadio: "$1 auswählen"- toggleSwitch: "$1 umschalten"+ pressKey: '$1 auf "$2" drücken'+ toggleCheckbox: '"$1" umschalten'+ select: '"$1" auswählen'+ enter: 'In "$1" eingeben'+ toggleSwitch: '"$1" umschalten'- clickLink: 'Link "$1" anklicken'+ clickLink: "Link „$1“ anklicken"- click: "$1 anklicken"- typeIntoField: "In $1-Feld $2 eingeben"- typeInto: "In $1 eingeben"+ click: '"$1" anklicken'+ clickHere: "Hier klicken"+ rightClick: '"$1" rechtsklicken'+ rightClickHere: "Hier rechtsklicken"+ typeIntoField: 'In Feld $1 eingeben "$2"'+ typeInto: 'In "$1" eingeben'+ type: '"$1" eingeben'typeSecret: "Passwort eingeben"+ copyFrom: 'Aus "$1" kopieren'+ pasteInto: 'In "$1" einfügen'+ cutFrom: 'Aus "$1" ausschneiden'+ drag: '"$1" ziehen'+ typeValueInto: '"$1" in $2 eingeben'+ clearField: "$1 leeren"- copyFrom: "Aus $1 kopieren"- pasteInto: "In $1 einfügen"- cutFrom: "Aus $1 ausschneiden"- drag: "$1 ziehen"navigate: Zur Seite navigierendefaultAction: "$1 $2"diff --cc src/locales/en.ymlindex f05f9dd,6663c5a..1dee6c1--- a/src/locales/en.yml+++ b/src/locales/en.yml@@@ -146,89 -163,22 +163,89 @@@ settingsblurPresets:email: Email- phoneNumbers: Phone Numbers+ phoneNumbers: "Phone numbers"ssn: SSN- creditCard: Credit Card- ipAddress: IP Address- macAddress: MAC Address+ creditCard: "Credit card"+ ipAddress: "IP address"+ macAddress: "MAC address"+desktop:+ ready: Ready+ pause: Pause+ resume: Resume+ finish: Finish+ screenshotDelay: Screenshot delay+ keepClicksBeyondArea: Capture clicks outside the area+ guideInApp: "Guide in $1"+ capturingSection: Capturing+ milliseconds: ms+ captureMode: What to capture+ modeWindow: Window+ modeScreen: Screen+ modeRegion: Area+ startSheetTitle: Start a capture+ moreStepsAfter: "New steps are inserted after step $1."+ moreStepsFirst: "New steps are inserted before step 1."+ startButton: Start+ shortcutsSection: "Shortcuts"+ generalSection: "General"+ appLanguage: "App language"+ appLanguageHint: "The language of Mimik's own screens. AI descriptions have their own setting."+ languageSystem: "Same as the system"+ cardLanguage: "Language"+ cardStartup: "Startup"+ cardUpdates: "Updates"+ startAtLogin: "Start at login"+ startAtLoginHint: "Mimik opens in the tray, without a window."+ version: "Version $1"+ versionHint: "Mimik looks for updates each time it starts."+ checkUpdates: "Check for updates"+ traySetArea: "Set capture area"+ trayQuit: "Quit Mimik"+ trayRecording: "Mimik is recording. Click to finish."+ cannotRecord: "Mimik cannot record"+ updateReady: "Update ready"+ updateReadyMessage: "Mimik $1 is ready to install."+ restartNow: "Restart now"+ later: "Later"+ updateFailed: "Update check failed"+ upToDate: "Up to date"+ upToDateMessage: "Mimik $1 is current."+ cardScreenshots: "Screenshots"+ cardKeyboard: "Typing and keys"+ cardGlobalKeys: "Global keys"+ cardGlobalKeysHint: "Taken from every application while Mimik is running."+ zoomLevel: "Zoom toward the click"+ zoomLevelHint: "New recordings start here. Automatic keeps every step the same size."+ zoomAuto: "Automatic"+ zoomGuide: "Zoom"+ recordKeys: "Record shortcuts and named keys"+ recordTyping: "Record what you type"+ typingDebounce: "Close a typing step after"+ cardScreenshotsHint: "What each step captures"+ cardKeyboardHint: "What the keyboard adds to a guide"+ captureModeHint: "Window follows the app you click."+ screenshotDelayHint: "Wait before taking the screenshot, for menus that animate."+ recordKeysHint: "Ctrl+S, Enter and the like become steps."+ seconds: "s"+ shortcutStartStop: "Start or finish a recording"+ shortcutPauseResume: "Pause or resume"+ shortcutCapture: "Capture a step now"+ shortcutPress: "Press keys…"+ shortcutClear: "Clear"+fullview:+ collapseSidebar: Collapse sidebar+ expandSidebar: Expand sidebar- allGuides: All Guides+ allGuides: "All guides"starred: Starredtrash: Trash- searchPlaceholder: Search guides...- guideMe: Guide Me- untitledGuide: Untitled Guide+ searchPlaceholder: Search guides…+ guideMe: "Guide Me"+ untitledGuide: "Untitled guide"writingTitle: Writing a title from your captured steps...writingDescription: "Writing a description\u2026"- guideNotFound: "Guide not found."+ guideNotFound: "Guide not found"stepCount: "$1 step"stepCountPlural: "$1 steps"pageOf: "$1 / $2"@@@ -530,24 -510,21 +577,26 @@@ onboardingopenMimik: Open Mimiksteps:- pressKey: "Press $1 on $2"- toggleCheckbox: "Toggle $1"- selectRadio: "Select $1"- toggleSwitch: "Toggle $1"+ pressKey: 'Press $1 on "$2"'+ toggleCheckbox: 'Toggle "$1"'+ select: 'Select "$1"'+ enter: 'Enter "$1"'+ toggleSwitch: 'Toggle "$1"'clickLink: 'Click link "$1"'- click: "Click $1"- typeIntoField: "Type into $1 field $2"- typeInto: "Type into $1"+ click: 'Click "$1"'+ clickHere: "Click here"+ rightClick: 'Right-click "$1"'+ rightClickHere: "Right-click here"+ typeIntoField: 'Type into $1 field "$2"'+ typeInto: 'Type into "$1"'+ type: 'Type "$1"'typeSecret: "Type password"+ copyFrom: 'Copy from "$1"'+ pasteInto: 'Paste into "$1"'+ cutFrom: 'Cut from "$1"'+ drag: 'Drag "$1"'+ typeValueInto: 'Type "$1" in $2'+ clearField: "Clear $1"- copyFrom: "Copy from $1"- pasteInto: "Paste into $1"- cutFrom: "Cut from $1"- drag: "Drag $1"navigate: Navigate to pagedefaultAction: "$1 $2"diff --cc src/locales/es.ymlindex 2f19036,8b0e31e..05a7d10--- a/src/locales/es.yml+++ b/src/locales/es.yml@@@ -530,24 -510,21 +577,26 @@@ onboardingopenMimik: Abrir Mimiksteps:- pressKey: "Pulsar $1 en $2"- toggleCheckbox: "Marcar o desmarcar $1"- selectRadio: "Seleccionar $1"- toggleSwitch: "Alternar $1"+ pressKey: 'Pulsar $1 en "$2"'+ toggleCheckbox: 'Marcar "$1"'+ select: 'Seleccionar "$1"'+ enter: 'Escribir en "$1"'+ toggleSwitch: 'Alternar "$1"'- clickLink: 'Clic en enlace "$1"'+ clickLink: "Clic en el enlace \"$1\""- click: "Clic en $1"- typeIntoField: "Escribir en el campo $1 $2"- typeInto: "Escribir en $1"+ click: 'Clic en "$1"'+ clickHere: "Clic aquí"+ rightClick: 'Clic derecho en "$1"'+ rightClickHere: "Clic derecho aquí"+ typeIntoField: 'Escribir en el campo $1 "$2"'+ typeInto: 'Escribir en "$1"'+ type: 'Escribir "$1"'typeSecret: "Escribir contraseña"+ copyFrom: 'Copiar de "$1"'+ pasteInto: 'Pegar en "$1"'+ cutFrom: 'Cortar de "$1"'+ drag: 'Arrastrar "$1"'+ typeValueInto: 'Escribir "$1" en $2'+ clearField: "Borrar $1"- copyFrom: "Copiar de $1"- pasteInto: "Pegar en $1"- cutFrom: "Cortar de $1"- drag: "Arrastrar $1"navigate: Ir a la páginadefaultAction: "$1 $2"diff --cc src/locales/fr.ymlindex 46fe7e0,e11a6ff..458b93e--- a/src/locales/fr.yml+++ b/src/locales/fr.yml@@@ -530,24 -510,21 +577,26 @@@ onboardingopenMimik: Ouvrir Mimiksteps:- pressKey: "Appuyer sur $1 dans $2"- toggleCheckbox: "Cocher/décocher $1"- selectRadio: "Sélectionner $1"- toggleSwitch: "Activer/désactiver $1"+ pressKey: 'Appuyer sur $1 dans "$2"'+ toggleCheckbox: 'Cocher "$1"'+ select: 'Sélectionner "$1"'+ enter: 'Saisir dans "$1"'+ toggleSwitch: 'Activer/désactiver "$1"'- clickLink: 'Cliquer sur le lien "$1"'+ clickLink: "Cliquer sur le lien « $1 »"- click: "Cliquer sur $1"- typeIntoField: "Saisir dans le champ $1 $2"- typeInto: "Saisir dans $1"+ click: 'Cliquer sur "$1"'+ clickHere: "Cliquer ici"+ rightClick: 'Clic droit sur "$1"'+ rightClickHere: "Clic droit ici"+ typeIntoField: 'Saisir dans le champ $1 "$2"'+ typeInto: 'Saisir dans "$1"'+ type: 'Saisir "$1"'typeSecret: "Saisir le mot de passe"+ copyFrom: 'Copier depuis "$1"'+ pasteInto: 'Coller dans "$1"'+ cutFrom: 'Couper depuis "$1"'+ drag: 'Glisser "$1"'+ typeValueInto: 'Saisir "$1" dans $2'+ clearField: "Effacer $1"- copyFrom: "Copier depuis $1"- pasteInto: "Coller dans $1"- cutFrom: "Couper depuis $1"- drag: "Glisser $1"navigate: "Aller à la page"defaultAction: "$1 $2"diff --cc src/locales/pt-BR.ymlindex 94faa7a,d32bc6b..4371bc5--- a/src/locales/pt-BR.yml+++ b/src/locales/pt-BR.yml@@@ -525,30 -505,27 +572,32 @@@ onboardingfeatureAIAssist: Assistente de IAfeatureVoice: "Narração por voz"featureAnnotate: Anotar e ocultar- featureExports: Exportar em tudo+ featureExports: "Exportar em PDF, vídeo e mais"featureSmartBlur: Desfoque inteligente- openMimik: Abrir Mimik+ openMimik: "Abrir o Mimik"steps:- pressKey: "Pressionar $1 em $2"- toggleCheckbox: "Marcar/desmarcar $1"- selectRadio: "Selecionar $1"- toggleSwitch: "Ligar/desligar $1"+ pressKey: 'Pressionar $1 em "$2"'+ toggleCheckbox: 'Marcar "$1"'+ select: 'Selecionar "$1"'+ enter: 'Digitar em "$1"'+ toggleSwitch: 'Ligar/desligar "$1"'clickLink: 'Clicar no link "$1"'- click: "Clicar em $1"- typeIntoField: "Digitar no campo $1 $2"- typeInto: "Digitar em $1"+ click: 'Clicar em "$1"'+ clickHere: "Clicar aqui"+ rightClick: 'Clicar com o botão direito em "$1"'+ rightClickHere: "Clicar com o botão direito aqui"+ typeIntoField: 'Digitar no campo $1 "$2"'+ typeInto: 'Digitar em "$1"'+ type: 'Digitar "$1"'typeSecret: "Digitar senha"+ copyFrom: 'Copiar de "$1"'+ pasteInto: 'Colar em "$1"'+ cutFrom: 'Recortar de "$1"'+ drag: 'Arrastar "$1"'- navigate: Ir pra página++ navigate: "Ir para a página"+ typeValueInto: 'Digitar "$1" em $2'+ clearField: "Limpar $1"- copyFrom: "Copiar de $1"- pasteInto: "Colar em $1"- cutFrom: "Recortar de $1"- drag: "Arrastar $1"- navigate: "Ir para a página"defaultAction: "$1 $2"export:diff --cc src/locales/zh-CN.ymlindex a43bbdc,a8882fc..35c50d1--- a/src/locales/zh-CN.yml+++ b/src/locales/zh-CN.yml@@@ -530,24 -510,21 +577,26 @@@ onboardingopenMimik: 打开 Mimiksteps:- pressKey: "在 $2 上按 $1"- toggleCheckbox: "切换 $1"- selectRadio: "选择 $1"- toggleSwitch: "切换 $1"+ pressKey: '在“$2”上按 $1'+ toggleCheckbox: '切换“$1”'+ select: '选择“$1”'+ enter: '在“$1”中输入'+ toggleSwitch: '切换“$1”'clickLink: '点击链接“$1”'- click: "点击 $1"- typeIntoField: "在 $1 字段中输入 $2"- typeInto: "在 $1 中输入"+ click: '点击“$1”'+ clickHere: "点击此处"+ rightClick: '右键点击“$1”'+ rightClickHere: "右键点击此处"+ typeIntoField: '在 $1 字段“$2”中输入'+ typeInto: '在“$1”中输入'+ type: "输入“$1”"typeSecret: "输入密码"+ copyFrom: '从“$1”复制'+ pasteInto: '粘贴到“$1”'+ cutFrom: '从“$1”剪切'+ drag: '拖动“$1”'+ typeValueInto: '在 $2 中输入 "$1"'+ clearField: "清空 $1"- copyFrom: "从 $1 复制"- pasteInto: "粘贴到 $1"- cutFrom: "从 $1 剪切"- drag: "拖动 $1"navigate: 导航到页面defaultAction: "$1 $2"diff --cc src/ui/fullview/App.tsxindex c5b22c2,cdb4b77..3cf984a--- a/src/ui/fullview/App.tsx+++ b/src/ui/fullview/App.tsx@@@ -1,21 -1,37 +1,24 @@@-import { useEffect } from 'react';-import { useFullview } from '@/stores/fullview';-import { TooltipProvider } from '@/ui/components/ui/tooltip';-import UpdateNotice from '@/ui/shared/UpdateNotice';-import VoiceNotice from './components/VoiceNotice';-import GuideContent from './GuideContent';-import LibraryContent from './LibraryContent';-import { useRoute } from './router';-import SearchModal from './SearchModal';-import TopNav from './TopNav';+import { AppFrame, GuideContent, LibraryContent, SearchModal, TooltipProvider, useFullview, useRoute } from '@mimik/ui';+import { browser } from '#imports';+import { openSidebar } from '@/lib/browser-api/open-sidebar';+import { UpdateNotice } from '@/ui/shared/UpdateNotice';+import { VoiceNotice } from './components/VoiceNotice';-export default function FullViewApp() {+export function FullViewApp() {const route = useRoute();- const historyOpen = useFullview((s) => s.historyOpen);- const { toggleSearch, historyOpen, transcriptOpen } = useFullview((s) => ({- toggleSearch: s.toggleSearch,++ const { historyOpen, transcriptOpen } = useFullview((s) => ({+ historyOpen: s.historyOpen,+ transcriptOpen: s.transcriptOpen,+ }));- useEffect(() => {- const handler = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key === 'k') {- e.preventDefault();- toggleSearch();- }- };- window.addEventListener('keydown', handler);- return () => window.removeEventListener('keydown', handler);- }, [toggleSearch]);-return (<TooltipProvider>- <div className="min-h-screen flex flex-col bg-background">- <TopNav route={route} />+ <AppFrame+ route={route}+ onStartCapture={openSidebar}+ onSettings={() => browser.runtime.openOptionsPage()}+ settingsExternal+ ><SearchModal /><UpdateNotice className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50" />diff --cc src/ui/fullview/__tests__/ExportPreviewModal.test.tsxindex 2480832,0b1489d..eb3dcc0--- a/src/ui/fullview/__tests__/ExportPreviewModal.test.tsx+++ b/src/ui/fullview/__tests__/ExportPreviewModal.test.tsx@@@ -7,11 -7,14 +7,17 @@@ import type { Guide, Screenshot, Stepconst exportGuideAsVideo = vi.hoisted(() => vi.fn());const exportGuideAsHTML = vi.hoisted(() => vi.fn());const canExportVideo = vi.hoisted(() => vi.fn());+ const stored = vi.hoisted(() => ({ value: {} as Record<string, unknown> }));+-vi.mock('@/lib/browser-api', () => ({++vi.mock('@/core/env', async (importOriginal) => ({++ ...(await importOriginal<typeof import('@/core/env')>()),+ localStorage: { get: async () => stored.value, set: async () => {} },+ }));vi.mock('@/core/export/video-export', () => ({ exportGuideAsVideo }));-vi.mock('@/ui/fullview/VideoStepPlayer', () => ({ default: () => <div data-testid="video-player" /> }));+vi.mock('@mimik/ui/export/components/VideoStepPlayer', () => ({+ VideoStepPlayer: () => <div data-testid="video-player" />,+}));vi.mock('@/core/export/html-export', () => ({ exportGuideAsHTML }));vi.mock('@/core/export/video-support', async (importOriginal) => ({...(await importOriginal<typeof import('@/core/export/video-support')>()),diff --cc src/ui/shared/SettingsView.tsxindex 2391e78,171c281..028482b--- a/src/ui/shared/SettingsView.tsx+++ b/src/ui/shared/SettingsView.tsx@@@ -1,44 -1,111 +1,81 @@@-import {- ArrowLeft,- AudioLines,- Bug,- Check,- ChevronDown,- ChevronRight,- EyeOff,- Globe,- ImageIcon,- Mic,- Shield,- Sparkles,- Star,- Target,- Trash2,- TriangleAlert,-} from 'lucide-react';-import { useCallback, useEffect, useRef, useState } from 'react';-import { i18n } from '#imports';-import { PRESET_LABELS, type PresetKey } from '@/core/blur/regexes';-import { type AIApiKeys, keyFor, migrateApiKeys, withKeyFor } from '@/core/capture/ai/keys';-import {- AI_PROVIDERS,- type AIProviderKey,- CUSTOM_MODEL_VALUE,- DEFAULT_AI_PROVIDER,- isCustomBaseUrl,- isCustomModel,- providerOrDefault,-} from '@/core/capture/ai/models';-import { AI_LANGUAGES, type AILanguageCode } from '@/core/capture/ai/prompts';-import { resolveVoiceApiKey } from '@/core/capture/voice/api-key';-import type { VoiceProvider } from '@/core/capture/voice/transcribe';-import { type BrandLogo, defaultFooterLine, makeBrandLogo } from '@/core/export/branding';+import { PRESET_LABELS, type PresetKey } from '@mimik/core/blur/regexes';+import { keyFor, migrateApiKeys } from '@mimik/core/capture/ai/keys';+import { type AIProviderKey, providerOrDefault } from '@mimik/core/capture/ai/models';+import { resolveVoiceApiKey } from '@mimik/core/capture/voice/api-key';+import type { VoiceProvider } from '@mimik/core/capture/voice/transcribe';+import { i18n } from '@mimik/core/env';+ import {+ keyForVoiceoverProvider,+ parseVoiceoverKeys,+ resolveVoiceoverConfig,+ type VoiceoverApiKeys,+ voiceoverKeyPlaceholder,+ withVoiceoverKey,-} from '@/core/export/voiceover/config';++} from '@mimik/core/export/voiceover/config';+ import {+ DEFAULT_VOICEOVER_PROVIDER,+ VOICEOVER_PROVIDER_KEYS,+ VOICEOVER_PROVIDERS,+ type VoiceoverProviderKey,+ type VoiceoverVoice,+ voiceoverProvider,-} from '@/core/export/voiceover/providers';-import { DEFAULT_TARGET_COLOR, TARGET_COLORS } from '@/core/screenshot/types';-import { localStorage } from '@/lib/browser-api';-import { logger } from '@/lib/logger';++} from '@mimik/core/export/voiceover/providers';+import {+ AiSettings,+ BrandingSettings,+ Button,+ KeyStatusNote,+ ModelList,+ SecretInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ SettingsCard,+ Switch,+} from '@mimik/ui';- import { ArrowLeft, Bug, Check, ChevronRight, EyeOff, Mic, Shield, Sparkles, Star, TriangleAlert } from 'lucide-react';++import {++ ArrowLeft,++ AudioLines,++ Bug,++ Check,++ ChevronRight,++ EyeOff,++ Mic,++ Shield,++ Sparkles,++ Star,++ TriangleAlert,++} from 'lucide-react';+import { useEffect, useState } from 'react';+import { localStorage } from '@/lib/browser-api/local-storage';+ import { sendMessage } from '@/lib/messaging';-import { Button } from '@/ui/components/ui/button';-import { Input } from '@/ui/components/ui/input';-import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover';-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/ui/components/ui/select';-import ColorPicker from '@/ui/shared/ColorPicker';-import { KeyStatusNote, KeyWarningNote, ModelList, SecretInput, useKeyCheck } from '@/ui/shared/key-check';-import MicrophonePicker from '@/ui/shared/MicrophonePicker';-import { changedSettings, type SettingsSnapshot } from '@/ui/shared/settings-autosave';+import { useKeyCheck } from '@/ui/shared/hooks/use-key-check';+import { useSettingsAutosave } from '@/ui/shared/hooks/use-settings-autosave';+import { MicrophonePicker } from '@/ui/shared/MicrophonePicker';interface SettingsViewProps {onBack?: () => void;}-const SAVE_DEBOUNCE_MS = 400;-const SAVED_BADGE_MS = 1600;--const FOOTER_PRESETS = () => [- defaultFooterLine(),- i18n.t('settings.footerPresetConfidential'),- i18n.t('settings.footerPresetNoDistribute'),-];--export default function SettingsView({ onBack }: SettingsViewProps) {+export function SettingsView({ onBack }: SettingsViewProps) {const [provider, setProvider] = useState<AIProviderKey>('openai');- const [model, setModel] = useState(AI_PROVIDERS.openai.defaultModel);const [apiKey, setApiKey] = useState('');- const [apiKeys, setApiKeys] = useState<AIApiKeys>({});- const [baseUrl, setBaseUrl] = useState('');- const [saved, setSaved] = useState(false);++ const [apiKeys, setApiKeys] = useState<Record<string, string>>({});const aiKeyCheck = useKeyCheck();const voiceKeyCheck = useKeyCheck();- const [customModel, setCustomModel] = useState(false);- const [ownServer, setOwnServer] = useState(false);const [loaded, setLoaded] = useState(false);- const savedSnapshot = useRef<SettingsSnapshot | null>(null);- const pending = useRef<SettingsSnapshot>({});- const saveTimer = useRef<number | undefined>(undefined);- const [aiLanguage, setAiLanguage] = useState<AILanguageCode>('en');const [voiceProvider, setVoiceProvider] = useState<VoiceProvider>('openai');const [voiceApiKey, setVoiceApiKey] = useState('');const [voiceMicrophoneId, setVoiceMicrophoneId] = useState('');+ const [voiceoverProviderKey, setVoiceoverProviderKey] = useState<VoiceoverProviderKey>(DEFAULT_VOICEOVER_PROVIDER);+ const [voiceoverApiKey, setVoiceoverApiKey] = useState('');+ const [voiceoverApiKeys, setVoiceoverApiKeys] = useState<VoiceoverApiKeys>({});+ const [voiceoverVoiceId, setVoiceoverVoiceId] = useState(VOICEOVER_PROVIDERS.openai.defaultVoice);+ const [voiceoverModelId, setVoiceoverModelId] = useState(VOICEOVER_PROVIDERS.openai.defaultModel);+ const [voices, setVoices] = useState<VoiceoverVoice[]>(VOICEOVER_PROVIDERS.openai.voices);+ const voiceoverKeyCheck = useKeyCheck();- const [targetColor, setTargetColor] = useState<string>(DEFAULT_TARGET_COLOR);- const [brandLogo, setBrandLogo] = useState<BrandLogo | null>(null);- const [brandFooter, setBrandFooter] = useState('');- const [brandAttribution, setBrandAttribution] = useState(true);- const logoInputRef = useRef<HTMLInputElement>(null);const [blurPresets, setBlurPresets] = useState<Record<PresetKey, boolean>>({email: true,phone: true,@@@ -61,15 -128,43 +98,29 @@@'voiceProvider','voiceApiKey','voiceMicrophoneId',+ 'voiceoverProvider',+ 'voiceoverApiKeys',+ 'voiceoverVoiceId',+ 'voiceoverModelId',- 'targetColor',- 'brandLogo',- 'brandFooter',- 'brandAttribution',]).then((result) => {const p = providerOrDefault(result.aiProvider);setProvider(p);- setApiKey(keyFor(migrateApiKeys(result), p));- setModel((result.aiModel as string) || AI_PROVIDERS[p].defaultModel);+ const keys = migrateApiKeys(result);+ setApiKeys(keys);+ setApiKey(keyFor(keys, p));- if (isCustomBaseUrl(AI_PROVIDERS[p], result.aiBaseUrl as string)) {- setBaseUrl(result.aiBaseUrl as string);- setOwnServer(true);- }- if (result.aiLanguage) setAiLanguage(result.aiLanguage as AILanguageCode);if (result.blurPresets) setBlurPresets(result.blurPresets as Record<PresetKey, boolean>);setVoiceProvider((result.voiceProvider as VoiceProvider) || 'openai');if (result.voiceApiKey) setVoiceApiKey(result.voiceApiKey as string);if (result.voiceMicrophoneId) setVoiceMicrophoneId(result.voiceMicrophoneId as string);+ const vo = resolveVoiceoverConfig(result);+ const voKeys = parseVoiceoverKeys(result.voiceoverApiKeys);+ setVoiceoverProviderKey(vo.provider);+ setVoiceoverApiKeys(voKeys);+ setVoiceoverApiKey(keyForVoiceoverProvider(voKeys, vo.provider));+ setVoiceoverVoiceId(vo.voiceId);+ setVoiceoverModelId(vo.modelId);+ setVoices(voiceoverProvider(vo.provider).voices);- if (result.targetColor) setTargetColor(result.targetColor as string);- if (result.brandLogo) setBrandLogo(result.brandLogo as BrandLogo);- setBrandFooter(typeof result.brandFooter === 'string' ? result.brandFooter : defaultFooterLine());- if (result.brandAttribution === false) setBrandAttribution(false);setLoaded(true);});}, []);@@@ -79,12 -180,141 +130,58 @@@voiceProvider,voiceApiKey,voiceMicrophoneId,+ voiceoverProvider: voiceoverProviderKey,+ voiceoverApiKeys: withVoiceoverKey(voiceoverApiKeys, voiceoverProviderKey, voiceoverApiKey),+ voiceoverVoiceId,+ voiceoverModelId,- targetColor,- brandLogo,- brandFooter,- brandAttribution,};- const flush = useCallback(async () => {- const patch = pending.current;- pending.current = {};- if (Object.keys(patch).length === 0) return;- try {- await localStorage.set(patch);- setSaved(true);- } catch (err) {- logger.error('Settings autosave failed', err);- setSaved(false);- }- }, []);-- useEffect(() => {- if (!loaded) return;- const snapshot = savedSnapshot.current;- if (!snapshot) {- savedSnapshot.current = stored;- return;- }-- const patch = changedSettings(stored, snapshot);- if (!patch) return;+ const { saved, queue } = useSettingsAutosave(stored, loaded);- savedSnapshot.current = stored;- Object.assign(pending.current, patch);- window.clearTimeout(saveTimer.current);- saveTimer.current = window.setTimeout(() => void flush(), SAVE_DEBOUNCE_MS);+ const voiceKey = resolveVoiceApiKey({ voiceProvider, voiceApiKey, aiProvider: provider, aiApiKey: apiKey });++ const voiceoverKey = resolveVoiceoverConfig({++ voiceoverProvider: voiceoverProviderKey,++ voiceoverApiKeys: withVoiceoverKey(voiceoverApiKeys, voiceoverProviderKey, voiceoverApiKey),++ voiceoverVoiceId,++ voiceoverModelId,++ aiProvider: provider,++ aiApiKey: apiKey,++ aiApiKeys: apiKeys,+ });+- useEffect(- () => () => {- window.clearTimeout(saveTimer.current);- void flush();- },- [flush],- );-- useEffect(() => {- if (!saved) return;- const timer = window.setTimeout(() => setSaved(false), SAVED_BADGE_MS);- return () => window.clearTimeout(timer);- }, [saved]);-+ useEffect(() => {+ const config = voiceoverProvider(voiceoverProviderKey);+ const key = voiceoverApiKey.trim();+ if (!config.catalog || !key) {+ setVoices(config.voices);+ return;+ }+ let active = true;+ const timer = window.setTimeout(() => {+ sendMessage('listVoices', { provider: voiceoverProviderKey, apiKey: key })+ .then((result) => {+ if (active && result.voices.length > 0) setVoices(result.voices);+ })+ .catch(() => undefined);+ }, 600);+ return () => {+ active = false;+ window.clearTimeout(timer);+ };+ }, [voiceoverProviderKey, voiceoverApiKey]);++ const handleVoiceoverProviderChange = (next: VoiceoverProviderKey) => {+ const keys = withVoiceoverKey(voiceoverApiKeys, voiceoverProviderKey, voiceoverApiKey);+ const config = voiceoverProvider(next);+ setVoiceoverApiKeys(keys);+ setVoiceoverProviderKey(next);+ setVoiceoverApiKey(keyForVoiceoverProvider(keys, next));+ setVoiceoverVoiceId(config.defaultVoice);+ setVoiceoverModelId(config.defaultModel);+ setVoices(config.voices);+ voiceoverKeyCheck.reset();+ };- const handleLogoPick = async (file: File | undefined) => {- if (!file) return;- setBrandLogo(await makeBrandLogo(file));- };-- const handleProviderChange = (newProvider: AIProviderKey) => {- setProvider(newProvider);- setApiKey(keyFor(apiKeys, newProvider));- aiKeyCheck.reset();- setCustomModel(false);- setModel(AI_PROVIDERS[newProvider].defaultModel);- setOwnServer(false);- setBaseUrl('');- };-- const handleOwnServerToggle = () => {- setOwnServer((on) => {- if (on) setBaseUrl('');- return !on;- });- aiKeyCheck.reset();- };-- const handleModelChange = (value: string) => {- if (value === CUSTOM_MODEL_VALUE) {- setCustomModel(true);- setModel('');- aiKeyCheck.reset();- return;- }- setCustomModel(false);- setModel(value);- aiKeyCheck.reset();- };-- const providerConfig = AI_PROVIDERS[provider] ?? AI_PROVIDERS[DEFAULT_AI_PROVIDER];- const usingCustomModel = customModel || isCustomModel(model, providerConfig);- const voiceKey = resolveVoiceApiKey({ voiceProvider, voiceApiKey, aiProvider: provider, aiApiKey: apiKey });- const voiceoverKey = resolveVoiceoverConfig({- voiceoverProvider: voiceoverProviderKey,- voiceoverApiKeys: withVoiceoverKey(voiceoverApiKeys, voiceoverProviderKey, voiceoverApiKey),- voiceoverVoiceId,- voiceoverModelId,- aiProvider: provider,- aiApiKey: apiKey,- aiApiKeys: apiKeys,- });-const BLUR_PRESET_I18N: Record<PresetKey, string> = {email: 'blurPresets.email',phone: 'blurPresets.phoneNumbers',@@@ -119,17 -349,297 +216,28 @@@</div><div className="flex-1 px-3 py-4 space-y-3">- <div className="border border-border rounded-[10px] p-3.5 space-y-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <Sparkles size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.aiDescriptions')}</span>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- {i18n.t('settings.provider')}- </label>- <Select value={provider} onValueChange={(v) => handleProviderChange(v as AIProviderKey)}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {Object.entries(AI_PROVIDERS).map(([key, cfg]) => (- <SelectItem key={key} value={key}>- {cfg.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.model')}</label>- <Select value={usingCustomModel ? CUSTOM_MODEL_VALUE : model} onValueChange={handleModelChange}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {providerConfig.models.map((m) => (- <SelectItem key={m.id} value={m.id}>- {m.label}- </SelectItem>- ))}- </SelectContent>- </Select>- {usingCustomModel && (- <Input- value={model}- onChange={(e) => {- setModel(e.target.value);- aiKeyCheck.reset();- }}- placeholder={providerConfig.defaultModel}- aria-label={i18n.t('settings.modelCustom')}- className="mt-1.5 h-8 text-[13px] rounded-lg border-border"- />- )}- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.apiKey')}</label>- <div className="flex items-center gap-1.5">- <SecretInput- value={apiKey}- onChange={(next) => {- setApiKey(next);- setApiKeys((prev) => withKeyFor(prev, provider, next));- aiKeyCheck.reset();- }}- placeholder="sk-..."- className="h-8 text-[13px] rounded-lg border-border"- />- <Button- variant="outline"- size="sm"- disabled={!apiKey || aiKeyCheck.status === 'checking'}- onClick={() => {- if (aiKeyCheck.status !== 'checking') void aiKeyCheck.check(provider, apiKey, baseUrl, model);- }}- className="h-8 shrink-0 rounded-lg bg-card text-[11px] font-semibold"- >- {i18n.t('settings.checkKey')}- </Button>- </div>- <KeyStatusNote status={aiKeyCheck.status} />- <KeyWarningNote warning={aiKeyCheck.warning} />- {aiKeyCheck.models && <ModelList models={aiKeyCheck.models} />}- {!apiKey.trim() && (- <p className="mt-1.5 flex items-start gap-1.5 text-[10px] text-destructive leading-relaxed" role="alert">- <TriangleAlert size={11} className="shrink-0 mt-0.5" />- <span>{i18n.t('settings.aiNoKey')}</span>- </p>- )}- </div>-- <div>- <div className="flex items-center justify-between gap-3 py-0.5">- <span className="text-[11px] font-semibold text-foreground flex items-center gap-1">- <Globe size={11} className="-mt-px" />- {i18n.t('settings.useOwnServer')}- </span>- <button- type="button"- role="switch"- aria-checked={ownServer}- aria-label={i18n.t('settings.useOwnServer')}- onClick={handleOwnServerToggle}- className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${- ownServer ? 'bg-accent' : 'bg-border'- }`}- >- <span- className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${- ownServer ? 'translate-x-4' : 'translate-x-0'- }`}- />- </button>- </div>- {ownServer && (- <div className="mt-2 space-y-1.5">- <Input- type="text"- value={baseUrl}- onChange={(e) => {- setBaseUrl(e.target.value);- aiKeyCheck.reset();- }}- placeholder={providerConfig.defaultBaseUrl}- aria-label={i18n.t('settings.baseUrl')}- className="h-8 text-[13px] rounded-lg border-border"- />- <p className="text-[10px] text-muted-foreground leading-relaxed">- {i18n.t(- providerConfig.protocol === 'anthropic'- ? 'settings.ownServerHintAnthropic'- : 'settings.ownServerHintOpenai',- )}- </p>- </div>- )}- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- <Globe size={11} className="inline mr-1 -mt-px" />- {i18n.t('settings.aiLanguage')}- </label>- <Select value={aiLanguage} onValueChange={(v) => setAiLanguage(v as AILanguageCode)}>- <SelectTrigger className="h-8">- <SelectValue />- </SelectTrigger>- <SelectContent>- {AI_LANGUAGES.map((lang) => (- <SelectItem key={lang.code} value={lang.code}>- {lang.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </div>-- <div className="border border-border rounded-[10px] p-3.5 flex items-center justify-between gap-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center shrink-0">- <Target size={14} className="text-accent" />- </div>- <div>- <div className="text-xs font-bold text-foreground">{i18n.t('settings.targetColor')}</div>- <div className="text-[11px] text-muted-foreground">{i18n.t('settings.targetColorHint')}</div>- </div>- </div>- <Popover>- <PopoverTrigger asChild>- <button- type="button"- className="flex items-center gap-2 shrink-0 border border-border rounded-lg px-2 py-1.5 text-[11px] text-foreground hover:border-accent"- >- <span- className="w-[22px] h-[22px] rounded-full border border-foreground/15"- style={{ backgroundColor: targetColor }}- />- <code className="tabular-nums">{targetColor.toUpperCase()}</code>- <ChevronDown size={12} className="opacity-60" />- </button>- </PopoverTrigger>- <PopoverContent align="end" className="w-56 p-2.5">- <ColorPicker value={targetColor} presets={TARGET_COLORS} onChange={setTargetColor} />- </PopoverContent>- </Popover>- </div>-- <div className="border border-border rounded-[10px] p-3.5 space-y-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <ImageIcon size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.branding')}</span>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- {i18n.t('settings.brandLogo')}- </label>- <input- ref={logoInputRef}- type="file"- accept="image/png,image/jpeg,image/svg+xml,image/webp"- className="hidden"- onChange={(e) => handleLogoPick(e.target.files?.[0])}- />- <div className="flex items-center gap-2.5">- {brandLogo && (- <img- src={brandLogo.dataUrl}- alt=""- className="h-9 max-w-[92px] object-contain rounded border border-border bg-secondary p-1"- />- )}- <button- type="button"- onClick={() => logoInputRef.current?.click()}- className="border border-border rounded-lg px-2.5 py-1.5 text-[11px] font-medium text-foreground hover:border-accent transition-colors"- >- {brandLogo ? i18n.t('settings.replaceLogo') : i18n.t('settings.uploadLogo')}- </button>- {brandLogo && (- <button- onClick={() => setBrandLogo(null)}- aria-label={i18n.t('settings.removeLogo')}- className="w-7 h-7 rounded-lg flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors"- >- <Trash2 size={14} />- </button>- )}- </div>- </div>-- <div>- <label className="block text-[11px] font-semibold text-foreground mb-1">- {i18n.t('settings.footerLine')}- </label>- <Input- value={brandFooter}- onChange={(e) => setBrandFooter(e.target.value)}- placeholder={i18n.t('settings.footerLinePlaceholder')}- className="h-8 text-[13px] rounded-lg border-border"- />- <div className="flex flex-wrap gap-1.5 mt-2">- {FOOTER_PRESETS().map((preset) => (- <button- key={preset}- type="button"- onClick={() => setBrandFooter(preset)}- className={`px-2 py-1 rounded-md border text-[10px] transition-colors ${- brandFooter === preset- ? 'border-accent text-accent'- : 'border-border text-muted-foreground hover:border-accent hover:text-foreground'- }`}- >- {preset}- </button>- ))}- </div>- </div>-- <div className="flex items-center justify-between gap-3 pt-1">- <div className="text-[11px] font-semibold text-foreground">{i18n.t('settings.attribution')}</div>- <button- onClick={() => setBrandAttribution((prev) => !prev)}- className={`w-9 h-5 rounded-full transition-colors relative shrink-0 ${- brandAttribution ? 'bg-accent' : 'bg-border'- }`}- >- <span- className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${- brandAttribution ? 'translate-x-4' : 'translate-x-0'- }`}- />- </button>- </div>- </div>-- <div className="border border-border rounded-[10px] p-3.5 space-y-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <Mic size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.voiceNarration')}</span>- <span className="ml-auto shrink-0 rounded-md bg-secondary px-1.5 py-0.5 text-[9px] font-semibold tracking-wide text-muted-foreground">+ <AiSettings+ keyCheck={aiKeyCheck}+ onChange={(patch) => {+ if (typeof patch.aiProvider === 'string') setProvider(patch.aiProvider as AIProviderKey);+ if (typeof patch.aiApiKey === 'string') setApiKey(patch.aiApiKey);++ if (patch.aiApiKeys && typeof patch.aiApiKeys === 'object')++ setApiKeys(patch.aiApiKeys as Record<string, string>);+ }}+ />++ <BrandingSettings onChange={queue} />+- <SettingsCard icon={Mic} title={i18n.t('settings.voiceNarration')}>++ <SettingsCard++ icon={Mic}++ title={i18n.t('settings.voiceNarration')}++ hint={i18n.t('settings.voiceNarrationHint')}++ action={++ <span className="shrink-0 rounded-md bg-secondary px-1.5 py-0.5 text-[9px] font-semibold tracking-wide text-muted-foreground">+ {i18n.t('settings.speechToText')}+ </span>- </div>-- <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('settings.voiceNarrationHint')}</p>-++ }++ ><div><label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.provider')}@@@ -192,9 -702,120 +300,110 @@@{import.meta.env.BROWSER !== 'firefox' && (<MicrophonePicker value={voiceMicrophoneId} onChange={setVoiceMicrophoneId} triggerClassName="h-8" />)}- </div>-- <div className="border border-border rounded-[10px] p-3.5 space-y-3">- <div className="flex items-center gap-2.5">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <AudioLines size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.voiceover')}</span>- <span className="ml-auto shrink-0 rounded-md bg-secondary px-1.5 py-0.5 text-[9px] font-semibold tracking-wide text-muted-foreground">+ </SettingsCard>+++ <SettingsCard++ icon={AudioLines}++ title={i18n.t('settings.voiceover')}++ hint={i18n.t('settings.voiceoverHint')}++ action={++ <span className="shrink-0 rounded-md bg-secondary px-1.5 py-0.5 text-[9px] font-semibold tracking-wide text-muted-foreground">+ {i18n.t('settings.textToSpeech')}+ </span>- </div>-- <p className="text-[10px] text-muted-foreground leading-relaxed">{i18n.t('settings.voiceoverHint')}</p>-++ }++ >+ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">+ {i18n.t('settings.provider')}+ </label>+ <Select+ value={voiceoverProviderKey}+ onValueChange={(v) => handleVoiceoverProviderChange(v as VoiceoverProviderKey)}+ >+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {VOICEOVER_PROVIDER_KEYS.map((key) => (+ <SelectItem key={key} value={key}>+ {VOICEOVER_PROVIDERS[key].label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.apiKey')}</label>+ <div className="flex items-center gap-1.5">+ <SecretInput+ value={voiceoverApiKey}+ onChange={(next) => {+ setVoiceoverApiKey(next);+ voiceoverKeyCheck.reset();+ }}+ placeholder={voiceoverKeyPlaceholder(voiceoverProviderKey)}+ className="h-8 text-[13px] rounded-lg border-border"+ />+ <Button+ variant="outline"+ size="sm"+ disabled={!voiceoverApiKey || voiceoverKeyCheck.status === 'checking'}+ onClick={() => void voiceoverKeyCheck.check(voiceoverProviderKey, voiceoverApiKey)}+ className="h-8 shrink-0 rounded-lg bg-card text-[11px] font-semibold"+ >+ {i18n.t('settings.checkKey')}+ </Button>+ </div>+ <KeyStatusNote status={voiceoverKeyCheck.status} />+ {voiceoverKey.source === 'ai' && (+ <p className="mt-1.5 flex items-start gap-1.5 text-[10px] text-muted-foreground leading-relaxed">+ <Sparkles size={11} className="shrink-0 mt-0.5 text-accent" />+ <span>{i18n.t('settings.voiceoverUsingAiKey')}</span>+ </p>+ )}+ {voiceoverKey.source === 'none' && (+ <p className="mt-1.5 flex items-start gap-1.5 text-[10px] text-muted-foreground leading-relaxed">+ <TriangleAlert size={11} className="shrink-0 mt-0.5 text-destructive" />+ <span>{i18n.t('settings.voiceoverNoKey')}</span>+ </p>+ )}+ </div>++ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.voice')}</label>+ <Select value={voiceoverVoiceId} onValueChange={setVoiceoverVoiceId}>+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {voices.map((voice) => (+ <SelectItem key={voice.id} value={voice.id}>+ {voice.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div>+ <label className="block text-[11px] font-semibold text-foreground mb-1">{i18n.t('settings.model')}</label>+ <Select value={voiceoverModelId} onValueChange={setVoiceoverModelId}>+ <SelectTrigger className="h-8">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {voiceoverProvider(voiceoverProviderKey).models.map((option) => (+ <SelectItem key={option.id} value={option.id}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>- </div>-- <div className="border border-border rounded-[10px] p-3.5 space-y-1">- <div className="flex items-center gap-2.5 mb-2">- <div className="w-7 h-7 rounded-lg bg-secondary flex items-center justify-center">- <EyeOff size={14} className="text-accent" />- </div>- <span className="text-xs font-bold text-foreground">{i18n.t('settings.smartBlur')}</span>- </div>++ </SettingsCard>++ <SettingsCard icon={EyeOff} title={i18n.t('settings.smartBlur')} className="space-y-1 [&>*:first-child]:mb-2">{(Object.keys(PRESET_LABELS) as PresetKey[]).map((key, i, arr) => (<divkey={key}diff --cc src/ui/sidepanel/App.tsxindex 8f40a3b,4fe7edf..2af68a2--- a/src/ui/sidepanel/App.tsx+++ b/src/ui/sidepanel/App.tsx@@@ -3,30 -1,34 +3,30 @@@ import { Button, Input, TooltipProvideimport { Globe, Search, Settings, Video } from 'lucide-react';import { useCallback, useEffect, useState } from 'react';import { browser, i18n } from '#imports';+import { isRecordableUrl } from '@/capture/recordable-tabs';- import { CaptureState } from '@/core/capture/machine';+ import { CaptureState, type PauseReason } from '@/core/capture/machine';-import { isRecordableUrl } from '@/core/capture/recordable-tabs';import type { GuideMeSession } from '@/core/guideme/session';import { SESSION_KEY } from '@/core/guideme/session';-import {- createTab,- focusWindow,- getActiveTab,- getExtensionURL,- queryTabs,- requestHostPermissions,- updateTab,-} from '@/lib/browser-api';-import { logger } from '@/lib/logger';+import { createTab } from '@/lib/browser-api/create-tab';+import { focusWindow } from '@/lib/browser-api/focus-window';+import { getActiveTab } from '@/lib/browser-api/get-active-tab';+import { getExtensionURL } from '@/lib/browser-api/get-extension-url';+import { queryTabs } from '@/lib/browser-api/query-tabs';+import { requestHostPermissions } from '@/lib/browser-api/request-host-permissions';+import { updateTab } from '@/lib/browser-api/update-tab';import { sendMessage } from '@/lib/messaging';-import { getVoiceStatus } from '@/lib/offscreen';-import { connectToBackground, type PanelAiUpdate, type PanelVoiceUpdate } from '@/lib/port';-import { Button } from '@/ui/components/ui/button';-import { Input } from '@/ui/components/ui/input';-import { TooltipProvider } from '@/ui/components/ui/tooltip';-import SettingsView from '@/ui/shared/SettingsView';-import UpdateNotice from '@/ui/shared/UpdateNotice';-import GuideEditor from './GuideEditor';-import GuideMeCompletion from './GuideMeCompletion';-import GuideMeView from './GuideMeView';-import LibraryView from './LibraryView';-import RecordingView from './RecordingView';-import VoiceToast from './VoiceToast';+import { getVoiceStatus } from '@/lib/offscreen/get-voice-status';+import { connectToBackground } from '@/lib/port/connect-to-background';+import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port/types';+import { SettingsView } from '@/ui/shared/SettingsView';+import { UpdateNotice } from '@/ui/shared/UpdateNotice';+import { GuideEditor } from './GuideEditor';+import { GuideMeCompletion } from './GuideMeCompletion';+import { GuideMeView } from './GuideMeView';+import { LibraryView } from './LibraryView';+import { MascotIcon } from './MascotIcon';+import { RecordingView } from './RecordingView';+import { VoiceToast } from './VoiceToast';type View =| { name: 'library' }diff --cc src/ui/sidepanel/LibraryView.tsxindex 79d812b,6834503..0fdb78d--- a/src/ui/sidepanel/LibraryView.tsx+++ b/src/ui/sidepanel/LibraryView.tsx@@@ -1,5 -1,4 +1,5 @@@+import { FaviconImg, formatRelativeTime, Tooltip, TooltipContent, TooltipTrigger } from '@mimik/ui';- import { Star, Trash2 } from 'lucide-react';+ import { LayoutDashboard, Star, Trash2 } from 'lucide-react';import { useCallback, useEffect, useState } from 'react';import { i18n } from '#imports';import {@@@ -11,6 -10,22 +11,7 @@@toggleStar,} from '@/core/guides/service';import type { Guide } from '@/core/guides/types';-import { createTab, focusWindow, getExtensionURL, queryTabs, updateTab } from '@/lib/browser-api';-import { formatRelativeTime } from '@/lib/utils';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';-import FaviconImg from '@/ui/shared/FaviconImg';--async function openDashboard() {- const url = getExtensionURL('/fullview.html');- const tabs = await queryTabs({ url });- const existing = tabs[0];- if (existing?.id) {- await updateTab(existing.id, { active: true });- if (existing.windowId) await focusWindow(existing.windowId);- } else {- await createTab({ url });- }-}++import { openDashboard } from './lib/open-dashboard';interface LibraryViewProps {onOpen: (guideId: string) => void;diff --cc src/ui/sidepanel/MicToggle.tsxindex fc37b55,aaf6433..c920a9e--- a/src/ui/sidepanel/MicToggle.tsx+++ b/src/ui/sidepanel/MicToggle.tsx@@@ -17,7 -15,18 +18,7 @@@ interface MicTogglePropsonChange: (enabled: boolean) => void;}- export function MicToggle({ enabled, live, onChange }: MicToggleProps) {-const MICROPHONE: PermissionDescriptor = { name: 'microphone' as PermissionName };--async function microphoneGranted(): Promise<boolean> {- try {- const status = await navigator.permissions.query(MICROPHONE);- return status.state === 'granted';- } catch {- return false;- }-}--export default function MicToggle({ enabled, live, paused = false, onChange }: MicToggleProps) {++export function MicToggle({ enabled, live, paused = false, onChange }: MicToggleProps) {const [keyed, setKeyed] = useState(false);useEffect(() => {diff --cc src/ui/sidepanel/RecordingView.tsxindex 5fb65dc,aceeaa3..df59cd3--- a/src/ui/sidepanel/RecordingView.tsx+++ b/src/ui/sidepanel/RecordingView.tsx@@@ -1,43 -1,45 +1,45 @@@+import { extractDomain } from '@mimik/core/guides/domain';+import {+ Button,+ CameraMascot,+ ScreenshotView,+ StepSourceBadge,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@mimik/ui';- import { Check, EyeOff, Loader2, X } from 'lucide-react';+ import { Check, EyeOff, Loader2, Pause, Play, X } from 'lucide-react';import { useCallback, useEffect, useRef, useState } from 'react';- import { browser, i18n } from '#imports';+ import { i18n } from '#imports';+ import type { PauseReason } from '@/core/capture/machine';import { deleteStep, getScreenshotsForSteps, getStepsForGuide } from '@/core/guides/service';import type { Screenshot, Step } from '@/core/guides/types';-import { getActiveTab, localStorage } from '@/lib/browser-api';+import { getActiveTab } from '@/lib/browser-api/get-active-tab';+import { localStorage } from '@/lib/browser-api/local-storage';import { sendMessage } from '@/lib/messaging';-import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port';-import { extractDomain } from '@/lib/utils';-import { Button } from '@/ui/components/ui/button';-import { Tooltip, TooltipContent, TooltipTrigger } from '@/ui/components/ui/tooltip';-import ScreenshotView from '@/ui/shared/ScreenshotView';-import StepSourceBadge from '@/ui/shared/StepSourceBadge';-import AiStatus from './AiStatus';-import MicToggle from './MicToggle';-import VoiceStatus from './VoiceStatus';+import type { PanelAiUpdate, PanelVoiceUpdate } from '@/lib/port/types';+import { AiStatus } from './AiStatus';+import { timeAgo } from './lib/time-ago';+import { MicToggle } from './MicToggle';+import { VoiceStatus } from './VoiceStatus';interface RecordingViewProps {guideId: string;onStop: () => void;voice: PanelVoiceUpdate;aiFailure: PanelAiUpdate | null;+ paused: boolean;+ pauseReason: PauseReason | null;}-function timeAgo(createdAt: number): string {- const diff = Math.floor((Date.now() - createdAt) / 1000);- if (diff < 3) return i18n.t('recording.justNow');- if (diff < 60) return i18n.t('recording.secondsAgo', [String(diff)]);- return i18n.t('recording.minutesAgo', [String(Math.floor(diff / 60))]);-}-interface LiveStep {step: Step;screenshot?: Screenshot;}- export function RecordingView({ guideId, onStop, voice, aiFailure }: RecordingViewProps) {-export default function RecordingView({ guideId, onStop, voice, aiFailure, paused, pauseReason }: RecordingViewProps) {++export function RecordingView({ guideId, onStop, voice, aiFailure, paused, pauseReason }: RecordingViewProps) {const [steps, setSteps] = useState<LiveStep[]>([]);const [siteUrl, setSiteUrl] = useState('');- const [isBlurring, setIsBlurring] = useState(false);const [voiceEnabled, setVoiceEnabled] = useState(false);const [, setTick] = useState(0);const bottomRef = useRef<HTMLDivElement>(null);diff --cc src/ui/sidepanel/VoiceStatus.tsxindex 3df0561,fa7fbb8..204bef5--- a/src/ui/sidepanel/VoiceStatus.tsx+++ b/src/ui/sidepanel/VoiceStatus.tsx@@@ -7,9 -7,10 +7,10 @@@ import { MicMeter } from './MicMeter'interface VoiceStatusProps {update: PanelVoiceUpdate;enabled: boolean;+ paused?: boolean;}- export function VoiceStatus({ update, enabled }: VoiceStatusProps) {-export default function VoiceStatus({ update, enabled, paused = false }: VoiceStatusProps) {++export function VoiceStatus({ update, enabled, paused = false }: VoiceStatusProps) {if (update.phase === 'error') {return (<div className="px-4 pt-2.5 flex items-start gap-2" role="status">diff --cc src/ui/sidepanel/__tests__/voice-status-paused.test.tsxindex 0000000,010dafa..857f831mode 000000,100644..100644--- a/src/ui/sidepanel/__tests__/voice-status-paused.test.tsx+++ b/src/ui/sidepanel/__tests__/voice-status-paused.test.tsx@@@ -1,0 -1,32 +1,32 @@@+ // @vitest-environment jsdom+ import { render, screen } from '@testing-library/react';+ import { describe, expect, it, vi } from 'vitest';-import type { PanelVoiceUpdate } from '@/lib/port';++import type { PanelVoiceUpdate } from '@/lib/port/types';+-vi.mock('../MicMeter', () => ({ default: () => null }));++vi.mock('../MicMeter', () => ({ MicMeter: () => null }));+-import VoiceStatus from '../VoiceStatus';++import { VoiceStatus } from '../VoiceStatus';++ const idle: PanelVoiceUpdate = { type: 'VOICE_UPDATE', phase: 'idle' };++ describe('the narration line under a paused recording', () => {+ it('says narration is paused, not that it starts with the next recording', () => {+ render(<VoiceStatus update={idle} enabled paused />);++ expect(screen.getByText('voice.pausedWithCapture')).toBeTruthy();+ expect(screen.queryByText('voice.nextRecording')).toBeNull();+ });++ it('still promises the next recording when capture is not paused', () => {+ render(<VoiceStatus update={idle} enabled />);++ expect(screen.getByText('voice.nextRecording')).toBeTruthy();+ expect(screen.queryByText('voice.pausedWithCapture')).toBeNull();+ });++ it('says nothing at all when narration is switched off', () => {+ const { container } = render(<VoiceStatus update={idle} enabled={false} paused />);++ expect(container.textContent).toBe('');+ });+ });diff --cc src/ui/sidepanel/lib/open-dashboard.tsindex 0000000,0000000..5cfa477new file mode 100644--- /dev/null+++ b/src/ui/sidepanel/lib/open-dashboard.ts@@@ -1,0 -1,0 +1,17 @@@++import { createTab } from '@/lib/browser-api/create-tab';++import { focusWindow } from '@/lib/browser-api/focus-window';++import { getExtensionURL } from '@/lib/browser-api/get-extension-url';++import { queryTabs } from '@/lib/browser-api/query-tabs';++import { updateTab } from '@/lib/browser-api/update-tab';++++export async function openDashboard() {++ const url = getExtensionURL('/fullview.html');++ const tabs = await queryTabs({ url });++ const existing = tabs[0];++ if (existing?.id) {++ await updateTab(existing.id, { active: true });++ if (existing.windowId) await focusWindow(existing.windowId);++ } else {++ await createTab({ url });++ }++}