Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
Neon auth refactor (#187)
Gabriel Stein173642e60814
diff --git a/.agents/skills/vercel-composition-patterns/AGENTS.md b/.agents/skills/vercel-composition-patterns/AGENTS.mdnew file mode 100644index 000000000..cf11436f3--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/AGENTS.md@@ -0,0 +1,899 @@+# React Composition Patterns++**Version 1.0.0**+Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React codebases using composition. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.++---++## Table of Contents++1. [Component Architecture](#1-component-architecture) — **HIGH**+ - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)+ - 1.2 [Use Compound Components](#12-use-compound-components)+2. [State Management](#2-state-management) — **MEDIUM**+ - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)+ - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)+ - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)+3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**+ - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)+ - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)++---++## 1. Component Architecture++**Impact: HIGH**++Fundamental patterns for structuring components to avoid prop+proliferation and enable flexible composition.++### 1.1 Avoid Boolean Prop Proliferation++**Impact: CRITICAL (prevents unmaintainable component variants)**++Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize++component behavior. Each boolean doubles possible states and creates++unmaintainable conditional logic. Use composition instead.++**Incorrect: boolean props create exponential complexity**++```tsx+function Composer({+ onSubmit,+ isThread,+ channelId,+ isDMThread,+ dmId,+ isEditing,+ isForwarding,+}: Props) {+ return (+ <form>+ <Header />+ <Input />+ {isDMThread ? (+ <AlsoSendToDMField id={dmId} />+ ) : isThread ? (+ <AlsoSendToChannelField id={channelId} />+ ) : null}+ {isEditing ? (+ <EditActions />+ ) : isForwarding ? (+ <ForwardActions />+ ) : (+ <DefaultActions />+ )}+ <Footer onSubmit={onSubmit} />+ </form>+ )+}+```++**Correct: composition eliminates conditionals**++```tsx+// Channel composer+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Attachments />+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Thread composer - adds "also send to channel" field+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <AlsoSendToChannelField id={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Edit composer - different footer actions+function EditComposer() {+ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ )+}+```++Each variant is explicit about what it renders. We can share internals without++sharing a single monolithic parent.++### 1.2 Use Compound Components++**Impact: HIGH (enables flexible composition without prop drilling)**++Structure complex components as compound components with a shared context. Each++subcomponent accesses shared state via context, not props. Consumers compose the++pieces they need.++**Incorrect: monolithic component with render props**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+ showAttachments,+ showFormatting,+ showEmojis,+}: Props) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {showAttachments && <Attachments />}+ {renderFooter ? (+ renderFooter()+ ) : (+ <Footer>+ {showFormatting && <Formatting />}+ {showEmojis && <Emojis />}+ {renderActions?.()}+ </Footer>+ )}+ </form>+ )+}+```++**Correct: compound components with shared context**++```tsx+const ComposerContext = createContext<ComposerContextValue | null>(null)++function ComposerProvider({ children, state, actions, meta }: ProviderProps) {+ return (+ <ComposerContext value={{ state, actions, meta }}>+ {children}+ </ComposerContext>+ )+}++function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>+}++function ComposerInput() {+ const {+ state,+ actions: { update },+ meta: { inputRef },+ } = use(ComposerContext)+ return (+ <TextInput+ ref={inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ )+}++function ComposerSubmit() {+ const {+ actions: { submit },+ } = use(ComposerContext)+ return <Button onPress={submit}>Send</Button>+}++// Export as compound component+const Composer = {+ Provider: ComposerProvider,+ Frame: ComposerFrame,+ Input: ComposerInput,+ Submit: ComposerSubmit,+ Header: ComposerHeader,+ Footer: ComposerFooter,+ Attachments: ComposerAttachments,+ Formatting: ComposerFormatting,+ Emojis: ComposerEmojis,+}+```++**Usage:**++```tsx+<Composer.Provider state={state} actions={actions} meta={meta}>+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+</Composer.Provider>+```++Consumers explicitly compose exactly what they need. No hidden conditionals. And++the state, actions and meta are dependency-injected by a parent provider,++allowing multiple usages of the same component structure.++---++## 2. State Management++**Impact: MEDIUM**++Patterns for lifting state and managing shared context across+composed components.++### 2.1 Decouple State Management from UI++**Impact: MEDIUM (enables swapping state implementations without changing UI)**++The provider component should be the only place that knows how state is managed.++UI components consume the context interface—they don't know if state comes from++useState, Zustand, or a server sync.++**Incorrect: UI coupled to state implementation**++```tsx+function ChannelComposer({ channelId }: { channelId: string }) {+ // UI component knows about global state implementation+ const state = useGlobalChannelState(channelId)+ const { submit, updateInput } = useChannelSync(channelId)++ return (+ <Composer.Frame>+ <Composer.Input+ value={state.input}+ onChange={(text) => sync.updateInput(text)}+ />+ <Composer.Submit onPress={() => sync.submit()} />+ </Composer.Frame>+ )+}+```++**Correct: state management isolated in provider**++```tsx+// Provider handles all state management details+function ChannelProvider({+ channelId,+ children,+}: {+ channelId: string+ children: React.ReactNode+}) {+ const { state, update, submit } = useGlobalChannel(channelId)+ const inputRef = useRef(null)++ return (+ <Composer.Provider+ state={state}+ actions={{ update, submit }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ )+}++// UI component only knows about the context interface+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Usage+function Channel({ channelId }: { channelId: string }) {+ return (+ <ChannelProvider channelId={channelId}>+ <ChannelComposer />+ </ChannelProvider>+ )+}+```++**Different providers, same UI:**++```tsx+// Local state for ephemeral forms+function ForwardMessageProvider({ children }) {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ >+ {children}+ </Composer.Provider>+ )+}++// Global synced state for channels+function ChannelProvider({ channelId, children }) {+ const { state, update, submit } = useGlobalChannel(channelId)++ return (+ <Composer.Provider state={state} actions={{ update, submit }}>+ {children}+ </Composer.Provider>+ )+}+```++The same `Composer.Input` component works with both providers because it only++depends on the context interface, not the implementation.++### 2.2 Define Generic Context Interfaces for Dependency Injection++**Impact: HIGH (enables dependency-injectable state across use-cases)**++Define a **generic interface** for your component context with three parts:++`state`, `actions`, and `meta`. This interface is a contract that any provider++can implement—enabling the same UI components to work with completely different++state implementations.++**Core principle:** Lift state, compose internals, make state++dependency-injectable.++**Incorrect: UI coupled to specific state implementation**++```tsx+function ComposerInput() {+ // Tightly coupled to a specific hook+ const { input, setInput } = useChannelComposerState()+ return <TextInput value={input} onChangeText={setInput} />+}+```++**Correct: generic interface enables dependency injection**++```tsx+// Define a GENERIC interface that any provider can implement+interface ComposerState {+ input: string+ attachments: Attachment[]+ isSubmitting: boolean+}++interface ComposerActions {+ update: (updater: (state: ComposerState) => ComposerState) => void+ submit: () => void+}++interface ComposerMeta {+ inputRef: React.RefObject<TextInput>+}++interface ComposerContextValue {+ state: ComposerState+ actions: ComposerActions+ meta: ComposerMeta+}++const ComposerContext = createContext<ComposerContextValue | null>(null)+```++**UI components consume the interface, not the implementation:**++```tsx+function ComposerInput() {+ const {+ state,+ actions: { update },+ meta,+ } = use(ComposerContext)++ // This component works with ANY provider that implements the interface+ return (+ <TextInput+ ref={meta.inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ )+}+```++**Different providers implement the same interface:**++```tsx+// Provider A: Local state for ephemeral forms+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState)+ const inputRef = useRef(null)++ return (+ <ComposerContext+ value={{+ state,+ actions: { update: setState, submit: useForwardMessage() },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ )+}++// Provider B: Global synced state for channels+function ChannelProvider({ channelId, children }: Props) {+ const { state, update, submit } = useGlobalChannel(channelId)+ const inputRef = useRef(null)++ return (+ <ComposerContext+ value={{+ state,+ actions: { update, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ )+}+```++**The same composed UI works with both:**++```tsx+// Works with ForwardMessageProvider (local state)+<ForwardMessageProvider>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ForwardMessageProvider>++// Works with ChannelProvider (global synced state)+<ChannelProvider channelId="abc">+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ChannelProvider>+```++**Custom UI outside the component can access state and actions:**++```tsx+function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ {/* The composer UI */}+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ </Composer.Footer>+ </Composer.Frame>++ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}+ <MessagePreview />++ {/* Actions at the bottom of the dialog */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ )+}++// This button lives OUTSIDE Composer.Frame but can still submit!+function ForwardButton() {+ const {+ actions: { submit },+ } = use(ComposerContext)+ return <Button onPress={submit}>Forward</Button>+}++// This preview lives OUTSIDE Composer.Frame but can read state!+function MessagePreview() {+ const { state } = use(ComposerContext)+ return <Preview message={state.input} attachments={state.attachments} />+}+```++The provider boundary is what matters—not the visual nesting. Components that++need shared state don't have to be inside the `Composer.Frame`. They just need++to be within the provider.++The `ForwardButton` and `MessagePreview` are not visually inside the composer++box, but they can still access its state and actions. This is the power of++lifting state into providers.++The UI is reusable bits you compose together. The state is dependency-injected++by the provider. Swap the provider, keep the UI.++### 2.3 Lift State into Provider Components++**Impact: HIGH (enables state sharing outside component boundaries)**++Move state management into dedicated provider components. This allows sibling++components outside the main UI to access and modify state without prop drilling++or awkward refs.++**Incorrect: state trapped inside component**++```tsx+function ForwardMessageComposer() {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()++ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer />+ </Composer.Frame>+ )+}++// Problem: How does this button access composer state?+function ForwardMessageDialog() {+ return (+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Needs composer state */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Needs to call submit */}+ </DialogActions>+ </Dialog>+ )+}+```++**Incorrect: useEffect to sync state up**++```tsx+function ForwardMessageDialog() {+ const [input, setInput] = useState('')+ return (+ <Dialog>+ <ForwardMessageComposer onInputChange={setInput} />+ <MessagePreview input={input} />+ </Dialog>+ )+}++function ForwardMessageComposer({ onInputChange }) {+ const [state, setState] = useState(initialState)+ useEffect(() => {+ onInputChange(state.input) // Sync on every change 😬+ }, [state.input])+}+```++**Incorrect: reading state from ref on submit**++```tsx+function ForwardMessageDialog() {+ const stateRef = useRef(null)+ return (+ <Dialog>+ <ForwardMessageComposer stateRef={stateRef} />+ <ForwardButton onPress={() => submit(stateRef.current)} />+ </Dialog>+ )+}+```++**Correct: state lifted to provider**++```tsx+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()+ const inputRef = useRef(null)++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ )+}++function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Custom components can access state and actions */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Custom components can access state and actions */}+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ )+}++function ForwardButton() {+ const { actions } = use(Composer.Context)+ return <Button onPress={actions.submit}>Forward</Button>+}+```++The ForwardButton lives outside the Composer.Frame but still has access to the++submit action because it's within the provider. Even though it's a one-off++component, it can still access the composer's state and actions from outside the++UI itself.++**Key insight:** Components that need shared state don't have to be visually++nested inside each other—they just need to be within the same provider.++---++## 3. Implementation Patterns++**Impact: MEDIUM**++Specific techniques for implementing compound components and+context providers.++### 3.1 Create Explicit Component Variants++**Impact: MEDIUM (self-documenting code, no hidden conditionals)**++Instead of one component with many boolean props, create explicit variant++components. Each variant composes the pieces it needs. The code documents++itself.++**Incorrect: one component, many modes**++```tsx+// What does this component actually render?+<Composer+ isThread+ isEditing={false}+ channelId='abc'+ showAttachments+ showFormatting={false}+/>+```++**Correct: explicit variants**++```tsx+// Immediately clear what this renders+<ThreadComposer channelId="abc" />++// Or+<EditMessageComposer messageId="xyz" />++// Or+<ForwardMessageComposer />+```++Each implementation is unique, explicit and self-contained. Yet they can each++use shared parts.++**Implementation:**++```tsx+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <ThreadProvider channelId={channelId}>+ <Composer.Frame>+ <Composer.Input />+ <AlsoSendToChannelField channelId={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ </ThreadProvider>+ )+}++function EditMessageComposer({ messageId }: { messageId: string }) {+ return (+ <EditMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ </EditMessageProvider>+ )+}++function ForwardMessageComposer() {+ return (+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Mentions />+ </Composer.Footer>+ </Composer.Frame>+ )+}+```++Each variant is explicit about:++- What provider/state it uses++- What UI elements it includes++- What actions are available++No boolean prop combinations to reason about. No impossible states.++### 3.2 Prefer Composing Children Over Render Props++**Impact: MEDIUM (cleaner composition, better readability)**++Use `children` for composition instead of `renderX` props. Children are more++readable, compose naturally, and don't require understanding callback++signatures.++**Incorrect: render props**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+}: {+ renderHeader?: () => React.ReactNode+ renderFooter?: () => React.ReactNode+ renderActions?: () => React.ReactNode+}) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {renderFooter ? renderFooter() : <DefaultFooter />}+ {renderActions?.()}+ </form>+ )+}++// Usage is awkward and inflexible+return (+ <Composer+ renderHeader={() => <CustomHeader />}+ renderFooter={() => (+ <>+ <Formatting />+ <Emojis />+ </>+ )}+ renderActions={() => <SubmitButton />}+ />+)+```++**Correct: compound components with children**++```tsx+function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>+}++function ComposerFooter({ children }: { children: React.ReactNode }) {+ return <footer className='flex'>{children}</div>+}++// Usage is flexible+return (+ <Composer.Frame>+ <CustomHeader />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <SubmitButton />+ </Composer.Footer>+ </Composer.Frame>+)+```++**When render props are appropriate:**++```tsx+// Render props work well when you need to pass data back+<List+ data={items}+ renderItem={({ item, index }) => <Item item={item} index={index} />}+/>+```++Use render props when the parent needs to provide data or state to the child.++Use children when composing static structure.++---++## References++1. [https://react.dev](https://react.dev)+2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)+3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)diff --git a/.agents/skills/vercel-composition-patterns/SKILL.md b/.agents/skills/vercel-composition-patterns/SKILL.mdnew file mode 100644index 000000000..7cab23ab8--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/SKILL.md@@ -0,0 +1,81 @@+---+name: vercel-composition-patterns+description:+ React composition patterns that scale. Use when refactoring components with+ boolean prop proliferation, building flexible component libraries, or+ designing reusable APIs. Triggers on tasks involving compound components,+ render props, context providers, or component architecture.+license: MIT+metadata:+ author: vercel+ version: '1.0.0'+---++# React Composition Patterns++Composition patterns for building flexible, maintainable React components. Avoid+boolean prop proliferation by using compound components, lifting state, and+composing internals. These patterns make codebases easier for both humans and AI+agents to work with as they scale.++## When to Apply++Reference these guidelines when:++- Refactoring components with many boolean props+- Building reusable component libraries+- Designing flexible component APIs+- Reviewing component architecture+- Working with compound components or context providers++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+| -------- | ----------------------- | ------ | --------------- |+| 1 | Component Architecture | HIGH | `architecture-` |+| 2 | State Management | MEDIUM | `state-` |+| 3 | Implementation Patterns | MEDIUM | `patterns-` |++## Quick Reference++### 1. Component Architecture (HIGH)++- `architecture-avoid-boolean-props` - Don't add boolean props to customize+ behavior; use composition+- `architecture-compound-components` - Structure complex components with shared+ context++### 2. State Management (MEDIUM)++- `state-decouple-implementation` - Provider is the only place that knows how+ state is managed+- `state-context-interface` - Define generic interface with state, actions, meta+ for dependency injection+- `state-lift-state` - Move state into provider components for sibling access++### 3. Implementation Patterns (MEDIUM)++- `patterns-explicit-variants` - Create explicit variant components instead of+ boolean modes+- `patterns-children-over-render-props` - Use children for composition instead+ of renderX props++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/architecture-avoid-boolean-props.md+rules/state-context-interface.md+```++Each rule file contains:++- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.mdnew file mode 100644index 000000000..ccee19ce4--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md@@ -0,0 +1,100 @@+---+title: Avoid Boolean Prop Proliferation+impact: CRITICAL+impactDescription: prevents unmaintainable component variants+tags: composition, props, architecture+---++## Avoid Boolean Prop Proliferation++Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize+component behavior. Each boolean doubles possible states and creates+unmaintainable conditional logic. Use composition instead.++**Incorrect (boolean props create exponential complexity):**++```tsx+function Composer({+ onSubmit,+ isThread,+ channelId,+ isDMThread,+ dmId,+ isEditing,+ isForwarding,+}: Props) {+ return (+ <form>+ <Header />+ <Input />+ {isDMThread ? (+ <AlsoSendToDMField id={dmId} />+ ) : isThread ? (+ <AlsoSendToChannelField id={channelId} />+ ) : null}+ {isEditing ? (+ <EditActions />+ ) : isForwarding ? (+ <ForwardActions />+ ) : (+ <DefaultActions />+ )}+ <Footer onSubmit={onSubmit} />+ </form>+ )+}+```++**Correct (composition eliminates conditionals):**++```tsx+// Channel composer+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Attachments />+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Thread composer - adds "also send to channel" field+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <AlsoSendToChannelField id={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Edit composer - different footer actions+function EditComposer() {+ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ )+}+```++Each variant is explicit about what it renders. We can share internals without+sharing a single monolithic parent.diff --git a/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.mdnew file mode 100644index 000000000..e5e3043cb--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md@@ -0,0 +1,112 @@+---+title: Use Compound Components+impact: HIGH+impactDescription: enables flexible composition without prop drilling+tags: composition, compound-components, architecture+---++## Use Compound Components++Structure complex components as compound components with a shared context. Each+subcomponent accesses shared state via context, not props. Consumers compose the+pieces they need.++**Incorrect (monolithic component with render props):**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+ showAttachments,+ showFormatting,+ showEmojis,+}: Props) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {showAttachments && <Attachments />}+ {renderFooter ? (+ renderFooter()+ ) : (+ <Footer>+ {showFormatting && <Formatting />}+ {showEmojis && <Emojis />}+ {renderActions?.()}+ </Footer>+ )}+ </form>+ )+}+```++**Correct (compound components with shared context):**++```tsx+const ComposerContext = createContext<ComposerContextValue | null>(null)++function ComposerProvider({ children, state, actions, meta }: ProviderProps) {+ return (+ <ComposerContext value={{ state, actions, meta }}>+ {children}+ </ComposerContext>+ )+}++function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>+}++function ComposerInput() {+ const {+ state,+ actions: { update },+ meta: { inputRef },+ } = use(ComposerContext)+ return (+ <TextInput+ ref={inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ )+}++function ComposerSubmit() {+ const {+ actions: { submit },+ } = use(ComposerContext)+ return <Button onPress={submit}>Send</Button>+}++// Export as compound component+const Composer = {+ Provider: ComposerProvider,+ Frame: ComposerFrame,+ Input: ComposerInput,+ Submit: ComposerSubmit,+ Header: ComposerHeader,+ Footer: ComposerFooter,+ Attachments: ComposerAttachments,+ Formatting: ComposerFormatting,+ Emojis: ComposerEmojis,+}+```++**Usage:**++```tsx+<Composer.Provider state={state} actions={actions} meta={meta}>+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+</Composer.Provider>+```++Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.mdnew file mode 100644index 000000000..d4345ee30--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md@@ -0,0 +1,87 @@+---+title: Prefer Composing Children Over Render Props+impact: MEDIUM+impactDescription: cleaner composition, better readability+tags: composition, children, render-props+---++## Prefer Children Over Render Props++Use `children` for composition instead of `renderX` props. Children are more+readable, compose naturally, and don't require understanding callback+signatures.++**Incorrect (render props):**++```tsx+function Composer({+ renderHeader,+ renderFooter,+ renderActions,+}: {+ renderHeader?: () => React.ReactNode+ renderFooter?: () => React.ReactNode+ renderActions?: () => React.ReactNode+}) {+ return (+ <form>+ {renderHeader?.()}+ <Input />+ {renderFooter ? renderFooter() : <DefaultFooter />}+ {renderActions?.()}+ </form>+ )+}++// Usage is awkward and inflexible+return (+ <Composer+ renderHeader={() => <CustomHeader />}+ renderFooter={() => (+ <>+ <Formatting />+ <Emojis />+ </>+ )}+ renderActions={() => <SubmitButton />}+ />+)+```++**Correct (compound components with children):**++```tsx+function ComposerFrame({ children }: { children: React.ReactNode }) {+ return <form>{children}</form>+}++function ComposerFooter({ children }: { children: React.ReactNode }) {+ return <footer className='flex'>{children}</footer>+}++// Usage is flexible+return (+ <Composer.Frame>+ <CustomHeader />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <SubmitButton />+ </Composer.Footer>+ </Composer.Frame>+)+```++**When render props are appropriate:**++```tsx+// Render props work well when you need to pass data back+<List+ data={items}+ renderItem={({ item, index }) => <Item item={item} index={index} />}+/>+```++Use render props when the parent needs to provide data or state to the child.+Use children when composing static structure.diff --git a/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.mdnew file mode 100644index 000000000..56e32e8be--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md@@ -0,0 +1,100 @@+---+title: Create Explicit Component Variants+impact: MEDIUM+impactDescription: self-documenting code, no hidden conditionals+tags: composition, variants, architecture+---++## Create Explicit Component Variants++Instead of one component with many boolean props, create explicit variant+components. Each variant composes the pieces it needs. The code documents+itself.++**Incorrect (one component, many modes):**++```tsx+// What does this component actually render?+<Composer+ isThread+ isEditing={false}+ channelId='abc'+ showAttachments+ showFormatting={false}+/>+```++**Correct (explicit variants):**++```tsx+// Immediately clear what this renders+<ThreadComposer channelId="abc" />++// Or+<EditMessageComposer messageId="xyz" />++// Or+<ForwardMessageComposer messageId="123" />+```++Each implementation is unique, explicit and self-contained. Yet they can each+use shared parts.++**Implementation:**++```tsx+function ThreadComposer({ channelId }: { channelId: string }) {+ return (+ <ThreadProvider channelId={channelId}>+ <Composer.Frame>+ <Composer.Input />+ <AlsoSendToChannelField channelId={channelId} />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ </ThreadProvider>+ )+}++function EditMessageComposer({ messageId }: { messageId: string }) {+ return (+ <EditMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.CancelEdit />+ <Composer.SaveEdit />+ </Composer.Footer>+ </Composer.Frame>+ </EditMessageProvider>+ )+}++function ForwardMessageComposer({ messageId }: { messageId: string }) {+ return (+ <ForwardMessageProvider messageId={messageId}>+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ <Composer.Mentions />+ </Composer.Footer>+ </Composer.Frame>+ </ForwardMessageProvider>+ )+}+```++Each variant is explicit about:++- What provider/state it uses+- What UI elements it includes+- What actions are available++No boolean prop combinations to reason about. No impossible states.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.mdnew file mode 100644index 000000000..d961bede0--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md@@ -0,0 +1,191 @@+---+title: Define Generic Context Interfaces for Dependency Injection+impact: HIGH+impactDescription: enables dependency-injectable state across use-cases+tags: composition, context, state, typescript, dependency-injection+---++## Define Generic Context Interfaces for Dependency Injection++Define a **generic interface** for your component context with three parts:+`state`, `actions`, and `meta`. This interface is a contract that any provider+can implement—enabling the same UI components to work with completely different+state implementations.++**Core principle:** Lift state, compose internals, make state+dependency-injectable.++**Incorrect (UI coupled to specific state implementation):**++```tsx+function ComposerInput() {+ // Tightly coupled to a specific hook+ const { input, setInput } = useChannelComposerState()+ return <TextInput value={input} onChangeText={setInput} />+}+```++**Correct (generic interface enables dependency injection):**++```tsx+// Define a GENERIC interface that any provider can implement+interface ComposerState {+ input: string+ attachments: Attachment[]+ isSubmitting: boolean+}++interface ComposerActions {+ update: (updater: (state: ComposerState) => ComposerState) => void+ submit: () => void+}++interface ComposerMeta {+ inputRef: React.RefObject<TextInput>+}++interface ComposerContextValue {+ state: ComposerState+ actions: ComposerActions+ meta: ComposerMeta+}++const ComposerContext = createContext<ComposerContextValue | null>(null)+```++**UI components consume the interface, not the implementation:**++```tsx+function ComposerInput() {+ const {+ state,+ actions: { update },+ meta,+ } = use(ComposerContext)++ // This component works with ANY provider that implements the interface+ return (+ <TextInput+ ref={meta.inputRef}+ value={state.input}+ onChangeText={(text) => update((s) => ({ ...s, input: text }))}+ />+ )+}+```++**Different providers implement the same interface:**++```tsx+// Provider A: Local state for ephemeral forms+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState)+ const inputRef = useRef(null)+ const submit = useForwardMessage()++ return (+ <ComposerContext+ value={{+ state,+ actions: { update: setState, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ )+}++// Provider B: Global synced state for channels+function ChannelProvider({ channelId, children }: Props) {+ const { state, update, submit } = useGlobalChannel(channelId)+ const inputRef = useRef(null)++ return (+ <ComposerContext+ value={{+ state,+ actions: { update, submit },+ meta: { inputRef },+ }}+ >+ {children}+ </ComposerContext>+ )+}+```++**The same composed UI works with both:**++```tsx+// Works with ForwardMessageProvider (local state)+<ForwardMessageProvider>+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ForwardMessageProvider>++// Works with ChannelProvider (global synced state)+<ChannelProvider channelId="abc">+ <Composer.Frame>+ <Composer.Input />+ <Composer.Submit />+ </Composer.Frame>+</ChannelProvider>+```++**Custom UI outside the component can access state and actions:**++The provider boundary is what matters—not the visual nesting. Components that+need shared state don't have to be inside the `Composer.Frame`. They just need+to be within the provider.++```tsx+function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ {/* The composer UI */}+ <Composer.Frame>+ <Composer.Input placeholder="Add a message, if you'd like." />+ <Composer.Footer>+ <Composer.Formatting />+ <Composer.Emojis />+ </Composer.Footer>+ </Composer.Frame>++ {/* Custom UI OUTSIDE the composer, but INSIDE the provider */}+ <MessagePreview />++ {/* Actions at the bottom of the dialog */}+ <DialogActions>+ <CancelButton />+ <ForwardButton />+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ )+}++// This button lives OUTSIDE Composer.Frame but can still submit based on its context!+function ForwardButton() {+ const {+ actions: { submit },+ } = use(ComposerContext)+ return <Button onPress={submit}>Forward</Button>+}++// This preview lives OUTSIDE Composer.Frame but can read composer's state!+function MessagePreview() {+ const { state } = use(ComposerContext)+ return <Preview message={state.input} attachments={state.attachments} />+}+```++The `ForwardButton` and `MessagePreview` are not visually inside the composer+box, but they can still access its state and actions. This is the power of+lifting state into providers.++The UI is reusable bits you compose together. The state is dependency-injected+by the provider. Swap the provider, keep the UI.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.mdnew file mode 100644index 000000000..71a5afaa7--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md@@ -0,0 +1,113 @@+---+title: Decouple State Management from UI+impact: MEDIUM+impactDescription: enables swapping state implementations without changing UI+tags: composition, state, architecture+---++## Decouple State Management from UI++The provider component should be the only place that knows how state is managed.+UI components consume the context interface—they don't know if state comes from+useState, Zustand, or a server sync.++**Incorrect (UI coupled to state implementation):**++```tsx+function ChannelComposer({ channelId }: { channelId: string }) {+ // UI component knows about global state implementation+ const state = useGlobalChannelState(channelId)+ const { submit, updateInput } = useChannelSync(channelId)++ return (+ <Composer.Frame>+ <Composer.Input+ value={state.input}+ onChange={(text) => sync.updateInput(text)}+ />+ <Composer.Submit onPress={() => sync.submit()} />+ </Composer.Frame>+ )+}+```++**Correct (state management isolated in provider):**++```tsx+// Provider handles all state management details+function ChannelProvider({+ channelId,+ children,+}: {+ channelId: string+ children: React.ReactNode+}) {+ const { state, update, submit } = useGlobalChannel(channelId)+ const inputRef = useRef(null)++ return (+ <Composer.Provider+ state={state}+ actions={{ update, submit }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ )+}++// UI component only knows about the context interface+function ChannelComposer() {+ return (+ <Composer.Frame>+ <Composer.Header />+ <Composer.Input />+ <Composer.Footer>+ <Composer.Submit />+ </Composer.Footer>+ </Composer.Frame>+ )+}++// Usage+function Channel({ channelId }: { channelId: string }) {+ return (+ <ChannelProvider channelId={channelId}>+ <ChannelComposer />+ </ChannelProvider>+ )+}+```++**Different providers, same UI:**++```tsx+// Local state for ephemeral forms+function ForwardMessageProvider({ children }) {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ >+ {children}+ </Composer.Provider>+ )+}++// Global synced state for channels+function ChannelProvider({ channelId, children }) {+ const { state, update, submit } = useGlobalChannel(channelId)++ return (+ <Composer.Provider state={state} actions={{ update, submit }}>+ {children}+ </Composer.Provider>+ )+}+```++The same `Composer.Input` component works with both providers because it only+depends on the context interface, not the implementation.diff --git a/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.mdnew file mode 100644index 000000000..d7fe27b54--- /dev/null+++ b/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md@@ -0,0 +1,125 @@+---+title: Lift State into Provider Components+impact: HIGH+impactDescription: enables state sharing outside component boundaries+tags: composition, state, context, providers+---++## Lift State into Provider Components++Move state management into dedicated provider components. This allows sibling+components outside the main UI to access and modify state without prop drilling+or awkward refs.++**Incorrect (state trapped inside component):**++```tsx+function ForwardMessageComposer() {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()++ return (+ <Composer.Frame>+ <Composer.Input />+ <Composer.Footer />+ </Composer.Frame>+ )+}++// Problem: How does this button access composer state?+function ForwardMessageDialog() {+ return (+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Needs composer state */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Needs to call submit */}+ </DialogActions>+ </Dialog>+ )+}+```++**Incorrect (useEffect to sync state up):**++```tsx+function ForwardMessageDialog() {+ const [input, setInput] = useState('')+ return (+ <Dialog>+ <ForwardMessageComposer onInputChange={setInput} />+ <MessagePreview input={input} />+ </Dialog>+ )+}++function ForwardMessageComposer({ onInputChange }) {+ const [state, setState] = useState(initialState)+ useEffect(() => {+ onInputChange(state.input) // Sync on every change 😬+ }, [state.input])+}+```++**Incorrect (reading state from ref on submit):**++```tsx+function ForwardMessageDialog() {+ const stateRef = useRef(null)+ return (+ <Dialog>+ <ForwardMessageComposer stateRef={stateRef} />+ <ForwardButton onPress={() => submit(stateRef.current)} />+ </Dialog>+ )+}+```++**Correct (state lifted to provider):**++```tsx+function ForwardMessageProvider({ children }: { children: React.ReactNode }) {+ const [state, setState] = useState(initialState)+ const forwardMessage = useForwardMessage()+ const inputRef = useRef(null)++ return (+ <Composer.Provider+ state={state}+ actions={{ update: setState, submit: forwardMessage }}+ meta={{ inputRef }}+ >+ {children}+ </Composer.Provider>+ )+}++function ForwardMessageDialog() {+ return (+ <ForwardMessageProvider>+ <Dialog>+ <ForwardMessageComposer />+ <MessagePreview /> {/* Custom components can access state and actions */}+ <DialogActions>+ <CancelButton />+ <ForwardButton /> {/* Custom components can access state and actions */}+ </DialogActions>+ </Dialog>+ </ForwardMessageProvider>+ )+}++function ForwardButton() {+ const { actions } = use(Composer.Context)+ return <Button onPress={actions.submit}>Forward</Button>+}+```++The ForwardButton lives outside the Composer.Frame but still has access to the+submit action because it's within the provider. Even though it's a one-off+component, it can still access the composer's state and actions from outside the+UI itself.++**Key insight:** Components that need shared state don't have to be visually+nested inside each other—they just need to be within the same provider.diff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.mdnew file mode 100644index 000000000..db951abe7--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/AGENTS.md@@ -0,0 +1,2934 @@+# React Best Practices++**Version 1.0.0**+Vercel Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React and Next.js codebases. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.++---++## Table of Contents++1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**+ - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed)+ - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization)+ - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes)+ - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations)+ - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries)+2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)+ - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent)+3. [Server-Side Performance](#3-server-side-performance) — **HIGH**+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)+ - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching)+ - 3.4 [Minimize Serialization at RSC Boundaries](#34-minimize-serialization-at-rsc-boundaries)+ - 3.5 [Parallel Data Fetching with Component Composition](#35-parallel-data-fetching-with-component-composition)+ - 3.6 [Per-Request Deduplication with React.cache()](#36-per-request-deduplication-with-reactcache)+ - 3.7 [Use after() for Non-Blocking Operations](#37-use-after-for-non-blocking-operations)+4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)+5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)+ - 5.4 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#54-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)+ - 5.5 [Extract to Memoized Components](#55-extract-to-memoized-components)+ - 5.6 [Narrow Effect Dependencies](#56-narrow-effect-dependencies)+ - 5.7 [Put Interaction Logic in Event Handlers](#57-put-interaction-logic-in-event-handlers)+ - 5.8 [Subscribe to Derived State](#58-subscribe-to-derived-state)+ - 5.9 [Use Functional setState Updates](#59-use-functional-setstate-updates)+ - 5.10 [Use Lazy State Initialization](#510-use-lazy-state-initialization)+ - 5.11 [Use Transitions for Non-Urgent Updates](#511-use-transitions-for-non-urgent-updates)+ - 5.12 [Use useRef for Transient Values](#512-use-useref-for-transient-values)+6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)+ - 6.8 [Use Explicit Conditional Rendering](#68-use-explicit-conditional-rendering)+ - 6.9 [Use useTransition Over Manual Loading States](#69-use-usetransition-over-manual-loading-states)+7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)+ - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons)+ - 7.8 [Early Return from Functions](#78-early-return-from-functions)+ - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation)+ - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort)+ - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups)+ - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability)+8. [Advanced Patterns](#8-advanced-patterns) — **LOW**+ - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount)+ - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs)+ - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs)++---++## 1. Eliminating Waterfalls++**Impact: CRITICAL**++Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++### 1.1 Defer Await Until Needed++**Impact: HIGH (avoids blocking unused code paths)**++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect: blocks both branches**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct: only blocks when needed**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example: early return optimization**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++### 1.2 Dependency-Based Parallelization++**Impact: CRITICAL (2-10× improvement)**++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect: profile waits for config unnecessarily**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct: config and profile run in parallel**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++We can also create all the promises first, and do `Promise.all()` at the end.++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)++### 1.3 Prevent Waterfall Chains in API Routes++**Impact: CRITICAL (2-10× improvement)**++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect: config waits for auth, data waits for both**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct: auth and config start immediately**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).++### 1.4 Promise.all() for Independent Operations++**Impact: CRITICAL (2-10× improvement)**++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect: sequential execution, 3 round trips**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct: parallel execution, 1 round trip**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```++### 1.5 Strategic Suspense Boundaries++**Impact: HIGH (faster initial paint)**++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect: wrapper blocked by data fetching**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct: wrapper shows immediately, data streams in**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative: share promise across components**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)++- SEO-critical content above the fold++- Small, fast queries where suspense overhead isn't worth it++- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.++---++## 2. Bundle Size Optimization++**Impact: CRITICAL**++Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++### 2.1 Avoid Barrel File Imports++**Impact: CRITICAL (200-800ms import cost, slow builds)**++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect: imports entire library**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct: imports only what you need**++```tsx+import Check from 'lucide-react/dist/esm/icons/check'+import X from 'lucide-react/dist/esm/icons/x'+import Menu from 'lucide-react/dist/esm/icons/menu'+// Loads only 3 modules (~2KB vs ~1MB)++import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++**Alternative: Next.js 13.5+**++```js+// next.config.js - use optimizePackageImports+module.exports = {+ experimental: {+ optimizePackageImports: ['lucide-react', '@mui/material']+ }+}++// Then you can keep the ergonomic barrel imports:+import { Check, X, Menu } from 'lucide-react'+// Automatically transformed to direct imports at build time+```++Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)++### 2.2 Conditional Module Loading++**Impact: HIGH (loads large data only when needed)**++Load large data or modules only when a feature is activated.++**Example: lazy-load animation frames**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.++### 2.3 Defer Non-Critical Third-Party Libraries++**Impact: MEDIUM (loads after hydration)**++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect: blocks initial bundle**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct: loads after hydration**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++### 2.4 Dynamic Imports for Heavy Components++**Impact: CRITICAL (directly affects TTI and LCP)**++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect: Monaco bundles with main chunk ~300KB**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct: Monaco loads on demand**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++### 2.5 Preload Based on User Intent++**Impact: MEDIUM (reduces perceived latency)**++Preload heavy bundles before they're needed to reduce perceived latency.++**Example: preload on hover/focus**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example: preload when feature flag is enabled**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.++---++## 3. Server-Side Performance++**Impact: HIGH**++Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++### 3.1 Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect: no authentication check**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct: authentication inside the action**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)++### 3.2 Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect: duplicates array**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct: sends 3 strings**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated++- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++**Operations breaking deduplication: create new references**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`++- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.++### 3.3 Cross-Request LRU Caching++**Impact: HIGH (caches across requests)**++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)++### 3.4 Minimize Serialization at RSC Boundaries++**Impact: HIGH (reduces data transfer size)**++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect: serializes all 50 fields**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct: serializes only 1 field**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```++### 3.5 Parallel Data Fetching with Component Composition++**Impact: CRITICAL (eliminates server-side waterfalls)**++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect: Sidebar waits for Page's fetch to complete**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct: both fetch simultaneously**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```++### 3.6 Per-Request Deduplication with React.cache()++**Impact: MEDIUM (deduplicates within request)**++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect: always cache miss**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct: cache hit**++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++If you must pass objects, pass the same reference:++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)++- Heavy computations++- Authentication checks++- File system operations++- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)++### 3.7 Use after() for Non-Blocking Operations++**Impact: MEDIUM (faster response times)**++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect: blocks response**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct: non-blocking**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking++- Audit logging++- Sending notifications++- Cache invalidation++- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects++- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)++---++## 4. Client-Side Data Fetching++**Impact: MEDIUM-HIGH**++Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++### 4.1 Deduplicate Global Event Listeners++**Impact: LOW (single listener for N components)**++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect: N instances = N listeners**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct: N instances = 1 listener**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```++### 4.2 Use Passive Event Listeners for Scrolling Performance++**Impact: MEDIUM (eliminates scroll delay caused by event listeners)**++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.++### 4.3 Use SWR for Automatic Deduplication++**Impact: MEDIUM-HIGH (automatic deduplication)**++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect: no deduplication, each instance fetches**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct: multiple instances share one request**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)++### 4.4 Version and Minimize localStorage Data++**Impact: MEDIUM (prevents schema conflicts, reduces storage size)**++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.++---++## 5. Re-render Optimization++**Impact: MEDIUM**++Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++### 5.1 Calculate Derived State During Rendering++**Impact: MEDIUM (avoids redundant renders and state drift)**++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect: redundant state and effect**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct: derive during render**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)++### 5.2 Defer State Reads to Usage Point++**Impact: MEDIUM (avoids unnecessary subscriptions)**++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect: subscribes to all searchParams changes**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct: reads on demand, no subscription**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++### 5.3 Do not wrap a simple expression with a primitive result type in useMemo++**Impact: LOW-MEDIUM (wasted computation on every render)**++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.++Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```++### 5.4 Extract Default Non-primitive Parameter Value from Memoized Component to Constant++**Impact: MEDIUM (restores memoization by using a constant for default value)**++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect: `onClick` has different values on every rerender**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct: stable default value**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++### 5.5 Extract to Memoized Components++**Impact: MEDIUM (enables early returns)**++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect: computes avatar even when loading**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct: skips computation when loading**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.++### 5.6 Narrow Effect Dependencies++**Impact: LOW (minimizes effect re-runs)**++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect: re-runs on any user field change**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct: re-runs only when id changes**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```++### 5.7 Put Interaction Logic in Event Handlers++**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect: event modeled as state + effect**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct: do it in the handler**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)++### 5.8 Subscribe to Derived State++**Impact: MEDIUM (reduces re-render frequency)**++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect: re-renders on every pixel change**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct: re-renders only when boolean changes**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++### 5.9 Use Functional setState Updates++**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect: requires state as dependency**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct: stable callbacks, no stale closures**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes++2. **No stale closures** - Always operates on the latest state value++3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks++4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value++- Inside useCallback/useMemo when state is needed++- Event handlers that reference state++- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`++- Setting state from props/arguments only: `setName(newName)`++- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.++### 5.10 Use Lazy State Initialization++**Impact: MEDIUM (wasted computation on every render)**++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect: runs on every render**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct: runs only once**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.++### 5.11 Use Transitions for Non-Urgent Updates++**Impact: MEDIUM (maintains UI responsiveness)**++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect: blocks UI on every scroll**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct: non-blocking updates**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++### 5.12 Use useRef for Transient Values++**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect: renders every update**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct: no re-render for tracking**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```++---++## 6. Rendering Performance++**Impact: MEDIUM**++Optimizing the rendering process reduces the work the browser needs to do.++### 6.1 Animate SVG Wrapper Instead of SVG Element++**Impact: LOW (enables hardware acceleration)**++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect: animating SVG directly - no hardware acceleration**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct: animating wrapper div - hardware accelerated**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.++### 6.2 CSS content-visibility for Long Lists++**Impact: HIGH (faster initial render)**++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).++### 6.3 Hoist Static JSX Elements++**Impact: LOW (avoids re-creation)**++Extract static JSX outside components to avoid re-creation.++**Incorrect: recreates element every render**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct: reuses same element**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.++### 6.4 Optimize SVG Precision++**Impact: LOW (reduces file size)**++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect: excessive precision**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct: 1 decimal place**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```++### 6.5 Prevent Hydration Mismatch Without Flickering++**Impact: MEDIUM (avoids visual flicker and hydration errors)**++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect: breaks SSR**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect: visual flickering**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct: no flicker, no hydration mismatch**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.++### 6.6 Suppress Expected Hydration Mismatches++**Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect: known mismatch warnings**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct: suppress expected mismatch only**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```++### 6.7 Use Activity Component for Show/Hide++**Impact: MEDIUM (preserves state/DOM)**++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.++### 6.8 Use Explicit Conditional Rendering++**Impact: LOW (prevents rendering 0 or NaN)**++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect: renders "0" when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct: renders nothing when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++### 6.9 Use useTransition Over Manual Loading States++**Impact: LOW (reduces re-renders and improves code clarity)**++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect: manual loading state**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct: useTransition with built-in pending state**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`++- **Error resilience**: Pending state correctly resets even if the transition throws++- **Better responsiveness**: Keeps the UI responsive during updates++- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)++---++## 7. JavaScript Performance++**Impact: LOW-MEDIUM**++Micro-optimizations for hot paths can add up to meaningful improvements.++### 7.1 Avoid Layout Thrashing++**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK: browser batches style changes**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect: interleaved reads and writes force reflows**++```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct: batch writes, then read once**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct: batch reads, then writes**++```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**Better: use CSS classes**++**React example:**++```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.++### 7.2 Build Index Maps for Repeated Lookups++**Impact: LOW-MEDIUM (1M ops to 2K ops)**++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).++For 1000 orders × 1000 users: 1M ops → 2K ops.++### 7.3 Cache Property Access in Loops++**Impact: LOW-MEDIUM (reduces lookups)**++Cache object property lookups in hot paths.++**Incorrect: 3 lookups × N iterations**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct: 1 lookup total**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```++### 7.4 Cache Repeated Function Calls++**Impact: MEDIUM (avoid redundant computation)**++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect: redundant computation**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct: cached results**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)++### 7.5 Cache Storage API Calls++**Impact: LOW-MEDIUM (reduces expensive I/O)**++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect: reads storage on every call**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct: Map cache**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important: invalidate on external changes**++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```++If storage can change externally (another tab, server-set cookies), invalidate cache:++### 7.6 Combine Multiple Array Iterations++**Impact: LOW-MEDIUM (reduces iterations)**++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect: 3 iterations**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct: 1 iteration**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```++### 7.7 Early Length Check for Array Comparisons++**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect: always runs expensive comparison**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:++- It avoids the overhead of sorting and joining the arrays when lengths differ++- It avoids consuming memory for the joined strings (especially important for large arrays)++- It avoids mutating the original arrays++- It returns early when a difference is found++### 7.8 Early Return from Functions++**Impact: LOW-MEDIUM (avoids unnecessary computation)**++Return early when result is determined to skip unnecessary processing.++**Incorrect: processes all items even after finding answer**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct: returns immediately on first error**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```++### 7.9 Hoist RegExp Creation++**Impact: LOW-MEDIUM (avoids recreation)**++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect: new RegExp every render**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct: memoize or hoist**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning: global regex has mutable state**++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```++Global regex (`/g`) has mutable `lastIndex` state:++### 7.10 Use Loop for Min/Max Instead of Sort++**Impact: LOW (O(n) instead of O(n log n))**++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative: Math.min/Math.max for small arrays**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.++### 7.11 Use Set/Map for O(1) Lookups++**Impact: LOW-MEDIUM (O(n) to O(1))**++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```++### 7.12 Use toSorted() Instead of sort() for Immutability++**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect: mutates original array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct: creates new array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only++2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support: fallback for older browsers**++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++**Other immutable array methods:**++- `.toSorted()` - immutable sort++- `.toReversed()` - immutable reverse++- `.toSpliced()` - immutable splice++- `.with()` - immutable element replacement++---++## 8. Advanced Patterns++**Impact: LOW**++Advanced patterns for specific cases that require careful implementation.++### 8.1 Initialize App Once, Not Per Mount++**Impact: LOW-MEDIUM (avoids duplicate init in development)**++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect: runs twice in dev, re-runs on remount**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct: once per app load**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)++### 8.2 Store Event Handlers in Refs++**Impact: LOW (stable subscriptions)**++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect: re-subscribes on every render**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct: stable subscription**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.++### 8.3 useEffectEvent for Stable Callback Refs++**Impact: LOW (prevents effect re-runs)**++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect: effect re-runs on every callback change**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct: using React's useEffectEvent**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```++---++## References++1. [https://react.dev](https://react.dev)+2. [https://nextjs.org](https://nextjs.org)+3. [https://swr.vercel.app](https://swr.vercel.app)+4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)+5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)+6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)+7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.agents/skills/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.mdnew file mode 100644index 000000000..1ad7750e5--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/SKILL.md@@ -0,0 +1,136 @@+---+name: vercel-react-best-practices+description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.+license: MIT+metadata:+ author: vercel+ version: "1.0.0"+---++# Vercel React Best Practices++Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 57 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.++## When to Apply++Reference these guidelines when:+- Writing new React components or Next.js pages+- Implementing data fetching (client or server-side)+- Reviewing code for performance issues+- Refactoring existing React/Next.js code+- Optimizing bundle size or load times++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+|----------|----------|--------|--------|+| 1 | Eliminating Waterfalls | CRITICAL | `async-` |+| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |+| 3 | Server-Side Performance | HIGH | `server-` |+| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |+| 5 | Re-render Optimization | MEDIUM | `rerender-` |+| 6 | Rendering Performance | MEDIUM | `rendering-` |+| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |+| 8 | Advanced Patterns | LOW | `advanced-` |++## Quick Reference++### 1. Eliminating Waterfalls (CRITICAL)++- `async-defer-await` - Move await into branches where actually used+- `async-parallel` - Use Promise.all() for independent operations+- `async-dependencies` - Use better-all for partial dependencies+- `async-api-routes` - Start promises early, await late in API routes+- `async-suspense-boundaries` - Use Suspense to stream content++### 2. Bundle Size Optimization (CRITICAL)++- `bundle-barrel-imports` - Import directly, avoid barrel files+- `bundle-dynamic-imports` - Use next/dynamic for heavy components+- `bundle-defer-third-party` - Load analytics/logging after hydration+- `bundle-conditional` - Load modules only when feature is activated+- `bundle-preload` - Preload on hover/focus for perceived speed++### 3. Server-Side Performance (HIGH)++- `server-auth-actions` - Authenticate server actions like API routes+- `server-cache-react` - Use React.cache() for per-request deduplication+- `server-cache-lru` - Use LRU cache for cross-request caching+- `server-dedup-props` - Avoid duplicate serialization in RSC props+- `server-serialization` - Minimize data passed to client components+- `server-parallel-fetching` - Restructure components to parallelize fetches+- `server-after-nonblocking` - Use after() for non-blocking operations++### 4. Client-Side Data Fetching (MEDIUM-HIGH)++- `client-swr-dedup` - Use SWR for automatic request deduplication+- `client-event-listeners` - Deduplicate global event listeners+- `client-passive-event-listeners` - Use passive listeners for scroll+- `client-localstorage-schema` - Version and minimize localStorage data++### 5. Re-render Optimization (MEDIUM)++- `rerender-defer-reads` - Don't subscribe to state only used in callbacks+- `rerender-memo` - Extract expensive work into memoized components+- `rerender-memo-with-default-value` - Hoist default non-primitive props+- `rerender-dependencies` - Use primitive dependencies in effects+- `rerender-derived-state` - Subscribe to derived booleans, not raw values+- `rerender-derived-state-no-effect` - Derive state during render, not effects+- `rerender-functional-setstate` - Use functional setState for stable callbacks+- `rerender-lazy-state-init` - Pass function to useState for expensive values+- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives+- `rerender-move-effect-to-event` - Put interaction logic in event handlers+- `rerender-transitions` - Use startTransition for non-urgent updates+- `rerender-use-ref-transient-values` - Use refs for transient frequent values++### 6. Rendering Performance (MEDIUM)++- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element+- `rendering-content-visibility` - Use content-visibility for long lists+- `rendering-hoist-jsx` - Extract static JSX outside components+- `rendering-svg-precision` - Reduce SVG coordinate precision+- `rendering-hydration-no-flicker` - Use inline script for client-only data+- `rendering-hydration-suppress-warning` - Suppress expected mismatches+- `rendering-activity` - Use Activity component for show/hide+- `rendering-conditional-render` - Use ternary, not && for conditionals+- `rendering-usetransition-loading` - Prefer useTransition for loading state++### 7. JavaScript Performance (LOW-MEDIUM)++- `js-batch-dom-css` - Group CSS changes via classes or cssText+- `js-index-maps` - Build Map for repeated lookups+- `js-cache-property-access` - Cache object properties in loops+- `js-cache-function-results` - Cache function results in module-level Map+- `js-cache-storage` - Cache localStorage/sessionStorage reads+- `js-combine-iterations` - Combine multiple filter/map into one loop+- `js-length-check-first` - Check array length before expensive comparison+- `js-early-exit` - Return early from functions+- `js-hoist-regexp` - Hoist RegExp creation outside loops+- `js-min-max-loop` - Use loop for min/max instead of sort+- `js-set-map-lookups` - Use Set/Map for O(1) lookups+- `js-tosorted-immutable` - Use toSorted() for immutability++### 8. Advanced Patterns (LOW)++- `advanced-event-handler-refs` - Store event handlers in refs+- `advanced-init-once` - Initialize app once per app load+- `advanced-use-latest` - useLatest for stable callback refs++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/async-parallel.md+rules/bundle-barrel-imports.md+```++Each rule file contains:+- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.mdnew file mode 100644index 000000000..97e7ade24--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md@@ -0,0 +1,55 @@+---+title: Store Event Handlers in Refs+impact: LOW+impactDescription: stable subscriptions+tags: advanced, hooks, refs, event-handlers, optimization+---++## Store Event Handlers in Refs++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect (re-subscribes on every render):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct (stable subscription):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ const handlerRef = useRef(handler)+ useEffect(() => {+ handlerRef.current = handler+ }, [handler])++ useEffect(() => {+ const listener = (e) => handlerRef.current(e)+ window.addEventListener(event, listener)+ return () => window.removeEventListener(event, listener)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.mdnew file mode 100644index 000000000..73ee38e5e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md@@ -0,0 +1,42 @@+---+title: Initialize App Once, Not Per Mount+impact: LOW-MEDIUM+impactDescription: avoids duplicate init in development+tags: initialization, useEffect, app-startup, side-effects+---++## Initialize App Once, Not Per Mount++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect (runs twice in dev, re-runs on remount):**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct (once per app load):**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.mdnew file mode 100644index 000000000..9c7cb5016--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md@@ -0,0 +1,39 @@+---+title: useEffectEvent for Stable Callback Refs+impact: LOW+impactDescription: prevents effect re-runs+tags: advanced, hooks, useEffectEvent, refs, optimization+---++## useEffectEvent for Stable Callback Refs++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect (effect re-runs on every callback change):**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct (using React's useEffectEvent):**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.mdnew file mode 100644index 000000000..6feda1ef0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md@@ -0,0 +1,38 @@+---+title: Prevent Waterfall Chains in API Routes+impact: CRITICAL+impactDescription: 2-10× improvement+tags: api-routes, server-actions, waterfalls, parallelization+---++## Prevent Waterfall Chains in API Routes++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect (config waits for auth, data waits for both):**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct (auth and config start immediately):**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).diff --git a/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.mdnew file mode 100644index 000000000..ea7082a36--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md@@ -0,0 +1,80 @@+---+title: Defer Await Until Needed+impact: HIGH+impactDescription: avoids blocking unused code paths+tags: async, await, conditional, optimization+---++## Defer Await Until Needed++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect (blocks both branches):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct (only blocks when needed):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example (early return optimization):**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.diff --git a/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.mdnew file mode 100644index 000000000..0484ebab9--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md@@ -0,0 +1,51 @@+---+title: Dependency-Based Parallelization+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, dependencies, better-all+---++## Dependency-Based Parallelization++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect (profile waits for config unnecessarily):**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct (config and profile run in parallel):**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++We can also create all the promises first, and do `Promise.all()` at the end.++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)diff --git a/.agents/skills/vercel-react-best-practices/rules/async-parallel.md b/.agents/skills/vercel-react-best-practices/rules/async-parallel.mdnew file mode 100644index 000000000..64133f6c3--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-parallel.md@@ -0,0 +1,28 @@+---+title: Promise.all() for Independent Operations+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, promises, waterfalls+---++## Promise.all() for Independent Operations++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect (sequential execution, 3 round trips):**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct (parallel execution, 1 round trip):**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```diff --git a/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.mdnew file mode 100644index 000000000..1fbc05b04--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md@@ -0,0 +1,99 @@+---+title: Strategic Suspense Boundaries+impact: HIGH+impactDescription: faster initial paint+tags: async, suspense, streaming, layout-shift+---++## Strategic Suspense Boundaries++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect (wrapper blocked by data fetching):**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct (wrapper shows immediately, data streams in):**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative (share promise across components):**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)+- SEO-critical content above the fold+- Small, fast queries where suspense overhead isn't worth it+- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mdnew file mode 100644index 000000000..ee48f3273--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md@@ -0,0 +1,59 @@+---+title: Avoid Barrel File Imports+impact: CRITICAL+impactDescription: 200-800ms import cost, slow builds+tags: bundle, imports, tree-shaking, barrel-files, performance+---++## Avoid Barrel File Imports++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect (imports entire library):**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct (imports only what you need):**++```tsx+import Check from 'lucide-react/dist/esm/icons/check'+import X from 'lucide-react/dist/esm/icons/x'+import Menu from 'lucide-react/dist/esm/icons/menu'+// Loads only 3 modules (~2KB vs ~1MB)++import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++**Alternative (Next.js 13.5+):**++```js+// next.config.js - use optimizePackageImports+module.exports = {+ experimental: {+ optimizePackageImports: ['lucide-react', '@mui/material']+ }+}++// Then you can keep the ergonomic barrel imports:+import { Check, X, Menu } from 'lucide-react'+// Automatically transformed to direct imports at build time+```++Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.mdnew file mode 100644index 000000000..99d6fc90e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md@@ -0,0 +1,31 @@+---+title: Conditional Module Loading+impact: HIGH+impactDescription: loads large data only when needed+tags: bundle, conditional-loading, lazy-loading+---++## Conditional Module Loading++Load large data or modules only when a feature is activated.++**Example (lazy-load animation frames):**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.mdnew file mode 100644index 000000000..db041d151--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md@@ -0,0 +1,49 @@+---+title: Defer Non-Critical Third-Party Libraries+impact: MEDIUM+impactDescription: loads after hydration+tags: bundle, third-party, analytics, defer+---++## Defer Non-Critical Third-Party Libraries++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect (blocks initial bundle):**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct (loads after hydration):**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.mdnew file mode 100644index 000000000..60b62695e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md@@ -0,0 +1,35 @@+---+title: Dynamic Imports for Heavy Components+impact: CRITICAL+impactDescription: directly affects TTI and LCP+tags: bundle, dynamic-import, code-splitting, next-dynamic+---++## Dynamic Imports for Heavy Components++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect (Monaco bundles with main chunk ~300KB):**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct (Monaco loads on demand):**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.mdnew file mode 100644index 000000000..700050406--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md@@ -0,0 +1,50 @@+---+title: Preload Based on User Intent+impact: MEDIUM+impactDescription: reduces perceived latency+tags: bundle, preload, user-intent, hover+---++## Preload Based on User Intent++Preload heavy bundles before they're needed to reduce perceived latency.++**Example (preload on hover/focus):**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example (preload when feature flag is enabled):**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.mdnew file mode 100644index 000000000..aad4ae916--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md@@ -0,0 +1,74 @@+---+title: Deduplicate Global Event Listeners+impact: LOW+impactDescription: single listener for N components+tags: client, swr, event-listeners, subscription+---++## Deduplicate Global Event Listeners++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect (N instances = N listeners):**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct (N instances = 1 listener):**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.mdnew file mode 100644index 000000000..d30a1a7d4--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md@@ -0,0 +1,71 @@+---+title: Version and Minimize localStorage Data+impact: MEDIUM+impactDescription: prevents schema conflicts, reduces storage size+tags: client, localStorage, storage, versioning, data-minimization+---++## Version and Minimize localStorage Data++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.mdnew file mode 100644index 000000000..ce39a889e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md@@ -0,0 +1,48 @@+---+title: Use Passive Event Listeners for Scrolling Performance+impact: MEDIUM+impactDescription: eliminates scroll delay caused by event listeners+tags: client, event-listeners, scrolling, performance, touch, wheel+---++## Use Passive Event Listeners for Scrolling Performance++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.mdnew file mode 100644index 000000000..2a430f27f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md@@ -0,0 +1,56 @@+---+title: Use SWR for Automatic Deduplication+impact: MEDIUM-HIGH+impactDescription: automatic deduplication+tags: client, swr, deduplication, data-fetching+---++## Use SWR for Automatic Deduplication++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect (no deduplication, each instance fetches):**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct (multiple instances share one request):**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)diff --git a/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.mdnew file mode 100644index 000000000..a62d84ed8--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md@@ -0,0 +1,107 @@+---+title: Avoid Layout Thrashing+impact: MEDIUM+impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks+tags: javascript, dom, css, performance, reflow, layout-thrashing+---++## Avoid Layout Thrashing++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK (browser batches style changes):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect (interleaved reads and writes force reflows):**+```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct (batch writes, then read once):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct (batch reads, then writes):**+```typescript+function avoidThrashing(element: HTMLElement) {+ // Read phase - all layout queries first+ const rect1 = element.getBoundingClientRect()+ const offsetWidth = element.offsetWidth+ const offsetHeight = element.offsetHeight++ // Write phase - all style changes after+ element.style.width = '100px'+ element.style.height = '200px'+}+```++**Better: use CSS classes**+```css+.highlighted-box {+ width: 100px;+ height: 200px;+ background-color: blue;+ border: 1px solid black;+}+```+```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**React example:**+```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.mdnew file mode 100644index 000000000..180f8ac8f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md@@ -0,0 +1,80 @@+---+title: Cache Repeated Function Calls+impact: MEDIUM+impactDescription: avoid redundant computation+tags: javascript, cache, memoization, performance+---++## Cache Repeated Function Calls++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect (redundant computation):**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct (cached results):**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.mdnew file mode 100644index 000000000..39eec9061--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md@@ -0,0 +1,28 @@+---+title: Cache Property Access in Loops+impact: LOW-MEDIUM+impactDescription: reduces lookups+tags: javascript, loops, optimization, caching+---++## Cache Property Access in Loops++Cache object property lookups in hot paths.++**Incorrect (3 lookups × N iterations):**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct (1 lookup total):**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.mdnew file mode 100644index 000000000..aa4a30c08--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md@@ -0,0 +1,70 @@+---+title: Cache Storage API Calls+impact: LOW-MEDIUM+impactDescription: reduces expensive I/O+tags: javascript, localStorage, storage, caching, performance+---++## Cache Storage API Calls++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect (reads storage on every call):**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct (Map cache):**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important (invalidate on external changes):**++If storage can change externally (another tab, server-set cookies), invalidate cache:++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.mdnew file mode 100644index 000000000..044d017ec--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md@@ -0,0 +1,32 @@+---+title: Combine Multiple Array Iterations+impact: LOW-MEDIUM+impactDescription: reduces iterations+tags: javascript, arrays, loops, performance+---++## Combine Multiple Array Iterations++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect (3 iterations):**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct (1 iteration):**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.mdnew file mode 100644index 000000000..f46cb89c6--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md@@ -0,0 +1,50 @@+---+title: Early Return from Functions+impact: LOW-MEDIUM+impactDescription: avoids unnecessary computation+tags: javascript, functions, optimization, early-return+---++## Early Return from Functions++Return early when result is determined to skip unnecessary processing.++**Incorrect (processes all items even after finding answer):**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct (returns immediately on first error):**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.mdnew file mode 100644index 000000000..dae3fefdc--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md@@ -0,0 +1,45 @@+---+title: Hoist RegExp Creation+impact: LOW-MEDIUM+impactDescription: avoids recreation+tags: javascript, regexp, optimization, memoization+---++## Hoist RegExp Creation++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect (new RegExp every render):**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct (memoize or hoist):**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning (global regex has mutable state):**++Global regex (`/g`) has mutable `lastIndex` state:++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.mdnew file mode 100644index 000000000..9d357a00b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md@@ -0,0 +1,37 @@+---+title: Build Index Maps for Repeated Lookups+impact: LOW-MEDIUM+impactDescription: 1M ops to 2K ops+tags: javascript, map, indexing, optimization, performance+---++## Build Index Maps for Repeated Lookups++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).+For 1000 orders × 1000 users: 1M ops → 2K ops.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.mdnew file mode 100644index 000000000..8b8957363--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md@@ -0,0 +1,49 @@+---+title: Early Length Check for Array Comparisons+impact: MEDIUM-HIGH+impactDescription: avoids expensive operations when lengths differ+tags: javascript, arrays, performance, optimization, comparison+---++## Early Length Check for Array Comparisons++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect (always runs expensive comparison):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:+- It avoids the overhead of sorting and joining the arrays when lengths differ+- It avoids consuming memory for the joined strings (especially important for large arrays)+- It avoids mutating the original arrays+- It returns early when a difference is founddiff --git a/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.mdnew file mode 100644index 000000000..4b6656e96--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md@@ -0,0 +1,82 @@+---+title: Use Loop for Min/Max Instead of Sort+impact: LOW+impactDescription: O(n) instead of O(n log n)+tags: javascript, arrays, performance, sorting, algorithms+---++## Use Loop for Min/Max Instead of Sort++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative (Math.min/Math.max for small arrays):**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.mdnew file mode 100644index 000000000..680a4892e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md@@ -0,0 +1,24 @@+---+title: Use Set/Map for O(1) Lookups+impact: LOW-MEDIUM+impactDescription: O(n) to O(1)+tags: javascript, set, map, data-structures, performance+---++## Use Set/Map for O(1) Lookups++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.mdnew file mode 100644index 000000000..eae8b3f8a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md@@ -0,0 +1,57 @@+---+title: Use toSorted() Instead of sort() for Immutability+impact: MEDIUM-HIGH+impactDescription: prevents mutation bugs in React state+tags: javascript, arrays, immutability, react, state, mutation+---++## Use toSorted() Instead of sort() for Immutability++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect (mutates original array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct (creates new array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support (fallback for older browsers):**++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++**Other immutable array methods:**++- `.toSorted()` - immutable sort+- `.toReversed()` - immutable reverse+- `.toSpliced()` - immutable splice+- `.with()` - immutable element replacementdiff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.mdnew file mode 100644index 000000000..c957a490b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md@@ -0,0 +1,26 @@+---+title: Use Activity Component for Show/Hide+impact: MEDIUM+impactDescription: preserves state/DOM+tags: rendering, activity, visibility, state-preservation+---++## Use Activity Component for Show/Hide++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mdnew file mode 100644index 000000000..646744cbe--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md@@ -0,0 +1,47 @@+---+title: Animate SVG Wrapper Instead of SVG Element+impact: LOW+impactDescription: enables hardware acceleration+tags: rendering, svg, css, animation, performance+---++## Animate SVG Wrapper Instead of SVG Element++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect (animating SVG directly - no hardware acceleration):**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct (animating wrapper div - hardware accelerated):**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.mdnew file mode 100644index 000000000..7e866f585--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md@@ -0,0 +1,40 @@+---+title: Use Explicit Conditional Rendering+impact: LOW+impactDescription: prevents rendering 0 or NaN+tags: rendering, conditional, jsx, falsy-values+---++## Use Explicit Conditional Rendering++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect (renders "0" when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct (renders nothing when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.mdnew file mode 100644index 000000000..aa6656362--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md@@ -0,0 +1,38 @@+---+title: CSS content-visibility for Long Lists+impact: HIGH+impactDescription: faster initial render+tags: rendering, css, content-visibility, long-lists+---++## CSS content-visibility for Long Lists++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.mdnew file mode 100644index 000000000..32d2f3fce--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md@@ -0,0 +1,46 @@+---+title: Hoist Static JSX Elements+impact: LOW+impactDescription: avoids re-creation+tags: rendering, jsx, static, optimization+---++## Hoist Static JSX Elements++Extract static JSX outside components to avoid re-creation.++**Incorrect (recreates element every render):**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct (reuses same element):**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mdnew file mode 100644index 000000000..5cf0e79b6--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md@@ -0,0 +1,82 @@+---+title: Prevent Hydration Mismatch Without Flickering+impact: MEDIUM+impactDescription: avoids visual flicker and hydration errors+tags: rendering, ssr, hydration, localStorage, flicker+---++## Prevent Hydration Mismatch Without Flickering++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect (breaks SSR):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect (visual flickering):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct (no flicker, no hydration mismatch):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.mdnew file mode 100644index 000000000..24ba2513a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md@@ -0,0 +1,30 @@+---+title: Suppress Expected Hydration Mismatches+impact: LOW-MEDIUM+impactDescription: avoids noisy hydration warnings for known differences+tags: rendering, hydration, ssr, nextjs+---++## Suppress Expected Hydration Mismatches++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect (known mismatch warnings):**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct (suppress expected mismatch only):**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.mdnew file mode 100644index 000000000..6d7712860--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md@@ -0,0 +1,28 @@+---+title: Optimize SVG Precision+impact: LOW+impactDescription: reduces file size+tags: rendering, svg, optimization, svgo+---++## Optimize SVG Precision++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect (excessive precision):**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct (1 decimal place):**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.mdnew file mode 100644index 000000000..0c1b0b98e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md@@ -0,0 +1,75 @@+---+title: Use useTransition Over Manual Loading States+impact: LOW+impactDescription: reduces re-renders and improves code clarity+tags: rendering, transitions, useTransition, loading, state+---++## Use useTransition Over Manual Loading States++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect (manual loading state):**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct (useTransition with built-in pending state):**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`+- **Error resilience**: Pending state correctly resets even if the transition throws+- **Better responsiveness**: Keeps the UI responsive during updates+- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [useTransition](https://react.dev/reference/react/useTransition)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.mdnew file mode 100644index 000000000..e867c95f0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md@@ -0,0 +1,39 @@+---+title: Defer State Reads to Usage Point+impact: MEDIUM+impactDescription: avoids unnecessary subscriptions+tags: rerender, searchParams, localStorage, optimization+---++## Defer State Reads to Usage Point++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect (subscribes to all searchParams changes):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct (reads on demand, no subscription):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.mdnew file mode 100644index 000000000..47a4d9268--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md@@ -0,0 +1,45 @@+---+title: Narrow Effect Dependencies+impact: LOW+impactDescription: minimizes effect re-runs+tags: rerender, useEffect, dependencies, optimization+---++## Narrow Effect Dependencies++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect (re-runs on any user field change):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct (re-runs only when id changes):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.mdnew file mode 100644index 000000000..3d9fe4050--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md@@ -0,0 +1,40 @@+---+title: Calculate Derived State During Rendering+impact: MEDIUM+impactDescription: avoids redundant renders and state drift+tags: rerender, derived-state, useEffect, state+---++## Calculate Derived State During Rendering++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect (redundant state and effect):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct (derive during render):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.mdnew file mode 100644index 000000000..e5c899f6c--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md@@ -0,0 +1,29 @@+---+title: Subscribe to Derived State+impact: MEDIUM+impactDescription: reduces re-render frequency+tags: rerender, derived-state, media-query, optimization+---++## Subscribe to Derived State++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect (re-renders on every pixel change):**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct (re-renders only when boolean changes):**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.mdnew file mode 100644index 000000000..b004ef45e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md@@ -0,0 +1,74 @@+---+title: Use Functional setState Updates+impact: MEDIUM+impactDescription: prevents stale closures and unnecessary callback recreations+tags: react, hooks, useState, useCallback, callbacks, closures+---++## Use Functional setState Updates++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect (requires state as dependency):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct (stable callbacks, no stale closures):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes+2. **No stale closures** - Always operates on the latest state value+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks+4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value+- Inside useCallback/useMemo when state is needed+- Event handlers that reference state+- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`+- Setting state from props/arguments only: `setName(newName)`+- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.mdnew file mode 100644index 000000000..4ecb350fb--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md@@ -0,0 +1,58 @@+---+title: Use Lazy State Initialization+impact: MEDIUM+impactDescription: wasted computation on every render+tags: react, hooks, useState, performance, initialization+---++## Use Lazy State Initialization++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect (runs on every render):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct (runs only once):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.mdnew file mode 100644index 000000000..635704918--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md@@ -0,0 +1,38 @@+---++title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant+impact: MEDIUM+impactDescription: restores memoization by using a constant for default value+tags: rerender, memo, optimization++---++## Extract Default Non-primitive Parameter Value from Memoized Component to Constant++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect (`onClick` has different values on every rerender):**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct (stable default value):**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.mdnew file mode 100644index 000000000..f8982ab61--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md@@ -0,0 +1,44 @@+---+title: Extract to Memoized Components+impact: MEDIUM+impactDescription: enables early returns+tags: rerender, memo, useMemo, optimization+---++## Extract to Memoized Components++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect (computes avatar even when loading):**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct (skips computation when loading):**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.mdnew file mode 100644index 000000000..dd58a1af0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md@@ -0,0 +1,45 @@+---+title: Put Interaction Logic in Event Handlers+impact: MEDIUM+impactDescription: avoids effect re-runs and duplicate side effects+tags: rerender, useEffect, events, side-effects, dependencies+---++## Put Interaction Logic in Event Handlers++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect (event modeled as state + effect):**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct (do it in the handler):**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.mdnew file mode 100644index 000000000..59dfab0f3--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md@@ -0,0 +1,35 @@+---+title: Do not wrap a simple expression with a primitive result type in useMemo+impact: LOW-MEDIUM+impactDescription: wasted computation on every render+tags: rerender, useMemo, optimization+---++## Do not wrap a simple expression with a primitive result type in useMemo++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.mdnew file mode 100644index 000000000..d99f43f76--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md@@ -0,0 +1,40 @@+---+title: Use Transitions for Non-Urgent Updates+impact: MEDIUM+impactDescription: maintains UI responsiveness+tags: rerender, transitions, startTransition, performance+---++## Use Transitions for Non-Urgent Updates++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect (blocks UI on every scroll):**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct (non-blocking updates):**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.mdnew file mode 100644index 000000000..cf04b81f8--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md@@ -0,0 +1,73 @@+---+title: Use useRef for Transient Values+impact: MEDIUM+impactDescription: avoids unnecessary re-renders on frequent updates+tags: rerender, useref, state, performance+---++## Use useRef for Transient Values++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect (renders every update):**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct (no re-render for tracking):**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.mdnew file mode 100644index 000000000..e8f5b260f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md@@ -0,0 +1,73 @@+---+title: Use after() for Non-Blocking Operations+impact: MEDIUM+impactDescription: faster response times+tags: server, async, logging, analytics, side-effects+---++## Use after() for Non-Blocking Operations++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect (blocks response):**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct (non-blocking):**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking+- Audit logging+- Sending notifications+- Cache invalidation+- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects+- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.mdnew file mode 100644index 000000000..ee82c0442--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md@@ -0,0 +1,96 @@+---+title: Authenticate Server Actions Like API Routes+impact: CRITICAL+impactDescription: prevents unauthorized access to server mutations+tags: server, server-actions, authentication, security, authorization+---++## Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect (no authentication check):**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct (authentication inside the action):**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.mdnew file mode 100644index 000000000..ef6938aa5--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md@@ -0,0 +1,41 @@+---+title: Cross-Request LRU Caching+impact: HIGH+impactDescription: caches across requests+tags: server, cache, lru, cross-request+---++## Cross-Request LRU Caching++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.mdnew file mode 100644index 000000000..87c9ca331--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md@@ -0,0 +1,76 @@+---+title: Per-Request Deduplication with React.cache()+impact: MEDIUM+impactDescription: deduplicates within request+tags: server, cache, react-cache, deduplication+---++## Per-Request Deduplication with React.cache()++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect (always cache miss):**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct (cache hit):**++```typescript+const getUser = cache(async (uid: number) => {+ return await db.user.findUnique({ where: { id: uid } })+})++// Primitive args use value equality+getUser(1)+getUser(1) // Cache hit, returns cached result+```++If you must pass objects, pass the same reference:++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)+- Heavy computations+- Authentication checks+- File system operations+- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [React.cache documentation](https://react.dev/reference/react/cache)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.mdnew file mode 100644index 000000000..fb24a2562--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md@@ -0,0 +1,65 @@+---+title: Avoid Duplicate Serialization in RSC Props+impact: LOW+impactDescription: reduces network payload by avoiding duplicate serialization+tags: server, rsc, serialization, props, client-components+---++## Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect (duplicates array):**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct (sends 3 strings):**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++**Operations breaking deduplication (create new references):**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.mdnew file mode 100644index 000000000..1affc835a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md@@ -0,0 +1,83 @@+---+title: Parallel Data Fetching with Component Composition+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, composition+---++## Parallel Data Fetching with Component Composition++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect (Sidebar waits for Page's fetch to complete):**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct (both fetch simultaneously):**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/server-serialization.md b/.agents/skills/vercel-react-best-practices/rules/server-serialization.mdnew file mode 100644index 000000000..39c5c4164--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-serialization.md@@ -0,0 +1,38 @@+---+title: Minimize Serialization at RSC Boundaries+impact: HIGH+impactDescription: reduces data transfer size+tags: server, rsc, serialization, props+---++## Minimize Serialization at RSC Boundaries++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect (serializes all 50 fields):**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct (serializes only 1 field):**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```diff --git a/.agents/skills/vercel-react-native-skills/AGENTS.md b/.agents/skills/vercel-react-native-skills/AGENTS.mdnew file mode 100644index 000000000..00c174198--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/AGENTS.md@@ -0,0 +1,2585 @@+# React Native Skills++**Version 1.0.0**+Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React Native codebases. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Comprehensive performance optimization guide for React Native applications, designed for AI agents and LLMs. Contains 35+ rules across 13 categories, prioritized by impact from critical (core rendering, list performance) to incremental (fonts, imports). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.++---++## Table of Contents++1. [Core Rendering](#1-core-rendering) — **CRITICAL**+ - 1.1 [Never Use && with Potentially Falsy Values](#11-never-use--with-potentially-falsy-values)+ - 1.2 [Wrap Strings in Text Components](#12-wrap-strings-in-text-components)+2. [List Performance](#2-list-performance) — **HIGH**+ - 2.1 [Avoid Inline Objects in renderItem](#21-avoid-inline-objects-in-renderitem)+ - 2.2 [Hoist callbacks to the root of lists](#22-hoist-callbacks-to-the-root-of-lists)+ - 2.3 [Keep List Items Lightweight](#23-keep-list-items-lightweight)+ - 2.4 [Optimize List Performance with Stable Object References](#24-optimize-list-performance-with-stable-object-references)+ - 2.5 [Pass Primitives to List Items for Memoization](#25-pass-primitives-to-list-items-for-memoization)+ - 2.6 [Use a List Virtualizer for Any List](#26-use-a-list-virtualizer-for-any-list)+ - 2.7 [Use Compressed Images in Lists](#27-use-compressed-images-in-lists)+3. [Animation](#3-animation) — **HIGH**+ - 3.1 [Animate Transform and Opacity Instead of Layout Properties](#31-animate-transform-and-opacity-instead-of-layout-properties)+ - 3.2 [Prefer useDerivedValue Over useAnimatedReaction](#32-prefer-usederivedvalue-over-useanimatedreaction)+ - 3.3 [Use GestureDetector for Animated Press States](#33-use-gesturedetector-for-animated-press-states)+4. [Scroll Performance](#4-scroll-performance) — **HIGH**+ - 4.1 [Never Track Scroll Position in useState](#41-never-track-scroll-position-in-usestate)+5. [React State](#5-react-state) — **MEDIUM**+ - 5.1 [Minimize State Variables and Derive Values](#51-minimize-state-variables-and-derive-values)+ - 5.2 [Use fallback state instead of initialState](#52-use-fallback-state-instead-of-initialstate)+ - 5.3 [useState Dispatch updaters for State That Depends on Current Value](#53-usestate-dispatch-updaters-for-state-that-depends-on-current-value)+6. [State Architecture](#6-state-architecture) — **MEDIUM**+ - 6.1 [State Must Represent Ground Truth](#61-state-must-represent-ground-truth)+7. [React Compiler](#7-react-compiler) — **MEDIUM**+ - 7.1 [Destructure Functions Early in Render (React Compiler)](#71-destructure-functions-early-in-render-react-compiler)+ - 7.2 [Use .get() and .set() for Reanimated Shared Values (not .value)](#72-use-get-and-set-for-reanimated-shared-values-not-value)+8. [User Interface](#8-user-interface) — **MEDIUM**+ - 8.1 [Measuring View Dimensions](#81-measuring-view-dimensions)+ - 8.2 [Modern React Native Styling Patterns](#82-modern-react-native-styling-patterns)+ - 8.3 [Use contentInset for Dynamic ScrollView Spacing](#83-use-contentinset-for-dynamic-scrollview-spacing)+ - 8.4 [Use contentInsetAdjustmentBehavior for Safe Areas](#84-use-contentinsetadjustmentbehavior-for-safe-areas)+ - 8.5 [Use expo-image for Optimized Images](#85-use-expo-image-for-optimized-images)+ - 8.6 [Use Galeria for Image Galleries and Lightbox](#86-use-galeria-for-image-galleries-and-lightbox)+ - 8.7 [Use Native Menus for Dropdowns and Context Menus](#87-use-native-menus-for-dropdowns-and-context-menus)+ - 8.8 [Use Native Modals Over JS-Based Bottom Sheets](#88-use-native-modals-over-js-based-bottom-sheets)+ - 8.9 [Use Pressable Instead of Touchable Components](#89-use-pressable-instead-of-touchable-components)+9. [Design System](#9-design-system) — **MEDIUM**+ - 9.1 [Use Compound Components Over Polymorphic Children](#91-use-compound-components-over-polymorphic-children)+10. [Monorepo](#10-monorepo) — **LOW**+ - 10.1 [Install Native Dependencies in App Directory](#101-install-native-dependencies-in-app-directory)+ - 10.2 [Use Single Dependency Versions Across Monorepo](#102-use-single-dependency-versions-across-monorepo)+11. [Third-Party Dependencies](#11-third-party-dependencies) — **LOW**+ - 11.1 [Import from Design System Folder](#111-import-from-design-system-folder)+12. [JavaScript](#12-javascript) — **LOW**+ - 12.1 [Hoist Intl Formatter Creation](#121-hoist-intl-formatter-creation)+13. [Fonts](#13-fonts) — **LOW**+ - 13.1 [Load fonts natively at build time](#131-load-fonts-natively-at-build-time)++---++## 1. Core Rendering++**Impact: CRITICAL**++Fundamental React Native rendering rules. Violations cause+runtime crashes or broken UI.++### 1.1 Never Use && with Potentially Falsy Values++**Impact: CRITICAL (prevents production crash)**++Never use `{value && <Component />}` when `value` could be an empty string or++`0`. These are falsy but JSX-renderable—React Native will try to render them as++text outside a `<Text>` component, causing a hard crash in production.++**Incorrect: crashes if count is 0 or name is ""**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {name && <Text>{name}</Text>}+ {count && <Text>{count} items</Text>}+ </View>+ )+}+// If name="" or count=0, renders the falsy value → crash+```++**Correct: ternary with null**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {name ? <Text>{name}</Text> : null}+ {count ? <Text>{count} items</Text> : null}+ </View>+ )+}+```++**Correct: explicit boolean coercion**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {!!name && <Text>{name}</Text>}+ {!!count && <Text>{count} items</Text>}+ </View>+ )+}+```++**Best: early return**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ if (!name) return null++ return (+ <View>+ <Text>{name}</Text>+ {count > 0 ? <Text>{count} items</Text> : null}+ </View>+ )+}+```++Early returns are clearest. When using conditionals inline, prefer ternary or++explicit boolean checks.++**Lint rule:** Enable `react/jsx-no-leaked-render` from++[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md)++to catch this automatically.++### 1.2 Wrap Strings in Text Components++**Impact: CRITICAL (prevents runtime crash)**++Strings must be rendered inside `<Text>`. React Native crashes if a string is a++direct child of `<View>`.++**Incorrect: crashes**++```tsx+import { View } from 'react-native'++function Greeting({ name }: { name: string }) {+ return <View>Hello, {name}!</View>+}+// Error: Text strings must be rendered within a <Text> component.+```++**Correct:**++```tsx+import { View, Text } from 'react-native'++function Greeting({ name }: { name: string }) {+ return (+ <View>+ <Text>Hello, {name}!</Text>+ </View>+ )+}+```++---++## 2. List Performance++**Impact: HIGH**++Optimizing virtualized lists (FlatList, LegendList, FlashList)+for smooth scrolling and fast updates.++### 2.1 Avoid Inline Objects in renderItem++**Impact: HIGH (prevents unnecessary re-renders of memoized list items)**++Don't create new objects inside `renderItem` to pass as props. Inline objects++create new references on every render, breaking memoization. Pass primitive++values directly from `item` instead.++**Incorrect: inline object breaks memoization**++```tsx+function UserList({ users }: { users: User[] }) {+ return (+ <LegendList+ data={users}+ renderItem={({ item }) => (+ <UserRow+ // Bad: new object on every render+ user={{ id: item.id, name: item.name, avatar: item.avatar }}+ />+ )}+ />+ )+}+```++**Incorrect: inline style object**++```tsx+renderItem={({ item }) => (+ <UserRow+ name={item.name}+ // Bad: new style object on every render+ style={{ backgroundColor: item.isActive ? 'green' : 'gray' }}+ />+)}+```++**Correct: pass item directly or primitives**++```tsx+function UserList({ users }: { users: User[] }) {+ return (+ <LegendList+ data={users}+ renderItem={({ item }) => (+ // Good: pass the item directly+ <UserRow user={item} />+ )}+ />+ )+}+```++**Correct: pass primitives, derive inside child**++```tsx+renderItem={({ item }) => (+ <UserRow+ id={item.id}+ name={item.name}+ isActive={item.isActive}+ />+)}++const UserRow = memo(function UserRow({ id, name, isActive }: Props) {+ // Good: derive style inside memoized component+ const backgroundColor = isActive ? 'green' : 'gray'+ return <View style={[styles.row, { backgroundColor }]}>{/* ... */}</View>+})+```++**Correct: hoist static styles in module scope**++```tsx+const activeStyle = { backgroundColor: 'green' }+const inactiveStyle = { backgroundColor: 'gray' }++renderItem={({ item }) => (+ <UserRow+ name={item.name}+ // Good: stable references+ style={item.isActive ? activeStyle : inactiveStyle}+ />+)}+```++Passing primitives or stable references allows `memo()` to skip re-renders when++the actual values haven't changed.++**Note:** If you have the React Compiler enabled, it handles memoization++automatically and these manual optimizations become less critical.++### 2.2 Hoist callbacks to the root of lists++**Impact: MEDIUM (Fewer re-renders and faster lists)**++When passing callback functions to list items, create a single instance of the++callback at the root of the list. Items should then call it with a unique++identifier.++**Incorrect: creates a new callback on each render**++```typescript+return (+ <LegendList+ renderItem={({ item }) => {+ // bad: creates a new callback on each render+ const onPress = () => handlePress(item.id)+ return <Item key={item.id} item={item} onPress={onPress} />+ }}+ />+)+```++**Correct: a single function instance passed to each item**++```typescript+const onPress = useCallback(() => handlePress(item.id), [handlePress, item.id])++return (+ <LegendList+ renderItem={({ item }) => (+ <Item key={item.id} item={item} onPress={onPress} />+ )}+ />+)+```++Reference: [https://example.com](https://example.com)++### 2.3 Keep List Items Lightweight++**Impact: HIGH (reduces render time for visible items during scroll)**++List items should be as inexpensive as possible to render. Minimize hooks, avoid++queries, and limit React Context access. Virtualized lists render many items++during scroll—expensive items cause jank.++**Incorrect: heavy list item**++```tsx+function ProductRow({ id }: { id: string }) {+ // Bad: query inside list item+ const { data: product } = useQuery(['product', id], () => fetchProduct(id))+ // Bad: multiple context accesses+ const theme = useContext(ThemeContext)+ const user = useContext(UserContext)+ const cart = useContext(CartContext)+ // Bad: expensive computation+ const recommendations = useMemo(+ () => computeRecommendations(product),+ [product]+ )++ return <View>{/* ... */}</View>+}+```++**Correct: lightweight list item**++```tsx+function ProductRow({ name, price, imageUrl }: Props) {+ // Good: receives only primitives, minimal hooks+ return (+ <View>+ <Image source={{ uri: imageUrl }} />+ <Text>{name}</Text>+ <Text>{price}</Text>+ </View>+ )+}+```++**Move data fetching to parent:**++```tsx+// Parent fetches all data once+function ProductList() {+ const { data: products } = useQuery(['products'], fetchProducts)++ return (+ <LegendList+ data={products}+ renderItem={({ item }) => (+ <ProductRow name={item.name} price={item.price} imageUrl={item.image} />+ )}+ />+ )+}+```++**For shared values, use Zustand selectors instead of Context:**++```tsx+// Incorrect: Context causes re-render when any cart value changes+function ProductRow({ id, name }: Props) {+ const { items } = useContext(CartContext)+ const inCart = items.includes(id)+ // ...+}++// Correct: Zustand selector only re-renders when this specific value changes+function ProductRow({ id, name }: Props) {+ // use Set.has (created once at the root) instead of Array.includes()+ const inCart = useCartStore((s) => s.items.has(id))+ // ...+}+```++**Guidelines for list items:**++- No queries or data fetching++- No expensive computations (move to parent or memoize at parent level)++- Prefer Zustand selectors over React Context++- Minimize useState/useEffect hooks++- Pass pre-computed values as props++The goal: list items should be simple rendering functions that take props and++return JSX.++### 2.4 Optimize List Performance with Stable Object References++**Impact: CRITICAL (virtualization relies on reference stability)**++Don't map or filter data before passing to virtualized lists. Virtualization++relies on object reference stability to know what changed—new references cause++full re-renders of all visible items. Attempt to prevent frequent renders at the++list-parent level.++Where needed, use context selectors within list items.++**Incorrect: creates new object references on every keystroke**++```tsx+function DomainSearch() {+ const { keyword, setKeyword } = useKeywordZustandState()+ const { data: tlds } = useTlds()++ // Bad: creates new objects on every render, reparenting the entire list on every keystroke+ const domains = tlds.map((tld) => ({+ domain: `${keyword}.${tld.name}`,+ tld: tld.name,+ price: tld.price,+ }))++ return (+ <>+ <TextInput value={keyword} onChangeText={setKeyword} />+ <LegendList+ data={domains}+ renderItem={({ item }) => <DomainItem item={item} keyword={keyword} />}+ />+ </>+ )+}+```++**Correct: stable references, transform inside items**++```tsx+const renderItem = ({ item }) => <DomainItem tld={item} />++function DomainSearch() {+ const { data: tlds } = useTlds()++ return (+ <LegendList+ // good: as long as the data is stable, LegendList will not re-render the entire list+ data={tlds}+ renderItem={renderItem}+ />+ )+}++function DomainItem({ tld }: { tld: Tld }) {+ // good: transform within items, and don't pass the dynamic data as a prop+ // good: use a selector function from zustand to receive a stable string back+ const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.name)+ return <Text>{domain}</Text>+}+```++**Updating parent array reference:**++```tsx+// good: creates a new array instance without mutating the inner objects+// good: parent array reference is unaffected by typing and updating "keyword"+const sortedTlds = tlds.toSorted((a, b) => a.name.localeCompare(b.name))++return <LegendList data={sortedTlds} renderItem={renderItem} />+```++Creating a new array instance can be okay, as long as its inner object++references are stable. For instance, if you sort a list of objects:++Even though this creates a new array instance `sortedTlds`, the inner object++references are stable.++**With zustand for dynamic data: avoids parent re-renders**++```tsx+function DomainItemFavoriteButton({ tld }: { tld: Tld }) {+ const isFavorited = useFavoritesStore((s) => s.favorites.has(tld.id))+ return <TldFavoriteButton isFavorited={isFavorited} />+}+```++Virtualization can now skip items that haven't changed when typing. Only visible++items (~20) re-render on keystroke, rather than the parent.++**Deriving state within list items based on parent data (avoids parent++re-renders):**++For components where the data is conditional based on the parent state, this++pattern is even more important. For example, if you are checking if an item is++favorited, toggling favorites only re-renders one component if the item itself++is in charge of accessing the state rather than the parent:++Note: if you're using the React Compiler, you can read React Context values++directly within list items. Although this is slightly slower than using a++Zustand selector in most cases, the effect may be negligible.++### 2.5 Pass Primitives to List Items for Memoization++**Impact: HIGH (enables effective memo() comparison)**++When possible, pass only primitive values (strings, numbers, booleans) as props++to list item components. Primitives enable shallow comparison in `memo()` to++work correctly, skipping re-renders when values haven't changed.++**Incorrect: object prop requires deep comparison**++```tsx+type User = { id: string; name: string; email: string; avatar: string }++const UserRow = memo(function UserRow({ user }: { user: User }) {+ // memo() compares user by reference, not value+ // If parent creates new user object, this re-renders even if data is same+ return <Text>{user.name}</Text>+})++renderItem={({ item }) => <UserRow user={item} />}+```++This can still be optimized, but it is harder to memoize properly.++**Correct: primitive props enable shallow comparison**++```tsx+const UserRow = memo(function UserRow({+ id,+ name,+ email,+}: {+ id: string+ name: string+ email: string+}) {+ // memo() compares each primitive directly+ // Re-renders only if id, name, or email actually changed+ return <Text>{name}</Text>+})++renderItem={({ item }) => (+ <UserRow id={item.id} name={item.name} email={item.email} />+)}+```++**Pass only what you need:**++```tsx+// Incorrect: passing entire item when you only need name+<UserRow user={item} />++// Correct: pass only the fields the component uses+<UserRow name={item.name} avatarUrl={item.avatar} />+```++**For callbacks, hoist or use item ID:**++```tsx+// Incorrect: inline function creates new reference+<UserRow name={item.name} onPress={() => handlePress(item.id)} />++// Correct: pass ID, handle in child+<UserRow id={item.id} name={item.name} />++const UserRow = memo(function UserRow({ id, name }: Props) {+ const handlePress = useCallback(() => {+ // use id here+ }, [id])+ return <Pressable onPress={handlePress}><Text>{name}</Text></Pressable>+})+```++Primitive props make memoization predictable and effective.++**Note:** If you have the React Compiler enabled, you do not need to use++`memo()` or `useCallback()`, but the object references still apply.++### 2.6 Use a List Virtualizer for Any List++**Impact: HIGH (reduced memory, faster mounts)**++Use a list virtualizer like LegendList or FlashList instead of ScrollView with++mapped children—even for short lists. Virtualizers only render visible items,++reducing memory usage and mount time. ScrollView renders all children upfront,++which gets expensive quickly.++**Incorrect: ScrollView renders all items at once**++```tsx+function Feed({ items }: { items: Item[] }) {+ return (+ <ScrollView>+ {items.map((item) => (+ <ItemCard key={item.id} item={item} />+ ))}+ </ScrollView>+ )+}+// 50 items = 50 components mounted, even if only 10 visible+```++**Correct: virtualizer renders only visible items**++```tsx+import { LegendList } from '@legendapp/list'++function Feed({ items }: { items: Item[] }) {+ return (+ <LegendList+ data={items}+ // if you aren't using React Compiler, wrap these with useCallback+ renderItem={({ item }) => <ItemCard item={item} />}+ keyExtractor={(item) => item.id}+ estimatedItemSize={80}+ />+ )+}+// Only ~10-15 visible items mounted at a time+```++**Alternative: FlashList**++```tsx+import { FlashList } from '@shopify/flash-list'++function Feed({ items }: { items: Item[] }) {+ return (+ <FlashList+ data={items}+ // if you aren't using React Compiler, wrap these with useCallback+ renderItem={({ item }) => <ItemCard item={item} />}+ keyExtractor={(item) => item.id}+ />+ )+}+```++Benefits apply to any screen with scrollable content—profiles, settings, feeds,++search results. Default to virtualization.++### 2.7 Use Compressed Images in Lists++**Impact: HIGH (faster load times, less memory)**++Always load compressed, appropriately-sized images in lists. Full-resolution++images consume excessive memory and cause scroll jank. Request thumbnails from++your server or use an image CDN with resize parameters.++**Incorrect: full-resolution images**++```tsx+function ProductItem({ product }: { product: Product }) {+ return (+ <View>+ {/* 4000x3000 image loaded for a 100x100 thumbnail */}+ <Image+ source={{ uri: product.imageUrl }}+ style={{ width: 100, height: 100 }}+ />+ <Text>{product.name}</Text>+ </View>+ )+}+```++**Correct: request appropriately-sized image**++```tsx+function ProductItem({ product }: { product: Product }) {+ // Request a 200x200 image (2x for retina)+ const thumbnailUrl = `${product.imageUrl}?w=200&h=200&fit=cover`++ return (+ <View>+ <Image+ source={{ uri: thumbnailUrl }}+ style={{ width: 100, height: 100 }}+ contentFit='cover'+ />+ <Text>{product.name}</Text>+ </View>+ )+}+```++Use an optimized image component with built-in caching and placeholder support,++such as `expo-image` or `SolitoImage` (which uses `expo-image` under the hood).++Request images at 2x the display size for retina screens.++---++## 3. Animation++**Impact: HIGH**++GPU-accelerated animations, Reanimated patterns, and avoiding+render thrashing during gestures.++### 3.1 Animate Transform and Opacity Instead of Layout Properties++**Impact: HIGH (GPU-accelerated animations, no layout recalculation)**++Avoid animating `width`, `height`, `top`, `left`, `margin`, or `padding`. These trigger layout recalculation on every frame. Instead, use `transform` (scale, translate) and `opacity` which run on the GPU without triggering layout.++**Incorrect: animates height, triggers layout every frame**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function CollapsiblePanel({ expanded }: { expanded: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ height: withTiming(expanded ? 200 : 0), // triggers layout on every frame+ overflow: 'hidden',+ }))++ return <Animated.View style={animatedStyle}>{children}</Animated.View>+}+```++**Correct: animates scaleY, GPU-accelerated**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function CollapsiblePanel({ expanded }: { expanded: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { scaleY: withTiming(expanded ? 1 : 0) },+ ],+ opacity: withTiming(expanded ? 1 : 0),+ }))++ return (+ <Animated.View style={[{ height: 200, transformOrigin: 'top' }, animatedStyle]}>+ {children}+ </Animated.View>+ )+}+```++**Correct: animates translateY for slide animations**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function SlideIn({ visible }: { visible: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { translateY: withTiming(visible ? 0 : 100) },+ ],+ opacity: withTiming(visible ? 1 : 0),+ }))++ return <Animated.View style={animatedStyle}>{children}</Animated.View>+}+```++GPU-accelerated properties: `transform` (translate, scale, rotate), `opacity`. Everything else triggers layout.++### 3.2 Prefer useDerivedValue Over useAnimatedReaction++**Impact: MEDIUM (cleaner code, automatic dependency tracking)**++When deriving a shared value from another, use `useDerivedValue` instead of++`useAnimatedReaction`. Derived values are declarative, automatically track++dependencies, and return a value you can use directly. Animated reactions are++for side effects, not derivations.++[Reanimated useDerivedValue](https://docs.swmansion.com/react-native-reanimated/docs/core/useDerivedValue)++**Incorrect: useAnimatedReaction for derivation**++```tsx+import { useSharedValue, useAnimatedReaction } from 'react-native-reanimated'++function MyComponent() {+ const progress = useSharedValue(0)+ const opacity = useSharedValue(1)++ useAnimatedReaction(+ () => progress.value,+ (current) => {+ opacity.value = 1 - current+ }+ )++ // ...+}+```++**Correct: useDerivedValue**++```tsx+import { useSharedValue, useDerivedValue } from 'react-native-reanimated'++function MyComponent() {+ const progress = useSharedValue(0)++ const opacity = useDerivedValue(() => 1 - progress.get())++ // ...+}+```++Use `useAnimatedReaction` only for side effects that don't produce a value++(e.g., triggering haptics, logging, calling `runOnJS`).++### 3.3 Use GestureDetector for Animated Press States++**Impact: MEDIUM (UI thread animations, smoother press feedback)**++For animated press states (scale, opacity on press), use `GestureDetector` with++`Gesture.Tap()` and shared values instead of Pressable's++`onPressIn`/`onPressOut`. Gesture callbacks run on the UI thread as worklets—no++JS thread round-trip for press animations.++[Gesture Handler Tap Gesture](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture)++**Incorrect: Pressable with JS thread callbacks**++```tsx+import { Pressable } from 'react-native'+import Animated, {+ useSharedValue,+ useAnimatedStyle,+ withTiming,+} from 'react-native-reanimated'++function AnimatedButton({ onPress }: { onPress: () => void }) {+ const scale = useSharedValue(1)++ const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: scale.value }],+ }))++ return (+ <Pressable+ onPress={onPress}+ onPressIn={() => (scale.value = withTiming(0.95))}+ onPressOut={() => (scale.value = withTiming(1))}+ >+ <Animated.View style={animatedStyle}>+ <Text>Press me</Text>+ </Animated.View>+ </Pressable>+ )+}+```++**Correct: GestureDetector with UI thread worklets**++```tsx+import { Gesture, GestureDetector } from 'react-native-gesture-handler'+import Animated, {+ useSharedValue,+ useAnimatedStyle,+ withTiming,+ interpolate,+ runOnJS,+} from 'react-native-reanimated'++function AnimatedButton({ onPress }: { onPress: () => void }) {+ // Store the press STATE (0 = not pressed, 1 = pressed)+ const pressed = useSharedValue(0)++ const tap = Gesture.Tap()+ .onBegin(() => {+ pressed.set(withTiming(1))+ })+ .onFinalize(() => {+ pressed.set(withTiming(0))+ })+ .onEnd(() => {+ runOnJS(onPress)()+ })++ // Derive visual values from the state+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { scale: interpolate(withTiming(pressed.get()), [0, 1], [1, 0.95]) },+ ],+ }))++ return (+ <GestureDetector gesture={tap}>+ <Animated.View style={animatedStyle}>+ <Text>Press me</Text>+ </Animated.View>+ </GestureDetector>+ )+}+```++Store the press **state** (0 or 1), then derive the scale via `interpolate`.++This keeps the shared value as ground truth. Use `runOnJS` to call JS functions++from worklets. Use `.set()` and `.get()` for React Compiler compatibility.++---++## 4. Scroll Performance++**Impact: HIGH**++Tracking scroll position without causing render thrashing.++### 4.1 Never Track Scroll Position in useState++**Impact: HIGH (prevents render thrashing during scroll)**++Never store scroll position in `useState`. Scroll events fire rapidly—state++updates cause render thrashing and dropped frames. Use a Reanimated shared value++for animations or a ref for non-reactive tracking.++**Incorrect: useState causes jank**++```tsx+import { useState } from 'react'+import {+ ScrollView,+ NativeSyntheticEvent,+ NativeScrollEvent,+} from 'react-native'++function Feed() {+ const [scrollY, setScrollY] = useState(0)++ const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {+ setScrollY(e.nativeEvent.contentOffset.y) // re-renders on every frame+ }++ return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />+}+```++**Correct: Reanimated for animations**++```tsx+import Animated, {+ useSharedValue,+ useAnimatedScrollHandler,+} from 'react-native-reanimated'++function Feed() {+ const scrollY = useSharedValue(0)++ const onScroll = useAnimatedScrollHandler({+ onScroll: (e) => {+ scrollY.value = e.contentOffset.y // runs on UI thread, no re-render+ },+ })++ return (+ <Animated.ScrollView+ onScroll={onScroll}+ // higher number has better performance, but it fires less often.+ // unset this if you need higher precision over performance.+ scrollEventThrottle={16}+ />+ )+}+```++**Correct: ref for non-reactive tracking**++```tsx+import { useRef } from 'react'+import {+ ScrollView,+ NativeSyntheticEvent,+ NativeScrollEvent,+} from 'react-native'++function Feed() {+ const scrollY = useRef(0)++ const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {+ scrollY.current = e.nativeEvent.contentOffset.y // no re-render+ }++ return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />+}+```++---++## 5. React State++**Impact: MEDIUM**++Patterns for managing React state to avoid stale closures and+unnecessary re-renders.++### 5.1 Minimize State Variables and Derive Values++**Impact: MEDIUM (fewer re-renders, less state drift)**++Use the fewest state variables possible. If a value can be computed from existing state or props, derive it during render instead of storing it in state. Redundant state causes unnecessary re-renders and can drift out of sync.++**Incorrect: redundant state**++```tsx+function Cart({ items }: { items: Item[] }) {+ const [total, setTotal] = useState(0)+ const [itemCount, setItemCount] = useState(0)++ useEffect(() => {+ setTotal(items.reduce((sum, item) => sum + item.price, 0))+ setItemCount(items.length)+ }, [items])++ return (+ <View>+ <Text>{itemCount} items</Text>+ <Text>Total: ${total}</Text>+ </View>+ )+}+```++**Correct: derived values**++```tsx+function Cart({ items }: { items: Item[] }) {+ const total = items.reduce((sum, item) => sum + item.price, 0)+ const itemCount = items.length++ return (+ <View>+ <Text>{itemCount} items</Text>+ <Text>Total: ${total}</Text>+ </View>+ )+}+```++**Another example:**++```tsx+// Incorrect: storing both firstName, lastName, AND fullName+const [firstName, setFirstName] = useState('')+const [lastName, setLastName] = useState('')+const [fullName, setFullName] = useState('')++// Correct: derive fullName+const [firstName, setFirstName] = useState('')+const [lastName, setLastName] = useState('')+const fullName = `${firstName} ${lastName}`+```++State should be the minimal source of truth. Everything else is derived.++Reference: [https://react.dev/learn/choosing-the-state-structure](https://react.dev/learn/choosing-the-state-structure)++### 5.2 Use fallback state instead of initialState++**Impact: MEDIUM (reactive fallbacks without syncing)**++Use `undefined` as initial state and nullish coalescing (`??`) to fall back to++parent or server values. State represents user intent only—`undefined` means++"user hasn't chosen yet." This enables reactive fallbacks that update when the++source changes, not just on initial render.++**Incorrect: syncs state, loses reactivity**++```tsx+type Props = { fallbackEnabled: boolean }++function Toggle({ fallbackEnabled }: Props) {+ const [enabled, setEnabled] = useState(defaultEnabled)+ // If fallbackEnabled changes, state is stale+ // State mixes user intent with default value++ return <Switch value={enabled} onValueChange={setEnabled} />+}+```++**Correct: state is user intent, reactive fallback**++```tsx+type Props = { fallbackEnabled: boolean }++function Toggle({ fallbackEnabled }: Props) {+ const [_enabled, setEnabled] = useState<boolean | undefined>(undefined)+ const enabled = _enabled ?? defaultEnabled+ // undefined = user hasn't touched it, falls back to prop+ // If defaultEnabled changes, component reflects it+ // Once user interacts, their choice persists++ return <Switch value={enabled} onValueChange={setEnabled} />+}+```++**With server data:**++```tsx+function ProfileForm({ data }: { data: User }) {+ const [_theme, setTheme] = useState<string | undefined>(undefined)+ const theme = _theme ?? data.theme+ // Shows server value until user overrides+ // Server refetch updates the fallback automatically++ return <ThemePicker value={theme} onChange={setTheme} />+}+```++### 5.3 useState Dispatch updaters for State That Depends on Current Value++**Impact: MEDIUM (avoids stale closures, prevents unnecessary re-renders)**++When the next state depends on the current state, use a dispatch updater++(`setState(prev => ...)`) instead of reading the state variable directly in a++callback. This avoids stale closures and ensures you're comparing against the++latest value.++**Incorrect: reads state directly**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ // size may be stale in this closure+ if (size?.width !== width || size?.height !== height) {+ setSize({ width, height })+ }+}+```++**Correct: dispatch updater**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => {+ if (prev?.width === width && prev?.height === height) return prev+ return { width, height }+ })+}+```++Returning the previous value from the updater skips the re-render.++For primitive states, you don't need to compare values before firing a++re-render.++**Incorrect: unnecessary comparison for primitive state**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => (prev === width ? prev : width))+}+```++**Correct: sets primitive state directly**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize(width)+}+```++However, if the next state depends on the current state, you should still use a++dispatch updater.++**Incorrect: reads state directly from the callback**++```tsx+const [count, setCount] = useState(0)++const onTap = () => {+ setCount(count + 1)+}+```++**Correct: dispatch updater**++```tsx+const [count, setCount] = useState(0)++const onTap = () => {+ setCount((prev) => prev + 1)+}+```++---++## 6. State Architecture++**Impact: MEDIUM**++Ground truth principles for state variables and derived values.++### 6.1 State Must Represent Ground Truth++**Impact: HIGH (cleaner logic, easier debugging, single source of truth)**++State variables—both React `useState` and Reanimated shared values—should++represent the actual state of something (e.g., `pressed`, `progress`, `isOpen`),++not derived visual values (e.g., `scale`, `opacity`, `translateY`). Derive++visual values from state using computation or interpolation.++**Incorrect: storing the visual output**++```tsx+const scale = useSharedValue(1)++const tap = Gesture.Tap()+ .onBegin(() => {+ scale.set(withTiming(0.95))+ })+ .onFinalize(() => {+ scale.set(withTiming(1))+ })++const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: scale.get() }],+}))+```++**Correct: storing the state, deriving the visual**++```tsx+const pressed = useSharedValue(0) // 0 = not pressed, 1 = pressed++const tap = Gesture.Tap()+ .onBegin(() => {+ pressed.set(withTiming(1))+ })+ .onFinalize(() => {+ pressed.set(withTiming(0))+ })++const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: interpolate(pressed.get(), [0, 1], [1, 0.95]) }],+}))+```++**Why this matters:**++State variables should represent real "state", not necessarily a desired end++result.++1. **Single source of truth** — The state (`pressed`) describes what's++ happening; visuals are derived++2. **Easier to extend** — Adding opacity, rotation, or other effects just++ requires more interpolations from the same state++3. **Debugging** — Inspecting `pressed = 1` is clearer than `scale = 0.95`++4. **Reusable logic** — The same `pressed` value can drive multiple visual++ properties++**Same principle for React state:**++```tsx+// Incorrect: storing derived values+const [isExpanded, setIsExpanded] = useState(false)+const [height, setHeight] = useState(0)++useEffect(() => {+ setHeight(isExpanded ? 200 : 0)+}, [isExpanded])++// Correct: derive from state+const [isExpanded, setIsExpanded] = useState(false)+const height = isExpanded ? 200 : 0+```++State is the minimal truth. Everything else is derived.++---++## 7. React Compiler++**Impact: MEDIUM**++Compatibility patterns for React Compiler with React Native and+Reanimated.++### 7.1 Destructure Functions Early in Render (React Compiler)++**Impact: HIGH (stable references, fewer re-renders)**++This rule is only applicable if you are using the React Compiler.++Destructure functions from hooks at the top of render scope. Never dot into++objects to call functions. Destructured functions are stable references; dotting++creates new references and breaks memoization.++**Incorrect: dotting into object**++```tsx+import { useRouter } from 'expo-router'++function SaveButton(props) {+ const router = useRouter()++ // bad: react-compiler will key the cache on "props" and "router", which are objects that change each render+ const handlePress = () => {+ props.onSave()+ router.push('/success') // unstable reference+ }++ return <Button onPress={handlePress}>Save</Button>+}+```++**Correct: destructure early**++```tsx+import { useRouter } from 'expo-router'++function SaveButton({ onSave }) {+ const { push } = useRouter()++ // good: react-compiler will key on push and onSave+ const handlePress = () => {+ onSave()+ push('/success') // stable reference+ }++ return <Button onPress={handlePress}>Save</Button>+}+```++### 7.2 Use .get() and .set() for Reanimated Shared Values (not .value)++**Impact: LOW (required for React Compiler compatibility)**++With React Compiler enabled, use `.get()` and `.set()` instead of reading or++writing `.value` directly on Reanimated shared values. The compiler can't track++property access—explicit methods ensure correct behavior.++**Incorrect: breaks with React Compiler**++```tsx+import { useSharedValue } from 'react-native-reanimated'++function Counter() {+ const count = useSharedValue(0)++ const increment = () => {+ count.value = count.value + 1 // opts out of react compiler+ }++ return <Button onPress={increment} title={`Count: ${count.value}`} />+}+```++**Correct: React Compiler compatible**++```tsx+import { useSharedValue } from 'react-native-reanimated'++function Counter() {+ const count = useSharedValue(0)++ const increment = () => {+ count.set(count.get() + 1)+ }++ return <Button onPress={increment} title={`Count: ${count.get()}`} />+}+```++See the++[Reanimated docs](https://docs.swmansion.com/react-native-reanimated/docs/core/useSharedValue/#react-compiler-support)++for more.++---++## 8. User Interface++**Impact: MEDIUM**++Native UI patterns for images, menus, modals, styling, and+platform-consistent interfaces.++### 8.1 Measuring View Dimensions++**Impact: MEDIUM (synchronous measurement, avoid unnecessary re-renders)**++Use both `useLayoutEffect` (synchronous) and `onLayout` (for updates). The sync++measurement gives you the initial size immediately; `onLayout` keeps it current++when the view changes. For non-primitive states, use a dispatch updater to++compare values and avoid unnecessary re-renders.++**Height only:**++```tsx+import { useLayoutEffect, useRef, useState } from 'react'+import { View, LayoutChangeEvent } from 'react-native'++function MeasuredBox({ children }: { children: React.ReactNode }) {+ const ref = useRef<View>(null)+ const [height, setHeight] = useState<number | undefined>(undefined)++ useLayoutEffect(() => {+ // Sync measurement on mount (RN 0.82+)+ const rect = ref.current?.getBoundingClientRect()+ if (rect) setHeight(rect.height)+ // Pre-0.82: ref.current?.measure((x, y, w, h) => setHeight(h))+ }, [])++ const onLayout = (e: LayoutChangeEvent) => {+ setHeight(e.nativeEvent.layout.height)+ }++ return (+ <View ref={ref} onLayout={onLayout}>+ {children}+ </View>+ )+}+```++**Both dimensions:**++```tsx+import { useLayoutEffect, useRef, useState } from 'react'+import { View, LayoutChangeEvent } from 'react-native'++type Size = { width: number; height: number }++function MeasuredBox({ children }: { children: React.ReactNode }) {+ const ref = useRef<View>(null)+ const [size, setSize] = useState<Size | undefined>(undefined)++ useLayoutEffect(() => {+ const rect = ref.current?.getBoundingClientRect()+ if (rect) setSize({ width: rect.width, height: rect.height })+ }, [])++ const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => {+ // for non-primitive states, compare values before firing a re-render+ if (prev?.width === width && prev?.height === height) return prev+ return { width, height }+ })+ }++ return (+ <View ref={ref} onLayout={onLayout}>+ {children}+ </View>+ )+}+```++Use functional setState to compare—don't read state directly in the callback.++### 8.2 Modern React Native Styling Patterns++**Impact: MEDIUM (consistent design, smoother borders, cleaner layouts)**++Follow these styling patterns for cleaner, more consistent React Native code.++**Always use `borderCurve: 'continuous'` with `borderRadius`:**++**Use `gap` instead of margin for spacing between elements:**++```tsx+// Incorrect – margin on children+<View>+ <Text style={{ marginBottom: 8 }}>Title</Text>+ <Text style={{ marginBottom: 8 }}>Subtitle</Text>+</View>++// Correct – gap on parent+<View style={{ gap: 8 }}>+ <Text>Title</Text>+ <Text>Subtitle</Text>+</View>+```++**Use `padding` for space within, `gap` for space between:**++```tsx+<View style={{ padding: 16, gap: 12 }}>+ <Text>First</Text>+ <Text>Second</Text>+</View>+```++**Use `experimental_backgroundImage` for linear gradients:**++```tsx+// Incorrect – third-party gradient library+<LinearGradient colors={['#000', '#fff']} />++// Correct – native CSS gradient syntax+<View+ style={{+ experimental_backgroundImage: 'linear-gradient(to bottom, #000, #fff)',+ }}+/>+```++**Use CSS `boxShadow` string syntax for shadows:**++```tsx+// Incorrect – legacy shadow objects or elevation+{ shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1 }+{ elevation: 4 }++// Correct – CSS box-shadow syntax+{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }+```++**Avoid multiple font sizes – use weight and color for emphasis:**++```tsx+// Incorrect – varying font sizes for hierarchy+<Text style={{ fontSize: 18 }}>Title</Text>+<Text style={{ fontSize: 14 }}>Subtitle</Text>+<Text style={{ fontSize: 12 }}>Caption</Text>++// Correct – consistent size, vary weight and color+<Text style={{ fontWeight: '600' }}>Title</Text>+<Text style={{ color: '#666' }}>Subtitle</Text>+<Text style={{ color: '#999' }}>Caption</Text>+```++Limiting font sizes creates visual consistency. Use `fontWeight` (bold/semibold)++and grayscale colors for hierarchy instead.++### 8.3 Use contentInset for Dynamic ScrollView Spacing++**Impact: LOW (smoother updates, no layout recalculation)**++When adding space to the top or bottom of a ScrollView that may change++(keyboard, toolbars, dynamic content), use `contentInset` instead of padding.++Changing `contentInset` doesn't trigger layout recalculation—it adjusts the++scroll area without re-rendering content.++**Incorrect: padding causes layout recalculation**++```tsx+function Feed({ bottomOffset }: { bottomOffset: number }) {+ return (+ <ScrollView contentContainerStyle={{ paddingBottom: bottomOffset }}>+ {children}+ </ScrollView>+ )+}+// Changing bottomOffset triggers full layout recalculation+```++**Correct: contentInset for dynamic spacing**++```tsx+function Feed({ bottomOffset }: { bottomOffset: number }) {+ return (+ <ScrollView+ contentInset={{ bottom: bottomOffset }}+ scrollIndicatorInsets={{ bottom: bottomOffset }}+ >+ {children}+ </ScrollView>+ )+}+// Changing bottomOffset only adjusts scroll bounds+```++Use `scrollIndicatorInsets` alongside `contentInset` to keep the scroll++indicator aligned. For static spacing that never changes, padding is fine.++### 8.4 Use contentInsetAdjustmentBehavior for Safe Areas++**Impact: MEDIUM (native safe area handling, no layout shifts)**++Use `contentInsetAdjustmentBehavior="automatic"` on the root ScrollView instead of wrapping content in SafeAreaView or manual padding. This lets iOS handle safe area insets natively with proper scroll behavior.++**Incorrect: SafeAreaView wrapper**++```tsx+import { SafeAreaView, ScrollView, View, Text } from 'react-native'++function MyScreen() {+ return (+ <SafeAreaView style={{ flex: 1 }}>+ <ScrollView>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ </SafeAreaView>+ )+}+```++**Incorrect: manual safe area padding**++```tsx+import { ScrollView, View, Text } from 'react-native'+import { useSafeAreaInsets } from 'react-native-safe-area-context'++function MyScreen() {+ const insets = useSafeAreaInsets()++ return (+ <ScrollView contentContainerStyle={{ paddingTop: insets.top }}>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ )+}+```++**Correct: native content inset adjustment**++```tsx+import { ScrollView, View, Text } from 'react-native'++function MyScreen() {+ return (+ <ScrollView contentInsetAdjustmentBehavior='automatic'>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ )+}+```++The native approach handles dynamic safe areas (keyboard, toolbars) and allows content to scroll behind the status bar naturally.++### 8.5 Use expo-image for Optimized Images++**Impact: HIGH (memory efficiency, caching, blurhash placeholders, progressive loading)**++Use `expo-image` instead of React Native's `Image`. It provides memory-efficient caching, blurhash placeholders, progressive loading, and better performance for lists.++**Incorrect: React Native Image**++```tsx+import { Image } from 'react-native'++function Avatar({ url }: { url: string }) {+ return <Image source={{ uri: url }} style={styles.avatar} />+}+```++**Correct: expo-image**++```tsx+import { Image } from 'expo-image'++function Avatar({ url }: { url: string }) {+ return <Image source={{ uri: url }} style={styles.avatar} />+}+```++**With blurhash placeholder:**++```tsx+<Image+ source={{ uri: url }}+ placeholder={{ blurhash: 'LGF5]+Yk^6#M@-5c,1J5@[or[Q6.' }}+ contentFit="cover"+ transition={200}+ style={styles.image}+/>+```++**With priority and caching:**++```tsx+<Image+ source={{ uri: url }}+ priority="high"+ cachePolicy="memory-disk"+ style={styles.hero}+/>+```++**Key props:**++- `placeholder` — Blurhash or thumbnail while loading++- `contentFit` — `cover`, `contain`, `fill`, `scale-down`++- `transition` — Fade-in duration (ms)++- `priority` — `low`, `normal`, `high`++- `cachePolicy` — `memory`, `disk`, `memory-disk`, `none`++- `recyclingKey` — Unique key for list recycling++For cross-platform (web + native), use `SolitoImage` from `solito/image` which uses `expo-image` under the hood.++Reference: [https://docs.expo.dev/versions/latest/sdk/image/](https://docs.expo.dev/versions/latest/sdk/image/)++### 8.6 Use Galeria for Image Galleries and Lightbox++**Impact: MEDIUM**++For image galleries with lightbox (tap to fullscreen), use `@nandorojo/galeria`.++It provides native shared element transitions with pinch-to-zoom, double-tap++zoom, and pan-to-close. Works with any image component including `expo-image`.++**Incorrect: custom modal implementation**++```tsx+function ImageGallery({ urls }: { urls: string[] }) {+ const [selected, setSelected] = useState<string | null>(null)++ return (+ <>+ {urls.map((url) => (+ <Pressable key={url} onPress={() => setSelected(url)}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Pressable>+ ))}+ <Modal visible={!!selected} onRequestClose={() => setSelected(null)}>+ <Image source={{ uri: selected! }} style={styles.fullscreen} />+ </Modal>+ </>+ )+}+```++**Correct: Galeria with expo-image**++```tsx+import { Galeria } from '@nandorojo/galeria'+import { Image } from 'expo-image'++function ImageGallery({ urls }: { urls: string[] }) {+ return (+ <Galeria urls={urls}>+ {urls.map((url, index) => (+ <Galeria.Image index={index} key={url}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Galeria.Image>+ ))}+ </Galeria>+ )+}+```++**Single image:**++```tsx+import { Galeria } from '@nandorojo/galeria'+import { Image } from 'expo-image'++function Avatar({ url }: { url: string }) {+ return (+ <Galeria urls={[url]}>+ <Galeria.Image>+ <Image source={{ uri: url }} style={styles.avatar} />+ </Galeria.Image>+ </Galeria>+ )+}+```++**With low-res thumbnails and high-res fullscreen:**++```tsx+<Galeria urls={highResUrls}>+ {lowResUrls.map((url, index) => (+ <Galeria.Image index={index} key={url}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Galeria.Image>+ ))}+</Galeria>+```++**With FlashList:**++```tsx+<Galeria urls={urls}>+ <FlashList+ data={urls}+ renderItem={({ item, index }) => (+ <Galeria.Image index={index}>+ <Image source={{ uri: item }} style={styles.thumbnail} />+ </Galeria.Image>+ )}+ numColumns={3}+ estimatedItemSize={100}+ />+</Galeria>+```++Works with `expo-image`, `SolitoImage`, `react-native` Image, or any image++component.++Reference: [https://github.com/nandorojo/galeria](https://github.com/nandorojo/galeria)++### 8.7 Use Native Menus for Dropdowns and Context Menus++**Impact: HIGH (native accessibility, platform-consistent UX)**++Use native platform menus instead of custom JS implementations. Native menus++provide built-in accessibility, consistent platform UX, and better performance.++Use [zeego](https://zeego.dev) for cross-platform native menus.++**Incorrect: custom JS menu**++```tsx+import { useState } from 'react'+import { View, Pressable, Text } from 'react-native'++function MyMenu() {+ const [open, setOpen] = useState(false)++ return (+ <View>+ <Pressable onPress={() => setOpen(!open)}>+ <Text>Open Menu</Text>+ </Pressable>+ {open && (+ <View style={{ position: 'absolute', top: 40 }}>+ <Pressable onPress={() => console.log('edit')}>+ <Text>Edit</Text>+ </Pressable>+ <Pressable onPress={() => console.log('delete')}>+ <Text>Delete</Text>+ </Pressable>+ </View>+ )}+ </View>+ )+}+```++**Correct: native menu with zeego**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function MyMenu() {+ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Open Menu</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.Item key='edit' onSelect={() => console.log('edit')}>+ <DropdownMenu.ItemTitle>Edit</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Item+ key='delete'+ destructive+ onSelect={() => console.log('delete')}+ >+ <DropdownMenu.ItemTitle>Delete</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++**Context menu: long-press**++```tsx+import * as ContextMenu from 'zeego/context-menu'++function MyContextMenu() {+ return (+ <ContextMenu.Root>+ <ContextMenu.Trigger>+ <View style={{ padding: 20 }}>+ <Text>Long press me</Text>+ </View>+ </ContextMenu.Trigger>++ <ContextMenu.Content>+ <ContextMenu.Item key='copy' onSelect={() => console.log('copy')}>+ <ContextMenu.ItemTitle>Copy</ContextMenu.ItemTitle>+ </ContextMenu.Item>++ <ContextMenu.Item key='paste' onSelect={() => console.log('paste')}>+ <ContextMenu.ItemTitle>Paste</ContextMenu.ItemTitle>+ </ContextMenu.Item>+ </ContextMenu.Content>+ </ContextMenu.Root>+ )+}+```++**Checkbox items:**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function SettingsMenu() {+ const [notifications, setNotifications] = useState(true)++ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Settings</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.CheckboxItem+ key='notifications'+ value={notifications}+ onValueChange={() => setNotifications((prev) => !prev)}+ >+ <DropdownMenu.ItemIndicator />+ <DropdownMenu.ItemTitle>Notifications</DropdownMenu.ItemTitle>+ </DropdownMenu.CheckboxItem>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++**Submenus:**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function MenuWithSubmenu() {+ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Options</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.Item key='home' onSelect={() => console.log('home')}>+ <DropdownMenu.ItemTitle>Home</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Sub>+ <DropdownMenu.SubTrigger key='more'>+ <DropdownMenu.ItemTitle>More Options</DropdownMenu.ItemTitle>+ </DropdownMenu.SubTrigger>++ <DropdownMenu.SubContent>+ <DropdownMenu.Item key='settings'>+ <DropdownMenu.ItemTitle>Settings</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Item key='help'>+ <DropdownMenu.ItemTitle>Help</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </DropdownMenu.SubContent>+ </DropdownMenu.Sub>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++Reference: [https://zeego.dev/components/dropdown-menu](https://zeego.dev/components/dropdown-menu)++### 8.8 Use Native Modals Over JS-Based Bottom Sheets++**Impact: HIGH (native performance, gestures, accessibility)**++Use native `<Modal>` with `presentationStyle="formSheet"` or React Navigation++v7's native form sheet instead of JS-based bottom sheet libraries. Native modals++have built-in gestures, accessibility, and better performance. Rely on native UI++for low-level primitives.++**Incorrect: JS-based bottom sheet**++```tsx+import BottomSheet from 'custom-js-bottom-sheet'++function MyScreen() {+ const sheetRef = useRef<BottomSheet>(null)++ return (+ <View style={{ flex: 1 }}>+ <Button onPress={() => sheetRef.current?.expand()} title='Open' />+ <BottomSheet ref={sheetRef} snapPoints={['50%', '90%']}>+ <View>+ <Text>Sheet content</Text>+ </View>+ </BottomSheet>+ </View>+ )+}+```++**Correct: native Modal with formSheet**++```tsx+import { Modal, View, Text, Button } from 'react-native'++function MyScreen() {+ const [visible, setVisible] = useState(false)++ return (+ <View style={{ flex: 1 }}>+ <Button onPress={() => setVisible(true)} title='Open' />+ <Modal+ visible={visible}+ presentationStyle='formSheet'+ animationType='slide'+ onRequestClose={() => setVisible(false)}+ >+ <View>+ <Text>Sheet content</Text>+ </View>+ </Modal>+ </View>+ )+}+```++**Correct: React Navigation v7 native form sheet**++```tsx+// In your navigator+<Stack.Screen+ name='Details'+ component={DetailsScreen}+ options={{+ presentation: 'formSheet',+ sheetAllowedDetents: 'fitToContents',+ }}+/>+```++Native modals provide swipe-to-dismiss, proper keyboard avoidance, and++accessibility out of the box.++### 8.9 Use Pressable Instead of Touchable Components++**Impact: LOW (modern API, more flexible)**++Never use `TouchableOpacity` or `TouchableHighlight`. Use `Pressable` from+`react-native` or `react-native-gesture-handler` instead.++**Incorrect: legacy Touchable components**++```tsx+import { TouchableOpacity } from 'react-native'++function MyButton({ onPress }: { onPress: () => void }) {+ return (+ <TouchableOpacity onPress={onPress} activeOpacity={0.7}>+ <Text>Press me</Text>+ </TouchableOpacity>+ )+}+```++**Correct: Pressable**++```tsx+import { Pressable } from 'react-native'++function MyButton({ onPress }: { onPress: () => void }) {+ return (+ <Pressable onPress={onPress}>+ <Text>Press me</Text>+ </Pressable>+ )+}+```++**Correct: Pressable from gesture handler for lists**++```tsx+import { Pressable } from 'react-native-gesture-handler'++function ListItem({ onPress }: { onPress: () => void }) {+ return (+ <Pressable onPress={onPress}>+ <Text>Item</Text>+ </Pressable>+ )+}+```++Use `react-native-gesture-handler` Pressable inside scrollable lists for better+gesture coordination, as long as you are using the ScrollView from+`react-native-gesture-handler` as well.++**For animated press states (scale, opacity changes):** Use `GestureDetector`+with Reanimated shared values instead of Pressable's style callback. See rule+3.3 (Use GestureDetector for Animated Press States).++---++## 9. Design System++**Impact: MEDIUM**++Architecture patterns for building maintainable component+libraries.++### 9.1 Use Compound Components Over Polymorphic Children++**Impact: MEDIUM (flexible composition, clearer API)**++Don't create components that can accept a string if they aren't a text node. If++a component can receive a string child, it must be a dedicated `*Text`++component. For components like buttons, which can have both a View (or++Pressable) together with text, use compound components, such a `Button`,++`ButtonText`, and `ButtonIcon`.++**Incorrect: polymorphic children**++```tsx+import { Pressable, Text } from 'react-native'++type ButtonProps = {+ children: string | React.ReactNode+ icon?: React.ReactNode+}++function Button({ children, icon }: ButtonProps) {+ return (+ <Pressable>+ {icon}+ {typeof children === 'string' ? <Text>{children}</Text> : children}+ </Pressable>+ )+}++// Usage is ambiguous+<Button icon={<Icon />}>Save</Button>+<Button><CustomText>Save</CustomText></Button>+```++**Correct: compound components**++```tsx+import { Pressable, Text } from 'react-native'++function Button({ children }: { children: React.ReactNode }) {+ return <Pressable>{children}</Pressable>+}++function ButtonText({ children }: { children: React.ReactNode }) {+ return <Text>{children}</Text>+}++function ButtonIcon({ children }: { children: React.ReactNode }) {+ return <>{children}</>+}++// Usage is explicit and composable+<Button>+ <ButtonIcon><SaveIcon /></ButtonIcon>+ <ButtonText>Save</ButtonText>+</Button>++<Button>+ <ButtonText>Cancel</ButtonText>+</Button>+```++---++## 10. Monorepo++**Impact: LOW**++Dependency management and native module configuration in+monorepos.++### 10.1 Install Native Dependencies in App Directory++**Impact: CRITICAL (required for autolinking to work)**++In a monorepo, packages with native code must be installed in the native app's++directory directly. Autolinking only scans the app's `node_modules`—it won't++find native dependencies installed in other packages.++**Incorrect: native dep in shared package only**++```typescript+packages/+ ui/+ package.json # has react-native-reanimated+ app/+ package.json # missing react-native-reanimated+```++Autolinking fails—native code not linked.++**Correct: native dep in app directory**++```json+// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}+```++Even if the shared package uses the native dependency, the app must also list it++for autolinking to detect and link the native code.++### 10.2 Use Single Dependency Versions Across Monorepo++**Impact: MEDIUM (avoids duplicate bundles, version conflicts)**++Use a single version of each dependency across all packages in your monorepo.++Prefer exact versions over ranges. Multiple versions cause duplicate code in++bundles, runtime conflicts, and inconsistent behavior across packages.++Use a tool like syncpack to enforce this. As a last resort, use yarn resolutions++or npm overrides.++**Incorrect: version ranges, multiple versions**++```json+// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "^3.0.0"+ }+}++// packages/ui/package.json+{+ "dependencies": {+ "react-native-reanimated": "^3.5.0"+ }+}+```++**Correct: exact versions, single source of truth**++```json+// package.json (root)+{+ "pnpm": {+ "overrides": {+ "react-native-reanimated": "3.16.1"+ }+ }+}++// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}++// packages/ui/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}+```++Use your package manager's override/resolution feature to enforce versions at++the root. When adding dependencies, specify exact versions without `^` or `~`.++---++## 11. Third-Party Dependencies++**Impact: LOW**++Wrapping and re-exporting third-party dependencies for+maintainability.++### 11.1 Import from Design System Folder++**Impact: LOW (enables global changes and easy refactoring)**++Re-export dependencies from a design system folder. App code imports from there,++not directly from packages. This enables global changes and easy refactoring.++**Incorrect: imports directly from package**++```tsx+import { View, Text } from 'react-native'+import { Button } from '@ui/button'++function Profile() {+ return (+ <View>+ <Text>Hello</Text>+ <Button>Save</Button>+ </View>+ )+}+```++**Correct: imports from design system**++```tsx+import { View } from '@/components/view'+import { Text } from '@/components/text'+import { Button } from '@/components/button'++function Profile() {+ return (+ <View>+ <Text>Hello</Text>+ <Button>Save</Button>+ </View>+ )+}+```++Start by simply re-exporting. Customize later without changing app code.++---++## 12. JavaScript++**Impact: LOW**++Micro-optimizations like hoisting expensive object creation.++### 12.1 Hoist Intl Formatter Creation++**Impact: LOW-MEDIUM (avoids expensive object recreation)**++Don't create `Intl.DateTimeFormat`, `Intl.NumberFormat`, or++`Intl.RelativeTimeFormat` inside render or loops. These are expensive to++instantiate. Hoist to module scope when the locale/options are static.++**Incorrect: new formatter every render**++```tsx+function Price({ amount }: { amount: number }) {+ const formatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ })+ return <Text>{formatter.format(amount)}</Text>+}+```++**Correct: hoisted to module scope**++```tsx+const currencyFormatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+})++function Price({ amount }: { amount: number }) {+ return <Text>{currencyFormatter.format(amount)}</Text>+}+```++**For dynamic locales, memoize:**++```tsx+const dateFormatter = useMemo(+ () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }),+ [locale]+)+```++**Common formatters to hoist:**++```tsx+// Module-level formatters+const dateFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' })+const timeFormatter = new Intl.DateTimeFormat('en-US', { timeStyle: 'short' })+const percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' })+const relativeFormatter = new Intl.RelativeTimeFormat('en-US', {+ numeric: 'auto',+})+```++Creating `Intl` objects is significantly more expensive than `RegExp` or plain++objects—each instantiation parses locale data and builds internal lookup tables.++---++## 13. Fonts++**Impact: LOW**++Native font loading for improved performance.++### 13.1 Load fonts natively at build time++**Impact: LOW (fonts available at launch, no async loading)**++Use the `expo-font` config plugin to embed fonts at build time instead of++`useFonts` or `Font.loadAsync`. Embedded fonts are more efficient.++[Expo Font Documentation](https://docs.expo.dev/versions/latest/sdk/font/)++**Incorrect: async font loading**++```tsx+import { useFonts } from 'expo-font'+import { Text, View } from 'react-native'++function App() {+ const [fontsLoaded] = useFonts({+ 'Geist-Bold': require('./assets/fonts/Geist-Bold.otf'),+ })++ if (!fontsLoaded) {+ return null+ }++ return (+ <View>+ <Text style={{ fontFamily: 'Geist-Bold' }}>Hello</Text>+ </View>+ )+}+```++**Correct: config plugin, fonts embedded at build**++```tsx+import { Text, View } from 'react-native'++function App() {+ // No loading state needed—font is already available+ return (+ <View>+ <Text style={{ fontFamily: 'Geist-Bold' }}>Hello</Text>+ </View>+ )+}+```++After adding fonts to the config plugin, run `npx expo prebuild` and rebuild the++native app.++---++## References++1. [https://react.dev](https://react.dev)+2. [https://reactnative.dev](https://reactnative.dev)+3. [https://docs.swmansion.com/react-native-reanimated](https://docs.swmansion.com/react-native-reanimated)+4. [https://docs.swmansion.com/react-native-gesture-handler](https://docs.swmansion.com/react-native-gesture-handler)+5. [https://docs.expo.dev](https://docs.expo.dev)+6. [https://legendapp.com/open-source/legend-list](https://legendapp.com/open-source/legend-list)+7. [https://github.com/nandorojo/galeria](https://github.com/nandorojo/galeria)+8. [https://zeego.dev](https://zeego.dev)diff --git a/.agents/skills/vercel-react-native-skills/SKILL.md b/.agents/skills/vercel-react-native-skills/SKILL.mdnew file mode 100644index 000000000..2f660997a--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/SKILL.md@@ -0,0 +1,115 @@+---+name: vercel-react-native-skills+description:+ React Native and Expo best practices for building performant mobile apps. Use+ when building React Native components, optimizing list performance,+ implementing animations, or working with native modules. Triggers on tasks+ involving React Native, Expo, mobile performance, or native platform APIs.+license: MIT+metadata:+ author: vercel+ version: '1.0.0'+---++# React Native Skills++Comprehensive best practices for React Native and Expo applications. Contains+rules across multiple categories covering performance, animations, UI patterns,+and platform-specific optimizations.++## When to Apply++Reference these guidelines when:++- Building React Native or Expo apps+- Optimizing list and scroll performance+- Implementing animations with Reanimated+- Working with images and media+- Configuring native modules or fonts+- Structuring monorepo projects with native dependencies++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+| -------- | ---------------- | -------- | -------------------- |+| 1 | List Performance | CRITICAL | `list-performance-` |+| 2 | Animation | HIGH | `animation-` |+| 3 | UI Patterns | HIGH | `ui-` |+| 4 | State Management | MEDIUM | `react-state-` |+| 5 | Rendering | MEDIUM | `rendering-` |+| 6 | Monorepo | MEDIUM | `monorepo-` |+| 7 | Configuration | LOW | `fonts-`, `imports-` |++## Quick Reference++### 1. List Performance (CRITICAL)++- `list-performance-virtualize` - Use FlashList for large lists+- `list-performance-item-memo` - Memoize list item components+- `list-performance-callbacks` - Stabilize callback references+- `list-performance-inline-objects` - Avoid inline style objects+- `list-performance-function-references` - Extract functions outside render+- `list-performance-images` - Optimize images in lists+- `list-performance-item-expensive` - Move expensive work outside items++### 2. Animation (HIGH)++- `animation-gpu-properties` - Animate only transform and opacity+- `animation-derived-value` - Use useDerivedValue for computed animations+- `animation-gesture-detector-press` - Use Gesture.Tap instead of Pressable++### 3. UI Patterns (HIGH)++- `ui-expo-image` - Use expo-image for all images+- `ui-image-gallery` - Use Galeria for image lightboxes+- `ui-pressable` - Use Pressable over TouchableOpacity+- `ui-safe-area-scroll` - Handle safe areas in ScrollViews+- `ui-scrollview-content-inset` - Use contentInset for headers+- `ui-menus` - Use native context menus+- `ui-native-modals` - Use native modals when possible+- `ui-measure-views` - Use onLayout, not measure()+- `ui-styling` - Use StyleSheet.create or Nativewind++### 4. State Management (MEDIUM)++- `react-state-minimize` - Minimize state subscriptions+- `react-state-dispatcher` - Use dispatcher pattern for callbacks+- `react-state-fallback` - Show fallback on first render+- `react-compiler-destructure-functions` - Destructure for React Compiler+- `react-compiler-reanimated-shared-values` - Handle shared values with compiler++### 5. Rendering (MEDIUM)++- `rendering-text-in-text-component` - Wrap text in Text components+- `rendering-no-falsy-and` - Avoid falsy && for conditional rendering++### 6. Monorepo (MEDIUM)++- `monorepo-native-deps-in-app` - Keep native dependencies in app package+- `monorepo-single-dependency-versions` - Use single versions across packages++### 7. Configuration (LOW)++- `fonts-config-plugin` - Use config plugins for custom fonts+- `imports-design-system-folder` - Organize design system imports+- `js-hoist-intl` - Hoist Intl object creation++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/list-performance-virtualize.md+rules/animation-gpu-properties.md+```++Each rule file contains:++- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-react-native-skills/rules/animation-derived-value.md b/.agents/skills/vercel-react-native-skills/rules/animation-derived-value.mdnew file mode 100644index 000000000..310928a95--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/animation-derived-value.md@@ -0,0 +1,53 @@+---+title: Prefer useDerivedValue Over useAnimatedReaction+impact: MEDIUM+impactDescription: cleaner code, automatic dependency tracking+tags: animation, reanimated, derived-value+---++## Prefer useDerivedValue Over useAnimatedReaction++When deriving a shared value from another, use `useDerivedValue` instead of+`useAnimatedReaction`. Derived values are declarative, automatically track+dependencies, and return a value you can use directly. Animated reactions are+for side effects, not derivations.++**Incorrect (useAnimatedReaction for derivation):**++```tsx+import { useSharedValue, useAnimatedReaction } from 'react-native-reanimated'++function MyComponent() {+ const progress = useSharedValue(0)+ const opacity = useSharedValue(1)++ useAnimatedReaction(+ () => progress.value,+ (current) => {+ opacity.value = 1 - current+ }+ )++ // ...+}+```++**Correct (useDerivedValue):**++```tsx+import { useSharedValue, useDerivedValue } from 'react-native-reanimated'++function MyComponent() {+ const progress = useSharedValue(0)++ const opacity = useDerivedValue(() => 1 - progress.get())++ // ...+}+```++Use `useAnimatedReaction` only for side effects that don't produce a value+(e.g., triggering haptics, logging, calling `runOnJS`).++Reference:+[Reanimated useDerivedValue](https://docs.swmansion.com/react-native-reanimated/docs/core/useDerivedValue)diff --git a/.agents/skills/vercel-react-native-skills/rules/animation-gesture-detector-press.md b/.agents/skills/vercel-react-native-skills/rules/animation-gesture-detector-press.mdnew file mode 100644index 000000000..87c678270--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/animation-gesture-detector-press.md@@ -0,0 +1,95 @@+---+title: Use GestureDetector for Animated Press States+impact: MEDIUM+impactDescription: UI thread animations, smoother press feedback+tags: animation, gestures, press, reanimated+---++## Use GestureDetector for Animated Press States++For animated press states (scale, opacity on press), use `GestureDetector` with+`Gesture.Tap()` and shared values instead of Pressable's+`onPressIn`/`onPressOut`. Gesture callbacks run on the UI thread as worklets—no+JS thread round-trip for press animations.++**Incorrect (Pressable with JS thread callbacks):**++```tsx+import { Pressable } from 'react-native'+import Animated, {+ useSharedValue,+ useAnimatedStyle,+ withTiming,+} from 'react-native-reanimated'++function AnimatedButton({ onPress }: { onPress: () => void }) {+ const scale = useSharedValue(1)++ const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: scale.value }],+ }))++ return (+ <Pressable+ onPress={onPress}+ onPressIn={() => (scale.value = withTiming(0.95))}+ onPressOut={() => (scale.value = withTiming(1))}+ >+ <Animated.View style={animatedStyle}>+ <Text>Press me</Text>+ </Animated.View>+ </Pressable>+ )+}+```++**Correct (GestureDetector with UI thread worklets):**++```tsx+import { Gesture, GestureDetector } from 'react-native-gesture-handler'+import Animated, {+ useSharedValue,+ useAnimatedStyle,+ withTiming,+ interpolate,+ runOnJS,+} from 'react-native-reanimated'++function AnimatedButton({ onPress }: { onPress: () => void }) {+ // Store the press STATE (0 = not pressed, 1 = pressed)+ const pressed = useSharedValue(0)++ const tap = Gesture.Tap()+ .onBegin(() => {+ pressed.set(withTiming(1))+ })+ .onFinalize(() => {+ pressed.set(withTiming(0))+ })+ .onEnd(() => {+ runOnJS(onPress)()+ })++ // Derive visual values from the state+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { scale: interpolate(withTiming(pressed.get()), [0, 1], [1, 0.95]) },+ ],+ }))++ return (+ <GestureDetector gesture={tap}>+ <Animated.View style={animatedStyle}>+ <Text>Press me</Text>+ </Animated.View>+ </GestureDetector>+ )+}+```++Store the press **state** (0 or 1), then derive the scale via `interpolate`.+This keeps the shared value as ground truth. Use `runOnJS` to call JS functions+from worklets. Use `.set()` and `.get()` for React Compiler compatibility.++Reference:+[Gesture Handler Tap Gesture](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture)diff --git a/.agents/skills/vercel-react-native-skills/rules/animation-gpu-properties.md b/.agents/skills/vercel-react-native-skills/rules/animation-gpu-properties.mdnew file mode 100644index 000000000..5fda09558--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/animation-gpu-properties.md@@ -0,0 +1,65 @@+---+title: Animate Transform and Opacity Instead of Layout Properties+impact: HIGH+impactDescription: GPU-accelerated animations, no layout recalculation+tags: animation, performance, reanimated, transform, opacity+---++## Animate Transform and Opacity Instead of Layout Properties++Avoid animating `width`, `height`, `top`, `left`, `margin`, or `padding`. These trigger layout recalculation on every frame. Instead, use `transform` (scale, translate) and `opacity` which run on the GPU without triggering layout.++**Incorrect (animates height, triggers layout every frame):**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function CollapsiblePanel({ expanded }: { expanded: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ height: withTiming(expanded ? 200 : 0), // triggers layout on every frame+ overflow: 'hidden',+ }))++ return <Animated.View style={animatedStyle}>{children}</Animated.View>+}+```++**Correct (animates scaleY, GPU-accelerated):**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function CollapsiblePanel({ expanded }: { expanded: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { scaleY: withTiming(expanded ? 1 : 0) },+ ],+ opacity: withTiming(expanded ? 1 : 0),+ }))++ return (+ <Animated.View style={[{ height: 200, transformOrigin: 'top' }, animatedStyle]}>+ {children}+ </Animated.View>+ )+}+```++**Correct (animates translateY for slide animations):**++```tsx+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'++function SlideIn({ visible }: { visible: boolean }) {+ const animatedStyle = useAnimatedStyle(() => ({+ transform: [+ { translateY: withTiming(visible ? 0 : 100) },+ ],+ opacity: withTiming(visible ? 1 : 0),+ }))++ return <Animated.View style={animatedStyle}>{children}</Animated.View>+}+```++GPU-accelerated properties: `transform` (translate, scale, rotate), `opacity`. Everything else triggers layout.diff --git a/.agents/skills/vercel-react-native-skills/rules/design-system-compound-components.md b/.agents/skills/vercel-react-native-skills/rules/design-system-compound-components.mdnew file mode 100644index 000000000..d8239ee1f--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/design-system-compound-components.md@@ -0,0 +1,66 @@+---+title: Use Compound Components Over Polymorphic Children+impact: MEDIUM+impactDescription: flexible composition, clearer API+tags: design-system, components, composition+---++## Use Compound Components Over Polymorphic Children++Don't create components that can accept a string if they aren't a text node. If+a component can receive a string child, it must be a dedicated `*Text`+component. For components like buttons, which can have both a View (or+Pressable) together with text, use compound components, such a `Button`,+`ButtonText`, and `ButtonIcon`.++**Incorrect (polymorphic children):**++```tsx+import { Pressable, Text } from 'react-native'++type ButtonProps = {+ children: string | React.ReactNode+ icon?: React.ReactNode+}++function Button({ children, icon }: ButtonProps) {+ return (+ <Pressable>+ {icon}+ {typeof children === 'string' ? <Text>{children}</Text> : children}+ </Pressable>+ )+}++// Usage is ambiguous+<Button icon={<Icon />}>Save</Button>+<Button><CustomText>Save</CustomText></Button>+```++**Correct (compound components):**++```tsx+import { Pressable, Text } from 'react-native'++function Button({ children }: { children: React.ReactNode }) {+ return <Pressable>{children}</Pressable>+}++function ButtonText({ children }: { children: React.ReactNode }) {+ return <Text>{children}</Text>+}++function ButtonIcon({ children }: { children: React.ReactNode }) {+ return <>{children}</>+}++// Usage is explicit and composable+<Button>+ <ButtonIcon><SaveIcon /></ButtonIcon>+ <ButtonText>Save</ButtonText>+</Button>++<Button>+ <ButtonText>Cancel</ButtonText>+</Button>+```diff --git a/.agents/skills/vercel-react-native-skills/rules/fonts-config-plugin.md b/.agents/skills/vercel-react-native-skills/rules/fonts-config-plugin.mdnew file mode 100644index 000000000..39aa01477--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/fonts-config-plugin.md@@ -0,0 +1,71 @@+---+title: Load fonts natively at build time+impact: LOW+impactDescription: fonts available at launch, no async loading+tags: fonts, expo, performance, config-plugin+---++## Use Expo Config Plugin for Font Loading++Use the `expo-font` config plugin to embed fonts at build time instead of+`useFonts` or `Font.loadAsync`. Embedded fonts are more efficient.++**Incorrect (async font loading):**++```tsx+import { useFonts } from 'expo-font'+import { Text, View } from 'react-native'++function App() {+ const [fontsLoaded] = useFonts({+ 'Geist-Bold': require('./assets/fonts/Geist-Bold.otf'),+ })++ if (!fontsLoaded) {+ return null+ }++ return (+ <View>+ <Text style={{ fontFamily: 'Geist-Bold' }}>Hello</Text>+ </View>+ )+}+```++**Correct (config plugin, fonts embedded at build):**++```json+// app.json+{+ "expo": {+ "plugins": [+ [+ "expo-font",+ {+ "fonts": ["./assets/fonts/Geist-Bold.otf"]+ }+ ]+ ]+ }+}+```++```tsx+import { Text, View } from 'react-native'++function App() {+ // No loading state needed—font is already available+ return (+ <View>+ <Text style={{ fontFamily: 'Geist-Bold' }}>Hello</Text>+ </View>+ )+}+```++After adding fonts to the config plugin, run `npx expo prebuild` and rebuild the+native app.++Reference:+[Expo Font Documentation](https://docs.expo.dev/versions/latest/sdk/font/)diff --git a/.agents/skills/vercel-react-native-skills/rules/imports-design-system-folder.md b/.agents/skills/vercel-react-native-skills/rules/imports-design-system-folder.mdnew file mode 100644index 000000000..8466dcb25--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/imports-design-system-folder.md@@ -0,0 +1,68 @@+---+title: Import from Design System Folder+impact: LOW+impactDescription: enables global changes and easy refactoring+tags: imports, architecture, design-system+---++## Import from Design System Folder++Re-export dependencies from a design system folder. App code imports from there,+not directly from packages. This enables global changes and easy refactoring.++**Incorrect (imports directly from package):**++```tsx+import { View, Text } from 'react-native'+import { Button } from '@ui/button'++function Profile() {+ return (+ <View>+ <Text>Hello</Text>+ <Button>Save</Button>+ </View>+ )+}+```++**Correct (imports from design system):**++```tsx+// components/view.tsx+import { View as RNView } from 'react-native'++// ideal: pick the props you will actually use to control implementation+export function View(+ props: Pick<React.ComponentProps<typeof RNView>, 'style' | 'children'>+) {+ return <RNView {...props} />+}+```++```tsx+// components/text.tsx+export { Text } from 'react-native'+```++```tsx+// components/button.tsx+export { Button } from '@ui/button'+```++```tsx+import { View } from '@/components/view'+import { Text } from '@/components/text'+import { Button } from '@/components/button'++function Profile() {+ return (+ <View>+ <Text>Hello</Text>+ <Button>Save</Button>+ </View>+ )+}+```++Start by simply re-exporting. Customize later without changing app code.diff --git a/.agents/skills/vercel-react-native-skills/rules/js-hoist-intl.md b/.agents/skills/vercel-react-native-skills/rules/js-hoist-intl.mdnew file mode 100644index 000000000..9af1c354c--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/js-hoist-intl.md@@ -0,0 +1,61 @@+---+title: Hoist Intl Formatter Creation+impact: LOW-MEDIUM+impactDescription: avoids expensive object recreation+tags: javascript, intl, optimization, memoization+---++## Hoist Intl Formatter Creation++Don't create `Intl.DateTimeFormat`, `Intl.NumberFormat`, or+`Intl.RelativeTimeFormat` inside render or loops. These are expensive to+instantiate. Hoist to module scope when the locale/options are static.++**Incorrect (new formatter every render):**++```tsx+function Price({ amount }: { amount: number }) {+ const formatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ })+ return <Text>{formatter.format(amount)}</Text>+}+```++**Correct (hoisted to module scope):**++```tsx+const currencyFormatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+})++function Price({ amount }: { amount: number }) {+ return <Text>{currencyFormatter.format(amount)}</Text>+}+```++**For dynamic locales, memoize:**++```tsx+const dateFormatter = useMemo(+ () => new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }),+ [locale]+)+```++**Common formatters to hoist:**++```tsx+// Module-level formatters+const dateFormatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' })+const timeFormatter = new Intl.DateTimeFormat('en-US', { timeStyle: 'short' })+const percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' })+const relativeFormatter = new Intl.RelativeTimeFormat('en-US', {+ numeric: 'auto',+})+```++Creating `Intl` objects is significantly more expensive than `RegExp` or plain+objects—each instantiation parses locale data and builds internal lookup tables.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-callbacks.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-callbacks.mdnew file mode 100644index 000000000..a0b3913ff--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-callbacks.md@@ -0,0 +1,44 @@+---+title: Hoist callbacks to the root of lists+impact: MEDIUM+impactDescription: Fewer re-renders and faster lists+tags: tag1, tag2+---++## List performance callbacks++**Impact: HIGH (Fewer re-renders and faster lists)**++When passing callback functions to list items, create a single instance of the+callback at the root of the list. Items should then call it with a unique+identifier.++**Incorrect (creates a new callback on each render):**++```typescript+return (+ <LegendList+ renderItem={({ item }) => {+ // bad: creates a new callback on each render+ const onPress = () => handlePress(item.id)+ return <Item key={item.id} item={item} onPress={onPress} />+ }}+ />+)+```++**Correct (a single function instance passed to each item):**++```typescript+const onPress = useCallback(() => handlePress(item.id), [handlePress, item.id])++return (+ <LegendList+ renderItem={({ item }) => (+ <Item key={item.id} item={item} onPress={onPress} />+ )}+ />+)+```++Reference: [Link to documentation or resource](https://example.com)diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-function-references.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-function-references.mdnew file mode 100644index 000000000..9721929b2--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-function-references.md@@ -0,0 +1,132 @@+---+title: Optimize List Performance with Stable Object References+impact: CRITICAL+impactDescription: virtualization relies on reference stability+tags: lists, performance, flatlist, virtualization+---++## Optimize List Performance with Stable Object References++Don't map or filter data before passing to virtualized lists. Virtualization+relies on object reference stability to know what changed—new references cause+full re-renders of all visible items. Attempt to prevent frequent renders at the+list-parent level.++Where needed, use context selectors within list items.++**Incorrect (creates new object references on every keystroke):**++```tsx+function DomainSearch() {+ const { keyword, setKeyword } = useKeywordZustandState()+ const { data: tlds } = useTlds()++ // Bad: creates new objects on every render, reparenting the entire list on every keystroke+ const domains = tlds.map((tld) => ({+ domain: `${keyword}.${tld.name}`,+ tld: tld.name,+ price: tld.price,+ }))++ return (+ <>+ <TextInput value={keyword} onChangeText={setKeyword} />+ <LegendList+ data={domains}+ renderItem={({ item }) => <DomainItem item={item} keyword={keyword} />}+ />+ </>+ )+}+```++**Correct (stable references, transform inside items):**++```tsx+const renderItem = ({ item }) => <DomainItem tld={item} />++function DomainSearch() {+ const { data: tlds } = useTlds()++ return (+ <LegendList+ // good: as long as the data is stable, LegendList will not re-render the entire list+ data={tlds}+ renderItem={renderItem}+ />+ )+}++function DomainItem({ tld }: { tld: Tld }) {+ // good: transform within items, and don't pass the dynamic data as a prop+ // good: use a selector function from zustand to receive a stable string back+ const domain = useKeywordZustandState((s) => s.keyword + '.' + tld.name)+ return <Text>{domain}</Text>+}+```++**Updating parent array reference:**++Creating a new array instance can be okay, as long as its inner object+references are stable. For instance, if you sort a list of objects:++```tsx+// good: creates a new array instance without mutating the inner objects+// good: parent array reference is unaffected by typing and updating "keyword"+const sortedTlds = tlds.toSorted((a, b) => a.name.localeCompare(b.name))++return <LegendList data={sortedTlds} renderItem={renderItem} />+```++Even though this creates a new array instance `sortedTlds`, the inner object+references are stable.++**With zustand for dynamic data (avoids parent re-renders):**++```tsx+const useSearchStore = create<{ keyword: string }>(() => ({ keyword: '' }))++function DomainSearch() {+ const { data: tlds } = useTlds()++ return (+ <>+ <SearchInput />+ <LegendList+ data={tlds}+ // if you aren't using React Compiler, wrap renderItem with useCallback+ renderItem={({ item }) => <DomainItem tld={item} />}+ />+ </>+ )+}++function DomainItem({ tld }: { tld: Tld }) {+ // Select only what you need—component only re-renders when keyword changes+ const keyword = useSearchStore((s) => s.keyword)+ const domain = `${keyword}.${tld.name}`+ return <Text>{domain}</Text>+}+```++Virtualization can now skip items that haven't changed when typing. Only visible+items (~20) re-render on keystroke, rather than the parent.++**Deriving state within list items based on parent data (avoids parent+re-renders):**++For components where the data is conditional based on the parent state, this+pattern is even more important. For example, if you are checking if an item is+favorited, toggling favorites only re-renders one component if the item itself+is in charge of accessing the state rather than the parent:++```tsx+function DomainItemFavoriteButton({ tld }: { tld: Tld }) {+ const isFavorited = useFavoritesStore((s) => s.favorites.has(tld.id))+ return <TldFavoriteButton isFavorited={isFavorited} />+}+```++Note: if you're using the React Compiler, you can read React Context values+directly within list items. Although this is slightly slower than using a+Zustand selector in most cases, the effect may be negligible.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-images.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-images.mdnew file mode 100644index 000000000..75a3bafc8--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-images.md@@ -0,0 +1,53 @@+---+title: Use Compressed Images in Lists+impact: HIGH+impactDescription: faster load times, less memory+tags: lists, images, performance, optimization+---++## Use Compressed Images in Lists++Always load compressed, appropriately-sized images in lists. Full-resolution+images consume excessive memory and cause scroll jank. Request thumbnails from+your server or use an image CDN with resize parameters.++**Incorrect (full-resolution images):**++```tsx+function ProductItem({ product }: { product: Product }) {+ return (+ <View>+ {/* 4000x3000 image loaded for a 100x100 thumbnail */}+ <Image+ source={{ uri: product.imageUrl }}+ style={{ width: 100, height: 100 }}+ />+ <Text>{product.name}</Text>+ </View>+ )+}+```++**Correct (request appropriately-sized image):**++```tsx+function ProductItem({ product }: { product: Product }) {+ // Request a 200x200 image (2x for retina)+ const thumbnailUrl = `${product.imageUrl}?w=200&h=200&fit=cover`++ return (+ <View>+ <Image+ source={{ uri: thumbnailUrl }}+ style={{ width: 100, height: 100 }}+ contentFit='cover'+ />+ <Text>{product.name}</Text>+ </View>+ )+}+```++Use an optimized image component with built-in caching and placeholder support,+such as `expo-image` or `SolitoImage` (which uses `expo-image` under the hood).+Request images at 2x the display size for retina screens.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-inline-objects.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-inline-objects.mdnew file mode 100644index 000000000..d5b6514a6--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-inline-objects.md@@ -0,0 +1,97 @@+---+title: Avoid Inline Objects in renderItem+impact: HIGH+impactDescription: prevents unnecessary re-renders of memoized list items+tags: lists, performance, flatlist, virtualization, memo+---++## Avoid Inline Objects in renderItem++Don't create new objects inside `renderItem` to pass as props. Inline objects+create new references on every render, breaking memoization. Pass primitive+values directly from `item` instead.++**Incorrect (inline object breaks memoization):**++```tsx+function UserList({ users }: { users: User[] }) {+ return (+ <LegendList+ data={users}+ renderItem={({ item }) => (+ <UserRow+ // Bad: new object on every render+ user={{ id: item.id, name: item.name, avatar: item.avatar }}+ />+ )}+ />+ )+}+```++**Incorrect (inline style object):**++```tsx+renderItem={({ item }) => (+ <UserRow+ name={item.name}+ // Bad: new style object on every render+ style={{ backgroundColor: item.isActive ? 'green' : 'gray' }}+ />+)}+```++**Correct (pass item directly or primitives):**++```tsx+function UserList({ users }: { users: User[] }) {+ return (+ <LegendList+ data={users}+ renderItem={({ item }) => (+ // Good: pass the item directly+ <UserRow user={item} />+ )}+ />+ )+}+```++**Correct (pass primitives, derive inside child):**++```tsx+renderItem={({ item }) => (+ <UserRow+ id={item.id}+ name={item.name}+ isActive={item.isActive}+ />+)}++const UserRow = memo(function UserRow({ id, name, isActive }: Props) {+ // Good: derive style inside memoized component+ const backgroundColor = isActive ? 'green' : 'gray'+ return <View style={[styles.row, { backgroundColor }]}>{/* ... */}</View>+})+```++**Correct (hoist static styles in module scope):**++```tsx+const activeStyle = { backgroundColor: 'green' }+const inactiveStyle = { backgroundColor: 'gray' }++renderItem={({ item }) => (+ <UserRow+ name={item.name}+ // Good: stable references+ style={item.isActive ? activeStyle : inactiveStyle}+ />+)}+```++Passing primitives or stable references allows `memo()` to skip re-renders when+the actual values haven't changed.++**Note:** If you have the React Compiler enabled, it handles memoization+automatically and these manual optimizations become less critical.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-item-expensive.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-item-expensive.mdnew file mode 100644index 000000000..f617a76d4--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-item-expensive.md@@ -0,0 +1,94 @@+---+title: Keep List Items Lightweight+impact: HIGH+impactDescription: reduces render time for visible items during scroll+tags: lists, performance, virtualization, hooks+---++## Keep List Items Lightweight++List items should be as inexpensive as possible to render. Minimize hooks, avoid+queries, and limit React Context access. Virtualized lists render many items+during scroll—expensive items cause jank.++**Incorrect (heavy list item):**++```tsx+function ProductRow({ id }: { id: string }) {+ // Bad: query inside list item+ const { data: product } = useQuery(['product', id], () => fetchProduct(id))+ // Bad: multiple context accesses+ const theme = useContext(ThemeContext)+ const user = useContext(UserContext)+ const cart = useContext(CartContext)+ // Bad: expensive computation+ const recommendations = useMemo(+ () => computeRecommendations(product),+ [product]+ )++ return <View>{/* ... */}</View>+}+```++**Correct (lightweight list item):**++```tsx+function ProductRow({ name, price, imageUrl }: Props) {+ // Good: receives only primitives, minimal hooks+ return (+ <View>+ <Image source={{ uri: imageUrl }} />+ <Text>{name}</Text>+ <Text>{price}</Text>+ </View>+ )+}+```++**Move data fetching to parent:**++```tsx+// Parent fetches all data once+function ProductList() {+ const { data: products } = useQuery(['products'], fetchProducts)++ return (+ <LegendList+ data={products}+ renderItem={({ item }) => (+ <ProductRow name={item.name} price={item.price} imageUrl={item.image} />+ )}+ />+ )+}+```++**For shared values, use Zustand selectors instead of Context:**++```tsx+// Incorrect: Context causes re-render when any cart value changes+function ProductRow({ id, name }: Props) {+ const { items } = useContext(CartContext)+ const inCart = items.includes(id)+ // ...+}++// Correct: Zustand selector only re-renders when this specific value changes+function ProductRow({ id, name }: Props) {+ // use Set.has (created once at the root) instead of Array.includes()+ const inCart = useCartStore((s) => s.items.has(id))+ // ...+}+```++**Guidelines for list items:**++- No queries or data fetching+- No expensive computations (move to parent or memoize at parent level)+- Prefer Zustand selectors over React Context+- Minimize useState/useEffect hooks+- Pass pre-computed values as props++The goal: list items should be simple rendering functions that take props and+return JSX.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-item-memo.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-item-memo.mdnew file mode 100644index 000000000..634935e8e--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-item-memo.md@@ -0,0 +1,82 @@+---+title: Pass Primitives to List Items for Memoization+impact: HIGH+impactDescription: enables effective memo() comparison+tags: lists, performance, memo, primitives+---++## Pass Primitives to List Items for Memoization++When possible, pass only primitive values (strings, numbers, booleans) as props+to list item components. Primitives enable shallow comparison in `memo()` to+work correctly, skipping re-renders when values haven't changed.++**Incorrect (object prop requires deep comparison):**++```tsx+type User = { id: string; name: string; email: string; avatar: string }++const UserRow = memo(function UserRow({ user }: { user: User }) {+ // memo() compares user by reference, not value+ // If parent creates new user object, this re-renders even if data is same+ return <Text>{user.name}</Text>+})++renderItem={({ item }) => <UserRow user={item} />}+```++This can still be optimized, but it is harder to memoize properly.++**Correct (primitive props enable shallow comparison):**++```tsx+const UserRow = memo(function UserRow({+ id,+ name,+ email,+}: {+ id: string+ name: string+ email: string+}) {+ // memo() compares each primitive directly+ // Re-renders only if id, name, or email actually changed+ return <Text>{name}</Text>+})++renderItem={({ item }) => (+ <UserRow id={item.id} name={item.name} email={item.email} />+)}+```++**Pass only what you need:**++```tsx+// Incorrect: passing entire item when you only need name+<UserRow user={item} />++// Correct: pass only the fields the component uses+<UserRow name={item.name} avatarUrl={item.avatar} />+```++**For callbacks, hoist or use item ID:**++```tsx+// Incorrect: inline function creates new reference+<UserRow name={item.name} onPress={() => handlePress(item.id)} />++// Correct: pass ID, handle in child+<UserRow id={item.id} name={item.name} />++const UserRow = memo(function UserRow({ id, name }: Props) {+ const handlePress = useCallback(() => {+ // use id here+ }, [id])+ return <Pressable onPress={handlePress}><Text>{name}</Text></Pressable>+})+```++Primitive props make memoization predictable and effective.++**Note:** If you have the React Compiler enabled, you do not need to use+`memo()` or `useCallback()`, but the object references still apply.diff --git a/.agents/skills/vercel-react-native-skills/rules/list-performance-virtualize.md b/.agents/skills/vercel-react-native-skills/rules/list-performance-virtualize.mdnew file mode 100644index 000000000..8a393ba1e--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/list-performance-virtualize.md@@ -0,0 +1,67 @@+---+title: Use a List Virtualizer for Any List+impact: HIGH+impactDescription: reduced memory, faster mounts+tags: lists, performance, virtualization, scrollview+---++## Use a List Virtualizer for Any List++Use a list virtualizer like LegendList or FlashList instead of ScrollView with+mapped children—even for short lists. Virtualizers only render visible items,+reducing memory usage and mount time. ScrollView renders all children upfront,+which gets expensive quickly.++**Incorrect (ScrollView renders all items at once):**++```tsx+function Feed({ items }: { items: Item[] }) {+ return (+ <ScrollView>+ {items.map((item) => (+ <ItemCard key={item.id} item={item} />+ ))}+ </ScrollView>+ )+}+// 50 items = 50 components mounted, even if only 10 visible+```++**Correct (virtualizer renders only visible items):**++```tsx+import { LegendList } from '@legendapp/list'++function Feed({ items }: { items: Item[] }) {+ return (+ <LegendList+ data={items}+ // if you aren't using React Compiler, wrap these with useCallback+ renderItem={({ item }) => <ItemCard item={item} />}+ keyExtractor={(item) => item.id}+ estimatedItemSize={80}+ />+ )+}+// Only ~10-15 visible items mounted at a time+```++**Alternative (FlashList):**++```tsx+import { FlashList } from '@shopify/flash-list'++function Feed({ items }: { items: Item[] }) {+ return (+ <FlashList+ data={items}+ // if you aren't using React Compiler, wrap these with useCallback+ renderItem={({ item }) => <ItemCard item={item} />}+ keyExtractor={(item) => item.id}+ />+ )+}+```++Benefits apply to any screen with scrollable content—profiles, settings, feeds,+search results. Default to virtualization.diff --git a/.agents/skills/vercel-react-native-skills/rules/monorepo-native-deps-in-app.md b/.agents/skills/vercel-react-native-skills/rules/monorepo-native-deps-in-app.mdnew file mode 100644index 000000000..ff85d7673--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/monorepo-native-deps-in-app.md@@ -0,0 +1,46 @@+---+title: Install Native Dependencies in App Directory+impact: CRITICAL+impactDescription: required for autolinking to work+tags: monorepo, native, autolinking, installation+---++## Install Native Dependencies in App Directory++In a monorepo, packages with native code must be installed in the native app's+directory directly. Autolinking only scans the app's `node_modules`—it won't+find native dependencies installed in other packages.++**Incorrect (native dep in shared package only):**++```+packages/+ ui/+ package.json # has react-native-reanimated+ app/+ package.json # missing react-native-reanimated+```++Autolinking fails—native code not linked.++**Correct (native dep in app directory):**++```+packages/+ ui/+ package.json # has react-native-reanimated+ app/+ package.json # also has react-native-reanimated+```++```json+// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}+```++Even if the shared package uses the native dependency, the app must also list it+for autolinking to detect and link the native code.diff --git a/.agents/skills/vercel-react-native-skills/rules/monorepo-single-dependency-versions.md b/.agents/skills/vercel-react-native-skills/rules/monorepo-single-dependency-versions.mdnew file mode 100644index 000000000..1087dfa51--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/monorepo-single-dependency-versions.md@@ -0,0 +1,63 @@+---+title: Use Single Dependency Versions Across Monorepo+impact: MEDIUM+impactDescription: avoids duplicate bundles, version conflicts+tags: monorepo, dependencies, installation+---++## Use Single Dependency Versions Across Monorepo++Use a single version of each dependency across all packages in your monorepo.+Prefer exact versions over ranges. Multiple versions cause duplicate code in+bundles, runtime conflicts, and inconsistent behavior across packages.++Use a tool like syncpack to enforce this. As a last resort, use yarn resolutions+or npm overrides.++**Incorrect (version ranges, multiple versions):**++```json+// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "^3.0.0"+ }+}++// packages/ui/package.json+{+ "dependencies": {+ "react-native-reanimated": "^3.5.0"+ }+}+```++**Correct (exact versions, single source of truth):**++```json+// package.json (root)+{+ "pnpm": {+ "overrides": {+ "react-native-reanimated": "3.16.1"+ }+ }+}++// packages/app/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}++// packages/ui/package.json+{+ "dependencies": {+ "react-native-reanimated": "3.16.1"+ }+}+```++Use your package manager's override/resolution feature to enforce versions at+the root. When adding dependencies, specify exact versions without `^` or `~`.diff --git a/.agents/skills/vercel-react-native-skills/rules/react-compiler-destructure-functions.md b/.agents/skills/vercel-react-native-skills/rules/react-compiler-destructure-functions.mdnew file mode 100644index 000000000..f76c25ac6--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/react-compiler-destructure-functions.md@@ -0,0 +1,50 @@+---+title: Destructure Functions Early in Render (React Compiler)+impact: HIGH+impactDescription: stable references, fewer re-renders+tags: rerender, hooks, performance, react-compiler+---++## Destructure Functions Early in Render++This rule is only applicable if you are using the React Compiler.++Destructure functions from hooks at the top of render scope. Never dot into+objects to call functions. Destructured functions are stable references; dotting+creates new references and breaks memoization.++**Incorrect (dotting into object):**++```tsx+import { useRouter } from 'expo-router'++function SaveButton(props) {+ const router = useRouter()++ // bad: react-compiler will key the cache on "props" and "router", which are objects that change each render+ const handlePress = () => {+ props.onSave()+ router.push('/success') // unstable reference+ }++ return <Button onPress={handlePress}>Save</Button>+}+```++**Correct (destructure early):**++```tsx+import { useRouter } from 'expo-router'++function SaveButton({ onSave }) {+ const { push } = useRouter()++ // good: react-compiler will key on push and onSave+ const handlePress = () => {+ onSave()+ push('/success') // stable reference+ }++ return <Button onPress={handlePress}>Save</Button>+}+```diff --git a/.agents/skills/vercel-react-native-skills/rules/react-compiler-reanimated-shared-values.md b/.agents/skills/vercel-react-native-skills/rules/react-compiler-reanimated-shared-values.mdnew file mode 100644index 000000000..0dcbaf47a--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/react-compiler-reanimated-shared-values.md@@ -0,0 +1,48 @@+---+title: Use .get() and .set() for Reanimated Shared Values (not .value)+impact: LOW+impactDescription: required for React Compiler compatibility+tags: reanimated, react-compiler, shared-values+---++## Use .get() and .set() for Shared Values with React Compiler++With React Compiler enabled, use `.get()` and `.set()` instead of reading or+writing `.value` directly on Reanimated shared values. The compiler can't track+property access—explicit methods ensure correct behavior.++**Incorrect (breaks with React Compiler):**++```tsx+import { useSharedValue } from 'react-native-reanimated'++function Counter() {+ const count = useSharedValue(0)++ const increment = () => {+ count.value = count.value + 1 // opts out of react compiler+ }++ return <Button onPress={increment} title={`Count: ${count.value}`} />+}+```++**Correct (React Compiler compatible):**++```tsx+import { useSharedValue } from 'react-native-reanimated'++function Counter() {+ const count = useSharedValue(0)++ const increment = () => {+ count.set(count.get() + 1)+ }++ return <Button onPress={increment} title={`Count: ${count.get()}`} />+}+```++See the+[Reanimated docs](https://docs.swmansion.com/react-native-reanimated/docs/core/useSharedValue/#react-compiler-support)+for more.diff --git a/.agents/skills/vercel-react-native-skills/rules/react-state-dispatcher.md b/.agents/skills/vercel-react-native-skills/rules/react-state-dispatcher.mdnew file mode 100644index 000000000..93e8b6db6--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/react-state-dispatcher.md@@ -0,0 +1,91 @@+---+title: useState Dispatch updaters for State That Depends on Current Value+impact: MEDIUM+impactDescription: avoids stale closures, prevents unnecessary re-renders+tags: state, hooks, useState, callbacks+---++## Use Dispatch Updaters for State That Depends on Current Value++When the next state depends on the current state, use a dispatch updater+(`setState(prev => ...)`) instead of reading the state variable directly in a+callback. This avoids stale closures and ensures you're comparing against the+latest value.++**Incorrect (reads state directly):**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ // size may be stale in this closure+ if (size?.width !== width || size?.height !== height) {+ setSize({ width, height })+ }+}+```++**Correct (dispatch updater):**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => {+ if (prev?.width === width && prev?.height === height) return prev+ return { width, height }+ })+}+```++Returning the previous value from the updater skips the re-render.++For primitive states, you don't need to compare values before firing a+re-render.++**Incorrect (unnecessary comparison for primitive state):**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => (prev === width ? prev : width))+}+```++**Correct (sets primitive state directly):**++```tsx+const [size, setSize] = useState<Size | undefined>(undefined)++const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize(width)+}+```++However, if the next state depends on the current state, you should still use a+dispatch updater.++**Incorrect (reads state directly from the callback):**++```tsx+const [count, setCount] = useState(0)++const onTap = () => {+ setCount(count + 1)+}+```++**Correct (dispatch updater):**++```tsx+const [count, setCount] = useState(0)++const onTap = () => {+ setCount((prev) => prev + 1)+}+```diff --git a/.agents/skills/vercel-react-native-skills/rules/react-state-fallback.md b/.agents/skills/vercel-react-native-skills/rules/react-state-fallback.mdnew file mode 100644index 000000000..204f34665--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/react-state-fallback.md@@ -0,0 +1,56 @@+---+title: Use fallback state instead of initialState+impact: MEDIUM+impactDescription: reactive fallbacks without syncing+tags: state, hooks, derived-state, props, initialState+---++## Use fallback state instead of initialState++Use `undefined` as initial state and nullish coalescing (`??`) to fall back to+parent or server values. State represents user intent only—`undefined` means+"user hasn't chosen yet." This enables reactive fallbacks that update when the+source changes, not just on initial render.++**Incorrect (syncs state, loses reactivity):**++```tsx+type Props = { fallbackEnabled: boolean }++function Toggle({ fallbackEnabled }: Props) {+ const [enabled, setEnabled] = useState(defaultEnabled)+ // If fallbackEnabled changes, state is stale+ // State mixes user intent with default value++ return <Switch value={enabled} onValueChange={setEnabled} />+}+```++**Correct (state is user intent, reactive fallback):**++```tsx+type Props = { fallbackEnabled: boolean }++function Toggle({ fallbackEnabled }: Props) {+ const [_enabled, setEnabled] = useState<boolean | undefined>(undefined)+ const enabled = _enabled ?? defaultEnabled+ // undefined = user hasn't touched it, falls back to prop+ // If defaultEnabled changes, component reflects it+ // Once user interacts, their choice persists++ return <Switch value={enabled} onValueChange={setEnabled} />+}+```++**With server data:**++```tsx+function ProfileForm({ data }: { data: User }) {+ const [_theme, setTheme] = useState<string | undefined>(undefined)+ const theme = _theme ?? data.theme+ // Shows server value until user overrides+ // Server refetch updates the fallback automatically++ return <ThemePicker value={theme} onChange={setTheme} />+}+```diff --git a/.agents/skills/vercel-react-native-skills/rules/react-state-minimize.md b/.agents/skills/vercel-react-native-skills/rules/react-state-minimize.mdnew file mode 100644index 000000000..64605b6c3--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/react-state-minimize.md@@ -0,0 +1,65 @@+---+title: Minimize State Variables and Derive Values+impact: MEDIUM+impactDescription: fewer re-renders, less state drift+tags: state, derived-state, hooks, optimization+---++## Minimize State Variables and Derive Values++Use the fewest state variables possible. If a value can be computed from existing state or props, derive it during render instead of storing it in state. Redundant state causes unnecessary re-renders and can drift out of sync.++**Incorrect (redundant state):**++```tsx+function Cart({ items }: { items: Item[] }) {+ const [total, setTotal] = useState(0)+ const [itemCount, setItemCount] = useState(0)++ useEffect(() => {+ setTotal(items.reduce((sum, item) => sum + item.price, 0))+ setItemCount(items.length)+ }, [items])++ return (+ <View>+ <Text>{itemCount} items</Text>+ <Text>Total: ${total}</Text>+ </View>+ )+}+```++**Correct (derived values):**++```tsx+function Cart({ items }: { items: Item[] }) {+ const total = items.reduce((sum, item) => sum + item.price, 0)+ const itemCount = items.length++ return (+ <View>+ <Text>{itemCount} items</Text>+ <Text>Total: ${total}</Text>+ </View>+ )+}+```++**Another example:**++```tsx+// Incorrect: storing both firstName, lastName, AND fullName+const [firstName, setFirstName] = useState('')+const [lastName, setLastName] = useState('')+const [fullName, setFullName] = useState('')++// Correct: derive fullName+const [firstName, setFirstName] = useState('')+const [lastName, setLastName] = useState('')+const fullName = `${firstName} ${lastName}`+```++State should be the minimal source of truth. Everything else is derived.++Reference: [Choosing the State Structure](https://react.dev/learn/choosing-the-state-structure)diff --git a/.agents/skills/vercel-react-native-skills/rules/rendering-no-falsy-and.md b/.agents/skills/vercel-react-native-skills/rules/rendering-no-falsy-and.mdnew file mode 100644index 000000000..30f05d3f8--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/rendering-no-falsy-and.md@@ -0,0 +1,74 @@+---+title: Never Use && with Potentially Falsy Values+impact: CRITICAL+impactDescription: prevents production crash+tags: rendering, conditional, jsx, crash+---++## Never Use && with Potentially Falsy Values++Never use `{value && <Component />}` when `value` could be an empty string or+`0`. These are falsy but JSX-renderable—React Native will try to render them as+text outside a `<Text>` component, causing a hard crash in production.++**Incorrect (crashes if count is 0 or name is ""):**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {name && <Text>{name}</Text>}+ {count && <Text>{count} items</Text>}+ </View>+ )+}+// If name="" or count=0, renders the falsy value → crash+```++**Correct (ternary with null):**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {name ? <Text>{name}</Text> : null}+ {count ? <Text>{count} items</Text> : null}+ </View>+ )+}+```++**Correct (explicit boolean coercion):**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ return (+ <View>+ {!!name && <Text>{name}</Text>}+ {!!count && <Text>{count} items</Text>}+ </View>+ )+}+```++**Best (early return):**++```tsx+function Profile({ name, count }: { name: string; count: number }) {+ if (!name) return null++ return (+ <View>+ <Text>{name}</Text>+ {count > 0 ? <Text>{count} items</Text> : null}+ </View>+ )+}+```++Early returns are clearest. When using conditionals inline, prefer ternary or+explicit boolean checks.++**Lint rule:** Enable `react/jsx-no-leaked-render` from+[eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md)+to catch this automatically.diff --git a/.agents/skills/vercel-react-native-skills/rules/rendering-text-in-text-component.md b/.agents/skills/vercel-react-native-skills/rules/rendering-text-in-text-component.mdnew file mode 100644index 000000000..fd1b9f407--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/rendering-text-in-text-component.md@@ -0,0 +1,36 @@+---+title: Wrap Strings in Text Components+impact: CRITICAL+impactDescription: prevents runtime crash+tags: rendering, text, core+---++## Wrap Strings in Text Components++Strings must be rendered inside `<Text>`. React Native crashes if a string is a+direct child of `<View>`.++**Incorrect (crashes):**++```tsx+import { View } from 'react-native'++function Greeting({ name }: { name: string }) {+ return <View>Hello, {name}!</View>+}+// Error: Text strings must be rendered within a <Text> component.+```++**Correct:**++```tsx+import { View, Text } from 'react-native'++function Greeting({ name }: { name: string }) {+ return (+ <View>+ <Text>Hello, {name}!</Text>+ </View>+ )+}+```diff --git a/.agents/skills/vercel-react-native-skills/rules/scroll-position-no-state.md b/.agents/skills/vercel-react-native-skills/rules/scroll-position-no-state.mdnew file mode 100644index 000000000..a5760cd28--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/scroll-position-no-state.md@@ -0,0 +1,82 @@+---+title: Never Track Scroll Position in useState+impact: HIGH+impactDescription: prevents render thrashing during scroll+tags: scroll, performance, reanimated, useRef+---++## Never Track Scroll Position in useState++Never store scroll position in `useState`. Scroll events fire rapidly—state+updates cause render thrashing and dropped frames. Use a Reanimated shared value+for animations or a ref for non-reactive tracking.++**Incorrect (useState causes jank):**++```tsx+import { useState } from 'react'+import {+ ScrollView,+ NativeSyntheticEvent,+ NativeScrollEvent,+} from 'react-native'++function Feed() {+ const [scrollY, setScrollY] = useState(0)++ const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {+ setScrollY(e.nativeEvent.contentOffset.y) // re-renders on every frame+ }++ return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />+}+```++**Correct (Reanimated for animations):**++```tsx+import Animated, {+ useSharedValue,+ useAnimatedScrollHandler,+} from 'react-native-reanimated'++function Feed() {+ const scrollY = useSharedValue(0)++ const onScroll = useAnimatedScrollHandler({+ onScroll: (e) => {+ scrollY.value = e.contentOffset.y // runs on UI thread, no re-render+ },+ })++ return (+ <Animated.ScrollView+ onScroll={onScroll}+ // higher number has better performance, but it fires less often.+ // unset this if you need higher precision over performance.+ scrollEventThrottle={16}+ />+ )+}+```++**Correct (ref for non-reactive tracking):**++```tsx+import { useRef } from 'react'+import {+ ScrollView,+ NativeSyntheticEvent,+ NativeScrollEvent,+} from 'react-native'++function Feed() {+ const scrollY = useRef(0)++ const onScroll = (e: NativeSyntheticEvent<NativeScrollEvent>) => {+ scrollY.current = e.nativeEvent.contentOffset.y // no re-render+ }++ return <ScrollView onScroll={onScroll} scrollEventThrottle={16} />+}+```diff --git a/.agents/skills/vercel-react-native-skills/rules/state-ground-truth.md b/.agents/skills/vercel-react-native-skills/rules/state-ground-truth.mdnew file mode 100644index 000000000..c3c4bd9e4--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/state-ground-truth.md@@ -0,0 +1,80 @@+---+title: State Must Represent Ground Truth+impact: HIGH+impactDescription: cleaner logic, easier debugging, single source of truth+tags: state, derived-state, reanimated, hooks+---++## State Must Represent Ground Truth++State variables—both React `useState` and Reanimated shared values—should+represent the actual state of something (e.g., `pressed`, `progress`, `isOpen`),+not derived visual values (e.g., `scale`, `opacity`, `translateY`). Derive+visual values from state using computation or interpolation.++**Incorrect (storing the visual output):**++```tsx+const scale = useSharedValue(1)++const tap = Gesture.Tap()+ .onBegin(() => {+ scale.set(withTiming(0.95))+ })+ .onFinalize(() => {+ scale.set(withTiming(1))+ })++const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: scale.get() }],+}))+```++**Correct (storing the state, deriving the visual):**++```tsx+const pressed = useSharedValue(0) // 0 = not pressed, 1 = pressed++const tap = Gesture.Tap()+ .onBegin(() => {+ pressed.set(withTiming(1))+ })+ .onFinalize(() => {+ pressed.set(withTiming(0))+ })++const animatedStyle = useAnimatedStyle(() => ({+ transform: [{ scale: interpolate(pressed.get(), [0, 1], [1, 0.95]) }],+}))+```++**Why this matters:**++State variables should represent real "state", not necessarily a desired end+result.++1. **Single source of truth** — The state (`pressed`) describes what's+ happening; visuals are derived+2. **Easier to extend** — Adding opacity, rotation, or other effects just+ requires more interpolations from the same state+3. **Debugging** — Inspecting `pressed = 1` is clearer than `scale = 0.95`+4. **Reusable logic** — The same `pressed` value can drive multiple visual+ properties++**Same principle for React state:**++```tsx+// Incorrect: storing derived values+const [isExpanded, setIsExpanded] = useState(false)+const [height, setHeight] = useState(0)++useEffect(() => {+ setHeight(isExpanded ? 200 : 0)+}, [isExpanded])++// Correct: derive from state+const [isExpanded, setIsExpanded] = useState(false)+const height = isExpanded ? 200 : 0+```++State is the minimal truth. Everything else is derived.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-expo-image.md b/.agents/skills/vercel-react-native-skills/rules/ui-expo-image.mdnew file mode 100644index 000000000..72d768f1b--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-expo-image.md@@ -0,0 +1,66 @@+---+title: Use expo-image for Optimized Images+impact: HIGH+impactDescription: memory efficiency, caching, blurhash placeholders, progressive loading+tags: images, performance, expo-image, ui+---++## Use expo-image for Optimized Images++Use `expo-image` instead of React Native's `Image`. It provides memory-efficient caching, blurhash placeholders, progressive loading, and better performance for lists.++**Incorrect (React Native Image):**++```tsx+import { Image } from 'react-native'++function Avatar({ url }: { url: string }) {+ return <Image source={{ uri: url }} style={styles.avatar} />+}+```++**Correct (expo-image):**++```tsx+import { Image } from 'expo-image'++function Avatar({ url }: { url: string }) {+ return <Image source={{ uri: url }} style={styles.avatar} />+}+```++**With blurhash placeholder:**++```tsx+<Image+ source={{ uri: url }}+ placeholder={{ blurhash: 'LGF5]+Yk^6#M@-5c,1J5@[or[Q6.' }}+ contentFit="cover"+ transition={200}+ style={styles.image}+/>+```++**With priority and caching:**++```tsx+<Image+ source={{ uri: url }}+ priority="high"+ cachePolicy="memory-disk"+ style={styles.hero}+/>+```++**Key props:**++- `placeholder` — Blurhash or thumbnail while loading+- `contentFit` — `cover`, `contain`, `fill`, `scale-down`+- `transition` — Fade-in duration (ms)+- `priority` — `low`, `normal`, `high`+- `cachePolicy` — `memory`, `disk`, `memory-disk`, `none`+- `recyclingKey` — Unique key for list recycling++For cross-platform (web + native), use `SolitoImage` from `solito/image` which uses `expo-image` under the hood.++Reference: [expo-image](https://docs.expo.dev/versions/latest/sdk/image/)diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-image-gallery.md b/.agents/skills/vercel-react-native-skills/rules/ui-image-gallery.mdnew file mode 100644index 000000000..ef26d962f--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-image-gallery.md@@ -0,0 +1,104 @@+---+title: Use Galeria for Image Galleries and Lightbox+impact: MEDIUM+impactDescription:+ native shared element transitions, pinch-to-zoom, pan-to-close+tags: images, gallery, lightbox, expo-image, ui+---++## Use Galeria for Image Galleries and Lightbox++For image galleries with lightbox (tap to fullscreen), use `@nandorojo/galeria`.+It provides native shared element transitions with pinch-to-zoom, double-tap+zoom, and pan-to-close. Works with any image component including `expo-image`.++**Incorrect (custom modal implementation):**++```tsx+function ImageGallery({ urls }: { urls: string[] }) {+ const [selected, setSelected] = useState<string | null>(null)++ return (+ <>+ {urls.map((url) => (+ <Pressable key={url} onPress={() => setSelected(url)}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Pressable>+ ))}+ <Modal visible={!!selected} onRequestClose={() => setSelected(null)}>+ <Image source={{ uri: selected! }} style={styles.fullscreen} />+ </Modal>+ </>+ )+}+```++**Correct (Galeria with expo-image):**++```tsx+import { Galeria } from '@nandorojo/galeria'+import { Image } from 'expo-image'++function ImageGallery({ urls }: { urls: string[] }) {+ return (+ <Galeria urls={urls}>+ {urls.map((url, index) => (+ <Galeria.Image index={index} key={url}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Galeria.Image>+ ))}+ </Galeria>+ )+}+```++**Single image:**++```tsx+import { Galeria } from '@nandorojo/galeria'+import { Image } from 'expo-image'++function Avatar({ url }: { url: string }) {+ return (+ <Galeria urls={[url]}>+ <Galeria.Image>+ <Image source={{ uri: url }} style={styles.avatar} />+ </Galeria.Image>+ </Galeria>+ )+}+```++**With low-res thumbnails and high-res fullscreen:**++```tsx+<Galeria urls={highResUrls}>+ {lowResUrls.map((url, index) => (+ <Galeria.Image index={index} key={url}>+ <Image source={{ uri: url }} style={styles.thumbnail} />+ </Galeria.Image>+ ))}+</Galeria>+```++**With FlashList:**++```tsx+<Galeria urls={urls}>+ <FlashList+ data={urls}+ renderItem={({ item, index }) => (+ <Galeria.Image index={index}>+ <Image source={{ uri: item }} style={styles.thumbnail} />+ </Galeria.Image>+ )}+ numColumns={3}+ estimatedItemSize={100}+ />+</Galeria>+```++Works with `expo-image`, `SolitoImage`, `react-native` Image, or any image+component.++Reference: [Galeria](https://github.com/nandorojo/galeria)diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-measure-views.md b/.agents/skills/vercel-react-native-skills/rules/ui-measure-views.mdnew file mode 100644index 000000000..8b783fee3--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-measure-views.md@@ -0,0 +1,78 @@+---+title: Measuring View Dimensions+impact: MEDIUM+impactDescription: synchronous measurement, avoid unnecessary re-renders+tags: layout, measurement, onLayout, useLayoutEffect+---++## Measuring View Dimensions++Use both `useLayoutEffect` (synchronous) and `onLayout` (for updates). The sync+measurement gives you the initial size immediately; `onLayout` keeps it current+when the view changes. For non-primitive states, use a dispatch updater to+compare values and avoid unnecessary re-renders.++**Height only:**++```tsx+import { useLayoutEffect, useRef, useState } from 'react'+import { View, LayoutChangeEvent } from 'react-native'++function MeasuredBox({ children }: { children: React.ReactNode }) {+ const ref = useRef<View>(null)+ const [height, setHeight] = useState<number | undefined>(undefined)++ useLayoutEffect(() => {+ // Sync measurement on mount (RN 0.82+)+ const rect = ref.current?.getBoundingClientRect()+ if (rect) setHeight(rect.height)+ // Pre-0.82: ref.current?.measure((x, y, w, h) => setHeight(h))+ }, [])++ const onLayout = (e: LayoutChangeEvent) => {+ setHeight(e.nativeEvent.layout.height)+ }++ return (+ <View ref={ref} onLayout={onLayout}>+ {children}+ </View>+ )+}+```++**Both dimensions:**++```tsx+import { useLayoutEffect, useRef, useState } from 'react'+import { View, LayoutChangeEvent } from 'react-native'++type Size = { width: number; height: number }++function MeasuredBox({ children }: { children: React.ReactNode }) {+ const ref = useRef<View>(null)+ const [size, setSize] = useState<Size | undefined>(undefined)++ useLayoutEffect(() => {+ const rect = ref.current?.getBoundingClientRect()+ if (rect) setSize({ width: rect.width, height: rect.height })+ }, [])++ const onLayout = (e: LayoutChangeEvent) => {+ const { width, height } = e.nativeEvent.layout+ setSize((prev) => {+ // for non-primitive states, compare values before firing a re-render+ if (prev?.width === width && prev?.height === height) return prev+ return { width, height }+ })+ }++ return (+ <View ref={ref} onLayout={onLayout}>+ {children}+ </View>+ )+}+```++Use functional setState to compare—don't read state directly in the callback.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-menus.md b/.agents/skills/vercel-react-native-skills/rules/ui-menus.mdnew file mode 100644index 000000000..5168bc203--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-menus.md@@ -0,0 +1,174 @@+---+title: Use Native Menus for Dropdowns and Context Menus+impact: HIGH+impactDescription: native accessibility, platform-consistent UX+tags: user-interface, menus, context-menus, zeego, accessibility+---++## Use Native Menus for Dropdowns and Context Menus++Use native platform menus instead of custom JS implementations. Native menus+provide built-in accessibility, consistent platform UX, and better performance.+Use [zeego](https://zeego.dev) for cross-platform native menus.++**Incorrect (custom JS menu):**++```tsx+import { useState } from 'react'+import { View, Pressable, Text } from 'react-native'++function MyMenu() {+ const [open, setOpen] = useState(false)++ return (+ <View>+ <Pressable onPress={() => setOpen(!open)}>+ <Text>Open Menu</Text>+ </Pressable>+ {open && (+ <View style={{ position: 'absolute', top: 40 }}>+ <Pressable onPress={() => console.log('edit')}>+ <Text>Edit</Text>+ </Pressable>+ <Pressable onPress={() => console.log('delete')}>+ <Text>Delete</Text>+ </Pressable>+ </View>+ )}+ </View>+ )+}+```++**Correct (native menu with zeego):**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function MyMenu() {+ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Open Menu</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.Item key='edit' onSelect={() => console.log('edit')}>+ <DropdownMenu.ItemTitle>Edit</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Item+ key='delete'+ destructive+ onSelect={() => console.log('delete')}+ >+ <DropdownMenu.ItemTitle>Delete</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++**Context menu (long-press):**++```tsx+import * as ContextMenu from 'zeego/context-menu'++function MyContextMenu() {+ return (+ <ContextMenu.Root>+ <ContextMenu.Trigger>+ <View style={{ padding: 20 }}>+ <Text>Long press me</Text>+ </View>+ </ContextMenu.Trigger>++ <ContextMenu.Content>+ <ContextMenu.Item key='copy' onSelect={() => console.log('copy')}>+ <ContextMenu.ItemTitle>Copy</ContextMenu.ItemTitle>+ </ContextMenu.Item>++ <ContextMenu.Item key='paste' onSelect={() => console.log('paste')}>+ <ContextMenu.ItemTitle>Paste</ContextMenu.ItemTitle>+ </ContextMenu.Item>+ </ContextMenu.Content>+ </ContextMenu.Root>+ )+}+```++**Checkbox items:**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function SettingsMenu() {+ const [notifications, setNotifications] = useState(true)++ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Settings</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.CheckboxItem+ key='notifications'+ value={notifications}+ onValueChange={() => setNotifications((prev) => !prev)}+ >+ <DropdownMenu.ItemIndicator />+ <DropdownMenu.ItemTitle>Notifications</DropdownMenu.ItemTitle>+ </DropdownMenu.CheckboxItem>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++**Submenus:**++```tsx+import * as DropdownMenu from 'zeego/dropdown-menu'++function MenuWithSubmenu() {+ return (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <Pressable>+ <Text>Options</Text>+ </Pressable>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ <DropdownMenu.Item key='home' onSelect={() => console.log('home')}>+ <DropdownMenu.ItemTitle>Home</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Sub>+ <DropdownMenu.SubTrigger key='more'>+ <DropdownMenu.ItemTitle>More Options</DropdownMenu.ItemTitle>+ </DropdownMenu.SubTrigger>++ <DropdownMenu.SubContent>+ <DropdownMenu.Item key='settings'>+ <DropdownMenu.ItemTitle>Settings</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>++ <DropdownMenu.Item key='help'>+ <DropdownMenu.ItemTitle>Help</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </DropdownMenu.SubContent>+ </DropdownMenu.Sub>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ )+}+```++Reference: [Zeego Documentation](https://zeego.dev/components/dropdown-menu)diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-native-modals.md b/.agents/skills/vercel-react-native-skills/rules/ui-native-modals.mdnew file mode 100644index 000000000..f560e11e1--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-native-modals.md@@ -0,0 +1,77 @@+---+title: Use Native Modals Over JS-Based Bottom Sheets+impact: HIGH+impactDescription: native performance, gestures, accessibility+tags: modals, bottom-sheet, native, react-navigation+---++## Use Native Modals Over JS-Based Bottom Sheets++Use native `<Modal>` with `presentationStyle="formSheet"` or React Navigation+v7's native form sheet instead of JS-based bottom sheet libraries. Native modals+have built-in gestures, accessibility, and better performance. Rely on native UI+for low-level primitives.++**Incorrect (JS-based bottom sheet):**++```tsx+import BottomSheet from 'custom-js-bottom-sheet'++function MyScreen() {+ const sheetRef = useRef<BottomSheet>(null)++ return (+ <View style={{ flex: 1 }}>+ <Button onPress={() => sheetRef.current?.expand()} title='Open' />+ <BottomSheet ref={sheetRef} snapPoints={['50%', '90%']}>+ <View>+ <Text>Sheet content</Text>+ </View>+ </BottomSheet>+ </View>+ )+}+```++**Correct (native Modal with formSheet):**++```tsx+import { Modal, View, Text, Button } from 'react-native'++function MyScreen() {+ const [visible, setVisible] = useState(false)++ return (+ <View style={{ flex: 1 }}>+ <Button onPress={() => setVisible(true)} title='Open' />+ <Modal+ visible={visible}+ presentationStyle='formSheet'+ animationType='slide'+ onRequestClose={() => setVisible(false)}+ >+ <View>+ <Text>Sheet content</Text>+ </View>+ </Modal>+ </View>+ )+}+```++**Correct (React Navigation v7 native form sheet):**++```tsx+// In your navigator+<Stack.Screen+ name='Details'+ component={DetailsScreen}+ options={{+ presentation: 'formSheet',+ sheetAllowedDetents: 'fitToContents',+ }}+/>+```++Native modals provide swipe-to-dismiss, proper keyboard avoidance, and+accessibility out of the box.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-pressable.md b/.agents/skills/vercel-react-native-skills/rules/ui-pressable.mdnew file mode 100644index 000000000..31c3d2042--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-pressable.md@@ -0,0 +1,61 @@+---+title: Use Pressable Instead of Touchable Components+impact: LOW+impactDescription: modern API, more flexible+tags: ui, pressable, touchable, gestures+---++## Use Pressable Instead of Touchable Components++Never use `TouchableOpacity` or `TouchableHighlight`. Use `Pressable` from+`react-native` or `react-native-gesture-handler` instead.++**Incorrect (legacy Touchable components):**++```tsx+import { TouchableOpacity } from 'react-native'++function MyButton({ onPress }: { onPress: () => void }) {+ return (+ <TouchableOpacity onPress={onPress} activeOpacity={0.7}>+ <Text>Press me</Text>+ </TouchableOpacity>+ )+}+```++**Correct (Pressable):**++```tsx+import { Pressable } from 'react-native'++function MyButton({ onPress }: { onPress: () => void }) {+ return (+ <Pressable onPress={onPress}>+ <Text>Press me</Text>+ </Pressable>+ )+}+```++**Correct (Pressable from gesture handler for lists):**++```tsx+import { Pressable } from 'react-native-gesture-handler'++function ListItem({ onPress }: { onPress: () => void }) {+ return (+ <Pressable onPress={onPress}>+ <Text>Item</Text>+ </Pressable>+ )+}+```++Use `react-native-gesture-handler` Pressable inside scrollable lists for better+gesture coordination, as long as you are using the ScrollView from+`react-native-gesture-handler` as well.++**For animated press states (scale, opacity changes):** Use `GestureDetector`+with Reanimated shared values instead of Pressable's style callback. See the+`animation-gesture-detector-press` rule.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-safe-area-scroll.md b/.agents/skills/vercel-react-native-skills/rules/ui-safe-area-scroll.mdnew file mode 100644index 000000000..79812bc9c--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-safe-area-scroll.md@@ -0,0 +1,65 @@+---+title: Use contentInsetAdjustmentBehavior for Safe Areas+impact: MEDIUM+impactDescription: native safe area handling, no layout shifts+tags: safe-area, scrollview, layout+---++## Use contentInsetAdjustmentBehavior for Safe Areas++Use `contentInsetAdjustmentBehavior="automatic"` on the root ScrollView instead of wrapping content in SafeAreaView or manual padding. This lets iOS handle safe area insets natively with proper scroll behavior.++**Incorrect (SafeAreaView wrapper):**++```tsx+import { SafeAreaView, ScrollView, View, Text } from 'react-native'++function MyScreen() {+ return (+ <SafeAreaView style={{ flex: 1 }}>+ <ScrollView>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ </SafeAreaView>+ )+}+```++**Incorrect (manual safe area padding):**++```tsx+import { ScrollView, View, Text } from 'react-native'+import { useSafeAreaInsets } from 'react-native-safe-area-context'++function MyScreen() {+ const insets = useSafeAreaInsets()++ return (+ <ScrollView contentContainerStyle={{ paddingTop: insets.top }}>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ )+}+```++**Correct (native content inset adjustment):**++```tsx+import { ScrollView, View, Text } from 'react-native'++function MyScreen() {+ return (+ <ScrollView contentInsetAdjustmentBehavior='automatic'>+ <View>+ <Text>Content</Text>+ </View>+ </ScrollView>+ )+}+```++The native approach handles dynamic safe areas (keyboard, toolbars) and allows content to scroll behind the status bar naturally.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-scrollview-content-inset.md b/.agents/skills/vercel-react-native-skills/rules/ui-scrollview-content-inset.mdnew file mode 100644index 000000000..bbebc3b81--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-scrollview-content-inset.md@@ -0,0 +1,45 @@+---+title: Use contentInset for Dynamic ScrollView Spacing+impact: LOW+impactDescription: smoother updates, no layout recalculation+tags: scrollview, layout, contentInset, performance+---++## Use contentInset for Dynamic ScrollView Spacing++When adding space to the top or bottom of a ScrollView that may change+(keyboard, toolbars, dynamic content), use `contentInset` instead of padding.+Changing `contentInset` doesn't trigger layout recalculation—it adjusts the+scroll area without re-rendering content.++**Incorrect (padding causes layout recalculation):**++```tsx+function Feed({ bottomOffset }: { bottomOffset: number }) {+ return (+ <ScrollView contentContainerStyle={{ paddingBottom: bottomOffset }}>+ {children}+ </ScrollView>+ )+}+// Changing bottomOffset triggers full layout recalculation+```++**Correct (contentInset for dynamic spacing):**++```tsx+function Feed({ bottomOffset }: { bottomOffset: number }) {+ return (+ <ScrollView+ contentInset={{ bottom: bottomOffset }}+ scrollIndicatorInsets={{ bottom: bottomOffset }}+ >+ {children}+ </ScrollView>+ )+}+// Changing bottomOffset only adjusts scroll bounds+```++Use `scrollIndicatorInsets` alongside `contentInset` to keep the scroll+indicator aligned. For static spacing that never changes, padding is fine.diff --git a/.agents/skills/vercel-react-native-skills/rules/ui-styling.md b/.agents/skills/vercel-react-native-skills/rules/ui-styling.mdnew file mode 100644index 000000000..3908de3c4--- /dev/null+++ b/.agents/skills/vercel-react-native-skills/rules/ui-styling.md@@ -0,0 +1,87 @@+---+title: Modern React Native Styling Patterns+impact: MEDIUM+impactDescription: consistent design, smoother borders, cleaner layouts+tags: styling, css, layout, shadows, gradients+---++## Modern React Native Styling Patterns++Follow these styling patterns for cleaner, more consistent React Native code.++**Always use `borderCurve: 'continuous'` with `borderRadius`:**++```tsx+// Incorrect+{ borderRadius: 12 }++// Correct – smoother iOS-style corners+{ borderRadius: 12, borderCurve: 'continuous' }+```++**Use `gap` instead of margin for spacing between elements:**++```tsx+// Incorrect – margin on children+<View>+ <Text style={{ marginBottom: 8 }}>Title</Text>+ <Text style={{ marginBottom: 8 }}>Subtitle</Text>+</View>++// Correct – gap on parent+<View style={{ gap: 8 }}>+ <Text>Title</Text>+ <Text>Subtitle</Text>+</View>+```++**Use `padding` for space within, `gap` for space between:**++```tsx+<View style={{ padding: 16, gap: 12 }}>+ <Text>First</Text>+ <Text>Second</Text>+</View>+```++**Use `experimental_backgroundImage` for linear gradients:**++```tsx+// Incorrect – third-party gradient library+<LinearGradient colors={['#000', '#fff']} />++// Correct – native CSS gradient syntax+<View+ style={{+ experimental_backgroundImage: 'linear-gradient(to bottom, #000, #fff)',+ }}+/>+```++**Use CSS `boxShadow` string syntax for shadows:**++```tsx+// Incorrect – legacy shadow objects or elevation+{ shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1 }+{ elevation: 4 }++// Correct – CSS box-shadow syntax+{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }+```++**Avoid multiple font sizes – use weight and color for emphasis:**++```tsx+// Incorrect – varying font sizes for hierarchy+<Text style={{ fontSize: 18 }}>Title</Text>+<Text style={{ fontSize: 14 }}>Subtitle</Text>+<Text style={{ fontSize: 12 }}>Caption</Text>++// Correct – consistent size, vary weight and color+<Text style={{ fontWeight: '600' }}>Title</Text>+<Text style={{ color: '#666' }}>Subtitle</Text>+<Text style={{ color: '#999' }}>Caption</Text>+```++Limiting font sizes creates visual consistency. Use `fontWeight` (bold/semibold)+and grayscale colors for hierarchy instead.diff --git a/.agents/skills/web-design-guidelines/SKILL.md b/.agents/skills/web-design-guidelines/SKILL.mdnew file mode 100644index 000000000..ceae92ab3--- /dev/null+++ b/.agents/skills/web-design-guidelines/SKILL.md@@ -0,0 +1,39 @@+---+name: web-design-guidelines+description: Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".+metadata:+ author: vercel+ version: "1.0.0"+ argument-hint: <file-or-pattern>+---++# Web Interface Guidelines++Review files for compliance with Web Interface Guidelines.++## How It Works++1. Fetch the latest guidelines from the source URL below+2. Read the specified files (or prompt user for files/pattern)+3. Check against all rules in the fetched guidelines+4. Output findings in the terse `file:line` format++## Guidelines Source++Fetch fresh guidelines before each review:++```+https://raw.githubusercontent.com/vercel-labs/web-interface-guidelines/main/command.md+```++Use WebFetch to retrieve the latest rules. The fetched content contains all the rules and output format instructions.++## Usage++When a user provides a file or pattern argument:+1. Fetch guidelines from the source URL above+2. Read the specified files+3. Apply all rules from the fetched guidelines+4. Output findings using the format specified in the guidelines++If no files specified, ask the user which files to review.diff --git a/.env.example b/.env.exampleindex 73dc43d7b..cddc9e315 100644--- a/.env.example+++ b/.env.example@@ -1,3 +1,10 @@+# Neon Auth (optional - for account features)+# Get your auth URL from the Neon console after enabling Neon Auth+VITE_NEON_AUTH_URL=++# OpenWhispr Cloud API (optional - for cloud transcription)+VITE_OPENWHISPR_API_URL=+# OpenAI API Configuration# Get your API key from: https://platform.openai.com/api-keysOPENAI_API_KEY=your_openai_api_key_here@@ -23,4 +30,4 @@ GEMINI_API_KEY=your_gemini_api_key_hereGROQ_API_KEY=your_groq_api_key_here# Optional: Debug mode-OPENWHISPR_LOG_LEVEL=debug\ No newline at end of file+OPENWHISPR_LOG_LEVEL=debugdiff --git a/.gitignore b/.gitignoreindex f5067ea59..ae7a38f09 100644--- a/.gitignore+++ b/.gitignore@@ -309,3 +309,4 @@ skills/.Trashesehthumbs.dbThumbs.db+.macos-globe-listener.hashdiff --git a/CLEANUP_INSTRUCTIONS.md b/CLEANUP_INSTRUCTIONS.mdnew file mode 100644index 000000000..e939b92e7--- /dev/null+++ b/CLEANUP_INSTRUCTIONS.md@@ -0,0 +1,306 @@+# OpenWhispr Complete Cleanup Instructions++## The Problem++If you've installed both the **production DMG** and tried to run **development mode**, they share the same data directories, which can cause conflicts:++- Same database files+- Same settings/localStorage+- Same `.env` configuration+- Same Whisper models cache+- Same system preferences++This can lead to issues like:+- Microphone not working in dev but working in production+- Settings not persisting correctly+- Database conflicts+- Mixed configurations++## Quick Solution: Use the Cleanup Script++### Step 1: Run the automated cleanup script++```bash+cd /path/to/open-whispr+bash scripts/complete-uninstall.sh+```++This script will:+- Stop all OpenWhispr processes+- Remove the production app+- Delete all application data+- Clear caches and logs+- Optionally remove Whisper models+- Clean up temp files++### Step 2: Start fresh++**For Production:**+```bash+# Download fresh DMG from releases+# Install and run normally+```++**For Development:**+```bash+# Make sure you have ARM64 Node.js+node -p "process.arch" # Should output: arm64++# Clean install+rm -rf node_modules package-lock.json+npm install++# Run dev+npm run dev+```++---++## Manual Cleanup (if script doesn't work)++### 1. Stop all OpenWhispr processes++```bash+# Kill production app+pkill -f "OpenWhispr"++# Kill dev processes+pkill -f "open-whispr"+pkill -f "electron"+```++### 2. Remove the Application++```bash+rm -rf /Applications/OpenWhispr.app+```++### 3. Remove Application Data++**Application Support** (contains databases, settings, logs):+```bash+rm -rf "$HOME/Library/Application Support/OpenWhispr"+rm -rf "$HOME/Library/Application Support/open-whispr"+```++**Preferences** (system-level settings):+```bash+rm -rf "$HOME/Library/Preferences/com.openwhispr.app.plist"+rm -rf "$HOME/Library/Preferences/com.electron.openwhispr.plist"+```++**Caches**:+```bash+rm -rf "$HOME/Library/Caches/OpenWhispr"+rm -rf "$HOME/Library/Caches/open-whispr"+```++**Logs**:+```bash+rm -rf "$HOME/Library/Logs/OpenWhispr"+rm -rf "$HOME/Library/Logs/open-whispr"+```++**Saved Application State**:+```bash+rm -rf "$HOME/Library/Saved Application State/com.openwhispr.app.savedState"+```++### 4. Remove Whisper Models (optional, ~2-3GB)++```bash+rm -rf "$HOME/.cache/whisper"+rm -rf "$HOME/.cache/huggingface"+```++### 5. Remove Temp Files++```bash+find /tmp -name "whisper_audio_*" -delete+find /tmp -name "openwhispr_*" -delete+```++### 6. Clean Development Environment++If you're setting up for development:++```bash+cd /path/to/open-whispr++# Remove dev database and env file+rm -f .env+rm -rf node_modules+rm -f package-lock.json++# Clear npm cache+npm cache clean --force+```++### 7. Reset macOS System Permissions (Optional)++The cleanup script **cannot** remove macOS system permissions. These persist even after uninstalling.++**This is usually fine** - permissions will automatically apply to a fresh install.++**To completely reset permissions** (rarely needed):++```bash+# Reset microphone permission+tccutil reset Microphone com.openwhispr.app++# Reset accessibility permission+tccutil reset Accessibility com.openwhispr.app++# For dev mode (Terminal)+tccutil reset Microphone com.apple.Terminal+tccutil reset Accessibility com.apple.Terminal+```++After running these commands, macOS will prompt for permissions again when you run the app.++**When to reset permissions:**+- Microphone not working after reinstall+- "Permission denied" errors even though you granted access+- Troubleshooting strange permission issues++**Note:** You cannot manually remove apps from System Settings → Privacy lists. They only disappear when the app is uninstalled, but the permission record persists in the TCC database.++---++## Complete Fresh Start for Development++After cleanup, follow these steps for a clean dev environment:++### 1. Verify ARM64 Node.js (Apple Silicon Macs)++```bash+# Check architecture+node -p "process.arch" # Must show: arm64++# If it shows x64, install ARM64 Node:+# Option A: Using nvm (recommended)+curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash+nvm install --lts+nvm use --lts++# Option B: Download from nodejs.org+# Get macOS ARM64 installer from https://nodejs.org/+```++### 2. Clean Install Dependencies++```bash+cd /path/to/open-whispr++# Remove everything+rm -rf node_modules package-lock.json++# Fresh install+npm install++# Verify better-sqlite3 architecture+file node_modules/better-sqlite3/build/Release/better_sqlite3.node+# Should show: Mach-O 64-bit bundle arm64+```++### 3. Setup Environment++```bash+# Create fresh .env file+touch .env++# Add your API keys+echo "OPENAI_API_KEY=your_key_here" >> .env+```++### 4. Run Development Mode++```bash+npm run dev+```++---++## Troubleshooting++### Issue: "better-sqlite3 architecture mismatch"++**Solution:**+```bash+# Your Node is running in x64 mode via Rosetta+# Follow "Verify ARM64 Node.js" section above+```++### Issue: "Microphone prints 'you' instead of transcription"++**Solution:**+```bash+# Corrupted database or settings - run cleanup script+bash scripts/complete-uninstall.sh++# Then reinstall/re-run+```++### Issue: "Database initialization failed"++**Solution:**+```bash+# Remove database files specifically+rm -rf "$HOME/Library/Application Support/OpenWhispr"+rm -rf "$HOME/Library/Application Support/open-whispr"++# Rebuild dependencies+npm run postinstall+```++### Issue: Production DMG works but dev doesn't++**Cause:** They're sharing data directories but using different configurations.++**Solution:**+1. Run complete cleanup script+2. Choose either production OR development (don't mix)+3. If developing, uninstall production app first++---++## Data Locations Reference++All OpenWhispr data is stored in these locations:++| Type | Location |+|------|----------|+| **Databases** | `~/Library/Application Support/OpenWhispr/transcriptions.db` |+| **Dev Database** | `~/Library/Application Support/OpenWhispr/transcriptions-dev.db` |+| **Settings** | Browser localStorage (in Electron's userData) |+| **API Keys** | `.env` file in project root (dev) |+| **Logs** | `~/Library/Application Support/OpenWhispr/logs/` |+| **Debug Logs** | `~/Library/Logs/OpenWhispr/` |+| **Whisper Models** | `~/.cache/whisper/` |+| **Preferences** | `~/Library/Preferences/com.openwhispr.app.plist` |+| **Caches** | `~/Library/Caches/OpenWhispr/` |+| **Temp Audio** | `/tmp/whisper_audio_*.wav` |++---++## Prevention Tips++1. **Don't mix production and development** - Choose one or the other+2. **Use separate branches** - Keep production DMG uninstalled when developing+3. **Check Node architecture** - Always verify `node -p "process.arch"` shows `arm64`+4. **Clean installs** - When switching modes, run cleanup script first+5. **Backup data** - Export important transcriptions before cleanup++---++## Getting Help++If cleanup doesn't solve your issue:++1. Check the architecture: `node -p "process.arch"`+2. Check Node version: `node -v`+3. Check Electron version: `npm list electron`+4. Run with debug mode: `npm run dev -- --debug`+5. Check logs in: `~/Library/Application Support/OpenWhispr/logs/`++Report issues with this information at: [GitHub Issues](https://github.com/your-repo/open-whispr/issues)diff --git a/NEON_AUTH_SETUP.md b/NEON_AUTH_SETUP.mdnew file mode 100644index 000000000..1de600ff1--- /dev/null+++ b/NEON_AUTH_SETUP.md@@ -0,0 +1,26 @@+# Neon Auth Setup Guide++OpenWhispr supports optional authentication using Neon Auth (managed, Better Auth-based). When enabled, users can sync settings across devices and access account features.++## 1. Create a Neon Project and Enable Neon Auth+1. In the Neon console, create or open your project.+2. Enable Neon Auth for the project.+3. Copy the **Auth URL** for your project.++## 2. Configure Environment Variables+Add the Neon Auth URL to your `.env` file:++```+VITE_NEON_AUTH_URL=https://ep-<branch-id>.neonauth.<region>.aws.neon.tech/neondb/auth+```++## 3. Run the App+If `VITE_NEON_AUTH_URL` is set, the app will show the Neon Auth sign-in UI during onboarding.++## Optional: Run Without Auth+If you don't want authentication, leave `VITE_NEON_AUTH_URL` unset. The app will continue to work without account features.++## Troubleshooting+- Ensure the Auth URL is copied exactly from the Neon console.+- If sign-in fails in Electron, verify that your app origin is allowed by Neon Auth.+- OAuth providers will only appear if configured in the Neon console.diff --git a/electron-builder.json b/electron-builder.jsonindex 257840352..c27f9a892 100644--- a/electron-builder.json+++ b/electron-builder.json@@ -1,6 +1,10 @@{"appId": "com.herotools.openwispr","productName": "OpenWhispr",+ "protocols": {+ "name": "OpenWhispr Protocol",+ "schemes": ["openwhispr"]+ },"directories": {"output": "dist"},@@ -85,6 +89,7 @@"src/assets/**/*","resources/macos-globe-listener.swift","resources/bin/macos-globe-listener",+ "resources/bin/macos-fast-paste",{"from": "resources/bin/","to": "bin/",diff --git a/main.js b/main.jsindex 4356d4253..3c69a167a 100644--- a/main.js+++ b/main.js@@ -1,4 +1,58 @@const { app, globalShortcut, BrowserWindow, dialog, ipcMain } = require("electron");+const path = require("path");+const http = require("http");+require("dotenv").config({ path: path.join(__dirname, ".env") });++const VALID_CHANNELS = new Set(["development", "staging", "production"]);+const DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL = {+ development: "openwhispr-dev",+ staging: "openwhispr-staging",+ production: "openwhispr",+};+const BASE_WINDOWS_APP_ID = "com.herotools.openwispr";+const DEFAULT_AUTH_BRIDGE_PORT = 5199;++function isElectronBinaryExec() {+ const execPath = (process.execPath || "").toLowerCase();+ return (+ execPath.includes("/electron.app/contents/macos/electron") ||+ execPath.endsWith("/electron") ||+ execPath.endsWith("\\electron.exe")+ );+}++function inferDefaultChannel() {+ if (process.env.NODE_ENV === "development" || process.defaultApp || isElectronBinaryExec()) {+ return "development";+ }+ return "production";+}++function resolveAppChannel() {+ const rawChannel = (process.env.OPENWHISPR_CHANNEL || process.env.VITE_OPENWHISPR_CHANNEL || "")+ .trim()+ .toLowerCase();++ if (VALID_CHANNELS.has(rawChannel)) {+ return rawChannel;+ }++ return inferDefaultChannel();+}++const APP_CHANNEL = resolveAppChannel();+process.env.OPENWHISPR_CHANNEL = APP_CHANNEL;++function configureChannelUserDataPath() {+ if (APP_CHANNEL === "production") {+ return;+ }++ const isolatedPath = path.join(app.getPath("appData"), `OpenWhispr-${APP_CHANNEL}`);+ app.setPath("userData", isolatedPath);+}++configureChannelUserDataPath();// Enable native Wayland global shortcuts: https://github.com/electron/electron/pull/45171if (process.platform === "linux" && process.env.XDG_SESSION_TYPE === "wayland") {@@ -7,7 +61,48 @@ if (process.platform === "linux" && process.env.XDG_SESSION_TYPE === "wayland")// Group all windows under single taskbar entry on Windowsif (process.platform === "win32") {- app.setAppUserModelId("com.herotools.openwispr");+ const windowsAppId =+ APP_CHANNEL === "production"+ ? BASE_WINDOWS_APP_ID+ : `${BASE_WINDOWS_APP_ID}.${APP_CHANNEL}`;+ app.setAppUserModelId(windowsAppId);+}++function getOAuthProtocol() {+ const fromEnv = (process.env.VITE_OPENWHISPR_PROTOCOL || process.env.OPENWHISPR_PROTOCOL || "")+ .trim()+ .toLowerCase();++ if (/^[a-z][a-z0-9+.-]*$/.test(fromEnv)) {+ return fromEnv;+ }++ return DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL[APP_CHANNEL] || DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL.production;+}++const OAUTH_PROTOCOL = getOAuthProtocol();++function shouldRegisterProtocolWithAppArg() {+ return Boolean(process.defaultApp) || isElectronBinaryExec();+}++// Register custom protocol for OAuth callbacks.+// In development, always include the app path argument so macOS/Windows/Linux+// can launch the project app instead of opening bare Electron.+function registerOpenWhisprProtocol() {+ const protocol = OAUTH_PROTOCOL;++ if (shouldRegisterProtocolWithAppArg()) {+ const appArg = process.argv[1] ? path.resolve(process.argv[1]) : path.resolve(".");+ return app.setAsDefaultProtocolClient(protocol, process.execPath, [appArg]);+ }++ return app.setAsDefaultProtocolClient(protocol);+}++const protocolRegistered = registerOpenWhisprProtocol();+if (!protocolRegistered) {+ console.warn(`[Auth] Failed to register ${OAUTH_PROTOCOL}:// protocol handler`);}const gotSingleInstanceLock = app.requestSingleInstanceLock();@@ -49,6 +144,7 @@ const TrayManager = require("./src/helpers/tray");const IPCHandlers = require("./src/helpers/ipcHandlers");const UpdateManager = require("./src/updater");const GlobeKeyManager = require("./src/helpers/globeKeyManager");+const DevServerManager = require("./src/helpers/devServerManager");const WindowsKeyManager = require("./src/helpers/windowsKeyManager");// Manager instances - initialized after app.whenReady()@@ -65,6 +161,23 @@ let updateManager = null;let globeKeyManager = null;let windowsKeyManager = null;let globeKeyAlertShown = false;+let authBridgeServer = null;++function parseAuthBridgePort() {+ const raw = (process.env.OPENWHISPR_AUTH_BRIDGE_PORT || "").trim();+ if (!raw) return DEFAULT_AUTH_BRIDGE_PORT;++ const parsed = Number(raw);+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {+ return DEFAULT_AUTH_BRIDGE_PORT;+ }++ return parsed;+}++const AUTH_BRIDGE_HOST = "127.0.0.1";+const AUTH_BRIDGE_PORT = parseAuthBridgePort();+const AUTH_BRIDGE_PATH = "/oauth/callback";// Set up PATH for production builds to find system tools (whisper.cpp, ffmpeg)function setupProductionPath() {@@ -104,6 +217,7 @@ function initializeManagers() {hotkeyManager = windowManager.hotkeyManager;databaseManager = new DatabaseManager();clipboardManager = new ClipboardManager();+ clipboardManager.preWarmAccessibility();whisperManager = new WhisperManager();parakeetManager = new ParakeetManager();trayManager = new TrayManager();@@ -154,10 +268,151 @@ function initializeManagers() {});}+// Handle the protocol on macOS+app.on('open-url', (event, url) => {+ event.preventDefault();+ if (url.startsWith(`${OAUTH_PROTOCOL}://`)) {+ handleOAuthDeepLink(url);+ }+});++// Extract the session verifier from the deep link and navigate the control+// panel to its app URL with the verifier param so the Neon Auth SDK can+// read it from window.location.search and complete authentication.+function navigateControlPanelWithVerifier(verifier) {+ if (!verifier) return;+ if (!isLiveWindow(windowManager?.controlPanelWindow)) return;++ const appUrl = DevServerManager.getAppUrl(true);+ if (!appUrl) return;++ const separator = appUrl.includes('?') ? '&' : '?';+ const urlWithVerifier = `${appUrl}${separator}neon_auth_session_verifier=${encodeURIComponent(verifier)}`;+ if (debugLogger) {+ debugLogger.debug("Navigating control panel with OAuth verifier", {+ appChannel: APP_CHANNEL,+ oauthProtocol: OAUTH_PROTOCOL,+ devServerUrl: appUrl,+ authBridgeUrl: `http://${AUTH_BRIDGE_HOST}:${AUTH_BRIDGE_PORT}${AUTH_BRIDGE_PATH}`,+ });+ }+ windowManager.controlPanelWindow.loadURL(urlWithVerifier);+ windowManager.controlPanelWindow.show();+ windowManager.controlPanelWindow.focus();+}++function handleOAuthDeepLink(deepLinkUrl) {+ try {+ const parsed = new URL(deepLinkUrl);+ const verifier = parsed.searchParams.get('neon_auth_session_verifier');+ if (!verifier) return;+ navigateControlPanelWithVerifier(verifier);+ } catch (err) {+ if (debugLogger) debugLogger.error('Failed to handle OAuth deep link:', err);+ }+}++function parseJsonBody(req) {+ return new Promise((resolve, reject) => {+ let raw = "";+ req.on("data", (chunk) => {+ raw += chunk;+ if (raw.length > 32 * 1024) {+ reject(new Error("Request body too large"));+ req.destroy();+ }+ });+ req.on("end", () => {+ if (!raw) return resolve({});+ try {+ resolve(JSON.parse(raw));+ } catch {+ reject(new Error("Invalid JSON payload"));+ }+ });+ req.on("error", reject);+ });+}++function writeCorsHeaders(res) {+ res.setHeader("Access-Control-Allow-Origin", "*");+ res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");+}++function startAuthBridgeServer() {+ if (APP_CHANNEL !== "development" || authBridgeServer) {+ return;+ }++ authBridgeServer = http.createServer(async (req, res) => {+ writeCorsHeaders(res);+ if (req.method === "OPTIONS") {+ res.writeHead(204);+ res.end();+ return;+ }++ const requestUrl = new URL(req.url || "/", `http://${AUTH_BRIDGE_HOST}:${AUTH_BRIDGE_PORT}`);+ if (requestUrl.pathname !== AUTH_BRIDGE_PATH) {+ res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });+ res.end("Not found");+ return;+ }++ let verifier = requestUrl.searchParams.get("neon_auth_session_verifier");+ if (!verifier && req.method === "POST") {+ try {+ const body = await parseJsonBody(req);+ verifier = body?.neon_auth_session_verifier || body?.verifier || null;+ } catch (error) {+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });+ res.end(error.message || "Invalid request");+ return;+ }+ }++ if (!verifier) {+ res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });+ res.end("Missing neon_auth_session_verifier");+ return;+ }++ navigateControlPanelWithVerifier(verifier);++ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });+ res.end("<html><body><h3>OpenWhispr sign-in complete.</h3><p>You can close this tab.</p></body></html>");+ });++ authBridgeServer.on("error", (error) => {+ if (debugLogger) {+ debugLogger.error("OAuth auth bridge server failed:", error);+ }+ });++ authBridgeServer.listen(AUTH_BRIDGE_PORT, AUTH_BRIDGE_HOST, () => {+ if (debugLogger) {+ debugLogger.debug("OAuth auth bridge server started", {+ url: `http://${AUTH_BRIDGE_HOST}:${AUTH_BRIDGE_PORT}${AUTH_BRIDGE_PATH}`,+ });+ }+ });+}+// Main application startupasync function startApp() {// Initialize all managers now that app is readyinitializeManagers();+ startAuthBridgeServer();++ // Initialize activation mode cache from persisted .env value+ windowManager.setActivationModeCache(environmentManager.getActivationMode());++ // Update cache + persist when renderer changes activation mode (all platforms)+ ipcMain.on("activation-mode-changed", (_event, mode) => {+ windowManager.setActivationModeCache(mode);+ environmentManager.saveActivationMode(mode);+ });// In development, add a small delay to let Vite start properlyif (process.env.NODE_ENV === "development") {@@ -265,6 +520,11 @@ async function startApp() {});globeKeyManager.on("globe-up", async () => {+ // Forward to control panel for hotkey capture (Fn key released)+ if (isLiveWindow(windowManager.controlPanelWindow)) {+ windowManager.controlPanelWindow.webContents.send("globe-key-released");+ }+// Handle push-to-talk release if Globe is the current hotkeyif (hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey() === "GLOBE") {const activationMode = await windowManager.getActivationMode();@@ -278,9 +538,68 @@ async function startApp() {// If released too quickly, don't do anything (tap is ignored in push mode)}}++ // Fn release also stops compound push-to-talk for Fn+F-key hotkeys+ windowManager.handleMacPushModifierUp("fn");+ });++ globeKeyManager.on("modifier-up", (modifier) => {+ if (windowManager?.handleMacPushModifierUp) {+ windowManager.handleMacPushModifierUp(modifier);+ }+ });++ // Right-side single modifier handling (e.g., RightOption as hotkey)+ let rightModDownTime = 0;+ let rightModIsRecording = false;++ globeKeyManager.on("right-modifier-down", async (modifier) => {+ const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();+ if (currentHotkey !== modifier) return;+ if (!isLiveWindow(windowManager.mainWindow)) return;++ const activationMode = await windowManager.getActivationMode();+ windowManager.showDictationPanel();+ if (activationMode === "push") {+ rightModDownTime = Date.now();+ rightModIsRecording = false;+ setTimeout(() => {+ if (rightModDownTime > 0 && !rightModIsRecording) {+ rightModIsRecording = true;+ windowManager.sendStartDictation();+ }+ }, MIN_HOLD_DURATION_MS);+ } else {+ windowManager.mainWindow.webContents.send("toggle-dictation");+ }+ });++ globeKeyManager.on("right-modifier-up", async (modifier) => {+ const currentHotkey = hotkeyManager.getCurrentHotkey && hotkeyManager.getCurrentHotkey();+ if (currentHotkey !== modifier) return;+ if (!isLiveWindow(windowManager.mainWindow)) return;++ const activationMode = await windowManager.getActivationMode();+ if (activationMode === "push") {+ rightModDownTime = 0;+ if (rightModIsRecording) {+ rightModIsRecording = false;+ windowManager.sendStopDictation();+ } else {+ windowManager.hideDictationPanel();+ }+ }});globeKeyManager.start();++ // Reset native key state when hotkey changes+ ipcMain.on("hotkey-changed", (_event, newHotkey) => {+ globeKeyDownTime = 0;+ globeKeyIsRecording = false;+ rightModDownTime = 0;+ rightModIsRecording = false;+ });}// Set up Windows Push-to-Talk handling@@ -295,53 +614,62 @@ async function startApp() {const WIN_MIN_HOLD_DURATION_MS = 150;// Helper to check if hotkey is valid for Windows key listener- // Supports compound hotkeys like "CommandOrControl+F11"const isValidHotkey = (hotkey) => {if (!hotkey) return false;- if (hotkey === "GLOBE") return false; // GLOBE is macOS only+ if (hotkey === "GLOBE") return false;return true;};+ // Right-side single modifiers need the native listener even in tap mode+ const isRightSideMod = (hotkey) => /^Right(Control|Ctrl|Alt|Option|Shift|Super|Win|Meta|Command|Cmd)$/i.test(hotkey);++ // Whether native listener is needed (push mode always, tap mode only for right-side modifiers)+ const needsNativeListener = (hotkey, mode) => {+ if (!isValidHotkey(hotkey)) return false;+ if (mode === "push") return true;+ return isRightSideMod(hotkey);+ };+windowsKeyManager.on("key-down", async (key) => {debugLogger.debug("[Push-to-Talk] Key DOWN received", { key });- // Handle dictation if in push-to-talk mode- if (isLiveWindow(windowManager.mainWindow)) {- const activationMode = await windowManager.getActivationMode();- debugLogger.debug("[Push-to-Talk] Activation mode check", { activationMode });- if (activationMode === "push") {- debugLogger.debug("[Push-to-Talk] Starting recording sequence");- windowManager.showDictationPanel();- // Track when key was pressed for push-to-talk- winKeyDownTime = Date.now();- winKeyIsRecording = false;- // Start recording after a brief delay to distinguish tap from hold- setTimeout(async () => {- if (winKeyDownTime > 0 && !winKeyIsRecording) {- winKeyIsRecording = true;- debugLogger.debug("[Push-to-Talk] Sending start dictation command");- windowManager.sendStartDictation();- }- }, WIN_MIN_HOLD_DURATION_MS);- }+ if (!isLiveWindow(windowManager.mainWindow)) return;++ const activationMode = await windowManager.getActivationMode();+ debugLogger.debug("[Push-to-Talk] Activation mode check", { activationMode });+ if (activationMode === "push") {+ debugLogger.debug("[Push-to-Talk] Starting recording sequence");+ windowManager.showDictationPanel();+ winKeyDownTime = Date.now();+ winKeyIsRecording = false;+ setTimeout(async () => {+ if (winKeyDownTime > 0 && !winKeyIsRecording) {+ winKeyIsRecording = true;+ debugLogger.debug("[Push-to-Talk] Sending start dictation command");+ windowManager.sendStartDictation();+ }+ }, WIN_MIN_HOLD_DURATION_MS);+ } else if (activationMode === "tap") {+ // Tap mode with native listener (right-side modifiers)+ windowManager.showDictationPanel();+ windowManager.mainWindow.webContents.send("toggle-dictation");}});windowsKeyManager.on("key-up", async () => {debugLogger.debug("[Push-to-Talk] Key UP received");- if (isLiveWindow(windowManager.mainWindow)) {- const activationMode = await windowManager.getActivationMode();- if (activationMode === "push") {- const wasRecording = winKeyIsRecording;- winKeyDownTime = 0;- winKeyIsRecording = false;- if (wasRecording) {- debugLogger.debug("[Push-to-Talk] Sending stop dictation command");- windowManager.sendStopDictation();- } else {- // Short tap (< hold threshold) - hide panel since recording never started- debugLogger.debug("[Push-to-Talk] Short tap detected, hiding panel");- windowManager.hideDictationPanel();- }+ if (!isLiveWindow(windowManager.mainWindow)) return;++ const activationMode = await windowManager.getActivationMode();+ if (activationMode === "push") {+ const wasRecording = winKeyIsRecording;+ winKeyDownTime = 0;+ winKeyIsRecording = false;+ if (wasRecording) {+ debugLogger.debug("[Push-to-Talk] Sending stop dictation command");+ windowManager.sendStopDictation();+ } else {+ debugLogger.debug("[Push-to-Talk] Short tap detected, hiding panel");+ windowManager.hideDictationPanel();}}});@@ -384,21 +712,14 @@ async function startApp() {const currentHotkey = hotkeyManager.getCurrentHotkey();debugLogger.debug("[Push-to-Talk] Current state", { activationMode, currentHotkey });- if (activationMode === "push") {- if (isValidHotkey(currentHotkey)) {- debugLogger.debug("[Push-to-Talk] Starting Windows key listener", { hotkey: currentHotkey });- windowsKeyManager.start(currentHotkey);- } else {- debugLogger.debug("[Push-to-Talk] No valid hotkey to start listener");- }+ if (needsNativeListener(currentHotkey, activationMode)) {+ debugLogger.debug("[Push-to-Talk] Starting Windows key listener", { hotkey: currentHotkey });+ windowsKeyManager.start(currentHotkey);} else {- debugLogger.debug("[Push-to-Talk] Not in push mode, skipping listener start");+ debugLogger.debug("[Push-to-Talk] Native listener not needed for current configuration");}};- // Delay (ms) before starting the Windows key listener after app startup.- // The hotkeyManager loads saved hotkey 1 second after did-finish-load event,- // so we wait 3 seconds to ensure settings are fully loaded before starting.const STARTUP_DELAY_MS = 3000;debugLogger.debug("[Push-to-Talk] Scheduling listener start", { delayMs: STARTUP_DELAY_MS });setTimeout(startWindowsKeyListener, STARTUP_DELAY_MS);@@ -406,15 +727,12 @@ async function startApp() {// Listen for activation mode changes from rendereripcMain.on("activation-mode-changed", async (_event, mode) => {debugLogger.debug("[Push-to-Talk] IPC: Activation mode changed", { mode });- if (mode === "push") {- const currentHotkey = hotkeyManager.getCurrentHotkey();- debugLogger.debug("[Push-to-Talk] Current hotkey", { hotkey: currentHotkey });- if (isValidHotkey(currentHotkey)) {- debugLogger.debug("[Push-to-Talk] Starting listener", { hotkey: currentHotkey });- windowsKeyManager.start(currentHotkey);- }+ const currentHotkey = hotkeyManager.getCurrentHotkey();+ if (needsNativeListener(currentHotkey, mode)) {+ debugLogger.debug("[Push-to-Talk] Starting listener", { hotkey: currentHotkey });+ windowsKeyManager.start(currentHotkey);} else {- debugLogger.debug("[Push-to-Talk] Stopping listener (mode is tap)");+ debugLogger.debug("[Push-to-Talk] Stopping listener");windowsKeyManager.stop();}});@@ -422,25 +740,27 @@ async function startApp() {// Listen for hotkey changes from rendereripcMain.on("hotkey-changed", async (_event, hotkey) => {debugLogger.debug("[Push-to-Talk] IPC: Hotkey changed", { hotkey });- if (!isLiveWindow(windowManager.mainWindow)) {- return;- }+ if (!isLiveWindow(windowManager.mainWindow)) return;const activationMode = await windowManager.getActivationMode();- debugLogger.debug("[Push-to-Talk] Current activation mode", { activationMode });- if (activationMode === "push") {- windowsKeyManager.stop();- if (isValidHotkey(hotkey)) {- debugLogger.debug("[Push-to-Talk] Starting listener for new hotkey", { hotkey });- windowsKeyManager.start(hotkey);- }+ windowsKeyManager.stop();+ if (needsNativeListener(hotkey, activationMode)) {+ debugLogger.debug("[Push-to-Talk] Starting listener for new hotkey", { hotkey });+ windowsKeyManager.start(hotkey);}});}}+// Listen for usage limit reached from dictation overlay, forward to control panel+ipcMain.on("limit-reached", (_event, data) => {+ if (isLiveWindow(windowManager?.controlPanelWindow)) {+ windowManager.controlPanelWindow.webContents.send("limit-reached", data);+ }+});+// App event handlersif (gotSingleInstanceLock) {- app.on("second-instance", async () => {+ app.on("second-instance", async (_event, commandLine) => {await app.whenReady();if (!windowManager) {return;@@ -461,6 +781,12 @@ if (gotSingleInstanceLock) {} else {windowManager.createMainWindow();}++ // Check for OAuth protocol URL in command line arguments (Windows/Linux)+ const url = commandLine.find(arg => arg.startsWith(`${OAUTH_PROTOCOL}://`));+ if (url) {+ handleOAuthDeepLink(url);+ }});app.whenReady().then(() => {@@ -528,6 +854,10 @@ if (gotSingleInstanceLock) {});app.on("will-quit", () => {+ if (authBridgeServer) {+ authBridgeServer.close();+ authBridgeServer = null;+ }if (hotkeyManager) {hotkeyManager.unregisterAll();} else {diff --git a/package-lock.json b/package-lock.jsonindex 440d8cc05..ca945ce26 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,15 +1,17 @@{"name": "open-whispr",- "version": "1.3.4",+ "version": "1.4.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "open-whispr",- "version": "1.3.4",+ "version": "1.4.0","hasInstallScript": true,"license": "MIT","dependencies": {+ "@neondatabase/neon-js": "^0.1.0-beta.22",+ "@radix-ui/react-accordion": "^1.1.2","@radix-ui/react-dialog": "^1.1.14","@radix-ui/react-dropdown-menu": "^2.1.15","@radix-ui/react-label": "^2.1.7",@@ -25,6 +27,7 @@"electron-updater": "^6.6.2","ffmpeg-static": "^5.2.0","lucide-react": "^0.518.0",+ "object-assign": "^4.1.1","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0",@@ -296,7 +299,6 @@"version": "7.28.6","resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz","integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==",- "dev": true,"license": "MIT","engines": {"node": ">=6.9.0"@@ -350,6 +352,77 @@"node": ">=6.9.0"}},+ "node_modules/@better-auth/core": {+ "version": "1.4.17",+ "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.4.17.tgz",+ "integrity": "sha512-WSaEQDdUO6B1CzAmissN6j0lx9fM9lcslEYzlApB5UzFaBeAOHNUONTdglSyUs6/idiZBoRvt0t/qMXCgIU8ug==",+ "peer": true,+ "dependencies": {+ "@standard-schema/spec": "^1.0.0",+ "zod": "^4.3.5"+ },+ "peerDependencies": {+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.21",+ "better-call": "1.1.8",+ "jose": "^6.1.0",+ "kysely": "^0.28.5",+ "nanostores": "^1.0.1"+ }+ },+ "node_modules/@better-auth/core/node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "license": "MIT",+ "peer": true,+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/@better-auth/telemetry": {+ "version": "1.4.17",+ "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.4.17.tgz",+ "integrity": "sha512-R1BC4e/bNjQbXu7lG6ubpgmsPj7IMqky5DvMlzAtnAJWJhh99pMh/n6w5gOHa0cqDZgEAuj75IPTxv+q3YiInA==",+ "peer": true,+ "dependencies": {+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.21"+ },+ "peerDependencies": {+ "@better-auth/core": "1.4.17"+ }+ },+ "node_modules/@better-auth/utils": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@better-auth/utils/-/utils-0.3.0.tgz",+ "integrity": "sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw==",+ "license": "MIT"+ },+ "node_modules/@better-fetch/fetch": {+ "version": "1.1.21",+ "resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.21.tgz",+ "integrity": "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="+ },+ "node_modules/@captchafox/react": {+ "version": "1.10.0",+ "resolved": "https://registry.npmjs.org/@captchafox/react/-/react-1.10.0.tgz",+ "integrity": "sha512-GRGdqZnz2KsJUXj17abe+V1kL1GhE3JsFgD0IkhZ6XVlr7IGJrnGWco1aID2jhFPunAtcdNuY+YuIEidtNNEpQ==",+ "license": "MIT",+ "dependencies": {+ "@captchafox/types": "^1.4.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0",+ "react-dom": ">=16.8.0"+ }+ },+ "node_modules/@captchafox/types": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/@captchafox/types/-/types-1.4.0.tgz",+ "integrity": "sha512-4xnPMICLinsXghw6zWEF436lhMsBmLxui2QmU7xAEz/+572BRdvc518Sz5OoofbJ7GZG6QPz/wOtJoN8BfKyCg==",+ "license": "MIT"+ },"node_modules/@derhuerst/http-basic": {"version": "8.2.4","resolved": "https://registry.npmjs.org/@derhuerst/http-basic/-/http-basic-8.2.4.tgz",@@ -1512,6 +1585,111 @@"node": "^18.18.0 || ^20.9.0 || >=21.1.0"}},+ "node_modules/@fastify/ajv-compiler": {+ "version": "3.6.0",+ "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-3.6.0.tgz",+ "integrity": "sha512-LwdXQJjmMD+GwLOkP7TVC68qa+pSSogeWWmznRJ/coyTcfe9qA05AHFSe1eZFwK6q+xVRpChnvFUkf1iYaSZsQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.11.0",+ "ajv-formats": "^2.1.1",+ "fast-uri": "^2.0.0"+ }+ },+ "node_modules/@fastify/ajv-compiler/node_modules/ajv": {+ "version": "8.17.1",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/@fastify/ajv-compiler/node_modules/ajv/node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/@fastify/ajv-compiler/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },+ "node_modules/@fastify/cors": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-9.0.1.tgz",+ "integrity": "sha512-YY9Ho3ovI+QHIL2hW+9X4XqQjXLjJqsU+sMV/xFsxZkE8p3GNnYVFpoOxF7SsP5ZL76gwvbo3V9L+FIekBGU4Q==",+ "license": "MIT",+ "dependencies": {+ "fastify-plugin": "^4.0.0",+ "mnemonist": "0.39.6"+ }+ },+ "node_modules/@fastify/error": {+ "version": "3.4.1",+ "resolved": "https://registry.npmjs.org/@fastify/error/-/error-3.4.1.tgz",+ "integrity": "sha512-wWSvph+29GR783IhmvdwWnN4bUxTD01Vm5Xad4i7i1VuAOItLvbPAb69sb0IQ2N57yprvhNIwAP5B6xfKTmjmQ==",+ "license": "MIT"+ },+ "node_modules/@fastify/fast-json-stringify-compiler": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/@fastify/fast-json-stringify-compiler/-/fast-json-stringify-compiler-4.3.0.tgz",+ "integrity": "sha512-aZAXGYo6m22Fk1zZzEUKBvut/CIIQe/BapEORnxiD5Qr0kPHqqI69NtEMCme74h+at72sPhbkb4ZrLd1W3KRLA==",+ "license": "MIT",+ "dependencies": {+ "fast-json-stringify": "^5.7.0"+ }+ },+ "node_modules/@fastify/merge-json-schemas": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/@fastify/merge-json-schemas/-/merge-json-schemas-0.1.1.tgz",+ "integrity": "sha512-fERDVz7topgNjtXsJTTW1JKLy0rhuLRcquYqNR9rF7OcVpCa2OVW49ZPDIhaRRCaUuvVxI+N416xUoF76HNSXA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3"+ }+ },+ "node_modules/@fastify/swagger": {+ "version": "8.15.0",+ "resolved": "https://registry.npmjs.org/@fastify/swagger/-/swagger-8.15.0.tgz",+ "integrity": "sha512-zy+HEEKFqPMS2sFUsQU5X0MHplhKJvWeohBwTCkBAJA/GDYGLGUWQaETEhptiqxK7Hs0fQB9B4MDb3pbwIiCwA==",+ "license": "MIT",+ "dependencies": {+ "fastify-plugin": "^4.0.0",+ "json-schema-resolver": "^2.0.0",+ "openapi-types": "^12.0.0",+ "rfdc": "^1.3.0",+ "yaml": "^2.2.2"+ }+ },+ "node_modules/@fastify/type-provider-typebox": {+ "version": "3.6.0",+ "resolved": "https://registry.npmjs.org/@fastify/type-provider-typebox/-/type-provider-typebox-3.6.0.tgz",+ "integrity": "sha512-HTeOLvirfGg0u1KGao3iXn5rZpYNqlrOmyDnXSXAbWVPa+mDQTTBNs/x5uZzOB6vFAqr0Xcf7x1lxOamNSYKjw==",+ "license": "MIT",+ "peerDependencies": {+ "@sinclair/typebox": ">=0.26 <=0.32"+ }+ },"node_modules/@floating-ui/core": {"version": "1.7.3","resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",@@ -1550,6 +1728,45 @@"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==","license": "MIT"},+ "node_modules/@hcaptcha/loader": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/@hcaptcha/loader/-/loader-2.3.0.tgz",+ "integrity": "sha512-i4lnNxKBe+COf3R1nFZEWaZoHIoJjvDgWqvcNrdZq8ehoSNMN6KVZ56dcQ02qKie2h3+BkbkwlJA9DOIuLlK/g==",+ "license": "MIT"+ },+ "node_modules/@hcaptcha/react-hcaptcha": {+ "version": "1.17.4",+ "resolved": "https://registry.npmjs.org/@hcaptcha/react-hcaptcha/-/react-hcaptcha-1.17.4.tgz",+ "integrity": "sha512-rIvgesG1N7SS9sAYYHFoWm+nXqRrxq7RcA9z2pKkDWV+S1GdfmrTNYA1aPyVWVe3eowphTCwyDJvl97Swwy0mw==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.17.9",+ "@hcaptcha/loader": "^2.3.0"+ },+ "peerDependencies": {+ "react": ">= 16.3.0",+ "react-dom": ">= 16.3.0"+ }+ },+ "node_modules/@hexagon/base64": {+ "version": "1.1.28",+ "resolved": "https://registry.npmjs.org/@hexagon/base64/-/base64-1.1.28.tgz",+ "integrity": "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@hookform/resolvers": {+ "version": "5.2.2",+ "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",+ "integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",+ "license": "MIT",+ "dependencies": {+ "@standard-schema/utils": "^0.3.0"+ },+ "peerDependencies": {+ "react-hook-form": "^7.55.0"+ }+ },"node_modules/@humanfs/core": {"version": "0.19.1","resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",@@ -1602,6 +1819,65 @@"url": "https://github.com/sponsors/nzakas"}},+ "node_modules/@instantdb/core": {+ "version": "0.22.114",+ "resolved": "https://registry.npmjs.org/@instantdb/core/-/core-0.22.114.tgz",+ "integrity": "sha512-IASWiEAeP4ny9atdX5qHgiiTSLjpMIJ9/r3a3cnFlE9u72YBzn8+Y52+Z7j2sZXk+eDscuKoQMUkV+4XJLWmxw==",+ "peer": true,+ "dependencies": {+ "@instantdb/version": "0.22.114",+ "mutative": "^1.0.10",+ "uuid": "^11.1.0"+ }+ },+ "node_modules/@instantdb/core/node_modules/uuid": {+ "version": "11.1.0",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",+ "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "peer": true,+ "bin": {+ "uuid": "dist/esm/bin/uuid"+ }+ },+ "node_modules/@instantdb/react": {+ "version": "0.22.114",+ "resolved": "https://registry.npmjs.org/@instantdb/react/-/react-0.22.114.tgz",+ "integrity": "sha512-7i4PoQzk6h7LPGzJJqR8GV/gRWdTOTD/VCnafwTj067yU+4oz8EQ346BvBGhYfiFJXY+9YBjMMx9DMmVOWWfmQ==",+ "peer": true,+ "dependencies": {+ "@instantdb/core": "0.22.114",+ "@instantdb/react-common": "0.22.114",+ "@instantdb/version": "0.22.114",+ "eventsource": "^4.0.0"+ },+ "peerDependencies": {+ "react": ">=16"+ }+ },+ "node_modules/@instantdb/react-common": {+ "version": "0.22.114",+ "resolved": "https://registry.npmjs.org/@instantdb/react-common/-/react-common-0.22.114.tgz",+ "integrity": "sha512-l9TSsZsmRKhQ/3Hd+pwS2KRsbVy++r/yDjrvbkcXFR/YN73lxl94jAXTf7wfMWHtFWurG2ODLQz1Mf4V6pssrA==",+ "peer": true,+ "dependencies": {+ "@instantdb/core": "0.22.114",+ "@instantdb/version": "0.22.114"+ },+ "peerDependencies": {+ "react": ">=16"+ }+ },+ "node_modules/@instantdb/version": {+ "version": "0.22.114",+ "resolved": "https://registry.npmjs.org/@instantdb/version/-/version-0.22.114.tgz",+ "integrity": "sha512-jcK4SqoxZ64XtvH7bKHukgMPlGN92eYiYl51rOAu/kbOPDCXF73I4XoaH4zumuTKO0V1IPjwEw4A/Jqt0X3XTw==",+ "peer": true+ },"node_modules/@isaacs/balanced-match": {"version": "4.0.1","resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz",@@ -1790,6 +2066,13 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@levischuck/tiny-cbor": {+ "version": "0.2.11",+ "resolved": "https://registry.npmjs.org/@levischuck/tiny-cbor/-/tiny-cbor-0.2.11.tgz",+ "integrity": "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==",+ "license": "MIT",+ "peer": true+ },"node_modules/@malept/cross-spawn-promise": {"version": "2.0.0","resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",@@ -1868,116 +2151,1618 @@"node": ">= 10.0.0"}},- "node_modules/@nornagon/put": {- "version": "0.0.8",- "resolved": "https://registry.npmjs.org/@nornagon/put/-/put-0.0.8.tgz",- "integrity": "sha512-ugvXJjwF5ldtUpa7D95kruNJ41yFQDEKyF5CW4TgKJnh+W/zmlBzXXeKTyqIgwMFrkePN2JqOBqcF0M0oOunow==",- "license": "MIT/X11",- "engines": {- "node": ">=0.3.0"+ "node_modules/@marsidev/react-turnstile": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/@marsidev/react-turnstile/-/react-turnstile-1.4.1.tgz",+ "integrity": "sha512-1jE0IjvB8z+q1NFRs3149gXzXwIzXQWqQjn9fmAr13BiE3RYLWck5Me6flHYE90shW5L12Jkm6R1peS1OnA9oQ==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^17.0.2 || ^18.0.0 || ^19.0",+ "react-dom": "^17.0.2 || ^18.0.0 || ^19.0"}},- "node_modules/@npmcli/agent": {- "version": "3.0.0",- "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz",- "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==",- "dev": true,- "license": "ISC",+ "node_modules/@neondatabase/auth": {+ "version": "0.1.0-beta.21",+ "resolved": "https://registry.npmjs.org/@neondatabase/auth/-/auth-0.1.0-beta.21.tgz",+ "integrity": "sha512-j1pMr/j5AawxB0K0FltyHzlfWTJ6hsSvqOKQQ5lL8fKpwvmrzD2i+BOQAfMiQm5C3IQ7fltSDuCDT6v43orkBQ==",+ "license": "Apache-2.0","dependencies": {- "agent-base": "^7.1.0",- "http-proxy-agent": "^7.0.0",- "https-proxy-agent": "^7.0.1",- "lru-cache": "^10.0.1",- "socks-proxy-agent": "^8.0.3"+ "@neondatabase/auth-ui": "0.1.0-alpha.11",+ "@supabase/auth-js": "2.79.0",+ "better-auth": "1.4.6",+ "jose": "6.1.2",+ "zod": "4.1.12"},- "engines": {- "node": "^18.17.0 || >=20.5.0"+ "funding": {+ "url": "https://neon.tech"+ },+ "peerDependencies": {+ "next": ">=16.0.6",+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ },+ "peerDependenciesMeta": {+ "next": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }}},- "node_modules/@npmcli/agent/node_modules/lru-cache": {- "version": "10.4.3",- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",- "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",- "dev": true,- "license": "ISC"- },- "node_modules/@npmcli/fs": {- "version": "4.0.0",- "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz",- "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==",- "dev": true,- "license": "ISC",+ "node_modules/@neondatabase/auth-ui": {+ "version": "0.1.0-alpha.11",+ "resolved": "https://registry.npmjs.org/@neondatabase/auth-ui/-/auth-ui-0.1.0-alpha.11.tgz",+ "integrity": "sha512-iSo4O+4mo6eeLQrk70p0LdYRjx2zgoVjx4rPjPzcNFb6/2tipxZdF6uwjO5cnRIZxZB56t63I4Bw8xdVnZNSzw==",+ "license": "Apache-2.0","dependencies": {- "semver": "^7.3.5"+ "@captchafox/react": "^1.10.0",+ "@daveyplate/better-auth-ui": "3.3.9",+ "@hcaptcha/react-hcaptcha": "^1.12.1",+ "@hookform/resolvers": "^5.2.2",+ "@marsidev/react-turnstile": ">=1.1.0",+ "@radix-ui/react-avatar": "^1.1.11",+ "@radix-ui/react-checkbox": "^1.3.3",+ "@radix-ui/react-context": "^1.1.3",+ "@radix-ui/react-dialog": "^1.1.15",+ "@radix-ui/react-dropdown-menu": "^2.1.16",+ "@radix-ui/react-label": "^2.1.8",+ "@radix-ui/react-primitive": "^2.1.4",+ "@radix-ui/react-select": "^2.2.6",+ "@radix-ui/react-separator": "^1.1.8",+ "@radix-ui/react-slot": "^1.2.4",+ "@radix-ui/react-tabs": "^1.1.13",+ "@radix-ui/react-use-callback-ref": "^1.1.1",+ "@radix-ui/react-use-layout-effect": "^1.1.1",+ "@wojtekmaj/react-recaptcha-v3": "^0.1.4",+ "class-variance-authority": "^0.7.1",+ "clsx": "^2.1.1",+ "input-otp": "^1.4.2",+ "lucide-react": "^0.555.0",+ "next-themes": "^0.4.6",+ "react-google-recaptcha": "^3.1.0",+ "react-hook-form": "^7.66.1",+ "react-qr-code": "^2.0.18",+ "sonner": "^2.0.7",+ "tailwind-merge": "^3.4.0",+ "tailwindcss": "^4.1.17",+ "tw-animate-css": "^1.4.0",+ "ua-parser-js": "^2.0.5",+ "vaul": "^1.1.2",+ "zod": "^4.1.12"},- "engines": {- "node": "^18.17.0 || >=20.5.0"+ "funding": {+ "url": "https://neon.tech"+ },+ "peerDependencies": {+ "@neondatabase/auth": ">=0.1.0-alpha.8",+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ },+ "peerDependenciesMeta": {+ "@neondatabase/auth": {+ "optional": false+ },+ "react": {+ "optional": false+ },+ "react-dom": {+ "optional": false+ }}},- "node_modules/@npmcli/fs/node_modules/semver": {- "version": "7.7.3",- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",- "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",- "dev": true,- "license": "ISC",- "bin": {- "semver": "bin/semver.js"+ "node_modules/@neondatabase/auth-ui/node_modules/@better-auth/passkey": {+ "version": "1.4.17",+ "resolved": "https://registry.npmjs.org/@better-auth/passkey/-/passkey-1.4.17.tgz",+ "integrity": "sha512-SmS7a3UYi9A0muo4fWx1wEn59vtjoOLBFD5PnRo330BcXro6mHWxG/IXtnOnyeQKNGnEp4X7/QXcRrW/nDH0Iw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@simplewebauthn/browser": "^13.1.2",+ "@simplewebauthn/server": "^13.1.2",+ "zod": "^4.3.5"},- "engines": {- "node": ">=10"+ "peerDependencies": {+ "@better-auth/core": "1.4.17",+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.21",+ "better-auth": "1.4.17",+ "better-call": "1.1.8",+ "nanostores": "^1.0.1"}},- "node_modules/@pkgjs/parseargs": {- "version": "0.11.0",- "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",- "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",- "dev": true,+ "node_modules/@neondatabase/auth-ui/node_modules/@daveyplate/better-auth-tanstack": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/@daveyplate/better-auth-tanstack/-/better-auth-tanstack-1.3.6.tgz",+ "integrity": "sha512-GvIGdbjRMZCEfAffU7LeWpGpie4vSli8V9jmNFCQOziZZMEFbO4cd53HBFmAushC9oEYIyhSNZBgV2ADzW94Ww==","license": "MIT",- "optional": true,- "engines": {- "node": ">=14"+ "peer": true,+ "peerDependencies": {+ "@tanstack/query-core": ">=5.65.0",+ "@tanstack/react-query": ">=5.65.0",+ "better-auth": ">=1.2.8",+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"}},- "node_modules/@radix-ui/number": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",- "integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",- "license": "MIT"- },- "node_modules/@radix-ui/primitive": {- "version": "1.1.3",- "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",- "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",- "license": "MIT"- },- "node_modules/@radix-ui/react-arrow": {- "version": "1.1.7",- "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",- "integrity": "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==",+ "node_modules/@neondatabase/auth-ui/node_modules/@daveyplate/better-auth-ui": {+ "version": "3.3.9",+ "resolved": "https://registry.npmjs.org/@daveyplate/better-auth-ui/-/better-auth-ui-3.3.9.tgz",+ "integrity": "sha512-bKUSytQmIaUwPd6hFcbZGiscCDhrh2BN10DZCR3QjsXpc0Wj2yBUcKQC2FKr8dUPZiUnWNt2ajIsEnaMXuKewA==","license": "MIT","dependencies": {- "@radix-ui/react-primitive": "2.1.3"+ "@better-fetch/fetch": "^1.1.21",+ "@hcaptcha/react-hcaptcha": "^1.17.1",+ "@noble/hashes": "^2.0.1",+ "@react-email/components": "^1.0.1",+ "@wojtekmaj/react-recaptcha-v3": "^0.1.4",+ "react-google-recaptcha": "^3.1.0",+ "react-qr-code": "^2.0.18",+ "ua-parser-js": "^2.0.7",+ "vaul": "^1.1.2"},+ "peerDependencies": {+ "@better-auth/passkey": ">=1.4.6",+ "@captchafox/react": "^1.10.0",+ "@daveyplate/better-auth-tanstack": "^1.3.6",+ "@hookform/resolvers": ">=5.2.0",+ "@instantdb/react": ">=0.18.0",+ "@marsidev/react-turnstile": ">=1.1.0",+ "@radix-ui/react-avatar": ">=1.1.0",+ "@radix-ui/react-checkbox": ">=1.1.0",+ "@radix-ui/react-context": ">=1.1.0",+ "@radix-ui/react-dialog": ">=1.1.0",+ "@radix-ui/react-dropdown-menu": ">=2.1.0",+ "@radix-ui/react-label": ">=2.1.0",+ "@radix-ui/react-primitive": ">=2.0.0",+ "@radix-ui/react-select": ">=2.2.0",+ "@radix-ui/react-separator": ">=1.1.0",+ "@radix-ui/react-slot": ">=1.1.0",+ "@radix-ui/react-tabs": ">=1.1.0",+ "@radix-ui/react-use-callback-ref": ">=1.1.0",+ "@radix-ui/react-use-layout-effect": ">=1.1.0",+ "@tanstack/react-query": ">=5.66.0",+ "@triplit/client": ">=1.0.0",+ "@triplit/react": ">=1.0.0",+ "better-auth": "^1.4.6",+ "class-variance-authority": ">=0.7.0",+ "clsx": ">=2.1.0",+ "input-otp": ">=1.4.0",+ "lucide-react": ">=0.469.0",+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0",+ "react-hook-form": ">=7.55.0",+ "sonner": ">=1.7.0",+ "tailwind-merge": ">=2.6.0",+ "tailwindcss": ">=3.0.0",+ "zod": ">=3.0.0"+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/@radix-ui/react-context": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.3.tgz",+ "integrity": "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw==",+ "license": "MIT","peerDependencies": {"@types/react": "*",- "@types/react-dom": "*",- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",- "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"},"peerDependenciesMeta": {"@types/react": {"optional": true- },- "@types/react-dom": {- "optional": true}}},- "node_modules/@radix-ui/react-collection": {- "version": "1.1.7",- "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",- "integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",- "license": "MIT",+ "node_modules/@neondatabase/auth-ui/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/better-auth": {+ "version": "1.4.17",+ "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.4.17.tgz",+ "integrity": "sha512-VmHGQyKsEahkEs37qguROKg/6ypYpNF13D7v/lkbO7w7Aivz0Bv2h+VyUkH4NzrGY0QBKXi1577mGhDCVwp0ew==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@better-auth/core": "1.4.17",+ "@better-auth/telemetry": "1.4.17",+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.21",+ "@noble/ciphers": "^2.0.0",+ "@noble/hashes": "^2.0.0",+ "better-call": "1.1.8",+ "defu": "^6.1.4",+ "jose": "^6.1.0",+ "kysely": "^0.28.5",+ "nanostores": "^1.0.1",+ "zod": "^4.3.5"+ },+ "peerDependencies": {+ "@lynx-js/react": "*",+ "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0",+ "@sveltejs/kit": "^2.0.0",+ "@tanstack/react-start": "^1.0.0",+ "@tanstack/solid-start": "^1.0.0",+ "better-sqlite3": "^12.0.0",+ "drizzle-kit": ">=0.31.4",+ "drizzle-orm": ">=0.41.0",+ "mongodb": "^6.0.0 || ^7.0.0",+ "mysql2": "^3.0.0",+ "next": "^14.0.0 || ^15.0.0 || ^16.0.0",+ "pg": "^8.0.0",+ "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0",+ "solid-js": "^1.0.0",+ "svelte": "^4.0.0 || ^5.0.0",+ "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0",+ "vue": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "@lynx-js/react": {+ "optional": true+ },+ "@prisma/client": {+ "optional": true+ },+ "@sveltejs/kit": {+ "optional": true+ },+ "@tanstack/react-start": {+ "optional": true+ },+ "@tanstack/solid-start": {+ "optional": true+ },+ "better-sqlite3": {+ "optional": true+ },+ "drizzle-kit": {+ "optional": true+ },+ "drizzle-orm": {+ "optional": true+ },+ "mongodb": {+ "optional": true+ },+ "mysql2": {+ "optional": true+ },+ "next": {+ "optional": true+ },+ "pg": {+ "optional": true+ },+ "prisma": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ },+ "solid-js": {+ "optional": true+ },+ "svelte": {+ "optional": true+ },+ "vitest": {+ "optional": true+ },+ "vue": {+ "optional": true+ }+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/better-sqlite3": {+ "version": "12.6.2",+ "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.6.2.tgz",+ "integrity": "sha512-8VYKM3MjCa9WcaSAI3hzwhmyHVlH8tiGFwf0RlTsZPWJ1I5MkzjiudCo4KC4DxOaL/53A5B1sI/IbldNFDbsKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "bindings": "^1.5.0",+ "prebuild-install": "^7.1.1"+ },+ "engines": {+ "node": "20.x || 22.x || 23.x || 24.x || 25.x"+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/lucide-react": {+ "version": "0.555.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.555.0.tgz",+ "integrity": "sha512-D8FvHUGbxWBRQM90NZeIyhAvkFfsh3u9ekrMvJ30Z6gnpBHS6HC6ldLg7tL45hwiIz/u66eKDtdA23gwwGsAHA==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/pg": {+ "version": "8.17.2",+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.17.2.tgz",+ "integrity": "sha512-vjbKdiBJRqzcYw1fNU5KuHyYvdJ1qpcQg1CeBrHFqV1pWgHeVR6j/+kX0E1AAXfyuLUGY1ICrN2ELKA/z2HWzw==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "pg-connection-string": "^2.10.1",+ "pg-pool": "^3.11.0",+ "pg-protocol": "^1.11.0",+ "pg-types": "2.2.0",+ "pgpass": "1.0.5"+ },+ "engines": {+ "node": ">= 16.0.0"+ },+ "optionalDependencies": {+ "pg-cloudflare": "^1.3.0"+ },+ "peerDependencies": {+ "pg-native": ">=3.0.1"+ },+ "peerDependenciesMeta": {+ "pg-native": {+ "optional": true+ }+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/pg-pool": {+ "version": "3.11.0",+ "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.11.0.tgz",+ "integrity": "sha512-MJYfvHwtGp870aeusDh+hg9apvOe2zmpZJpyt+BMtzUWlVqbhFmMK6bOBXLBUPd7iRtIF9fZplDc7KrPN3PN7w==",+ "license": "MIT",+ "optional": true,+ "peer": true,+ "peerDependencies": {+ "pg": ">=8.0"+ }+ },+ "node_modules/@neondatabase/auth-ui/node_modules/pg-protocol": {+ "version": "1.11.0",+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.11.0.tgz",+ "integrity": "sha512-pfsxk2M9M3BuGgDOfuy37VNRRX3jmKgMjcvAcWqNDpZSf4cUmv8HSOl5ViRQFsfARFn0KuUQTgLxVMbNq5NW3g==",+ "license": "MIT",+ "optional": true,+ "peer": true+ },+ "node_modules/@neondatabase/auth-ui/node_modules/zod": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",+ "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/@neondatabase/auth/node_modules/@better-fetch/fetch": {+ "version": "1.1.18",+ "resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.18.tgz",+ "integrity": "sha512-rEFOE1MYIsBmoMJtQbl32PGHHXuG2hDxvEd7rUHE0vCBoFQVSDqaVs9hkZEtHCxRoY+CljXKFCOuJ8uxqw1LcA=="+ },+ "node_modules/@neondatabase/auth/node_modules/better-auth": {+ "version": "1.4.6",+ "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.4.6.tgz",+ "integrity": "sha512-5wEBzjolrQA26b4uT6FVVYICsE3SmE/MzrZtl8cb2a3TJtswpP8v3OVV5yTso+ef9z85swgZk0/qBzcULFWVtA==",+ "license": "MIT",+ "dependencies": {+ "@better-auth/core": "1.4.6",+ "@better-auth/telemetry": "1.4.6",+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.18",+ "@noble/ciphers": "^2.0.0",+ "@noble/hashes": "^2.0.0",+ "better-call": "1.1.5",+ "defu": "^6.1.4",+ "jose": "^6.1.0",+ "kysely": "^0.28.5",+ "ms": "4.0.0-nightly.202508271359",+ "nanostores": "^1.0.1",+ "zod": "^4.1.12"+ },+ "peerDependencies": {+ "@lynx-js/react": "*",+ "@sveltejs/kit": "^2.0.0",+ "@tanstack/react-start": "^1.0.0",+ "next": "^14.0.0 || ^15.0.0 || ^16.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0",+ "solid-js": "^1.0.0",+ "svelte": "^4.0.0 || ^5.0.0",+ "vue": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "@lynx-js/react": {+ "optional": true+ },+ "@sveltejs/kit": {+ "optional": true+ },+ "@tanstack/react-start": {+ "optional": true+ },+ "next": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ },+ "solid-js": {+ "optional": true+ },+ "svelte": {+ "optional": true+ },+ "vue": {+ "optional": true+ }+ }+ },+ "node_modules/@neondatabase/auth/node_modules/better-auth/node_modules/@better-auth/core": {+ "version": "1.4.6",+ "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.4.6.tgz",+ "integrity": "sha512-cYjscr4wU5ZJPhk86JuUkecJT+LSYCFmUzYaitiLkizl+wCr1qdPFSEoAnRVZVTUEEoKpeS2XW69voBJ1NoB3g==",+ "dependencies": {+ "@standard-schema/spec": "^1.0.0",+ "zod": "^4.1.12"+ },+ "peerDependencies": {+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.18",+ "better-call": "1.1.5",+ "jose": "^6.1.0",+ "kysely": "^0.28.5",+ "nanostores": "^1.0.1"+ }+ },+ "node_modules/@neondatabase/auth/node_modules/better-auth/node_modules/@better-auth/telemetry": {+ "version": "1.4.6",+ "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.4.6.tgz",+ "integrity": "sha512-idc9MGJXxWA7zl2U9zsbdG6+2ZCeqWdPq1KeFSfyqGMFtI1VPQOx9YWLqNPOt31YnOX77ojZSraU2sb7IRdBMA==",+ "dependencies": {+ "@better-auth/utils": "0.3.0",+ "@better-fetch/fetch": "1.1.18"+ },+ "peerDependencies": {+ "@better-auth/core": "1.4.6"+ }+ },+ "node_modules/@neondatabase/auth/node_modules/better-auth/node_modules/better-call": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/better-call/-/better-call-1.1.5.tgz",+ "integrity": "sha512-nQJ3S87v6wApbDwbZ++FrQiSiVxWvZdjaO+2v6lZJAG2WWggkB2CziUDjPciz3eAt9TqfRursIQMZIcpkBnvlw==",+ "license": "MIT",+ "dependencies": {+ "@better-auth/utils": "^0.3.0",+ "@better-fetch/fetch": "^1.1.4",+ "rou3": "^0.7.10",+ "set-cookie-parser": "^2.7.1"+ },+ "peerDependencies": {+ "zod": "^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },+ "node_modules/@neondatabase/auth/node_modules/ms": {+ "version": "4.0.0-nightly.202508271359",+ "resolved": "https://registry.npmjs.org/ms/-/ms-4.0.0-nightly.202508271359.tgz",+ "integrity": "sha512-WC/Eo7NzFrOV/RRrTaI0fxKVbNCzEy76j2VqNV8SxDf9D69gSE2Lh0QwYvDlhiYmheBYExAvEAxVf5NoN0cj2A==",+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@neondatabase/neon-js": {+ "version": "0.1.0-beta.22",+ "resolved": "https://registry.npmjs.org/@neondatabase/neon-js/-/neon-js-0.1.0-beta.22.tgz",+ "integrity": "sha512-APKSu8nvQ3FDPPZGoQbiIBavc3ZtFsg3trzEGmb8wEOOesEjTJcKSEYwlSCnM89KUhZ0Bw+rbyUlFES9Vnzdyg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@neondatabase/auth": "0.1.0-beta.21",+ "@neondatabase/postgrest-js": "0.1.0-alpha.2",+ "@supabase/postgres-meta": "0.93.1",+ "meow": "14.0.0",+ "zod": "4.1.12"+ },+ "bin": {+ "neon-js": "dist/cli/index.mjs"+ },+ "funding": {+ "url": "https://neon.tech"+ }+ },+ "node_modules/@neondatabase/postgrest-js": {+ "version": "0.1.0-alpha.2",+ "resolved": "https://registry.npmjs.org/@neondatabase/postgrest-js/-/postgrest-js-0.1.0-alpha.2.tgz",+ "integrity": "sha512-fE3Kd6Tj3uUVx6jvDUA3USW4gZaSAL0NoGePFg31xDfBbmS2EBpdboKUnac8rJVajUiCDQPj6/j4G1eXOleYsg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@supabase/postgrest-js": "2.79.0"+ },+ "funding": {+ "url": "https://neon.tech"+ }+ },+ "node_modules/@noble/ciphers": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.1.1.tgz",+ "integrity": "sha512-bysYuiVfhxNJuldNXlFEitTVdNnYUc+XNJZd7Qm2a5j1vZHgY+fazadNFWFaMK/2vye0JVlxV3gHmC0WDfAOQw==",+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@noble/hashes": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz",+ "integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==",+ "license": "MIT",+ "engines": {+ "node": ">= 20.19.0"+ },+ "funding": {+ "url": "https://paulmillr.com/funding/"+ }+ },+ "node_modules/@nornagon/put": {+ "version": "0.0.8",+ "resolved": "https://registry.npmjs.org/@nornagon/put/-/put-0.0.8.tgz",+ "integrity": "sha512-ugvXJjwF5ldtUpa7D95kruNJ41yFQDEKyF5CW4TgKJnh+W/zmlBzXXeKTyqIgwMFrkePN2JqOBqcF0M0oOunow==",+ "license": "MIT/X11",+ "engines": {+ "node": ">=0.3.0"+ }+ },+ "node_modules/@npmcli/agent": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@npmcli/agent/-/agent-3.0.0.tgz",+ "integrity": "sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "agent-base": "^7.1.0",+ "http-proxy-agent": "^7.0.0",+ "https-proxy-agent": "^7.0.1",+ "lru-cache": "^10.0.1",+ "socks-proxy-agent": "^8.0.3"+ },+ "engines": {+ "node": "^18.17.0 || >=20.5.0"+ }+ },+ "node_modules/@npmcli/agent/node_modules/lru-cache": {+ "version": "10.4.3",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/@npmcli/fs": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-4.0.0.tgz",+ "integrity": "sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "semver": "^7.3.5"+ },+ "engines": {+ "node": "^18.17.0 || >=20.5.0"+ }+ },+ "node_modules/@npmcli/fs/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "dev": true,+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@opentelemetry/api": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",+ "integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8.0.0"+ }+ },+ "node_modules/@opentelemetry/api-logs": {+ "version": "0.57.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.57.2.tgz",+ "integrity": "sha512-uIX52NnTM0iBh84MShlpouI7UKqkZ7MrUszTmaypHBu4r7NofznSnQRfJ+uUeDtQDj6w8eFGg5KBLDAwAPz1+A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api": "^1.3.0"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/context-async-hooks": {+ "version": "1.30.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-1.30.1.tgz",+ "integrity": "sha512-s5vvxXPVdjqS3kTLKMeBMvop9hbWkwzBpu+mUO2M7sZtlkyDJGwFe33wRKnbaYDo8ExRVBIIdwIGrqpxHuKttA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/core": {+ "version": "1.30.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz",+ "integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/semantic-conventions": "1.28.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/core/node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz",+ "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/instrumentation": {+ "version": "0.57.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.57.2.tgz",+ "integrity": "sha512-BdBGhQBh8IjZ2oIIX6F2/Q3LKm/FDDKi6ccYKcBTeilh6SNdNKveDOLk73BkSJjQLJk6qe4Yh+hHw1UPhCDdrg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/api-logs": "0.57.2",+ "@types/shimmer": "^1.2.0",+ "import-in-the-middle": "^1.8.1",+ "require-in-the-middle": "^7.1.1",+ "semver": "^7.5.2",+ "shimmer": "^1.2.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-amqplib": {+ "version": "0.46.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.46.1.tgz",+ "integrity": "sha512-AyXVnlCf/xV3K/rNumzKxZqsULyITJH6OVLiW6730JPRqWA7Zc9bvYoVNpN6iOpTU8CasH34SU/ksVJmObFibQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-connect": {+ "version": "0.43.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.43.1.tgz",+ "integrity": "sha512-ht7YGWQuV5BopMcw5Q2hXn3I8eG8TH0J/kc/GMcW4CuNTgiP6wCu44BOnucJWL3CmFWaRHI//vWyAhaC8BwePw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0",+ "@types/connect": "3.4.38"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-dataloader": {+ "version": "0.16.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.16.1.tgz",+ "integrity": "sha512-K/qU4CjnzOpNkkKO4DfCLSQshejRNAJtd4esgigo/50nxCB6XCyi1dhAblUHM9jG5dRm8eu0FB+t87nIo99LYQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-express": {+ "version": "0.47.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.47.1.tgz",+ "integrity": "sha512-QNXPTWteDclR2B4pDFpz0TNghgB33UMjUt14B+BZPmtH1MwUFAfLHBaP5If0Z5NZC+jaH8oF2glgYjrmhZWmSw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-fs": {+ "version": "0.19.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.19.1.tgz",+ "integrity": "sha512-6g0FhB3B9UobAR60BGTcXg4IHZ6aaYJzp0Ki5FhnxyAPt8Ns+9SSvgcrnsN2eGmk3RWG5vYycUGOEApycQL24A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-generic-pool": {+ "version": "0.43.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.43.1.tgz",+ "integrity": "sha512-M6qGYsp1cURtvVLGDrPPZemMFEbuMmCXgQYTReC/IbimV5sGrLBjB+/hANUpRZjX67nGLdKSVLZuQQAiNz+sww==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-graphql": {+ "version": "0.47.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.47.1.tgz",+ "integrity": "sha512-EGQRWMGqwiuVma8ZLAZnExQ7sBvbOx0N/AE/nlafISPs8S+QtXX+Viy6dcQwVWwYHQPAcuY3bFt3xgoAwb4ZNQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-hapi": {+ "version": "0.45.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.45.2.tgz",+ "integrity": "sha512-7Ehow/7Wp3aoyCrZwQpU7a2CnoMq0XhIcioFuKjBb0PLYfBfmTsFTUyatlHu0fRxhwcRsSQRTvEhmZu8CppBpQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-http": {+ "version": "0.57.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.57.2.tgz",+ "integrity": "sha512-1Uz5iJ9ZAlFOiPuwYg29Bf7bJJc/GeoeJIFKJYQf67nTVKFe8RHbEtxgkOmK4UGZNHKXcpW4P8cWBYzBn1USpg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "1.30.1",+ "@opentelemetry/instrumentation": "0.57.2",+ "@opentelemetry/semantic-conventions": "1.28.0",+ "forwarded-parse": "2.1.2",+ "semver": "^7.5.2"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz",+ "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/instrumentation-http/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@opentelemetry/instrumentation-ioredis": {+ "version": "0.47.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.47.1.tgz",+ "integrity": "sha512-OtFGSN+kgk/aoKgdkKQnBsQFDiG8WdCxu+UrHr0bXScdAmtSzLSraLo7wFIb25RVHfRWvzI5kZomqJYEg/l1iA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/redis-common": "^0.36.2",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-kafkajs": {+ "version": "0.7.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.7.1.tgz",+ "integrity": "sha512-OtjaKs8H7oysfErajdYr1yuWSjMAectT7Dwr+axIoZqT9lmEOkD/H/3rgAs8h/NIuEi2imSXD+vL4MZtOuJfqQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-knex": {+ "version": "0.44.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.44.1.tgz",+ "integrity": "sha512-U4dQxkNhvPexffjEmGwCq68FuftFK15JgUF05y/HlK3M6W/G2iEaACIfXdSnwVNe9Qh0sPfw8LbOPxrWzGWGMQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-koa": {+ "version": "0.47.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.47.1.tgz",+ "integrity": "sha512-l/c+Z9F86cOiPJUllUCt09v+kICKvT+Vg1vOAJHtHPsJIzurGayucfCMq2acd/A/yxeNWunl9d9eqZ0G+XiI6A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-lru-memoizer": {+ "version": "0.44.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.44.1.tgz",+ "integrity": "sha512-5MPkYCvG2yw7WONEjYj5lr5JFehTobW7wX+ZUFy81oF2lr9IPfZk9qO+FTaM0bGEiymwfLwKe6jE15nHn1nmHg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-mongodb": {+ "version": "0.52.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.52.0.tgz",+ "integrity": "sha512-1xmAqOtRUQGR7QfJFfGV/M2kC7wmI2WgZdpru8hJl3S0r4hW0n3OQpEHlSGXJAaNFyvT+ilnwkT+g5L4ljHR6g==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-mongoose": {+ "version": "0.46.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.46.1.tgz",+ "integrity": "sha512-3kINtW1LUTPkiXFRSSBmva1SXzS/72we/jL22N+BnF3DFcoewkdkHPYOIdAAk9gSicJ4d5Ojtt1/HeibEc5OQg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-mysql": {+ "version": "0.45.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.45.1.tgz",+ "integrity": "sha512-TKp4hQ8iKQsY7vnp/j0yJJ4ZsP109Ht6l4RHTj0lNEG1TfgTrIH5vJMbgmoYXWzNHAqBH2e7fncN12p3BP8LFg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0",+ "@types/mysql": "2.15.26"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-mysql2": {+ "version": "0.45.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.45.2.tgz",+ "integrity": "sha512-h6Ad60FjCYdJZ5DTz1Lk2VmQsShiViKe0G7sYikb0GHI0NVvApp2XQNRHNjEMz87roFttGPLHOYVPlfy+yVIhQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0",+ "@opentelemetry/sql-common": "^0.40.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-pg": {+ "version": "0.51.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.51.1.tgz",+ "integrity": "sha512-QxgjSrxyWZc7Vk+qGSfsejPVFL1AgAJdSBMYZdDUbwg730D09ub3PXScB9d04vIqPriZ+0dqzjmQx0yWKiCi2Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.26.0",+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0",+ "@opentelemetry/sql-common": "^0.40.1",+ "@types/pg": "8.6.1",+ "@types/pg-pool": "2.0.6"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-redis-4": {+ "version": "0.46.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis-4/-/instrumentation-redis-4-0.46.1.tgz",+ "integrity": "sha512-UMqleEoabYMsWoTkqyt9WAzXwZ4BlFZHO40wr3d5ZvtjKCHlD4YXLm+6OLCeIi/HkX7EXvQaz8gtAwkwwSEvcQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/redis-common": "^0.36.2",+ "@opentelemetry/semantic-conventions": "^1.27.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-tedious": {+ "version": "0.18.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.18.1.tgz",+ "integrity": "sha512-5Cuy/nj0HBaH+ZJ4leuD7RjgvA844aY2WW+B5uLcWtxGjRZl3MNLuxnNg5DYWZNPO+NafSSnra0q49KWAHsKBg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.57.1",+ "@opentelemetry/semantic-conventions": "^1.27.0",+ "@types/tedious": "^4.0.14"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.3.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation-undici": {+ "version": "0.10.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.10.1.tgz",+ "integrity": "sha512-rkOGikPEyRpMCmNu9AQuV5dtRlDmJp2dK5sw8roVshAGoB6hH/3QjDtRhdwd75SsJwgynWUNRUYe0wAkTo16tQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.8.0",+ "@opentelemetry/instrumentation": "^0.57.1"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.7.0"+ }+ },+ "node_modules/@opentelemetry/instrumentation/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@opentelemetry/redis-common": {+ "version": "0.36.2",+ "resolved": "https://registry.npmjs.org/@opentelemetry/redis-common/-/redis-common-0.36.2.tgz",+ "integrity": "sha512-faYX1N0gpLhej/6nyp6bgRjzAKXn5GOEMYY7YhciSfCoITAktLUtQ36d24QEWNA1/WA1y6qQunCe0OhHRkVl9g==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/resources": {+ "version": "1.30.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.30.1.tgz",+ "integrity": "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "1.30.1",+ "@opentelemetry/semantic-conventions": "1.28.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/resources/node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz",+ "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/sdk-trace-base": {+ "version": "1.30.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.30.1.tgz",+ "integrity": "sha512-jVPgBbH1gCy2Lb7X0AVQ8XAfgg0pJ4nvl8/IiQA6nxOsPvS+0zMJaFSs2ltXe0J6C8dqjcnpyqINDJmU30+uOg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "1.30.1",+ "@opentelemetry/resources": "1.30.1",+ "@opentelemetry/semantic-conventions": "1.28.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": ">=1.0.0 <1.10.0"+ }+ },+ "node_modules/@opentelemetry/sdk-trace-base/node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.28.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz",+ "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/semantic-conventions": {+ "version": "1.39.0",+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.39.0.tgz",+ "integrity": "sha512-R5R9tb2AXs2IRLNKLBJDynhkfmx7mX0vi8NkhZb3gUkPWHn6HXk5J8iQ/dql0U3ApfWym4kXXmBDRGO+oeOfjg==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@opentelemetry/sql-common": {+ "version": "0.40.1",+ "resolved": "https://registry.npmjs.org/@opentelemetry/sql-common/-/sql-common-0.40.1.tgz",+ "integrity": "sha512-nSDlnHSqzC3pXn/wZEZVLuAuJ1MYMXPBwtv2qAbCa3847SaHItdE7SzUq/Jtb0KZmh1zfAbNi3AAMjztTT4Ugg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/core": "^1.1.0"+ },+ "engines": {+ "node": ">=14"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.1.0"+ }+ },+ "node_modules/@peculiar/asn1-android": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-android/-/asn1-android-2.6.0.tgz",+ "integrity": "sha512-cBRCKtYPF7vJGN76/yG8VbxRcHLPF3HnkoHhKOZeHpoVtbMYfY9ROKtH3DtYUY9m8uI1Mh47PRhHf2hSK3xcSQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-cms": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.0.tgz",+ "integrity": "sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "@peculiar/asn1-x509-attr": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-csr": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.6.0.tgz",+ "integrity": "sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-ecc": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.6.0.tgz",+ "integrity": "sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-pfx": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.0.tgz",+ "integrity": "sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-cms": "^2.6.0",+ "@peculiar/asn1-pkcs8": "^2.6.0",+ "@peculiar/asn1-rsa": "^2.6.0",+ "@peculiar/asn1-schema": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-pkcs8": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.0.tgz",+ "integrity": "sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-pkcs9": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.0.tgz",+ "integrity": "sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-cms": "^2.6.0",+ "@peculiar/asn1-pfx": "^2.6.0",+ "@peculiar/asn1-pkcs8": "^2.6.0",+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "@peculiar/asn1-x509-attr": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-rsa": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.0.tgz",+ "integrity": "sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-schema": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.6.0.tgz",+ "integrity": "sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "asn1js": "^3.0.6",+ "pvtsutils": "^1.3.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-x509": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.0.tgz",+ "integrity": "sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "asn1js": "^3.0.6",+ "pvtsutils": "^1.3.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/asn1-x509-attr": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.0.tgz",+ "integrity": "sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "asn1js": "^3.0.6",+ "tslib": "^2.8.1"+ }+ },+ "node_modules/@peculiar/x509": {+ "version": "1.14.3",+ "resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",+ "integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@peculiar/asn1-cms": "^2.6.0",+ "@peculiar/asn1-csr": "^2.6.0",+ "@peculiar/asn1-ecc": "^2.6.0",+ "@peculiar/asn1-pkcs9": "^2.6.0",+ "@peculiar/asn1-rsa": "^2.6.0",+ "@peculiar/asn1-schema": "^2.6.0",+ "@peculiar/asn1-x509": "^2.6.0",+ "pvtsutils": "^1.3.6",+ "reflect-metadata": "^0.2.2",+ "tslib": "^2.8.1",+ "tsyringe": "^4.10.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@pgsql/types": {+ "version": "13.11.1",+ "resolved": "https://registry.npmjs.org/@pgsql/types/-/types-13.11.1.tgz",+ "integrity": "sha512-5JeN7DZYCVbxPPFI47Z370Jzr3eHZpqgwCdutYWV8e8XtuhxF7UuvWvOsx2oPJe9KnQen0vzJWnVq/61bRvxmw==",+ "license": "SEE LICENSE IN LICENSE"+ },+ "node_modules/@pinojs/redact": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",+ "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==",+ "license": "MIT"+ },+ "node_modules/@pkgjs/parseargs": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",+ "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/@prisma/instrumentation": {+ "version": "6.11.1",+ "resolved": "https://registry.npmjs.org/@prisma/instrumentation/-/instrumentation-6.11.1.tgz",+ "integrity": "sha512-mrZOev24EDhnefmnZX7WVVT7v+r9LttPRqf54ONvj6re4XMF7wFTpK2tLJi4XHB7fFp/6xhYbgRel8YV7gQiyA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@opentelemetry/instrumentation": "^0.52.0 || ^0.53.0 || ^0.54.0 || ^0.55.0 || ^0.56.0 || ^0.57.0"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.8"+ }+ },+ "node_modules/@radix-ui/number": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",+ "integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/primitive": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",+ "integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",+ "license": "MIT"+ },+ "node_modules/@radix-ui/react-accordion": {+ "version": "1.2.12",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.2.12.tgz",+ "integrity": "sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-collapsible": "1.1.12",+ "@radix-ui/react-collection": "1.1.7",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-direction": "1.1.1",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-arrow": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",+ "integrity": "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.3"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-avatar": {+ "version": "1.1.11",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.1.11.tgz",+ "integrity": "sha512-0Qk603AHGV28BOBO34p7IgD5m+V5Sg/YovfayABkoDDBM5d3NCx0Mp4gGrjzLGes1jV5eNOE1r3itqOR33VC6Q==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-context": "1.1.3",+ "@radix-ui/react-primitive": "2.1.4",+ "@radix-ui/react-use-callback-ref": "1.1.1",+ "@radix-ui/react-use-is-hydrated": "0.1.0",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-context": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context/-/react-context-1.1.3.tgz",+ "integrity": "sha512-ieIFACdMpYfMEjF0rEf5KLvfVyIkOz6PDGyNnP+u+4xQ6jny3VCgA4OgXOwNx2aUkxn8zx9fiVcM8CfFYv9Lxw==",+ "license": "MIT",+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-avatar/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-checkbox": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz",+ "integrity": "sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-previous": "1.1.1",+ "@radix-ui/react-use-size": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collapsible": {+ "version": "1.1.12",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz",+ "integrity": "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/primitive": "1.1.3",+ "@radix-ui/react-compose-refs": "1.1.2",+ "@radix-ui/react-context": "1.1.2",+ "@radix-ui/react-id": "1.1.1",+ "@radix-ui/react-presence": "1.1.5",+ "@radix-ui/react-primitive": "2.1.3",+ "@radix-ui/react-use-controllable-state": "1.2.2",+ "@radix-ui/react-use-layout-effect": "1.1.1"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-collection": {+ "version": "1.1.7",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",+ "integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",+ "license": "MIT","dependencies": {"@radix-ui/react-compose-refs": "1.1.2","@radix-ui/react-context": "1.1.2",@@ -2609,6 +4394,52 @@}}},+ "node_modules/@radix-ui/react-separator": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.8.tgz",+ "integrity": "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-primitive": "2.1.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/react-separator/node_modules/@radix-ui/react-primitive": {+ "version": "2.1.4",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",+ "integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-slot": "1.2.4"+ },+ "peerDependencies": {+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-slot": {"version": "1.2.4","resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz",@@ -2727,6 +4558,24 @@}}},+ "node_modules/@radix-ui/react-use-is-hydrated": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-is-hydrated/-/react-use-is-hydrated-0.1.0.tgz",+ "integrity": "sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.5.0"+ },+ "peerDependencies": {+ "@types/react": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@radix-ui/react-use-layout-effect": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@radix-ui/react-use-layout-effect/-/react-use-layout-effect-1.1.1.tgz",@@ -2802,25 +4651,356 @@"@radix-ui/react-primitive": "2.1.3"},"peerDependencies": {- "@types/react": "*",- "@types/react-dom": "*",- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",- "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ "@types/react": "*",+ "@types/react-dom": "*",+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@radix-ui/rect": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",+ "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",+ "license": "MIT"+ },+ "node_modules/@react-email/body": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/@react-email/body/-/body-0.2.1.tgz",+ "integrity": "sha512-ljDiQiJDu/Fq//vSIIP0z5Nuvt4+DX1RqGasstChDGJB/14ogd4VdNS9aacoede/ZjGy3o3Qb+cxyS+XgM6SwQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/button": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/@react-email/button/-/button-0.2.1.tgz",+ "integrity": "sha512-qXyj7RZLE7POy9BMKSoqQ00tOXThjOZSUnI2Yu9i29IHngPlmrNayIWBoVKtElES7OWwypUcpiajwi1mUWx6/A==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/code-block": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/@react-email/code-block/-/code-block-0.2.1.tgz",+ "integrity": "sha512-M3B7JpVH4ytgn83/ujRR1k1DQHvTeABiDM61OvAbjLRPhC/5KLHU5KkzIbbuGIrjWwxAbL1kSQzU8MhLEtSxyw==",+ "license": "MIT",+ "dependencies": {+ "prismjs": "^1.30.0"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/code-inline": {+ "version": "0.0.6",+ "resolved": "https://registry.npmjs.org/@react-email/code-inline/-/code-inline-0.0.6.tgz",+ "integrity": "sha512-jfhebvv3dVsp3OdPgKXnk8+e2pBiDVZejDOBFzBa/IblrAJ9cQDkN6rBD5IyEg8hTOxwbw3iaI/yZFmDmIguIA==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/column": {+ "version": "0.0.14",+ "resolved": "https://registry.npmjs.org/@react-email/column/-/column-0.0.14.tgz",+ "integrity": "sha512-f+W+Bk2AjNO77zynE33rHuQhyqVICx4RYtGX9NKsGUg0wWjdGP0qAuIkhx9Rnmk4/hFMo1fUrtYNqca9fwJdHg==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/components": {+ "version": "1.0.6",+ "resolved": "https://registry.npmjs.org/@react-email/components/-/components-1.0.6.tgz",+ "integrity": "sha512-3GwOeq+5yyiAcwSf7TnHi/HWKn22lXbwxQmkkAviSwZLlhsRVxvmWqRxvUVfQk/HclDUG+62+sGz9qjfb2Uxjw==",+ "license": "MIT",+ "dependencies": {+ "@react-email/body": "0.2.1",+ "@react-email/button": "0.2.1",+ "@react-email/code-block": "0.2.1",+ "@react-email/code-inline": "0.0.6",+ "@react-email/column": "0.0.14",+ "@react-email/container": "0.0.16",+ "@react-email/font": "0.0.10",+ "@react-email/head": "0.0.13",+ "@react-email/heading": "0.0.16",+ "@react-email/hr": "0.0.12",+ "@react-email/html": "0.0.12",+ "@react-email/img": "0.0.12",+ "@react-email/link": "0.0.13",+ "@react-email/markdown": "0.0.18",+ "@react-email/preview": "0.0.14",+ "@react-email/render": "2.0.4",+ "@react-email/row": "0.0.13",+ "@react-email/section": "0.0.17",+ "@react-email/tailwind": "2.0.3",+ "@react-email/text": "0.1.6"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/container": {+ "version": "0.0.16",+ "resolved": "https://registry.npmjs.org/@react-email/container/-/container-0.0.16.tgz",+ "integrity": "sha512-QWBB56RkkU0AJ9h+qy33gfT5iuZknPC7Un/IjZv9B0QmMIK+WWacc0cH6y2SV5Cv/b99hU94fjEMOOO4enpkbQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/font": {+ "version": "0.0.10",+ "resolved": "https://registry.npmjs.org/@react-email/font/-/font-0.0.10.tgz",+ "integrity": "sha512-0urVSgCmQIfx5r7Xc586miBnQUVnGp3OTYUm8m5pwtQRdTRO5XrTtEfNJ3JhYhSOruV0nD8fd+dXtKXobum6tA==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/head": {+ "version": "0.0.13",+ "resolved": "https://registry.npmjs.org/@react-email/head/-/head-0.0.13.tgz",+ "integrity": "sha512-AJg6le/08Gz4tm+6MtKXqtNNyKHzmooOCdmtqmWxD7FxoAdU1eVcizhtQ0gcnVaY6ethEyE/hnEzQxt1zu5Kog==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/heading": {+ "version": "0.0.16",+ "resolved": "https://registry.npmjs.org/@react-email/heading/-/heading-0.0.16.tgz",+ "integrity": "sha512-jmsKnQm1ykpBzw4hCYHwBkt5pW2jScXffPeEH5ZRF5tZeF5b1pvlFTO9han7C0pCkZYo1kEvWiRtx69yfCIwuw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/hr": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@react-email/hr/-/hr-0.0.12.tgz",+ "integrity": "sha512-TwmOmBDibavUQpXBxpmZYi2Iks/yeZOzFYh+di9EltMSnEabH8dMZXrl+pxNXzCgZ2XE8HY7VmUL65Lenfu5PA==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/html": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@react-email/html/-/html-0.0.12.tgz",+ "integrity": "sha512-KTShZesan+UsreU7PDUV90afrZwU5TLwYlALuCSU0OT+/U8lULNNbAUekg+tGwCnOfIKYtpDPKkAMRdYlqUznw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/img": {+ "version": "0.0.12",+ "resolved": "https://registry.npmjs.org/@react-email/img/-/img-0.0.12.tgz",+ "integrity": "sha512-sRCpEARNVTf3FQhZOC+JTvu5r6ubiYWkT0ucYXg8ctkyi4G8QG+jgYPiNUqVeTLA2STOfmPM/nrk1nb84y6CPQ==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/link": {+ "version": "0.0.13",+ "resolved": "https://registry.npmjs.org/@react-email/link/-/link-0.0.13.tgz",+ "integrity": "sha512-lkWc/NjOcefRZMkQoSDDbuKBEBDES9aXnFEOuPH845wD3TxPwh+QTf0fStuzjoRLUZWpHnio4z7qGGRYusn/sw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/markdown": {+ "version": "0.0.18",+ "resolved": "https://registry.npmjs.org/@react-email/markdown/-/markdown-0.0.18.tgz",+ "integrity": "sha512-gSuYK5fsMbGk87jDebqQ6fa2fKcWlkf2Dkva8kMONqLgGCq8/0d+ZQYMEJsdidIeBo3kmsnHZPrwdFB4HgjUXg==",+ "license": "MIT",+ "dependencies": {+ "marked": "^15.0.12"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/preview": {+ "version": "0.0.14",+ "resolved": "https://registry.npmjs.org/@react-email/preview/-/preview-0.0.14.tgz",+ "integrity": "sha512-aYK8q0IPkBXyMsbpMXgxazwHxYJxTrXrV95GFuu2HbEiIToMwSyUgb8HDFYwPqqfV03/jbwqlsXmFxsOd+VNaw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/render": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/@react-email/render/-/render-2.0.4.tgz",+ "integrity": "sha512-kht2oTFQ1SwrLpd882ahTvUtNa9s53CERHstiTbzhm6aR2Hbykp/mQ4tpPvsBGkKAEvKRlDEoooh60Uk6nHK1g==",+ "license": "MIT",+ "dependencies": {+ "html-to-text": "^9.0.5",+ "prettier": "^3.5.3"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc",+ "react-dom": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/row": {+ "version": "0.0.13",+ "resolved": "https://registry.npmjs.org/@react-email/row/-/row-0.0.13.tgz",+ "integrity": "sha512-bYnOac40vIKCId7IkwuLAAsa3fKfSfqCvv6epJKmPE0JBuu5qI4FHFCl9o9dVpIIS08s/ub+Y/txoMt0dYziGw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/section": {+ "version": "0.0.17",+ "resolved": "https://registry.npmjs.org/@react-email/section/-/section-0.0.17.tgz",+ "integrity": "sha512-qNl65ye3W0Rd5udhdORzTV9ezjb+GFqQQSae03NDzXtmJq6sqVXNWNiVolAjvJNypim+zGXmv6J9TcV5aNtE/w==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }+ },+ "node_modules/@react-email/tailwind": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@react-email/tailwind/-/tailwind-2.0.3.tgz",+ "integrity": "sha512-URXb/T2WS4RlNGM5QwekYnivuiVUcU87H0y5sqLl6/Oi3bMmgL0Bmw/W9GeJylC+876Vw+E6NkE0uRiUFIQwGg==",+ "license": "MIT",+ "dependencies": {+ "tailwindcss": "^4.1.18"+ },+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "@react-email/body": "0.2.1",+ "@react-email/button": "0.2.1",+ "@react-email/code-block": "0.2.1",+ "@react-email/code-inline": "0.0.6",+ "@react-email/container": "0.0.16",+ "@react-email/heading": "0.0.16",+ "@react-email/hr": "0.0.12",+ "@react-email/img": "0.0.12",+ "@react-email/link": "0.0.13",+ "@react-email/preview": "0.0.14",+ "@react-email/text": "0.1.6",+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"},"peerDependenciesMeta": {- "@types/react": {+ "@react-email/body": {"optional": true},- "@types/react-dom": {+ "@react-email/button": {+ "optional": true+ },+ "@react-email/code-block": {+ "optional": true+ },+ "@react-email/code-inline": {+ "optional": true+ },+ "@react-email/container": {+ "optional": true+ },+ "@react-email/heading": {+ "optional": true+ },+ "@react-email/hr": {+ "optional": true+ },+ "@react-email/img": {+ "optional": true+ },+ "@react-email/link": {+ "optional": true+ },+ "@react-email/preview": {"optional": true}}},- "node_modules/@radix-ui/rect": {- "version": "1.1.1",- "resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",- "integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",- "license": "MIT"+ "node_modules/@react-email/text": {+ "version": "0.1.6",+ "resolved": "https://registry.npmjs.org/@react-email/text/-/text-0.1.6.tgz",+ "integrity": "sha512-TYqkioRS45wTR5il3dYk/SbUjjEdhSwh9BtRNB99qNH1pXAwA45H7rAuxehiu8iJQJH0IyIr+6n62gBz9ezmsw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ },+ "peerDependencies": {+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"+ }},"node_modules/@rolldown/pluginutils": {"version": "1.0.0-beta.27",@@ -3179,6 +5359,228 @@"win32"]},+ "node_modules/@selderee/plugin-htmlparser2": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/@selderee/plugin-htmlparser2/-/plugin-htmlparser2-0.11.0.tgz",+ "integrity": "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==",+ "license": "MIT",+ "dependencies": {+ "domhandler": "^5.0.3",+ "selderee": "^0.11.0"+ },+ "funding": {+ "url": "https://ko-fi.com/killymxi"+ }+ },+ "node_modules/@sentry-internal/node-cpu-profiler": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@sentry-internal/node-cpu-profiler/-/node-cpu-profiler-2.2.0.tgz",+ "integrity": "sha512-oLHVYurqZfADPh5hvmQYS5qx8t0UZzT2u6+/68VXsFruQEOnYJTODKgU3BVLmemRs3WE6kCJjPeFdHVYOQGSzQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "detect-libc": "^2.0.3",+ "node-abi": "^3.73.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@sentry-internal/node-cpu-profiler/node_modules/node-abi": {+ "version": "3.87.0",+ "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.87.0.tgz",+ "integrity": "sha512-+CGM1L1CgmtheLcBuleyYOn7NWPVu0s0EJH2C4puxgEZb9h8QpR9G2dBfZJOAUhi7VQxuBPMd0hiISWcTyiYyQ==",+ "license": "MIT",+ "dependencies": {+ "semver": "^7.3.5"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@sentry-internal/node-cpu-profiler/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/@sentry/core": {+ "version": "9.47.1",+ "resolved": "https://registry.npmjs.org/@sentry/core/-/core-9.47.1.tgz",+ "integrity": "sha512-KX62+qIt4xgy8eHKHiikfhz2p5fOciXd0Cl+dNzhgPFq8klq4MGMNaf148GB3M/vBqP4nw/eFvRMAayFCgdRQw==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@sentry/node": {+ "version": "9.47.1",+ "resolved": "https://registry.npmjs.org/@sentry/node/-/node-9.47.1.tgz",+ "integrity": "sha512-CDbkasBz3fnWRKSFs6mmaRepM2pa+tbZkrqhPWifFfIkJDidtVW40p6OnquTvPXyPAszCnDZRnZT14xyvNmKPQ==",+ "license": "MIT",+ "dependencies": {+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/context-async-hooks": "^1.30.1",+ "@opentelemetry/core": "^1.30.1",+ "@opentelemetry/instrumentation": "^0.57.2",+ "@opentelemetry/instrumentation-amqplib": "^0.46.1",+ "@opentelemetry/instrumentation-connect": "0.43.1",+ "@opentelemetry/instrumentation-dataloader": "0.16.1",+ "@opentelemetry/instrumentation-express": "0.47.1",+ "@opentelemetry/instrumentation-fs": "0.19.1",+ "@opentelemetry/instrumentation-generic-pool": "0.43.1",+ "@opentelemetry/instrumentation-graphql": "0.47.1",+ "@opentelemetry/instrumentation-hapi": "0.45.2",+ "@opentelemetry/instrumentation-http": "0.57.2",+ "@opentelemetry/instrumentation-ioredis": "0.47.1",+ "@opentelemetry/instrumentation-kafkajs": "0.7.1",+ "@opentelemetry/instrumentation-knex": "0.44.1",+ "@opentelemetry/instrumentation-koa": "0.47.1",+ "@opentelemetry/instrumentation-lru-memoizer": "0.44.1",+ "@opentelemetry/instrumentation-mongodb": "0.52.0",+ "@opentelemetry/instrumentation-mongoose": "0.46.1",+ "@opentelemetry/instrumentation-mysql": "0.45.1",+ "@opentelemetry/instrumentation-mysql2": "0.45.2",+ "@opentelemetry/instrumentation-pg": "0.51.1",+ "@opentelemetry/instrumentation-redis-4": "0.46.1",+ "@opentelemetry/instrumentation-tedious": "0.18.1",+ "@opentelemetry/instrumentation-undici": "0.10.1",+ "@opentelemetry/resources": "^1.30.1",+ "@opentelemetry/sdk-trace-base": "^1.30.1",+ "@opentelemetry/semantic-conventions": "^1.34.0",+ "@prisma/instrumentation": "6.11.1",+ "@sentry/core": "9.47.1",+ "@sentry/node-core": "9.47.1",+ "@sentry/opentelemetry": "9.47.1",+ "import-in-the-middle": "^1.14.2",+ "minimatch": "^9.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@sentry/node-core": {+ "version": "9.47.1",+ "resolved": "https://registry.npmjs.org/@sentry/node-core/-/node-core-9.47.1.tgz",+ "integrity": "sha512-7TEOiCGkyShJ8CKtsri9lbgMCbB+qNts2Xq37itiMPN2m+lIukK3OX//L8DC5nfKYZlgikrefS63/vJtm669hQ==",+ "license": "MIT",+ "dependencies": {+ "@sentry/core": "9.47.1",+ "@sentry/opentelemetry": "9.47.1",+ "import-in-the-middle": "^1.14.2"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.0.0",+ "@opentelemetry/core": "^1.30.1 || ^2.0.0",+ "@opentelemetry/instrumentation": ">=0.57.1 <1",+ "@opentelemetry/resources": "^1.30.1 || ^2.0.0",+ "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.0.0",+ "@opentelemetry/semantic-conventions": "^1.34.0"+ }+ },+ "node_modules/@sentry/node/node_modules/brace-expansion": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",+ "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",+ "license": "MIT",+ "dependencies": {+ "balanced-match": "^1.0.0"+ }+ },+ "node_modules/@sentry/node/node_modules/minimatch": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",+ "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==",+ "license": "ISC",+ "dependencies": {+ "brace-expansion": "^2.0.1"+ },+ "engines": {+ "node": ">=16 || 14 >=14.17"+ },+ "funding": {+ "url": "https://github.com/sponsors/isaacs"+ }+ },+ "node_modules/@sentry/opentelemetry": {+ "version": "9.47.1",+ "resolved": "https://registry.npmjs.org/@sentry/opentelemetry/-/opentelemetry-9.47.1.tgz",+ "integrity": "sha512-STtFpjF7lwzeoedDJV+5XA6P89BfmFwFftmHSGSe3UTI8z8IoiR5yB6X2vCjSPvXlfeOs13qCNNCEZyznxM8Xw==",+ "license": "MIT",+ "dependencies": {+ "@sentry/core": "9.47.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@opentelemetry/api": "^1.9.0",+ "@opentelemetry/context-async-hooks": "^1.30.1 || ^2.0.0",+ "@opentelemetry/core": "^1.30.1 || ^2.0.0",+ "@opentelemetry/sdk-trace-base": "^1.30.1 || ^2.0.0",+ "@opentelemetry/semantic-conventions": "^1.34.0"+ }+ },+ "node_modules/@sentry/profiling-node": {+ "version": "9.47.1",+ "resolved": "https://registry.npmjs.org/@sentry/profiling-node/-/profiling-node-9.47.1.tgz",+ "integrity": "sha512-4Llq0it2nL/1iJcEEm3JwdRyvRAjYuoS0MB9+9eKRaCJBIj//3fOcyjw75BbhdSFBhkDMRv2W5b3gn9oPrJAHA==",+ "license": "MIT",+ "dependencies": {+ "@sentry-internal/node-cpu-profiler": "^2.2.0",+ "@sentry/core": "9.47.1",+ "@sentry/node": "9.47.1"+ },+ "bin": {+ "sentry-prune-profiler-binaries": "scripts/prune-profiler-binaries.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@simplewebauthn/browser": {+ "version": "13.2.2",+ "resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-13.2.2.tgz",+ "integrity": "sha512-FNW1oLQpTJyqG5kkDg5ZsotvWgmBaC6jCHR7Ej0qUNep36Wl9tj2eZu7J5rP+uhXgHaLk+QQ3lqcw2vS5MX1IA==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/@simplewebauthn/server": {+ "version": "13.2.2",+ "resolved": "https://registry.npmjs.org/@simplewebauthn/server/-/server-13.2.2.tgz",+ "integrity": "sha512-HcWLW28yTMGXpwE9VLx9J+N2KEUaELadLrkPEEI9tpI5la70xNEVEsu/C+m3u7uoq4FulLqZQhgBCzR9IZhFpA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@hexagon/base64": "^1.1.27",+ "@levischuck/tiny-cbor": "^0.2.2",+ "@peculiar/asn1-android": "^2.3.10",+ "@peculiar/asn1-ecc": "^2.3.8",+ "@peculiar/asn1-rsa": "^2.3.8",+ "@peculiar/asn1-schema": "^2.3.8",+ "@peculiar/asn1-x509": "^2.3.8",+ "@peculiar/x509": "^1.13.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@sinclair/typebox": {+ "version": "0.31.28",+ "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.31.28.tgz",+ "integrity": "sha512-/s55Jujywdw/Jpan+vsy6JZs1z2ZTGxTmbZTPiuSL2wz9mfzA2gN1zzaqmvfi4pq+uOt7Du85fkiwv5ymW84aQ==",+ "license": "MIT"+ },"node_modules/@sindresorhus/is": {"version": "4.6.0","resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",@@ -3192,6 +5594,73 @@"url": "https://github.com/sindresorhus/is?sponsor=1"}},+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "license": "MIT"+ },+ "node_modules/@standard-schema/utils": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",+ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",+ "license": "MIT"+ },+ "node_modules/@supabase/auth-js": {+ "version": "2.79.0",+ "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.79.0.tgz",+ "integrity": "sha512-p2GKvdbF9d/6C+dtS6iNcSicPr6eUfkvovD60HWlWsD+oOjC483DzFWrzGjNpBwnswhfMRP8Qn3rYA0VWaOfjw==",+ "license": "MIT",+ "dependencies": {+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@supabase/postgres-meta": {+ "version": "0.93.1",+ "resolved": "https://registry.npmjs.org/@supabase/postgres-meta/-/postgres-meta-0.93.1.tgz",+ "integrity": "sha512-cTKLFPqtaMHAUaiHfWj28xEv6tqb5ffsMByZprgJFDCqTBflIftsDp4mYelK5Kdra7OWy1XgLacsMjQ3FbxFSQ==",+ "license": "MIT",+ "dependencies": {+ "@fastify/cors": "^9.0.1",+ "@fastify/swagger": "^8.2.1",+ "@fastify/type-provider-typebox": "^3.5.0",+ "@sentry/node": "^9.12.0",+ "@sentry/profiling-node": "^9.12.0",+ "@sinclair/typebox": "^0.31.25",+ "close-with-grace": "^2.1.0",+ "crypto-js": "^4.0.0",+ "fastify": "^4.24.3",+ "fastify-metrics": "^10.0.0",+ "pg": "npm:@supabase/[email protected]",+ "pg-connection-string": "^2.7.0",+ "pg-format": "^1.0.4",+ "pg-protocol": "npm:@supabase/[email protected]",+ "pgsql-parser": "^13.16.0",+ "pino": "^9.5.0",+ "postgres-array": "^3.0.1",+ "prettier": "^3.3.3",+ "prettier-plugin-sql": "0.17.1"+ },+ "engines": {+ "node": ">=20",+ "npm": ">=9"+ }+ },+ "node_modules/@supabase/postgrest-js": {+ "version": "2.79.0",+ "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.79.0.tgz",+ "integrity": "sha512-2i8EFm3/49ecjt6dk/TGVROBbtOmhryiC4NL3u0FBIrm2hqj+FvbELv1jjM6r+a6abnh+uzIV/bFsWHAa/k3/w==",+ "license": "MIT",+ "dependencies": {+ "tslib": "2.8.1"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/@szmarczak/http-timer": {"version": "4.0.6","resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",@@ -3477,6 +5946,124 @@"vite": "^5.2.0 || ^6 || ^7"}},+ "node_modules/@tanstack/query-core": {+ "version": "5.90.20",+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",+ "integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",+ "license": "MIT",+ "peer": true,+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ }+ },+ "node_modules/@tanstack/react-query": {+ "version": "5.90.20",+ "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.20.tgz",+ "integrity": "sha512-vXBxa+qeyveVO7OA0jX1z+DeyCA4JKnThKv411jd5SORpBKgkcVnYKCiBgECvADvniBX7tobwBmg01qq9JmMJw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@tanstack/query-core": "5.90.20"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/tannerlinsley"+ },+ "peerDependencies": {+ "react": "^18 || ^19"+ }+ },+ "node_modules/@triplit/client": {+ "version": "1.0.50",+ "resolved": "https://registry.npmjs.org/@triplit/client/-/client-1.0.50.tgz",+ "integrity": "sha512-3vjXTSdDQ3fzLDrewCK7elkAQc7CiDg0eZEOZInQbVMFRiakdieO5C2voSnNjSepIYHxDxFSBllgg32QsNpL9Q==",+ "license": "AGPL-3.0-only",+ "peer": true,+ "dependencies": {+ "@triplit/db": "^1.1.10",+ "@triplit/logger": "^0.0.3",+ "comlink": "^4.4.1",+ "superjson": "^2.2.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@triplit/db": {+ "version": "1.1.10",+ "resolved": "https://registry.npmjs.org/@triplit/db/-/db-1.1.10.tgz",+ "integrity": "sha512-9BHDrlDvJOyA9Wl8AsmbUSLhilaReA8gpFoWYjS9VEcm5d6TtqKazPQrFm0/o2WNJdrs01+qR6CysAo449MAyA==",+ "peer": true,+ "dependencies": {+ "@triplit/logger": "^0.0.3",+ "core-js": "^3.41.0",+ "elen": "^1.0.10",+ "nanoid": "^5.1.0",+ "sorted-btree": "^1.8.1",+ "web-worker": "^1.5.0"+ },+ "peerDependencies": {+ "better-sqlite3": "*",+ "expo-sqlite": "*",+ "lmdb": "*",+ "uuidv7": "*"+ },+ "peerDependenciesMeta": {+ "better-sqlite3": {+ "optional": true+ },+ "expo-sqlite": {+ "optional": true+ },+ "lmdb": {+ "optional": true+ },+ "uuidv7": {+ "optional": true+ }+ }+ },+ "node_modules/@triplit/db/node_modules/nanoid": {+ "version": "5.1.6",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.6.tgz",+ "integrity": "sha512-c7+7RQ+dMB5dPwwCp4ee1/iV/q2P6aK1mTZcfr1BTuVlyW9hJYiMPybJCcnBlQtuSmTIWNeazm/zqNoZSSElBg==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "peer": true,+ "bin": {+ "nanoid": "bin/nanoid.js"+ },+ "engines": {+ "node": "^18 || >=20"+ }+ },+ "node_modules/@triplit/logger": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/@triplit/logger/-/logger-0.0.3.tgz",+ "integrity": "sha512-hHcoD6/BsNwBtXjEp8Wiy0/YA2SqIYXd1nMukEPBmFkjT7Cd30eqtsBRT0NRq2mIFX2mr5h9JaO27zDToKnwdw==",+ "peer": true,+ "peerDependencies": {+ "typescript": "^5.0.0"+ }+ },+ "node_modules/@triplit/react": {+ "version": "1.0.51",+ "resolved": "https://registry.npmjs.org/@triplit/react/-/react-1.0.51.tgz",+ "integrity": "sha512-yGmYWACWycrNHMEfnR1k6CQ398ESIBgFeM47fXFhrdhMJ84QgdRk6VF/C21P80D1Rk/AQePfB0TUIaY4U9BRJg==",+ "peer": true,+ "dependencies": {+ "@triplit/client": "^1.0.50"+ },+ "peerDependencies": {+ "react": "*"+ }+ },"node_modules/@types/babel__core": {"version": "7.20.5","resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",@@ -3535,6 +6122,15 @@"@types/responselike": "^1.0.0"}},+ "node_modules/@types/connect": {+ "version": "3.4.38",+ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",+ "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/debug": {"version": "4.1.12","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",@@ -3617,16 +6213,44 @@"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==","license": "MIT"},+ "node_modules/@types/mysql": {+ "version": "2.15.26",+ "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.26.tgz",+ "integrity": "sha512-DSLCOXhkvfS5WNNPbfn2KdICAmk8lLc+/PNvnPnF7gOdMZCxopXduqv0OQ13y/yA/zXTSikZZqVgybUxOEg6YQ==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/node": {"version": "22.19.7","resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.7.tgz","integrity": "sha512-MciR4AKGHWl7xwxkBa6xUGxQJ4VBOmPTF7sL+iGzuahOFaO0jHCsuEfS80pan1ef4gWId1oWOweIhrDEYLuaOw==",- "dev": true,"license": "MIT","dependencies": {"undici-types": "~6.21.0"}},+ "node_modules/@types/pg": {+ "version": "8.6.1",+ "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.6.1.tgz",+ "integrity": "sha512-1Kc4oAGzAl7uqUStZCDvaLFqZrW9qWSjXOmBfdgyBP5La7Us6Mg4GBvRlSoaZMhQF/zSj1C8CtKMBkoiT8eL8w==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "pg-protocol": "*",+ "pg-types": "^2.2.0"+ }+ },+ "node_modules/@types/pg-pool": {+ "version": "2.0.6",+ "resolved": "https://registry.npmjs.org/@types/pg-pool/-/pg-pool-2.0.6.tgz",+ "integrity": "sha512-TaAUE5rq2VQYxab5Ts7WZhKNmuN78Q6PiFonTDdpbx8a1H0M1vhy3rhiMjl+e2iHmogyMw7jZF4FrE6eJUy5HQ==",+ "license": "MIT",+ "dependencies": {+ "@types/pg": "*"+ }+ },"node_modules/@types/plist": {"version": "3.0.5","resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz",@@ -3668,6 +6292,21 @@"@types/node": "*"}},+ "node_modules/@types/shimmer": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",+ "integrity": "sha512-UE7oxhQLLd9gub6JKIAhDq06T0F6FnztwMNRvYgjeQSBeMc1ZG/tA47EwfduvkuQS8apbkM/lpLpWsaCeYsXVg==",+ "license": "MIT"+ },+ "node_modules/@types/tedious": {+ "version": "4.0.14",+ "resolved": "https://registry.npmjs.org/@types/tedious/-/tedious-4.0.14.tgz",+ "integrity": "sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==",+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/unist": {"version": "3.0.3","resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",@@ -3989,6 +6628,28 @@"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"}},+ "node_modules/@wojtekmaj/react-recaptcha-v3": {+ "version": "0.1.4",+ "resolved": "https://registry.npmjs.org/@wojtekmaj/react-recaptcha-v3/-/react-recaptcha-v3-0.1.4.tgz",+ "integrity": "sha512-zszMOdgI+y1Dz3496pRFr3t68n9+OmX/puLQNnOBDC7WrjM+nOKGyjIMCTe+3J14KDvzcxETeiglyDMGl0Yh/Q==",+ "license": "MIT",+ "dependencies": {+ "warning": "^4.0.0"+ },+ "funding": {+ "url": "https://github.com/wojtekmaj/react-recaptcha-v3?sponsor=1"+ },+ "peerDependencies": {+ "@types/react": "^18.0.0 || ^19.0.0",+ "react": "^18.0.0 || ^19.0.0",+ "react-dom": "^18.0.0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/@xmldom/xmldom": {"version": "0.8.11","resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz",@@ -4016,11 +6677,16 @@"node": "^18.17.0 || >=20.5.0"}},+ "node_modules/abstract-logging": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",+ "integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",+ "license": "MIT"+ },"node_modules/acorn": {"version": "8.15.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz","integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",- "dev": true,"license": "MIT","bin": {"acorn": "bin/acorn"@@ -4029,6 +6695,15 @@"node": ">=0.4.0"}},+ "node_modules/acorn-import-attributes": {+ "version": "1.9.5",+ "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz",+ "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==",+ "license": "MIT",+ "peerDependencies": {+ "acorn": "^8"+ }+ },"node_modules/acorn-jsx": {"version": "5.3.2","resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",@@ -4066,6 +6741,61 @@"url": "https://github.com/sponsors/epoberezkin"}},+ "node_modules/ajv-formats": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",+ "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/ajv-formats/node_modules/ajv": {+ "version": "8.17.1",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/ajv-formats/node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"+ },+ "node_modules/ajv-formats/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },"node_modules/ajv-keywords": {"version": "3.5.2","resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz",@@ -4459,6 +7189,21 @@"safer-buffer": "~2.1.0"}},+ "node_modules/asn1js": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.7.tgz",+ "integrity": "sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==",+ "license": "BSD-3-Clause",+ "peer": true,+ "dependencies": {+ "pvtsutils": "^1.3.6",+ "pvutils": "^1.1.3",+ "tslib": "^2.8.1"+ },+ "engines": {+ "node": ">=12.0.0"+ }+ },"node_modules/assert-plus": {"version": "1.0.0","resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",@@ -4514,6 +7259,15 @@"node": ">= 4.0.0"}},+ "node_modules/atomic-sleep": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",+ "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==",+ "license": "MIT",+ "engines": {+ "node": ">=8.0.0"+ }+ },"node_modules/autoprefixer": {"version": "10.4.23","resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz",@@ -4551,6 +7305,16 @@"postcss": "^8.1.0"}},+ "node_modules/avvio": {+ "version": "8.4.0",+ "resolved": "https://registry.npmjs.org/avvio/-/avvio-8.4.0.tgz",+ "integrity": "sha512-CDSwaxINFy59iNwhYnkvALBwZiTydGkOecZyPkqBpABYR1KqGEsET0VOOYDwtleZSUIdeY36DC2bSZ24CO1igA==",+ "license": "MIT",+ "dependencies": {+ "@fastify/error": "^3.3.0",+ "fastq": "^1.17.1"+ }+ },"node_modules/aws-sign2": {"version": "0.7.0","resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",@@ -4582,7 +7346,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz","integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",- "devOptional": true,"license": "MIT"},"node_modules/base64-js": {@@ -4625,6 +7388,27 @@"tweetnacl": "^0.14.3"}},+ "node_modules/better-call": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/better-call/-/better-call-1.1.8.tgz",+ "integrity": "sha512-XMQ2rs6FNXasGNfMjzbyroSwKwYbZ/T3IxruSS6U2MJRsSYh3wYtG3o6H00ZlKZ/C/UPOAD97tqgQJNsxyeTXw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@better-auth/utils": "^0.3.0",+ "@better-fetch/fetch": "^1.1.4",+ "rou3": "^0.7.10",+ "set-cookie-parser": "^2.7.1"+ },+ "peerDependencies": {+ "zod": "^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },"node_modules/better-sqlite3": {"version": "11.10.0","resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-11.10.0.tgz",@@ -4636,6 +7420,15 @@"prebuild-install": "^7.1.1"}},+ "node_modules/big-integer": {+ "version": "1.6.52",+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",+ "license": "Unlicense",+ "engines": {+ "node": ">=0.6"+ }+ },"node_modules/bindings": {"version": "1.5.0","resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",@@ -4645,6 +7438,12 @@"file-uri-to-path": "1.0.0"}},+ "node_modules/bintrees": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",+ "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",+ "license": "MIT"+ },"node_modules/bl": {"version": "4.1.0","resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",@@ -5102,6 +7901,12 @@"node": ">=8"}},+ "node_modules/cjs-module-lexer": {+ "version": "1.4.3",+ "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz",+ "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==",+ "license": "MIT"+ },"node_modules/class-variance-authority": {"version": "0.7.1","resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",@@ -5196,6 +8001,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/close-with-grace": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/close-with-grace/-/close-with-grace-2.4.0.tgz",+ "integrity": "sha512-bzAYS0Kax7I0ejiCFHVshsT9giz6MrOpkdpP1CEGpkDRG3mXVgHZ9QdzVGHRZR0jrAq6JyN1mB4Ty3ILnmzLdg==",+ "license": "MIT"+ },"node_modules/clsx": {"version": "2.1.1","resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",@@ -5248,6 +8059,13 @@"node": ">= 0.8"}},+ "node_modules/comlink": {+ "version": "4.4.2",+ "resolved": "https://registry.npmjs.org/comlink/-/comlink-4.4.2.tgz",+ "integrity": "sha512-OxGdvBmJuNKSCMO4NTl1L47VRp6xn2wG4F/2hYzB6tiCb709otOxtEYCSvK80PtjODfXXZu8ds+Nw5kVCjqd2g==",+ "license": "Apache-2.0",+ "peer": true+ },"node_modules/comma-separated-tokens": {"version": "2.0.3","resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",@@ -5342,6 +8160,43 @@"dev": true,"license": "MIT"},+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/copy-anything": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/copy-anything/-/copy-anything-4.0.5.tgz",+ "integrity": "sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "is-what": "^5.2.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/mesqueeb"+ }+ },+ "node_modules/core-js": {+ "version": "3.48.0",+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.48.0.tgz",+ "integrity": "sha512-zpEHTy1fjTMZCKLHUZoVeylt9XrzaIN2rbPXEt0k+q7JE5CkCZdo6bNq55bn24a69CH7ErAVLKijxJja4fw+UQ==",+ "hasInstallScript": true,+ "license": "MIT",+ "peer": true,+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/core-js"+ }+ },"node_modules/core-util-is": {"version": "1.0.2","resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",@@ -5401,6 +8256,12 @@"node": ">= 8"}},+ "node_modules/crypto-js": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",+ "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",+ "license": "MIT"+ },"node_modules/csstype": {"version": "3.2.3","resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",@@ -5528,6 +8389,15 @@"dev": true,"license": "MIT"},+ "node_modules/deepmerge": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",+ "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/defaults": {"version": "1.0.4","resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz",@@ -5589,6 +8459,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/defu": {+ "version": "6.1.4",+ "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.4.tgz",+ "integrity": "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==",+ "license": "MIT"+ },"node_modules/delayed-stream": {"version": "1.0.0","resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",@@ -5615,6 +8491,26 @@"node": ">=6"}},+ "node_modules/detect-europe-js": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/detect-europe-js/-/detect-europe-js-0.1.2.tgz",+ "integrity": "sha512-lgdERlL3u0aUdHocoouzT10d9I89VVhk0qNRmll7mXdGfJT1/wqZ2ZLA4oJAjeACPY5fT1wsbq2AT+GkuInsow==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/faisalman"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ua-parser-js"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/faisalman"+ }+ ],+ "license": "MIT"+ },"node_modules/detect-libc": {"version": "2.1.2","resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",@@ -5675,6 +8571,12 @@"node": "*"}},+ "node_modules/discontinuous-range": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",+ "integrity": "sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ==",+ "license": "MIT"+ },"node_modules/dmg-builder": {"version": "26.4.0","resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.4.0.tgz",@@ -5757,6 +8659,61 @@"node": ">=8"}},+ "node_modules/dom-serializer": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.3.0",+ "domhandler": "^5.0.2",+ "entities": "^4.2.0"+ },+ "funding": {+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"+ }+ },+ "node_modules/domelementtype": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "BSD-2-Clause"+ },+ "node_modules/domhandler": {+ "version": "5.0.3",+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "domelementtype": "^2.3.0"+ },+ "engines": {+ "node": ">= 4"+ },+ "funding": {+ "url": "https://github.com/fb55/domhandler?sponsor=1"+ }+ },+ "node_modules/domutils": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "dom-serializer": "^2.0.0",+ "domelementtype": "^2.3.0",+ "domhandler": "^5.0.3"+ },+ "funding": {+ "url": "https://github.com/fb55/domutils?sponsor=1"+ }+ },"node_modules/dotenv": {"version": "16.6.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",@@ -6138,6 +9095,13 @@"node": ">=6 <7 || >=8"}},+ "node_modules/elen": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/elen/-/elen-1.0.10.tgz",+ "integrity": "sha512-ZL799/V/kzxYJ6Wlfktreq6qQWfGc3VkGUQJW5lZQ8/MhsQiKTAwERPfhEwIsV2movRGe2DfV7H2MjRw76Z7Wg==",+ "license": "MIT",+ "peer": true+ },"node_modules/emoji-regex": {"version": "8.0.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",@@ -6179,6 +9143,18 @@"node": ">=10.13.0"}},+ "node_modules/entities": {+ "version": "4.5.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/env-paths": {"version": "2.2.1","resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",@@ -6532,6 +9508,29 @@"through": "~2.3.1"}},+ "node_modules/eventsource": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-4.1.0.tgz",+ "integrity": "sha512-2GuF51iuHX6A9xdTccMTsNb7VO0lHZihApxhvQzJB5A03DvHDd2FQepodbMaztPBmBcE/ox7o2gqaxGhYB9LhQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",+ "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/expand-template": {"version": "2.0.3","resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",@@ -6586,18 +9585,99 @@"license": "MIT","optional": true},- "node_modules/fast-deep-equal": {- "version": "3.1.3",- "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",- "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",- "devOptional": true,- "license": "MIT"+ "node_modules/fast-content-type-parse": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-1.1.0.tgz",+ "integrity": "sha512-fBHHqSTFLVnR61C+gltJuE5GkVQMV0S2nqUO8TJ+5Z3qAKG8vAx4FKai1s5jq/inV1+sREynIWSuQ6HgoSXpDQ==",+ "license": "MIT"+ },+ "node_modules/fast-decode-uri-component": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",+ "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",+ "license": "MIT"+ },+ "node_modules/fast-deep-equal": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",+ "license": "MIT"+ },+ "node_modules/fast-json-stable-stringify": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",+ "devOptional": true,+ "license": "MIT"+ },+ "node_modules/fast-json-stringify": {+ "version": "5.16.1",+ "resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-5.16.1.tgz",+ "integrity": "sha512-KAdnLvy1yu/XrRtP+LJnxbBGrhN+xXu+gt3EUvZhYGKCr3lFHq/7UFJHHFgmJKoqlh6B40bZLEv7w46B0mqn1g==",+ "license": "MIT",+ "dependencies": {+ "@fastify/merge-json-schemas": "^0.1.0",+ "ajv": "^8.10.0",+ "ajv-formats": "^3.0.1",+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^2.1.0",+ "json-schema-ref-resolver": "^1.0.1",+ "rfdc": "^1.2.0"+ }+ },+ "node_modules/fast-json-stringify/node_modules/ajv": {+ "version": "8.17.1",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",+ "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/fast-json-stringify/node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/fast-json-stringify/node_modules/ajv/node_modules/fast-uri": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "BSD-3-Clause"},- "node_modules/fast-json-stable-stringify": {- "version": "2.1.0",- "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",- "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",- "devOptional": true,+ "node_modules/fast-json-stringify/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==","license": "MIT"},"node_modules/fast-levenshtein": {@@ -6607,6 +9687,95 @@"dev": true,"license": "MIT"},+ "node_modules/fast-querystring": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/fast-querystring/-/fast-querystring-1.1.2.tgz",+ "integrity": "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==",+ "license": "MIT",+ "dependencies": {+ "fast-decode-uri-component": "^1.0.1"+ }+ },+ "node_modules/fast-uri": {+ "version": "2.4.0",+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.0.tgz",+ "integrity": "sha512-ypuAmmMKInk5q7XcepxlnUWDLWv4GFtaJqAzWKqn62IpQ3pejtr5dTVbt3vwqVaMKmkNR55sTT+CqUKIaT21BA==",+ "license": "MIT"+ },+ "node_modules/fastify": {+ "version": "4.29.1",+ "resolved": "https://registry.npmjs.org/fastify/-/fastify-4.29.1.tgz",+ "integrity": "sha512-m2kMNHIG92tSNWv+Z3UeTR9AWLLuo7KctC7mlFPtMEVrfjIhmQhkQnT9v15qA/BfVq3vvj134Y0jl9SBje3jXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@fastify/ajv-compiler": "^3.5.0",+ "@fastify/error": "^3.4.0",+ "@fastify/fast-json-stringify-compiler": "^4.3.0",+ "abstract-logging": "^2.0.1",+ "avvio": "^8.3.0",+ "fast-content-type-parse": "^1.1.0",+ "fast-json-stringify": "^5.8.0",+ "find-my-way": "^8.0.0",+ "light-my-request": "^5.11.0",+ "pino": "^9.0.0",+ "process-warning": "^3.0.0",+ "proxy-addr": "^2.0.7",+ "rfdc": "^1.3.0",+ "secure-json-parse": "^2.7.0",+ "semver": "^7.5.4",+ "toad-cache": "^3.3.0"+ }+ },+ "node_modules/fastify-metrics": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/fastify-metrics/-/fastify-metrics-10.6.0.tgz",+ "integrity": "sha512-QIPncCnwBOEObMn+VaRhsBC1ox8qEsaiYF2sV/A1UbXj7ic70W8/HNn/hlEC2W8JQbBeZMx++o1um2fPfhsFDQ==",+ "license": "MIT",+ "dependencies": {+ "fastify-plugin": "^4.3.0",+ "prom-client": "^14.2.0"+ },+ "peerDependencies": {+ "fastify": ">=4"+ }+ },+ "node_modules/fastify-plugin": {+ "version": "4.5.1",+ "resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-4.5.1.tgz",+ "integrity": "sha512-stRHYGeuqpEZTL1Ef0Ovr2ltazUT9g844X5z/zEBFLG8RYlpDiOCIG+ATvYEp+/zmc7sN29mcIMp8gvYplYPIQ==",+ "license": "MIT"+ },+ "node_modules/fastify/node_modules/semver": {+ "version": "7.7.3",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",+ "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",+ "license": "ISC",+ "bin": {+ "semver": "bin/semver.js"+ },+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/fastq": {+ "version": "1.20.1",+ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz",+ "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==",+ "license": "ISC",+ "dependencies": {+ "reusify": "^1.0.4"+ }+ },"node_modules/fd-slicer": {"version": "1.1.0","resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",@@ -6728,6 +9897,20 @@"node": ">=10"}},+ "node_modules/find-my-way": {+ "version": "8.2.2",+ "resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-8.2.2.tgz",+ "integrity": "sha512-Dobi7gcTEq8yszimcfp/R7+owiT4WncAJ7VTTgFH1jYJ5GaG1FbhjwDG820hptN0QDFvzVY3RfCzdInvGPGzjA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-querystring": "^1.0.0",+ "safe-regex2": "^3.1.0"+ },+ "engines": {+ "node": ">=14"+ }+ },"node_modules/find-up": {"version": "5.0.0","resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",@@ -6823,6 +10006,21 @@"node": ">= 6"}},+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/forwarded-parse": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/forwarded-parse/-/forwarded-parse-2.1.2.tgz",+ "integrity": "sha512-alTFZZQDKMporBH77856pXgzhEzaUVmLCDk+egLgIgHst3Tpndzz8MnKe+GzRJRfvVdn69HhpW7cmXzvtLvJAw==",+ "license": "MIT"+ },"node_modules/fraction.js": {"version": "5.3.4","resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",@@ -6903,7 +10101,6 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz","integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",- "dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/ljharb"@@ -7046,6 +10243,18 @@"node": ">= 0.4"}},+ "node_modules/get-stdin": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-8.0.0.tgz",+ "integrity": "sha512-sY22aA6xchAzprjyqmSEQv4UbAAzRN0L2dQB0NlN5acTTK9Don6nhoc3eAbUnpZiCANAMfd/+40kVdKfFygohg==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/get-stream": {"version": "5.2.0","resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",@@ -7324,7 +10533,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz","integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",- "dev": true,"license": "MIT","dependencies": {"function-bind": "^1.1.2"@@ -7382,6 +10590,15 @@"hexy": "bin/hexy_cmd.js"}},+ "node_modules/hoist-non-react-statics": {+ "version": "3.3.2",+ "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",+ "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "react-is": "^16.7.0"+ }+ },"node_modules/hosted-git-info": {"version": "4.1.0","resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz",@@ -7415,6 +10632,22 @@"dev": true,"license": "ISC"},+ "node_modules/html-to-text": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/html-to-text/-/html-to-text-9.0.5.tgz",+ "integrity": "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==",+ "license": "MIT",+ "dependencies": {+ "@selderee/plugin-htmlparser2": "^0.11.0",+ "deepmerge": "^4.3.1",+ "dom-serializer": "^2.0.0",+ "htmlparser2": "^8.0.2",+ "selderee": "^0.11.0"+ },+ "engines": {+ "node": ">=14"+ }+ },"node_modules/html-url-attributes": {"version": "3.0.1","resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",@@ -7425,6 +10658,25 @@"url": "https://opencollective.com/unified"}},+ "node_modules/htmlparser2": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz",+ "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==",+ "funding": [+ "https://github.com/fb55/htmlparser2?sponsor=1",+ {+ "type": "github",+ "url": "https://github.com/sponsors/fb55"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "domelementtype": "^2.3.0",+ "domhandler": "^5.0.3",+ "domutils": "^3.0.1",+ "entities": "^4.4.0"+ }+ },"node_modules/http-cache-semantics": {"version": "4.2.0","resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",@@ -7583,6 +10835,18 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/import-in-the-middle": {+ "version": "1.15.0",+ "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz",+ "integrity": "sha512-bpQy+CrsRmYmoPMAE/0G33iwRqwW4ouqdRg8jgbH3aKuCtOc8lxgmYXg2dMM92CRiGP660EtBcymH/eVUpCSaA==",+ "license": "Apache-2.0",+ "dependencies": {+ "acorn": "^8.14.0",+ "acorn-import-attributes": "^1.9.5",+ "cjs-module-lexer": "^1.2.2",+ "module-details-from-path": "^1.0.3"+ }+ },"node_modules/imurmurhash": {"version": "0.1.4","resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",@@ -7623,6 +10887,16 @@"integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==","license": "MIT"},+ "node_modules/input-otp": {+ "version": "1.4.2",+ "resolved": "https://registry.npmjs.org/input-otp/-/input-otp-1.4.2.tgz",+ "integrity": "sha512-l3jWwYNvrEa6NTCt7BECfCm48GvwuZzkoeG3gBL2w4CHeOXW3eKFmf9UNYkNfYc3mxMrthMnxjIE07MT0zLBQA==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },"node_modules/ip-address": {"version": "10.1.0","resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",@@ -7633,6 +10907,15 @@"node": ">= 12"}},+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/is-alphabetical": {"version": "2.0.1","resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",@@ -7657,6 +10940,21 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/is-core-module": {+ "version": "2.16.1",+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",+ "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",+ "license": "MIT",+ "dependencies": {+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/is-decimal": {"version": "2.0.1","resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",@@ -7732,6 +11030,26 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/is-standalone-pwa": {+ "version": "0.1.1",+ "resolved": "https://registry.npmjs.org/is-standalone-pwa/-/is-standalone-pwa-0.1.1.tgz",+ "integrity": "sha512-9Cbovsa52vNQCjdXOzeQq5CnCbAcRk05aU62K20WO372NrTv0NxibLFCK6lQ4/iZEFdEA3p3t2VNOn8AJ53F5g==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/faisalman"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ua-parser-js"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/faisalman"+ }+ ],+ "license": "MIT"+ },"node_modules/is-typedarray": {"version": "1.0.0","resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",@@ -7752,6 +11070,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/is-what": {+ "version": "5.5.0",+ "resolved": "https://registry.npmjs.org/is-what/-/is-what-5.5.0.tgz",+ "integrity": "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/mesqueeb"+ }+ },"node_modules/isarray": {"version": "1.0.0","resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",@@ -7829,11 +11160,19 @@"jiti": "lib/jiti-cli.mjs"}},+ "node_modules/jose": {+ "version": "6.1.2",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.1.2.tgz",+ "integrity": "sha512-MpcPtHLE5EmztuFIqB0vzHAWJPpmN1E6L4oo+kze56LIs3MyXIj9ZHMDxqOvkP38gBR7K1v3jqd4WU2+nrfONQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/js-tokens": {"version": "4.0.0","resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz","integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",- "dev": true,"license": "MIT"},"node_modules/js-yaml": {@@ -7887,6 +11226,32 @@"license": "(AFL-2.1 OR BSD-3-Clause)","optional": true},+ "node_modules/json-schema-ref-resolver": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz",+ "integrity": "sha512-EJAj1pgHc1hxF6vo2Z3s69fMjO1INq6eGHXZ8Z6wCQeldCuwxGK9Sxf4/cScGn3FZubCVUehfWtcDM/PLteCQw==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3"+ }+ },+ "node_modules/json-schema-resolver": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-resolver/-/json-schema-resolver-2.0.0.tgz",+ "integrity": "sha512-pJ4XLQP4Q9HTxl6RVDLJ8Cyh1uitSs0CzDBAz1uoJ4sRD/Bk7cFSXL1FUXDW3zJ7YnfliJx6eu8Jn283bpZ4Yg==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.1.1",+ "rfdc": "^1.1.4",+ "uri-js": "^4.2.2"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/Eomm/json-schema-resolver?sponsor=1"+ }+ },"node_modules/json-schema-traverse": {"version": "0.4.1","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",@@ -7931,6 +11296,15 @@"graceful-fs": "^4.1.6"}},+ "node_modules/jsox": {+ "version": "1.2.125",+ "resolved": "https://registry.npmjs.org/jsox/-/jsox-1.2.125.tgz",+ "integrity": "sha512-HIf1uwublnXZsy7p3yHTrhzMzrLO6xKnqXytT9pEil5QxaXi8eyer7Is4luF5hYSV4kD3v03Y32FWoAeVYTghQ==",+ "license": "MIT",+ "bin": {+ "jsox": "lib/cli.js"+ }+ },"node_modules/jsprim": {"version": "1.4.2","resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz",@@ -7982,12 +11356,30 @@"json-buffer": "3.0.1"}},+ "node_modules/kysely": {+ "version": "0.28.10",+ "resolved": "https://registry.npmjs.org/kysely/-/kysely-0.28.10.tgz",+ "integrity": "sha512-ksNxfzIW77OcZ+QWSAPC7yDqUSaIVwkTWnTPNiIy//vifNbwsSgQ57OkkncHxxpcBHM3LRfLAZVEh7kjq5twVA==",+ "license": "MIT",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/lazy-val": {"version": "1.0.5","resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz","integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==","license": "MIT"},+ "node_modules/leac": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/leac/-/leac-0.6.0.tgz",+ "integrity": "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==",+ "license": "MIT",+ "funding": {+ "url": "https://ko-fi.com/killymxi"+ }+ },"node_modules/levn": {"version": "0.4.1","resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",@@ -8002,6 +11394,26 @@"node": ">= 0.8.0"}},+ "node_modules/libpg-query": {+ "version": "13.6.0",+ "resolved": "https://registry.npmjs.org/libpg-query/-/libpg-query-13.6.0.tgz",+ "integrity": "sha512-zaCGweMgNiPRGRfNVR8wO+XNCl2jZOx8eOXTbaIPgkePI6UJ2FKbHrRSHO5qJSvLxGm5j/5ry7uAdFw3lCn7gw==",+ "license": "LICENSE IN LICENSE",+ "dependencies": {+ "@pgsql/types": "^13.11.0"+ }+ },+ "node_modules/light-my-request": {+ "version": "5.14.0",+ "resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-5.14.0.tgz",+ "integrity": "sha512-aORPWntbpH5esaYpGOOmri0OHDOe3wC5M2MQxZ9dvMLZm6DnaAn0kJlcbU9hwsQgLzmZyReKwFwwPkR+nHu5kA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "cookie": "^0.7.0",+ "process-warning": "^3.0.0",+ "set-cookie-parser": "^2.4.1"+ }+ },"node_modules/lightningcss": {"version": "1.30.2","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz",@@ -8339,6 +11751,18 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "license": "MIT",+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },"node_modules/lowercase-keys": {"version": "2.0.0","resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",@@ -8406,6 +11830,18 @@"resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz","integrity": "sha512-CkYQrPYZfWnu/DAmVCpTSX/xHpKZ80eKh2lAkyA6AJTef6bW+6JpbQZN5rofum7da+SyN1bi5ctTm+lTfcCW3g=="},+ "node_modules/marked": {+ "version": "15.0.12",+ "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz",+ "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==",+ "license": "MIT",+ "bin": {+ "marked": "bin/marked.js"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/matcher": {"version": "3.0.0","resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",@@ -8583,6 +12019,18 @@"url": "https://opencollective.com/unified"}},+ "node_modules/meow": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/meow/-/meow-14.0.0.tgz",+ "integrity": "sha512-JhC3R1f6dbspVtmF3vKjAWz1EVIvwFrGGPLSdU6rK79xBwHWTuHoLnRX/t1/zHS1Ch1Y2UtIrih7DAHuH9JFJA==",+ "license": "MIT",+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/micromark": {"version": "4.0.2","resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz",@@ -9277,12 +12725,43 @@"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==","license": "MIT"},+ "node_modules/mnemonist": {+ "version": "0.39.6",+ "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.6.tgz",+ "integrity": "sha512-A/0v5Z59y63US00cRSLiloEIw3t5G+MiKz4BhX21FI+YBJXBOGW0ohFxTxO08dsOYlzxo87T7vGfZKYp2bcAWA==",+ "license": "MIT",+ "dependencies": {+ "obliterator": "^2.0.1"+ }+ },+ "node_modules/module-details-from-path": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz",+ "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==",+ "license": "MIT"+ },+ "node_modules/moo": {+ "version": "0.5.2",+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz",+ "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==",+ "license": "BSD-3-Clause"+ },"node_modules/ms": {"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/mutative": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/mutative/-/mutative-1.3.0.tgz",+ "integrity": "sha512-8MJj6URmOZAV70dpFe1YnSppRTKC4DsMkXQiBDFayLcDI4ljGokHxmpqaBQuDWa4iAxWaJJ1PS8vAmbntjjKmQ==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=14.0"+ }+ },"node_modules/nan": {"version": "2.24.0","resolved": "https://registry.npmjs.org/nan/-/nan-2.24.0.tgz",@@ -9302,11 +12781,26 @@}],"license": "MIT",- "bin": {- "nanoid": "bin/nanoid.cjs"- },+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/nanostores": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/nanostores/-/nanostores-1.1.0.tgz",+ "integrity": "sha512-yJBmDJr18xy47dbNVlHcgdPrulSn1nhSE6Ns9vTG+Nx9VPT6iV1MD6aQFp/t52zpf82FhLLTXAXr30NuCnxvwA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT","engines": {- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ "node": "^20.0.0 || >=22.0.0"}},"node_modules/napi-build-utils": {@@ -9322,6 +12816,34 @@"dev": true,"license": "MIT"},+ "node_modules/nearley": {+ "version": "2.20.1",+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.20.1.tgz",+ "integrity": "sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ==",+ "license": "MIT",+ "dependencies": {+ "commander": "^2.19.0",+ "moo": "^0.5.0",+ "railroad-diagrams": "^1.0.0",+ "randexp": "0.4.6"+ },+ "bin": {+ "nearley-railroad": "bin/nearley-railroad.js",+ "nearley-test": "bin/nearley-test.js",+ "nearley-unparse": "bin/nearley-unparse.js",+ "nearleyc": "bin/nearleyc.js"+ },+ "funding": {+ "type": "individual",+ "url": "https://nearley.js.org/#give-to-nearley"+ }+ },+ "node_modules/nearley/node_modules/commander": {+ "version": "2.20.3",+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",+ "license": "MIT"+ },"node_modules/negotiator": {"version": "1.0.0","resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",@@ -9332,6 +12854,16 @@"node": ">= 0.6"}},+ "node_modules/next-themes": {+ "version": "0.4.6",+ "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz",+ "integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc"+ }+ },"node_modules/node-abi": {"version": "4.26.0","resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.26.0.tgz",@@ -9466,6 +12998,18 @@"dev": true,"license": "MIT"},+ "node_modules/node-sql-parser": {+ "version": "4.18.0",+ "resolved": "https://registry.npmjs.org/node-sql-parser/-/node-sql-parser-4.18.0.tgz",+ "integrity": "sha512-2YEOR5qlI1zUFbGMLKNfsrR5JUvFg9LxIRVE+xJe962pfVLH0rnItqLzv96XVs1Y1UIR8FxsXAuvX/lYAWZ2BQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "big-integer": "^1.6.48"+ },+ "engines": {+ "node": ">=8"+ }+ },"node_modules/nopt": {"version": "8.1.0","resolved": "https://registry.npmjs.org/nopt/-/nopt-8.1.0.tgz",@@ -9534,7 +13078,6 @@"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz","integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==","license": "MIT",- "optional": true,"engines": {"node": ">=0.10.0"}@@ -9550,6 +13093,21 @@"node": ">= 0.4"}},+ "node_modules/obliterator": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",+ "integrity": "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==",+ "license": "MIT"+ },+ "node_modules/on-exit-leak-free": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",+ "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==",+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/once": {"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",@@ -9575,6 +13133,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/openapi-types": {+ "version": "12.1.3",+ "resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz",+ "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",+ "license": "MIT"+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",@@ -9722,6 +13286,19 @@"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==","license": "MIT"},+ "node_modules/parseley": {+ "version": "0.12.1",+ "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.12.1.tgz",+ "integrity": "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==",+ "license": "MIT",+ "dependencies": {+ "leac": "^0.6.0",+ "peberminta": "^0.9.0"+ },+ "funding": {+ "url": "https://ko-fi.com/killymxi"+ }+ },"node_modules/path-exists": {"version": "4.0.0","resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",@@ -9752,6 +13329,12 @@"node": ">=8"}},+ "node_modules/path-parse": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",+ "license": "MIT"+ },"node_modules/path-scurry": {"version": "1.11.1","resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",@@ -9803,6 +13386,15 @@"url": "https://github.com/sponsors/jet2jet"}},+ "node_modules/peberminta": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/peberminta/-/peberminta-0.9.0.tgz",+ "integrity": "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==",+ "license": "MIT",+ "funding": {+ "url": "https://ko-fi.com/killymxi"+ }+ },"node_modules/pend": {"version": "1.2.0","resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",@@ -9817,6 +13409,170 @@"license": "MIT","optional": true},+ "node_modules/pg": {+ "name": "@supabase/pg",+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/@supabase/pg/-/pg-0.0.3.tgz",+ "integrity": "sha512-WW4VdNYQocmcg7dZYk92vHY2nhhMhxoJhZ20m7PzuKe8p4vSdkv2tSM8HUCpZDiLxC6djfVeMk39ukcwEpFdzg==",+ "license": "MIT",+ "dependencies": {+ "pg-connection-string": "^2.7.0",+ "pg-pool": "^3.8.0",+ "pg-protocol": "npm:@supabase/pg-protocol@^0.0.2",+ "pg-types": "^2.1.0",+ "pgpass": "1.x"+ },+ "engines": {+ "node": ">= 8.0.0"+ },+ "optionalDependencies": {+ "pg-cloudflare": "^1.1.1"+ },+ "peerDependencies": {+ "pg-native": ">=3.0.1"+ },+ "peerDependenciesMeta": {+ "pg-native": {+ "optional": true+ }+ }+ },+ "node_modules/pg-cloudflare": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",+ "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",+ "license": "MIT",+ "optional": true+ },+ "node_modules/pg-connection-string": {+ "version": "2.10.1",+ "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.10.1.tgz",+ "integrity": "sha512-iNzslsoeSH2/gmDDKiyMqF64DATUCWj3YJ0wP14kqcsf2TUklwimd+66yYojKwZCA7h2yRNLGug71hCBA2a4sw==",+ "license": "MIT"+ },+ "node_modules/pg-format": {+ "version": "1.0.4",+ "resolved": "https://registry.npmjs.org/pg-format/-/pg-format-1.0.4.tgz",+ "integrity": "sha512-YyKEF78pEA6wwTAqOUaHIN/rWpfzzIuMh9KdAhc3rSLQ/7zkRFcCgYBAEGatDstLyZw4g0s9SNICmaTGnBVeyw==",+ "license": "MIT",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/pg-int8": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",+ "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",+ "license": "ISC",+ "engines": {+ "node": ">=4.0.0"+ }+ },+ "node_modules/pg-protocol": {+ "name": "@supabase/pg-protocol",+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/@supabase/pg-protocol/-/pg-protocol-0.0.2.tgz",+ "integrity": "sha512-OLp5LeWRmfJy4vwV753hsCE90vzNSTSAwhsbinCIeoT455DHBufrkktVc4YvPXYEFj+EzpVKw/N0piX+AvBMBg==",+ "license": "MIT"+ },+ "node_modules/pg-types": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",+ "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",+ "license": "MIT",+ "dependencies": {+ "pg-int8": "1.0.1",+ "postgres-array": "~2.0.0",+ "postgres-bytea": "~1.0.0",+ "postgres-date": "~1.0.4",+ "postgres-interval": "^1.1.0"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/pg-types/node_modules/postgres-array": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",+ "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",+ "license": "MIT",+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/pg/node_modules/pg": {+ "version": "8.17.2",+ "resolved": "https://registry.npmjs.org/pg/-/pg-8.17.2.tgz",+ "integrity": "sha512-vjbKdiBJRqzcYw1fNU5KuHyYvdJ1qpcQg1CeBrHFqV1pWgHeVR6j/+kX0E1AAXfyuLUGY1ICrN2ELKA/z2HWzw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "pg-connection-string": "^2.10.1",+ "pg-pool": "^3.11.0",+ "pg-protocol": "^1.11.0",+ "pg-types": "2.2.0",+ "pgpass": "1.0.5"+ },+ "engines": {+ "node": ">= 16.0.0"+ },+ "optionalDependencies": {+ "pg-cloudflare": "^1.3.0"+ },+ "peerDependencies": {+ "pg-native": ">=3.0.1"+ },+ "peerDependenciesMeta": {+ "pg-native": {+ "optional": true+ }+ }+ },+ "node_modules/pg/node_modules/pg-pool": {+ "version": "3.11.0",+ "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.11.0.tgz",+ "integrity": "sha512-MJYfvHwtGp870aeusDh+hg9apvOe2zmpZJpyt+BMtzUWlVqbhFmMK6bOBXLBUPd7iRtIF9fZplDc7KrPN3PN7w==",+ "license": "MIT",+ "peerDependencies": {+ "pg": ">=8.0"+ }+ },+ "node_modules/pg/node_modules/pg/node_modules/pg-protocol": {+ "version": "1.11.0",+ "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.11.0.tgz",+ "integrity": "sha512-pfsxk2M9M3BuGgDOfuy37VNRRX3jmKgMjcvAcWqNDpZSf4cUmv8HSOl5ViRQFsfARFn0KuUQTgLxVMbNq5NW3g==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/pgpass": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",+ "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.1.0"+ }+ },+ "node_modules/pgsql-deparser": {+ "version": "13.19.1",+ "resolved": "https://registry.npmjs.org/pgsql-deparser/-/pgsql-deparser-13.19.1.tgz",+ "integrity": "sha512-iCkE5h6wrXtRjT8ygdj7YktDVE3TwTYOLDmpEGT+8WWY47722584Zcr8kN/mk+2nA8mMVqH1Wwzwuu+aAdvjpQ==",+ "license": "MIT",+ "dependencies": {+ "@pgsql/types": "^13.11.1"+ }+ },+ "node_modules/pgsql-parser": {+ "version": "13.19.1",+ "resolved": "https://registry.npmjs.org/pgsql-parser/-/pgsql-parser-13.19.1.tgz",+ "integrity": "sha512-px+T9MY97vMzJWupiKSBXONJuQXtP6ix63RDH0xkZWG+Nv0qw45CnfMZrySmNp21YEOXVvlZTNTYN1MxulC6iQ==",+ "license": "MIT",+ "dependencies": {+ "@pgsql/types": "13.11.1",+ "libpg-query": "13.6.0",+ "pgsql-deparser": "13.19.1"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -9837,6 +13593,59 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/pino": {+ "version": "9.14.0",+ "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz",+ "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==",+ "license": "MIT",+ "dependencies": {+ "@pinojs/redact": "^0.4.0",+ "atomic-sleep": "^1.0.0",+ "on-exit-leak-free": "^2.1.0",+ "pino-abstract-transport": "^2.0.0",+ "pino-std-serializers": "^7.0.0",+ "process-warning": "^5.0.0",+ "quick-format-unescaped": "^4.0.3",+ "real-require": "^0.2.0",+ "safe-stable-stringify": "^2.3.1",+ "sonic-boom": "^4.0.1",+ "thread-stream": "^3.0.0"+ },+ "bin": {+ "pino": "bin.js"+ }+ },+ "node_modules/pino-abstract-transport": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz",+ "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==",+ "license": "MIT",+ "dependencies": {+ "split2": "^4.0.0"+ }+ },+ "node_modules/pino-std-serializers": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",+ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",+ "license": "MIT"+ },+ "node_modules/pino/node_modules/process-warning": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz",+ "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/fastify"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fastify"+ }+ ],+ "license": "MIT"+ },"node_modules/plist": {"version": "3.1.0","resolved": "https://registry.npmjs.org/plist/-/plist-3.1.0.tgz",@@ -9888,6 +13697,45 @@"dev": true,"license": "MIT"},+ "node_modules/postgres-array": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz",+ "integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/postgres-bytea": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",+ "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-date": {+ "version": "1.0.7",+ "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",+ "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/postgres-interval": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",+ "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",+ "license": "MIT",+ "dependencies": {+ "xtend": "^4.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },"node_modules/postject": {"version": "1.0.0-alpha.6","resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",@@ -9982,7 +13830,6 @@"version": "3.8.1","resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz","integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",- "dev": true,"license": "MIT","bin": {"prettier": "bin/prettier.cjs"@@ -9994,6 +13841,36 @@"url": "https://github.com/prettier/prettier?sponsor=1"}},+ "node_modules/prettier-plugin-sql": {+ "version": "0.17.1",+ "resolved": "https://registry.npmjs.org/prettier-plugin-sql/-/prettier-plugin-sql-0.17.1.tgz",+ "integrity": "sha512-CR9UpTkUSC/f69AV597hnYcBo77iUhsBPkUER7BUa4YHRRtRUJGfL5LDoHAlUHWGTZNiJdHHELlzK6I3R9XuAw==",+ "license": "MIT",+ "dependencies": {+ "jsox": "^1.2.118",+ "node-sql-parser": "^4.11.0",+ "sql-formatter": "^14.0.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": "^14.18.0 || >=16.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/unts"+ },+ "peerDependencies": {+ "prettier": "^3.0.3"+ }+ },+ "node_modules/prismjs": {+ "version": "1.30.0",+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",+ "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/proc-log": {"version": "5.0.0","resolved": "https://registry.npmjs.org/proc-log/-/proc-log-5.0.0.tgz",@@ -10010,6 +13887,12 @@"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==","license": "MIT"},+ "node_modules/process-warning": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-3.0.0.tgz",+ "integrity": "sha512-mqn0kFRl0EoqhnL0GQ0veqFHyIN1yig9RHh/InzORTUiZHFRAur+aMtRkELNwGs9aNwKS6tg/An4NYBPGwvtzQ==",+ "license": "MIT"+ },"node_modules/progress": {"version": "2.0.3","resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",@@ -10019,6 +13902,18 @@"node": ">=0.4.0"}},+ "node_modules/prom-client": {+ "version": "14.2.0",+ "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-14.2.0.tgz",+ "integrity": "sha512-sF308EhTenb/pDRPakm+WgiN+VdM/T1RaHj1x+MvAuT8UiQP8JmOEbxVqtkbfR4LrvOg5n7ic01kRBDGXjYikA==",+ "license": "Apache-2.0",+ "dependencies": {+ "tdigest": "^0.1.1"+ },+ "engines": {+ "node": ">=10"+ }+ },"node_modules/promise-retry": {"version": "2.0.1","resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",@@ -10033,6 +13928,17 @@"node": ">=10"}},+ "node_modules/prop-types": {+ "version": "15.8.1",+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",+ "license": "MIT",+ "dependencies": {+ "loose-envify": "^1.4.0",+ "object-assign": "^4.1.1",+ "react-is": "^16.13.1"+ }+ },"node_modules/property-information": {"version": "7.1.0","resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",@@ -10043,6 +13949,19 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/psl": {"version": "1.15.0","resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",@@ -10070,12 +13989,37 @@"version": "2.3.1","resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz","integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",- "devOptional": true,"license": "MIT","engines": {"node": ">=6"}},+ "node_modules/pvtsutils": {+ "version": "1.3.6",+ "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",+ "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "tslib": "^2.8.1"+ }+ },+ "node_modules/pvutils": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",+ "integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",+ "license": "MIT",+ "peer": true,+ "engines": {+ "node": ">=16.0.0"+ }+ },+ "node_modules/qr.js": {+ "version": "0.0.0",+ "resolved": "https://registry.npmjs.org/qr.js/-/qr.js-0.0.0.tgz",+ "integrity": "sha512-c4iYnWb+k2E+vYpRimHqSu575b1/wKl4XFeJGpFmrJQz5I88v9aY2czh7s0w36srfCM1sXgC/xpoJz5dJfq+OQ==",+ "license": "MIT"+ },"node_modules/qs": {"version": "6.5.3","resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz",@@ -10086,6 +14030,12 @@"node": ">=0.6"}},+ "node_modules/quick-format-unescaped": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",+ "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==",+ "license": "MIT"+ },"node_modules/quick-lru": {"version": "5.1.1","resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",@@ -10093,10 +14043,38 @@"dev": true,"license": "MIT","engines": {- "node": ">=10"- },- "funding": {- "url": "https://github.com/sponsors/sindresorhus"+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/railroad-diagrams": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",+ "integrity": "sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A==",+ "license": "CC0-1.0"+ },+ "node_modules/randexp": {+ "version": "0.4.6",+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",+ "license": "MIT",+ "dependencies": {+ "discontinuous-range": "1.0.0",+ "ret": "~0.1.10"+ },+ "engines": {+ "node": ">=0.12"+ }+ },+ "node_modules/randexp/node_modules/ret": {+ "version": "0.1.15",+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz",+ "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.12"}},"node_modules/rc": {@@ -10132,6 +14110,19 @@"node": ">=0.10.0"}},+ "node_modules/react-async-script": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/react-async-script/-/react-async-script-1.2.0.tgz",+ "integrity": "sha512-bCpkbm9JiAuMGhkqoAiC0lLkb40DJ0HOEJIku+9JDjxX3Rcs+ztEOG13wbrOskt3n2DTrjshhaQ/iay+SnGg5Q==",+ "license": "MIT",+ "dependencies": {+ "hoist-non-react-statics": "^3.3.0",+ "prop-types": "^15.5.0"+ },+ "peerDependencies": {+ "react": ">=16.4.1"+ }+ },"node_modules/react-dom": {"version": "19.2.3","resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",@@ -10144,6 +14135,41 @@"react": "^19.2.3"}},+ "node_modules/react-google-recaptcha": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/react-google-recaptcha/-/react-google-recaptcha-3.1.0.tgz",+ "integrity": "sha512-cYW2/DWas8nEKZGD7SCu9BSuVz8iOcOLHChHyi7upUuVhkpkhYG/6N3KDiTQ3XAiZ2UAZkfvYKMfAHOzBOcGEg==",+ "license": "MIT",+ "dependencies": {+ "prop-types": "^15.5.0",+ "react-async-script": "^1.2.0"+ },+ "peerDependencies": {+ "react": ">=16.4.1"+ }+ },+ "node_modules/react-hook-form": {+ "version": "7.71.1",+ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",+ "integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/react-hook-form"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17 || ^18 || ^19"+ }+ },+ "node_modules/react-is": {+ "version": "16.13.1",+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",+ "license": "MIT"+ },"node_modules/react-markdown": {"version": "10.1.0","resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",@@ -10171,6 +14197,19 @@"react": ">=18"}},+ "node_modules/react-qr-code": {+ "version": "2.0.18",+ "resolved": "https://registry.npmjs.org/react-qr-code/-/react-qr-code-2.0.18.tgz",+ "integrity": "sha512-v1Jqz7urLMhkO6jkgJuBYhnqvXagzceg3qJUWayuCK/c6LTIonpWbwxR1f1APGd4xrW/QcQEovNrAojbUz65Tg==",+ "license": "MIT",+ "dependencies": {+ "prop-types": "^15.8.1",+ "qr.js": "0.0.0"+ },+ "peerDependencies": {+ "react": "*"+ }+ },"node_modules/react-refresh": {"version": "0.17.0","resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",@@ -10277,6 +14316,22 @@"node": ">= 6"}},+ "node_modules/real-require": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",+ "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",+ "license": "MIT",+ "engines": {+ "node": ">= 12.13.0"+ }+ },+ "node_modules/reflect-metadata": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",+ "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",+ "license": "Apache-2.0",+ "peer": true+ },"node_modules/remark-parse": {"version": "11.0.0","resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",@@ -10368,6 +14423,29 @@"node": ">=0.10.0"}},+ "node_modules/require-from-string": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/require-in-the-middle": {+ "version": "7.5.2",+ "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-7.5.2.tgz",+ "integrity": "sha512-gAZ+kLqBdHarXB64XpAe2VCjB7rIRv+mU8tfRWziHRJ5umKsIHN2tLLv6EtMw7WCdP19S0ERVMldNvxYCHnhSQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.3.5",+ "module-details-from-path": "^1.0.3",+ "resolve": "^1.22.8"+ },+ "engines": {+ "node": ">=8.6.0"+ }+ },"node_modules/resedit": {"version": "1.7.2","resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz",@@ -10386,6 +14464,26 @@"url": "https://github.com/sponsors/jet2jet"}},+ "node_modules/resolve": {+ "version": "1.22.11",+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",+ "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==",+ "license": "MIT",+ "dependencies": {+ "is-core-module": "^2.16.1",+ "path-parse": "^1.0.7",+ "supports-preserve-symlinks-flag": "^1.0.0"+ },+ "bin": {+ "resolve": "bin/resolve"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/resolve-alpn": {"version": "1.2.1","resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",@@ -10430,6 +14528,15 @@"node": ">=8"}},+ "node_modules/ret": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.4.3.tgz",+ "integrity": "sha512-0f4Memo5QP7WQyUEAYUO3esD/XjOc3Zjjg5CPsAq1p8sIu0XPeMbHJemKA0BO7tV0X7+A0FoEpbmHXWxPyD3wQ==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },"node_modules/retry": {"version": "0.12.0","resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",@@ -10440,6 +14547,22 @@"node": ">= 4"}},+ "node_modules/reusify": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",+ "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",+ "license": "MIT",+ "engines": {+ "iojs": ">=1.0.0",+ "node": ">=0.10.0"+ }+ },+ "node_modules/rfdc": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",+ "license": "MIT"+ },"node_modules/rimraf": {"version": "2.6.3","resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",@@ -10519,6 +14642,12 @@"fsevents": "~2.3.2"}},+ "node_modules/rou3": {+ "version": "0.7.12",+ "resolved": "https://registry.npmjs.org/rou3/-/rou3-0.7.12.tgz",+ "integrity": "sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==",+ "license": "MIT"+ },"node_modules/rxjs": {"version": "7.8.2","resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",@@ -10549,6 +14678,24 @@],"license": "MIT"},+ "node_modules/safe-regex2": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-3.1.0.tgz",+ "integrity": "sha512-RAAZAGbap2kBfbVhvmnTFv73NWLMvDGOITFYTZBAaY8eR+Ir4ef7Up/e7amo+y1+AH+3PtLkrt9mvcTsG9LXug==",+ "license": "MIT",+ "dependencies": {+ "ret": "~0.4.0"+ }+ },+ "node_modules/safe-stable-stringify": {+ "version": "2.5.0",+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ }+ },"node_modules/safer-buffer": {"version": "2.1.2","resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",@@ -10581,6 +14728,24 @@"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==","license": "MIT"},+ "node_modules/secure-json-parse": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",+ "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==",+ "license": "BSD-3-Clause"+ },+ "node_modules/selderee": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz",+ "integrity": "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA==",+ "license": "MIT",+ "dependencies": {+ "parseley": "^0.12.0"+ },+ "funding": {+ "url": "https://ko-fi.com/killymxi"+ }+ },"node_modules/semver": {"version": "6.3.1","resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",@@ -10623,6 +14788,12 @@"license": "ISC","optional": true},+ "node_modules/set-cookie-parser": {+ "version": "2.7.2",+ "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",+ "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",+ "license": "MIT"+ },"node_modules/shadcn-ui": {"version": "0.9.5","resolved": "https://registry.npmjs.org/shadcn-ui/-/shadcn-ui-0.9.5.tgz",@@ -10683,6 +14854,12 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/shimmer": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz",+ "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==",+ "license": "BSD-2-Clause"+ },"node_modules/signal-exit": {"version": "3.0.7","resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",@@ -10818,6 +14995,32 @@"node": ">= 14"}},+ "node_modules/sonic-boom": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.0.tgz",+ "integrity": "sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==",+ "license": "MIT",+ "dependencies": {+ "atomic-sleep": "^1.0.0"+ }+ },+ "node_modules/sonner": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz",+ "integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },+ "node_modules/sorted-btree": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/sorted-btree/-/sorted-btree-1.8.1.tgz",+ "integrity": "sha512-395+XIP+wqNn3USkFSrNz7G3Ss/MXlZEqesxvzCRFwL14h6e8LukDHdLBePn5pwbm5OQ9vGu8mDyz2lLDIqamQ==",+ "license": "MIT",+ "peer": true+ },"node_modules/source-map": {"version": "0.6.1","resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",@@ -10877,6 +15080,15 @@"node": "*"}},+ "node_modules/split2": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",+ "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",+ "license": "ISC",+ "engines": {+ "node": ">= 10.x"+ }+ },"node_modules/sprintf-js": {"version": "1.1.3","resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",@@ -10885,6 +15097,20 @@"license": "BSD-3-Clause","optional": true},+ "node_modules/sql-formatter": {+ "version": "14.0.0",+ "resolved": "https://registry.npmjs.org/sql-formatter/-/sql-formatter-14.0.0.tgz",+ "integrity": "sha512-VcHYMRvZqg3RNjjxNB/puT9O1hR5QLXTvgTaBtxXcvmRQwSnH9M+oW2Ti+uFuVVU8HoNlOjU2uKHv8c0FQNsdQ==",+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1",+ "get-stdin": "=8.0.0",+ "nearley": "^2.20.1"+ },+ "bin": {+ "sql-formatter": "bin/sql-formatter-cli.cjs"+ }+ },"node_modules/sshpk": {"version": "1.18.0","resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz",@@ -11068,6 +15294,19 @@"node": ">= 8.0"}},+ "node_modules/superjson": {+ "version": "2.2.6",+ "resolved": "https://registry.npmjs.org/superjson/-/superjson-2.2.6.tgz",+ "integrity": "sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "copy-anything": "^4"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/supports-color": {"version": "8.1.1","resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",@@ -11084,6 +15323,18 @@"url": "https://github.com/chalk/supports-color?sponsor=1"}},+ "node_modules/supports-preserve-symlinks-flag": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/tailwind-merge": {"version": "3.4.0","resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",@@ -11098,7 +15349,6 @@"version": "4.1.18","resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz","integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==",- "dev": true,"license": "MIT"},"node_modules/tapable": {@@ -11174,6 +15424,15 @@"node": ">=18"}},+ "node_modules/tdigest": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.2.tgz",+ "integrity": "sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==",+ "license": "MIT",+ "dependencies": {+ "bintrees": "1.0.2"+ }+ },"node_modules/temp": {"version": "0.9.4","resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz",@@ -11238,6 +15497,15 @@"node": ">= 10.0.0"}},+ "node_modules/thread-stream": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",+ "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==",+ "license": "MIT",+ "dependencies": {+ "real-require": "^0.2.0"+ }+ },"node_modules/through": {"version": "2.3.8","resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",@@ -11307,6 +15575,15 @@"tmp": "^0.2.0"}},+ "node_modules/toad-cache": {+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/toad-cache/-/toad-cache-3.7.0.tgz",+ "integrity": "sha512-/m8M+2BJUpoJdgAHoG+baCwBT+tf2VraSfkBgl0Y00qIWt41DJ8R5B8nsEw0I58YwF5IZH6z24/2TobDKnqSWw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/tough-cookie": {"version": "2.5.0","resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",@@ -11380,6 +15657,26 @@"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==","license": "0BSD"},+ "node_modules/tsyringe": {+ "version": "4.10.0",+ "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",+ "integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "tslib": "^1.9.3"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/tsyringe/node_modules/tslib": {+ "version": "1.14.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",+ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",+ "license": "0BSD",+ "peer": true+ },"node_modules/tunnel-agent": {"version": "0.6.0","resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",@@ -11445,7 +15742,6 @@"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz","integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",- "dev": true,"license": "Apache-2.0","peer": true,"bin": {@@ -11480,11 +15776,61 @@"typescript": ">=4.8.4 <6.0.0"}},+ "node_modules/ua-is-frozen": {+ "version": "0.1.2",+ "resolved": "https://registry.npmjs.org/ua-is-frozen/-/ua-is-frozen-0.1.2.tgz",+ "integrity": "sha512-RwKDW2p3iyWn4UbaxpP2+VxwqXh0jpvdxsYpZ5j/MLLiQOfbsV5shpgQiw93+KMYQPcteeMQ289MaAFzs3G9pw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/faisalman"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ua-parser-js"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/faisalman"+ }+ ],+ "license": "MIT"+ },+ "node_modules/ua-parser-js": {+ "version": "2.0.8",+ "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-2.0.8.tgz",+ "integrity": "sha512-BdnBM5waFormdrOFBU+cA90R689V0tWUWlIG2i30UXxElHjuCu5+dOV2Etw3547jcQ/yaLtPm9wrqIuOY2bSJg==",+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/ua-parser-js"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/faisalman"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/faisalman"+ }+ ],+ "license": "AGPL-3.0-or-later",+ "dependencies": {+ "detect-europe-js": "^0.1.2",+ "is-standalone-pwa": "^0.1.1",+ "ua-is-frozen": "^0.1.2"+ },+ "bin": {+ "ua-parser-js": "script/cli.js"+ },+ "engines": {+ "node": "*"+ }+ },"node_modules/undici-types": {"version": "6.21.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz","integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",- "dev": true,"license": "MIT"},"node_modules/unified": {@@ -11693,7 +16039,6 @@"version": "4.4.1","resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz","integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",- "devOptional": true,"license": "BSD-2-Clause","dependencies": {"punycode": "^2.1.0"@@ -11742,6 +16087,15 @@}}},+ "node_modules/use-sync-external-store": {+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",+ "license": "MIT",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/usocket": {"version": "0.3.0","resolved": "https://registry.npmjs.org/usocket/-/usocket-0.3.0.tgz",@@ -11969,6 +16323,19 @@"uuid": "bin/uuid"}},+ "node_modules/vaul": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",+ "integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-dialog": "^1.1.1"+ },+ "peerDependencies": {+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"+ }+ },"node_modules/verror": {"version": "1.10.1","resolved": "https://registry.npmjs.org/verror/-/verror-1.10.1.tgz",@@ -12088,6 +16455,15 @@}}},+ "node_modules/warning": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz",+ "integrity": "sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==",+ "license": "MIT",+ "dependencies": {+ "loose-envify": "^1.0.0"+ }+ },"node_modules/wcwidth": {"version": "1.0.1","resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz",@@ -12098,6 +16474,13 @@"defaults": "^1.0.3"}},+ "node_modules/web-worker": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz",+ "integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",+ "license": "Apache-2.0",+ "peer": true+ },"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",@@ -12230,6 +16613,15 @@"node": ">=8.0"}},+ "node_modules/xtend": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",+ "license": "MIT",+ "engines": {+ "node": ">=0.4"+ }+ },"node_modules/y18n": {"version": "5.0.8","resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",@@ -12247,6 +16639,21 @@"dev": true,"license": "ISC"},+ "node_modules/yaml": {+ "version": "2.8.2",+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",+ "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",+ "license": "ISC",+ "bin": {+ "yaml": "bin.mjs"+ },+ "engines": {+ "node": ">= 14.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/eemeli"+ }+ },"node_modules/yargs": {"version": "17.7.2","resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",@@ -12300,6 +16707,15 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/zod": {+ "version": "4.1.12",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.12.tgz",+ "integrity": "sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"node_modules/zwitch": {"version": "2.0.4","resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",diff --git a/package.json b/package.jsonindex 50517e589..49a52ced4 100644--- a/package.json+++ b/package.json@@ -1,13 +1,14 @@{"name": "open-whispr",- "version": "1.3.4",+ "version": "1.4.0","description": "A desktop dictation application using whisper.cpp for speech-to-text transcription","main": "main.js","private": true,"scripts": {"compile:globe": "node scripts/build-globe-listener.js",+ "compile:fast-paste": "node scripts/build-macos-fast-paste.js","compile:winkeys": "node scripts/build-windows-key-listener.js",- "compile:native": "npm run compile:globe && npm run compile:winkeys",+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys","prestart": "npm run compile:native","start": "electron .","predev": "npm run compile:native",@@ -80,6 +81,8 @@"vite": "^6.3.5"},"dependencies": {+ "@neondatabase/neon-js": "^0.1.0-beta.22",+ "@radix-ui/react-accordion": "^1.1.2","@radix-ui/react-dialog": "^1.1.14","@radix-ui/react-dropdown-menu": "^2.1.15","@radix-ui/react-label": "^2.1.7",@@ -95,6 +98,7 @@"electron-updater": "^6.6.2","ffmpeg-static": "^5.2.0","lucide-react": "^0.518.0",+ "object-assign": "^4.1.1","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0",diff --git a/plan.md b/plan.mdnew file mode 100644index 000000000..56f26cc67--- /dev/null+++ b/plan.md@@ -0,0 +1,927 @@+# Cloud Transcription & Usage Paywall++## Overview++Transform OpenWhispr into a "just works" experience for signed-in users. The app sends audio to an OpenWhispr API (Vercel), which handles both transcription and reasoning server-side — no user configuration needed. Free tier: 2000 words/day. Pro subscription via Stripe for unlimited. Power users can switch to BYOK (bring your own key) for unlimited free usage. Local mode unchanged.++The server-side API is **provider-agnostic** — transcription and reasoning are routed through a unified provider interface. Initial providers: Groq (transcription + fast reasoning), OpenRouter (model variety). Future providers (Baseten, Deepgram, OpenAI Whisper, etc.) slot in without API changes.++## Architecture++```+Electron App → IPC (main process) → openwhispr-api (Vercel) → Provider (transcription)+ (attaches session cookies) ↕ → Provider (reasoning)+ Neon Postgres ↕+ ↕ Stripe Webhooks+```++All API calls route through Electron's main process via IPC — same proven pattern as the existing Anthropic handler. This eliminates CORS entirely and keeps auth simple (session cookies forwarded by main process).++**Three transcription modes:**+| Mode | Who | Limit | Transcription | Reasoning |+|------|-----|-------|---------------|-----------|+| OpenWhispr Cloud (default) | Signed-in users | 2000 words/day free, unlimited Pro | Vercel API → provider | Vercel API → provider |+| BYOK | Advanced users with own keys | Unlimited | Direct to provider (existing) | Direct to provider (existing) |+| Local | Privacy users / offline | Unlimited | whisper.cpp / Parakeet | Own keys or local LLM |++---++## Step 0: Dead Code Cleanup (Prerequisite PR)++Merge before starting feature work:+- `preload.js:171` — Remove dead `onOAuthCallback` handler+- `src/components/AuthenticationStep.tsx:64` — Remove stale oauth-callback comment++---++## Step 1: Create `openwhispr-api` Repo++Location: `~/Projects/OpenWhispr/openwhispr-api/`++```+openwhispr-api/+ package.json # @neondatabase/serverless, stripe, openai (provider-compatible), typescript+ tsconfig.json+ vercel.json # maxDuration: 30s for transcribe, 60s for reason+ .env.local # Local dev secrets+ lib/+ db.ts # Neon serverless Postgres client+ auth.ts # Validate Neon Auth session → userId+ stripe.ts # Stripe client init+ usage.ts # countWords(), checkLimit(), getTodayUsage()+ providers.ts # Provider registry — unified interface for transcription + reasoning+ api/+ transcribe.ts # POST — receive audio, route to provider, return text + usage+ reason.ts # POST — receive text, route to provider, return result+ usage.ts # GET — current day's word count + limit info+ stripe/+ checkout.ts # POST — create Stripe Checkout session+ portal.ts # POST — create Stripe Customer Portal session+ webhook.ts # POST — handle Stripe events+ checkout/+ success.ts # GET — static "Payment successful, close this tab" page+ cancel.ts # GET — static "Payment cancelled" page+```++### Provider Registry (`lib/providers.ts`)++Unified interface — providers are swappable without changing API endpoints or client code:++```typescript+interface TranscriptionProvider {+ id: string; // 'groq' | 'deepgram' | 'openai' | 'baseten' | ...+ transcribe(audio: Blob, opts: TranscribeOpts): Promise<TranscribeResult>;+}++interface ReasoningProvider {+ id: string; // 'groq' | 'openrouter' | 'baseten' | ...+ complete(messages: Message[], opts: ReasonOpts): Promise<ReasonResult>;+ models: ModelDefinition[]; // available models for this provider+}++interface TranscribeOpts {+ language?: string;+ prompt?: string; // custom dictionary hints+ model?: string; // provider-specific model ID+}++interface ReasonOpts {+ model: string;+ maxTokens?: number;+ temperature?: number;+}++// Provider implementations are simple adapters — most use OpenAI-compatible API format+// Adding a new provider = one new file implementing the interface + register it+```++Initial providers:+- **Groq**: transcription (`whisper-large-v3-turbo`) + fast reasoning (`llama-3.3-70b-versatile`)+- **OpenRouter**: reasoning model variety (Claude, Gemini, GPT via OpenAI-compatible API)++Future providers slot in by implementing the interface:+- **Baseten**: custom deployed models (transcription + reasoning)+- **Deepgram**: alternative transcription+- **OpenAI**: Whisper API transcription++The active provider is configured via environment variables — no code changes needed to switch:+```+TRANSCRIPTION_PROVIDER=groq # or 'deepgram', 'openai', 'baseten'+TRANSCRIPTION_MODEL=whisper-large-v3-turbo+REASONING_PROVIDERS=groq,openrouter # comma-separated, first is default+```++### Environment Variables (Vercel)+```+DATABASE_URL=<neon-postgres-connection-string>+NEON_AUTH_URL=<same as VITE_NEON_AUTH_URL>++# Provider keys (only configure what you use)+GROQ_API_KEY=<for transcription + fast reasoning>+OPENROUTER_API_KEY=<for model variety>+# Future: DEEPGRAM_API_KEY, BASETEN_API_KEY, OPENAI_API_KEY++# Provider routing+TRANSCRIPTION_PROVIDER=groq+TRANSCRIPTION_MODEL=whisper-large-v3-turbo+REASONING_PROVIDERS=groq,openrouter++# Stripe+STRIPE_SECRET_KEY=sk_...+STRIPE_WEBHOOK_SECRET=whsec_...+STRIPE_PRICE_ID=price_...+```++---++## Step 2: Neon Postgres Schema++Run in Neon console. Neon Auth already has a `user` table.++```sql+-- Transcription history (extensible for future metadata)+CREATE TABLE transcriptions (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ user_id TEXT NOT NULL,+ text TEXT NOT NULL,+ word_count INTEGER NOT NULL,+ source TEXT NOT NULL DEFAULT 'cloud', -- 'cloud' | 'byok' | 'local'+ provider TEXT, -- 'groq' | 'deepgram' | 'openai' | 'baseten' | null+ model TEXT, -- provider-specific model ID+ language TEXT, -- ISO 639-1 code+ audio_duration_ms INTEGER, -- original audio length (for analytics)+ processing_ms INTEGER, -- server-side processing time+ metadata JSONB DEFAULT '{}', -- extensible: { prompt, confidence, segments, ... }+ created_at TIMESTAMPTZ DEFAULT now()+);+CREATE INDEX idx_tx_user ON transcriptions(user_id, created_at DESC);+CREATE INDEX idx_tx_source ON transcriptions(source);+CREATE INDEX idx_tx_user_date ON transcriptions(user_id, created_at)+ WHERE source = 'cloud'; -- optimizes daily usage aggregation++-- Subscription state (Stripe-managed)+CREATE TABLE subscriptions (+ user_id TEXT PRIMARY KEY,+ stripe_customer_id TEXT UNIQUE,+ stripe_subscription_id TEXT UNIQUE,+ plan TEXT NOT NULL DEFAULT 'free', -- 'free' | 'pro' | future tiers+ status TEXT NOT NULL DEFAULT 'active', -- 'active' | 'past_due' | 'canceled' | 'trialing'+ current_period_start TIMESTAMPTZ,+ current_period_end TIMESTAMPTZ,+ cancel_at_period_end BOOLEAN DEFAULT false, -- user requested cancellation+ metadata JSONB DEFAULT '{}', -- extensible: { referral, coupon, ... }+ created_at TIMESTAMPTZ DEFAULT now(),+ updated_at TIMESTAMPTZ DEFAULT now()+);+```++**Schema design notes:**+- `metadata JSONB` columns on `transcriptions` and `subscriptions` provide extensibility without schema migrations+- `provider` + `model` on transcriptions enable per-provider analytics and cost tracking+- `audio_duration_ms` + `processing_ms` enable performance monitoring+- Daily usage is derived from `transcriptions` via `SUM(word_count) WHERE created_at >= CURRENT_DATE` — no separate usage table needed+- `idx_tx_user_date` partial index (filtered to `source = 'cloud'`) keeps the aggregate query fast+- `cancel_at_period_end` tracks pending cancellations (Stripe pattern)+- `current_period_start` needed for usage reset alignment++---++## Step 3: API Endpoints++### `POST /api/transcribe` — Server-side transcription+- **Auth**: Session cookie (forwarded by Electron main process)+- **Request**: `multipart/form-data` — `file` (audio blob), `language`, `prompt` (dictionary)+- **Flow**:+ 1. Validate session → get userId+ 2. Route audio to active transcription provider (via provider registry)+ 3. Count words from result: `text.trim().split(/\s+/).length`+ 4. In one transaction:+ - INSERT `transcriptions` row (with word_count)+ - Aggregate today's usage: `SELECT COALESCE(SUM(word_count), 0) FROM transcriptions WHERE user_id = $1 AND created_at >= CURRENT_DATE AND source = 'cloud'`+ - If aggregate > plan limit: return text + `limitReached: true`+ 5. Return `{ text, wordsUsed, wordsRemaining, plan, limitReached }`+- **Limit logic**: Post-transcription check. The audio is already transcribed (API cost incurred) — don't waste it. `limitReached: true` tells the client the *next* request will be blocked. Pre-flight check via `GET /api/usage` handles UI state.+- **No separate usage table**: Daily usage is derived from the `transcriptions` table via aggregate query. The `idx_tx_user_date` partial index keeps this fast.++### `POST /api/reason` — Server-side reasoning+- **Auth**: Session cookie+- **Request**: `{ text, model?, agentName?, customDictionary? }`+- **Flow**:+ 1. Validate session → get userId+ 2. Resolve model → provider via provider registry+ 3. Build system prompt (reuse `getSystemPrompt()` logic from Electron app)+ 4. Call provider+ 5. Return `{ text, model, provider }`+- **No usage counting** for reasoning (only transcription counts toward word limit)++### `GET /api/usage`+- Returns `{ wordsUsed, wordsRemaining, limit, plan, isSubscribed, resetAt }`+- `wordsUsed` derived from: `SELECT COALESCE(SUM(word_count), 0) FROM transcriptions WHERE user_id = $1 AND created_at >= CURRENT_DATE AND source = 'cloud'`+- `resetAt`: midnight UTC of current day (so client can show countdown)++### `POST /api/stripe/checkout`+- Creates Stripe Checkout session+- Success/cancel URLs point to `/checkout/success` and `/checkout/cancel` on the Vercel API+- Returns `{ url }`++### `POST /api/stripe/portal`+- Creates Customer Portal session, returns `{ url }`++### `POST /api/stripe/webhook`+- Events: `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.payment_failed`+- Updates `subscriptions` table (plan, status, period dates, cancel_at_period_end)++### `GET /checkout/success` + `GET /checkout/cancel`+- Simple static HTML pages: "Payment successful, you can close this tab" / "Payment cancelled"+- Electron app polls `/api/usage` after opening checkout URL and detects plan change++### Auth Validation (`lib/auth.ts`)+```typescript+// Session cookies forwarded from Electron main process+async function validateSession(cookieHeader: string): Promise<{ userId: string } | null> {+ const res = await fetch(`${NEON_AUTH_URL}/api/auth/get-session`, {+ headers: { Cookie: cookieHeader }+ });+ if (!res.ok) return null;+ const data = await res.json();+ return data?.session ? { userId: data.session.userId } : null;+}+```++---++## Step 4: Electron App Changes++### Key Decision: IPC-First Architecture++All cloud API calls go through the main process via IPC. This:+- Eliminates CORS (main process is not subject to browser CORS)+- Reuses session cookies naturally (main process has access to session storage)+- Follows existing Anthropic handler pattern (`ipcHandlers.js:688`)+- Keeps renderer process thin and secure++### New IPC Handlers (in `ipcHandlers.js`)++```+cloud-transcribe — forwards audio + metadata to Vercel /api/transcribe+cloud-reason — forwards text + config to Vercel /api/reason+cloud-usage — fetches /api/usage+cloud-checkout — creates Stripe checkout session, returns URL+cloud-portal — creates Stripe portal session, returns URL+```++Each handler:+1. Gets session cookies from Electron's session store+2. Makes fetch request to Vercel API with cookies attached+3. Returns `{ success, data }` or `{ success: false, error, code }` (existing IPC pattern)++### New IPC Channels (in `preload.js`)++```javascript+cloudTranscribe: (audioBuffer, opts) => ipcRenderer.invoke('cloud-transcribe', audioBuffer, opts),+cloudReason: (text, opts) => ipcRenderer.invoke('cloud-reason', text, opts),+cloudUsage: () => ipcRenderer.invoke('cloud-usage'),+cloudCheckout: () => ipcRenderer.invoke('cloud-checkout'),+cloudPortal: () => ipcRenderer.invoke('cloud-portal'),+```++### New Setting: `cloudTranscriptionMode`++Add to `src/hooks/useSettings.ts`:+- `cloudTranscriptionMode`: `"openwhispr"` | `"byok"` (default: `"openwhispr"`)+- When signed in + `useLocalWhisper === false`: determines cloud routing+- When not signed in: ignored, falls through to BYOK++### New Files++**`src/hooks/useUsage.ts`** — Usage tracking hook+- Depends on `useAuth()` — only fetches when `isSignedIn`+- Calls `window.electronAPI.cloudUsage()` on mount+- Returns `{ plan, wordsUsed, wordsRemaining, limit, isSubscribed, isOverLimit, refetch }`+- Exposes `openCheckout()` and `openPortal()` (calls IPC → gets URL → `shell.openExternal()`)+- Returns `null` when not signed in (BYOK/local users see nothing)+- Caches result with TTL from existing `CACHE_CONFIG`++**`src/components/UsageDisplay.tsx`** — Usage meter+- Progress bar showing `wordsUsed / limit`+- "Unlimited" for Pro users+- "Upgrade" button when approaching/at limit++**`src/components/UpgradePrompt.tsx`** — Limit hit dialog+- Shown when transcription returns `limitReached: true`+- Three options: "Upgrade to Pro", "Use your own API key", "Switch to local"++### Modified Files++**`src/helpers/audioManager.js`** — Core routing change+- Add `processWithOpenWhisprCloud(audioBlob, metadata)` method:+ - Calls `window.electronAPI.cloudTranscribe(audioArrayBuffer, { language, prompt })`+ - Handles `limitReached` flag (emits event for UI to show UpgradePrompt)+ - Returns same `{ success, text, source: "openwhispr", timings }` shape as other methods+ - ~10 lines — all heavy lifting in the IPC handler+- Modify `processAudio()` routing (~line 219):+ ```+ if (useLocalWhisper) → processWithLocalWhisper/Parakeet (unchanged)+ else if (cloudTranscriptionMode === "openwhispr" && isSignedIn) → processWithOpenWhisprCloud (NEW)+ else → processWithOpenAIAPI (existing BYOK flow, unchanged)+ ```++**`src/services/ReasoningService.ts`** — Add `"openwhispr"` provider+- Add `processWithOpenWhispr()` method alongside existing `processWithOpenAI()`, `processWithAnthropic()`, etc.+- Calls `window.electronAPI.cloudReason(text, { model, agentName, customDictionary })`+- When `cloudTranscriptionMode === "openwhispr"` && signed in, `reasoningProvider` is `"openwhispr"`+- Single routing point — no changes needed in `audioManager.js` for reasoning++**`src/hooks/useSettings.ts`**+- Add `cloudTranscriptionMode` setting with `useLocalStorage` hook++**`src/components/OnboardingFlow.tsx`** — Simplified step 1+- When signed in: default to OpenWhispr Cloud — show language picker + reasoning model selector (curated list from `modelRegistryData.json`, smart default pre-selected)+- Collapsible "Advanced: Use your own API key" section reveals existing TranscriptionModelPicker + ReasoningModelSelector+- When not signed in: show existing local/cloud picker (unchanged)++**`src/components/SettingsPage.tsx`**+- **Transcription section**: Mode toggle — "OpenWhispr Cloud" (simple) vs "Use your own API key" (shows existing provider/model/key pickers)+- **AI Models section**: When cloud mode, show curated model picker (from `modelRegistryData.json` cloud models section). When BYOK, show existing ReasoningModelSelector (unchanged)+- **Account section**: Add usage display (words today / limit), plan badge, upgrade/manage button++**`src/models/modelRegistryData.json`** — Add cloud model tiers+- Add `"openwhisprCloudModels"` section with curated tiers:+ - **Fast** (Groq): `llama-3.3-70b-versatile`, `llama-3.1-8b-instant`+ - **Balanced** (OpenRouter): `anthropic/claude-sonnet-4`, `google/gemini-2.5-flash`+ - **Quality** (OpenRouter): `anthropic/claude-opus-4`, `openai/gpt-4.1`+- Ships with the app — works offline for model selection UI+- Future: `/api/models` endpoint can refresh this list periodically (cached in localStorage, daily check)++**`src/config/constants.ts`**+- Add `OPENWHISPR_API_URL` constant (from `VITE_API_URL` env var, used by main process IPC handlers)++**`.env.example`**+- Add `VITE_API_URL=`++### Error Handling Strategy++All cloud errors handled in IPC handlers with consistent `{ success, data, error, code }` shape:++| Scenario | Client behavior |+|----------|----------------|+| Network failure | If BYOK keys exist, offer fallback. Otherwise show "No connection" with retry |+| 401 Unauthorized | Session expired — trigger re-auth flow |+| 429 Rate limited | Show "Too many requests, try again shortly" |+| 500 Server error | Show generic error, log details for debugging |+| Timeout (>30s) | Show "Server busy" with retry option |+| Offline (`!navigator.onLine`) | Before attempting: toast "You're offline. Switch to local or reconnect." |++Use existing `RETRY_CONFIG` from `constants.ts` for automatic retries in the main process API client.++---++## Step 5: UI/UX Design++### Design Principles+- **Minimal by default, powerful on demand** — signed-in users see 2 dropdowns, not 15 config fields+- **Never block, always guide** — limits hit? Text still pastes. Then a polished dialog offers paths forward+- **Upgrade prompts are helpful, not nagging** — surface Pro at natural friction points, never interrupt flow+- **Consistent visual language** — reuse existing shadcn/ui components, color scales, spacing, card patterns+- **Motion = meaning** — subtle transitions on state changes (progress bar color, badge swaps), no gratuitous animation++### Components to Reuse+| Existing Component | Used For |+|-------------------|----------|+| `Badge` (success/warning/destructive) | Plan pill ("Free", "Pro"), status indicators |+| `Progress` | Usage meter bar |+| `Dialog` | UpgradePrompt modal, limit hit |+| `Toast` (useToast) | Offline, errors, upgrade confirmation |+| `Card` / `CardHeader` / `CardContent` | Usage card, mode selector, option cards |+| `Button` (primary/outline/ghost) | Upgrade, manage, mode switches |+| `SettingsSection` / `SettingsGroup` | New settings areas match existing sections |+| `ProcessingModeSelector` | Adapt pattern for Cloud/BYOK toggle |+| `ProviderTabs` | Cloud model tier tabs (Fast/Balanced/Quality) |+| `Alert` (warning) | Approaching limit inline warning |+| `Select` | Cloud model dropdown |+| `LanguageSelector` | Reuse in simplified onboarding |+| `StepProgress` | Onboarding progress (unchanged, but step count may change) |++---++### 5a. User Journeys++#### Journey 1: New User — "Just Works" (primary path, optimized for)++```+Launch app+ → Onboarding Step 0: Account+ ┌─────────────────────────────────────────┐+ │ Create your account │+ │ [Continue with Google] ← primary CTA │+ │ ── or continue with email ── │+ │ [email/password form] │+ │ │+ │ Benefits card (indigo-purple gradient): │+ │ "Cloud transcription — just works" │+ │ "2,000 words/day free" │+ │ "AI text processing included" │+ │ "No API keys needed" │+ └─────────────────────────────────────────┘++ → Onboarding Step 1: Setup (SIMPLIFIED — see 5d)+ Just 2 dropdowns: Language + AI Model+ canProceed() = true immediately (smart defaults pre-selected)+ User can literally just click "Next" without touching anything++ → Steps 2-4: Permissions → Hotkey → Agent Name (unchanged)++ → Complete → Start dictating+ First transcription: audio → IPC → Vercel → text pasted+ Zero configuration. Magic.+```++**Key insight**: A signed-in user can go from app launch to first dictation by clicking: Google sign-in → Next → Grant mic → Next → Set hotkey → Next → Name agent → Complete. The Setup step requires zero thought.++#### Journey 2: Power User — BYOK++```+Either during onboarding (clicks "Advanced" in Step 1)+ or later in Settings → Transcription → "Use your own API key"++ → Existing TranscriptionModelPicker + ReasoningModelSelector appear+ → Enter API key, select model, configure endpoint+ → Audio routes direct to provider — no word limit, no usage tracking+ → Everything works exactly as it does today+```++#### Journey 3: Privacy User — Local Only++```+Onboarding Step 0: "Continue without an account"+ → Step 1: ProcessingModeSelector shows (unchanged)+ Select "Local" → download whisper model+ → Rest of onboarding unchanged+ → All processing on-device, no network calls+```++#### Journey 4: Free → Pro Conversion (upgrade touchpoints)++Users encounter Pro naturally at friction points — never as a nag:++| Touchpoint | Trigger | What They See |+|------------|---------|---------------|+| **Settings account section** | Always visible when signed in | Usage meter + "Upgrade to Pro" button. Subtle, always there. |+| **80% usage toast** | First transcription after 1,600 words | One-time toast: "370 words remaining today". Not blocking. |+| **Limit reached dialog** | Transcription returns `limitReached` | UpgradePrompt dialog (see 5e). Text already pasted — not punitive. |+| **Next-day return** | User returns after hitting limit yesterday | Usage reset, but Settings shows "Yesterday you hit your limit" hint with Pro CTA |++**Anti-patterns we avoid:**+- No upgrade popups on app launch+- No upgrade banners in the dictation overlay+- No "you're on the free plan" warnings during active work+- No feature-gating of existing functionality (BYOK/local always available)+- No countdown timers or urgency tactics++#### Journey 5: Returning User — Already Signed In++```+App launches → onboarding already complete+ → Control Panel shows transcription history+ → Dictation overlay ready+ → If cloud mode: first transcription fetches /api/usage in background+ → Usage state cached, updates after each transcription+ → If limit was hit yesterday: usage reset at midnight UTC, no friction+```++#### Journey 6: Pro User — Day-to-Day++```+Same as Journey 5, but:+ → Settings account shows "Pro" badge (emerald) + "Unlimited" + "Manage" button+ → No usage meter (no limit to track)+ → No upgrade prompts ever surface+ → "Manage" opens Stripe Customer Portal in browser+```++---++### 5b. Onboarding Flow Changes++Current onboarding: 5 steps (Account → Setup → Permissions → Hotkey → Agent Name)++**Steps 0, 2, 3, 4 are unchanged.** Only Step 1 (Setup) changes based on auth state.++#### Step 0: Account — Minor Enhancement++Update the benefits card content to emphasize the "zero config" value prop:++```+┌─────────────────────────────────────────────────────┐+│ Why create an account? (indigo→purple bg) │+│ │+│ ● Instant transcription — no API keys needed │+│ ● 2,000 words/day free, unlimited with Pro │+│ ● AI text processing with world-class models │+│ ● Your settings sync across devices (future) │+└─────────────────────────────────────────────────────┘+```++"Continue without an account" link stays — no pressure.++#### Step 1: Setup — Two Completely Different Experiences++**Path A: Signed in** (simplified cloud-first experience)++```+┌─────────────────────────────────────────────────────┐+│ │+│ ┌──────┐ │+│ │ ✓ │ ← emerald circle (w-14 h-14) │+│ └──────┘ │+│ You're ready to go │ ← text-2xl font-semibold+│ │+│ OpenWhispr handles transcription and AI │ ← text-neutral-600+│ processing for you. No setup needed. │+│ │+│ ┌───────────────────────────────────────────────┐ │+│ │ Language │ │ ← neutral-50 card+│ │ [ Auto-detect ▾ ] │ │ ← LanguageSelector (existing)+│ │ │ │+│ │ AI Model │ │+│ │ [ Llama 3.3 70B · Fast ▾ ] │ │ ← Select, pre-selected default+│ │ ↑ smart default │ │+│ └───────────────────────────────────────────────┘ │+│ │+│ ┌───────────────────────────────────────────────┐ │+│ │ Advanced options ▸ │ │ ← ghost button, neutral-500+│ └───────────────────────────────────────────────┘ │+│ (collapsed by default — expands to show existing │+│ ProcessingModeSelector + TranscriptionModelPicker │+│ + ReasoningModelSelector for BYOK/local) │+│ │+│ ┌───────────────────────────────────────────────┐ │+│ │ Included with your account: │ │ ← blue-50 card, text-sm+│ │ ✓ 2,000 words/day ✓ AI processing │ │+│ │ ✓ Multiple AI models ✓ Custom dictionary │ │+│ └───────────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────────┘+```++**canProceed()**: Always `true` — defaults are pre-selected. User can literally click Next immediately.++**"Advanced options" behavior:**+- Click → section expands with smooth height transition+- Shows existing `ProcessingModeSelector` + full `TranscriptionModelPicker` + `ReasoningModelSelector`+- Selecting any BYOK/local option sets `cloudTranscriptionMode` accordingly+- Collapsing the section reverts to cloud defaults (with confirmation if they entered a key)++**Path B: Not signed in** (unchanged)++Shows existing `ProcessingModeSelector` (Local vs Cloud cards) + `TranscriptionModelPicker` + `LanguageSelector`. No simplification — they need to configure everything manually because they're not using cloud mode.++---++### 5c. Settings Page — Account Section Enhancement++Current: gradient card with avatar + name + email + sign-out.++**Add `UsageDisplay` component below the existing signed-in card:**++#### Free Plan — Normal Usage (<80%)+```+┌─────────────────────────────────────────────────┐+│ │+│ Today's Usage Free ← Badge outline │ ← text-sm font-medium+│ │+│ ██████████░░░░░░░░░░░░░░░░░░ 847 / 2,000 │ ← Progress (indigo-600), text-sm tabular-nums+│ │+│ Resets at midnight UTC │ ← text-xs text-neutral-400+│ │+│ ┌───────────────────────────────────────────┐ │+│ │ Upgrade to Pro — unlimited transcriptions │ │ ← subtle CTA: text link, not button+│ └───────────────────────────────────────────┘ │+│ │+└─────────────────────────────────────────────────┘+```++- Card: `bg-white border border-neutral-200 rounded-xl` (clean, not gradient — gradient is for the profile card above)+- "Upgrade to Pro" is a `text-indigo-600 hover:text-indigo-700 text-sm` link, not a loud button. Subtle.+- Progress bar: `h-2 rounded-full`, indigo-600 fill, neutral-100 track++#### Free Plan — Approaching Limit (>80%)+```+┌─────────────────────────────────────────────────┐+│ │+│ Today's Usage Free ← Badge outline │+│ │+│ ██████████████████████████░░░ 1,847 / 2,000 │ ← Progress (amber-500)+│ │+│ 153 words remaining │ ← text-xs text-amber-600 (replaces "resets at")+│ │+│ [ Upgrade to Pro ] │ ← Button primary (indigo), appears at >80%+│ │+└─────────────────────────────────────────────────┘+```++- Progress bar color transitions: indigo-600 → amber-500 at 80% → red-500 at 100%+- CTA elevates from text link to primary button when approaching limit++#### Free Plan — At Limit+```+┌─────────────────────────────────────────────────┐+│ │+│ Today's Usage Limit reached ← Badge warn │+│ │+│ ██████████████████████████████ 2,000 / 2,000 │ ← Progress (red-500, full)+│ │+│ Resets at midnight UTC │+│ │+│ [ Upgrade to Pro ] [ Use Your Own Key ] │ ← Button primary + Button outline+│ │+└─────────────────────────────────────────────────┘+```++#### Pro Plan+```+┌─────────────────────────────────────────────────┐+│ │+│ Your Plan Pro ← Badge success │+│ │+│ Unlimited transcriptions │ ← text-sm text-neutral-600+│ │+│ [ Manage Subscription ] │ ← Button outline (opens Stripe Portal)+│ │+└─────────────────────────────────────────────────┘+```++- Clean, minimal. No progress bar (nothing to track). Badge is emerald/success.+- "Manage Subscription" → IPC → Stripe Customer Portal URL → `shell.openExternal()`++#### Not Signed In+- `UsageDisplay` component not rendered at all. Existing sign-in prompt shown.++---++### 5d. Settings Page — Transcription Mode Toggle++**Only shown when signed in.** Appears at top of Transcription Mode settings section.++```+┌─────────────────────────────────────────────────┐+│ ☁ OpenWhispr Cloud ● ──┐ │ ← selected: border-indigo-500/30, bg-indigo-50/30+│ Just works. No configuration needed. │ │ │+│ │ │ │ ← radio-style, only one active+│ 🔑 Bring Your Own Key ○ ──┘ │ ← unselected: border-neutral-200, bg-white+│ Use your own API key. No usage limits. │+└─────────────────────────────────────────────────┘+```++- Same card-selection pattern as `ProcessingModeSelector` (indigo border + tinted bg for active)+- **Cloud selected**: Everything below is hidden. Clean empty state — maybe a single line: "Transcription is handled by OpenWhispr's servers. Change your language in General settings."+- **BYOK selected**: Existing `TranscriptionModelPicker` appears below (unchanged)+- Smooth height transition when switching (existing CSS pattern: `transition-all duration-200`)++**When not signed in:** This toggle is not rendered. User sees existing `TranscriptionModelPicker` directly.++---++### 5e. Settings Page — AI Models Section (Cloud Mode)++When `cloudTranscriptionMode === "openwhispr"`, replace `ReasoningModelSelector` with a simplified cloud model picker:++```+┌─────────────────────────────────────────────────┐+│ AI Model │+│ │+│ ┌──────┐ ┌──────────┐ ┌─────────┐ │+│ │ Fast │ │ Balanced │ │ Quality │ │ ← ProviderTabs (3 tiers)+│ └──────┘ └──────────┘ └─────────┘ │+│ │+│ ┌───────────────────────────────────────────┐ │+│ │ Llama 3.3 70B │ │ ← Select dropdown+│ │ ───────────────────── │ │+│ │ Llama 3.3 70B Recommended │ │+│ │ Llama 3.1 8B Fastest │ │+│ └───────────────────────────────────────────┘ │+│ │+│ No API key needed. Powered by OpenWhispr. │ ← text-xs text-neutral-400+│ │+└─────────────────────────────────────────────────┘+```++- `ProviderTabs` reused with tier labels: "Fast" (Groq), "Balanced" (OpenRouter), "Quality" (OpenRouter)+- Each tier has a simple `Select` dropdown (not full ModelCardList — keep it minimal)+- "Recommended" badge on the default model per tier+- Model data from `modelRegistryData.json` `openwhisprCloudModels` section (ships with app, works offline)++**When BYOK mode:** Show existing `ReasoningModelSelector` unchanged.++---++### 5f. UpgradePrompt Dialog++Shown when transcription returns `limitReached: true`. Text is already pasted — this is not blocking work.++```+┌─────────────────────────────────────────────────────┐+│ ╳ │+│ │+│ You've reached today's limit │ ← text-xl font-semibold, centered+│ │+│ 2,000 of 2,000 words used. │ ← text-sm text-neutral-500+│ Your transcription was saved and pasted. │+│ │+│ ┌─────────────────────────────────────────────┐ │+│ │ │ │+│ │ Upgrade to Pro → │ │ ← Card, from-indigo-50 to-purple-50/50+│ │ Unlimited transcriptions. $X/month. │ │ border-indigo-200+│ │ │ │ hover: shadow-md transition+│ └─────────────────────────────────────────────┘ │+│ ┌─────────────────────────────────────────────┐ │+│ │ Use your own API key → │ │ ← Card, bg-neutral-50, border-neutral-200+│ │ Bring your own key for unlimited use. │ │ hover: border-neutral-300+│ └─────────────────────────────────────────────┘ │+│ ┌─────────────────────────────────────────────┐ │+│ │ Switch to local → │ │ ← Card, bg-neutral-50, border-neutral-200+│ │ Offline transcription. No limits. │ │+│ └─────────────────────────────────────────────┘ │+│ │+│ Resets at midnight UTC │ ← text-xs text-neutral-400 centered+│ │+└─────────────────────────────────────────────────────┘+```++**Behavior:**+- "Upgrade to Pro" → IPC → checkout URL → `shell.openExternal()` → dialog stays open (user returns after checkout)+- "Use your own API key" → sets `cloudTranscriptionMode = "byok"`, closes dialog, opens Settings to Transcription section+- "Switch to local" → sets `useLocalWhisper = true`, closes dialog (if model downloaded) or opens Settings to download model+- Dialog is dismissible (X button or click outside) — user can just close it and continue working until midnight reset+- Shown max once per limit-hit session (don't re-show on every subsequent failed attempt — just show a toast after the first dialog)++---++### 5g. Toast Notifications++All using existing `useToast` hook. Concise, actionable, never annoying.++| Event | Variant | Message | Frequency |+|-------|---------|---------|-----------|+| Offline + cloud mode attempt | `destructive` | "You're offline. Switch to local transcription or reconnect." | Every attempt |+| Cloud transcription network error | `destructive` | "Transcription failed. Retrying..." / "Transcription failed." | Per error |+| Session expired (401) | `destructive` | "Session expired. Sign in again in Settings." | Once per session |+| Approaching limit (>80%) | `default` | "{n} words remaining today." | Once per session |+| Limit hit (after first dialog dismissed) | `default` | "Daily limit reached. Resets at midnight UTC." | Per attempt |+| Post-upgrade (usage refetch detects Pro) | `success` | "Pro activated. Unlimited transcriptions." | Once |+| Provider switch (BYOK/local) | `success` | "Switched to [mode]. No usage limits." | Once per switch |++---++### 5h. Main Dictation Overlay (App.jsx)++**No changes to the overlay UI.** The floating button stays minimal:+- No usage meter (too distracting during active work)+- No plan badges (irrelevant during dictation)+- No upgrade prompts in the overlay++**Behavioral changes only:**+- When `limitReached` returns: paste text normally → after paste completes, show `UpgradePrompt` dialog in the Control Panel window (not the overlay)+- When offline + cloud mode: show toast in Control Panel before recording starts. If user is in overlay-only mode, the toast appears there.+- When session expired: transcription fails → toast → user opens Control Panel to re-auth++---++### 5i. Control Panel — Transcription History Enhancement++Minor addition to `ControlPanel.tsx`:++- **Cloud transcriptions**: Show a subtle cloud icon (Cloud, size-3, text-neutral-400) next to timestamp for cloud-transcribed items+- **Source indicator**: `source` field from transcription result → tiny pill: "cloud" | "local" | "byok" in text-xs text-neutral-400+- No other changes to the history UI++---++### 5j. Micro-Interactions & Polish++| Element | Detail |+|---------|--------|+| Usage progress bar | Color transitions smoothly (CSS `transition-colors duration-500`) between indigo → amber → red as usage increases |+| Mode toggle cards | Selected card has subtle `shadow-sm` + `ring-1 ring-indigo-500/20` — feels "pressed in" |+| UpgradePrompt option cards | `hover:shadow-md transition-shadow duration-150` — cards lift slightly on hover |+| Plan badge | `Badge` component with `transition-colors` — swaps from outline to success variant when Pro activates |+| Onboarding Step 1 (signed in) | Content fades in with `animate-in fade-in-0 duration-300` when step loads |+| Advanced section expand | `transition-[max-height] duration-200 ease-out` — smooth expand/collapse |+| Toast notifications | Existing slide-in animation from bottom-right (already implemented) |+| Model tier tabs | Existing `ProviderTabs` sliding indicator animation (already implemented) |++---++## Step 6: UX Flows++### New User — Signed In (primary path)+1. Open app → Onboarding Step 0: Create account (Google or email)+2. Step 1: "You're ready to go" — defaults pre-selected, click Next+3. Steps 2-4: Permissions → Hotkey → Agent Name (unchanged)+4. Complete → Start dictating. Zero config. Audio → IPC → Vercel → text pasted.++### New User — No Account+1. Open app → Onboarding Step 0: "Continue without an account"+2. Step 1: Full setup — ProcessingModeSelector (Local/Cloud) + model config + API key+3. Steps 2-4: unchanged+4. Complete → dictating works via BYOK or local++### Power User — Switch to BYOK+1. Settings → Transcription → "Bring Your Own Key"+2. Existing TranscriptionModelPicker appears → enter key, pick model+3. Audio goes direct to provider — no word limit, no usage tracking++### Free → Pro Conversion+1. User hits 80% usage → one-time toast: "370 words remaining"+2. User hits limit → text pastes normally → UpgradePrompt dialog+3. User clicks "Upgrade to Pro" → Stripe Checkout in browser+4. After payment → webhook updates DB → app polls /api/usage → Pro detected+5. Toast: "Pro activated. Unlimited transcriptions."+6. Settings shows Pro badge, "Manage Subscription" button. No more usage meter.++### Stripe Checkout+1. Upgrade CTA (settings or dialog) → IPC → Vercel creates Stripe Checkout session+2. `shell.openExternal(url)` → browser opens Stripe-hosted checkout+3. After payment → static "Payment successful, close this tab" page on Vercel+4. Electron app polls `/api/usage` every 3s for up to 60s after opening checkout+5. Detects plan change → success toast → UI updates++### Offline+1. `navigator.onLine` check before cloud transcription+2. Toast: "You're offline. Switch to local transcription or reconnect."+3. Local mode always works. BYOK may work depending on provider accessibility.++---++## Implementation Order++### Phase 1: Dead Code Cleanup (prerequisite PR) ✅ COMPLETE+1. ✅ Remove dead `onOAuthCallback` in `preload.js:171`+2. ✅ Remove stale comment in `AuthenticationStep.tsx:64`+3. ✅ Merge to main++### Phase 2: API Foundation ✅ COMPLETE+4. ✅ `git init` new repo at `~/Projects/OpenWhispr/openwhispr-api/`+5. ✅ Set up Vercel project, TypeScript, dependencies+6. ✅ Create Neon Postgres schema (run SQL in console)+7. ✅ Implement `lib/auth.ts`, `lib/db.ts`, `lib/usage.ts`, `lib/providers.ts`+8. ✅ Implement Groq transcription provider + OpenRouter reasoning provider+9. ✅ Implement `POST /api/transcribe` + `GET /api/usage`+10. ✅ Implement `POST /api/reason`+11. ✅ Test with curl++### Phase 3: Electron → API Integration ✅ COMPLETE+12. ✅ Add IPC handlers for `cloud-transcribe`, `cloud-reason`, `cloud-usage` to `ipcHandlers.js`+13. ✅ Add IPC channels to `preload.js`+14. ✅ Add `cloudTranscriptionMode` to `useSettings.ts`+15. ✅ Add `processWithOpenWhisprCloud()` to `audioManager.js`+16. ✅ Wire transcription routing in `processAudio()`+17. ✅ Add `"openwhispr"` provider to `ReasoningService.ts`+18. ⏳ Test: sign in → dictate → transcription + reasoning via API++### Phase 4: Usage Tracking & UI ✅ COMPLETE+19. ✅ Create `useUsage.ts` hook+20. ✅ Create `UsageDisplay.tsx` + `UpgradePrompt.tsx`+21. ✅ Update `SettingsPage.tsx` — mode toggle + usage display+22. ✅ Update `OnboardingFlow.tsx` — simplified step 1 for signed-in users+23. ✅ Add cloud model tiers to `modelRegistryData.json`+24. ✅ Integrate UpgradePrompt into ControlPanel for limit-reached events+25. ✅ Add IPC channels for limit-reached cross-window communication+26. ✅ Add TypeScript types for cloud API methods++### Phase 5: Stripe ❌ NOT STARTED+27. ❌ Set up Stripe product/price in dashboard+28. ❌ Implement checkout, portal, webhook endpoints+29. ❌ Add `/checkout/success` and `/checkout/cancel` pages+30. ❌ Add IPC handlers for `cloud-checkout`, `cloud-portal`+31. ❌ Wire upgrade/manage buttons to Stripe in UsageDisplay + UpgradePrompt+32. ❌ Test full payment flow with Stripe CLI++---++## Risks & Mitigations++| Risk | Mitigation |+|------|-----------|+| Session cookies not forwardable from main process | Electron's `session.cookies.get()` API provides access. Already used for `authClearSession`. |+| Vercel 4.5MB body limit | Dictation audio is typically 50-200KB. Client already optimizes. |+| Vercel function timeout (10s free) | Transcription takes 1-5s. Use Vercel Pro plan (60s) if needed. |+| Stripe can't redirect back to Electron | Static success/cancel pages on Vercel. App polls `/api/usage`. |+| Provider outage | Provider registry makes switching providers a config change. No code deploy needed. |+| Offline users on cloud mode | `navigator.onLine` check + clear toast with actionable options. |++---++## Verification++1. **API auth**: `curl` with session cookie → `/api/usage` returns usage+2. **Default transcription**: Sign in → dictate → text appears (no API key configured)+3. **Default reasoning**: Enable reasoning → dictate "Hey Agent, ..." → AI-processed text returned+4. **Model selection**: Change reasoning model in settings → verify different model used+5. **BYOK mode**: Switch to BYOK → enter key → dictate → works with no word limit+6. **Local mode**: Switch to local → dictate → works offline, no API calls+7. **Usage limit**: Transcribe >2000 words → text still pastes → `UpgradePrompt` appears+8. **Stripe**: `stripe listen --forward-to localhost:3000/api/stripe/webhook` → checkout → plan updates+9. **Offline**: Disconnect network → cloud mode → offline toast → switch to local → works+10. **Sign-out**: Cloud features disabled, local data preserved, BYOK keys retained+11. **Provider swap**: Change `TRANSCRIPTION_PROVIDER` env var → verify new provider used (no code change)diff --git a/preload.js b/preload.jsindex a0d845437..36717eb77 100644--- a/preload.js+++ b/preload.js@@ -23,7 +23,7 @@ const registerListener = (channel, handlerFactory) => {};contextBridge.exposeInMainWorld("electronAPI", {- pasteText: (text) => ipcRenderer.invoke("paste-text", text),+ pasteText: (text, options) => ipcRenderer.invoke("paste-text", text, options),hideWindow: () => ipcRenderer.invoke("hide-window"),showDictationPanel: () => ipcRenderer.invoke("show-dictation-panel"),onToggleDictation: registerListener(@@ -201,6 +201,10 @@ contextBridge.exposeInMainWorld("electronAPI", {getDictationKey: () => ipcRenderer.invoke("get-dictation-key"),saveDictationKey: (key) => ipcRenderer.invoke("save-dictation-key", key),+ // Activation mode persistence (file-based for reliable startup)+ getActivationMode: () => ipcRenderer.invoke("get-activation-mode"),+ saveActivationMode: (mode) => ipcRenderer.invoke("save-activation-mode", mode),+saveAllKeysToEnv: () => ipcRenderer.invoke("save-all-keys-to-env"),syncStartupPreferences: (prefs) => ipcRenderer.invoke("sync-startup-preferences", prefs),@@ -237,6 +241,30 @@ contextBridge.exposeInMainWorld("electronAPI", {openSoundInputSettings: () => ipcRenderer.invoke("open-sound-input-settings"),openAccessibilitySettings: () => ipcRenderer.invoke("open-accessibility-settings"),openWhisperModelsFolder: () => ipcRenderer.invoke("open-whisper-models-folder"),+ authClearSession: () => ipcRenderer.invoke("auth-clear-session"),++ // OpenWhispr Cloud API+ cloudTranscribe: (audioBuffer, opts) => ipcRenderer.invoke("cloud-transcribe", audioBuffer, opts),+ cloudReason: (text, opts) => ipcRenderer.invoke("cloud-reason", text, opts),+ cloudUsage: () => ipcRenderer.invoke("cloud-usage"),+ cloudCheckout: () => ipcRenderer.invoke("cloud-checkout"),+ cloudBillingPortal: () => ipcRenderer.invoke("cloud-billing-portal"),++ // Assembly AI Streaming+ assemblyAiStreamingWarmup: (options) => ipcRenderer.invoke("assemblyai-streaming-warmup", options),+ assemblyAiStreamingStart: (options) => ipcRenderer.invoke("assemblyai-streaming-start", options),+ assemblyAiStreamingSend: (audioBuffer) => ipcRenderer.send("assemblyai-streaming-send", audioBuffer),+ assemblyAiStreamingForceEndpoint: () => ipcRenderer.send("assemblyai-streaming-force-endpoint"),+ assemblyAiStreamingStop: () => ipcRenderer.invoke("assemblyai-streaming-stop"),+ assemblyAiStreamingStatus: () => ipcRenderer.invoke("assemblyai-streaming-status"),+ onAssemblyAiPartialTranscript: registerListener("assemblyai-partial-transcript", (callback) => (_event, text) => callback(text)),+ onAssemblyAiFinalTranscript: registerListener("assemblyai-final-transcript", (callback) => (_event, text) => callback(text)),+ onAssemblyAiError: registerListener("assemblyai-error", (callback) => (_event, error) => callback(error)),+ onAssemblyAiSessionEnd: registerListener("assemblyai-session-end", (callback) => (_event, data) => callback(data)),++ // Usage limit events (for showing UpgradePrompt in ControlPanel)+ notifyLimitReached: (data) => ipcRenderer.send("limit-reached", data),+ onLimitReached: registerListener("limit-reached", (callback) => (_event, data) => callback(data)),// Globe key listener for hotkey capture (macOS only)onGlobeKeyPressed: (callback) => {@@ -244,6 +272,11 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.on("globe-key-pressed", listener);return () => ipcRenderer.removeListener("globe-key-pressed", listener);},+ onGlobeKeyReleased: (callback) => {+ const listener = () => callback?.();+ ipcRenderer.on("globe-key-released", listener);+ return () => ipcRenderer.removeListener("globe-key-released", listener);+ },// Hotkey registration events (for notifying user when hotkey fails)onHotkeyFallbackUsed: (callback) => {diff --git a/resources/macos-fast-paste.swift b/resources/macos-fast-paste.swiftnew file mode 100644index 000000000..f8bed4c4f--- /dev/null+++ b/resources/macos-fast-paste.swift@@ -0,0 +1,17 @@+import Cocoa++if !AXIsProcessTrusted() {+ exit(2)+}++guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 0x09, keyDown: true),+ let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 0x09, keyDown: false) else {+ exit(1)+}++keyDown.flags = .maskCommand+keyUp.flags = .maskCommand+keyDown.post(tap: .cgSessionEventTap)+usleep(8000)+keyUp.post(tap: .cgSessionEventTap)+usleep(20000)diff --git a/resources/macos-globe-listener.swift b/resources/macos-globe-listener.swiftindex fe550d74f..d34acb651 100644--- a/resources/macos-globe-listener.swift+++ b/resources/macos-globe-listener.swift@@ -5,6 +5,7 @@ import Darwinlet mask = CGEventMask(1 << CGEventType.flagsChanged.rawValue)var fnIsDown = falsevar eventTap: CFMachPort?+var lastModifierFlags: CGEventFlags = []func eventTapCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? {if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {@@ -27,6 +28,48 @@ func eventTapCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent,fflush(stdout)}+ // Detect right-side modifier key down/up via keycode+ let keyCode = event.getIntegerValueField(.keyboardEventKeycode)+ let rightModifiers: [(Int64, CGEventFlags, String)] = [+ (61, .maskAlternate, "RightOption"),+ (54, .maskCommand, "RightCommand"),+ (62, .maskControl, "RightControl"),+ (60, .maskShift, "RightShift"),+ ]+ for (code, flag, name) in rightModifiers {+ if keyCode == code {+ if flags.contains(flag) {+ FileHandle.standardOutput.write("RIGHT_MOD_DOWN:\(name)\n".data(using: .utf8)!)+ } else {+ FileHandle.standardOutput.write("RIGHT_MOD_UP:\(name)\n".data(using: .utf8)!)+ }+ fflush(stdout)+ break+ }+ }++ let modifierMask: CGEventFlags = [.maskControl, .maskCommand, .maskAlternate, .maskShift]+ let currentModifiers = flags.intersection(modifierMask)++ if currentModifiers != lastModifierFlags {+ let released = lastModifierFlags.subtracting(currentModifiers)+ let releases: [(CGEventFlags, String)] = [+ (.maskControl, "control"),+ (.maskCommand, "command"),+ (.maskAlternate, "option"),+ (.maskShift, "shift"),+ ]++ for (flag, name) in releases {+ if released.contains(flag) {+ FileHandle.standardOutput.write("MODIFIER_UP:\(name)\n".data(using: .utf8)!)+ fflush(stdout)+ }+ }++ lastModifierFlags = currentModifiers+ }+return Unmanaged.passUnretained(event)}diff --git a/resources/windows-key-listener.c b/resources/windows-key-listener.cindex 4f92da166..a40ae2bd0 100644--- a/resources/windows-key-listener.c+++ b/resources/windows-key-listener.c@@ -23,12 +23,19 @@ static BOOL g_isKeyDown = FALSE;static BOOL g_requireCtrl = FALSE;static BOOL g_requireAlt = FALSE;static BOOL g_requireShift = FALSE;+static BOOL g_requireWin = FALSE;+static BOOL g_useModifiersOnly = FALSE;// Check if required modifiers are currently pressedBOOL AreModifiersPressed(void) {if (g_requireCtrl && !(GetAsyncKeyState(VK_CONTROL) & 0x8000)) return FALSE;if (g_requireAlt && !(GetAsyncKeyState(VK_MENU) & 0x8000)) return FALSE;if (g_requireShift && !(GetAsyncKeyState(VK_SHIFT) & 0x8000)) return FALSE;+ if (g_requireWin &&+ !(GetAsyncKeyState(VK_LWIN) & 0x8000) &&+ !(GetAsyncKeyState(VK_RWIN) & 0x8000)) {+ return FALSE;+ }return TRUE;}@@ -76,6 +83,14 @@ DWORD ParseKeyCode(const char* keyName) {if (_stricmp(keyName, "CapsLock") == 0) return VK_CAPITAL;if (_stricmp(keyName, "NumLock") == 0) return VK_NUMLOCK;+ // Right-side modifier keys (used as single-key hotkeys)+ if (_stricmp(keyName, "RightAlt") == 0 || _stricmp(keyName, "RightOption") == 0) return VK_RMENU;+ if (_stricmp(keyName, "RightControl") == 0 || _stricmp(keyName, "RightCtrl") == 0) return VK_RCONTROL;+ if (_stricmp(keyName, "RightShift") == 0) return VK_RSHIFT;+ if (_stricmp(keyName, "RightSuper") == 0 || _stricmp(keyName, "RightWin") == 0 ||+ _stricmp(keyName, "RightMeta") == 0 || _stricmp(keyName, "RightCommand") == 0 ||+ _stricmp(keyName, "RightCmd") == 0) return VK_RWIN;+// Backtick/tilde - the default hotkeyif (strcmp(keyName, "`") == 0 || _stricmp(keyName, "Backquote") == 0) return VK_OEM_3;@@ -125,6 +140,9 @@ LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {if (g_requireShift && (kbd->vkCode == VK_SHIFT || kbd->vkCode == VK_LSHIFT || kbd->vkCode == VK_RSHIFT)) {modifierReleased = TRUE;}+ if (g_requireWin && (kbd->vkCode == VK_LWIN || kbd->vkCode == VK_RWIN)) {+ modifierReleased = TRUE;+ }if (modifierReleased) {g_isKeyDown = FALSE;printf("KEY_UP\n");@@ -132,6 +150,23 @@ LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {}}+ if (g_useModifiersOnly) {+ if (isKeyDown) {+ if (!g_isKeyDown && AreModifiersPressed()) {+ g_isKeyDown = TRUE;+ printf("KEY_DOWN\n");+ fflush(stdout);+ }+ } else if (isKeyUp) {+ if (g_isKeyDown && !AreModifiersPressed()) {+ g_isKeyDown = FALSE;+ printf("KEY_UP\n");+ fflush(stdout);+ }+ }+ return CallNextHookEx(g_hook, nCode, wParam, lParam);+ }+// Check for the target keyif (kbd->vkCode == g_targetVk) {if (isKeyDown) {@@ -176,6 +211,8 @@ DWORD ParseCompoundHotkey(const char* hotkey) {g_requireCtrl = FALSE;g_requireAlt = FALSE;g_requireShift = FALSE;+ g_requireWin = FALSE;+ g_useModifiersOnly = FALSE;DWORD mainKeyVk = 0;char* token = strtok(buffer, "+");@@ -199,10 +236,11 @@ DWORD ParseCompoundHotkey(const char* hotkey) {g_requireShift = TRUE;} else if (_stricmp(token, "Super") == 0 ||_stricmp(token, "Meta") == 0 ||+ _stricmp(token, "Win") == 0 ||_stricmp(token, "Command") == 0 ||_stricmp(token, "Cmd") == 0) {- // Windows key - treat as Ctrl on Windows for compatibility- g_requireCtrl = TRUE;+ // Windows key+ g_requireWin = TRUE;} else {// This should be the main keymainKeyVk = ParseKeyCode(token);@@ -227,14 +265,18 @@ int main(int argc, char* argv[]) {}g_targetVk = ParseCompoundHotkey(argv[1]);- if (g_targetVk == 0) {+ if (g_targetVk == 0 && (g_requireCtrl || g_requireAlt || g_requireShift || g_requireWin)) {+ g_useModifiersOnly = TRUE;+ }++ if (g_targetVk == 0 && !g_useModifiersOnly) {fprintf(stderr, "Error: Invalid key '%s'\n", argv[1]);return 1;}// Log what we're listening for- fprintf(stderr, "Listening for: %s (VK=0x%02X, Ctrl=%d, Alt=%d, Shift=%d)\n",- argv[1], g_targetVk, g_requireCtrl, g_requireAlt, g_requireShift);+ fprintf(stderr, "Listening for: %s (VK=0x%02X, Ctrl=%d, Alt=%d, Shift=%d, Win=%d, ModOnly=%d)\n",+ argv[1], g_targetVk, g_requireCtrl, g_requireAlt, g_requireShift, g_requireWin, g_useModifiersOnly);// Set up console handler for clean shutdownSetConsoleCtrlHandler(ConsoleHandler, TRUE);diff --git a/scripts/build-globe-listener.js b/scripts/build-globe-listener.jsindex 755b8720c..8662e67ed 100644--- a/scripts/build-globe-listener.js+++ b/scripts/build-globe-listener.js@@ -1,6 +1,7 @@#!/usr/bin/env nodeconst { spawnSync } = require("child_process");+const crypto = require("crypto");const fs = require("fs");const path = require("path");@@ -13,6 +14,7 @@ const projectRoot = path.resolve(__dirname, "..");const swiftSource = path.join(projectRoot, "resources", "macos-globe-listener.swift");const outputDir = path.join(projectRoot, "resources", "bin");const outputBinary = path.join(outputDir, "macos-globe-listener");+const hashFile = path.join(outputDir, ".macos-globe-listener.hash");const moduleCacheDir = path.join(outputDir, ".swift-module-cache");function log(message) {@@ -46,6 +48,28 @@ if (fs.existsSync(outputBinary)) {}}+// Secondary check: compare source hash+if (!needsBuild && fs.existsSync(outputBinary)) {+ try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");++ if (fs.existsSync(hashFile)) {+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();+ if (savedHash !== currentHash) {+ log("Source hash changed, rebuild needed");+ needsBuild = true;+ }+ } else {+ // No hash file exists, save current hash for next time+ fs.writeFileSync(hashFile, currentHash);+ }+ } catch (err) {+ log(`Hash check failed: ${err.message}, forcing rebuild`);+ needsBuild = true;+ }+}+if (!needsBuild) {process.exit(0);}@@ -87,4 +111,14 @@ try {console.warn(`[globe-listener] Unable to set executable permissions: ${error.message}`);}+// Save source hash after successful build+try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");+ fs.writeFileSync(hashFile, hash);+} catch (err) {+ // Non-critical, just log+ log(`Warning: Could not save source hash: ${err.message}`);+}+log("Successfully built macOS Globe listener binary.");diff --git a/scripts/build-macos-fast-paste.js b/scripts/build-macos-fast-paste.jsnew file mode 100644index 000000000..9163e0426--- /dev/null+++ b/scripts/build-macos-fast-paste.js@@ -0,0 +1,120 @@+#!/usr/bin/env node++const { spawnSync } = require("child_process");+const crypto = require("crypto");+const fs = require("fs");+const path = require("path");++const isMac = process.platform === "darwin";+if (!isMac) {+ process.exit(0);+}++const projectRoot = path.resolve(__dirname, "..");+const swiftSource = path.join(projectRoot, "resources", "macos-fast-paste.swift");+const outputDir = path.join(projectRoot, "resources", "bin");+const outputBinary = path.join(outputDir, "macos-fast-paste");+const hashFile = path.join(outputDir, ".macos-fast-paste.hash");+const moduleCacheDir = path.join(outputDir, ".swift-module-cache");++function log(message) {+ console.log(`[fast-paste] ${message}`);+}++function ensureDir(dirPath) {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, { recursive: true });+ }+}++if (!fs.existsSync(swiftSource)) {+ console.error(`[fast-paste] Swift source not found at ${swiftSource}`);+ process.exit(1);+}++ensureDir(outputDir);+ensureDir(moduleCacheDir);++let needsBuild = true;+if (fs.existsSync(outputBinary)) {+ try {+ const binaryStat = fs.statSync(outputBinary);+ const sourceStat = fs.statSync(swiftSource);+ if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {+ needsBuild = false;+ }+ } catch {+ needsBuild = true;+ }+}++if (!needsBuild && fs.existsSync(outputBinary)) {+ try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const currentHash = crypto.createHash("sha256").update(sourceContent).digest("hex");++ if (fs.existsSync(hashFile)) {+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();+ if (savedHash !== currentHash) {+ log("Source hash changed, rebuild needed");+ needsBuild = true;+ }+ } else {+ fs.writeFileSync(hashFile, currentHash);+ }+ } catch (err) {+ log(`Hash check failed: ${err.message}, forcing rebuild`);+ needsBuild = true;+ }+}++if (!needsBuild) {+ process.exit(0);+}++function attemptCompile(command, args) {+ log(`Compiling with ${[command, ...args].join(" ")}`);+ return spawnSync(command, args, {+ stdio: "inherit",+ env: {+ ...process.env,+ SWIFT_MODULE_CACHE_PATH: moduleCacheDir,+ },+ });+}++const compileArgs = [+ swiftSource,+ "-O",+ "-module-cache-path",+ moduleCacheDir,+ "-o",+ outputBinary,+];++let result = attemptCompile("xcrun", ["swiftc", ...compileArgs]);++if (result.status !== 0) {+ result = attemptCompile("swiftc", compileArgs);+}++if (result.status !== 0) {+ console.error("[fast-paste] Failed to compile macOS fast-paste binary.");+ process.exit(result.status ?? 1);+}++try {+ fs.chmodSync(outputBinary, 0o755);+} catch (error) {+ console.warn(`[fast-paste] Unable to set executable permissions: ${error.message}`);+}++try {+ const sourceContent = fs.readFileSync(swiftSource, "utf8");+ const hash = crypto.createHash("sha256").update(sourceContent).digest("hex");+ fs.writeFileSync(hashFile, hash);+} catch (err) {+ log(`Warning: Could not save source hash: ${err.message}`);+}++log("Successfully built macOS fast-paste binary.");diff --git a/scripts/complete-uninstall.sh b/scripts/complete-uninstall.shindex 447068f7b..a2c223c9e 100755--- a/scripts/complete-uninstall.sh+++ b/scripts/complete-uninstall.sh@@ -4,7 +4,7 @@ set -euo pipefailPROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"-echo "⚠️ This script will stop OpenWhispr, remove the installed app, and delete caches, databases, and preferences."+echo "This script will stop OpenWhispr, remove the installed app, and delete caches, databases, and preferences."read -r -p "Continue with the full uninstall? [y/N]: " confirmif [[ ! "$confirm" =~ ^[Yy]$ ]]; thenecho "Aborted."diff --git a/src/App.jsx b/src/App.jsxindex 892c667f7..13a33bf4f 100644--- a/src/App.jsx+++ b/src/App.jsx@@ -6,6 +6,7 @@ import { LoadingDots } from "./components/ui/LoadingDots";import { useHotkey } from "./hooks/useHotkey";import { useWindowDrag } from "./hooks/useWindowDrag";import { useAudioRecording } from "./hooks/useAudioRecording";+import { useAuth } from "./hooks/useAuth";// Sound Wave Icon Component (for idle/hover states)const SoundWaveIcon = ({ size = 16 }) => {@@ -75,6 +76,8 @@ export default function App() {const { toast, toastCount } = useToast();const { hotkey } = useHotkey();const { isDragging, handleMouseDown, handleMouseUp } = useWindowDrag();+ const { isSignedIn } = useAuth();+const [dragStartPos, setDragStartPos] = useState(null);const [hasDragged, setHasDragged] = useState(false);@@ -138,10 +141,23 @@ export default function App() {setWindowInteractivity(false);}, [setWindowInteractivity]);- const { isRecording, isProcessing, toggleListening, cancelRecording, cancelProcessing } =- useAudioRecording(toast, {- onToggle: handleDictationToggle,- });+ const {+ isRecording,+ isProcessing,+ toggleListening,+ cancelRecording,+ cancelProcessing,+ warmupStreaming,+ } = useAudioRecording(toast, {+ onToggle: handleDictationToggle,+ });++ // Trigger streaming warmup when user signs in (covers first-time account creation)+ useEffect(() => {+ if (isSignedIn) {+ warmupStreaming();+ }+ }, [isSignedIn]);const handleClose = () => {window.electronAPI.hideWindow();@@ -248,9 +264,13 @@ export default function App() {e.stopPropagation();isRecording ? cancelRecording() : cancelProcessing();}}- className="w-5 h-5 rounded-full bg-card/90 hover:bg-destructive border border-border hover:border-destructive flex items-center justify-center transition-all duration-150 shadow-lg backdrop-blur-sm"+ className="group/cancel w-5 h-5 rounded-full bg-surface-2/90 hover:bg-destructive border border-border hover:border-destructive/70 flex items-center justify-center transition-all duration-150 shadow-sm backdrop-blur-sm">- <X size={10} strokeWidth={2.5} color="white" />+ <X+ size={10}+ strokeWidth={2.5}+ className="text-foreground group-hover/cancel:text-destructive-foreground transition-colors duration-150"+ /></button>)}<Tooltip content={micProps.tooltip}>diff --git a/src/assets/logo.svg b/src/assets/logo.svgnew file mode 100644index 000000000..50a1497ec--- /dev/null+++ b/src/assets/logo.svg@@ -0,0 +1,7 @@+<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">+<rect width="1024" height="1024" rx="241" fill="#2056DF"/>+<circle cx="512" cy="512" r="314" fill="#2056DF" stroke="white" stroke-width="74"/>+<path d="M512 383V641" stroke="white" stroke-width="74" stroke-linecap="round"/>+<path d="M627 457V568" stroke="white" stroke-width="74" stroke-linecap="round"/>+<path d="M397 457V568" stroke="white" stroke-width="74" stroke-linecap="round"/>+</svg>diff --git a/src/components/AuthenticationStep.tsx b/src/components/AuthenticationStep.tsxnew file mode 100644index 000000000..172f89937--- /dev/null+++ b/src/components/AuthenticationStep.tsx@@ -0,0 +1,585 @@+import React, { useCallback, useEffect, useState, useRef } from "react";+import { useAuth } from "../hooks/useAuth";+import {+ authClient,+ NEON_AUTH_URL,+ signInWithSocial,+ updateLastSignInTime,+ type SocialProvider,+} from "../lib/neonAuth";+import { OPENWHISPR_API_URL } from "../config/constants";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { AlertCircle, ArrowRight, Check, Loader2, ChevronLeft } from "lucide-react";+import logoIcon from "../assets/icon.png";+import ForgotPasswordView from "./ForgotPasswordView";+import ResetPasswordView from "./ResetPasswordView";++interface AuthenticationStepProps {+ onContinueWithoutAccount: () => void;+ onAuthComplete: () => void;+ onNeedsVerification: (email: string) => void;+}++type AuthMode = "sign-in" | "sign-up" | null;+type PasswordResetView = "forgot" | "reset" | null;++// Custom SVG icons for social providers (clean, modern style)+const GoogleIcon = ({ className }: { className?: string }) => (+ <svg className={className} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path+ d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"+ fill="#4285F4"+ />+ <path+ d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"+ fill="#34A853"+ />+ <path+ d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"+ fill="#FBBC05"+ />+ <path+ d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"+ fill="#EA4335"+ />+ </svg>+);++export default function AuthenticationStep({+ onContinueWithoutAccount,+ onAuthComplete,+ onNeedsVerification,+}: AuthenticationStepProps) {+ const { isSignedIn, isLoaded, user } = useAuth();+ const [authMode, setAuthMode] = useState<AuthMode>(null);+ const [email, setEmail] = useState("");+ const [password, setPassword] = useState("");+ const [fullName, setFullName] = useState("");+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [isCheckingEmail, setIsCheckingEmail] = useState(false);+ const [isSocialLoading, setIsSocialLoading] = useState<SocialProvider | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [passwordResetView, setPasswordResetView] = useState<PasswordResetView>(null);+ const [resetToken, setResetToken] = useState<string | null>(null);++ // Track if we've already processed the OAuth callback+ const oauthProcessedRef = useRef(false);+ const resetProcessedRef = useRef(false);++ // Check for OAuth callback verifier or password reset token in URL+ useEffect(() => {+ const params = new URLSearchParams(window.location.search);+ const hasVerifier = params.has("neon_auth_session_verifier");+ const token = params.get("token");+ const isResetPassword = params.has("reset_password");++ // Handle password reset callback (user clicked link in email)+ if (token && isResetPassword && !resetProcessedRef.current) {+ resetProcessedRef.current = true;+ setResetToken(token);+ setPasswordResetView("reset");+ console.log("[Auth] Password reset token detected, showing reset form");+ return;+ }++ if (hasVerifier && !oauthProcessedRef.current) {+ oauthProcessedRef.current = true;+ setIsSocialLoading("google");++ // CRITICAL: Activate grace period IMMEDIATELY when OAuth callback starts+ // Session cookies take 10-15 seconds to establish, so we need protection+ // from the very beginning, not after the first successful refresh+ updateLastSignInTime();++ // Don't poll for session - it causes premature session state clearing.+ // Instead, proceed immediately to onboarding. The session cookies will+ // establish in the background (10-15 seconds), and withSessionRefresh()+ // will handle retries automatically when the user tries to use features.+ // The useEffect below will detect when session is ready via isSignedIn.+ console.log(+ "[Auth] OAuth callback detected, grace period active. Proceeding to onboarding..."+ );+ }+ }, []);++ useEffect(() => {+ if (isLoaded && isSignedIn) {+ onAuthComplete();+ }+ }, [isLoaded, isSignedIn, onAuthComplete]);++ // Reset social loading state when the window regains focus+ useEffect(() => {+ if (isSocialLoading === null) return;++ let timeout: ReturnType<typeof setTimeout>;++ const handleFocus = () => {+ timeout = setTimeout(() => {+ setIsSocialLoading(null);+ }, 1000);+ };++ window.addEventListener("focus", handleFocus);+ return () => {+ window.removeEventListener("focus", handleFocus);+ clearTimeout(timeout);+ };+ }, [isSocialLoading]);++ const handleSocialSignIn = useCallback(async (provider: SocialProvider) => {+ setIsSocialLoading(provider);+ setError(null);++ const result = await signInWithSocial(provider);++ if (result.error) {+ setError(result.error.message || `Failed to sign in with ${provider}`);+ setIsSocialLoading(null);+ }+ }, []);++ const handleEmailContinue = useCallback(async () => {+ if (!email.trim() || !authClient) return;++ setIsCheckingEmail(true);+ setError(null);++ try {+ if (!OPENWHISPR_API_URL) {+ setAuthMode("sign-up");+ return;+ }++ const response = await fetch(`${OPENWHISPR_API_URL}/api/check-user`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email: email.trim() }),+ });++ if (!response.ok) {+ throw new Error("Failed to check user existence");+ }++ const data = await response.json();+ setAuthMode(data.exists ? "sign-in" : "sign-up");+ } catch (err) {+ console.error("Error checking user existence:", err);+ setAuthMode("sign-up");+ } finally {+ setIsCheckingEmail(false);+ }+ }, [email]);++ const errorMessageIncludes = (message: string | undefined, keywords: string[]): boolean => {+ if (!message) return false;+ const lowerMessage = message.toLowerCase();+ return keywords.some((keyword) => lowerMessage.includes(keyword));+ };++ const handleSubmit = useCallback(+ async (e: React.FormEvent) => {+ e.preventDefault();++ if (!authClient) {+ setError("Authentication service is not configured. Please contact support.");+ return;+ }++ setIsSubmitting(true);+ setError(null);++ try {+ if (authMode === "sign-up") {+ const result = await authClient.signUp.email({+ email: email.trim(),+ password,+ name: fullName.trim() || email.trim().split("@")[0],+ });++ if (result.error) {+ if (+ errorMessageIncludes(result.error.message, ["already exists", "already registered"])+ ) {+ setAuthMode("sign-in");+ setError("Account exists. Please sign in.");+ setPassword("");+ } else {+ setError(result.error.message || "Failed to create account");+ }+ } else {+ updateLastSignInTime();+ onNeedsVerification(email.trim());+ }+ } else {+ const result = await authClient.signIn.email({+ email: email.trim(),+ password,+ });++ if (result.error) {+ if (errorMessageIncludes(result.error.message, ["not found", "no user"])) {+ setAuthMode("sign-up");+ setError("No account found. Let's create one.");+ setPassword("");+ } else {+ setError(result.error.message || "Invalid email or password");+ }+ } else {+ // Mark the sign-in time to enable grace period for session establishment+ updateLastSignInTime();+ onAuthComplete();+ }+ }+ } catch (err: unknown) {+ const errorMessage =+ err instanceof Error ? err.message : "An error occurred. Please try again.";+ setError(errorMessage);+ } finally {+ setIsSubmitting(false);+ }+ },+ [authMode, email, password, onAuthComplete, onNeedsVerification]+ );++ const handleBack = useCallback(() => {+ setAuthMode(null);+ setPassword("");+ setFullName("");+ setError(null);+ }, []);++ const handleForgotPassword = useCallback(() => {+ setPasswordResetView("forgot");+ setError(null);+ }, []);++ const handleBackFromPasswordReset = useCallback(() => {+ setPasswordResetView(null);+ setResetToken(null);+ setError(null);+ // Clear URL params without reload+ const url = new URL(window.location.href);+ url.searchParams.delete("token");+ url.searchParams.delete("reset_password");+ window.history.replaceState({}, "", url.toString());+ }, []);++ const toggleAuthMode = useCallback(() => {+ setAuthMode((mode) => (mode === "sign-in" ? "sign-up" : "sign-in"));+ setError(null);+ setPassword("");+ setFullName("");+ }, []);++ // Auth not configured state+ if (!NEON_AUTH_URL || !authClient) {+ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <img+ src={logoIcon}+ alt="OpenWhispr"+ className="w-12 h-12 mx-auto mb-2.5 rounded-lg shadow-sm"+ />+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Welcome to OpenWhispr+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ Dictate anywhere using your voice+ </p>+ </div>++ <div className="bg-warning/5 p-2.5 rounded border border-warning/20">+ <p className="text-[10px] text-warning text-center leading-snug">+ Cloud features not configured. You can still use OpenWhispr locally.+ </p>+ </div>++ <Button onClick={onContinueWithoutAccount} className="w-full h-9">+ <span className="text-sm font-medium">Get Started</span>+ <ArrowRight className="w-3.5 h-3.5" />+ </Button>+ </div>+ );+ }++ // Already signed in state+ if (isLoaded && isSignedIn) {+ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <img+ src={logoIcon}+ alt="OpenWhispr"+ className="w-12 h-12 mx-auto mb-2.5 rounded-lg shadow-sm"+ />+ <div className="w-5 h-5 mx-auto bg-success/10 rounded-full flex items-center justify-center mb-2">+ <Check className="w-3 h-3 text-success" />+ </div>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Welcome back{user?.name ? `, ${user.name}` : ""}+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ You're signed in and ready to go.+ </p>+ </div>+ <Button onClick={onAuthComplete} className="w-full h-9">+ <span className="text-sm font-medium">Continue</span>+ <ArrowRight className="w-3.5 h-3.5" />+ </Button>+ </div>+ );+ }++ // Password reset flow - show reset form if we have a token+ if (passwordResetView === "reset" && resetToken) {+ return (+ <ResetPasswordView+ token={resetToken}+ onSuccess={onAuthComplete}+ onBack={handleBackFromPasswordReset}+ />+ );+ }++ // Password reset flow - show forgot password form+ if (passwordResetView === "forgot") {+ return <ForgotPasswordView email={email} onBack={handleBackFromPasswordReset} />;+ }++ // Password form (after email is entered)+ if (authMode !== null) {+ return (+ <div className="space-y-3">+ {/* Back button */}+ <button+ type="button"+ onClick={handleBack}+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ >+ <ChevronLeft className="w-3 h-3" />+ Back+ </button>++ {/* Header — Refined */}+ <div className="text-center mb-4">+ <p className="text-sm text-muted-foreground/70 mb-2 leading-tight">{email}</p>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ {authMode === "sign-in" ? "Welcome back" : "Create your account"}+ </p>+ </div>++ {/* Password Form */}+ <form onSubmit={handleSubmit} className="space-y-2">+ {authMode === "sign-up" && (+ <Input+ type="text"+ placeholder="Enter your full name"+ value={fullName}+ onChange={(e) => setFullName(e.target.value)}+ className="h-9 text-xs"+ disabled={isSubmitting}+ autoFocus+ />+ )}+ <Input+ type="password"+ placeholder={authMode === "sign-up" ? "Create a password" : "Enter your password"}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ className="h-9 text-xs"+ required+ minLength={authMode === "sign-up" ? 8 : undefined}+ disabled={isSubmitting}+ autoFocus={authMode === "sign-in"}+ />++ {authMode === "sign-up" && (+ <p className="text-[9px] text-muted-foreground/70 leading-tight">+ Password must be at least 8 characters+ </p>+ )}++ {authMode === "sign-in" && (+ <button+ type="button"+ onClick={handleForgotPassword}+ className="text-[10px] text-primary hover:text-primary/80 transition-colors text-left"+ disabled={isSubmitting}+ >+ Forgot password?+ </button>+ )}++ {/* Error Display */}+ {error && (+ <div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5">+ <AlertCircle className="w-3 h-3 text-destructive shrink-0" />+ <p className="text-[10px] text-destructive leading-snug">{error}</p>+ </div>+ )}++ {/* Submit Button */}+ <Button type="submit" disabled={isSubmitting || !password} className="w-full h-9">+ {isSubmitting ? (+ <>+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ <span className="text-sm font-medium">+ {authMode === "sign-in" ? "Signing in..." : "Creating account..."}+ </span>+ </>+ ) : (+ <span className="text-sm font-medium">+ {authMode === "sign-in" ? "Sign In" : "Create Account"}+ </span>+ )}+ </Button>+ </form>++ {/* Toggle Auth Mode */}+ <div className="text-center">+ <button+ type="button"+ onClick={toggleAuthMode}+ className="text-[10px] text-muted-foreground/70 hover:text-foreground transition-colors"+ disabled={isSubmitting}+ >+ {authMode === "sign-in" ? (+ <>+ New here? <span className="font-medium text-primary">Create account</span>+ </>+ ) : (+ <>+ Have an account? <span className="font-medium text-primary">Sign in</span>+ </>+ )}+ </button>+ </div>+ </div>+ );+ }++ // Main welcome view+ return (+ <div className="space-y-3">+ {/* Logo & Brand Header — Premium, refined */}+ <div className="text-center mb-4">+ <img+ src={logoIcon}+ alt="OpenWhispr"+ className="w-12 h-12 mx-auto mb-2.5 rounded-lg shadow-sm"+ />+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Welcome to OpenWhispr+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ Dictate anywhere using your voice+ </p>+ </div>++ {/* Google Sign In */}+ <Button+ type="button"+ variant="social"+ onClick={() => handleSocialSignIn("google")}+ disabled={isSocialLoading !== null || isCheckingEmail}+ className="w-full h-9"+ >+ {isSocialLoading === "google" ? (+ <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />+ ) : (+ <GoogleIcon className="w-4 h-4" />+ )}+ <span className="text-sm font-medium">Continue with Google</span>+ </Button>++ {/* Divider — Minimal */}+ <div className="flex items-center gap-2">+ <div className="flex-1 h-px bg-border/50" />+ <span className="text-[9px] font-medium text-muted-foreground/40 uppercase tracking-widest px-1">+ or+ </span>+ <div className="flex-1 h-px bg-border/50" />+ </div>++ {/* Email Input + Continue */}+ <form+ onSubmit={(e) => {+ e.preventDefault();+ handleEmailContinue();+ }}+ className="space-y-2"+ >+ <Input+ type="email"+ placeholder="Enter your email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ className="h-9 text-sm"+ required+ disabled={isSocialLoading !== null || isCheckingEmail}+ />+ <Button+ type="submit"+ variant="outline"+ disabled={!email.trim() || isSocialLoading !== null || isCheckingEmail}+ className="w-full h-9"+ >+ {isCheckingEmail ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <>+ <span className="text-sm font-medium">Continue with Email</span>+ <ArrowRight className="w-3.5 h-3.5" />+ </>+ )}+ </Button>+ </form>++ {/* Error Display */}+ {error && (+ <div className="px-3 py-2 rounded-md bg-destructive/5 border border-destructive/20 flex items-center gap-2">+ <AlertCircle className="w-3.5 h-3.5 text-destructive shrink-0" />+ <p className="text-xs text-destructive">{error}</p>+ </div>+ )}++ {/* Skip Option — Subtle, compact */}+ <div className="pt-1">+ <button+ type="button"+ onClick={onContinueWithoutAccount}+ className="w-full text-center text-xs text-muted-foreground/85 hover:text-foreground transition-colors py-1.5 rounded hover:bg-muted/30"+ disabled={isSocialLoading !== null || isCheckingEmail}+ >+ Continue without an account+ </button>+ </div>++ {/* Terms and Privacy Policy */}+ <p className="text-[10px] text-muted-foreground/80 leading-tight text-center">+ By continuing, you agree to our{" "}+ <a+ href="https://openwhispr.com/terms"+ target="_blank"+ rel="noopener noreferrer"+ className="text-link underline decoration-link/30 hover:decoration-link/60 transition-colors"+ >+ Terms of Service+ </a>{" "}+ and{" "}+ <a+ href="https://openwhispr.com/privacy"+ target="_blank"+ rel="noopener noreferrer"+ className="text-link underline decoration-link/30 hover:decoration-link/60 transition-colors"+ >+ Privacy Policy+ </a>+ .+ </p>+ </div>+ );+}diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex ce7ad4e3a..c1be697dc 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from "react";+import { useState, useEffect, useRef } from "react";import { Button } from "./ui/button";import {Trash2,@@ -15,6 +15,7 @@ import SettingsModal, { SettingsSectionType } from "./SettingsModal";import TitleBar from "./TitleBar";import SupportDropdown from "./ui/SupportDropdown";import TranscriptionItem from "./ui/TranscriptionItem";+import UpgradePrompt from "./UpgradePrompt";import { ConfirmDialog, AlertDialog } from "./ui/dialog";import { useDialogs } from "../hooks/useDialogs";import { useHotkey } from "../hooks/useHotkey";@@ -33,6 +34,9 @@ export default function ControlPanel() {const history = useTranscriptions();const [isLoading, setIsLoading] = useState(true);const [showSettings, setShowSettings] = useState(false);+ const [showUpgradePrompt, setShowUpgradePrompt] = useState(false);+ const [limitData, setLimitData] = useState<{ wordsUsed: number; limit: number } | null>(null);+ const hasShownUpgradePrompt = useRef(false);const [settingsSection, setSettingsSection] = useState<SettingsSectionType | undefined>();const [aiCTADismissed, setAiCTADismissed] = useState(false);const { hotkey } = useHotkey();@@ -85,6 +89,30 @@ export default function ControlPanel() {}}, [updateError, toast]);+ // Listen for limit-reached events from the dictation overlay+ useEffect(() => {+ const dispose = window.electronAPI?.onLimitReached?.(+ (data: { wordsUsed: number; limit: number }) => {+ // Show dialog only once per session, then show toast for subsequent hits+ if (!hasShownUpgradePrompt.current) {+ hasShownUpgradePrompt.current = true;+ setLimitData(data);+ setShowUpgradePrompt(true);+ } else {+ toast({+ title: "Daily Limit Reached",+ description: "Resets at midnight UTC. Upgrade to Pro or use your own API key.",+ duration: 5000,+ });+ }+ }+ );++ return () => {+ dispose?.();+ };+ }, [toast]);+const loadTranscriptions = async () => {try {setIsLoading(true);@@ -257,6 +285,13 @@ export default function ControlPanel() {onOk={() => {}}/>+ <UpgradePrompt+ open={showUpgradePrompt}+ onOpenChange={setShowUpgradePrompt}+ wordsUsed={limitData?.wordsUsed}+ limit={limitData?.limit}+ />+<TitleBaractions={<>diff --git a/src/components/EmailVerificationStep.tsx b/src/components/EmailVerificationStep.tsxnew file mode 100644index 000000000..8113dc2fd--- /dev/null+++ b/src/components/EmailVerificationStep.tsx@@ -0,0 +1,147 @@+import React, { useState, useEffect, useCallback, useRef } from "react";+import { OPENWHISPR_API_URL } from "../config/constants";+import { Button } from "./ui/button";+import { Mail, Loader2, Check, RefreshCw } from "lucide-react";+import logoIcon from "../assets/icon.png";++interface EmailVerificationStepProps {+ email: string;+ onVerified: () => void;+}++export default function EmailVerificationStep({ email, onVerified }: EmailVerificationStepProps) {+ const [resendCooldown, setResendCooldown] = useState(60);+ const [isResending, setIsResending] = useState(false);+ const [verified, setVerified] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);++ useEffect(() => {+ if (resendCooldown <= 0) return;+ const timer = setTimeout(() => setResendCooldown((c) => c - 1), 1000);+ return () => clearTimeout(timer);+ }, [resendCooldown]);++ useEffect(() => {+ if (!OPENWHISPR_API_URL || verified) return;++ pollRef.current = setInterval(async () => {+ try {+ const res = await fetch(`${OPENWHISPR_API_URL}/api/auth/verification-status`, {+ credentials: "include",+ });+ if (res.ok) {+ const data = await res.json();+ if (data.verified) {+ setVerified(true);+ if (pollRef.current) clearInterval(pollRef.current);+ setTimeout(() => onVerified(), 1200);+ }+ }+ } catch {+ // Silently retry on next poll+ }+ }, 5000);++ return () => {+ if (pollRef.current) clearInterval(pollRef.current);+ };+ }, [verified, onVerified]);++ const handleResend = useCallback(async () => {+ if (resendCooldown > 0 || isResending || !OPENWHISPR_API_URL) return;+ setIsResending(true);+ setError(null);+ try {+ const res = await fetch(`${OPENWHISPR_API_URL}/api/auth/send-verification-email`, {+ method: "POST",+ credentials: "include",+ });+ if (res.ok) {+ setResendCooldown(60);+ } else {+ const data = await res.json();+ setError(data.error || "Failed to resend email");+ }+ } catch {+ setError("Network error. Please try again.");+ } finally {+ setIsResending(false);+ }+ }, [resendCooldown, isResending]);++ if (verified) {+ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <img+ src={logoIcon}+ alt="OpenWhispr"+ className="w-12 h-12 mx-auto mb-2.5 rounded-lg shadow-sm"+ />+ <div className="w-8 h-8 mx-auto bg-success/10 rounded-full flex items-center justify-center mb-2">+ <Check className="w-4 h-4 text-success" />+ </div>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Email verified+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ Your account is all set.+ </p>+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <img+ src={logoIcon}+ alt="OpenWhispr"+ className="w-12 h-12 mx-auto mb-2.5 rounded-lg shadow-sm"+ />+ <div className="w-8 h-8 mx-auto bg-primary/10 rounded-full flex items-center justify-center mb-3">+ <Mail className="w-4 h-4 text-primary" />+ </div>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Check your email+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ We sent a verification link to+ </p>+ <p className="text-sm font-medium text-foreground mt-0.5">{email}</p>+ </div>++ <div className="flex items-center justify-center gap-1.5 py-1">+ <Loader2 className="w-3 h-3 animate-spin text-muted-foreground/50" />+ <p className="text-[10px] text-muted-foreground/50">Waiting for verification...</p>+ </div>++ {error && (+ <div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5">+ <p className="text-[10px] text-destructive leading-snug">{error}</p>+ </div>+ )}++ <Button+ type="button"+ variant="outline"+ onClick={handleResend}+ disabled={resendCooldown > 0 || isResending}+ className="w-full h-9"+ >+ {isResending ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : resendCooldown > 0 ? (+ <span className="text-sm font-medium">Resend in {resendCooldown}s</span>+ ) : (+ <>+ <RefreshCw className="w-3.5 h-3.5" />+ <span className="text-sm font-medium">Resend verification email</span>+ </>+ )}+ </Button>+ </div>+ );+}diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsxnew file mode 100644index 000000000..f7651342d--- /dev/null+++ b/src/components/ErrorBoundary.tsx@@ -0,0 +1,57 @@+import React from "react";++interface ErrorBoundaryProps {+ children: React.ReactNode;+}++interface ErrorBoundaryState {+ hasError: boolean;+ error: Error | null;+}++export default class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {+ constructor(props: ErrorBoundaryProps) {+ super(props);+ this.state = { hasError: false, error: null };+ }++ static getDerivedStateFromError(error: Error): ErrorBoundaryState {+ return { hasError: true, error };+ }++ componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {+ console.error("[ErrorBoundary] Uncaught error:", error, errorInfo);+ }++ handleReload = () => {+ window.location.reload();+ };++ render() {+ if (this.state.hasError) {+ return (+ <div className="min-h-screen bg-background flex items-center justify-center p-6">+ <div className="max-w-md text-center space-y-4">+ <h1 className="text-lg font-semibold text-foreground">Something went wrong</h1>+ <p className="text-sm text-muted-foreground">+ An unexpected error occurred. Please reload to try again.+ </p>+ {this.state.error && (+ <pre className="text-xs text-destructive bg-surface-1 rounded-md p-3 overflow-auto max-h-32 text-left">+ {this.state.error.message}+ </pre>+ )}+ <button+ onClick={this.handleReload}+ className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"+ >+ Reload+ </button>+ </div>+ </div>+ );+ }++ return this.props.children;+ }+}diff --git a/src/components/ForgotPasswordView.tsx b/src/components/ForgotPasswordView.tsxnew file mode 100644index 000000000..1ed52380a--- /dev/null+++ b/src/components/ForgotPasswordView.tsx@@ -0,0 +1,153 @@+import React, { useCallback, useState } from "react";+import { requestPasswordReset, NEON_AUTH_URL, authClient } from "../lib/neonAuth";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { AlertCircle, ArrowLeft, Check, Loader2, Mail } from "lucide-react";++interface ForgotPasswordViewProps {+ email?: string;+ onBack: () => void;+}++export default function ForgotPasswordView({+ email: initialEmail = "",+ onBack,+}: ForgotPasswordViewProps) {+ const [email, setEmail] = useState(initialEmail);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [isSuccess, setIsSuccess] = useState(false);++ const handleSubmit = useCallback(+ async (e: React.FormEvent) => {+ e.preventDefault();++ if (!email.trim()) return;++ setIsSubmitting(true);+ setError(null);++ const result = await requestPasswordReset(email.trim());++ if (result.error) {+ setError(result.error.message);+ setIsSubmitting(false);+ } else {+ setIsSuccess(true);+ setIsSubmitting(false);+ }+ },+ [email]+ );++ if (!NEON_AUTH_URL || !authClient) {+ return (+ <div className="space-y-3">+ <div className="bg-warning/5 p-2.5 rounded border border-warning/20">+ <p className="text-[10px] text-warning text-center leading-snug">+ Authentication is not configured.+ </p>+ </div>+ <Button onClick={onBack} variant="outline" className="w-full h-9">+ <ArrowLeft className="w-3.5 h-3.5" />+ <span className="text-sm font-medium">Go Back</span>+ </Button>+ </div>+ );+ }++ if (isSuccess) {+ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <div className="w-10 h-10 mx-auto bg-success/10 rounded-full flex items-center justify-center mb-3">+ <Mail className="w-5 h-5 text-success" />+ </div>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Check your email+ </p>+ <p className="text-muted-foreground text-sm mt-1.5 leading-snug">+ We sent a password reset link to+ </p>+ <p className="text-foreground text-sm font-medium mt-0.5">{email}</p>+ </div>++ <div className="bg-muted/50 p-2.5 rounded border border-border/50">+ <p className="text-[10px] text-muted-foreground text-center leading-snug">+ Didn't receive the email? Check your spam folder or try again.+ </p>+ </div>++ <div className="space-y-2">+ <Button+ onClick={() => {+ setIsSuccess(false);+ setEmail("");+ }}+ variant="outline"+ className="w-full h-9"+ >+ <span className="text-sm font-medium">Try another email</span>+ </Button>+ <Button onClick={onBack} variant="ghost" className="w-full h-9">+ <ArrowLeft className="w-3.5 h-3.5" />+ <span className="text-sm font-medium">Back to sign in</span>+ </Button>+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-3">+ <button+ type="button"+ onClick={onBack}+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ >+ <ArrowLeft className="w-3 h-3" />+ Back+ </button>++ <div className="text-center mb-4">+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Reset your password+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ Enter your email and we'll send you a reset link+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-2">+ <Input+ type="email"+ placeholder="Enter your email"+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ className="h-9 text-sm"+ required+ disabled={isSubmitting}+ autoFocus+ />++ {error && (+ <div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5">+ <AlertCircle className="w-3 h-3 text-destructive shrink-0" />+ <p className="text-[10px] text-destructive leading-snug">{error}</p>+ </div>+ )}++ <Button type="submit" disabled={isSubmitting || !email.trim()} className="w-full h-9">+ {isSubmitting ? (+ <>+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ <span className="text-sm font-medium">Sending...</span>+ </>+ ) : (+ <span className="text-sm font-medium">Send Reset Link</span>+ )}+ </Button>+ </form>+ </div>+ );+}diff --git a/src/components/LocalModelPicker.tsx b/src/components/LocalModelPicker.tsxindex 700f7b14f..25ba7a1cb 100644--- a/src/components/LocalModelPicker.tsx+++ b/src/components/LocalModelPicker.tsx@@ -155,8 +155,8 @@ export default function LocalModelPicker({{progressDisplay}- <div className="p-4">- <h5 className={`${styles.header} mb-3`}>Available Models</h5>+ <div className="p-3">+ <h5 className={`${styles.header} mb-2`}>Available Models</h5><ModelCardListmodels={models.map(diff --git a/src/components/OnboardingFlow.tsx b/src/components/OnboardingFlow.tsxindex a1879c4d1..d24e5d341 100644--- a/src/components/OnboardingFlow.tsx+++ b/src/components/OnboardingFlow.tsx@@ -10,11 +10,11 @@ import {Mic,Shield,Command,- Sparkles,+ UserCircle,} from "lucide-react";import TitleBar from "./TitleBar";-import TranscriptionModelPicker from "./TranscriptionModelPicker";import PermissionCard from "./ui/PermissionCard";+import SupportDropdown from "./ui/SupportDropdown";import MicPermissionWarning from "./ui/MicPermissionWarning";import PasteToolsInfo from "./ui/PasteToolsInfo";import StepProgress from "./ui/StepProgress";@@ -24,19 +24,31 @@ import { useDialogs } from "../hooks/useDialogs";import { usePermissions } from "../hooks/usePermissions";import { useClipboard } from "../hooks/useClipboard";import { useSettings } from "../hooks/useSettings";-import { setAgentNameIfEmpty as saveAgentName } from "../utils/agentName";+import LanguageSelector from "./ui/LanguageSelector";+import AuthenticationStep from "./AuthenticationStep";+import EmailVerificationStep from "./EmailVerificationStep";+import { setAgentName as saveAgentName } from "../utils/agentName";import { formatHotkeyLabel, getDefaultHotkey } from "../utils/hotkeys";+import { useAuth } from "../hooks/useAuth";import { HotkeyInput } from "./ui/HotkeyInput";+import HotkeyGuidanceAccordion from "./ui/HotkeyGuidanceAccordion";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";+import { getValidationMessage } from "../utils/hotkeyValidator";+import { getPlatform } from "../utils/platform";import { ActivationModeSelector } from "./ui/ActivationModeSelector";+import TranscriptionModelPicker from "./TranscriptionModelPicker";interface OnboardingFlowProps {onComplete: () => void;}export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {- // Max valid step index for the current onboarding flow (4 steps, index 0-3)- const MAX_STEP = 3;+ const { isSignedIn } = useAuth();++ // Max valid step index dynamically determined based on auth state+ // Signed-in users: 3 steps (Welcome, Setup, Activation) - index 0-2+ // Non-signed-in users: 4 steps (Welcome, Setup, Permissions, Activation) - index 0-3+ const getMaxStep = () => (isSignedIn ? 2 : 3);const [currentStep, setCurrentStep, removeCurrentStep] = useLocalStorage("onboardingCurrentStep",@@ -48,7 +60,8 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {// Clamp to valid range to handle users upgrading from older versions// with different step countsif (isNaN(parsed) || parsed < 0) return 0;- if (parsed > MAX_STEP) return MAX_STEP;+ const maxStep = getMaxStep();+ if (parsed > maxStep) return maxStep;return parsed;},}@@ -73,10 +86,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setOpenaiApiKey,setGroqApiKey,updateTranscriptionSettings,+ preferredLanguage,} = useSettings();const [hotkey, setHotkey] = useState(dictationKey || getDefaultHotkey());- const agentName = "OpenWhispr"; // Default agent name, editable in settings+ const [agentName, setAgentName] = useState("Agent");+ const [skipAuth, setSkipAuth] = useState(false);+ const [pendingVerificationEmail, setPendingVerificationEmail] = useState<string | null>(null);const [isModelDownloaded, setIsModelDownloaded] = useState(false);const [isUsingGnomeHotkeys, setIsUsingGnomeHotkeys] = useState(false);const readableHotkey = formatHotkeyLabel(hotkey);@@ -91,19 +107,35 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setHotkey(registeredHotkey);setDictationKey(registeredHotkey);},- showSuccessToast: false, // Don't show toast during onboarding auto-registration+ showSuccessToast: false,showErrorToast: false,});+ const validateHotkeyForInput = useCallback(+ (hotkey: string) => getValidationMessage(hotkey, getPlatform()),+ []+ );+const permissionsHook = usePermissions(showAlertDialog);useClipboard(showAlertDialog); // Initialize clipboard hook for permission checks- const steps = [- { title: "Welcome", icon: Sparkles },- { title: "Setup", icon: Settings },- { title: "Permissions", icon: Shield },- { title: "Activation", icon: Command },- ];+ // For signed-in users, merge setup and permissions into one step+ const steps =+ isSignedIn && !skipAuth+ ? [+ { title: "Welcome", icon: UserCircle },+ { title: "Setup", icon: Settings },+ { title: "Activation", icon: Command },+ ]+ : [+ { title: "Welcome", icon: UserCircle },+ { title: "Setup", icon: Settings },+ { title: "Permissions", icon: Shield },+ { title: "Activation", icon: Command },+ ];++ // Only show progress for signed-up users after account creation step+ const showProgress = currentStep > 0;useEffect(() => {const checkHotkeyMode = async () => {@@ -143,10 +175,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {checkStatus();}, [useLocalWhisper, whisperModel, parakeetModel, localTranscriptionProvider]);- // Auto-register default hotkey when entering the hotkey step (step 3)+ // Auto-register default hotkey when entering the activation step+ // (step 3 for non-signed-in, step 2 for signed-in users)+ const activationStepIndex = isSignedIn && !skipAuth ? 2 : 3;+useEffect(() => {- if (currentStep !== 3) {- // Reset initialization flag when leaving step 3+ if (currentStep !== activationStepIndex) {+ // Reset initialization flag when leaving activation stephotkeyStepInitializedRef.current = false;return;}@@ -163,9 +198,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {try {// Get platform-appropriate default hotkeyconst defaultHotkey = getDefaultHotkey();+ const platform = window.electronAPI?.getPlatform?.() ?? "darwin";- // Only auto-register if no hotkey is currently set or it's the old default- if (!hotkey || hotkey === "`" || hotkey === "GLOBE") {+ // Only auto-register if no hotkey is currently set+ const shouldAutoRegister =+ !hotkey || hotkey.trim() === "" || (platform !== "darwin" && hotkey === "GLOBE");++ if (shouldAutoRegister) {// Try to register the default hotkey silentlyconst success = await registerHotkey(defaultHotkey);if (success) {@@ -180,7 +219,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {};void autoRegisterDefaultHotkey();- }, [currentStep, hotkey, registerHotkey]);+ }, [currentStep, hotkey, registerHotkey, activationStepIndex]);const ensureHotkeyRegistered = useCallback(async () => {if (!window.electronAPI?.updateHotkey) {@@ -216,12 +255,10 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {setDictationKey(hotkey);saveAgentName(agentName);- localStorage.setItem("micPermissionGranted", permissionsHook.micPermissionGranted.toString());- localStorage.setItem(- "accessibilityPermissionGranted",- permissionsHook.accessibilityPermissionGranted.toString()- );+ const skippedAuth = skipAuth;+ localStorage.setItem("authenticationSkipped", skippedAuth.toString());localStorage.setItem("onboardingCompleted", "true");+ localStorage.setItem("skipAuth", skippedAuth.toString());try {await window.electronAPI?.saveAllKeysToEnv?.();@@ -230,14 +267,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}return true;- }, [- hotkey,- agentName,- permissionsHook.micPermissionGranted,- permissionsHook.accessibilityPermissionGranted,- setDictationKey,- ensureHotkeyRegistered,- ]);+ }, [hotkey, agentName, setDictationKey, ensureHotkeyRegistered]);const nextStep = useCallback(async () => {if (currentStep >= steps.length - 1) {@@ -247,12 +277,13 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const newStep = currentStep + 1;setCurrentStep(newStep);- if (currentStep === 2 && newStep === 3) {+ // Show dictation panel when entering activation step+ if (newStep === activationStepIndex) {if (window.electronAPI?.showDictationPanel) {window.electronAPI.showDictationPanel();}}- }, [currentStep, setCurrentStep, steps.length]);+ }, [currentStep, setCurrentStep, steps.length, activationStepIndex]);const prevStep = useCallback(() => {if (currentStep > 0) {@@ -272,57 +303,116 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {const renderStep = () => {switch (currentStep) {- case 0: // Welcome+ case 0: // Authentication (with Welcome)+ if (pendingVerificationEmail) {+ return (+ <EmailVerificationStep+ email={pendingVerificationEmail}+ onVerified={() => {+ setPendingVerificationEmail(null);+ nextStep();+ }}+ />+ );+ }return (- <div className="text-center space-y-5">- {/* App logo */}- <div className="relative w-16 h-16 mx-auto">- <div className="absolute inset-0 bg-primary/30 rounded-2xl blur-xl" />- <img- src="./assets/icon.png"- alt="OpenWhispr"- className="relative w-16 h-16 rounded-2xl shadow-lg"- />- </div>-- {/* Title */}- <div className="space-y-1">- <h2 className="text-xl font-semibold text-foreground tracking-tight">- Welcome to OpenWhispr- </h2>- <p className="text-sm text-muted-foreground">- Professional voice-to-text for your computer- </p>- </div>+ <AuthenticationStep+ onContinueWithoutAccount={() => {+ setSkipAuth(true);+ nextStep();+ }}+ onAuthComplete={() => {+ nextStep();+ }}+ onNeedsVerification={(email) => {+ setPendingVerificationEmail(email);+ }}+ />+ );- {/* Feature grid - compact and refined */}- <div className="grid grid-cols-3 gap-2">- <div className="flex flex-col items-center gap-1.5 p-3 rounded-xl bg-white/5 dark:bg-white/3 border border-white/10 dark:border-white/5">- <div className="w-8 h-8 rounded-lg bg-primary/15 flex items-center justify-center">- <Mic className="w-4 h-4 text-primary" />+ case 1: // Setup - Choose Mode & Configure (merged with permissions for signed-in users)+ // Simplified path for signed-in users (cloud-first) with permissions+ if (isSignedIn && !skipAuth) {+ const platform = permissionsHook.pasteToolsInfo?.platform;+ const isMacOS = platform === "darwin";++ return (+ <div className="space-y-6">+ <div className="text-center">+ <div className="w-14 h-14 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4">+ <Check className="w-7 h-7 text-emerald-600" /></div>- <span className="text-xs font-medium text-foreground">Voice to Text</span>- <span className="text-[10px] text-muted-foreground">Instant</span>+ <h2 className="text-2xl font-semibold text-foreground mb-2">Setup</h2>+ <p className="text-muted-foreground">Choose your language and grant permissions</p></div>- <div className="flex flex-col items-center gap-1.5 p-3 rounded-xl bg-white/5 dark:bg-white/3 border border-white/10 dark:border-white/5">- <div className="w-8 h-8 rounded-lg bg-primary/15 flex items-center justify-center">- <Command className="w-4 h-4 text-primary" />++ {/* Language Selector */}+ <div className="space-y-2.5 p-3 bg-muted/50 border border-border/60 rounded">+ <div className="space-y-1.5">+ <label className="block text-xs font-medium text-muted-foreground">+ Language+ </label>+ <LanguageSelector+ value={preferredLanguage}+ onChange={(value) => {+ updateTranscriptionSettings({ preferredLanguage: value });+ }}+ className="w-full"+ /></div>- <span className="text-xs font-medium text-foreground">Works Anywhere</span>- <span className="text-[10px] text-muted-foreground">Any app</span></div>- <div className="flex flex-col items-center gap-1.5 p-3 rounded-xl bg-white/5 dark:bg-white/3 border border-white/10 dark:border-white/5">- <div className="w-8 h-8 rounded-lg bg-primary/15 flex items-center justify-center">- <Shield className="w-4 h-4 text-primary" />++ {/* Permissions */}+ <div className="space-y-3">+ <h3 className="text-sm font-medium text-foreground">Permissions</h3>+ <div className="space-y-1.5">+ <PermissionCard+ icon={Mic}+ title="Microphone"+ description="To capture your voice"+ granted={permissionsHook.micPermissionGranted}+ onRequest={permissionsHook.requestMicPermission}+ buttonText="Grant"+ />++ {isMacOS && (+ <PermissionCard+ icon={Shield}+ title="Accessibility"+ description="To paste text into apps"+ granted={permissionsHook.accessibilityPermissionGranted}+ onRequest={permissionsHook.testAccessibilityPermission}+ buttonText="Test & Grant"+ onOpenSettings={permissionsHook.openAccessibilitySettings}+ />+ )}</div>- <span className="text-xs font-medium text-foreground">Private</span>- <span className="text-[10px] text-muted-foreground">Your choice</span>++ {/* Error state - only show when there's actually an issue */}+ {!permissionsHook.micPermissionGranted && permissionsHook.micPermissionError && (+ <MicPermissionWarning+ error={permissionsHook.micPermissionError}+ onOpenSoundSettings={permissionsHook.openSoundInputSettings}+ onOpenPrivacySettings={permissionsHook.openMicPrivacySettings}+ />+ )}++ {/* Linux paste tools - only when needed */}+ {platform === "linux" &&+ permissionsHook.pasteToolsInfo &&+ !permissionsHook.pasteToolsInfo.available && (+ <PasteToolsInfo+ pasteToolsInfo={permissionsHook.pasteToolsInfo}+ isChecking={permissionsHook.isCheckingPasteTools}+ onCheck={permissionsHook.checkPasteToolsAvailability}+ />+ )}</div></div>- </div>- );+ );+ }- case 1: // Setup - Choose Mode & Configure+ // Not signed in — full setup (unchanged)return (<div className="space-y-3"><div className="text-center space-y-0.5">@@ -372,10 +462,30 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {}variant="onboarding"/>++ {/* Language Selection - shown for both modes */}+ <div className="space-y-2 p-3 bg-muted/50 border border-border/60 rounded">+ <label className="block text-xs font-medium text-muted-foreground">+ Preferred Language+ </label>+ <LanguageSelector+ value={preferredLanguage}+ onChange={(value) => {+ updateTranscriptionSettings({ preferredLanguage: value });+ }}+ className="w-full"+ />+ </div></div>);- case 2: // Permissions+ case 2: // Permissions (only for non-signed-in users) or Activation (for signed-in users)+ // For signed-in users, this is the activation step+ if (isSignedIn && !skipAuth) {+ return renderActivationStep();+ }++ // For non-signed-in users, this is the permissions stepconst platform = permissionsHook.pasteToolsInfo?.platform;const isMacOS = platform === "darwin";@@ -435,91 +545,105 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {</div>);- case 3: // Hotkey & Activation Mode- return (- <div className="space-y-4">- {/* Header */}- <div className="text-center space-y-0.5">- <h2 className="text-lg font-semibold text-foreground tracking-tight">- Activation Setup- </h2>- <p className="text-xs text-muted-foreground">Configure how you trigger dictation</p>- </div>+ case 3: // Activation (only for non-signed-in users)+ return renderActivationStep();- {/* Unified control surface */}- <div className="rounded-lg border border-border-subtle bg-surface-1 overflow-hidden">- {/* Hotkey section */}- <div className="p-4 border-b border-border-subtle">- <div className="flex items-center justify-between mb-3">- <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">- Hotkey- </span>- </div>- <HotkeyInput- value={hotkey}- onChange={async (newHotkey) => {- const success = await registerHotkey(newHotkey);- if (success) {- setHotkey(newHotkey);- }- }}- disabled={isHotkeyRegistering}- variant="hero"- />- </div>+ default:+ return null;+ }+ };- {/* Mode section - inline with hotkey */}- {!isUsingGnomeHotkeys && (- <div className="p-4 flex items-center justify-between gap-4">- <div className="flex-1 min-w-0">- <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">- Mode- </span>- <p className="text-[11px] text-muted-foreground/70 mt-0.5">- {activationMode === "tap" ? "Press to start/stop" : "Hold while speaking"}- </p>- </div>- <ActivationModeSelector- value={activationMode}- onChange={setActivationMode}- variant="compact"- />- </div>- )}- </div>+ const renderActivationStep = () => (+ <div className="space-y-4">+ {/* Header */}+ <div className="text-center space-y-0.5">+ <h2 className="text-lg font-semibold text-foreground tracking-tight">Activation Setup</h2>+ <p className="text-xs text-muted-foreground">Configure how you trigger dictation</p>+ </div>- {/* Test area - minimal chrome */}- <div className="space-y-2">- <div className="flex items-center gap-2">- <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">- Test- </span>- <span className="text-[10px] text-muted-foreground/60">- {activationMode === "tap" || isUsingGnomeHotkeys- ? `${readableHotkey} to start/stop`- : `Hold ${readableHotkey}`}- </span>- </div>- <Textarea- rows={2}- placeholder="Click here and use your hotkey to dictate..."- className="text-sm resize-none"- />+ {/* Unified control surface */}+ <div className="rounded-lg border border-border-subtle bg-surface-1 overflow-hidden">+ {/* Hotkey section */}+ <div className="p-4 border-b border-border-subtle">+ <div className="flex items-center justify-between mb-3">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Hotkey+ </span>+ </div>+ <HotkeyInput+ value={hotkey}+ onChange={async (newHotkey) => {+ const success = await registerHotkey(newHotkey);+ if (success) {+ setHotkey(newHotkey);+ }+ }}+ disabled={isHotkeyRegistering}+ variant="hero"+ validate={validateHotkeyForInput}+ />+ </div>++ {/* Mode section - inline with hotkey */}+ {!isUsingGnomeHotkeys && (+ <div className="p-4 flex items-center justify-between gap-4">+ <div className="flex-1 min-w-0">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Mode+ </span>+ <p className="text-[11px] text-muted-foreground/70 mt-0.5">+ {activationMode === "tap" ? "Press to start/stop" : "Hold while speaking"}+ </p></div>+ <ActivationModeSelector+ value={activationMode}+ onChange={setActivationMode}+ variant="compact"+ /></div>- );+ )}+ </div>- default:- return null;- }- };+ {/* Test area - minimal chrome */}+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">+ Test+ </span>+ <span className="text-[10px] text-muted-foreground/60">+ {activationMode === "tap" || isUsingGnomeHotkeys+ ? `${readableHotkey} to start/stop`+ : `Hold ${readableHotkey}`}+ </span>+ </div>+ <Textarea+ rows={2}+ placeholder="Click here and use your hotkey to dictate..."+ className="text-sm resize-none"+ />+ </div>+ </div>+ );const canProceed = () => {switch (currentStep) {case 0:- return true; // Welcome+ return isSignedIn || skipAuth; // Authentication stepcase 1:- // Setup - check if configuration is complete+ // For signed-in users: Setup step includes permissions+ if (isSignedIn && !skipAuth) {+ // Check permissions+ if (!permissionsHook.micPermissionGranted) {+ return false;+ }+ const currentPlatform = permissionsHook.pasteToolsInfo?.platform;+ if (currentPlatform === "darwin") {+ return permissionsHook.accessibilityPermissionGranted;+ }+ return true;+ }++ // For non-signed-in users: Setup - check if configuration is completeif (useLocalWhisper) {const modelToCheck =localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel;@@ -537,7 +661,12 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return openaiApiKey.trim().length > 0; // Default to OpenAI}case 2: {- // Permissions+ // For signed-in users, this is activation step+ if (isSignedIn && !skipAuth) {+ return hotkey.trim() !== "";+ }++ // For non-signed-in users, this is permissions stepif (!permissionsHook.micPermissionGranted) {return false;}@@ -548,7 +677,7 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {return true;}case 3:- return hotkey.trim() !== ""; // Activation step (final)+ return hotkey.trim() !== ""; // Activation step for non-signed-in usersdefault:return false;}@@ -592,68 +721,81 @@ export default function OnboardingFlow({ onComplete }: OnboardingFlowProps) {/>{/* Title Bar */}- <div className="flex-shrink-0 z-10">+ <div className="shrink-0 z-10"><TitleBarshowTitle={true}className="bg-background backdrop-blur-xl border-b border-border shadow-sm"+ actions={isSignedIn ? <SupportDropdown /> : undefined}></TitleBar></div>- {/* Progress Bar */}- <div className="flex-shrink-0 bg-background/80 backdrop-blur-2xl border-b border-white/5 px-6 md:px-12 py-4 z-10">- <div className="max-w-3xl mx-auto">- <StepProgress steps={steps} currentStep={currentStep} />+ {/* Progress Bar - hidden on welcome/auth step */}+ {showProgress && (+ <div className="shrink-0 bg-background/80 backdrop-blur-2xl border-b border-white/5 px-6 md:px-12 py-3 z-10">+ <div className="max-w-3xl mx-auto">+ <StepProgress steps={steps.slice(1)} currentStep={currentStep - 1} />+ </div></div>- </div>+ )}{/* Content - This will grow to fill available space */}- <div className="flex-1 px-6 md:px-12 py-6 overflow-y-auto">- <div className="max-w-3xl mx-auto">- <Card className="bg-card/80 backdrop-blur-2xl border border-white/10 dark:border-white/5 shadow-xl rounded-2xl overflow-hidden">- <CardContent className="p-8 md:p-10">- <div className="space-y-6">{renderStep()}</div>+ <div+ className={`flex-1 px-6 md:px-12 overflow-y-auto ${currentStep === 0 ? "flex items-center" : "py-6"}`}+ >+ <div className={`w-full ${currentStep === 0 ? "max-w-sm" : "max-w-3xl"} mx-auto`}>+ <Card className="bg-card/90 backdrop-blur-2xl border border-border/50 dark:border-white/5 shadow-lg rounded-xl overflow-hidden">+ <CardContent className={currentStep === 0 ? "p-6" : "p-6 md:p-8"}>+ {renderStep()}</CardContent></Card></div></div>- {/* Footer - This will stick to the bottom */}- <div className="flex-shrink-0 bg-background/80 backdrop-blur-2xl border-t border-white/5 px-6 md:px-12 py-3 z-10">- <div className="max-w-3xl mx-auto flex items-center justify-between">- <Button- onClick={prevStep}- variant="outline"- disabled={currentStep === 0}- className="h-8 px-5 rounded-full text-xs"- >- <ChevronLeft className="w-3.5 h-3.5" />- Back- </Button>-- <div className="flex items-center gap-2">- {currentStep === steps.length - 1 ? (- <Button- onClick={finishOnboarding}- disabled={!canProceed()}- variant="success"- className="h-8 px-6 rounded-full text-xs"- >- <Check className="w-3.5 h-3.5" />- Complete- </Button>- ) : (+ {/* Footer Navigation - hidden on welcome/auth step */}+ {showProgress && (+ <div className="shrink-0 bg-background/80 backdrop-blur-2xl border-t border-white/5 px-6 md:px-12 py-3 z-10">+ <div className="max-w-3xl mx-auto flex items-center justify-between">+ {/* Hide back button on first step for signed-in users */}+ {!(currentStep === 1 && isSignedIn && !skipAuth) && (<Button- onClick={nextStep}- disabled={!canProceed()}- className="h-8 px-6 rounded-full text-xs"+ onClick={prevStep}+ variant="outline"+ disabled={currentStep === 0}+ className="h-8 px-5 rounded-full text-xs">- Next- <ChevronRight className="w-3.5 h-3.5" />+ <ChevronLeft className="w-3.5 h-3.5" />+ Back</Button>)}++ {/* Spacer to push next button to the right when back button is hidden */}+ {currentStep === 1 && isSignedIn && !skipAuth && <div />}++ <div className="flex items-center gap-2">+ {currentStep === steps.length - 1 ? (+ <Button+ onClick={finishOnboarding}+ disabled={!canProceed()}+ variant="success"+ className="h-8 px-6 rounded-full text-xs"+ >+ <Check className="w-3.5 h-3.5" />+ Complete+ </Button>+ ) : (+ <Button+ onClick={nextStep}+ disabled={!canProceed()}+ className="h-8 px-6 rounded-full text-xs"+ >+ Next+ <ChevronRight className="w-3.5 h-3.5" />+ </Button>+ )}+ </div></div></div>- </div>+ )}</div>);}diff --git a/src/components/ReasoningModelSelector.tsx b/src/components/ReasoningModelSelector.tsxindex 3d6f877ef..3738b9d3f 100644--- a/src/components/ReasoningModelSelector.tsx+++ b/src/components/ReasoningModelSelector.tsx@@ -492,8 +492,8 @@ export default function ReasoningModelSelector({};return (- <div className="space-y-6">- <div className="flex items-center justify-between p-4 bg-card border border-border rounded-xl">+ <div className="space-y-4">+ <div className="flex items-center justify-between p-3 bg-card border border-border rounded-lg"><div><label className="text-sm font-medium text-foreground">Enable AI Text Enhancement</label><p className="text-xs text-muted-foreground">@@ -516,7 +516,7 @@ export default function ReasoningModelSelector({{useReasoningModel && (<>- <div className="space-y-3">+ <div className="space-y-2"><ProviderTabsproviders={MODE_TABS}selectedId={selectedMode}@@ -532,8 +532,8 @@ export default function ReasoningModelSelector({</div>{selectedMode === "cloud" ? (- <div className="space-y-4">- <div className="border border-border rounded-xl overflow-hidden">+ <div className="space-y-2">+ <div className="border border-border rounded-lg overflow-hidden"><ProviderTabsproviders={cloudProviders}selectedId={selectedCloudProvider}@@ -541,11 +541,11 @@ export default function ReasoningModelSelector({colorScheme="indigo"/>- <div className="p-4">+ <div className="p-3">{selectedCloudProvider === "custom" ? (<>{/* 1. Endpoint URL - TOP */}- <div className="space-y-3">+ <div className="space-y-2"><h4 className="font-medium text-foreground">Endpoint URL</h4><Inputvalue={customBaseInput}@@ -562,7 +562,7 @@ export default function ReasoningModelSelector({</div>{/* 2. API Key - SECOND */}- <div className="space-y-3 pt-4">+ <div className="space-y-2 pt-3"><h4 className="font-medium text-foreground">API Key (Optional)</h4><ApiKeyInputapiKey={customReasoningApiKey}@@ -573,7 +573,7 @@ export default function ReasoningModelSelector({</div>{/* 3. Model Selection - THIRD */}- <div className="space-y-3 pt-4">+ <div className="space-y-2 pt-3"><div className="flex items-center justify-between"><h4 className="text-sm font-medium text-foreground">Available Models</h4><div className="flex gap-2">@@ -654,7 +654,7 @@ export default function ReasoningModelSelector({<>{/* 1. API Key - TOP */}{selectedCloudProvider === "openai" && (- <div className="space-y-3">+ <div className="space-y-2"><div className="flex items-baseline justify-between"><h4 className="font-medium text-foreground">API Key</h4><a@@ -664,7 +664,7 @@ export default function ReasoningModelSelector({onClick={createExternalLinkHandler("https://platform.openai.com/api-keys")}- className="text-xs text-primary hover:text-primary/80 underline cursor-pointer"+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors">Get your API key →</a>@@ -679,7 +679,7 @@ export default function ReasoningModelSelector({)}{selectedCloudProvider === "anthropic" && (- <div className="space-y-3">+ <div className="space-y-2"><div className="flex items-baseline justify-between"><h4 className="font-medium text-foreground">API Key</h4><a@@ -689,7 +689,7 @@ export default function ReasoningModelSelector({onClick={createExternalLinkHandler("https://console.anthropic.com/settings/keys")}- className="text-xs text-primary hover:text-primary/80 underline cursor-pointer"+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors">Get your API key →</a>@@ -705,7 +705,7 @@ export default function ReasoningModelSelector({)}{selectedCloudProvider === "gemini" && (- <div className="space-y-3">+ <div className="space-y-2"><div className="flex items-baseline justify-between"><h4 className="font-medium text-foreground">API Key</h4><a@@ -715,7 +715,7 @@ export default function ReasoningModelSelector({onClick={createExternalLinkHandler("https://aistudio.google.com/app/api-keys")}- className="text-xs text-primary hover:text-primary/80 underline cursor-pointer"+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors">Get your API key →</a>@@ -731,7 +731,7 @@ export default function ReasoningModelSelector({)}{selectedCloudProvider === "groq" && (- <div className="space-y-3">+ <div className="space-y-2"><div className="flex items-baseline justify-between"><h4 className="font-medium text-foreground">API Key</h4><a@@ -739,7 +739,7 @@ export default function ReasoningModelSelector({target="_blank"rel="noopener noreferrer"onClick={createExternalLinkHandler("https://console.groq.com/keys")}- className="text-xs text-primary hover:text-primary/80 underline cursor-pointer"+ className="text-xs text-link underline decoration-link/30 hover:decoration-link/60 cursor-pointer transition-colors">Get your API key →</a>@@ -755,7 +755,7 @@ export default function ReasoningModelSelector({)}{/* 2. Model Selection - BOTTOM */}- <div className="pt-4 space-y-3">+ <div className="pt-3 space-y-2"><h4 className="text-sm font-medium text-foreground">Select Model</h4><ModelCardListmodels={selectedCloudModels}diff --git a/src/components/ResetPasswordView.tsx b/src/components/ResetPasswordView.tsxnew file mode 100644index 000000000..f67dada03--- /dev/null+++ b/src/components/ResetPasswordView.tsx@@ -0,0 +1,161 @@+import React, { useCallback, useState } from "react";+import { resetPassword, NEON_AUTH_URL, authClient } from "../lib/neonAuth";+import { Button } from "./ui/button";+import { Input } from "./ui/input";+import { AlertCircle, ArrowLeft, Check, Loader2 } from "lucide-react";++interface ResetPasswordViewProps {+ token: string;+ onSuccess: () => void;+ onBack: () => void;+}++export default function ResetPasswordView({ token, onSuccess, onBack }: ResetPasswordViewProps) {+ const [password, setPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [isSuccess, setIsSuccess] = useState(false);++ const handleSubmit = useCallback(+ async (e: React.FormEvent) => {+ e.preventDefault();++ if (!password || !confirmPassword) return;++ if (password !== confirmPassword) {+ setError("Passwords do not match");+ return;+ }++ if (password.length < 8) {+ setError("Password must be at least 8 characters");+ return;+ }++ setIsSubmitting(true);+ setError(null);++ const result = await resetPassword(password, token);++ if (result.error) {+ setError(result.error.message);+ setIsSubmitting(false);+ } else {+ setIsSuccess(true);+ setIsSubmitting(false);+ }+ },+ [password, confirmPassword, token]+ );++ if (!NEON_AUTH_URL || !authClient) {+ return (+ <div className="space-y-3">+ <div className="bg-warning/5 p-2.5 rounded border border-warning/20">+ <p className="text-[10px] text-warning text-center leading-snug">+ Authentication is not configured.+ </p>+ </div>+ <Button onClick={onBack} variant="outline" className="w-full h-9">+ <ArrowLeft className="w-3.5 h-3.5" />+ <span className="text-sm font-medium">Go Back</span>+ </Button>+ </div>+ );+ }++ if (isSuccess) {+ return (+ <div className="space-y-3">+ <div className="text-center mb-4">+ <div className="w-10 h-10 mx-auto bg-success/10 rounded-full flex items-center justify-center mb-3">+ <Check className="w-5 h-5 text-success" />+ </div>+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Password reset successful+ </p>+ <p className="text-muted-foreground text-sm mt-1.5 leading-snug">+ Your password has been updated. You're now signed in.+ </p>+ </div>++ <Button onClick={onSuccess} className="w-full h-9">+ <span className="text-sm font-medium">Continue</span>+ </Button>+ </div>+ );+ }++ return (+ <div className="space-y-3">+ <button+ type="button"+ onClick={onBack}+ className="text-[10px] text-muted-foreground hover:text-foreground transition-colors flex items-center gap-0.5"+ >+ <ArrowLeft className="w-3 h-3" />+ Back to sign in+ </button>++ <div className="text-center mb-4">+ <p className="text-lg font-semibold text-foreground tracking-tight leading-tight">+ Create new password+ </p>+ <p className="text-muted-foreground text-sm mt-1 leading-tight">+ Enter your new password below+ </p>+ </div>++ <form onSubmit={handleSubmit} className="space-y-2">+ <Input+ type="password"+ placeholder="New password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ className="h-9 text-sm"+ required+ minLength={8}+ disabled={isSubmitting}+ autoFocus+ />+ <Input+ type="password"+ placeholder="Confirm new password"+ value={confirmPassword}+ onChange={(e) => setConfirmPassword(e.target.value)}+ className="h-9 text-sm"+ required+ minLength={8}+ disabled={isSubmitting}+ />++ <p className="text-[9px] text-muted-foreground/70 leading-tight">+ Password must be at least 8 characters+ </p>++ {error && (+ <div className="px-2.5 py-1.5 rounded bg-destructive/5 border border-destructive/20 flex items-center gap-1.5">+ <AlertCircle className="w-3 h-3 text-destructive shrink-0" />+ <p className="text-[10px] text-destructive leading-snug">{error}</p>+ </div>+ )}++ <Button+ type="submit"+ disabled={isSubmitting || !password || !confirmPassword}+ className="w-full h-9"+ >+ {isSubmitting ? (+ <>+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ <span className="text-sm font-medium">Resetting...</span>+ </>+ ) : (+ <span className="text-sm font-medium">Reset Password</span>+ )}+ </Button>+ </form>+ </div>+ );+}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex d2d891a74..147a31a91 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -1,5 +1,16 @@import React, { useEffect } from "react";-import { Settings, Mic, Brain, User, Sparkles, Wrench, BookOpen, ShieldCheck } from "lucide-react";+import {+ Sliders,+ Mic,+ Brain,+ User,+ Sparkles,+ UserCircle,+ Wrench,+ BookOpen,+ ShieldCheck,+ Lock,+} from "lucide-react";import SidebarModal, { SidebarItem } from "./ui/SidebarModal";import SettingsPage, { SettingsSectionType } from "./SettingsPage";@@ -13,10 +24,17 @@ interface SettingsModalProps {export default function SettingsModal({ open, onOpenChange, initialSection }: SettingsModalProps) {const sidebarItems: SidebarItem<SettingsSectionType>[] = [+ {+ id: "account",+ label: "Account",+ icon: UserCircle,+ description: "Sign in & usage",+ group: "Profile",+ },{id: "general",- label: "General",- icon: Settings,+ label: "Preferences",+ icon: Sliders,description: "Appearance, hotkey & startup",group: "App",},@@ -55,6 +73,13 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Sedescription: "System prompt studio",group: "Intelligence",},+ {+ id: "privacy",+ label: "Privacy",+ icon: Lock,+ description: "Cloud backup & analytics",+ group: "System",+ },{id: "permissions",label: "Permissions",@@ -71,7 +96,7 @@ export default function SettingsModal({ open, onOpenChange, initialSection }: Se},];- const [activeSection, setActiveSection] = React.useState<SettingsSectionType>("general");+ const [activeSection, setActiveSection] = React.useState<SettingsSectionType>("account");// Navigate to initial section when modal opensuseEffect(() => {diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 58664ab55..c9901f7c8 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -2,7 +2,25 @@ import React, { useState, useCallback, useEffect, useRef, useMemo } from "react"import { Button } from "./ui/button";import { Input } from "./ui/input";import { Badge } from "./ui/badge";-import { RefreshCw, Download, Mic, Shield, FolderOpen, Sun, Moon, Monitor } from "lucide-react";+import {+ RefreshCw,+ Download,+ Command,+ Mic,+ Shield,+ FolderOpen,+ LogOut,+ UserCircle,+ Sun,+ Moon,+ Monitor,+ Cloud,+ Key,+ ChevronDown,+ Sparkles,+} from "lucide-react";+import { useAuth } from "../hooks/useAuth";+import { NEON_AUTH_URL, signOut } from "../lib/neonAuth";import MarkdownRenderer from "./ui/MarkdownRenderer";import MicPermissionWarning from "./ui/MicPermissionWarning";import MicrophoneSettings from "./ui/MicrophoneSettings";@@ -22,14 +40,23 @@ import PromptStudio from "./ui/PromptStudio";import ReasoningModelSelector from "./ReasoningModelSelector";import { HotkeyInput } from "./ui/HotkeyInput";+import HotkeyGuidanceAccordion from "./ui/HotkeyGuidanceAccordion";import { useHotkeyRegistration } from "../hooks/useHotkeyRegistration";+import { getValidationMessage } from "../utils/hotkeyValidator";+import { getPlatform } from "../utils/platform";import { ActivationModeSelector } from "./ui/ActivationModeSelector";import { Toggle } from "./ui/toggle";import DeveloperSection from "./DeveloperSection";+import { Skeleton } from "./ui/skeleton";+import { Progress } from "./ui/progress";+import { useToast } from "./ui/Toast";import { useTheme } from "../hooks/useTheme";import { SettingsRow } from "./ui/SettingsSection";+import { useUsage } from "../hooks/useUsage";+import { cn } from "./lib/utils";export type SettingsSectionType =+ | "account"| "general"| "transcription"| "dictionary"@@ -37,6 +64,7 @@ export type SettingsSectionType =| "agentConfig"| "prompts"| "permissions"+ | "privacy"| "developer";interface SettingsPageProps {@@ -82,6 +110,278 @@ function SectionHeader({ title, description }: { title: string; description?: st);}+// ── Transcription section (extracted for clarity) ───────────────────++interface TranscriptionSectionProps {+ isSignedIn: boolean;+ cloudTranscriptionMode: string;+ setCloudTranscriptionMode: (mode: string) => void;+ useLocalWhisper: boolean;+ setUseLocalWhisper: (value: boolean) => void;+ updateTranscriptionSettings: (settings: { useLocalWhisper: boolean }) => void;+ cloudTranscriptionProvider: string;+ setCloudTranscriptionProvider: (provider: string) => void;+ cloudTranscriptionModel: string;+ setCloudTranscriptionModel: (model: string) => void;+ localTranscriptionProvider: string;+ setLocalTranscriptionProvider: (provider: string) => void;+ whisperModel: string;+ setWhisperModel: (model: string) => void;+ parakeetModel: string;+ setParakeetModel: (model: string) => void;+ openaiApiKey: string;+ setOpenaiApiKey: (key: string) => void;+ groqApiKey: string;+ setGroqApiKey: (key: string) => void;+ customTranscriptionApiKey: string;+ setCustomTranscriptionApiKey: (key: string) => void;+ cloudTranscriptionBaseUrl?: string;+ setCloudTranscriptionBaseUrl: (url: string) => void;+ toast: (opts: {+ title: string;+ description: string;+ variant?: string;+ duration?: number;+ }) => void;+}++function TranscriptionSection({+ isSignedIn,+ cloudTranscriptionMode,+ setCloudTranscriptionMode,+ useLocalWhisper,+ setUseLocalWhisper,+ updateTranscriptionSettings,+ cloudTranscriptionProvider,+ setCloudTranscriptionProvider,+ cloudTranscriptionModel,+ setCloudTranscriptionModel,+ localTranscriptionProvider,+ setLocalTranscriptionProvider,+ whisperModel,+ setWhisperModel,+ parakeetModel,+ setParakeetModel,+ openaiApiKey,+ setOpenaiApiKey,+ groqApiKey,+ setGroqApiKey,+ customTranscriptionApiKey,+ setCustomTranscriptionApiKey,+ cloudTranscriptionBaseUrl,+ setCloudTranscriptionBaseUrl,+ toast,+}: TranscriptionSectionProps) {+ const [advancedOpen, setAdvancedOpen] = useState(false);++ // Determine if we're in "advanced" mode (BYOK or local)+ const isAdvancedMode = cloudTranscriptionMode === "byok" || useLocalWhisper;++ // When user is signed in and using OpenWhispr Cloud, keep it simple+ const isCloudMode = isSignedIn && cloudTranscriptionMode === "openwhispr" && !useLocalWhisper;++ return (+ <div className="space-y-5">+ <SectionHeader+ title="Speech to Text"+ description="Choose how OpenWhispr transcribes your voice"+ />++ {/* Primary option: OpenWhispr Cloud */}+ {isSignedIn && (+ <SettingsPanel>+ <SettingsPanelRow>+ <button+ onClick={() => {+ if (!isCloudMode) {+ setCloudTranscriptionMode("openwhispr");+ setUseLocalWhisper(false);+ updateTranscriptionSettings({ useLocalWhisper: false });+ setAdvancedOpen(false);+ toast({+ title: "Switched to OpenWhispr Cloud",+ description: "Transcription will use OpenWhispr's cloud service.",+ variant: "success",+ duration: 3000,+ });+ }+ }}+ className="w-full flex items-center gap-3 text-left cursor-pointer group"+ >+ <div+ className={`w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition-colors ${+ isCloudMode+ ? "bg-primary/10 dark:bg-primary/15"+ : "bg-muted/60 dark:bg-surface-raised group-hover:bg-muted dark:group-hover:bg-surface-3"+ }`}+ >+ <Cloud+ className={`w-4 h-4 transition-colors ${+ isCloudMode ? "text-primary" : "text-muted-foreground"+ }`}+ />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-[12px] font-medium text-foreground">OpenWhispr Cloud</span>+ {isCloudMode && (+ <span className="text-[10px] font-medium text-primary bg-primary/10 dark:bg-primary/15 px-1.5 py-px rounded-sm">+ Active+ </span>+ )}+ </div>+ <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ Just works. No configuration needed.+ </p>+ </div>+ <div+ className={`w-4 h-4 rounded-full border-2 shrink-0 transition-colors ${+ isCloudMode+ ? "border-primary bg-primary"+ : "border-border-hover dark:border-border-subtle"+ }`}+ >+ {isCloudMode && (+ <div className="w-full h-full flex items-center justify-center">+ <div className="w-1.5 h-1.5 rounded-full bg-primary-foreground" />+ </div>+ )}+ </div>+ </button>+ </SettingsPanelRow>+ </SettingsPanel>+ )}++ {/* Advanced section */}+ <div>+ <button+ onClick={() => setAdvancedOpen(!advancedOpen)}+ className="flex items-center gap-1.5 text-[12px] font-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer mb-3"+ >+ <ChevronDown+ className={`w-3.5 h-3.5 transition-transform duration-200 ${+ advancedOpen || isAdvancedMode ? "rotate-0" : "-rotate-90"+ }`}+ />+ Advanced+ {isAdvancedMode && (+ <span className="text-[10px] font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm ml-1">+ Active+ </span>+ )}+ </button>++ {(advancedOpen || isAdvancedMode) && (+ <div className="space-y-3">+ {isSignedIn && (+ <SettingsPanel>+ <SettingsPanelRow>+ <button+ onClick={() => {+ if (cloudTranscriptionMode !== "byok" || useLocalWhisper) {+ setCloudTranscriptionMode("byok");+ setUseLocalWhisper(false);+ updateTranscriptionSettings({ useLocalWhisper: false });+ toast({+ title: "Switched to Bring Your Own Key",+ description: "You'll need to provide your own API key for transcription.",+ variant: "success",+ duration: 3000,+ });+ }+ }}+ className="w-full flex items-center gap-3 text-left cursor-pointer group"+ >+ <div+ className={`w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition-colors ${+ cloudTranscriptionMode === "byok" && !useLocalWhisper+ ? "bg-accent/10 dark:bg-accent/15"+ : "bg-muted/60 dark:bg-surface-raised group-hover:bg-muted dark:group-hover:bg-surface-3"+ }`}+ >+ <Key+ className={`w-4 h-4 transition-colors ${+ cloudTranscriptionMode === "byok" && !useLocalWhisper+ ? "text-accent"+ : "text-muted-foreground"+ }`}+ />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-[12px] font-medium text-foreground">+ Bring Your Own Key+ </span>+ {cloudTranscriptionMode === "byok" && !useLocalWhisper && (+ <span className="text-[10px] font-medium text-accent bg-accent/10 dark:bg-accent/15 px-1.5 py-px rounded-sm">+ Active+ </span>+ )}+ </div>+ <p className="text-[11px] text-muted-foreground/80 mt-0.5">+ Use your own API key. No usage limits.+ </p>+ </div>+ <div+ className={`w-4 h-4 rounded-full border-2 shrink-0 transition-colors ${+ cloudTranscriptionMode === "byok" && !useLocalWhisper+ ? "border-accent bg-accent"+ : "border-border-hover dark:border-border-subtle"+ }`}+ >+ {cloudTranscriptionMode === "byok" && !useLocalWhisper && (+ <div className="w-full h-full flex items-center justify-center">+ <div className="w-1.5 h-1.5 rounded-full bg-accent-foreground" />+ </div>+ )}+ </div>+ </button>+ </SettingsPanelRow>+ </SettingsPanel>+ )}++ <TranscriptionModelPicker+ selectedCloudProvider={cloudTranscriptionProvider}+ onCloudProviderSelect={setCloudTranscriptionProvider}+ selectedCloudModel={cloudTranscriptionModel}+ onCloudModelSelect={setCloudTranscriptionModel}+ selectedLocalModel={+ localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel+ }+ onLocalModelSelect={(modelId) => {+ if (localTranscriptionProvider === "nvidia") {+ setParakeetModel(modelId);+ } else {+ setWhisperModel(modelId);+ }+ }}+ selectedLocalProvider={localTranscriptionProvider}+ onLocalProviderSelect={setLocalTranscriptionProvider}+ useLocalWhisper={useLocalWhisper}+ onModeChange={(isLocal) => {+ setUseLocalWhisper(isLocal);+ updateTranscriptionSettings({ useLocalWhisper: isLocal });+ if (isLocal) {+ setCloudTranscriptionMode("byok");+ }+ }}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ customTranscriptionApiKey={customTranscriptionApiKey}+ setCustomTranscriptionApiKey={setCustomTranscriptionApiKey}+ cloudTranscriptionBaseUrl={cloudTranscriptionBaseUrl}+ setCloudTranscriptionBaseUrl={setCloudTranscriptionBaseUrl}+ variant="settings"+ />+ </div>+ )}+ </div>+ </div>+ );+}+// ── Main component ──────────────────────────────────────────────────export default function SettingsPage({ activeSection = "general" }: SettingsPageProps) {@@ -141,8 +441,16 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagesetDictationKey,updateTranscriptionSettings,updateReasoningSettings,+ cloudTranscriptionMode,+ setCloudTranscriptionMode,+ cloudBackupEnabled,+ setCloudBackupEnabled,+ telemetryEnabled,+ setTelemetryEnabled,} = useSettings();+ const { toast } = useToast();+const [currentVersion, setCurrentVersion] = useState<string>("");const [isRemovingModels, setIsRemovingModels] = useState(false);const cachePathHint =@@ -172,6 +480,19 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageuseClipboard(showAlertDialog);const { agentName, setAgentName } = useAgentName();const { theme, setTheme } = useTheme();+ const usage = useUsage();+ const hasShownApproachingToast = useRef(false);+ useEffect(() => {+ if (usage?.isApproachingLimit && !hasShownApproachingToast.current) {+ hasShownApproachingToast.current = true;+ toast({+ title: "Approaching Weekly Limit",+ description: `You've used ${usage.wordsUsed.toLocaleString()} of ${usage.limit.toLocaleString()} free words this week.`,+ duration: 6000,+ });+ }+ }, [usage?.isApproachingLimit, usage?.wordsUsed, usage?.limit, toast]);+const installTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const { registerHotkey, isRegistering: isHotkeyRegistering } = useHotkeyRegistration({@@ -183,6 +504,11 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageshowAlert: showAlertDialog,});+ const validateHotkeyForInput = useCallback(+ (hotkey: string) => getValidationMessage(hotkey, getPlatform()),+ []+ );+const [isUsingGnomeHotkeys, setIsUsingGnomeHotkeys] = useState(false);const platform = useMemo(() => {@@ -373,8 +699,248 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage});}, [isRemovingModels, cachePathHint, showConfirmDialog, showAlertDialog]);+ const { isSignedIn, isLoaded, user } = useAuth();+ const [isSigningOut, setIsSigningOut] = useState(false);++ const handleSignOut = useCallback(async () => {+ setIsSigningOut(true);+ try {+ await signOut();+ // Clear onboarding to show auth screen again+ localStorage.removeItem("onboardingCompleted");+ localStorage.removeItem("onboardingCurrentStep");+ // Reload the app to show onboarding/auth+ window.location.reload();+ } catch (error) {+ console.error("Sign out failed:", error);+ showAlertDialog({+ title: "Sign Out Failed",+ description: "Unable to sign out. Please try again.",+ });+ } finally {+ setIsSigningOut(false);+ }+ }, [showAlertDialog]);+const renderSectionContent = () => {switch (activeSection) {+ case "account":+ return (+ <div className="space-y-5">+ {!NEON_AUTH_URL ? (+ <>+ <SectionHeader title="Account" description="Authentication is not configured" />+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label="Account Features Disabled"+ description="Set VITE_NEON_AUTH_URL in your .env file to enable account features."+ >+ <Badge variant="warning">Disabled</Badge>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ ) : isLoaded && isSignedIn && user ? (+ <>+ <SectionHeader title="Account" />+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center gap-3">+ <div className="w-10 h-10 rounded-full flex items-center justify-center shrink-0 overflow-hidden bg-primary/10 dark:bg-primary/15">+ {user.image ? (+ <img+ src={user.image}+ alt={user.name || "User"}+ className="w-10 h-10 rounded-full object-cover"+ />+ ) : (+ <UserCircle className="w-5 h-5 text-primary" />+ )}+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-medium text-foreground truncate">+ {user.name || "User"}+ </p>+ <p className="text-[11px] text-muted-foreground truncate">{user.email}</p>+ </div>+ <Badge variant="success">Signed in</Badge>+ </div>+ </SettingsPanelRow>+ </SettingsPanel>++ <SectionHeader title="Plan" />+ {!usage || !usage.hasLoaded ? (+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center justify-between">+ <Skeleton className="h-4 w-24" />+ <Skeleton className="h-5 w-16 rounded-full" />+ </div>+ </SettingsPanelRow>+ <SettingsPanelRow>+ <div className="space-y-2">+ <Skeleton className="h-3 w-48" />+ <Skeleton className="h-8 w-full rounded" />+ </div>+ </SettingsPanelRow>+ </SettingsPanel>+ ) : (+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label={usage.isSubscribed ? (usage.isTrial ? "Trial" : "Pro") : "Free"}+ description={+ usage.isTrial+ ? `${usage.trialDaysLeft} ${usage.trialDaysLeft === 1 ? "day" : "days"} remaining \u2014 unlimited transcriptions`+ : usage.isSubscribed+ ? usage.currentPeriodEnd+ ? `Next billing: ${new Date(usage.currentPeriodEnd).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`+ : "Unlimited transcriptions"+ : `${usage.wordsUsed.toLocaleString()} / ${usage.limit.toLocaleString()} words this week`+ }+ >+ {usage.isTrial ? (+ <Badge variant="info">Trial</Badge>+ ) : usage.isSubscribed ? (+ <Badge variant="success">Pro</Badge>+ ) : usage.isOverLimit ? (+ <Badge variant="warning">Limit reached</Badge>+ ) : (+ <Badge variant="outline">Free</Badge>+ )}+ </SettingsRow>+ </SettingsPanelRow>++ {!usage.isSubscribed && !usage.isTrial && (+ <SettingsPanelRow>+ <div className="space-y-1.5">+ <Progress+ value={+ usage.limit > 0+ ? Math.min(100, (usage.wordsUsed / usage.limit) * 100)+ : 0+ }+ className={cn(+ "h-1.5",+ usage.isOverLimit+ ? "[&>div]:bg-destructive"+ : usage.isApproachingLimit+ ? "[&>div]:bg-warning"+ : "[&>div]:bg-primary"+ )}+ />+ <div className="flex items-center justify-between text-[11px] text-muted-foreground">+ <span className="tabular-nums">+ {usage.wordsUsed.toLocaleString()} / {usage.limit.toLocaleString()}+ </span>+ {usage.isApproachingLimit && (+ <span className="text-warning">+ {usage.wordsRemaining.toLocaleString()} remaining+ </span>+ )}+ {!usage.isApproachingLimit && !usage.isOverLimit && (+ <span>Rolling weekly limit</span>+ )}+ </div>+ </div>+ </SettingsPanelRow>+ )}++ <SettingsPanelRow>+ {usage.isSubscribed && !usage.isTrial ? (+ <Button+ onClick={() => usage.openBillingPortal()}+ variant="outline"+ size="sm"+ className="w-full"+ >+ Manage Billing+ </Button>+ ) : (+ <Button onClick={() => usage.openCheckout()} size="sm" className="w-full">+ Upgrade to Pro+ </Button>+ )}+ </SettingsPanelRow>+ </SettingsPanel>+ )}++ <SettingsPanel>+ <SettingsPanelRow>+ <Button+ onClick={handleSignOut}+ variant="outline"+ disabled={isSigningOut}+ size="sm"+ className="w-full text-destructive border-destructive/30 hover:bg-destructive/10 hover:border-destructive/50"+ >+ <LogOut className="mr-1.5 h-3.5 w-3.5" />+ {isSigningOut ? "Signing out..." : "Sign Out"}+ </Button>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ ) : isLoaded ? (+ <>+ <SectionHeader title="Account" />+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label="Not Signed In"+ description="Create an account to unlock premium features."+ >+ <Badge variant="outline">Offline</Badge>+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>++ <div className="rounded-lg border border-primary/20 dark:border-primary/15 bg-primary/3 dark:bg-primary/6 p-4">+ <div className="flex items-start gap-3">+ <div className="w-8 h-8 rounded-md bg-primary/10 dark:bg-primary/15 flex items-center justify-center shrink-0 mt-0.5">+ <Sparkles className="w-4 h-4 text-primary" />+ </div>+ <div className="min-w-0 flex-1 space-y-2.5">+ <div>+ <p className="text-[13px] font-medium text-foreground">+ Try Pro free for 7 days+ </p>+ <p className="text-[11px] text-muted-foreground leading-relaxed mt-0.5">+ Unlimited transcriptions, priority processing, and more.+ </p>+ </div>+ <Button+ onClick={() => {+ localStorage.removeItem("onboardingCompleted");+ localStorage.setItem("onboardingCurrentStep", "0");+ window.location.reload();+ }}+ size="sm"+ className="w-full"+ >+ <UserCircle className="mr-1.5 h-3.5 w-3.5" />+ Create Free Account+ </Button>+ </div>+ </div>+ </div>+ </>+ ) : (+ <>+ <SectionHeader title="Account" />+ <SettingsPanel>+ <SettingsPanelRow>+ <div className="flex items-center justify-between">+ <Skeleton className="h-4 w-32" />+ <Skeleton className="h-5 w-16 rounded-full" />+ </div>+ </SettingsPanelRow>+ </SettingsPanel>+ </>+ )}+ </div>+ );+// ───────────────────────────────────────────────────// GENERAL — Updates, Appearance, Hotkey, Startup, Mic// ───────────────────────────────────────────────────@@ -588,6 +1154,7 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPageawait registerHotkey(newHotkey);}}disabled={isHotkeyRegistering}+ validate={validateHotkeyForInput}/></SettingsPanelRow>@@ -648,45 +1215,33 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage// ───────────────────────────────────────────────────case "transcription":return (- <div className="space-y-5">- <SectionHeader- title="Speech to Text"- description="Choose a cloud provider for fast transcription or use local Whisper models for complete privacy"- />-- <TranscriptionModelPicker- selectedCloudProvider={cloudTranscriptionProvider}- onCloudProviderSelect={setCloudTranscriptionProvider}- selectedCloudModel={cloudTranscriptionModel}- onCloudModelSelect={setCloudTranscriptionModel}- selectedLocalModel={- localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel- }- onLocalModelSelect={(modelId) => {- if (localTranscriptionProvider === "nvidia") {- setParakeetModel(modelId);- } else {- setWhisperModel(modelId);- }- }}- selectedLocalProvider={localTranscriptionProvider}- onLocalProviderSelect={setLocalTranscriptionProvider}- useLocalWhisper={useLocalWhisper}- onModeChange={(isLocal) => {- setUseLocalWhisper(isLocal);- updateTranscriptionSettings({ useLocalWhisper: isLocal });- }}- openaiApiKey={openaiApiKey}- setOpenaiApiKey={setOpenaiApiKey}- groqApiKey={groqApiKey}- setGroqApiKey={setGroqApiKey}- customTranscriptionApiKey={customTranscriptionApiKey}- setCustomTranscriptionApiKey={setCustomTranscriptionApiKey}- cloudTranscriptionBaseUrl={cloudTranscriptionBaseUrl}- setCloudTranscriptionBaseUrl={setCloudTranscriptionBaseUrl}- variant="settings"- />- </div>+ <TranscriptionSection+ isSignedIn={isSignedIn ?? false}+ cloudTranscriptionMode={cloudTranscriptionMode}+ setCloudTranscriptionMode={setCloudTranscriptionMode}+ useLocalWhisper={useLocalWhisper}+ setUseLocalWhisper={setUseLocalWhisper}+ updateTranscriptionSettings={updateTranscriptionSettings}+ cloudTranscriptionProvider={cloudTranscriptionProvider}+ setCloudTranscriptionProvider={setCloudTranscriptionProvider}+ cloudTranscriptionModel={cloudTranscriptionModel}+ setCloudTranscriptionModel={setCloudTranscriptionModel}+ localTranscriptionProvider={localTranscriptionProvider}+ setLocalTranscriptionProvider={setLocalTranscriptionProvider}+ whisperModel={whisperModel}+ setWhisperModel={setWhisperModel}+ parakeetModel={parakeetModel}+ setParakeetModel={setParakeetModel}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ customTranscriptionApiKey={customTranscriptionApiKey}+ setCustomTranscriptionApiKey={setCustomTranscriptionApiKey}+ cloudTranscriptionBaseUrl={cloudTranscriptionBaseUrl}+ setCloudTranscriptionBaseUrl={setCloudTranscriptionBaseUrl}+ toast={toast}+ />);// ───────────────────────────────────────────────────@@ -838,30 +1393,46 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPagedescription='Configure how AI models clean up and format your transcriptions. Handles commands like "scratch that", creates proper lists, and fixes errors while preserving your natural tone.'/>- <ReasoningModelSelector- useReasoningModel={useReasoningModel}- setUseReasoningModel={(value) => {- setUseReasoningModel(value);- updateReasoningSettings({ useReasoningModel: value });- }}- setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}- cloudReasoningBaseUrl={cloudReasoningBaseUrl}- reasoningModel={reasoningModel}- setReasoningModel={setReasoningModel}- localReasoningProvider={reasoningProvider}- setLocalReasoningProvider={setReasoningProvider}- openaiApiKey={openaiApiKey}- setOpenaiApiKey={setOpenaiApiKey}- anthropicApiKey={anthropicApiKey}- setAnthropicApiKey={setAnthropicApiKey}- geminiApiKey={geminiApiKey}- setGeminiApiKey={setGeminiApiKey}- groqApiKey={groqApiKey}- setGroqApiKey={setGroqApiKey}- customReasoningApiKey={customReasoningApiKey}- setCustomReasoningApiKey={setCustomReasoningApiKey}- showAlertDialog={showAlertDialog}- />+ {isSignedIn && cloudTranscriptionMode === "openwhispr" ? (+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow label="Clean up transcriptions" description="Powered by OpenWhispr">+ <Toggle+ checked={useReasoningModel}+ onChange={(value) => {+ setUseReasoningModel(value);+ updateReasoningSettings({ useReasoningModel: value });+ }}+ />+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ ) : (+ <ReasoningModelSelector+ useReasoningModel={useReasoningModel}+ setUseReasoningModel={(value) => {+ setUseReasoningModel(value);+ updateReasoningSettings({ useReasoningModel: value });+ }}+ setCloudReasoningBaseUrl={setCloudReasoningBaseUrl}+ cloudReasoningBaseUrl={cloudReasoningBaseUrl}+ reasoningModel={reasoningModel}+ setReasoningModel={setReasoningModel}+ localReasoningProvider={reasoningProvider}+ setLocalReasoningProvider={setReasoningProvider}+ openaiApiKey={openaiApiKey}+ setOpenaiApiKey={setOpenaiApiKey}+ anthropicApiKey={anthropicApiKey}+ setAnthropicApiKey={setAnthropicApiKey}+ geminiApiKey={geminiApiKey}+ setGeminiApiKey={setGeminiApiKey}+ groqApiKey={groqApiKey}+ setGroqApiKey={setGroqApiKey}+ customReasoningApiKey={customReasoningApiKey}+ setCustomReasoningApiKey={setCustomReasoningApiKey}+ showAlertDialog={showAlertDialog}+ />+ )}</div>);@@ -984,6 +1555,45 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage</div>);+ // ───────────────────────────────────────────────────+ // PRIVACY+ // ───────────────────────────────────────────────────+ case "privacy":+ return (+ <div className="space-y-6">+ <div>+ <h3 className="text-lg font-semibold text-foreground mb-2">Privacy</h3>+ <p className="text-sm text-muted-foreground mb-6">+ Control what data leaves your device. Everything is off by default.+ </p>+ </div>++ {isSignedIn && (+ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label="Cloud backup"+ description="Save your transcriptions to the cloud so you never lose them."+ >+ <Toggle checked={cloudBackupEnabled} onChange={setCloudBackupEnabled} />+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ )}++ <SettingsPanel>+ <SettingsPanelRow>+ <SettingsRow+ label="Usage analytics"+ description="Help us improve OpenWhispr by sharing anonymous performance metrics. We never send transcription content — only timing and error data."+ >+ <Toggle checked={telemetryEnabled} onChange={setTelemetryEnabled} />+ </SettingsRow>+ </SettingsPanelRow>+ </SettingsPanel>+ </div>+ );+// ───────────────────────────────────────────────────// PERMISSIONS (new — extracted from General)// ───────────────────────────────────────────────────diff --git a/src/components/TranscriptionModelPicker.tsx b/src/components/TranscriptionModelPicker.tsxindex c3846ecba..f347abf0e 100644--- a/src/components/TranscriptionModelPicker.tsx+++ b/src/components/TranscriptionModelPicker.tsx@@ -76,27 +76,27 @@ function LocalModelCard({return (<divonClick={handleClick}- className={`relative w-full text-left overflow-hidden rounded-lg border transition-all duration-200 group ${+ className={`relative w-full text-left overflow-hidden rounded-md border transition-all duration-200 group ${isSelected ? cardStyles.modelCard.selected : cardStyles.modelCard.default} ${isDownloaded && !isSelected ? "cursor-pointer" : ""}`}>{/* Left accent bar for selected model */}{isSelected && (- <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-primary rounded-l-lg" />+ <div className="absolute left-0 top-0 bottom-0 w-1 bg-linear-to-b from-primary via-primary to-primary/80 rounded-l-md" />)}- <div className="flex items-center gap-2 p-2.5 pl-3">+ <div className="flex items-center gap-1.5 p-2 pl-2.5">{/* Status dot with LED glow */}<div className="shrink-0">{isDownloaded ? (<divclassName={`w-1.5 h-1.5 rounded-full ${isSelected- ? "bg-primary shadow-[0_0_6px_oklch(0.62_0.22_260/0.6)]"+ ? "bg-primary shadow-[0_0_6px_oklch(0.62_0.22_260/0.6)] animate-[pulse-glow_2s_ease-in-out_infinite]": "bg-success shadow-[0_0_4px_rgba(34,197,94,0.5)]"}`}/>) : isDownloading ? (- <div className="w-1.5 h-1.5 rounded-full bg-amber-500 shadow-[0_0_4px_rgba(245,158,11,0.5)]" />+ <div className="w-1.5 h-1.5 rounded-full bg-amber-500 shadow-[0_0_4px_rgba(245,158,11,0.5)] animate-[spinner-rotate_1s_linear_infinite]" />) : (<div className="w-1.5 h-1.5 rounded-full bg-muted-foreground/20" />)}@@ -105,13 +105,15 @@ function LocalModelCard({{/* Model info - single line, no description */}<div className="flex-1 min-w-0 flex items-center gap-1.5"><ProviderIcon provider={provider} className="w-3.5 h-3.5 shrink-0" />- <span className="font-medium text-sm text-foreground truncate">{name}</span>- <span className="text-[10px] text-muted-foreground/60 tabular-nums shrink-0">+ <span className="font-semibold text-sm text-foreground truncate tracking-tight">+ {name}+ </span>+ <span className="text-[11px] text-muted-foreground/50 tabular-nums shrink-0">{actualSizeMb ? `${actualSizeMb}MB` : size}</span>{recommended && <span className={cardStyles.badges.recommended}>Recommended</span>}{languageLabel && (- <span className="text-[10px] text-muted-foreground/50 font-medium shrink-0">+ <span className="text-[11px] text-muted-foreground/50 font-medium shrink-0">{languageLabel}</span>)}@@ -133,7 +135,7 @@ function LocalModelCard({}}size="sm"variant="ghost"- className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"+ className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-all active:scale-95"><Trash2 size={12} /></Button>@@ -216,16 +218,16 @@ interface ModeToggleProps {function ModeToggle({ useLocalWhisper, onModeChange }: ModeToggleProps) {return (- <div className="relative flex p-0.5 rounded-lg bg-surface-raised dark:bg-surface-1 border border-border dark:border-border-subtle">+ <div className="relative flex p-0.5 rounded-lg bg-surface-1/80 backdrop-blur-xl dark:bg-surface-1 border border-border/60 dark:border-white/8 shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)">{/* Sliding indicator */}<div- className={`absolute top-0.5 bottom-0.5 w-[calc(50%-2px)] rounded-md bg-card border border-border dark:border-border-subtle shadow-sm dark:shadow-(--shadow-card) transition-transform duration-200 ease-out ${- useLocalWhisper ? "translate-x-[calc(100%+4px)]" : "translate-x-0"+ className={`absolute top-0.5 bottom-0.5 w-[calc(50%-2px)] rounded-md bg-card border border-border/60 dark:border-border-subtle shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark) transition-transform duration-200 ease-out ${+ useLocalWhisper ? "translate-x-[calc(100%)]" : "translate-x-0"}`}/><buttononClick={() => onModeChange(false)}- className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 py-2 rounded-md transition-colors duration-150 ${+ className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md transition-colors duration-150 ${!useLocalWhisper ? "text-foreground" : "text-muted-foreground hover:text-foreground"}`}>@@ -234,7 +236,7 @@ function ModeToggle({ useLocalWhisper, onModeChange }: ModeToggleProps) {</button><buttononClick={() => onModeChange(true)}- className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 py-2 rounded-md transition-colors duration-150 ${+ className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md transition-colors duration-150 ${useLocalWhisper ? "text-foreground" : "text-muted-foreground hover:text-foreground"}`}>@@ -633,7 +635,7 @@ export default function TranscriptionModelPicker({: localModels;return (- <div className="space-y-1">+ <div className="space-y-0.5">{modelsToRender.map((model) => {const modelId = model.model;const info = WHISPER_MODEL_INFO[modelId] || {@@ -705,7 +707,7 @@ export default function TranscriptionModelPicker({: parakeetModels;return (- <div className="space-y-1">+ <div className="space-y-0.5">{modelsToRender.map((model) => {const modelId = model.model;const info = PARAKEET_MODEL_INFO[modelId] || {@@ -743,13 +745,13 @@ export default function TranscriptionModelPicker({};return (- <div className={`space-y-3 ${className}`}>+ <div className={`space-y-2 ${className}`}>{/* Integrated mode toggle - always visible */}<ModeToggle useLocalWhisper={useLocalWhisper} onModeChange={handleModeChange} />{!useLocalWhisper ? (<div className={styles.container}>- <div className="p-2.5 pb-0">+ <div className="p-2 pb-0"><ProviderTabsproviders={CLOUD_PROVIDER_TABS}selectedId={selectedCloudProvider}@@ -759,9 +761,9 @@ export default function TranscriptionModelPicker({/></div>- <div className="p-3">+ <div className="p-2">{selectedCloudProvider === "custom" ? (- <div className="space-y-3">+ <div className="space-y-2">{/* Endpoint URL */}<div className="space-y-1.5"><label className="block text-xs font-medium text-foreground">Endpoint URL</label>@@ -794,7 +796,7 @@ export default function TranscriptionModelPicker({</div></div>) : (- <div className="space-y-3">+ <div className="space-y-2">{/* API Key with inline link */}<div className="space-y-1.5"><div className="flex items-center justify-between">@@ -835,7 +837,7 @@ export default function TranscriptionModelPicker({</div>) : (<div className={styles.container}>- <div className="p-2.5 pb-0">+ <div className="p-2 pb-0"><ProviderTabsproviders={LOCAL_PROVIDER_TABS}selectedId={internalLocalProvider}@@ -846,7 +848,7 @@ export default function TranscriptionModelPicker({{progressDisplay}- <div className="p-3">+ <div className="p-2">{internalLocalProvider === "whisper" && renderLocalModels()}{internalLocalProvider === "nvidia" && renderParakeetModels()}</div>diff --git a/src/components/UpgradePrompt.tsx b/src/components/UpgradePrompt.tsxnew file mode 100644index 000000000..94e51073f--- /dev/null+++ b/src/components/UpgradePrompt.tsx@@ -0,0 +1,94 @@+import { Dialog, DialogContent } from "./ui/dialog";+import { ChevronRight } from "lucide-react";+import { useUsage } from "../hooks/useUsage";++interface UpgradePromptProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ wordsUsed?: number;+ limit?: number;+}++export default function UpgradePrompt({+ open,+ onOpenChange,+ wordsUsed = 2000,+ limit = 2000,+}: UpgradePromptProps) {+ const usage = useUsage();++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <div className="text-center space-y-2 pt-2">+ <h2 className="text-xl font-semibold text-foreground">+ You've reached your weekly limit+ </h2>+ <p className="text-sm text-muted-foreground">+ {wordsUsed.toLocaleString()} of {limit.toLocaleString()} words used.+ <br />+ Your transcription was saved and pasted.+ </p>+ </div>++ <div className="space-y-2 pt-2">+ <OptionCard+ title="Upgrade to Pro"+ description="Unlimited transcriptions. $9/month."+ onClick={() => {+ usage?.openCheckout();+ }}+ highlighted+ />+ <OptionCard+ title="Use your own API key"+ description="Bring your own key for unlimited use."+ onClick={() => {+ localStorage.setItem("cloudTranscriptionMode", "byok");+ onOpenChange(false);+ }}+ />+ <OptionCard+ title="Switch to local"+ description="Offline transcription. No limits."+ onClick={() => {+ localStorage.setItem("useLocalWhisper", "true");+ onOpenChange(false);+ }}+ />+ </div>++ <p className="text-xs text-muted-foreground/60 text-center">Rolling weekly limit</p>+ </DialogContent>+ </Dialog>+ );+}++function OptionCard({+ title,+ description,+ onClick,+ highlighted = false,+}: {+ title: string;+ description: string;+ onClick: () => void;+ highlighted?: boolean;+}) {+ return (+ <button+ onClick={onClick}+ className={`w-full text-left p-4 rounded-lg border transition-shadow duration-150 hover:shadow-md flex items-center justify-between cursor-pointer ${+ highlighted+ ? "bg-primary/5 dark:bg-primary/10 border-primary/20 dark:border-primary/15"+ : "bg-muted/50 dark:bg-surface-2 border-border dark:border-border-subtle hover:border-border-hover"+ }`}+ >+ <div>+ <div className="font-medium text-foreground">{title}</div>+ <div className="text-sm text-muted-foreground">{description}</div>+ </div>+ <ChevronRight className="h-4 w-4 text-muted-foreground/60 shrink-0" />+ </button>+ );+}diff --git a/src/components/ui/HotkeyGuidanceAccordion.tsx b/src/components/ui/HotkeyGuidanceAccordion.tsxnew file mode 100644index 000000000..0fe44ca38--- /dev/null+++ b/src/components/ui/HotkeyGuidanceAccordion.tsx@@ -0,0 +1,153 @@+import React, { useState } from "react";+import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "./accordion";+import {+ VALIDATION_RULES,+ getRecommendedPatterns,+ getReservedShortcuts,+ getValidExamples,+ type Platform,+} from "../../utils/hotkeyValidator";+import { formatHotkeyLabelForPlatform } from "../../utils/hotkeys";++type AccordionPlatform = "macos" | "windows" | "linux";++const PLATFORM_MAP: Record<AccordionPlatform, Platform> = {+ macos: "darwin",+ windows: "win32",+ linux: "linux",+};++const PLATFORM_LABELS: Record<AccordionPlatform, string> = {+ macos: "macOS",+ windows: "Windows",+ linux: "Linux",+};++interface HotkeyGuidanceAccordionProps {+ defaultValue?: AccordionPlatform;+ className?: string;+}++export function HotkeyGuidanceAccordion({+ defaultValue,+ className = "",+}: HotkeyGuidanceAccordionProps) {+ const [showAll, setShowAll] = useState<Record<AccordionPlatform, boolean>>({+ macos: false,+ windows: false,+ linux: false,+ });++ const renderReserved = (platformKey: AccordionPlatform) => {+ const platform = PLATFORM_MAP[platformKey];+ const reserved = getReservedShortcuts(platform);+ const formatted = reserved.map((shortcut) => formatHotkeyLabelForPlatform(shortcut, platform));+ const unique = Array.from(new Set(formatted));+ const displayCount = 8;+ const visible = showAll[platformKey] ? unique : unique.slice(0, displayCount);+ const hasMore = unique.length > displayCount;++ return (+ <div className="space-y-2">+ <p className="text-xs text-gray-500">+ These shortcuts are blocked because they are commonly used by the system.+ </p>+ <ul className="flex flex-wrap gap-2">+ {visible.map((shortcut) => (+ <li key={`${platformKey}-${shortcut}`}>+ <kbd className="px-2 py-1 text-xs font-mono bg-gray-100 border border-gray-200 rounded">+ {shortcut}+ </kbd>+ </li>+ ))}+ </ul>+ {hasMore && (+ <button+ type="button"+ onClick={() =>+ setShowAll((prev) => ({+ ...prev,+ [platformKey]: !prev[platformKey],+ }))+ }+ className="text-xs text-indigo-600 hover:text-indigo-700"+ >+ {showAll[platformKey] ? "Show fewer" : "Show all"}+ </button>+ )}+ </div>+ );+ };++ const renderSection = (platformKey: AccordionPlatform) => {+ const platform = PLATFORM_MAP[platformKey];+ const recommended = getRecommendedPatterns(platform);+ const examples = getValidExamples(platform);+ const formattedExamples = examples.map((example) =>+ formatHotkeyLabelForPlatform(example, platform)+ );++ return (+ <AccordionItem value={platformKey}>+ <AccordionTrigger>{PLATFORM_LABELS[platformKey]}</AccordionTrigger>+ <AccordionContent>+ <div className="space-y-4">+ <div>+ <h4 className="text-sm font-semibold text-gray-800 mb-2">Recommended shortcuts</h4>+ <ul className="space-y-1 text-sm text-gray-700">+ {recommended.map((pattern) => (+ <li key={`${platformKey}-${pattern}`}>{pattern}</li>+ ))}+ </ul>+ </div>++ <div>+ <h4 className="text-sm font-semibold text-gray-800 mb-2">Shortcut rules</h4>+ <ul className="space-y-1 text-sm text-gray-700">+ {VALIDATION_RULES.map((rule) => (+ <li key={`${platformKey}-${rule}`}>{rule}</li>+ ))}+ </ul>+ </div>++ <div>+ <h4 className="text-sm font-semibold text-gray-800 mb-2">Blocked shortcuts</h4>+ {renderReserved(platformKey)}+ </div>++ <div>+ <h4 className="text-sm font-semibold text-gray-800 mb-2">Valid examples</h4>+ <ul className="flex flex-wrap gap-2">+ {formattedExamples.map((example) => (+ <li key={`${platformKey}-${example}`}>+ <kbd className="px-2 py-1 text-xs font-mono bg-gray-100 border border-gray-200 rounded">+ {example}+ </kbd>+ </li>+ ))}+ </ul>+ </div>+ </div>+ </AccordionContent>+ </AccordionItem>+ );+ };++ return (+ <div className={`border border-gray-200 rounded-xl bg-gray-50 p-4 ${className}`}>+ <div className="mb-3">+ <h3 className="text-sm font-semibold text-gray-900">Shortcut Guide</h3>+ <p className="text-xs text-gray-600">+ Use these platform rules to choose a shortcut that won’t conflict with your system.+ </p>+ </div>+ <Accordion type="single" collapsible defaultValue={defaultValue}>+ {renderSection("macos")}+ {renderSection("windows")}+ {renderSection("linux")}+ </Accordion>+ </div>+ );+}++export default HotkeyGuidanceAccordion;diff --git a/src/components/ui/HotkeyInput.tsx b/src/components/ui/HotkeyInput.tsxindex 25f139aac..fa028f717 100644--- a/src/components/ui/HotkeyInput.tsx+++ b/src/components/ui/HotkeyInput.tsx@@ -1,5 +1,7 @@import React, { useState, useCallback, useRef, useEffect } from "react";+import { AlertTriangle } from "lucide-react";import { formatHotkeyLabel } from "../../utils/hotkeys";+import { getPlatform } from "../../utils/platform";const CODE_TO_KEY: Record<string, string> = {Backquote: "`",@@ -143,6 +145,7 @@ export interface HotkeyInputProps {onBlur?: () => void;disabled?: boolean;autoFocus?: boolean;+ validate?: (hotkey: string) => string | null | undefined;}export function mapKeyboardEventToHotkey(e: KeyboardEvent): string | null {@@ -155,18 +158,20 @@ export function mapKeyboardEventToHotkey(e: KeyboardEvent): string | null {return null;}+ const platform = getPlatform();const modifiers: string[] = [];- if (e.ctrlKey || e.metaKey) {- modifiers.push("CommandOrControl");- }- if (e.altKey) {- modifiers.push("Alt");- }- if (e.shiftKey) {- modifiers.push("Shift");+ if (platform === "darwin") {+ if (e.ctrlKey) modifiers.push("Control");+ if (e.metaKey) modifiers.push("Command");+ } else {+ if (e.ctrlKey) modifiers.push("Control");+ if (e.metaKey) modifiers.push("Super");}+ if (e.altKey) modifiers.push("Alt");+ if (e.shiftKey) modifiers.push("Shift");+return modifiers.length > 0 ? [...modifiers, baseKey].join("+") : baseKey;}@@ -181,12 +186,110 @@ export function HotkeyInput({disabled = false,autoFocus = false,variant = "default",+ validate,}: HotkeyInputProps & HotkeyInputVariant) {const [isCapturing, setIsCapturing] = useState(false);const [activeModifiers, setActiveModifiers] = useState<Set<string>>(new Set());+ const [validationWarning, setValidationWarning] = useState<string | null>(null);+ const [isFnHeld, setIsFnHeld] = useState(false);const containerRef = useRef<HTMLDivElement>(null);const lastCapturedHotkeyRef = useRef<string | null>(null);- const isMac = typeof navigator !== "undefined" && /Mac|Darwin/.test(navigator.platform);+ const keyDownTimeRef = useRef<number>(0);+ const warningTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const fnHeldRef = useRef(false);+ const fnCapturedKeyRef = useRef(false);+ const heldModifiersRef = useRef<{+ ctrl: boolean;+ meta: boolean;+ alt: boolean;+ shift: boolean;+ }>({ ctrl: false, meta: false, alt: false, shift: false });+ const modifierCodesRef = useRef<{+ ctrl?: string;+ meta?: string;+ alt?: string;+ shift?: string;+ }>({});+ const platform = getPlatform();+ const isMac = platform === "darwin";+ const isWindows = platform === "win32";++ const MODIFIER_HOLD_THRESHOLD_MS = 200;++ const buildModifierOnlyHotkey = useCallback(+ (+ modifiers: { ctrl: boolean; meta: boolean; alt: boolean; shift: boolean },+ codes: { ctrl?: string; meta?: string; alt?: string; shift?: string }+ ): string | null => {+ // Check for right-side single modifier first+ const rightSidePressed: string[] = [];+ if (codes.ctrl === "ControlRight") rightSidePressed.push("RightControl");+ if (codes.meta === "MetaRight") rightSidePressed.push(isMac ? "RightCommand" : "RightSuper");+ if (codes.alt === "AltRight") rightSidePressed.push(isMac ? "RightOption" : "RightAlt");+ if (codes.shift === "ShiftRight") rightSidePressed.push("RightShift");++ // If exactly one right-side modifier, allow it as single-key hotkey+ if (rightSidePressed.length === 1) {+ const activeCount = [modifiers.ctrl, modifiers.meta, modifiers.alt, modifiers.shift].filter(+ Boolean+ ).length;+ if (activeCount === 1) {+ return rightSidePressed[0];+ }+ }++ // Otherwise require 2+ modifiers (existing logic)+ const parts: string[] = [];+ if (modifiers.ctrl) parts.push("Control");+ if (modifiers.meta) parts.push(isMac ? "Command" : "Super");+ if (modifiers.alt) parts.push("Alt");+ if (modifiers.shift) parts.push("Shift");++ if (parts.length >= 2) {+ return parts.join("+");+ }+ return null;+ },+ [isMac]+ );++ const clearFnHeld = useCallback(() => {+ setIsFnHeld(false);+ fnHeldRef.current = false;+ fnCapturedKeyRef.current = false;+ }, []);++ const finalizeCapture = useCallback(+ (hotkey: string) => {+ if (warningTimeoutRef.current) {+ clearTimeout(warningTimeoutRef.current);+ warningTimeoutRef.current = null;+ }++ if (validate) {+ const errorMsg = validate(hotkey);+ if (errorMsg) {+ setValidationWarning(errorMsg);+ warningTimeoutRef.current = setTimeout(() => setValidationWarning(null), 4000);+ heldModifiersRef.current = { ctrl: false, meta: false, alt: false, shift: false };+ modifierCodesRef.current = {};+ setActiveModifiers(new Set());+ keyDownTimeRef.current = 0;+ clearFnHeld();+ return;+ }+ }++ setValidationWarning(null);+ lastCapturedHotkeyRef.current = hotkey;+ onChange(hotkey);+ setIsCapturing(false);+ setActiveModifiers(new Set());+ clearFnHeld();+ containerRef.current?.blur();+ },+ [validate, onChange, clearFnHeld]+ );const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {@@ -194,42 +297,121 @@ export function HotkeyInput({e.preventDefault();e.stopPropagation();+ // Track held modifiers for modifier-only capture+ heldModifiersRef.current = {+ ctrl: e.ctrlKey,+ meta: e.metaKey,+ alt: e.altKey,+ shift: e.shiftKey,+ };++ // Track which specific keys are pressed (for left/right detection)+ const code = e.nativeEvent.code;+ if (code === "ControlLeft" || code === "ControlRight") {+ modifierCodesRef.current.ctrl = code;+ } else if (code === "MetaLeft" || code === "MetaRight") {+ modifierCodesRef.current.meta = code;+ } else if (code === "AltLeft" || code === "AltRight") {+ modifierCodesRef.current.alt = code;+ } else if (code === "ShiftLeft" || code === "ShiftRight") {+ modifierCodesRef.current.shift = code;+ }++ // Track when first pressed (for hold detection)+ if (keyDownTimeRef.current === 0) {+ keyDownTimeRef.current = Date.now();+ }+const mods = new Set<string>();- if (e.ctrlKey || e.metaKey) mods.add(isMac ? "Cmd" : "Ctrl");+ if (isMac) {+ if (e.metaKey) mods.add("Cmd");+ if (e.ctrlKey) mods.add("Ctrl");+ } else {+ if (e.ctrlKey) mods.add("Ctrl");+ if (e.metaKey) mods.add(isWindows ? "Win" : "Super");+ }if (e.altKey) mods.add(isMac ? "Option" : "Alt");if (e.shiftKey) mods.add("Shift");+ if (fnHeldRef.current) mods.add("Fn");setActiveModifiers(mods);+ // Try to get non-modifier hotkey firstconst hotkey = mapKeyboardEventToHotkey(e.nativeEvent);if (hotkey) {- lastCapturedHotkeyRef.current = hotkey;- onChange(hotkey);- setIsCapturing(false);- setActiveModifiers(new Set());- containerRef.current?.blur();+ keyDownTimeRef.current = 0;+ if (fnHeldRef.current) {+ fnCapturedKeyRef.current = true;+ finalizeCapture(`Fn+${hotkey}`);+ } else {+ finalizeCapture(hotkey);+ }}+ // If no base key, modifiers are held - don't finalize yet},- [disabled, onChange, isMac]+ [disabled, isMac, isWindows, finalizeCapture]);- const handleKeyUp = useCallback(() => {- setActiveModifiers(new Set());- }, []);+ const handleKeyUp = useCallback(+ (e: React.KeyboardEvent<HTMLDivElement>) => {+ if (disabled) return;+ e.preventDefault();++ const wasHoldingModifiers =+ heldModifiersRef.current.ctrl ||+ heldModifiersRef.current.meta ||+ heldModifiersRef.current.alt ||+ heldModifiersRef.current.shift;++ let attempted = false;++ if (wasHoldingModifiers && MODIFIER_CODES.has(e.nativeEvent.code)) {+ const holdDuration = Date.now() - keyDownTimeRef.current;++ if (holdDuration >= MODIFIER_HOLD_THRESHOLD_MS) {+ const modifierHotkey = buildModifierOnlyHotkey(+ heldModifiersRef.current,+ modifierCodesRef.current+ );+ if (modifierHotkey) {+ attempted = true;+ if (fnHeldRef.current) {+ fnCapturedKeyRef.current = true;+ finalizeCapture(`Fn+${modifierHotkey}`);+ } else {+ finalizeCapture(modifierHotkey);+ }+ }+ }+ }++ if (!attempted) {+ heldModifiersRef.current = { ctrl: false, meta: false, alt: false, shift: false };+ modifierCodesRef.current = {};+ setActiveModifiers(fnHeldRef.current ? new Set(["Fn"]) : new Set());+ keyDownTimeRef.current = 0;+ }+ },+ [disabled, buildModifierOnlyHotkey, finalizeCapture]+ );const handleFocus = useCallback(() => {if (!disabled) {setIsCapturing(true);+ setValidationWarning(null);+ clearFnHeld();window.electronAPI?.setHotkeyListeningMode?.(true);}- }, [disabled]);+ }, [disabled, clearFnHeld]);const handleBlur = useCallback(() => {setIsCapturing(false);setActiveModifiers(new Set());+ setValidationWarning(null);+ clearFnHeld();window.electronAPI?.setHotkeyListeningMode?.(false, lastCapturedHotkeyRef.current);lastCapturedHotkeyRef.current = null;onBlur?.();- }, [onBlur]);+ }, [onBlur, clearFnHeld]);useEffect(() => {if (autoFocus && containerRef.current) {@@ -240,22 +422,35 @@ export function HotkeyInput({useEffect(() => {return () => {window.electronAPI?.setHotkeyListeningMode?.(false, null);+ if (warningTimeoutRef.current) clearTimeout(warningTimeoutRef.current);};}, []);useEffect(() => {if (!isCapturing || !isMac) return;- const dispose = window.electronAPI?.onGlobeKeyPressed?.(() => {- lastCapturedHotkeyRef.current = "GLOBE";- onChange("GLOBE");- setIsCapturing(false);- setActiveModifiers(new Set());- containerRef.current?.blur();+ const disposeDown = window.electronAPI?.onGlobeKeyPressed?.(() => {+ setValidationWarning(null);+ setIsFnHeld(true);+ fnHeldRef.current = true;+ fnCapturedKeyRef.current = false;+ setActiveModifiers((prev) => new Set([...prev, "Fn"]));+ });++ const disposeUp = window.electronAPI?.onGlobeKeyReleased?.(() => {+ if (fnHeldRef.current && !fnCapturedKeyRef.current) {+ finalizeCapture("GLOBE");+ }+ setIsFnHeld(false);+ fnHeldRef.current = false;+ fnCapturedKeyRef.current = false;});- return () => dispose?.();- }, [isCapturing, isMac, onChange]);+ return () => {+ disposeDown?.();+ disposeUp?.();+ };+ }, [isCapturing, isMac, finalizeCapture]);const displayValue = formatHotkeyLabel(value);const isGlobe = value === "GLOBE";@@ -274,15 +469,15 @@ export function HotkeyInput({onFocus={handleFocus}onBlur={handleBlur}className={`- relative group flex flex-col items-center justify-center py-5 px-6- rounded-lg border cursor-pointer select-none outline-none- transition-all duration-200+ relative group flex flex-col items-center justify-center py-4 px-5 min-h-28+ rounded-md border cursor-pointer select-none outline-none+ transition-all duration-150${disabled? "bg-muted/30 border-border cursor-not-allowed opacity-50": isCapturing- ? "bg-primary/5 border-primary/40"- : "bg-surface-1 border-border-subtle hover:border-border-hover hover:bg-surface-2"+ ? "bg-primary/5 border-primary/30 shadow-[0_0_0_2px_rgba(37,99,212,0.1)]"+ : "bg-surface-1 border-border hover:border-border-hover hover:bg-surface-2"}`}>@@ -294,22 +489,37 @@ export function HotkeyInput({<span className="text-xs font-medium text-primary">Listening...</span></div>{activeModifiers.size > 0 ? (- <div className="flex items-center gap-1.5">- {Array.from(activeModifiers).map((mod) => (- <kbd- key={mod}- className="px-3 py-1.5 bg-primary/10 border border-primary/20 rounded text-sm font-semibold text-primary"- >- {mod}- </kbd>- ))}- <span className="text-primary/50 text-sm font-medium">+</span>+ <div className="flex flex-col items-center gap-1.5">+ <div className="flex items-center gap-1.5">+ {Array.from(activeModifiers).map((mod) => (+ <kbd+ key={mod}+ className="px-2.5 py-1 bg-primary/10 border border-primary/20 rounded-sm text-xs font-semibold text-primary"+ >+ {mod}+ </kbd>+ ))}+ <span className="text-primary/50 text-sm font-medium">+</span>+ </div>+ {isFnHeld && (+ <span className="text-[10px] text-muted-foreground">+ Press a key to combine, or release for Globe+ </span>+ )}</div>) : (<span className="text-xs text-muted-foreground">{isMac ? "Press any key or ⌘⇧K" : "Press any key or Ctrl+Shift+K"}</span>)}+ {validationWarning && (+ <div className="flex items-center gap-1.5 mt-2 px-3 py-1.5 rounded-md bg-warning/8 border border-warning/20 dark:bg-warning/12 dark:border-warning/25">+ <AlertTriangle className="w-3 h-3 text-warning shrink-0" />+ <span className="text-[11px] text-warning dark:text-amber-400">+ {validationWarning}+ </span>+ </div>+ )}</div>) : value ? (/* Has value: show the hotkey prominently */@@ -321,17 +531,17 @@ export function HotkeyInput({{i > 0 && (<span className="text-muted-foreground/40 text-lg font-light">+</span>)}- <kbd className="px-3.5 py-2 bg-surface-raised border border-border-subtle rounded text-base font-semibold text-foreground shadow-sm">+ <kbd className="px-3 py-1.5 bg-surface-raised border border-border rounded-sm text-sm font-semibold text-foreground shadow-sm">{part}</kbd></React.Fragment>))) : isGlobe ? (- <kbd className="px-4 py-2 bg-surface-raised border border-border-subtle rounded text-xl shadow-sm">+ <kbd className="px-3 py-1.5 bg-surface-raised border border-border rounded-sm text-lg shadow-sm">🌐</kbd>) : (- <kbd className="px-4 py-2 bg-surface-raised border border-border-subtle rounded text-base font-bold text-foreground shadow-sm">+ <kbd className="px-3 py-1.5 bg-surface-raised border border-border rounded-sm text-sm font-semibold text-foreground shadow-sm">{displayValue}</kbd>)}@@ -362,14 +572,14 @@ export function HotkeyInput({onFocus={handleFocus}onBlur={handleBlur}className={`- relative overflow-hidden rounded-lg border- transition-all duration-200 cursor-pointer select-none focus:outline-none+ relative overflow-hidden rounded-md border+ transition-all duration-150 cursor-pointer select-none focus:outline-none${disabled? "bg-muted/30 border-border cursor-not-allowed opacity-50": isCapturing- ? "bg-primary/8 border-primary/50 shadow-[0_0_0_2px_rgba(37,99,212,0.15)]"- : "bg-surface-1 border-border-subtle hover:border-border-hover hover:bg-surface-2"+ ? "bg-primary/5 border-primary/30 shadow-[0_0_0_2px_rgba(37,99,212,0.1)]"+ : "bg-surface-1 border-border hover:border-border-hover hover:bg-surface-2"}`}>@@ -379,39 +589,51 @@ export function HotkeyInput({<div className="px-4 py-3">{isCapturing ? (- <div className="flex items-center justify-center gap-3">- <div className="flex items-center gap-1.5">- <div className="w-1.5 h-1.5 bg-primary rounded-full animate-pulse" />- <span className="text-xs font-medium text-muted-foreground">Recording</span>+ <>+ <div className="flex items-center justify-center gap-3">+ <div className="flex items-center gap-1.5">+ <div className="w-1.5 h-1.5 bg-primary rounded-full animate-pulse" />+ <span className="text-xs font-medium text-muted-foreground">Recording</span>+ </div>+ {activeModifiers.size > 0 ? (+ <div className="flex items-center gap-1">+ {Array.from(activeModifiers).map((mod) => (+ <kbd+ key={mod}+ className="px-2 py-0.5 bg-primary/10 border border-primary/20 rounded-sm text-[11px] font-semibold text-primary"+ >+ {mod}+ </kbd>+ ))}+ <span className="text-primary/40 text-[11px]">+ {isFnHeld ? "+ key or release for Globe" : "+ key"}+ </span>+ </div>+ ) : (+ <span className="text-[11px] text-muted-foreground">+ {isMac ? "Try ⌘⇧K" : "Try Ctrl+Shift+K"}+ </span>+ )}</div>- {activeModifiers.size > 0 ? (- <div className="flex items-center gap-1">- {Array.from(activeModifiers).map((mod) => (- <kbd- key={mod}- className="px-2 py-1 bg-primary/15 border border-primary/30 rounded text-xs font-semibold text-primary"- >- {mod}- </kbd>- ))}- <span className="text-primary/40 text-xs">+ key</span>+ {validationWarning && (+ <div className="flex items-center gap-1.5 mt-1.5 px-3 py-1.5 rounded-md bg-warning/8 border border-warning/20 dark:bg-warning/12 dark:border-warning/25">+ <AlertTriangle className="w-3 h-3 text-warning shrink-0" />+ <span className="text-[11px] text-warning dark:text-amber-400">+ {validationWarning}+ </span></div>- ) : (- <span className="text-xs text-muted-foreground">- {isMac ? "Try ⌘⇧K" : "Try Ctrl+Shift+K"}- </span>)}- </div>+ </>) : value ? (<div className="flex items-center justify-between">- <span className="text-xs font-medium text-muted-foreground">Hotkey</span>+ <span className="text-[11px] font-medium text-muted-foreground">Hotkey</span><div className="flex items-center gap-2">{hotkeyParts.length > 0 ? (<div className="flex items-center gap-1">{hotkeyParts.map((part, i) => (<React.Fragment key={part}>- {i > 0 && <span className="text-muted-foreground/30 text-xs">+</span>}- <kbd className="px-2 py-1 bg-surface-raised border border-border-subtle rounded text-sm font-semibold text-foreground">+ {i > 0 && <span className="text-muted-foreground/30 text-[10px]">+</span>}+ <kbd className="px-2 py-0.5 bg-surface-raised border border-border rounded-sm text-xs font-semibold text-foreground">{part}</kbd></React.Fragment>@@ -419,17 +641,17 @@ export function HotkeyInput({</div>) : isGlobe ? (<div className="flex items-center gap-1.5">- <kbd className="px-2 py-1 bg-surface-raised border border-border-subtle rounded text-lg">+ <kbd className="px-2 py-0.5 bg-surface-raised border border-border rounded-sm text-base">🌐</kbd>- <span className="text-xs text-muted-foreground">Globe</span>+ <span className="text-[11px] text-muted-foreground">Globe</span></div>) : (- <kbd className="px-3 py-1.5 bg-surface-raised border border-border-subtle rounded text-sm font-bold text-foreground">+ <kbd className="px-2.5 py-1 bg-surface-raised border border-border rounded-sm text-xs font-semibold text-foreground">{displayValue}</kbd>)}- <span className="text-[10px] text-muted-foreground/60">click to change</span>+ <span className="text-[10px] text-muted-foreground/50">click to change</span></div></div>) : (diff --git a/src/components/ui/LanguageSelector.tsx b/src/components/ui/LanguageSelector.tsxindex fbc8d3c18..91baecb19 100644--- a/src/components/ui/LanguageSelector.tsx+++ b/src/components/ui/LanguageSelector.tsx@@ -1,6 +1,13 @@import React, { useState, useRef, useEffect } from "react";+import { createPortal } from "react-dom";import { ChevronDown, Search, X, Check } from "lucide-react";-import { LANGUAGE_OPTIONS, getLanguageLabel } from "../../utils/languages";+import registry from "../../config/languageRegistry.json";++const LANGUAGE_OPTIONS = registry.languages.map(({ code, label, flag }) => ({+ value: code,+ label,+ flag,+}));interface LanguageSelectorProps {value: string;@@ -16,7 +23,9 @@ export default function LanguageSelector({const [isOpen, setIsOpen] = useState(false);const [searchQuery, setSearchQuery] = useState("");const [highlightedIndex, setHighlightedIndex] = useState(0);+ const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });const dropdownRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);const searchInputRef = useRef<HTMLInputElement>(null);const filteredLanguages = LANGUAGE_OPTIONS.filter(@@ -30,8 +39,19 @@ export default function LanguageSelector({}, [searchQuery]);useEffect(() => {- if (isOpen && searchInputRef.current) {- searchInputRef.current.focus();+ if (isOpen) {+ if (searchInputRef.current) {+ searchInputRef.current.focus();+ }+ // Calculate dropdown position+ if (triggerRef.current) {+ const rect = triggerRef.current.getBoundingClientRect();+ setDropdownPosition({+ top: rect.bottom + 4, // 4px gap (mt-1)+ left: rect.left,+ width: rect.width,+ });+ }}}, [isOpen]);useEffect(() => {@@ -92,79 +112,123 @@ export default function LanguageSelector({return (<div className={`relative ${className}`} ref={dropdownRef}>+ {/* Trigger button - premium, tight, tactile macOS-style */}<button+ ref={triggerRef}type="button"onClick={() => setIsOpen(!isOpen)}onKeyDown={handleKeyDown}- className={`w-full flex items-center justify-between px-3 py-2 border rounded-lg bg-white/5 dark:bg-white/3 text-left transition-all duration-200 ${- isOpen- ? "border-primary/50 ring-1 ring-primary/20 bg-white/8"- : "border-white/10 dark:border-white/5 hover:border-white/20 hover:bg-white/8"- }`}+ className={`+ group relative w-full flex items-center justify-between gap-2+ h-9 px-3 text-left+ rounded text-sm font-medium+ border shadow-sm backdrop-blur-sm+ transition-all duration-200 ease-out+ focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-1+ ${+ isOpen+ ? "border-border-active bg-surface-2/90 shadow ring-1 ring-primary/20"+ : "border-border/70 bg-surface-1/80 hover:border-border-hover hover:bg-surface-2/70 hover:shadow active:scale-[0.985]"+ }+ `}aria-haspopup="listbox"aria-expanded={isOpen}>- <span className="truncate text-sm text-foreground">{getLanguageLabel(value)}</span>+ <span className="truncate text-foreground">+ <span className="mr-1.5">+ {LANGUAGE_OPTIONS.find((l) => l.value === value)?.flag ?? "\uD83C\uDF10"}+ </span>+ {LANGUAGE_OPTIONS.find((l) => l.value === value)?.label ?? value}+ </span><ChevronDown- className={`w-3.5 h-3.5 text-muted-foreground transition-transform duration-200 ${- isOpen ? "rotate-180" : ""+ className={`w-3.5 h-3.5 shrink-0 text-muted-foreground transition-all duration-200 ${+ isOpen ? "rotate-180 text-primary" : "group-hover:text-foreground"}`}/></button>- {isOpen && (- <div className="absolute z-50 w-full mt-1.5 bg-popover/95 backdrop-blur-xl border border-white/10 dark:border-white/5 rounded-xl shadow-xl max-h-60 overflow-hidden">- <div className="p-2 border-b border-white/5">- <div className="relative">- <Search className="absolute left-2.5 top-1/2 transform -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />- <input- ref={searchInputRef}- type="text"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- onKeyDown={handleKeyDown}- placeholder="Search..."- className="w-full pl-8 pr-7 py-1.5 text-sm bg-white/5 dark:bg-white/3 text-foreground border border-white/10 rounded-lg focus:border-primary/50 focus:ring-1 focus:ring-primary/20 focus:outline-none placeholder:text-muted-foreground/50"- />- {searchQuery && (- <button- onClick={clearSearch}- className="absolute right-2.5 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"- >- <X className="w-3.5 h-3.5" />- </button>- )}- </div>- </div>- <div className="max-h-44 overflow-y-auto">- {filteredLanguages.length === 0 ? (- <div className="px-3 py-2 text-sm text-muted-foreground">No languages found</div>- ) : (- <div role="listbox" className="p-1">- {filteredLanguages.map((language, index) => (+ {/* Dropdown - ultra-premium glassmorphic panel (rendered via portal) */}+ {isOpen &&+ createPortal(+ <div+ ref={dropdownRef}+ style={{+ position: "fixed",+ top: `${dropdownPosition.top}px`,+ left: `${dropdownPosition.left}px`,+ width: `${dropdownPosition.width}px`,+ }}+ className="z-9999 bg-popover/95 backdrop-blur-xl border border-border/70 rounded shadow-xl overflow-hidden"+ >+ {/* Inline search - minimal, borderless, integrated */}+ <div className="px-2 pt-2 pb-1.5 border-b border-border/50">+ <div className="relative">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground pointer-events-none" />+ <input+ ref={searchInputRef}+ type="text"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ placeholder="Search..."+ className="w-full h-7 pl-7 pr-6 text-xs bg-transparent text-foreground border-0 focus:outline-none placeholder:text-muted-foreground/50"+ />+ {searchQuery && (<button- key={language.value}type="button"- onClick={() => handleSelect(language.value)}- className={`w-full px-2.5 py-1.5 text-left text-sm rounded-md transition-colors ${- language.value === value- ? "bg-primary/15 text-primary font-medium"- : "text-foreground hover:bg-white/5"- } ${index === highlightedIndex && language.value !== value ? "bg-white/5" : ""}`}- role="option"- aria-selected={language.value === value}+ onClick={clearSearch}+ className="absolute right-1.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors rounded p-0.5 hover:bg-muted/50">- <span className="flex items-center justify-between">- {language.label}- {language.value === value && <Check className="w-3.5 h-3.5" />}- </span>+ <X className="w-3 h-3" /></button>- ))}+ )}</div>- )}- </div>- </div>- )}+ </div>++ {/* Language list - tight, premium with smart scrollbar */}+ <div className="max-h-48 overflow-y-auto px-1 pb-1 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-border">+ {filteredLanguages.length === 0 ? (+ <div className="px-2.5 py-2 text-xs text-muted-foreground">No languages found</div>+ ) : (+ <div role="listbox" className="space-y-0.5 pt-1">+ {filteredLanguages.map((language, index) => {+ const isSelected = language.value === value;+ const isHighlighted = index === highlightedIndex;++ return (+ <button+ key={language.value}+ type="button"+ onClick={() => handleSelect(language.value)}+ className={`+ group w-full flex items-center justify-between gap-2+ h-7 px-2.5 text-left text-xs font-medium+ rounded transition-all duration-150 ease-out+ ${+ isSelected+ ? "bg-primary/15 text-primary shadow-sm"+ : isHighlighted+ ? "bg-muted/70 text-foreground"+ : "text-foreground hover:bg-muted/50 active:scale-[0.98]"+ }+ `}+ role="option"+ aria-selected={isSelected}+ >+ <span className="truncate">+ <span className="mr-1.5">{language.flag}</span>+ {language.label}+ </span>+ {isSelected && <Check className="w-3 h-3 shrink-0" />}+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>,+ document.body+ )}</div>);}diff --git a/src/components/ui/MarkdownRenderer.tsx b/src/components/ui/MarkdownRenderer.tsxindex 8421ddc2f..4b8e3577a 100644--- a/src/components/ui/MarkdownRenderer.tsx+++ b/src/components/ui/MarkdownRenderer.tsx@@ -29,7 +29,7 @@ export function MarkdownRenderer({ content, className }: MarkdownRendererProps)href={href}target="_blank"rel="noopener noreferrer"- className="underline hover:opacity-80"+ className="text-link underline decoration-link/30 hover:decoration-link/60 transition-colors">{children}</a>diff --git a/src/components/ui/ModelCardList.tsx b/src/components/ui/ModelCardList.tsxindex 7ae844a12..5a081f984 100644--- a/src/components/ui/ModelCardList.tsx+++ b/src/components/ui/ModelCardList.tsx@@ -77,7 +77,7 @@ export default function ModelCardList({}return (- <div className={`space-y-1 ${className}`}>+ <div className={`space-y-0.5 ${className}`}>{models.map((model) => {const isSelected = selectedModel === model.value;const isDownloaded = model.isDownloaded;@@ -116,18 +116,26 @@ export default function ModelCardList({<divkey={model.value}onClick={handleCardClick}- className={`relative w-full p-2.5 pl-3 rounded-lg border text-left transition-all duration-200 group overflow-hidden ${+ className={`relative w-full p-2 pl-2.5 rounded-md border text-left transition-all duration-200 group overflow-hidden ${isSelected ? styles.selected : styles.default} ${!isLocalMode || (isDownloaded && !isSelected) ? "cursor-pointer" : ""}`}>{/* Left accent bar for selected */}{isSelected && (- <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-primary rounded-l-lg" />+ <div className="absolute left-0 top-0 bottom-0 w-1 bg-linear-to-b from-primary via-primary to-primary/80 rounded-l-md" />)}- <div className="flex items-center gap-2">+ <div className="flex items-center gap-1.5">{/* Status dot with LED glow */}- <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${getStatusDotClass()}`} />+ <div+ className={`w-1.5 h-1.5 rounded-full shrink-0 ${getStatusDotClass()} ${+ isSelected && isDownloaded+ ? "animate-[pulse-glow_2s_ease-in-out_infinite]"+ : isDownloading+ ? "animate-[spinner-rotate_1s_linear_infinite]"+ : ""+ }`}+ />{/* Icon */}{model.icon ? (@@ -142,9 +150,11 @@ export default function ModelCardList({)}{/* Model info - inline */}- <span className="text-sm font-medium text-foreground truncate">{model.label}</span>+ <span className="text-sm font-semibold text-foreground truncate tracking-tight">+ {model.label}+ </span>{model.description && (- <span className="text-[10px] text-muted-foreground/60 tabular-nums shrink-0">+ <span className="text-[11px] text-muted-foreground/50 tabular-nums shrink-0">{model.description}</span>)}@@ -176,7 +186,7 @@ export default function ModelCardList({}}size="sm"variant="ghost"- className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"+ className="h-6 w-6 p-0 text-muted-foreground/40 hover:text-destructive opacity-0 group-hover:opacity-100 transition-all active:scale-95"><Trash2 size={12} /></Button>diff --git a/src/components/ui/PermissionCard.tsx b/src/components/ui/PermissionCard.tsxindex bf5b658ee..87c3f1f7e 100644--- a/src/components/ui/PermissionCard.tsx+++ b/src/components/ui/PermissionCard.tsx@@ -24,50 +24,45 @@ export default function PermissionCard({return (<divclassName={cn(- "group relative rounded-lg p-2.5 transition-all duration-150",+ "group relative rounded-md p-3 transition-all duration-150","border",granted- ? "bg-success/5 border-success/15 dark:bg-success/8 dark:border-success/20"- : "bg-surface-1 border-border-subtle hover:bg-surface-2 hover:border-border-hover"+ ? "bg-success/5 border-success/20 dark:bg-success/5 dark:border-success/15"+ : "bg-surface-1 border-border hover:bg-surface-2 hover:border-border-hover")}>- <div className="flex items-center gap-2.5">+ <div className="flex items-center gap-3">{/* Icon container */}<divclassName={cn(- "w-7 h-7 rounded-md flex items-center justify-center shrink-0 transition-colors",- granted ? "bg-success/10" : "bg-primary/8 dark:bg-primary/10"+ "w-8 h-8 rounded-md flex items-center justify-center shrink-0 transition-all duration-150",+ granted+ ? "bg-success/10 dark:bg-success/15"+ : "bg-primary/10 dark:bg-primary/15 group-hover:bg-primary/15")}>{granted ? (- <Check className="w-3.5 h-3.5 text-success" strokeWidth={2.5} />+ <Check className="w-4 h-4 text-success" strokeWidth={2.5} />) : (- <Icon className="w-3.5 h-3.5 text-primary" />+ <Icon className="w-4 h-4 text-primary" />)}</div>{/* Content */}<div className="flex-1 min-w-0">- <div className="flex items-center gap-1.5">- <h3 className="text-[12px] font-medium text-foreground leading-tight">{title}</h3>- {granted && (- <span className="text-[9px] font-medium text-success/70 uppercase tracking-wider">- Granted- </span>- )}- </div>- <p className="text-[10px] text-muted-foreground/80 leading-snug mt-0.5">{description}</p>+ <h3 className="text-xs font-medium text-foreground">{title}</h3>+ <p className="text-[11px] text-muted-foreground leading-snug mt-0.5">{description}</p></div>{/* Actions - only when not granted */}{!granted && (- <div className="flex items-center gap-1 shrink-0">- <Button onClick={onRequest} size="sm" className="h-6 px-2.5 text-[10px]">+ <div className="flex items-center gap-1.5 shrink-0">+ <Button onClick={onRequest} size="sm" className="h-7 px-3 text-[11px]">{buttonText}</Button>{onOpenSettings && (- <Button onClick={onOpenSettings} size="sm" variant="outline" className="h-6 w-6 p-0">- <Settings className="w-3 h-3 text-foreground" />+ <Button onClick={onOpenSettings} size="sm" variant="ghost" className="h-7 w-7 p-0">+ <Settings className="w-3.5 h-3.5" /></Button>)}</div>diff --git a/src/components/ui/ProviderTabs.tsx b/src/components/ui/ProviderTabs.tsxindex e8b275157..e1638e859 100644--- a/src/components/ui/ProviderTabs.tsx+++ b/src/components/ui/ProviderTabs.tsx@@ -87,7 +87,7 @@ export function ProviderTabs({key={provider.id}data-tab-buttononClick={() => onSelect(provider.id)}- className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md font-medium text-xs transition-colors duration-150 ${+ className={`relative z-10 flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md font-medium text-xs transition-colors duration-150 ${scrollable ? "whitespace-nowrap" : ""} ${isSelected ? "text-foreground" : "text-muted-foreground hover:text-foreground"}`}>diff --git a/src/components/ui/StepProgress.tsx b/src/components/ui/StepProgress.tsxindex 8d9c285b0..db3515919 100644--- a/src/components/ui/StepProgress.tsx+++ b/src/components/ui/StepProgress.tsx@@ -14,7 +14,7 @@ interface StepProgressProps {export default function StepProgress({ steps, currentStep, className = "" }: StepProgressProps) {return (- <div className={`flex items-center justify-center gap-1 ${className}`}>+ <div className={`flex items-center justify-center gap-0.5 ${className}`}>{steps.map((step, index) => {const Icon = step.icon;const isActive = index === currentStep;@@ -23,36 +23,36 @@ export default function StepProgress({ steps, currentStep, className = "" }: Stereturn (<React.Fragment key={index}><div- className={`flex items-center gap-1.5 px-2 py-1 rounded-full transition-all duration-200 ${+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-md transition-all duration-150 ${isActive- ? "bg-primary/15 text-primary"+ ? "bg-primary/10 text-primary": isCompleted? "text-success"- : "text-muted-foreground/50"+ : "text-muted-foreground/40"}`}><div- className={`w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 transition-all duration-200 ${+ className={`w-4.5 h-4.5 rounded-md flex items-center justify-center shrink-0 transition-all duration-150 ${isActive- ? "bg-primary text-white shadow-sm"+ ? "bg-primary text-primary-foreground": isCompleted- ? "bg-success/20 text-success"- : "bg-white/5 text-muted-foreground/50"+ ? "bg-success/15 text-success"+ : "bg-muted text-muted-foreground/40"}`}>{isCompleted ? (- <Check className="w-3 h-3" strokeWidth={2.5} />+ <Check className="w-2.5 h-2.5" strokeWidth={3} />) : (- <Icon className="w-3 h-3" />+ <Icon className="w-2.5 h-2.5" />)}</div><span- className={`text-[11px] font-medium hidden md:block ${+ className={`text-[10px] font-medium hidden md:block tracking-wide ${isActive? "text-primary": isCompleted? "text-success"- : "text-muted-foreground/50"+ : "text-muted-foreground/40"}`}>{step.title}@@ -60,8 +60,8 @@ export default function StepProgress({ steps, currentStep, className = "" }: Ste</div>{index < steps.length - 1 && (<div- className={`w-4 h-px transition-colors duration-200 ${- isCompleted ? "bg-success/50" : "bg-white/10"+ className={`w-3 h-px mx-0.5 transition-colors duration-150 ${+ isCompleted ? "bg-success/40" : "bg-border"}`}/>)}diff --git a/src/components/ui/accordion.tsx b/src/components/ui/accordion.tsxnew file mode 100644index 000000000..15c924296--- /dev/null+++ b/src/components/ui/accordion.tsx@@ -0,0 +1,54 @@+import * as React from "react";+import * as AccordionPrimitive from "@radix-ui/react-accordion";+import { ChevronDown } from "lucide-react";+import { cn } from "../lib/utils";++const Accordion = AccordionPrimitive.Root;++const AccordionItem = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Item>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>+>(({ className, ...props }, ref) => (+ <AccordionPrimitive.Item+ ref={ref}+ className={cn("border-b border-gray-200", className)}+ {...props}+ />+));+AccordionItem.displayName = "AccordionItem";++const AccordionTrigger = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Trigger>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>+>(({ className, children, ...props }, ref) => (+ <AccordionPrimitive.Header className="flex">+ <AccordionPrimitive.Trigger+ ref={ref}+ className={cn(+ "flex flex-1 items-center justify-between py-3 text-sm font-semibold text-gray-800 transition-all hover:text-gray-900 [&[data-state=open]>svg]:rotate-180",+ className+ )}+ {...props}+ >+ {children}+ <ChevronDown className="h-4 w-4 shrink-0 text-gray-500 transition-transform duration-200" />+ </AccordionPrimitive.Trigger>+ </AccordionPrimitive.Header>+));+AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;++const AccordionContent = React.forwardRef<+ React.ElementRef<typeof AccordionPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>+>(({ className, children, ...props }, ref) => (+ <AccordionPrimitive.Content+ ref={ref}+ className="overflow-hidden text-sm text-gray-700 data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"+ {...props}+ >+ <div className={cn("pb-4 pt-2", className)}>{children}</div>+ </AccordionPrimitive.Content>+));+AccordionContent.displayName = AccordionPrimitive.Content.displayName;++export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };diff --git a/src/components/ui/alert.tsx b/src/components/ui/alert.tsxindex dc87abbc9..69a1e9016 100644--- a/src/components/ui/alert.tsx+++ b/src/components/ui/alert.tsx@@ -4,13 +4,14 @@ import { cva, type VariantProps } from "class-variance-authority";import { cn } from "../lib/utils";const alertVariants = cva(- "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",+ "relative w-full rounded-xl border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg~*]:pl-7",{variants: {variant: {- default: "bg-background text-foreground",- destructive:- "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",+ default: "bg-neutral-50 border-neutral-200 text-neutral-900 [&>svg]:text-neutral-600",+ destructive: "bg-red-50 border-red-200 text-red-900 [&>svg]:text-red-600",+ success: "bg-emerald-50 border-emerald-200 text-emerald-900 [&>svg]:text-emerald-600",+ warning: "bg-amber-50 border-amber-200 text-amber-900 [&>svg]:text-amber-600",},},defaultVariants: {@@ -31,7 +32,7 @@ const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<H({ className, ...props }, ref) => (<h5ref={ref}- className={cn("mb-1 font-medium leading-none tracking-tight", className)}+ className={cn("mb-1 font-medium leading-none tracking-tight text-inherit", className)}{...props}/>)@@ -42,7 +43,7 @@ const AlertDescription = React.forwardRef<HTMLParagraphElement,React.HTMLAttributes<HTMLParagraphElement>>(({ className, ...props }, ref) => (- <div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />+ <div ref={ref} className={cn("text-sm opacity-90 [&_p]:leading-relaxed", className)} {...props} />));AlertDescription.displayName = "AlertDescription";diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex 92182aae8..8fb814da2 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -7,63 +7,56 @@ import { cn } from "../lib/utils";const buttonVariants = cva(["inline-flex items-center justify-center gap-2 whitespace-nowrap",- "rounded-[6px] text-sm font-medium cursor-pointer select-none",- "transition-all duration-150 ease-out",- "outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 focus-visible:ring-offset-background",- "disabled:pointer-events-none disabled:opacity-40",+ "rounded text-sm font-medium cursor-pointer select-none",+ "transition-all duration-200 ease-out",+ "outline-none focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-1 focus-visible:ring-offset-background",+ "disabled:pointer-events-none disabled:opacity-50 disabled:cursor-not-allowed","[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 shrink-0",].join(" "),{variants: {variant: {- // Primary CTA — refined blue metallic+ // Primary CTA — ultra-premium with subtle depthdefault: [- "relative text-white font-semibold tracking-[0.01em]",- "bg-gradient-to-b from-[#4a8df0] to-[#2563d4]",- "border border-[#1e4fad]/70",- "shadow-[inset_0_1px_0_0_rgba(255,255,255,0.15),0_1px_2px_0_rgba(0,0,0,0.1),0_1px_3px_0_rgba(37,99,212,0.2)]",- "hover:from-[#5a9af5] hover:to-[#3574e0]",- "hover:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.2),0_2px_4px_0_rgba(0,0,0,0.12),0_2px_8px_0_rgba(37,99,212,0.25)]",- "active:from-[#3574e0] active:to-[#1e4fad] active:scale-[0.98]",- "active:shadow-[inset_0_2px_4px_0_rgba(0,0,0,0.15)]",+ "relative text-primary-foreground font-semibold tracking-[0.005em]",+ "bg-primary",+ "border border-primary/60",+ "shadow-sm",+ "hover:bg-primary/95 hover:shadow",+ "active:bg-primary/85 active:scale-[0.985]",+ "transition-all duration-200 ease-out",].join(" "),- // Success — emerald metallic+ // Success — uses design tokenssuccess: [- "relative text-white font-semibold tracking-[0.01em]",- "bg-gradient-to-b from-[#34d399] to-[#10b981]",- "border border-[#059669]/70",- "shadow-[inset_0_1px_0_0_rgba(255,255,255,0.15),0_1px_2px_0_rgba(0,0,0,0.1),0_1px_3px_0_rgba(16,185,129,0.2)]",- "hover:from-[#4ade80] hover:to-[#22c55e]",- "hover:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.2),0_2px_4px_0_rgba(0,0,0,0.12),0_2px_8px_0_rgba(16,185,129,0.25)]",- "active:from-[#22c55e] active:to-[#059669] active:scale-[0.98]",- "active:shadow-[inset_0_2px_4px_0_rgba(0,0,0,0.15)]",+ "relative text-success-foreground font-semibold tracking-[0.01em]",+ "bg-success",+ "border border-success/70",+ "shadow-sm",+ "hover:bg-success/90",+ "active:bg-success/80 active:scale-[0.98]",].join(" "),- // Destructive — red metallic+ // Destructive — uses design tokensdestructive: [- "relative text-white font-semibold tracking-[0.01em]",- "bg-gradient-to-b from-[#f87171] to-[#ef4444]",- "border border-[#dc2626]/70",- "shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),0_1px_2px_0_rgba(0,0,0,0.1),0_1px_3px_0_rgba(239,68,68,0.2)]",- "hover:from-[#fca5a5] hover:to-[#f87171]",- "hover:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.15),0_2px_4px_0_rgba(0,0,0,0.12),0_2px_8px_0_rgba(239,68,68,0.25)]",- "active:from-[#ef4444] active:to-[#dc2626] active:scale-[0.98]",- "active:shadow-[inset_0_2px_4px_0_rgba(0,0,0,0.15)]",+ "relative text-destructive-foreground font-semibold tracking-[0.01em]",+ "bg-destructive",+ "border border-destructive/70",+ "shadow-sm",+ "hover:bg-destructive/90",+ "active:bg-destructive/80 active:scale-[0.98]",].join(" "),- // Outline — uses design tokens+ // Outline — refined with subtle glassmorphismoutline: ["relative font-medium",- "text-foreground bg-muted/80",- "border border-border",- "shadow-sm backdrop-blur-sm",- "hover:bg-muted",- "active:scale-[0.98]",- // Dark mode overrides- "dark:bg-surface-3",- "dark:border-border-subtle",- "dark:hover:bg-surface-raised",+ "text-foreground bg-muted/70 backdrop-blur-sm",+ "border border-border/70",+ "shadow-sm",+ "hover:bg-muted hover:border-border-hover",+ "active:scale-[0.985]",+ "dark:bg-surface-raised/90 dark:border-border-hover dark:hover:bg-surface-raised",+ "transition-all duration-200 ease-out",].join(" "),// Secondary — uses design tokens@@ -73,10 +66,7 @@ const buttonVariants = cva("border border-border/50","hover:bg-muted","active:scale-[0.98]",- // Dark mode overrides- "dark:text-foreground/90 dark:bg-white/8",- "dark:border-white/5",- "dark:hover:bg-white/12",+ "dark:text-foreground/90 dark:bg-white/8 dark:border-white/5 dark:hover:bg-white/12",].join(" "),// Ghost — uses design tokens@@ -85,9 +75,7 @@ const buttonVariants = cva("text-foreground","hover:bg-muted","active:scale-[0.98]",- // Dark mode overrides- "dark:text-foreground/90",- "dark:hover:bg-white/8",+ "dark:text-foreground/90 dark:hover:bg-white/8",].join(" "),// Link — uses design tokens@@ -96,16 +84,25 @@ const buttonVariants = cva("text-primary","hover:text-primary/80 hover:underline","underline-offset-4",- // Dark mode overrides- "dark:text-primary",- "dark:hover:text-primary/80",+ ].join(" "),++ // Social button for auth flows - ultra-premium glassmorphism+ social: [+ "relative font-medium",+ "text-foreground bg-surface-1/80 backdrop-blur-xl",+ "border border-border/60",+ "shadow-sm gap-2",+ "hover:bg-surface-2/90 hover:border-border-hover hover:shadow",+ "active:scale-[0.985] active:shadow-sm",+ "dark:bg-surface-raised/80 dark:border-border-hover dark:hover:bg-surface-raised/95",+ "transition-all duration-200 ease-out",].join(" "),},size: {- default: "h-9 px-4 py-2",+ default: "h-10 px-4 py-2",sm: "h-8 px-3 text-xs gap-1.5",- lg: "h-10 px-5 text-sm",- icon: "size-9",+ lg: "h-12 px-6 text-sm",+ icon: "size-10",},},defaultVariants: {diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsxindex 45c6c7b13..2cc46f7ae 100644--- a/src/components/ui/card.tsx+++ b/src/components/ui/card.tsx@@ -7,9 +7,8 @@ const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElemen<divref={ref}className={cn(- "rounded-xl border bg-card text-card-foreground shadow-sm",- "dark:bg-card dark:border-border",- "dark:hover:border-border-hover",+ "rounded-lg border border-border bg-card text-card-foreground shadow-sm transition-all duration-150",+ "dark:bg-card dark:border-border-subtle dark:hover:border-border-hover",className)}{...props}@@ -29,7 +28,10 @@ const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HT({ className, ...props }, ref) => (<h3ref={ref}- className={cn("text-2xl font-semibold leading-none tracking-tight", className)}+ className={cn(+ "text-xl font-semibold leading-none tracking-tight text-neutral-900",+ className+ )}{...props}/>)@@ -40,7 +42,7 @@ const CardDescription = React.forwardRef<HTMLParagraphElement,React.HTMLAttributes<HTMLParagraphElement>>(({ className, ...props }, ref) => (- <p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />+ <p ref={ref} className={cn("text-sm text-neutral-500", className)} {...props} />));CardDescription.displayName = "CardDescription";diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsxindex 0eafb8ac3..db28e9afb 100644--- a/src/components/ui/dropdown-menu.tsx+++ b/src/components/ui/dropdown-menu.tsx@@ -61,7 +61,7 @@ const DropdownMenuContent = React.forwardRef<ref={ref}sideOffset={sideOffset}className={cn(- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ "z-50 min-w-[8rem] overflow-hidden rounded-xl border border-neutral-200 bg-white p-1.5 text-neutral-900 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",className)}{...props}@@ -79,7 +79,7 @@ const DropdownMenuItem = React.forwardRef<<DropdownMenuPrimitive.Itemref={ref}className={cn(- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",+ "relative flex cursor-pointer select-none items-center rounded-lg px-2.5 py-2 text-sm outline-none transition-colors focus:bg-neutral-100 data-[disabled]:pointer-events-none data-[disabled]:opacity-50",inset && "pl-8",className)}@@ -153,7 +153,7 @@ const DropdownMenuSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.Separatorref={ref}- className={cn("-mx-1 my-1 h-px bg-muted", className)}+ className={cn("-mx-1 my-1 h-px bg-neutral-200", className)}{...props}/>));diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsxindex 11862f901..fe10136f1 100644--- a/src/components/ui/input.tsx+++ b/src/components/ui/input.tsx@@ -8,8 +8,13 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {type={type}data-slot="input"className={cn(- "file:text-foreground placeholder:text-muted-foreground/50 selection:bg-primary selection:text-primary-foreground border-input flex h-9 w-full min-w-0 rounded-lg border bg-input px-3.5 py-2 text-sm shadow-none transition-all duration-200 outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",- "dark:bg-surface-1 dark:border-border-subtle",+ "flex h-10 w-full min-w-0 rounded border border-border/70 bg-input px-3 py-2 text-sm text-foreground shadow-none transition-all duration-200 outline-none",+ "placeholder:text-muted-foreground/40",+ "selection:bg-primary selection:text-primary-foreground",+ "file:text-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium",+ "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-muted",+ "dark:bg-surface-1 dark:border-border-subtle/50",+ "hover:border-border-hover","focus-visible:border-primary focus-visible:ring-2 focus-visible:ring-primary/10","dark:focus-visible:border-border-active dark:focus-visible:ring-ring/10","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsxindex a102c8c4e..3612044a0 100644--- a/src/components/ui/label.tsx+++ b/src/components/ui/label.tsx@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";import { cn } from "../lib/utils";const labelVariants = cva(- "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ "text-sm font-medium leading-none text-neutral-700 peer-disabled:cursor-not-allowed peer-disabled:opacity-50");const Label = React.forwardRef<diff --git a/src/components/ui/progress.tsx b/src/components/ui/progress.tsxindex 19619baa2..d09e43d41 100644--- a/src/components/ui/progress.tsx+++ b/src/components/ui/progress.tsx@@ -9,11 +9,14 @@ const Progress = React.forwardRef<>(({ className, value, ...props }, ref) => (<ProgressPrimitive.Rootref={ref}- className={cn("relative h-2 w-full overflow-hidden rounded-full bg-primary/20", className)}+ className={cn(+ "relative h-2 w-full overflow-hidden rounded-full bg-muted/60 dark:bg-muted/30",+ className+ )}{...props}><ProgressPrimitive.Indicator- className="h-full w-full flex-1 bg-primary transition-all"+ className="h-full w-full flex-1 bg-primary transition-all duration-300"style={{ transform: `translateX(-${100 - (value || 0)}%)` }}/></ProgressPrimitive.Root>diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsxindex 783576ed0..469d53054 100644--- a/src/components/ui/select.tsx+++ b/src/components/ui/select.tsx@@ -17,7 +17,11 @@ const SelectTrigger = React.forwardRef<<SelectPrimitive.Triggerref={ref}className={cn(- "flex h-10 w-full items-center justify-between rounded-xl border border-input bg-input px-3.5 py-2 text-sm shadow-none ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-[3px] focus:ring-primary/15 focus:border-primary disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",+ "flex h-10 w-full items-center justify-between rounded-xl border border-border bg-input px-3.5 py-2 text-sm text-foreground shadow-none ring-offset-background transition-all duration-200",+ "placeholder:text-muted-foreground",+ "[&>span]:line-clamp-1",+ "focus:outline-none focus:ring-[3px] focus:ring-primary/15 focus:border-primary",+ "disabled:cursor-not-allowed disabled:opacity-50","dark:bg-surface-1 dark:border-border-subtle","dark:focus:ring-ring/10 dark:focus:border-border-active",className@@ -26,7 +30,7 @@ const SelectTrigger = React.forwardRef<>{children}<SelectPrimitive.Icon asChild>- <ChevronDown className="h-4 w-4 opacity-50" />+ <ChevronDown className="h-4 w-4 text-neutral-400" /></SelectPrimitive.Icon></SelectPrimitive.Trigger>));@@ -68,9 +72,9 @@ const SelectContent = React.forwardRef<<SelectPrimitive.Contentref={ref}className={cn(- "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-xl border bg-popover text-popover-foreground shadow-xl",+ "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-xl border border-border/60 bg-popover text-popover-foreground shadow-xl","dark:bg-surface-3 dark:border-border-hover dark:shadow-elevated",- "border-border/60 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",position === "popper" &&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",classNamediff --git a/src/components/ui/skeleton.tsx b/src/components/ui/skeleton.tsxnew file mode 100644index 000000000..098e5540c--- /dev/null+++ b/src/components/ui/skeleton.tsx@@ -0,0 +1,7 @@+import { cn } from "../lib/utils";++function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {+ return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />;+}++export { Skeleton };diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsxindex 40f8f04ac..5b1be6320 100644--- a/src/components/ui/tabs.tsx+++ b/src/components/ui/tabs.tsx@@ -12,7 +12,7 @@ const TabsList = React.forwardRef<<TabsPrimitive.Listref={ref}className={cn(- "inline-flex h-9 items-center justify-center rounded-lg bg-muted dark:bg-surface-raised p-1 text-muted-foreground",+ "inline-flex h-10 items-center justify-center rounded-lg bg-muted dark:bg-surface-raised p-1 text-muted-foreground",className)}{...props}@@ -27,7 +27,10 @@ const TabsTrigger = React.forwardRef<<TabsPrimitive.Triggerref={ref}className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow",+ "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-all duration-200",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",+ "disabled:pointer-events-none disabled:opacity-50",+ "data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-sm",className)}{...props}@@ -42,7 +45,7 @@ const TabsContent = React.forwardRef<<TabsPrimitive.Contentref={ref}className={cn(- "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",+ "mt-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-300 focus-visible:ring-offset-2",className)}{...props}diff --git a/src/components/ui/textarea.tsx b/src/components/ui/textarea.tsxindex afa394c48..5a1b926e3 100644--- a/src/components/ui/textarea.tsx+++ b/src/components/ui/textarea.tsx@@ -9,8 +9,11 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(return (<textareaclassName={cn(- "flex min-h-[80px] w-full rounded-lg border px-3 py-2 text-sm transition-all duration-200 ease-in-out outline-none disabled:cursor-not-allowed disabled:opacity-50 resize-y cursor-text",- // Use existing CSS from index.css - the textarea styles are already defined there+ "flex min-h-[80px] w-full rounded-xl border border-neutral-200 bg-white px-3.5 py-3 text-sm text-neutral-900 shadow-sm transition-all duration-200 outline-none resize-y cursor-text",+ "placeholder:text-neutral-400",+ "hover:border-neutral-300",+ "focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20",+ "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-neutral-50",className)}ref={ref}diff --git a/src/components/ui/toggle.tsx b/src/components/ui/toggle.tsxindex 68ca54047..caffb3615 100644--- a/src/components/ui/toggle.tsx+++ b/src/components/ui/toggle.tsx@@ -20,13 +20,13 @@ export const Toggle = ({ checked, onChange, disabled = false }: ToggleProps) =><buttononClick={() => !disabled && onChange(!checked)}disabled={disabled}- className={`relative inline-flex h-4.5 w-8 items-center rounded-full transition-all duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 ${getTrackClasses()} ${+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-all duration-150 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-offset-1 ${getTrackClasses()} ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`}><span- className={`inline-block h-3.5 w-3.5 transform rounded-full transition-all duration-150 ${- checked ? "translate-x-3.5" : "translate-x-0.5"+ className={`inline-block h-4 w-4 transform rounded-full transition-all duration-150 ${+ checked ? "translate-x-6" : "translate-x-1"} ${disabled ? "bg-muted-foreground/50" : "bg-background shadow-sm"}`}/></button>diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsxindex 209e9f344..cd839843f 100644--- a/src/components/ui/tooltip.tsx+++ b/src/components/ui/tooltip.tsx@@ -14,9 +14,9 @@ export const Tooltip = ({ children, content }: TooltipProps) => {{children}</div>{isVisible && (- <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 text-xs text-popover-foreground bg-popover border border-border rounded-md whitespace-nowrap z-10 shadow-lg">+ <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2.5 py-1.5 text-xs font-medium text-popover-foreground bg-popover border border-border rounded-md whitespace-nowrap z-50 shadow-lg animate-in fade-in-0 zoom-in-95 duration-150">{content}- <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-2 border-r-2 border-t-2 border-transparent border-t-popover"></div>+ <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-popover"></div></div>)}</div>diff --git a/src/config/constants.ts b/src/config/constants.tsindex f90b199e3..dc6884eda 100644--- a/src/config/constants.ts+++ b/src/config/constants.ts@@ -105,6 +105,9 @@ export const CACHE_CONFIG = {PASTE_DELAY_MS: 50, // Delay before paste simulation to allow clipboard to settle} as const;+// OpenWhispr Cloud API+export const OPENWHISPR_API_URL = (env.VITE_OPENWHISPR_API_URL as string) || "";+// Retry Configurationexport const RETRY_CONFIG = {MAX_RETRIES: 3,diff --git a/src/config/languageRegistry.json b/src/config/languageRegistry.jsonnew file mode 100644index 000000000..5c8383a63--- /dev/null+++ b/src/config/languageRegistry.json@@ -0,0 +1,525 @@+{+ "_genericTemplate": "LANGUAGE CONTEXT: The user's preferred language is set to \"{{code}}\". Detect the language of the transcribed text and respond in that same language. Maintain proper grammar, spelling, and punctuation for the target language. If the user naturally uses English words or technical terms, preserve those as-is.",+ "languages": [+ {+ "code": "auto",+ "label": "Auto-detect",+ "flag": "\uD83C\uDF10",+ "whisper": false,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The language preference is set to auto-detect. Detect the language of the transcribed text and respond entirely in that same language. Maintain consistent language throughout your response."+ },+ {+ "code": "af",+ "label": "Afrikaans",+ "flag": "\uD83C\uDDFF\uD83C\uDDE6",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "ar",+ "label": "Arabic",+ "flag": "\uD83C\uDDF8\uD83C\uDDE6",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Arabic. The transcribed text will be in Arabic. You MUST respond entirely in Arabic while maintaining proper Arabic grammar and punctuation. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "hy",+ "label": "Armenian",+ "flag": "\uD83C\uDDE6\uD83C\uDDF2",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "az",+ "label": "Azerbaijani",+ "flag": "\uD83C\uDDE6\uD83C\uDDFF",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "be",+ "label": "Belarusian",+ "flag": "\uD83C\uDDE7\uD83C\uDDFE",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "bs",+ "label": "Bosnian",+ "flag": "\uD83C\uDDE7\uD83C\uDDE6",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "bg",+ "label": "Bulgarian",+ "flag": "\uD83C\uDDE7\uD83C\uDDEC",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Bulgarian. The transcribed text will be in Bulgarian. You MUST respond entirely in Bulgarian while maintaining proper Bulgarian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "ca",+ "label": "Catalan",+ "flag": "\uD83C\uDDEA\uD83C\uDDF8",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Catalan. The transcribed text will be in Catalan. You MUST respond entirely in Catalan while maintaining proper Catalan grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "zh",+ "label": "Chinese",+ "flag": "\uD83C\uDDE8\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Chinese. The transcribed text will be in Chinese. You MUST respond entirely in Chinese while maintaining proper Chinese grammar and punctuation. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "hr",+ "label": "Croatian",+ "flag": "\uD83C\uDDED\uD83C\uDDF7",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Croatian. The transcribed text will be in Croatian. You MUST respond entirely in Croatian while maintaining proper Croatian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "cs",+ "label": "Czech",+ "flag": "\uD83C\uDDE8\uD83C\uDDFF",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Czech. The transcribed text will be in Czech. You MUST respond entirely in Czech while maintaining proper Czech grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "da",+ "label": "Danish",+ "flag": "\uD83C\uDDE9\uD83C\uDDF0",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Danish. The transcribed text will be in Danish. You MUST respond entirely in Danish while maintaining proper Danish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "nl",+ "label": "Dutch",+ "flag": "\uD83C\uDDF3\uD83C\uDDF1",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Dutch. The transcribed text will be in Dutch. You MUST respond entirely in Dutch while maintaining proper Dutch grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "en-US",+ "label": "English (US)",+ "flag": "\uD83C\uDDFA\uD83C\uDDF8",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is American English. You MUST use American English spelling conventions throughout your response (e.g., \"color\" not \"colour\", \"organize\" not \"organise\", \"center\" not \"centre\", \"defense\" not \"defence\", \"analyze\" not \"analyse\")."+ },+ {+ "code": "en-GB",+ "label": "English (UK)",+ "flag": "\uD83C\uDDEC\uD83C\uDDE7",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is British English. You MUST use British English spelling conventions throughout your response (e.g., \"colour\" not \"color\", \"organise\" not \"organize\", \"centre\" not \"center\", \"defence\" not \"defense\", \"analyse\" not \"analyze\")."+ },+ {+ "code": "et",+ "label": "Estonian",+ "flag": "\uD83C\uDDEA\uD83C\uDDEA",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Estonian. The transcribed text will be in Estonian. You MUST respond entirely in Estonian while maintaining proper Estonian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "fi",+ "label": "Finnish",+ "flag": "\uD83C\uDDEB\uD83C\uDDEE",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Finnish. The transcribed text will be in Finnish. You MUST respond entirely in Finnish while maintaining proper Finnish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "fr",+ "label": "French",+ "flag": "\uD83C\uDDEB\uD83C\uDDF7",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is French. The transcribed text will be in French. You MUST respond entirely in French while maintaining proper French grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their French speech, preserve those as-is."+ },+ {+ "code": "gl",+ "label": "Galician",+ "flag": "\uD83C\uDDEA\uD83C\uDDF8",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "de",+ "label": "German",+ "flag": "\uD83C\uDDE9\uD83C\uDDEA",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is German. The transcribed text will be in German. You MUST respond entirely in German while maintaining proper German grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their German speech, preserve those as-is."+ },+ {+ "code": "el",+ "label": "Greek",+ "flag": "\uD83C\uDDEC\uD83C\uDDF7",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Greek. The transcribed text will be in Greek. You MUST respond entirely in Greek while maintaining proper Greek grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "he",+ "label": "Hebrew",+ "flag": "\uD83C\uDDEE\uD83C\uDDF1",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Hebrew. The transcribed text will be in Hebrew. You MUST respond entirely in Hebrew while maintaining proper Hebrew grammar and punctuation. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "hi",+ "label": "Hindi",+ "flag": "\uD83C\uDDEE\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Hindi. The transcribed text will be in Hindi. You MUST respond entirely in Hindi while maintaining proper Hindi grammar and punctuation. If the user mixes Hindi and English (Hinglish), preserve that natural code-switching."+ },+ {+ "code": "hu",+ "label": "Hungarian",+ "flag": "\uD83C\uDDED\uD83C\uDDFA",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Hungarian. The transcribed text will be in Hungarian. You MUST respond entirely in Hungarian while maintaining proper Hungarian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "is",+ "label": "Icelandic",+ "flag": "\uD83C\uDDEE\uD83C\uDDF8",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "id",+ "label": "Indonesian",+ "flag": "\uD83C\uDDEE\uD83C\uDDE9",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Indonesian. The transcribed text will be in Indonesian. You MUST respond entirely in Indonesian while maintaining proper Indonesian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "it",+ "label": "Italian",+ "flag": "\uD83C\uDDEE\uD83C\uDDF9",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Italian. The transcribed text will be in Italian. You MUST respond entirely in Italian while maintaining proper Italian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their Italian speech, preserve those as-is."+ },+ {+ "code": "ja",+ "label": "Japanese",+ "flag": "\uD83C\uDDEF\uD83C\uDDF5",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Japanese. The transcribed text will be in Japanese. You MUST respond entirely in Japanese while maintaining proper Japanese grammar and punctuation. Preserve any English loanwords (katakana) or technical terms as the user spoke them."+ },+ {+ "code": "kn",+ "label": "Kannada",+ "flag": "\uD83C\uDDEE\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "kk",+ "label": "Kazakh",+ "flag": "\uD83C\uDDF0\uD83C\uDDFF",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "ko",+ "label": "Korean",+ "flag": "\uD83C\uDDF0\uD83C\uDDF7",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Korean. The transcribed text will be in Korean. You MUST respond entirely in Korean while maintaining proper Korean grammar and punctuation. Preserve any English loanwords or technical terms as the user spoke them."+ },+ {+ "code": "lv",+ "label": "Latvian",+ "flag": "\uD83C\uDDF1\uD83C\uDDFB",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Latvian. The transcribed text will be in Latvian. You MUST respond entirely in Latvian while maintaining proper Latvian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "lt",+ "label": "Lithuanian",+ "flag": "\uD83C\uDDF1\uD83C\uDDF9",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Lithuanian. The transcribed text will be in Lithuanian. You MUST respond entirely in Lithuanian while maintaining proper Lithuanian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "mk",+ "label": "Macedonian",+ "flag": "\uD83C\uDDF2\uD83C\uDDF0",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "ms",+ "label": "Malay",+ "flag": "\uD83C\uDDF2\uD83C\uDDFE",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "mt",+ "label": "Maltese",+ "flag": "\uD83C\uDDF2\uD83C\uDDF9",+ "whisper": false,+ "parakeet": true,+ "assemblyai": false+ },+ {+ "code": "mr",+ "label": "Marathi",+ "flag": "\uD83C\uDDEE\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "mi",+ "label": "Maori",+ "flag": "\uD83C\uDDF3\uD83C\uDDFF",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "ne",+ "label": "Nepali",+ "flag": "\uD83C\uDDF3\uD83C\uDDF5",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "no",+ "label": "Norwegian",+ "flag": "\uD83C\uDDF3\uD83C\uDDF4",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Norwegian. The transcribed text will be in Norwegian. You MUST respond entirely in Norwegian while maintaining proper Norwegian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "fa",+ "label": "Persian",+ "flag": "\uD83C\uDDEE\uD83C\uDDF7",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Persian. The transcribed text will be in Persian. You MUST respond entirely in Persian while maintaining proper Persian grammar and punctuation. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "pl",+ "label": "Polish",+ "flag": "\uD83C\uDDF5\uD83C\uDDF1",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Polish. The transcribed text will be in Polish. You MUST respond entirely in Polish while maintaining proper Polish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "pt",+ "label": "Portuguese",+ "flag": "\uD83C\uDDF5\uD83C\uDDF9",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Portuguese. The transcribed text will be in Portuguese. You MUST respond entirely in Portuguese while maintaining proper Portuguese grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their Portuguese speech, preserve those as-is."+ },+ {+ "code": "ro",+ "label": "Romanian",+ "flag": "\uD83C\uDDF7\uD83C\uDDF4",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Romanian. The transcribed text will be in Romanian. You MUST respond entirely in Romanian while maintaining proper Romanian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "ru",+ "label": "Russian",+ "flag": "\uD83C\uDDF7\uD83C\uDDFA",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Russian. The transcribed text will be in Russian. You MUST respond entirely in Russian while maintaining proper Russian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their Russian speech, preserve those as-is."+ },+ {+ "code": "sr",+ "label": "Serbian",+ "flag": "\uD83C\uDDF7\uD83C\uDDF8",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Serbian. The transcribed text will be in Serbian. You MUST respond entirely in Serbian while maintaining proper Serbian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "sk",+ "label": "Slovak",+ "flag": "\uD83C\uDDF8\uD83C\uDDF0",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Slovak. The transcribed text will be in Slovak. You MUST respond entirely in Slovak while maintaining proper Slovak grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "sl",+ "label": "Slovenian",+ "flag": "\uD83C\uDDF8\uD83C\uDDEE",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Slovenian. The transcribed text will be in Slovenian. You MUST respond entirely in Slovenian while maintaining proper Slovenian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "es",+ "label": "Spanish",+ "flag": "\uD83C\uDDEA\uD83C\uDDF8",+ "whisper": true,+ "parakeet": true,+ "assemblyai": true,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Spanish. The transcribed text will be in Spanish. You MUST respond entirely in Spanish while maintaining proper Spanish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms within their Spanish speech (code-switching), preserve those as-is."+ },+ {+ "code": "sw",+ "label": "Swahili",+ "flag": "\uD83C\uDDF0\uD83C\uDDEA",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "sv",+ "label": "Swedish",+ "flag": "\uD83C\uDDF8\uD83C\uDDEA",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Swedish. The transcribed text will be in Swedish. You MUST respond entirely in Swedish while maintaining proper Swedish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "tl",+ "label": "Tagalog",+ "flag": "\uD83C\uDDF5\uD83C\uDDED",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "ta",+ "label": "Tamil",+ "flag": "\uD83C\uDDEE\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "th",+ "label": "Thai",+ "flag": "\uD83C\uDDF9\uD83C\uDDED",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Thai. The transcribed text will be in Thai. You MUST respond entirely in Thai while maintaining proper Thai grammar and punctuation. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "tr",+ "label": "Turkish",+ "flag": "\uD83C\uDDF9\uD83C\uDDF7",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Turkish. The transcribed text will be in Turkish. You MUST respond entirely in Turkish while maintaining proper Turkish grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "uk",+ "label": "Ukrainian",+ "flag": "\uD83C\uDDFA\uD83C\uDDE6",+ "whisper": true,+ "parakeet": true,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Ukrainian. The transcribed text will be in Ukrainian. You MUST respond entirely in Ukrainian while maintaining proper Ukrainian grammar, spelling, and punctuation. If the user naturally uses English words or technical terms, preserve those as-is."+ },+ {+ "code": "ur",+ "label": "Urdu",+ "flag": "\uD83C\uDDF5\uD83C\uDDF0",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ },+ {+ "code": "vi",+ "label": "Vietnamese",+ "flag": "\uD83C\uDDFB\uD83C\uDDF3",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false,+ "instruction": "LANGUAGE CONTEXT: The user's preferred language is Vietnamese. The transcribed text will be in Vietnamese. You MUST respond entirely in Vietnamese while maintaining proper Vietnamese grammar, spelling, and diacritics. Preserve any English technical terms as the user spoke them."+ },+ {+ "code": "cy",+ "label": "Welsh",+ "flag": "\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73\uDB40\uDC7F",+ "whisper": true,+ "parakeet": false,+ "assemblyai": false+ }+ ]+}diff --git a/src/config/promptData.json b/src/config/promptData.jsonindex b4afa6741..597c26215 100644--- a/src/config/promptData.json+++ b/src/config/promptData.json@@ -1,5 +1,5 @@{- "UNIFIED_SYSTEM_PROMPT": "You are an AI assistant named \"{{agentName}}\", integrated into a speech-to-text dictation application. Your primary function is to process transcribed speech and output clean, polished, well-formatted text.\n\nCORE RESPONSIBILITY:\nYour job is ALWAYS to clean up transcribed speech. This is your default behavior for every input. Cleanup means:\n- Removing filler words (um, uh, er, like, you know, I mean, so, basically) unless they add genuine meaning\n- Fixing grammar, spelling, and punctuation errors\n- Breaking up run-on sentences with appropriate punctuation\n- Removing false starts, stutters, and accidental word repetitions\n- Correcting obvious speech-to-text transcription errors\n- Maintaining the speaker's natural voice, tone, vocabulary, and intent\n- Preserving technical terms, proper nouns, names, and specialized jargon exactly as spoken\n- Keeping the same level of formality (casual speech stays casual, formal stays formal)\n\nSMART FORMATTING:\nApply intelligent formatting based on content context. Use your judgment to make the output readable and well-structured:\n\nBullet points - Use when the user is listing items:\n- Shopping or grocery lists (\"I need to get eggs, milk, bread...\")\n- To-do items (\"I need to remember to call John, send the report, book the flight...\")\n- Multiple points or ideas (\"There are a few things... first... also... and finally...\")\n- Features, benefits, or options being enumerated\n\nNumbered lists - Use when order or sequence matters:\n- Step-by-step instructions (\"First do this, then do that, finally...\")\n- Ranked items or priorities\n- Processes or procedures\n\nParagraph breaks - Add line breaks between:\n- Distinct topics or ideas\n- Natural transitions in thought\n- Different sections of longer content\n\nEmail formatting - When dictating an email:\n- Greeting on its own line\n- Body paragraphs separated by line breaks\n- Closing and signature on separate lines\n\nSocial media / posts - When dictating content for LinkedIn, Twitter, etc:\n- Break into digestible paragraphs\n- Separate the hook/opening from the main content\n- Use line breaks for emphasis and readability\n\nDo NOT over-format. If someone is dictating a simple sentence or two, just output clean text. Only apply formatting when it genuinely improves readability and matches the content type.\n\nWHEN YOU ARE DIRECTLY ADDRESSED:\nSince your name is \"{{agentName}}\", the user may speak to you directly to give instructions. When you detect that the user is addressing YOU with a command or request, you should:\n1. STILL perform cleanup on the relevant content\n2. ALSO execute the instruction they gave you\n3. Remove your name and the instruction itself from the final output\n4. Output only the resulting processed text\n\nExamples of being directly addressed:\n- \"Hey {{agentName}}, make this sound more professional\"\n- \"{{agentName}}, put this in bullet points\"\n- \"Can you rewrite that more formally, {{agentName}}\"\n- \"{{agentName}} summarize what I just said\"\n\nCRITICAL: NOT EVERY MENTION OF YOUR NAME IS AN INSTRUCTION\nIf your name appears but the user is NOT giving you a command, treat it as normal content to clean up:\n- \"I was telling {{agentName}} about the project yesterday\" → Clean this up, keep your name in output\n- \"{{agentName}} is really helpful for dictation\" → Clean this up normally\n- \"My assistant {{agentName}} suggested we try this\" → Clean this up normally\n\nHOW TO TELL THE DIFFERENCE:\n- Direct address typically starts with or includes your name + a verb/action: \"{{agentName}}, make...\", \"Hey {{agentName}}, change...\", \"{{agentName}} please rewrite...\"\n- Talking ABOUT you uses your name as a subject/object in a sentence: \"I told {{agentName}}...\", \"{{agentName}} said...\", \"using {{agentName}} to...\"\n- When genuinely uncertain, default to cleanup-only mode\n\nOUTPUT RULES - THESE ARE ABSOLUTE:\n1. Output ONLY the processed text\n2. NEVER include explanations, commentary, or meta-text\n3. NEVER say things like \"Here's the cleaned up version:\" or \"I've made it more formal:\"\n4. NEVER offer alternatives or ask clarifying questions\n5. NEVER add content that wasn't in the original speech\n6. NEVER use labels, headers, or formatting unless specifically instructed\n7. If the input is empty or just filler words, output nothing\n\nYou are processing transcribed speech, so expect imperfect input. Your goal is to output exactly what the user intended to say, cleaned up and polished, as if they had typed it perfectly themselves.",+ "UNIFIED_SYSTEM_PROMPT": "You are an AI assistant named \"{{agentName}}\", integrated into a speech-to-text dictation application. Your primary function is to process transcribed speech and output clean, polished, well-formatted text.\n\nCORE RESPONSIBILITY:\nYour job is ALWAYS to clean up transcribed speech. This is your default behavior for every input. Cleanup means:\n- Removing filler words (um, uh, er, like, you know, I mean, so, basically) unless they add genuine meaning\n- Fixing grammar, spelling, and punctuation errors\n- Breaking up run-on sentences with appropriate punctuation\n- Removing false starts, stutters, and accidental word repetitions\n- Correcting obvious speech-to-text transcription errors\n- Maintaining the speaker's natural voice, tone, vocabulary, and intent\n- Preserving technical terms, proper nouns, names, and specialized jargon exactly as spoken\n- Keeping the same level of formality (casual speech stays casual, formal stays formal)\n\nSELF-CORRECTIONS:\nWhen the user verbally corrects themselves, use only the corrected version:\n- \"I need to call John... wait no, Sarah\" → \"I need to call Sarah\"\n- \"The meeting is on Tuesday... sorry, Wednesday at 3 PM\" → \"The meeting is on Wednesday at 3 PM\"\n- \"Send it to the marketing... actually, the sales team\" → \"Send it to the sales team\"\n- \"We need five... no, ten copies of the report\" → \"We need ten copies of the report\"\n\nCorrection phrases to watch for: \"wait no\", \"sorry\", \"I mean\", \"actually no\", \"scratch that\", \"no no\", \"let me rephrase\", \"correction\", \"I meant to say\", \"rather\", \"or rather\"\n\nBe careful: \"actually\" is often used for emphasis, not correction. \"Actually, I think this is a great idea\" is NOT a correction — keep it. Only treat it as a correction when followed by content that clearly replaces what was just said.\n\nVERBAL PUNCTUATION & FORMATTING COMMANDS:\nUsers may speak punctuation or formatting commands aloud. Convert them to their symbols:\n- \"period\" / \"full stop\" → .\n- \"comma\" → ,\n- \"question mark\" → ?\n- \"exclamation point\" / \"exclamation mark\" → !\n- \"colon\" → :\n- \"semicolon\" → ;\n- \"dash\" / \"hyphen\" → —\n- \"ellipsis\" / \"dot dot dot\" → ...\n- \"new line\" / \"line break\" → (insert line break)\n- \"new paragraph\" → (insert paragraph break)\n- \"open quote\" / \"close quote\" → \" \"\n- \"open parenthesis\" / \"close parenthesis\" → ( )\n- \"open bracket\" / \"close bracket\" → [ ]\n\nUse context to distinguish commands from literal mentions. \"I need eggs comma milk comma and bread\" → \"I need eggs, milk, and bread.\" But \"We discussed the use of commas in English class\" is content about commas — leave it as-is.\n\nNUMBERS, DATES & CURRENCY:\nConvert spoken numbers, dates, times, and currency to standard written forms:\n- Dates: \"January fifteenth twenty twenty-six\" → \"January 15, 2026\"\n- Times: \"five thirty PM\" → \"5:30 PM\", \"noon\" → \"noon\"\n- Currency: \"three hundred dollars\" → \"$300\", \"two hundred thirty-four dollars and fifty cents\" → \"$234.50\"\n- Percentages: \"twenty-five percent\" → \"25%\"\n- Phone numbers: \"five five five one two three four\" → \"555-1234\"\n- Large numbers: \"two point five million\" → \"2.5 million\"\n- Measurements: \"six feet two inches\" → \"6'2\\\"\"\n\nUse contextual judgment: small conversational numbers (one through ten) can stay as words when used casually (\"I have two cats\"). Larger numbers, financial figures, dates, times, and technical values should use digits.\n\nSMART FORMATTING:\nApply intelligent formatting based on content context. Use your judgment to make the output readable and well-structured:\n\nBullet points - Use when the user is listing items:\n- Shopping or grocery lists (\"I need to get eggs, milk, bread...\")\n- To-do items (\"I need to remember to call John, send the report, book the flight...\")\n- Multiple points or ideas (\"There are a few things... first... also... and finally...\")\n- Features, benefits, or options being enumerated\n\nNumbered lists - Use when order or sequence matters:\n- Step-by-step instructions (\"First do this, then do that, finally...\")\n- Ranked items or priorities\n- Processes or procedures\n\nParagraph breaks - Add line breaks between:\n- Distinct topics or ideas\n- Natural transitions in thought\n- Different sections of longer content\n\nEmail formatting - When dictating an email:\n- Greeting on its own line\n- Body paragraphs separated by line breaks\n- Closing and signature on separate lines\n\nSocial media / posts - When dictating content for LinkedIn, Twitter, etc:\n- Break into digestible paragraphs\n- Separate the hook/opening from the main content\n- Use line breaks for emphasis and readability\n\nDo NOT over-format. If someone is dictating a simple sentence or two, just output clean text. Only apply formatting when it genuinely improves readability and matches the content type.\n\nWHEN YOU ARE DIRECTLY ADDRESSED:\nSince your name is \"{{agentName}}\", the user may speak to you directly to give instructions. When you detect that the user is addressing YOU with a command or request, you should:\n1. STILL perform cleanup on the relevant content\n2. ALSO execute the instruction they gave you\n3. Remove your name and the instruction itself from the final output\n4. Output only the resulting processed text\n\nInstructions can appear ANYWHERE in the dictation — beginning, middle, or end:\n- Beginning: \"{{agentName}}, make this professional. The quarterly results show a fifteen percent increase...\"\n- Middle: \"...and we need more resources. Hey {{agentName}}, format this as an email. Also include the budget numbers...\"\n- End: \"...and that's everything for the report. {{agentName}}, clean this up and make it formal.\"\n\nWhen an instruction appears mid-text, strip the instruction and apply it to ALL the surrounding content (both before and after the instruction).\n\nCOMPOUND INSTRUCTIONS:\nThe user may give multiple instructions at once. Execute all of them:\n- \"{{agentName}}, make this professional and put it in bullet points\"\n- \"{{agentName}}, summarize this and make it shorter\"\n- \"Hey {{agentName}}, rewrite this as an email and make the tone more friendly\"\n\nCRITICAL: NOT EVERY MENTION OF YOUR NAME IS AN INSTRUCTION\nIf your name appears but the user is NOT giving you a command, treat it as normal content to clean up:\n- \"I was telling {{agentName}} about the project yesterday\" → Clean this up, keep your name in output\n- \"{{agentName}} is really helpful for dictation\" → Clean this up normally\n- \"My assistant {{agentName}} suggested we try this\" → Clean this up normally\n\nHOW TO TELL THE DIFFERENCE:\n- Direct address typically starts with or includes your name + a verb/action: \"{{agentName}}, make...\", \"Hey {{agentName}}, change...\", \"{{agentName}} please rewrite...\"\n- Talking ABOUT you uses your name as a subject/object in a sentence: \"I told {{agentName}}...\", \"{{agentName}} said...\", \"using {{agentName}} to...\"\n- When genuinely uncertain, default to cleanup-only mode\n\nOUTPUT RULES - THESE ARE ABSOLUTE:\n1. Output ONLY the processed text\n2. NEVER include explanations, commentary, or meta-text\n3. NEVER say things like \"Here's the cleaned up version:\" or \"I've made it more formal:\"\n4. NEVER offer alternatives or ask clarifying questions\n5. NEVER add content that wasn't in the original speech\n6. NEVER use labels, headers, or formatting unless specifically instructed\n7. If the input is empty or just filler words, output nothing\n\nYou are processing transcribed speech, so expect imperfect input. Your goal is to output exactly what the user intended to say, cleaned up and polished, as if they had typed it perfectly themselves.","DICTIONARY_SUFFIX": "\n\nCustom Dictionary (use these exact spellings when they appear in the text): ","LEGACY_PROMPTS": {"agent": "You are {{agentName}}, a helpful AI assistant. Clean up the following dictated text by fixing grammar, punctuation, and formatting. If I give you an instruction, execute it and remove the instruction from the output. Output ONLY the cleaned text:\n\n{{text}}",diff --git a/src/config/prompts.ts b/src/config/prompts.tsindex 9449a7123..eb0f8c59f 100644--- a/src/config/prompts.ts+++ b/src/config/prompts.ts@@ -1,4 +1,5 @@import promptData from "./promptData.json";+import { getLanguageInstruction } from "../utils/languageSupport";export const UNIFIED_SYSTEM_PROMPT = promptData.UNIFIED_SYSTEM_PROMPT;export const LEGACY_PROMPTS = promptData.LEGACY_PROMPTS;@@ -9,7 +10,11 @@ export function buildPrompt(text: string, agentName: string | null): string {return UNIFIED_SYSTEM_PROMPT.replace(/\{\{agentName\}\}/g, name).replace(/\{\{text\}\}/g, text);}-export function getSystemPrompt(agentName: string | null, customDictionary?: string[]): string {+export function getSystemPrompt(+ agentName: string | null,+ customDictionary?: string[],+ language?: string+): string {const name = agentName?.trim() || "Assistant";let promptTemplate = UNIFIED_SYSTEM_PROMPT;@@ -26,6 +31,11 @@ export function getSystemPrompt(agentName: string | null, customDictionary?: strlet prompt = promptTemplate.replace(/\{\{agentName\}\}/g, name);+ const langInstruction = getLanguageInstruction(language);+ if (langInstruction) {+ prompt += "\n\n" + langInstruction;+ }+if (customDictionary && customDictionary.length > 0) {prompt += DICTIONARY_SUFFIX + customDictionary.join(", ");}diff --git a/src/helpers/assemblyAiStreaming.js b/src/helpers/assemblyAiStreaming.jsnew file mode 100644index 000000000..d86ae847e--- /dev/null+++ b/src/helpers/assemblyAiStreaming.js@@ -0,0 +1,482 @@+const WebSocket = require("ws");+const debugLogger = require("./debugLogger");++const SAMPLE_RATE = 16000;+const WEBSOCKET_TIMEOUT_MS = 30000;+const TERMINATION_TIMEOUT_MS = 5000;+const TOKEN_REFRESH_BUFFER_MS = 30000;+const TOKEN_EXPIRY_MS = 300000;+const REWARM_DELAY_MS = 2000;+const MAX_REWARM_ATTEMPTS = 3;++class AssemblyAiStreaming {+ constructor() {+ this.ws = null;+ this.sessionId = null;+ this.isConnected = false;+ this.onPartialTranscript = null;+ this.onFinalTranscript = null;+ this.onError = null;+ this.onSessionEnd = null;+ this.pendingResolve = null;+ this.pendingReject = null;+ this.connectionTimeout = null;+ this.accumulatedText = "";+ this.lastTurnText = "";+ this.turns = [];+ this.terminationResolve = null;+ this.cachedToken = null;+ this.tokenFetchedAt = null;+ this.warmConnection = null;+ this.warmConnectionReady = false;+ this.warmConnectionOptions = null;+ this.rewarmAttempts = 0;+ this.rewarmTimer = null;+ }++ buildWebSocketUrl(options) {+ const sampleRate = options.sampleRate || SAMPLE_RATE;+ const params = new URLSearchParams({+ sample_rate: String(sampleRate),+ encoding: "pcm_s16le",+ format_turns: "true",+ token: options.token,+ });+ if (options.language && options.language !== "auto") {+ params.set("speech_model", "universal-streaming-multilingual");+ }+ return `wss://streaming.assemblyai.com/v3/ws?${params.toString()}`;+ }++ cacheToken(token) {+ this.cachedToken = token;+ this.tokenFetchedAt = Date.now();+ debugLogger.debug("AssemblyAI token cached", { expiresIn: TOKEN_EXPIRY_MS });+ }++ isTokenValid() {+ if (!this.cachedToken || !this.tokenFetchedAt) return false;+ const age = Date.now() - this.tokenFetchedAt;+ return age < TOKEN_EXPIRY_MS - TOKEN_REFRESH_BUFFER_MS;+ }++ getCachedToken() {+ return this.isTokenValid() ? this.cachedToken : null;+ }++ async warmup(options = {}) {+ const { token } = options;+ if (!token) {+ throw new Error("Streaming token is required for warmup");+ }++ if (this.warmConnection) {+ debugLogger.debug(+ this.warmConnectionReady+ ? "AssemblyAI connection already warm"+ : "AssemblyAI warmup already in progress, skipping"+ );+ return;+ }++ this.warmConnectionReady = false;+ this.cachedToken = token;+ this.tokenFetchedAt = Date.now();+ this.warmConnectionOptions = options;+ this.rewarmAttempts = 0;++ const url = this.buildWebSocketUrl(options);+ debugLogger.debug("AssemblyAI warming up connection");++ return new Promise((resolve, reject) => {+ const warmupTimeout = setTimeout(() => {+ this.cleanupWarmConnection();+ reject(new Error("AssemblyAI warmup connection timeout"));+ }, WEBSOCKET_TIMEOUT_MS);++ this.warmConnection = new WebSocket(url);++ this.warmConnection.on("open", () => {+ debugLogger.debug("AssemblyAI warm connection socket opened");+ });++ this.warmConnection.on("message", (data) => {+ try {+ const message = JSON.parse(data.toString());+ if (message.type === "Begin") {+ clearTimeout(warmupTimeout);+ this.warmConnectionReady = true;+ debugLogger.debug("AssemblyAI connection warmed up", { sessionId: message.id });+ resolve();+ }+ } catch (err) {+ debugLogger.error("AssemblyAI warmup message parse error", { error: err.message });+ }+ });++ this.warmConnection.on("error", (error) => {+ clearTimeout(warmupTimeout);+ debugLogger.error("AssemblyAI warmup connection error", { error: error.message });+ this.cleanupWarmConnection();+ reject(error);+ });++ this.warmConnection.on("close", () => {+ clearTimeout(warmupTimeout);+ // Only auto re-warm if this was a ready connection that got closed by the server+ // (not one we intentionally consumed via useWarmConnection)+ const wasReady = this.warmConnectionReady;+ debugLogger.debug("AssemblyAI warm connection closed", { wasReady });+ this.cleanupWarmConnection();+ if (wasReady) {+ this.scheduleRewarm();+ }+ });+ });+ }++ scheduleRewarm() {+ if (this.rewarmAttempts >= MAX_REWARM_ATTEMPTS) {+ debugLogger.debug("AssemblyAI max re-warm attempts reached, giving up");+ return;+ }+ if (this.isConnected) {+ // Active session in progress, don't re-warm+ return;+ }+ const token = this.getCachedToken();+ if (!token || !this.warmConnectionOptions) {+ debugLogger.debug("AssemblyAI cannot re-warm: no valid token or options");+ return;+ }++ this.rewarmAttempts++;+ debugLogger.debug("AssemblyAI scheduling re-warm", { attempt: this.rewarmAttempts });+ clearTimeout(this.rewarmTimer);+ this.rewarmTimer = setTimeout(() => {+ this.rewarmTimer = null;+ if (this.hasWarmConnection() || this.isConnected) return;+ this.warmup({ ...this.warmConnectionOptions, token }).catch((err) => {+ debugLogger.debug("AssemblyAI auto re-warm failed", { error: err.message });+ });+ }, REWARM_DELAY_MS);+ }++ useWarmConnection() {+ if (!this.warmConnection || !this.warmConnectionReady) {+ return false;+ }++ // Transfer warm connection to active connection+ this.ws = this.warmConnection;+ this.isConnected = true;+ this.warmConnection = null;+ this.warmConnectionReady = false;++ // Re-attach message handler for transcription events+ this.ws.removeAllListeners("message");+ this.ws.on("message", (data) => {+ this.handleMessage(data);+ });++ this.ws.removeAllListeners("error");+ this.ws.on("error", (error) => {+ debugLogger.error("AssemblyAI WebSocket error", { error: error.message });+ this.cleanup();+ this.onError?.(error);+ });++ this.ws.removeAllListeners("close");+ this.ws.on("close", (code, reason) => {+ debugLogger.debug("AssemblyAI WebSocket closed", { code, reason: reason?.toString() });+ this.cleanup();+ });++ debugLogger.debug("AssemblyAI using pre-warmed connection");+ return true;+ }++ cleanupWarmConnection() {+ if (this.warmConnection) {+ try {+ this.warmConnection.close();+ } catch (err) {+ // Ignore+ }+ this.warmConnection = null;+ }+ this.warmConnectionReady = false;+ this.warmConnectionOptions = null;+ }++ hasWarmConnection() {+ return this.warmConnection !== null && this.warmConnectionReady;+ }++ async connect(options = {}) {+ const { token } = options;+ if (!token) {+ throw new Error("Streaming token is required");+ }++ if (this.isConnected) {+ debugLogger.debug("AssemblyAI streaming already connected");+ return;+ }++ // Reset accumulated text for new session+ this.accumulatedText = "";+ this.lastTurnText = "";+ this.turns = [];++ // Try to use pre-warmed connection for instant start+ if (this.hasWarmConnection()) {+ if (this.useWarmConnection()) {+ debugLogger.debug("AssemblyAI using warm connection - instant start");+ return;+ }+ }++ const url = this.buildWebSocketUrl(options);+ debugLogger.debug("AssemblyAI streaming connecting (cold start)");++ return new Promise((resolve, reject) => {+ this.pendingResolve = resolve;+ this.pendingReject = reject;++ this.connectionTimeout = setTimeout(() => {+ this.cleanup();+ reject(new Error("AssemblyAI WebSocket connection timeout"));+ }, WEBSOCKET_TIMEOUT_MS);++ this.ws = new WebSocket(url);++ this.ws.on("open", () => {+ debugLogger.debug("AssemblyAI WebSocket connected");+ });++ this.ws.on("message", (data) => {+ this.handleMessage(data);+ });++ this.ws.on("error", (error) => {+ debugLogger.error("AssemblyAI WebSocket error", { error: error.message });+ this.cleanup();+ if (this.pendingReject) {+ this.pendingReject(error);+ this.pendingReject = null;+ this.pendingResolve = null;+ }+ this.onError?.(error);+ });++ this.ws.on("close", (code, reason) => {+ debugLogger.debug("AssemblyAI WebSocket closed", { code, reason: reason?.toString() });+ this.cleanup();+ });+ });+ }++ handleMessage(data) {+ try {+ const message = JSON.parse(data.toString());++ switch (message.type) {+ case "Begin":+ this.sessionId = message.id;+ this.isConnected = true;+ clearTimeout(this.connectionTimeout);+ debugLogger.debug("AssemblyAI session started", { sessionId: this.sessionId });+ if (this.pendingResolve) {+ this.pendingResolve();+ this.pendingResolve = null;+ this.pendingReject = null;+ }+ break;++ case "Turn":+ if (message.transcript) {+ if (message.end_of_turn) {+ // Turn has ended - append once, then replace with formatted variant if needed+ const trimmedTranscript = message.transcript.trim();+ const normalizedTranscript = this.normalizeTurnText(trimmedTranscript);+ const previousTurn = this.turns[this.turns.length - 1];++ if (!trimmedTranscript || !normalizedTranscript) {+ break;+ }++ if (previousTurn && previousTurn.normalized === normalizedTranscript) {+ // AssemblyAI can emit the same turn twice (raw then formatted). Replace previous+ // turn only when this variant is formatted, otherwise ignore duplicate.+ if (message.turn_is_formatted && previousTurn.text !== trimmedTranscript) {+ previousTurn.text = trimmedTranscript;+ this.lastTurnText = trimmedTranscript;+ this.accumulatedText = this.turns.map((turn) => turn.text).join(" ");+ this.onFinalTranscript?.(this.accumulatedText);+ debugLogger.debug("AssemblyAI formatted turn update applied", {+ text: trimmedTranscript.slice(0, 100),+ totalAccumulated: this.accumulatedText.length,+ });+ } else {+ debugLogger.debug("AssemblyAI duplicate turn ignored", {+ text: trimmedTranscript.slice(0, 100),+ });+ }+ break;+ }++ this.turns.push({+ text: trimmedTranscript,+ normalized: normalizedTranscript,+ });+ this.lastTurnText = trimmedTranscript;+ this.accumulatedText = this.turns.map((turn) => turn.text).join(" ");+ this.onFinalTranscript?.(this.accumulatedText);+ debugLogger.debug("AssemblyAI final transcript (end_of_turn)", {+ text: message.transcript.slice(0, 100),+ totalAccumulated: this.accumulatedText.length,+ });+ } else if (message.turn_is_formatted) {+ // Formatted but turn not ended yet - show as preview without accumulating+ this.onPartialTranscript?.(message.transcript);+ } else {+ // Partial transcript - show real-time updates (current turn only)+ this.onPartialTranscript?.(message.transcript);+ }+ }+ break;++ case "Termination":+ debugLogger.debug("AssemblyAI session terminated", {+ audioDuration: message.audio_duration_seconds,+ });+ // Resolve any pending termination wait+ if (this.terminationResolve) {+ this.terminationResolve({+ audioDuration: message.audio_duration_seconds,+ text: this.accumulatedText,+ });+ this.terminationResolve = null;+ }+ this.onSessionEnd?.({+ audioDuration: message.audio_duration_seconds,+ text: this.accumulatedText,+ });+ this.cleanup();+ break;++ case "Error":+ debugLogger.error("AssemblyAI streaming error", { error: message.error });+ this.onError?.(new Error(message.error));+ break;++ default:+ debugLogger.debug("AssemblyAI unknown message type", { type: message.type });+ }+ } catch (err) {+ debugLogger.error("AssemblyAI message parse error", { error: err.message });+ }+ }++ normalizeTurnText(text) {+ return text+ .toLowerCase()+ .replace(/[^\p{L}\p{N}\s]/gu, " ")+ .replace(/\s+/g, " ")+ .trim();+ }++ sendAudio(pcmBuffer) {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ return false;+ }++ this.ws.send(pcmBuffer);+ return true;+ }++ forceEndpoint() {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {+ return false;+ }++ this.ws.send(JSON.stringify({ type: "ForceEndpoint" }));+ debugLogger.debug("AssemblyAI ForceEndpoint sent");+ return true;+ }++ async disconnect(terminate = true) {+ if (!this.ws) return { text: this.accumulatedText };++ if (terminate && this.ws.readyState === WebSocket.OPEN) {+ try {+ this.ws.send(JSON.stringify({ type: "Terminate" }));++ let timeoutId;+ const result = await Promise.race([+ new Promise((resolve) => {+ this.terminationResolve = resolve;+ }),+ new Promise((resolve) => {+ timeoutId = setTimeout(() => {+ debugLogger.debug("AssemblyAI termination timeout, using accumulated text");+ resolve({ text: this.accumulatedText });+ }, TERMINATION_TIMEOUT_MS);+ }),+ ]);+ clearTimeout(timeoutId);++ this.terminationResolve = null;+ this.cleanup();+ return result;+ } catch (err) {+ debugLogger.debug("AssemblyAI terminate send failed", { error: err.message });+ }+ }++ const result = { text: this.accumulatedText };+ this.cleanup();+ return result;+ }++ cleanup() {+ clearTimeout(this.connectionTimeout);+ this.connectionTimeout = null;++ if (this.ws) {+ try {+ this.ws.close();+ } catch (err) {+ // Ignore close errors+ }+ this.ws = null;+ }++ this.isConnected = false;+ this.sessionId = null;+ this.terminationResolve = null;+ }++ cleanupAll() {+ this.cleanup();+ this.cleanupWarmConnection();+ clearTimeout(this.rewarmTimer);+ this.rewarmTimer = null;+ this.cachedToken = null;+ this.tokenFetchedAt = null;+ this.warmConnectionOptions = null;+ this.turns = [];+ }++ getStatus() {+ return {+ isConnected: this.isConnected,+ sessionId: this.sessionId,+ hasWarmConnection: this.hasWarmConnection(),+ hasValidToken: this.isTokenValid(),+ };+ }+}++module.exports = AssemblyAiStreaming;diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex c5a1ebd26..dd463274e 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -3,6 +3,8 @@ import { API_ENDPOINTS, buildApiUrl, normalizeBaseUrl } from "../config/constantimport logger from "../utils/logger";import { isBuiltInMicrophone } from "../utils/audioDeviceUtils";import { isSecureEndpoint } from "../utils/urlUtils";+import { withSessionRefresh } from "../lib/neonAuth";+import { getBaseLanguageCode, validateLanguageForModel } from "../utils/languageSupport";const SHORT_CLIP_DURATION_SECONDS = 2.5;const REASONING_CACHE_TTL = 30000; // 30 seconds@@ -27,6 +29,7 @@ class AudioManager {this.onStateChange = null;this.onError = null;this.onTranscriptionComplete = null;+ this.onPartialTranscript = null;this.cachedApiKey = null;this.cachedApiKeyProvider = null;this.cachedTranscriptionEndpoint = null;@@ -35,6 +38,19 @@ class AudioManager {this.recordingStartTime = null;this.reasoningAvailabilityCache = { value: false, expiresAt: 0 };this.cachedReasoningPreference = null;+ this.isStreaming = false;+ this.streamingAudioContext = null;+ this.streamingSource = null;+ this.streamingProcessor = null;+ this.streamingStream = null;+ this.streamingCleanupFns = [];+ this.streamingFinalText = "";+ this.streamingPartialText = "";+ this.streamingTextResolve = null;+ this.streamingTextDebounce = null;+ this.cachedMicDeviceId = null;+ this.persistentAudioContext = null;+ this.workletModuleLoaded = false;}getCustomDictionaryPrompt() {@@ -49,29 +65,47 @@ class AudioManager {return null;}- setCallbacks({ onStateChange, onError, onTranscriptionComplete }) {+ setCallbacks({ onStateChange, onError, onTranscriptionComplete, onPartialTranscript }) {this.onStateChange = onStateChange;this.onError = onError;this.onTranscriptionComplete = onTranscriptionComplete;+ this.onPartialTranscript = onPartialTranscript;}async getAudioConstraints() {const preferBuiltIn = localStorage.getItem("preferBuiltInMic") !== "false";const selectedDeviceId = localStorage.getItem("selectedMicDeviceId") || "";+ // Disable browser audio processing — dictation doesn't need it and it adds ~48ms latency+ const noProcessing = {+ echoCancellation: false,+ noiseSuppression: false,+ autoGainControl: false,+ };+if (preferBuiltIn) {+ if (this.cachedMicDeviceId) {+ logger.debug(+ "Using cached microphone device ID",+ { deviceId: this.cachedMicDeviceId },+ "audio"+ );+ return { audio: { deviceId: { exact: this.cachedMicDeviceId }, ...noProcessing } };+ }+try {const devices = await navigator.mediaDevices.enumerateDevices();const audioInputs = devices.filter((d) => d.kind === "audioinput");const builtInMic = audioInputs.find((d) => isBuiltInMicrophone(d.label));if (builtInMic) {+ this.cachedMicDeviceId = builtInMic.deviceId;logger.debug(- "Using built-in microphone",+ "Using built-in microphone (cached for next time)",{ deviceId: builtInMic.deviceId, label: builtInMic.label },"audio");- return { audio: { deviceId: { exact: builtInMic.deviceId } } };+ return { audio: { deviceId: { exact: builtInMic.deviceId }, ...noProcessing } };}} catch (error) {logger.debug(@@ -82,15 +116,32 @@ class AudioManager {}}- // Use selected device if specified and not preferring built-inif (!preferBuiltIn && selectedDeviceId) {logger.debug("Using selected microphone", { deviceId: selectedDeviceId }, "audio");- return { audio: { deviceId: { exact: selectedDeviceId } } };+ return { audio: { deviceId: { exact: selectedDeviceId }, ...noProcessing } };}- // Fall back to default devicelogger.debug("Using default microphone", {}, "audio");- return { audio: true };+ return { audio: noProcessing };+ }++ async cacheMicrophoneDeviceId() {+ if (this.cachedMicDeviceId) return; // Already cached++ const preferBuiltIn = localStorage.getItem("preferBuiltInMic") !== "false";+ if (!preferBuiltIn) return; // Only needed for built-in mic detection++ try {+ const devices = await navigator.mediaDevices.enumerateDevices();+ const audioInputs = devices.filter((d) => d.kind === "audioinput");+ const builtInMic = audioInputs.find((d) => isBuiltInMicrophone(d.label));+ if (builtInMic) {+ this.cachedMicDeviceId = builtInMic.deviceId;+ logger.debug("Microphone device ID pre-cached", { deviceId: builtInMic.deviceId }, "audio");+ }+ } catch (error) {+ logger.debug("Failed to pre-cache microphone device ID", { error: error.message }, "audio");+ }}async startRecording() {@@ -102,7 +153,6 @@ class AudioManager {const constraints = await this.getAudioConstraints();const stream = await navigator.mediaDevices.getUserMedia(constraints);- // Log which microphone is actually being usedconst audioTrack = stream.getAudioTracks()[0];if (audioTrack) {const settings = audioTrack.getSettings();@@ -134,7 +184,6 @@ class AudioManager {const audioBlob = new Blob(this.audioChunks, { type: this.recordingMimeType });- // Debug: Log audio blob infologger.info("Recording stopped",{@@ -151,7 +200,6 @@ class AudioManager {this.recordingStartTime = null;await this.processAudio(audioBlob, { durationSeconds });- // Clean up streamstream.getTracks().forEach((track) => track.stop());};@@ -161,7 +209,6 @@ class AudioManager {return true;} catch (error) {- // Provide more specific error messageslet errorTitle = "Recording Error";let errorDescription = `Failed to access microphone: ${error.message}`;@@ -189,7 +236,6 @@ class AudioManager {stopRecording() {if (this.mediaRecorder?.state === "recording") {this.mediaRecorder.stop();- // State change will be handled in onstop callbackreturn true;}return false;@@ -234,6 +280,17 @@ class AudioManager {const whisperModel = localStorage.getItem("whisperModel") || "base";const parakeetModel = localStorage.getItem("parakeetModel") || "parakeet-tdt-0.6b-v3";+ const cloudTranscriptionMode = localStorage.getItem("cloudTranscriptionMode") || "openwhispr";+ const isSignedIn = localStorage.getItem("isSignedIn") === "true";++ const isOpenWhisprCloudMode = !useLocalWhisper && cloudTranscriptionMode === "openwhispr";+ const useCloud = isOpenWhisprCloudMode && isSignedIn;+ logger.debug(+ "Transcription routing",+ { useLocalWhisper, useCloud, isSignedIn, cloudTranscriptionMode },+ "transcription"+ );+let result;let activeModel;if (useLocalWhisper) {@@ -244,6 +301,16 @@ class AudioManager {activeModel = whisperModel;result = await this.processWithLocalWhisper(audioBlob, whisperModel, metadata);}+ } else if (isOpenWhisprCloudMode) {+ if (!isSignedIn) {+ const err = new Error(+ "OpenWhispr Cloud requires sign-in. Please sign in again or switch to BYOK mode."+ );+ err.code = "AUTH_REQUIRED";+ throw err;+ }+ activeModel = "openwhispr-cloud";+ result = await this.processWithOpenWhisprCloud(audioBlob, metadata);} else {activeModel = this.getTranscriptionModel();result = await this.processWithOpenAIAPI(audioBlob, metadata);@@ -293,6 +360,7 @@ class AudioManager {this.onError?.({title: "Transcription Error",description: `Transcription failed: ${error.message}`,+ code: error.code,});}} finally {@@ -310,9 +378,9 @@ class AudioManager {// Send original audio to main process - FFmpeg in main process handles conversion// (renderer-side AudioContext conversion was unreliable with WebM/Opus format)const arrayBuffer = await audioBlob.arrayBuffer();- const language = localStorage.getItem("preferredLanguage");+ const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));const options = { model };- if (language && language !== "auto") {+ if (language) {options.language = language;}@@ -389,9 +457,9 @@ class AudioManager {try {const arrayBuffer = await audioBlob.arrayBuffer();- const language = localStorage.getItem("preferredLanguage");+ const language = validateLanguageForModel(localStorage.getItem("preferredLanguage"), model);const options = { model };- if (language && language !== "auto") {+ if (language) {options.language = language;}@@ -933,9 +1001,91 @@ class AudioManager {return result;}+ async processWithOpenWhisprCloud(audioBlob, metadata = {}) {+ if (!navigator.onLine) {+ const err = new Error("You're offline. Cloud transcription requires an internet connection.");+ err.code = "OFFLINE";+ throw err;+ }++ const timings = {};+ const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));++ const arrayBuffer = await audioBlob.arrayBuffer();+ const opts = {};+ if (language) opts.language = language;++ const dictionaryPrompt = this.getCustomDictionaryPrompt();+ if (dictionaryPrompt) opts.prompt = dictionaryPrompt;++ // Use withSessionRefresh to handle AUTH_EXPIRED automatically+ const transcriptionStart = performance.now();+ const result = await withSessionRefresh(async () => {+ const res = await window.electronAPI.cloudTranscribe(arrayBuffer, opts);+ if (!res.success) {+ const err = new Error(res.error || "Cloud transcription failed");+ err.code = res.code;+ throw err;+ }+ return res;+ });+ timings.transcriptionProcessingDurationMs = Math.round(performance.now() - transcriptionStart);++ // Process with reasoning if enabled+ let processedText = result.text;+ const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";+ if (useReasoningModel && processedText) {+ const reasoningStart = performance.now();+ const agentName = localStorage.getItem("agentName") || "";+ const cloudTranscriptionMode = localStorage.getItem("cloudTranscriptionMode") || "openwhispr";++ if (cloudTranscriptionMode === "openwhispr") {+ const reasonResult = await withSessionRefresh(async () => {+ const res = await window.electronAPI.cloudReason(processedText, {+ agentName,+ customDictionary: this.getCustomDictionaryArray(),+ language: localStorage.getItem("preferredLanguage") || "auto",+ });+ if (!res.success) {+ const err = new Error(res.error || "Cloud reasoning failed");+ err.code = res.code;+ throw err;+ }+ return res;+ });++ if (reasonResult.success) {+ processedText = reasonResult.text;+ }+ }+ timings.reasoningProcessingDurationMs = Math.round(performance.now() - reasoningStart);+ }++ return {+ success: true,+ text: processedText,+ source: "openwhispr",+ timings,+ limitReached: result.limitReached,+ wordsUsed: result.wordsUsed,+ wordsRemaining: result.wordsRemaining,+ };+ }++ getCustomDictionaryArray() {+ try {+ const raw = localStorage.getItem("customDictionary");+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+ }+async processWithOpenAIAPI(audioBlob, metadata = {}) {const timings = {};- const language = localStorage.getItem("preferredLanguage");+ const language = getBaseLanguageCode(localStorage.getItem("preferredLanguage"));const allowLocalFallback = localStorage.getItem("allowLocalFallback") === "true";const fallbackModel = localStorage.getItem("fallbackWhisperModel") || "base";@@ -1012,7 +1162,7 @@ class AudioManager {formData.append("file", optimizedAudio, `audio.${extension}`);formData.append("model", model);- if (language && language !== "auto") {+ if (language) {formData.append("language", language);}@@ -1402,9 +1552,9 @@ class AudioManager {}}- async safePaste(text) {+ async safePaste(text, options = {}) {try {- await window.electronAPI.pasteText(text);+ await window.electronAPI.pasteText(text, options);return true;} catch (error) {this.onError?.({@@ -1428,16 +1578,492 @@ class AudioManager {return {isRecording: this.isRecording,isProcessing: this.isProcessing,+ isStreaming: this.isStreaming,};}+ shouldUseStreaming() {+ const cloudTranscriptionMode = localStorage.getItem("cloudTranscriptionMode") || "openwhispr";+ const isSignedIn = localStorage.getItem("isSignedIn") === "true";+ const useLocalWhisper = localStorage.getItem("useLocalWhisper") === "true";+ const streamingDisabled = localStorage.getItem("assemblyAiStreaming") === "false";++ return (+ !useLocalWhisper &&+ cloudTranscriptionMode === "openwhispr" &&+ isSignedIn &&+ !streamingDisabled+ );+ }++ async warmupStreamingConnection() {+ if (!this.shouldUseStreaming()) {+ logger.debug("Streaming warmup skipped - not in streaming mode", {}, "streaming");+ return false;+ }++ try {+ const [, wsResult] = await Promise.all([+ this.cacheMicrophoneDeviceId(),+ withSessionRefresh(async () => {+ const res = await window.electronAPI.assemblyAiStreamingWarmup({+ sampleRate: 16000,+ language: getBaseLanguageCode(localStorage.getItem("preferredLanguage")),+ });+ // Throw error to trigger retry if AUTH_EXPIRED+ if (!res.success && res.code) {+ const err = new Error(res.error || "Warmup failed");+ err.code = res.code;+ throw err;+ }+ return res;+ }),+ ]);++ if (wsResult.success) {+ // Pre-load AudioWorklet module so first recording is faster+ try {+ const audioContext = await this.getOrCreateAudioContext();+ if (!this.workletModuleLoaded) {+ const workletUrl = new URL("./pcm-streaming-processor.js", document.baseURI).href;+ await audioContext.audioWorklet.addModule(workletUrl);+ this.workletModuleLoaded = true;+ logger.debug("AudioWorklet module pre-loaded during warmup", {}, "streaming");+ }+ } catch (e) {+ logger.debug("AudioWorklet pre-load failed (will retry on recording)", { error: e.message }, "streaming");+ }++ // Warm up the OS audio driver by briefly acquiring the mic, then releasing.+ // This forces macOS to initialize the audio subsystem so subsequent+ // getUserMedia calls resolve in ~100-200ms instead of ~500-1000ms.+ if (!this.micDriverWarmedUp) {+ try {+ const constraints = await this.getAudioConstraints();+ const tempStream = await navigator.mediaDevices.getUserMedia(constraints);+ tempStream.getTracks().forEach((track) => track.stop());+ this.micDriverWarmedUp = true;+ logger.debug("Microphone driver pre-warmed", {}, "streaming");+ } catch (e) {+ logger.debug("Mic driver warmup failed (non-critical)", { error: e.message }, "streaming");+ }+ }++ logger.info(+ "AssemblyAI streaming connection warmed up",+ { alreadyWarm: wsResult.alreadyWarm, micCached: !!this.cachedMicDeviceId },+ "streaming"+ );+ return true;+ } else if (wsResult.code === "NO_API") {+ logger.debug("Streaming warmup skipped - API not configured", {}, "streaming");+ return false;+ } else {+ logger.warn("AssemblyAI warmup failed", { error: wsResult.error }, "streaming");+ return false;+ }+ } catch (error) {+ logger.error("AssemblyAI warmup error", { error: error.message }, "streaming");+ return false;+ }+ }++ async getOrCreateAudioContext() {+ if (this.persistentAudioContext && this.persistentAudioContext.state !== "closed") {+ if (this.persistentAudioContext.state === "suspended") {+ await this.persistentAudioContext.resume();+ }+ return this.persistentAudioContext;+ }+ this.persistentAudioContext = new AudioContext({ sampleRate: 16000 });+ this.workletModuleLoaded = false;+ return this.persistentAudioContext;+ }++ async startStreamingRecording() {+ try {+ if (this.isRecording || this.isStreaming || this.isProcessing) {+ return false;+ }++ const t0 = performance.now();+ const constraints = await this.getAudioConstraints();+ const tConstraints = performance.now();++ // Run getUserMedia and WebSocket connect in parallel.+ // With warmup, WS resolves in ~5ms; getUserMedia (~500ms) dominates.+ const [stream, result] = await Promise.all([+ navigator.mediaDevices.getUserMedia(constraints),+ withSessionRefresh(async () => {+ const res = await window.electronAPI.assemblyAiStreamingStart({+ sampleRate: 16000,+ language: getBaseLanguageCode(localStorage.getItem("preferredLanguage")),+ });++ if (!res.success) {+ if (res.code === "NO_API") {+ return { needsFallback: true };+ }+ const err = new Error(res.error || "Failed to start streaming session");+ err.code = res.code;+ throw err;+ }+ return res;+ }),+ ]);+ const tParallel = performance.now();++ const audioTrack = stream.getAudioTracks()[0];+ if (audioTrack) {+ const settings = audioTrack.getSettings();+ logger.info(+ "Streaming recording started with microphone",+ {+ label: audioTrack.label,+ deviceId: settings.deviceId?.slice(0, 20) + "...",+ sampleRate: settings.sampleRate,+ usedCachedId: !!this.cachedMicDeviceId,+ },+ "audio"+ );+ }++ if (result.needsFallback) {+ stream.getTracks().forEach((track) => track.stop());+ logger.debug(+ "Streaming API not configured, falling back to regular recording",+ {},+ "streaming"+ );+ return this.startRecording();+ }++ const audioContext = await this.getOrCreateAudioContext();+ this.streamingAudioContext = audioContext;+ this.streamingSource = audioContext.createMediaStreamSource(stream);+ this.streamingStream = stream;++ if (!this.workletModuleLoaded) {+ const workletUrl = new URL("./pcm-streaming-processor.js", document.baseURI).href;+ await audioContext.audioWorklet.addModule(workletUrl);+ this.workletModuleLoaded = true;+ }++ this.streamingProcessor = new AudioWorkletNode(audioContext, "pcm-streaming-processor");++ this.streamingProcessor.port.onmessage = (event) => {+ if (!this.isStreaming) return;+ window.electronAPI.assemblyAiStreamingSend(event.data);+ };++ this.streamingSource.connect(this.streamingProcessor);++ const tReady = performance.now();+ logger.info(+ "Streaming start timing",+ {+ constraintsMs: Math.round(tConstraints - t0),+ getUserMediaAndWsMs: Math.round(tParallel - tConstraints),+ pipelineMs: Math.round(tReady - tParallel),+ totalMs: Math.round(tReady - t0),+ usedWarmConnection: result.usedWarmConnection,+ micDriverWarmedUp: !!this.micDriverWarmedUp,+ },+ "streaming"+ );++ // Show recording indicator only AFTER mic is live and audio pipeline is connected.+ // This ensures no words are lost — the user sees "recording" exactly when audio flows.+ this.isStreaming = true;+ this.isRecording = true;+ this.recordingStartTime = Date.now();+ this.onStateChange?.({ isRecording: true, isProcessing: false, isStreaming: true });++ this.streamingFinalText = "";+ this.streamingPartialText = "";+ this.streamingTextResolve = null;+ this.streamingTextDebounce = null;++ const partialCleanup = window.electronAPI.onAssemblyAiPartialTranscript((text) => {+ this.streamingPartialText = text;+ this.onPartialTranscript?.(text);+ });++ const finalCleanup = window.electronAPI.onAssemblyAiFinalTranscript((text) => {+ this.streamingFinalText = text;+ this.streamingPartialText = "";+ this.onPartialTranscript?.(text);+ });++ const errorCleanup = window.electronAPI.onAssemblyAiError((error) => {+ logger.error("AssemblyAI streaming error", { error }, "streaming");+ this.onError?.({+ title: "Streaming Error",+ description: error,+ });+ });++ const sessionEndCleanup = window.electronAPI.onAssemblyAiSessionEnd((data) => {+ logger.debug("AssemblyAI session ended", data, "streaming");+ if (data.text) {+ this.streamingFinalText = data.text;+ }+ });++ this.streamingCleanupFns = [partialCleanup, finalCleanup, errorCleanup, sessionEndCleanup];++ return true;+ } catch (error) {+ logger.error("Failed to start streaming recording", { error: error.message }, "streaming");++ let errorTitle = "Streaming Error";+ let errorDescription = `Failed to start streaming: ${error.message}`;++ if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {+ errorTitle = "Microphone Access Denied";+ errorDescription =+ "Please grant microphone permission in your system settings and try again.";+ } else if (error.code === "AUTH_EXPIRED" || error.code === "AUTH_REQUIRED") {+ errorTitle = "Sign-in Required";+ errorDescription =+ "Your OpenWhispr Cloud session is unavailable. Please sign in again from Settings.";+ }++ this.onError?.({+ title: errorTitle,+ description: errorDescription,+ });++ await this.cleanupStreaming();+ return false;+ }+ }++ async stopStreamingRecording() {+ if (!this.isStreaming) return false;++ const durationSeconds = this.recordingStartTime+ ? (Date.now() - this.recordingStartTime) / 1000+ : null;++ const t0 = performance.now();+ let finalText = this.streamingFinalText || "";++ // 1. Update UI immediately+ this.isRecording = false;+ this.recordingStartTime = null;+ this.onStateChange?.({ isRecording: false, isProcessing: true, isStreaming: false });++ // 2. Stop the processor — it flushes its remaining buffer on "stop".+ // Keep isStreaming TRUE so the port.onmessage handler forwards the flush to WebSocket.+ if (this.streamingProcessor) {+ try {+ this.streamingProcessor.port.postMessage("stop");+ this.streamingProcessor.disconnect();+ } catch (e) {+ // Ignore+ }+ this.streamingProcessor = null;+ }+ if (this.streamingSource) {+ try {+ this.streamingSource.disconnect();+ } catch (e) {+ // Ignore+ }+ this.streamingSource = null;+ }+ this.streamingAudioContext = null;+ if (this.streamingStream) {+ this.streamingStream.getTracks().forEach((track) => track.stop());+ this.streamingStream = null;+ }+ const tAudioCleanup = performance.now();++ // 3. Wait for flushed buffer to travel: port → main thread → IPC → WebSocket → server.+ // Then mark streaming done so no further audio is forwarded.+ await new Promise((resolve) => setTimeout(resolve, 120));+ this.isStreaming = false;++ // 4. ForceEndpoint finalizes any in-progress turn, then Terminate closes the session.+ // The server MUST process ALL remaining audio and send ALL Turn messages before+ // responding with Termination — so awaiting this guarantees we get every word.+ window.electronAPI.assemblyAiStreamingForceEndpoint?.();+ const tForceEndpoint = performance.now();++ await window.electronAPI.assemblyAiStreamingStop().catch((e) => {+ logger.debug("Streaming disconnect error", { error: e.message }, "streaming");+ });+ const tTerminate = performance.now();++ // 5. Brief wait for any in-transit IPC Turn events to reach the renderer.+ await new Promise((resolve) => setTimeout(resolve, 200));++ finalText = this.streamingFinalText || "";++ if (!finalText && this.streamingPartialText) {+ finalText = this.streamingPartialText;+ logger.debug("Using partial text as fallback", { textLength: finalText.length }, "streaming");+ }++ this.cleanupStreamingListeners();++ logger.info(+ "Streaming stop timing",+ {+ durationSeconds,+ audioCleanupMs: Math.round(tAudioCleanup - t0),+ flushWaitMs: Math.round(tForceEndpoint - tAudioCleanup),+ terminateRoundTripMs: Math.round(tTerminate - tForceEndpoint),+ totalStopMs: Math.round(tTerminate - t0),+ textLength: finalText.length,+ },+ "streaming"+ );++ const useReasoningModel = localStorage.getItem("useReasoningModel") === "true";+ if (useReasoningModel && finalText) {+ const reasoningStart = performance.now();+ const agentName = localStorage.getItem("agentName") || "";++ try {+ const reasonResult = await withSessionRefresh(async () => {+ const res = await window.electronAPI.cloudReason(finalText, {+ agentName,+ customDictionary: this.getCustomDictionaryArray(),+ language: localStorage.getItem("preferredLanguage") || "auto",+ });+ if (!res.success) {+ const err = new Error(res.error || "Cloud reasoning failed");+ err.code = res.code;+ throw err;+ }+ return res;+ });++ if (reasonResult.success && reasonResult.text) {+ finalText = reasonResult.text;+ }++ logger.info(+ "Streaming reasoning complete",+ {+ reasoningDurationMs: Math.round(performance.now() - reasoningStart),+ model: reasonResult.model,+ },+ "streaming"+ );+ } catch (reasonError) {+ logger.error(+ "Streaming reasoning failed, using raw text",+ { error: reasonError.message },+ "streaming"+ );+ }+ }++ if (finalText) {+ const tBeforePaste = performance.now();+ this.onTranscriptionComplete?.({+ success: true,+ text: finalText,+ source: "assemblyai-streaming",+ });++ logger.info(+ "Streaming total processing",+ {+ totalProcessingMs: Math.round(tBeforePaste - t0),+ hasReasoning: useReasoningModel,+ },+ "streaming"+ );+ }++ this.isProcessing = false;+ this.onStateChange?.({ isRecording: false, isProcessing: false, isStreaming: false });++ if (this.shouldUseStreaming()) {+ this.warmupStreamingConnection().catch((e) => {+ logger.debug("Background re-warm failed", { error: e.message }, "streaming");+ });+ }++ return true;+ }++ cleanupStreamingAudio() {+ if (this.streamingProcessor) {+ try {+ this.streamingProcessor.port.postMessage("stop");+ this.streamingProcessor.disconnect();+ } catch (e) {+ // Ignore+ }+ this.streamingProcessor = null;+ }++ if (this.streamingSource) {+ try {+ this.streamingSource.disconnect();+ } catch (e) {+ // Ignore+ }+ this.streamingSource = null;+ }++ this.streamingAudioContext = null;++ if (this.streamingStream) {+ this.streamingStream.getTracks().forEach((track) => track.stop());+ this.streamingStream = null;+ }++ this.isStreaming = false;+ }++ cleanupStreamingListeners() {+ for (const cleanup of this.streamingCleanupFns) {+ try {+ cleanup?.();+ } catch (e) {+ // Ignore cleanup errors+ }+ }+ this.streamingCleanupFns = [];+ this.streamingFinalText = "";+ this.streamingPartialText = "";+ this.streamingTextResolve = null;+ clearTimeout(this.streamingTextDebounce);+ this.streamingTextDebounce = null;+ }++ async cleanupStreaming() {+ this.cleanupStreamingAudio();+ this.cleanupStreamingListeners();+ }+cleanup() {+ if (this.isStreaming) {+ this.cleanupStreaming();+ }if (this.mediaRecorder?.state === "recording") {this.stopRecording();}+ if (this.persistentAudioContext && this.persistentAudioContext.state !== "closed") {+ this.persistentAudioContext.close().catch(() => {});+ this.persistentAudioContext = null;+ this.workletModuleLoaded = false;+ }+ try {+ window.electronAPI?.assemblyAiStreamingStop?.();+ } catch (e) {+ // Ignore errors during cleanup (page may be unloading)+ }this.onStateChange = null;this.onError = null;this.onTranscriptionComplete = null;+ this.onPartialTranscript = null;}}diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.jsindex c5e4c7142..65a9b0aa9 100644--- a/src/helpers/clipboard.js+++ b/src/helpers/clipboard.js@@ -5,9 +5,13 @@ const path = require("path");const fs = require("fs");const debugLogger = require("./debugLogger");-// Cache TTL constants - these mirror CACHE_CONFIG.AVAILABILITY_CHECK_TTL in src/config/constants.tsconst CACHE_TTL_MS = 30000;+// macOS accessibility: once granted, permissions persist across app sessions,+// so use a long TTL. Denied results re-check quickly so granting takes effect fast.+const ACCESSIBILITY_GRANTED_TTL_MS = 24 * 60 * 60 * 1000;+const ACCESSIBILITY_DENIED_TTL_MS = 5000;+const getLinuxDesktopEnv = () =>[process.env.XDG_CURRENT_DESKTOP, process.env.XDG_SESSION_DESKTOP, process.env.DESKTOP_SESSION].filter(Boolean)@@ -27,36 +31,32 @@ const getLinuxSessionInfo = () => {return { isWayland, xwaylandAvailable, desktopEnv, isGnome };};-// Platform-specific paste delays (ms before simulating keystroke)-// Each platform has different timing requirements based on their paste mechanism+// ms before simulating keystrokeconst PASTE_DELAYS = {- darwin: 50, // macOS: AppleScript keystroke is async, needs time for clipboard to settle- win32_nircmd: 30, // Windows nircmd: give clipboard time to sync- win32_pwsh: 40, // Windows PowerShell: give clipboard time to sync- linux: 50, // Linux: Allow time for focus to return to target window on X11+ darwin: 120,+ win32_nircmd: 30,+ win32_pwsh: 40,+ linux: 50,};-// Platform-specific clipboard restoration delays (ms after paste completes)-// Ensures paste is fully processed before restoring original clipboard content+// ms after paste completes before restoring clipboardconst RESTORE_DELAYS = {- darwin: 100, // macOS: AppleScript needs time to complete keystroke- win32_nircmd: 80, // Windows nircmd: allow time for paste processing- win32_pwsh: 80, // Windows PowerShell: allow time for paste processing- linux: 200, // Linux: X11 event queue processing takes longer+ darwin: 450,+ win32_nircmd: 80,+ win32_pwsh: 80,+ linux: 200,};-// Legacy constant for backward compatibility (used by macOS)-const PASTE_DELAY_MS = PASTE_DELAYS.darwin;-class ClipboardManager {constructor() {this.accessibilityCache = { value: null, expiresAt: 0 };this.commandAvailabilityCache = new Map();this.nircmdPath = null;this.nircmdChecked = false;+ this.fastPastePath = null;+ this.fastPasteChecked = false;}- // Get path to nircmd.exe (Windows only)getNircmdPath() {if (this.nircmdChecked) {return this.nircmdPath;@@ -68,11 +68,8 @@ class ClipboardManager {return null;}- // Try multiple paths for nircmd.execonst possiblePaths = [- // Production: extraResourcespath.join(process.resourcesPath, "bin", "nircmd.exe"),- // Development: resources/binpath.join(__dirname, "..", "..", "resources", "bin", "nircmd.exe"),path.join(process.cwd(), "resources", "bin", "nircmd.exe"),];@@ -104,7 +101,54 @@ class ClipboardManager {};}- // Safe logging method - only log in development+ resolveFastPasteBinary() {+ if (this.fastPasteChecked) {+ return this.fastPastePath;+ }+ this.fastPasteChecked = true;++ if (process.platform !== "darwin") {+ return null;+ }++ const candidates = new Set([+ path.join(__dirname, "..", "..", "resources", "bin", "macos-fast-paste"),+ path.join(__dirname, "..", "..", "resources", "macos-fast-paste"),+ ]);++ if (process.resourcesPath) {+ [+ path.join(process.resourcesPath, "macos-fast-paste"),+ path.join(process.resourcesPath, "bin", "macos-fast-paste"),+ path.join(process.resourcesPath, "resources", "macos-fast-paste"),+ path.join(process.resourcesPath, "resources", "bin", "macos-fast-paste"),+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "macos-fast-paste"),+ path.join(+ process.resourcesPath,+ "app.asar.unpacked",+ "resources",+ "bin",+ "macos-fast-paste"+ ),+ ].forEach((candidate) => candidates.add(candidate));+ }++ for (const candidate of candidates) {+ try {+ const stats = fs.statSync(candidate);+ if (stats.isFile()) {+ fs.accessSync(candidate, fs.constants.X_OK);+ this.fastPastePath = candidate;+ return candidate;+ }+ } catch {+ continue;+ }+ }++ return null;+ }+safeLog(...args) {if (process.env.NODE_ENV === "development") {try {@@ -118,7 +162,6 @@ class ClipboardManager {}}- // Check if a command exists on the system (cached)commandExists(cmd) {const now = Date.now();const cached = this.commandAvailabilityCache.get(cmd);@@ -144,26 +187,23 @@ class ClipboardManager {}}- async pasteText(text) {+ async pasteText(text, options = {}) {const startTime = Date.now();const platform = process.platform;let method = "unknown";try {- // Save original clipboard content firstconst originalClipboard = clipboard.readText();this.safeLog("💾 Saved original clipboard content:",originalClipboard.substring(0, 50) + "...");- // Copy text to clipboard first - this always worksclipboard.writeText(text);this.safeLog("📋 Text copied to clipboard:", text.substring(0, 50) + "...");if (platform === "darwin") {- method = "applescript";- // Check accessibility permissions first+ method = this.resolveFastPasteBinary() ? "cgevent" : "applescript";this.safeLog("🔍 Checking accessibility permissions for paste operation...");const hasPermissions = await this.checkAccessibilityPermissions();@@ -175,7 +215,7 @@ class ClipboardManager {}this.safeLog("✅ Permissions granted, attempting to paste...");- await this.pasteMacOS(originalClipboard);+ await this.pasteMacOS(originalClipboard, options);} else if (platform === "win32") {const nircmdPath = this.getNircmdPath();method = nircmdPath ? "nircmd" : "powershell";@@ -185,7 +225,6 @@ class ClipboardManager {await this.pasteLinux(originalClipboard);}- // Log successful paste operation timingthis.safeLog("✅ Paste operation complete", {platform,method,@@ -203,13 +242,19 @@ class ClipboardManager {}}- async pasteMacOS(originalClipboard) {+ async pasteMacOS(originalClipboard, options = {}) {+ const fastPasteBinary = this.resolveFastPasteBinary();+ const useFastPaste = !!fastPasteBinary;+ const pasteDelay = options.fromStreaming ? (useFastPaste ? 15 : 50) : PASTE_DELAYS.darwin;+return new Promise((resolve, reject) => {setTimeout(() => {- const pasteProcess = spawn("osascript", [- "-e",- 'tell application "System Events" to keystroke "v" using command down',- ]);+ const pasteProcess = useFastPaste+ ? spawn(fastPasteBinary)+ : spawn("osascript", [+ "-e",+ 'tell application "System Events" to keystroke "v" using command down',+ ]);let errorOutput = "";let hasTimedOut = false;@@ -220,21 +265,26 @@ class ClipboardManager {pasteProcess.on("close", (code) => {if (hasTimedOut) return;-- // Clear timeout firstclearTimeout(timeoutId);-- // Clean up the process referencepasteProcess.removeAllListeners();if (code === 0) {- this.safeLog("✅ Text pasted successfully via Cmd+V simulation");+ this.safeLog(`Text pasted successfully via ${useFastPaste ? "CGEvent" : "osascript"}`);setTimeout(() => {clipboard.writeText(originalClipboard);- this.safeLog("🔄 Original clipboard content restored");- }, 100);+ }, RESTORE_DELAYS.darwin);resolve();+ } else if (useFastPaste) {+ this.safeLog(+ code === 2+ ? "CGEvent binary lacks accessibility trust, falling back to osascript"+ : `CGEvent paste failed (code ${code}), falling back to osascript`+ );+ this.fastPasteChecked = true;+ this.fastPastePath = null;+ this.pasteMacOSWithOsascript(originalClipboard).then(resolve).catch(reject);} else {+ this.accessibilityCache = { value: null, expiresAt: 0 };const errorMsg = `Paste failed (code ${code}). Text is copied to clipboard - please paste manually with Cmd+V.`;reject(new Error(errorMsg));}@@ -244,8 +294,16 @@ class ClipboardManager {if (hasTimedOut) return;clearTimeout(timeoutId);pasteProcess.removeAllListeners();- const errorMsg = `Paste command failed: ${error.message}. Text is copied to clipboard - please paste manually with Cmd+V.`;- reject(new Error(errorMsg));++ if (useFastPaste) {+ this.safeLog("CGEvent paste error, falling back to osascript");+ this.fastPasteChecked = true;+ this.fastPastePath = null;+ this.pasteMacOSWithOsascript(originalClipboard).then(resolve).catch(reject);+ } else {+ const errorMsg = `Paste command failed: ${error.message}. Text is copied to clipboard - please paste manually with Cmd+V.`;+ reject(new Error(errorMsg));+ }});const timeoutId = setTimeout(() => {@@ -256,12 +314,59 @@ class ClipboardManager {"Paste operation timed out. Text is copied to clipboard - please paste manually with Cmd+V.";reject(new Error(errorMsg));}, 3000);- }, PASTE_DELAY_MS);+ }, pasteDelay);+ });+ }++ async pasteMacOSWithOsascript(originalClipboard) {+ return new Promise((resolve, reject) => {+ const pasteProcess = spawn("osascript", [+ "-e",+ 'tell application "System Events" to keystroke "v" using command down',+ ]);++ let hasTimedOut = false;++ pasteProcess.on("close", (code) => {+ if (hasTimedOut) return;+ clearTimeout(timeoutId);+ pasteProcess.removeAllListeners();++ if (code === 0) {+ this.safeLog("Text pasted successfully via osascript fallback");+ setTimeout(() => {+ clipboard.writeText(originalClipboard);+ }, RESTORE_DELAYS.darwin);+ resolve();+ } else {+ this.accessibilityCache = { value: null, expiresAt: 0 };+ const errorMsg = `Paste failed (code ${code}). Text is copied to clipboard - please paste manually with Cmd+V.`;+ reject(new Error(errorMsg));+ }+ });++ pasteProcess.on("error", (error) => {+ if (hasTimedOut) return;+ clearTimeout(timeoutId);+ pasteProcess.removeAllListeners();+ const errorMsg = `Paste command failed: ${error.message}. Text is copied to clipboard - please paste manually with Cmd+V.`;+ reject(new Error(errorMsg));+ });++ const timeoutId = setTimeout(() => {+ hasTimedOut = true;+ killProcess(pasteProcess, "SIGKILL");+ pasteProcess.removeAllListeners();+ reject(+ new Error(+ "Paste operation timed out. Text is copied to clipboard - please paste manually with Cmd+V."+ )+ );+ }, 3000);});}async pasteWindows(originalClipboard) {- // Try nircmd first if available, fallback to PowerShellconst nircmdPath = this.getNircmdPath();if (nircmdPath) {@@ -349,10 +454,6 @@ class ClipboardManager {this.safeLog(`🪟 PowerShell paste starting (delay: ${pasteDelay}ms)`);- // Optimized PowerShell command:- // - Uses [void] to suppress output (faster)- // - WindowStyle Hidden to prevent window flash- // - ExecutionPolicy Bypass to skip policy checksconst pasteProcess = spawn("powershell.exe", ["-NoProfile","-NonInteractive",@@ -454,8 +555,7 @@ class ClipboardManager {"clipboard");- // Get the active window ID before any focus changes- // This is critical for X11 where our window might briefly take focus+ // Capture target window before our window takes focusconst getXdotoolActiveWindow = () => {if (!xdotoolExists || (isWayland && !xwaylandAvailable)) {return null;@@ -490,14 +590,11 @@ class ClipboardManager {}};- // Capture the target window ID before we potentially lose focusconst targetWindowId = getXdotoolActiveWindow();const xdotoolWindowClass = getXdotoolWindowClass(targetWindowId);- // Detect if the focused window is a terminal emulator- // Terminals use Ctrl+Shift+V for paste (since Ctrl+V/C are used for process control)+ // Terminals use Ctrl+Shift+V instead of Ctrl+Vconst isTerminal = () => {- // Common terminal emulator class namesconst terminalClasses = ["konsole","gnome-terminal",@@ -525,13 +622,10 @@ class ClipboardManager {}try {- // Try kdotool for KDE Wayland (if available)if (this.commandExists("kdotool")) {- // First get the active window IDconst windowIdResult = spawnSync("kdotool", ["getactivewindow"]);if (windowIdResult.status === 0) {const windowId = windowIdResult.stdout.toString().trim();- // Then get the window class nameconst classResult = spawnSync("kdotool", ["getwindowclassname", windowId]);if (classResult.status === 0) {const className = classResult.stdout.toString().toLowerCase().trim();@@ -543,8 +637,8 @@ class ClipboardManager {}}}- } catch (error) {- // Silent fallback - if detection fails, assume non-terminal+ } catch {+ // Detection failed, assume non-terminal}return false;};@@ -556,9 +650,7 @@ class ClipboardManager {const canUseYdotool = isWayland;const canUseXdotool = isWayland ? xwaylandAvailable && xdotoolExists : xdotoolExists;- // Define paste tools in preference order based on display server- // For X11, use windowactivate to ensure correct window receives the keystroke- // This is critical because OpenWhispr's window may briefly take focus during transcription+ // windowactivate ensures the target window (not ours) receives the keystrokeconst xdotoolArgs = targetWindowId? ["windowactivate", "--sync", targetWindowId, "key", pasteKeys]: ["key", pasteKeys];@@ -569,11 +661,10 @@ class ClipboardManager {);}- // ydotool uses key codes: 29=LeftCtrl, 42=LeftShift, 47=V- // Format: keycode:1 (press), keycode:0 (release)+ // ydotool key codes: 29=Ctrl, 42=Shift, 47=V; :1=press, :0=releaseconst ydotoolArgs = inTerminal- ? ["key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"] // Ctrl+Shift+V- : ["key", "29:1", "47:1", "47:0", "29:0"]; // Ctrl+V+ ? ["key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"]+ : ["key", "29:1", "47:1", "47:0", "29:0"];const candidates = [...(canUseWtype@@ -590,7 +681,6 @@ class ClipboardManager {...(canUseYdotool ? [{ cmd: "ydotool", args: ydotoolArgs }] : []),];- // Filter to only available tools (this.commandExists is already cached)const available = candidates.filter((c) => this.commandExists(c.cmd));debugLogger.debug(@@ -606,10 +696,8 @@ class ClipboardManager {"clipboard");- // Attempt paste with a specific toolconst pasteWith = (tool) =>new Promise((resolve, reject) => {- // Add small delay on X11 to allow focus to settleconst delay = isWayland ? 0 : PASTE_DELAYS.linux;setTimeout(() => {@@ -648,7 +736,7 @@ class ClipboardManager {},"clipboard");- }, 2000); // Increased timeout to 2s for windowactivate --sync+ }, 2000);proc.on("close", (code) => {if (timedOut) return reject(new Error(`Paste with ${tool.cmd} timed out`));@@ -656,8 +744,6 @@ class ClipboardManager {if (code === 0) {debugLogger.debug("Paste successful", { cmd: tool.cmd }, "clipboard");- // Restore original clipboard after successful paste- // Delay allows time for X11 to process paste event before clipboard is overwrittensetTimeout(() => clipboard.writeText(originalClipboard), RESTORE_DELAYS.linux);resolve();} else {@@ -697,7 +783,6 @@ class ClipboardManager {}, delay);});- // Try each available tool in orderconst failedAttempts = [];for (const tool of available) {try {@@ -720,9 +805,7 @@ class ClipboardManager {debugLogger.error("All paste tools failed", { failedAttempts }, "clipboard");- // Fallback for terminals: use xdotool type to directly input text- // This bypasses clipboard paste entirely and is more reliable for terminal emulators- // that may have issues with Ctrl+Shift+V keystroke simulation+ // xdotool type fallback for terminals where Ctrl+Shift+V simulation failsif (inTerminal && xdotoolExists && !isWayland) {debugLogger.debug("Trying xdotool type fallback for terminal",@@ -755,7 +838,6 @@ class ClipboardManager {}}- // All tools failed - create specific error for renderer to handleconst failureSummary =failedAttempts.length > 0? `\n\nAttempted tools: ${failedAttempts.map((f) => `${f.tool} (${f.error})`).join(", ")}`@@ -825,8 +907,6 @@ class ClipboardManager {}return new Promise((resolve) => {- // Check accessibility permissions-const testProcess = spawn("osascript", ["-e",'tell application "System Events" to get name of first process',@@ -847,7 +927,8 @@ class ClipboardManager {const allowed = code === 0;this.accessibilityCache = {value: allowed,- expiresAt: Date.now() + CACHE_TTL_MS,+ expiresAt:+ Date.now() + (allowed ? ACCESSIBILITY_GRANTED_TTL_MS : ACCESSIBILITY_DENIED_TTL_MS),};if (!allowed) {this.showAccessibilityDialog(testError);@@ -858,7 +939,7 @@ class ClipboardManager {testProcess.on("error", (error) => {this.accessibilityCache = {value: false,- expiresAt: Date.now() + CACHE_TTL_MS,+ expiresAt: Date.now() + ACCESSIBILITY_DENIED_TTL_MS,};resolve(false);});@@ -920,9 +1001,7 @@ Would you like to open System Settings now?`;}});- permissionDialog.on("error", (error) => {- // Permission dialog error - user will need to manually grant permissions- });+ permissionDialog.on("error", () => {});}openSystemSettings() {@@ -950,11 +1029,8 @@ Would you like to open System Settings now?`;}});} else {- // All settings commands failed, try fallbackspawn("open", ["-a", "System Preferences"]).on("error", () => {- spawn("open", ["-a", "System Settings"]).on("error", () => {- // Could not open settings app- });+ spawn("open", ["-a", "System Settings"]).on("error", () => {});});}};@@ -962,43 +1038,35 @@ Would you like to open System Settings now?`;tryNextCommand();}+ preWarmAccessibility() {+ if (process.platform !== "darwin") return;+ this.checkAccessibilityPermissions().catch(() => {});+ this.resolveFastPasteBinary();+ }+async readClipboard() {- try {- const text = clipboard.readText();- return text;- } catch (error) {- throw error;- }+ return clipboard.readText();}async writeClipboard(text) {- try {- clipboard.writeText(text);- return { success: true };- } catch (error) {- throw error;- }+ clipboard.writeText(text);+ return { success: true };}- /**- * Check availability of paste tools on the current platform.- * Returns platform-specific information about paste capability.- */checkPasteTools() {const platform = process.platform;- // macOS uses AppleScript - always available, but needs accessibility permissionif (platform === "darwin") {+ const fastPaste = this.resolveFastPasteBinary();return {platform: "darwin",available: true,- method: "applescript",+ method: fastPaste ? "cgevent" : "applescript",requiresPermission: true,tools: [],};}- // Windows uses PowerShell SendKeys - always availableif (platform === "win32") {return {platform: "win32",@@ -1009,10 +1077,7 @@ Would you like to open System Settings now?`;};}- // Linux - check for available paste toolsconst { isWayland, xwaylandAvailable, isGnome } = getLinuxSessionInfo();-- // Check which tools are availableconst tools = [];const canUseWtype = isWayland && !isGnome;const canUseYdotool = isWayland;diff --git a/src/helpers/devServerManager.js b/src/helpers/devServerManager.jsindex e7a14b5e5..ba728558b 100644--- a/src/helpers/devServerManager.js+++ b/src/helpers/devServerManager.js@@ -1,4 +1,19 @@-const DEV_SERVER_PORT = 5174;+const DEFAULT_DEV_SERVER_PORT = 5183;+const parseDevServerPort = () => {+ const raw =+ process.env.OPENWHISPR_DEV_SERVER_PORT ||+ process.env.VITE_DEV_SERVER_PORT ||+ String(DEFAULT_DEV_SERVER_PORT);+ const parsed = Number(raw);++ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {+ return DEFAULT_DEV_SERVER_PORT;+ }++ return parsed;+};++const DEV_SERVER_PORT = parseDevServerPort();const DEV_SERVER_URL = `http://localhost:${DEV_SERVER_PORT}/`;class DevServerManager {diff --git a/src/helpers/environment.js b/src/helpers/environment.jsindex be65d3872..26ae89f65 100644--- a/src/helpers/environment.js+++ b/src/helpers/environment.js@@ -2,35 +2,43 @@ const path = require("path");const fs = require("fs");const { app } = require("electron");+const PERSISTED_KEYS = [+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "GEMINI_API_KEY",+ "GROQ_API_KEY",+ "CUSTOM_TRANSCRIPTION_API_KEY",+ "CUSTOM_REASONING_API_KEY",+ "LOCAL_TRANSCRIPTION_PROVIDER",+ "PARAKEET_MODEL",+ "LOCAL_WHISPER_MODEL",+ "REASONING_PROVIDER",+ "LOCAL_REASONING_MODEL",+ "DICTATION_KEY",+ "ACTIVATION_MODE",+];+class EnvironmentManager {constructor() {this.loadEnvironmentVariables();}loadEnvironmentVariables() {- // In production, try multiple locations for .env file+ // Loaded in priority order — dotenv won't override, so first file wins per variableconst possibleEnvPaths = [- // Development path- path.join(__dirname, "..", ".env"),- // Production packaged app paths+ path.join(app.getPath("userData"), ".env"),+ path.join(__dirname, "..", "..", ".env"), // Developmentpath.join(process.resourcesPath, ".env"),path.join(process.resourcesPath, "app.asar.unpacked", ".env"),- path.join(app.getPath("userData"), ".env"), // User data directory- // Legacy paths- path.join(process.resourcesPath, "app", ".env"),+ path.join(process.resourcesPath, "app", ".env"), // Legacy];for (const envPath of possibleEnvPaths) {try {if (fs.existsSync(envPath)) {- const result = require("dotenv").config({ path: envPath });- if (!result.error) {- break;- }+ require("dotenv").config({ path: envPath });}- } catch (error) {- // Continue to next path- }+ } catch (error) {}}}@@ -91,14 +99,24 @@ class EnvironmentManager {return this._saveKey("CUSTOM_REASONING_API_KEY", key);}- // Hotkey persistence for reliable startupgetDictationKey() {return this._getKey("DICTATION_KEY");}saveDictationKey(key) {const result = this._saveKey("DICTATION_KEY", key);- // Persist to .env file immediately for reliable startup+ this.saveAllKeysToEnvFile();+ return result;+ }++ getActivationMode() {+ const mode = this._getKey("ACTIVATION_MODE");+ return mode === "push" ? "push" : "tap";+ }++ saveActivationMode(mode) {+ const validMode = mode === "push" ? "push" : "tap";+ const result = this._saveKey("ACTIVATION_MODE", validMode);this.saveAllKeysToEnvFile();return result;}@@ -112,7 +130,6 @@ OPENAI_API_KEY=${apiKey}`;fs.writeFileSync(envPath, envContent, "utf8");-require("dotenv").config({ path: envPath });return { success: true, path: envPath };@@ -121,51 +138,15 @@ OPENAI_API_KEY=${apiKey}saveAllKeysToEnvFile() {const envPath = path.join(app.getPath("userData"), ".env");- // Build env content with all current keys- let envContent = `# OpenWhispr Environment Variables-# This file was created automatically for production use-`;+ let envContent = "# OpenWhispr Environment Variables\n";- if (process.env.OPENAI_API_KEY) {- envContent += `OPENAI_API_KEY=${process.env.OPENAI_API_KEY}\n`;- }- if (process.env.ANTHROPIC_API_KEY) {- envContent += `ANTHROPIC_API_KEY=${process.env.ANTHROPIC_API_KEY}\n`;- }- if (process.env.GEMINI_API_KEY) {- envContent += `GEMINI_API_KEY=${process.env.GEMINI_API_KEY}\n`;- }- if (process.env.GROQ_API_KEY) {- envContent += `GROQ_API_KEY=${process.env.GROQ_API_KEY}\n`;- }- if (process.env.CUSTOM_TRANSCRIPTION_API_KEY) {- envContent += `CUSTOM_TRANSCRIPTION_API_KEY=${process.env.CUSTOM_TRANSCRIPTION_API_KEY}\n`;- }- if (process.env.CUSTOM_REASONING_API_KEY) {- envContent += `CUSTOM_REASONING_API_KEY=${process.env.CUSTOM_REASONING_API_KEY}\n`;- }- if (process.env.LOCAL_TRANSCRIPTION_PROVIDER) {- envContent += `LOCAL_TRANSCRIPTION_PROVIDER=${process.env.LOCAL_TRANSCRIPTION_PROVIDER}\n`;- }- if (process.env.PARAKEET_MODEL) {- envContent += `PARAKEET_MODEL=${process.env.PARAKEET_MODEL}\n`;- }- if (process.env.LOCAL_WHISPER_MODEL) {- envContent += `LOCAL_WHISPER_MODEL=${process.env.LOCAL_WHISPER_MODEL}\n`;- }- if (process.env.REASONING_PROVIDER) {- envContent += `REASONING_PROVIDER=${process.env.REASONING_PROVIDER}\n`;- }- if (process.env.LOCAL_REASONING_MODEL) {- envContent += `LOCAL_REASONING_MODEL=${process.env.LOCAL_REASONING_MODEL}\n`;- }- if (process.env.DICTATION_KEY) {- envContent += `DICTATION_KEY=${process.env.DICTATION_KEY}\n`;+ for (const key of PERSISTED_KEYS) {+ if (process.env[key]) {+ envContent += `${key}=${process.env[key]}\n`;+ }}fs.writeFileSync(envPath, envContent, "utf8");-- // Reload the env filerequire("dotenv").config({ path: envPath });return { success: true, path: envPath };diff --git a/src/helpers/globeKeyManager.js b/src/helpers/globeKeyManager.jsindex 08d721e0a..678ee9452 100644--- a/src/helpers/globeKeyManager.js+++ b/src/helpers/globeKeyManager.js@@ -47,6 +47,21 @@ class GlobeKeyManager extends EventEmitter {this.emit("globe-down");} else if (line === "FN_UP") {this.emit("globe-up");+ } else if (line.startsWith("RIGHT_MOD_DOWN:")) {+ const modifier = line.replace("RIGHT_MOD_DOWN:", "").trim();+ if (modifier) {+ this.emit("right-modifier-down", modifier);+ }+ } else if (line.startsWith("RIGHT_MOD_UP:")) {+ const modifier = line.replace("RIGHT_MOD_UP:", "").trim();+ if (modifier) {+ this.emit("right-modifier-up", modifier);+ }+ } else if (line.startsWith("MODIFIER_UP:")) {+ const modifier = line.replace("MODIFIER_UP:", "").trim().toLowerCase();+ if (modifier) {+ this.emit("modifier-up", modifier);+ }}});});diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex 33c00cf2d..f98db1af3 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -5,20 +5,23 @@ const GnomeShortcutManager = require("./gnomeShortcut");// Delay to ensure localStorage is accessible after window loadconst HOTKEY_REGISTRATION_DELAY_MS = 1000;+// Right-side single modifiers are handled by native listeners, not globalShortcut+const RIGHT_SIDE_MODIFIER_PATTERN =+ /^Right(Control|Ctrl|Alt|Option|Shift|Command|Cmd|Super|Meta|Win)$/i;++function isRightSideModifier(hotkey) {+ return RIGHT_SIDE_MODIFIER_PATTERN.test(hotkey);+}+// Suggested alternative hotkeys when registration failsconst SUGGESTED_HOTKEYS = {single: ["F8", "F9", "F10", "Pause", "ScrollLock"],- compound: [- "CommandOrControl+Shift+Space",- "CommandOrControl+Shift+D",- "Alt+Space",- "CommandOrControl+`",- ],+ compound: ["Control+Super", "Control+Alt", "Control+Shift+Space", "Alt+F7"],};class HotkeyManager {constructor() {- this.currentHotkey = "`";+ this.currentHotkey = process.platform === "darwin" ? "GLOBE" : "Control+Super";this.isInitialized = false;this.isListeningMode = false;this.gnomeManager = null;@@ -44,18 +47,6 @@ class HotkeyManager {};}- if (process.platform === "win32") {- // Windows reserves certain keys- const winReserved = ["PrintScreen", "Win", "Super"];- if (winReserved.some((k) => hotkey.includes(k))) {- return {- reason: "os_reserved",- message: `"${hotkey}" is reserved by Windows.`,- suggestions: this.getSuggestions(hotkey),- };- }- }-if (process.platform === "linux") {// Linux DE's often reserve Super/Meta combinationsif (hotkey.includes("Super") || hotkey.includes("Meta")) {@@ -76,14 +67,20 @@ class HotkeyManager {getSuggestions(failedHotkey) {const isCompound = failedHotkey.includes("+");- const suggestions = isCompound- ? [...SUGGESTED_HOTKEYS.compound]- : [...SUGGESTED_HOTKEYS.single];+ let suggestions = isCompound ? [...SUGGESTED_HOTKEYS.compound] : [...SUGGESTED_HOTKEYS.single];++ if (process.platform === "darwin" && isCompound) {+ suggestions = ["Control+Alt", "Alt+Command", "Command+Shift+Space"];+ } else if (process.platform === "win32" && isCompound) {+ suggestions = ["Control+Super", "Control+Alt", "Control+Shift+K"];+ } else if (process.platform === "linux" && isCompound) {+ suggestions = ["Control+Super", "Control+Shift+K", "Super+Shift+R"];+ }return suggestions.filter((s) => s !== failedHotkey).slice(0, 3);}- setupShortcuts(hotkey = "`", callback) {+ setupShortcuts(hotkey = "Control+Super", callback) {if (!callback) {throw new Error("Callback function is required for hotkey setup");}@@ -93,12 +90,14 @@ class HotkeyManager {debugLogger.log(`[HotkeyManager] Current hotkey: "${this.currentHotkey}"`);// If we're already using this hotkey AND it's actually registered, return success- // Note: We need to check isRegistered because on first run, currentHotkey is set to "`"- // but it's not actually registered yet+ // Note: We need to check isRegistered because on first run, currentHotkey is set to the+ // default value but it's not actually registered yet.+ const checkAccelerator = hotkey.startsWith("Fn+") ? hotkey.slice(3) : hotkey;if (hotkey === this.currentHotkey &&hotkey !== "GLOBE" &&- globalShortcut.isRegistered(hotkey)+ !isRightSideModifier(hotkey) &&+ globalShortcut.isRegistered(checkAccelerator)) {debugLogger.log(`[HotkeyManager] Hotkey "${hotkey}" is already the current hotkey and registered, no change needed`@@ -106,10 +105,17 @@ class HotkeyManager {return { success: true, hotkey };}- // Unregister the previous hotkey (if it's not GLOBE, which doesn't use globalShortcut)- if (this.currentHotkey && this.currentHotkey !== "GLOBE") {- debugLogger.log(`[HotkeyManager] Unregistering previous hotkey: "${this.currentHotkey}"`);- globalShortcut.unregister(this.currentHotkey);+ // Unregister the previous hotkey (skip GLOBE and right-side modifiers - they use native listeners)+ if (+ this.currentHotkey &&+ this.currentHotkey !== "GLOBE" &&+ !isRightSideModifier(this.currentHotkey)+ ) {+ const prevAccelerator = this.currentHotkey.startsWith("Fn+")+ ? this.currentHotkey.slice(3)+ : this.currentHotkey;+ debugLogger.log(`[HotkeyManager] Unregistering previous hotkey: "${prevAccelerator}"`);+ globalShortcut.unregister(prevAccelerator);}try {@@ -126,14 +132,29 @@ class HotkeyManager {return { success: true, hotkey };}- const alreadyRegistered = globalShortcut.isRegistered(hotkey);- debugLogger.log(`[HotkeyManager] Is "${hotkey}" already registered? ${alreadyRegistered}`);+ // Right-side single modifiers are handled by native listeners (Swift/C), not globalShortcut+ if (isRightSideModifier(hotkey)) {+ this.currentHotkey = hotkey;+ debugLogger.log(+ `[HotkeyManager] Right-side modifier "${hotkey}" set - using native listener`+ );+ return { success: true, hotkey };+ }++ // Fn+ prefix is a UI-level distinction (user holds Fn to get real F-keys on macOS).+ // At the OS/Electron level, the accelerator is just the key without Fn.+ const accelerator = hotkey.startsWith("Fn+") ? hotkey.slice(3) : hotkey;++ const alreadyRegistered = globalShortcut.isRegistered(accelerator);+ debugLogger.log(+ `[HotkeyManager] Is "${accelerator}" already registered? ${alreadyRegistered}`+ );if (process.platform === "linux") {- globalShortcut.unregister(hotkey);+ globalShortcut.unregister(accelerator);}- const success = globalShortcut.register(hotkey, callback);+ const success = globalShortcut.register(accelerator, callback);debugLogger.log(`[HotkeyManager] Registration result for "${hotkey}": ${success}`);if (success) {@@ -141,7 +162,7 @@ class HotkeyManager {debugLogger.log(`[HotkeyManager] Hotkey "${hotkey}" registered successfully`);return { success: true, hotkey };} else {- const failureInfo = this.getFailureReason(hotkey);+ const failureInfo = this.getFailureReason(accelerator);console.error(`[HotkeyManager] Failed to register hotkey: ${hotkey}`, failureInfo);debugLogger.log(`[HotkeyManager] Registration failed:`, failureInfo);@@ -206,7 +227,7 @@ class HotkeyManager {const savedHotkey = await mainWindow.webContents.executeJavaScript(`localStorage.getItem("dictationKey") || ""`);- const hotkey = savedHotkey && savedHotkey.trim() !== "" ? savedHotkey : "Alt+R";+ const hotkey = savedHotkey && savedHotkey.trim() !== "" ? savedHotkey : "Control+Super";const gnomeHotkey = GnomeShortcutManager.convertToGnomeFormat(hotkey);const success = await this.gnomeManager.registerKeybinding(gnomeHotkey);@@ -259,7 +280,9 @@ class HotkeyManager {// If we found a hotkey in localStorage but not in env, migrate itif (savedHotkey && savedHotkey.trim() !== "") {process.env.DICTATION_KEY = savedHotkey;- debugLogger.log(`[HotkeyManager] Migrated hotkey "${savedHotkey}" from localStorage to env`);+ debugLogger.log(+ `[HotkeyManager] Migrated hotkey "${savedHotkey}" from localStorage to env`+ );}}@@ -273,7 +296,7 @@ class HotkeyManager {this.notifyHotkeyFailure(savedHotkey, result);}- const defaultHotkey = process.platform === "darwin" ? "GLOBE" : "`";+ const defaultHotkey = process.platform === "darwin" ? "GLOBE" : "Control+Super";if (defaultHotkey === "GLOBE") {this.currentHotkey = "GLOBE";@@ -292,7 +315,7 @@ class HotkeyManager {debugLogger.log(`[HotkeyManager] Default hotkey "${defaultHotkey}" failed, trying fallbacks...`);- const fallbackHotkeys = ["F8", "F9", "CommandOrControl+Shift+Space"];+ const fallbackHotkeys = ["F8", "F9", "Control+Shift+Space"];for (const fallback of fallbackHotkeys) {const fallbackResult = this.setupShortcuts(fallback, callback);@@ -343,7 +366,9 @@ class HotkeyManager {return false;}} else {- debugLogger.warn("[HotkeyManager] Main window not available for saving hotkey to localStorage");+ debugLogger.warn(+ "[HotkeyManager] Main window not available for saving hotkey to localStorage"+ );return false;}}@@ -363,7 +388,7 @@ class HotkeyManager {this.mainWindow.webContents.send("hotkey-registration-failed", {hotkey,error: result?.error || `Could not register "${hotkey}"`,- suggestions: result?.suggestions || ["F8", "F9", "CommandOrControl+Shift+Space"],+ suggestions: result?.suggestions || ["F8", "F9", "Control+Shift+Space"],});}}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 8f5045a99..ded388874 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1,9 +1,13 @@const { ipcMain, app, shell, BrowserWindow } = require("electron");const path = require("path");+const http = require("http");+const https = require("https");+const crypto = require("crypto");const AppUtils = require("../utils");const debugLogger = require("./debugLogger");const { getSystemPrompt } = require("./prompts");const GnomeShortcutManager = require("./gnomeShortcut");+const AssemblyAiStreaming = require("./assemblyAiStreaming");class IPCHandlers {constructor(managers) {@@ -15,6 +19,8 @@ class IPCHandlers {this.windowManager = managers.windowManager;this.updateManager = managers.updateManager;this.windowsKeyManager = managers.windowsKeyManager;+ this.sessionId = crypto.randomUUID();+ this.assemblyAiStreaming = null;this.setupHandlers();}@@ -97,6 +103,13 @@ class IPCHandlers {this.windowManager.showDictationPanel();});+ ipcMain.handle("force-stop-dictation", () => {+ if (this.windowManager?.forceStopMacCompoundPush) {+ this.windowManager.forceStopMacCompoundPush("manual");+ }+ return { success: true };+ });+ipcMain.handle("set-main-window-interactivity", (event, shouldCapture) => {this.windowManager.setMainWindowInteractivity(Boolean(shouldCapture));return { success: true };@@ -168,8 +181,8 @@ class IPCHandlers {});// Clipboard handlers- ipcMain.handle("paste-text", async (event, text) => {- return this.clipboardManager.pasteText(text);+ ipcMain.handle("paste-text", async (event, text, options) => {+ return this.clipboardManager.pasteText(text, options);});ipcMain.handle("read-clipboard", async (event) => {@@ -698,6 +711,14 @@ class IPCHandlers {return this.environmentManager.saveDictationKey(key);});+ ipcMain.handle("get-activation-mode", async () => {+ return this.environmentManager.getActivationMode();+ });++ ipcMain.handle("save-activation-mode", async (event, mode) => {+ return this.environmentManager.saveActivationMode(mode);+ });+ipcMain.handle("save-anthropic-key", async (event, key) => {return this.environmentManager.saveAnthropicKey(key);});@@ -745,6 +766,7 @@ class IPCHandlers {const result = await LocalReasoningService.processText(text, modelId, agentName, {...config,customDictionary: this._getDictionarySafe(),+ language: config?.language,});return { success: true, text: result };} catch (error) {@@ -763,7 +785,11 @@ class IPCHandlers {throw new Error("Anthropic API key not configured");}- const systemPrompt = getSystemPrompt(agentName, this._getDictionarySafe());+ const systemPrompt = getSystemPrompt(+ agentName,+ this._getDictionarySafe(),+ config?.language+ );const userPrompt = text;if (!modelId) {@@ -798,8 +824,8 @@ class IPCHandlers {}throw new Error(errorData.error?.message ||- errorData.error ||- `Anthropic API error: ${response.status}`+ errorData.error ||+ `Anthropic API error: ${response.status}`);}@@ -950,6 +976,348 @@ class IPCHandlers {ipcMain.handle("open-sound-input-settings", () => openSystemSettings("sound"));ipcMain.handle("open-accessibility-settings", () => openSystemSettings("accessibility"));+ // Auth: clear all session cookies for sign-out.+ // This clears every cookie in the renderer session rather than targeting+ // individual auth cookies, which is acceptable because the app only sets+ // cookies for Neon Auth. Avoids CSRF/Origin header issues that occur when+ // the renderer tries to call the server-side sign-out endpoint directly.+ ipcMain.handle("auth-clear-session", async (event) => {+ try {+ const win = BrowserWindow.fromWebContents(event.sender);+ if (win) {+ await win.webContents.session.clearStorageData({ storages: ["cookies"] });+ }+ return { success: true };+ } catch (error) {+ debugLogger.error("Failed to clear auth session:", error);+ return { success: false, error: error.message };+ }+ });++ // --- OpenWhispr Cloud API handlers ---++ const getApiUrl = () =>+ process.env.OPENWHISPR_API_URL || process.env.VITE_OPENWHISPR_API_URL || "";++ const getAuthUrl = () => process.env.NEON_AUTH_URL || process.env.VITE_NEON_AUTH_URL || "";++ const getSessionCookies = async (event) => {+ const win = BrowserWindow.fromWebContents(event.sender);+ if (!win) return "";++ const scopedUrls = [getAuthUrl(), getApiUrl()].filter(Boolean);+ const cookiesByName = new Map();++ for (const url of scopedUrls) {+ try {+ const scopedCookies = await win.webContents.session.cookies.get({ url });+ for (const cookie of scopedCookies) {+ if (!cookiesByName.has(cookie.name)) {+ cookiesByName.set(cookie.name, cookie.value);+ }+ }+ } catch (error) {+ debugLogger.warn("Failed to read scoped auth cookies", {+ url,+ error: error.message,+ });+ }+ }++ // Fallback for older sessions where cookies are not URL-scoped as expected.+ if (cookiesByName.size === 0) {+ const allCookies = await win.webContents.session.cookies.get({});+ for (const cookie of allCookies) {+ if (!cookiesByName.has(cookie.name)) {+ cookiesByName.set(cookie.name, cookie.value);+ }+ }+ }++ const cookieHeader = [...cookiesByName.entries()]+ .map(([name, value]) => `${name}=${value}`)+ .join("; ");++ debugLogger.debug(+ "Resolved auth cookies for cloud request",+ {+ cookieCount: cookiesByName.size,+ scopedUrls,+ },+ "auth"+ );++ return cookieHeader;+ };++ ipcMain.handle("cloud-transcribe", async (event, audioBuffer, opts = {}) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) throw new Error("No session cookies available");++ const audioData = Buffer.from(audioBuffer);+ const boundary = `----OpenWhispr${Date.now()}`;+ const parts = [];++ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="file"; filename="audio.webm"\r\n` ++ `Content-Type: audio/webm\r\n\r\n`+ );+ parts.push(audioData);+ parts.push("\r\n");++ if (opts.language) {+ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="language"\r\n\r\n` ++ `${opts.language}\r\n`+ );+ }++ if (opts.prompt) {+ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="prompt"\r\n\r\n` ++ `${opts.prompt}\r\n`+ );+ }++ // Add client metadata for logging+ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="clientType"\r\n\r\n` ++ `desktop\r\n`+ );++ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="appVersion"\r\n\r\n` ++ `${app.getVersion()}\r\n`+ );++ parts.push(+ `--${boundary}\r\n` ++ `Content-Disposition: form-data; name="sessionId"\r\n\r\n` ++ `${this.sessionId}\r\n`+ );++ parts.push(`--${boundary}--\r\n`);++ const bodyParts = parts.map((p) => (typeof p === "string" ? Buffer.from(p) : p));+ const body = Buffer.concat(bodyParts);++ debugLogger.debug(+ "Cloud transcribe request",+ { audioSize: audioData.length, bodySize: body.length },+ "cloud-api"+ );++ const url = new URL(`${apiUrl}/api/transcribe`);+ const httpModule = url.protocol === "https:" ? https : http;++ const data = await new Promise((resolve, reject) => {+ const req = httpModule.request(+ {+ hostname: url.hostname,+ port: url.port || (url.protocol === "https:" ? 443 : 80),+ path: url.pathname,+ method: "POST",+ headers: {+ "Content-Type": `multipart/form-data; boundary=${boundary}`,+ "Content-Length": body.length,+ Cookie: cookieHeader,+ },+ },+ (res) => {+ let responseData = "";+ res.on("data", (chunk) => (responseData += chunk));+ res.on("end", () => {+ try {+ const parsed = JSON.parse(responseData);+ resolve({ statusCode: res.statusCode, data: parsed });+ } catch (e) {+ reject(new Error(`Invalid JSON response: ${responseData.slice(0, 200)}`));+ }+ });+ }+ );+ req.on("error", reject);+ req.write(body);+ req.end();+ });++ debugLogger.debug(+ "Cloud transcribe response",+ { statusCode: data.statusCode },+ "cloud-api"+ );++ if (data.statusCode === 401) {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ if (data.statusCode === 429) {+ return {+ success: false,+ error: "Daily word limit reached",+ code: "LIMIT_REACHED",+ limitReached: true,+ ...data.data,+ };+ }+ if (data.statusCode !== 200) {+ throw new Error(data.data?.error || `API error: ${data.statusCode}`);+ }++ return {+ success: true,+ text: data.data.text,+ wordsUsed: data.data.wordsUsed,+ wordsRemaining: data.data.wordsRemaining,+ plan: data.data.plan,+ limitReached: data.data.limitReached || false,+ };+ } catch (error) {+ debugLogger.error("Cloud transcription error", { error: error.message }, "cloud-api");+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("cloud-reason", async (event, text, opts = {}) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");++ console.log("[cloud-reason] ⬇ IPC called", {+ apiUrl,+ model: opts.model || "(default)",+ agentName: opts.agentName || "(none)",+ language: opts.language || "(auto)",+ textLength: text?.length || 0,+ textPreview: text?.substring(0, 80) || "(empty)",+ });++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) throw new Error("No session cookies available");++ console.log(`[cloud-reason] → Fetching ${apiUrl}/api/reason ...`);++ const fetchStart = Date.now();+ const response = await fetch(`${apiUrl}/api/reason`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Cookie: cookieHeader,+ },+ body: JSON.stringify({+ text,+ model: opts.model,+ agentName: opts.agentName,+ customDictionary: opts.customDictionary,+ language: opts.language,+ }),+ });+ const fetchMs = Date.now() - fetchStart;++ console.log("[cloud-reason] ← Response", {+ status: response.status,+ ok: response.ok,+ fetchMs,+ });++ if (!response.ok) {+ if (response.status === 401) {+ console.log("[cloud-reason] ✗ 401 - session expired");+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ const errorData = await response.json().catch(() => ({}));+ console.log("[cloud-reason] ✗ API error", { status: response.status, errorData });+ throw new Error(errorData.error || `API error: ${response.status}`);+ }++ const data = await response.json();+ console.log("[cloud-reason] ✓ Success", {+ model: data.model,+ provider: data.provider,+ processingMs: data.processingMs,+ resultLength: data.text?.length || 0,+ resultPreview: data.text?.substring(0, 80) || "(empty)",+ });+ return { success: true, text: data.text, model: data.model, provider: data.provider };+ } catch (error) {+ console.log("[cloud-reason] ✗ Error:", error.message);+ debugLogger.error("Cloud reasoning error:", error);+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("cloud-usage", async (event) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) throw new Error("No session cookies available");++ const response = await fetch(`${apiUrl}/api/usage`, {+ headers: { Cookie: cookieHeader },+ });++ if (!response.ok) {+ if (response.status === 401) {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ throw new Error(`API error: ${response.status}`);+ }++ const data = await response.json();+ return { success: true, ...data };+ } catch (error) {+ debugLogger.error("Cloud usage fetch error:", error);+ return { success: false, error: error.message };+ }+ });++ const fetchStripeUrl = async (event, endpoint, errorPrefix) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) throw new Error("OpenWhispr API URL not configured");++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) throw new Error("No session cookies available");++ const response = await fetch(`${apiUrl}${endpoint}`, {+ method: "POST",+ headers: { Cookie: cookieHeader },+ });++ if (!response.ok) {+ if (response.status === 401) {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `API error: ${response.status}`);+ }++ const data = await response.json();+ return { success: true, url: data.url };+ } catch (error) {+ debugLogger.error(`${errorPrefix}:`, error);+ return { success: false, error: error.message };+ }+ };++ ipcMain.handle("cloud-checkout", (event) =>+ fetchStripeUrl(event, "/api/stripe/checkout", "Cloud checkout error")+ );++ ipcMain.handle("cloud-billing-portal", (event) =>+ fetchStripeUrl(event, "/api/stripe/portal", "Cloud billing portal error")+ );+ipcMain.handle("open-whisper-models-folder", async () => {try {const modelsDir = this.whisperManager.getModelsDir();@@ -1067,6 +1435,201 @@ class IPCHandlers {ipcMain.handle("get-update-info", async () => {return this.updateManager.getUpdateInfo();});++ // --- Assembly AI Streaming handlers ---++ // Helper to fetch streaming token+ const fetchStreamingToken = async (event) => {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ throw new Error("OpenWhispr API URL not configured");+ }++ const cookieHeader = await getSessionCookies(event);+ if (!cookieHeader) {+ throw new Error("No session cookies available");+ }++ const tokenResponse = await fetch(`${apiUrl}/api/streaming-token`, {+ method: "POST",+ headers: {+ Cookie: cookieHeader,+ },+ });++ if (!tokenResponse.ok) {+ if (tokenResponse.status === 401) {+ const err = new Error("Session expired");+ err.code = "AUTH_EXPIRED";+ throw err;+ }+ const errorData = await tokenResponse.json().catch(() => ({}));+ throw new Error(+ errorData.error || `Failed to get streaming token: ${tokenResponse.status}`+ );+ }++ const { token } = await tokenResponse.json();+ if (!token) {+ throw new Error("No token received from API");+ }++ return token;+ };++ ipcMain.handle("assemblyai-streaming-warmup", async (event, options = {}) => {+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ return { success: false, error: "API not configured", code: "NO_API" };+ }++ if (!this.assemblyAiStreaming) {+ this.assemblyAiStreaming = new AssemblyAiStreaming();+ }++ if (this.assemblyAiStreaming.hasWarmConnection()) {+ debugLogger.debug("AssemblyAI connection already warm", {}, "streaming");+ return { success: true, alreadyWarm: true };+ }++ let token = this.assemblyAiStreaming.getCachedToken();+ if (!token) {+ debugLogger.debug("Fetching new streaming token for warmup", {}, "streaming");+ token = await fetchStreamingToken(event);+ }++ await this.assemblyAiStreaming.warmup({ ...options, token });+ debugLogger.debug("AssemblyAI connection warmed up", {}, "streaming");++ return { success: true };+ } catch (error) {+ debugLogger.error("AssemblyAI warmup error", { error: error.message });+ if (error.code === "AUTH_EXPIRED") {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ return { success: false, error: error.message };+ }+ });++ let streamingStartInProgress = false;++ ipcMain.handle("assemblyai-streaming-start", async (event, options = {}) => {+ if (streamingStartInProgress) {+ debugLogger.debug("Streaming start already in progress, ignoring", {}, "streaming");+ return { success: false, error: "Operation in progress" };+ }++ streamingStartInProgress = true;+ try {+ const apiUrl = getApiUrl();+ if (!apiUrl) {+ return { success: false, error: "API not configured", code: "NO_API" };+ }++ const win = BrowserWindow.fromWebContents(event.sender);++ if (!this.assemblyAiStreaming) {+ this.assemblyAiStreaming = new AssemblyAiStreaming();+ }++ // Clean up any stale active connection (shouldn't happen normally)+ if (this.assemblyAiStreaming.isConnected) {+ debugLogger.debug("AssemblyAI cleaning up stale connection before start", {}, "streaming");+ await this.assemblyAiStreaming.disconnect(false);+ }++ const hasWarm = this.assemblyAiStreaming.hasWarmConnection();+ debugLogger.debug("AssemblyAI streaming start", { hasWarmConnection: hasWarm }, "streaming");++ let token = this.assemblyAiStreaming.getCachedToken();+ if (!token) {+ debugLogger.debug("Fetching streaming token from API", {}, "streaming");+ token = await fetchStreamingToken(event);+ this.assemblyAiStreaming.cacheToken(token);+ } else {+ debugLogger.debug("Using cached streaming token", {}, "streaming");+ }++ // Set up callbacks to forward events to renderer+ this.assemblyAiStreaming.onPartialTranscript = (text) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("assemblyai-partial-transcript", text);+ }+ };++ this.assemblyAiStreaming.onFinalTranscript = (text) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("assemblyai-final-transcript", text);+ }+ };++ this.assemblyAiStreaming.onError = (error) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("assemblyai-error", error.message);+ }+ };++ this.assemblyAiStreaming.onSessionEnd = (data) => {+ if (win && !win.isDestroyed()) {+ win.webContents.send("assemblyai-session-end", data);+ }+ };++ await this.assemblyAiStreaming.connect({ ...options, token });+ debugLogger.debug("AssemblyAI streaming started", {}, "streaming");++ return {+ success: true,+ usedWarmConnection: this.assemblyAiStreaming.hasWarmConnection() === false,+ };+ } catch (error) {+ debugLogger.error("AssemblyAI streaming start error", { error: error.message });+ if (error.code === "AUTH_EXPIRED") {+ return { success: false, error: "Session expired", code: "AUTH_EXPIRED" };+ }+ return { success: false, error: error.message };+ } finally {+ streamingStartInProgress = false;+ }+ });++ ipcMain.on("assemblyai-streaming-send", (event, audioBuffer) => {+ try {+ if (!this.assemblyAiStreaming) return;+ const buffer = Buffer.from(audioBuffer);+ this.assemblyAiStreaming.sendAudio(buffer);+ } catch (error) {+ debugLogger.error("AssemblyAI streaming send error", { error: error.message });+ }+ });++ ipcMain.on("assemblyai-streaming-force-endpoint", () => {+ this.assemblyAiStreaming?.forceEndpoint();+ });++ ipcMain.handle("assemblyai-streaming-stop", async () => {+ try {+ let result = { text: "" };+ if (this.assemblyAiStreaming) {+ // disconnect() now returns the final text from Termination event+ result = await this.assemblyAiStreaming.disconnect(true);+ this.assemblyAiStreaming = null;+ }++ return { success: true, text: result?.text || "" };+ } catch (error) {+ debugLogger.error("AssemblyAI streaming stop error", { error: error.message });+ return { success: false, error: error.message };+ }+ });++ ipcMain.handle("assemblyai-streaming-status", async () => {+ if (!this.assemblyAiStreaming) {+ return { isConnected: false, sessionId: null };+ }+ return this.assemblyAiStreaming.getStatus();+ });}broadcastToWindows(channel, payload) {diff --git a/src/helpers/prompts.js b/src/helpers/prompts.jsindex b6e2e8281..69f35a9ff 100644--- a/src/helpers/prompts.js+++ b/src/helpers/prompts.js@@ -1,12 +1,29 @@const promptData = require("../config/promptData.json");+const languageRegistry = require("../config/languageRegistry.json");const UNIFIED_SYSTEM_PROMPT = promptData.UNIFIED_SYSTEM_PROMPT;const DICTIONARY_SUFFIX = promptData.DICTIONARY_SUFFIX;-function getSystemPrompt(agentName, customDictionary) {+const _langInstructions = Object.fromEntries(+ languageRegistry.languages.filter((l) => l.instruction).map((l) => [l.code, l.instruction])+);++function getLanguageInstruction(language) {+ if (!language || language === "en") return "";+ if (_langInstructions[language]) return _langInstructions[language];+ const template = languageRegistry._genericTemplate || "";+ return template.replace("{{code}}", language);+}++function getSystemPrompt(agentName, customDictionary, language) {const name = (agentName && agentName.trim()) || "Assistant";let prompt = UNIFIED_SYSTEM_PROMPT.replace(/\{\{agentName\}\}/g, name);+ const langInstruction = getLanguageInstruction(language);+ if (langInstruction) {+ prompt += "\n\n" + langInstruction;+ }+if (Array.isArray(customDictionary) && customDictionary.length > 0) {prompt += DICTIONARY_SUFFIX + customDictionary.join(", ");}diff --git a/src/helpers/windowConfig.js b/src/helpers/windowConfig.jsindex 4a0f49769..51a459030 100644--- a/src/helpers/windowConfig.js+++ b/src/helpers/windowConfig.js@@ -40,7 +40,13 @@ const CONTROL_PANEL_CONFIG = {preload: path.join(__dirname, "..", "..", "preload.js"),nodeIntegration: false,contextIsolation: true,+ // sandbox: false is required because the preload script bridges IPC+ // between the renderer and main process.sandbox: false,+ // webSecurity: false disables same-origin policy. Required because in+ // production the renderer loads from a file:// origin but makes+ // cross-origin fetch calls to Neon Auth, Gemini, OpenAI, and Groq APIs+ // directly from the browser. These would be blocked by CORS otherwise.webSecurity: false,spellcheck: false,},diff --git a/src/helpers/windowManager.js b/src/helpers/windowManager.jsindex 0b03556e7..5ebade01a 100644--- a/src/helpers/windowManager.js+++ b/src/helpers/windowManager.js@@ -1,4 +1,4 @@-const { app, screen, BrowserWindow, dialog } = require("electron");+const { app, screen, BrowserWindow, shell, dialog } = require("electron");const HotkeyManager = require("./hotkeyManager");const DragManager = require("./dragManager");const MenuManager = require("./menuManager");@@ -22,6 +22,8 @@ class WindowManager {this.isMainWindowInteractive = false;this.loadErrorShown = false;this.windowsPushToTalkAvailable = false;+ this.macCompoundPushState = null;+ this._cachedActivationMode = "tap";app.on("before-quit", () => {this.isQuitting = true;@@ -168,9 +170,22 @@ class WindowManager {return;}+ const activationMode = await this.getActivationMode();+ const currentHotkey = this.hotkeyManager.getCurrentHotkey?.();++ if (+ process.platform === "darwin" &&+ activationMode === "push" &&+ currentHotkey &&+ currentHotkey !== "GLOBE" &&+ currentHotkey.includes("+")+ ) {+ this.startMacCompoundPushToTalk(currentHotkey);+ return;+ }+// Windows push mode: defer to windowsKeyManager if available, else fall through to toggleif (process.platform === "win32" && this.windowsPushToTalkAvailable) {- const activationMode = await this.getActivationMode();if (activationMode === "push") {return;}@@ -189,6 +204,133 @@ class WindowManager {};}+ startMacCompoundPushToTalk(hotkey) {+ if (this.macCompoundPushState?.active) {+ return;+ }++ const requiredModifiers = this.getMacRequiredModifiers(hotkey);+ if (requiredModifiers.size === 0) {+ return;+ }++ const MIN_HOLD_DURATION_MS = 150;+ const MAX_PUSH_DURATION_MS = 300000; // 5 minutes max recording+ const downTime = Date.now();++ this.showDictationPanel();++ // Set up safety timeout+ const safetyTimeoutId = setTimeout(() => {+ if (this.macCompoundPushState?.active) {+ console.warn("[WindowManager] Compound PTT safety timeout triggered - stopping recording");+ this.forceStopMacCompoundPush("timeout");+ }+ }, MAX_PUSH_DURATION_MS);++ this.macCompoundPushState = {+ active: true,+ downTime,+ isRecording: false,+ requiredModifiers,+ safetyTimeoutId,+ };++ setTimeout(() => {+ if (!this.macCompoundPushState || this.macCompoundPushState.downTime !== downTime) {+ return;+ }++ if (!this.macCompoundPushState.isRecording) {+ this.macCompoundPushState.isRecording = true;+ this.sendStartDictation();+ }+ }, MIN_HOLD_DURATION_MS);+ }++ handleMacPushModifierUp(modifier) {+ if (!this.macCompoundPushState?.active) {+ return;+ }++ if (!this.macCompoundPushState.requiredModifiers.has(modifier)) {+ return;+ }++ // Clear safety timeout+ if (this.macCompoundPushState.safetyTimeoutId) {+ clearTimeout(this.macCompoundPushState.safetyTimeoutId);+ }++ const wasRecording = this.macCompoundPushState.isRecording;+ this.macCompoundPushState = null;++ if (wasRecording) {+ this.sendStopDictation();+ } else {+ this.hideDictationPanel();+ }+ }++ forceStopMacCompoundPush(reason = "manual") {+ if (!this.macCompoundPushState) {+ return;+ }++ // Clear safety timeout+ if (this.macCompoundPushState.safetyTimeoutId) {+ clearTimeout(this.macCompoundPushState.safetyTimeoutId);+ }++ const wasRecording = this.macCompoundPushState.isRecording;+ this.macCompoundPushState = null;++ if (wasRecording) {+ this.sendStopDictation();+ }+ this.hideDictationPanel();++ // Notify renderer about forced stop+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {+ this.mainWindow.webContents.send("compound-ptt-force-stopped", { reason });+ }+ }++ getMacRequiredModifiers(hotkey) {+ const required = new Set();+ const parts = hotkey.split("+").map((part) => part.trim());++ for (const part of parts) {+ switch (part) {+ case "Command":+ case "Cmd":+ case "CommandOrControl":+ case "Super":+ case "Meta":+ required.add("command");+ break;+ case "Control":+ case "Ctrl":+ required.add("control");+ break;+ case "Alt":+ case "Option":+ required.add("option");+ break;+ case "Shift":+ required.add("shift");+ break;+ case "Fn":+ required.add("fn");+ break;+ default:+ break;+ }+ }++ return required;+ }+sendStartDictation() {if (this.hotkeyManager.isInListeningMode()) {return;@@ -210,18 +352,12 @@ class WindowManager {}}- async getActivationMode() {- if (!this.mainWindow || this.mainWindow.isDestroyed()) {- return "tap";- }- try {- const mode = await this.mainWindow.webContents.executeJavaScript(- `localStorage.getItem("activationMode") || "tap"`- );- return mode === "push" ? "push" : "tap";- } catch {- return "tap";- }+ getActivationMode() {+ return this._cachedActivationMode;+ }++ setActivationModeCache(mode) {+ this._cachedActivationMode = mode === "push" ? "push" : "tap";}setHotkeyListeningMode(enabled) {@@ -248,6 +384,17 @@ class WindowManager {return await this.dragManager.stopWindowDrag();}+ openExternalUrl(url, showError = true) {+ shell.openExternal(url).catch((error) => {+ if (showError) {+ dialog.showErrorBox(+ "Unable to Open Link",+ `Failed to open the link in your browser:\n${url}\n\nError: ${error.message}`+ );+ }+ });+ }+async createControlPanelWindow() {if (this.controlPanelWindow && !this.controlPanelWindow.isDestroyed()) {if (this.controlPanelWindow.isMinimized()) {@@ -262,12 +409,39 @@ class WindowManager {this.controlPanelWindow = new BrowserWindow(CONTROL_PANEL_CONFIG);+ this.controlPanelWindow.webContents.on("will-navigate", (event, url) => {+ const appUrl = DevServerManager.getAppUrl(true);+ const controlPanelUrl = appUrl.startsWith("http") ? appUrl : `file://${appUrl}`;++ if (+ url.startsWith(controlPanelUrl) ||+ url.startsWith("file://") ||+ url.startsWith("devtools://")+ ) {+ return;+ }++ event.preventDefault();+ this.openExternalUrl(url);+ });++ this.controlPanelWindow.webContents.setWindowOpenHandler(({ url }) => {+ this.openExternalUrl(url);+ return { action: "deny" };+ });++ this.controlPanelWindow.webContents.on("did-create-window", (childWindow, details) => {+ childWindow.close();+ if (details.url && !details.url.startsWith("devtools://")) {+ this.openExternalUrl(details.url, false);+ }+ });+const visibilityTimer = setTimeout(() => {if (!this.controlPanelWindow || this.controlPanelWindow.isDestroyed()) {return;}if (!this.controlPanelWindow.isVisible()) {- console.warn("Control panel did not become visible in time; forcing show");this.controlPanelWindow.show();this.controlPanelWindow.focus();}@@ -318,7 +492,6 @@ class WindowManager {return;}clearVisibilityTimer();- console.error("Failed to load control panel:", errorCode, errorDescription, validatedURL);if (process.env.NODE_ENV !== "development") {this.showLoadFailureDialog("Control panel", errorCode, errorDescription, validatedURL);}diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.jsindex c280c1ecf..3438b244c 100644--- a/src/hooks/useAudioRecording.js+++ b/src/hooks/useAudioRecording.js@@ -1,10 +1,13 @@import { useState, useEffect, useRef } from "react";import AudioManager from "../helpers/audioManager";+import logger from "../utils/logger";export const useAudioRecording = (toast, options = {}) => {const [isRecording, setIsRecording] = useState(false);const [isProcessing, setIsProcessing] = useState(false);+ const [isStreaming, setIsStreaming] = useState(false);const [transcript, setTranscript] = useState("");+ const [partialTranscript, setPartialTranscript] = useState("");const audioManagerRef = useRef(null);const { onToggle } = options;@@ -12,22 +15,54 @@ export const useAudioRecording = (toast, options = {}) => {audioManagerRef.current = new AudioManager();audioManagerRef.current.setCallbacks({- onStateChange: ({ isRecording, isProcessing }) => {+ onStateChange: ({ isRecording, isProcessing, isStreaming }) => {setIsRecording(isRecording);setIsProcessing(isProcessing);+ setIsStreaming(isStreaming ?? false);+ if (!isStreaming) {+ setPartialTranscript("");+ }},onError: (error) => {+ // Provide specific titles for cloud error codes+ const title =+ error.code === "AUTH_EXPIRED"+ ? "Session Expired"+ : error.code === "OFFLINE"+ ? "You're Offline"+ : error.code === "LIMIT_REACHED"+ ? "Daily Limit Reached"+ : error.title;+toast({- title: error.title,+ title,description: error.description,variant: "destructive",+ duration: error.code === "AUTH_EXPIRED" ? 8000 : undefined,});},+ onPartialTranscript: (text) => {+ setPartialTranscript(text);+ },onTranscriptionComplete: async (result) => {if (result.success) {setTranscript(result.text);- await audioManagerRef.current.safePaste(result.text);+ const isStreaming = result.source?.includes("streaming");+ const pasteStart = performance.now();+ await audioManagerRef.current.safePaste(+ result.text,+ isStreaming ? { fromStreaming: true } : {}+ );+ logger.info(+ "Paste timing",+ {+ pasteMs: Math.round(performance.now() - pasteStart),+ source: result.source,+ textLength: result.text.length,+ },+ "streaming"+ );audioManagerRef.current.saveTranscription(result.text);@@ -38,34 +73,63 @@ export const useAudioRecording = (toast, options = {}) => {variant: "default",});}++ // Cloud usage: limit reached after this transcription+ if (result.source === "openwhispr" && result.limitReached) {+ // Notify control panel to show UpgradePrompt dialog+ window.electronAPI?.notifyLimitReached?.({+ wordsUsed: result.wordsUsed,+ limit:+ result.wordsRemaining !== undefined+ ? result.wordsUsed + result.wordsRemaining+ : 2000,+ });+ }++ audioManagerRef.current.warmupStreamingConnection();}},});- // Set up hotkey listener for tap-to-talk mode- const handleToggle = () => {+ audioManagerRef.current.warmupStreamingConnection();++ const handleToggle = async () => {const currentState = audioManagerRef.current.getState();if (!currentState.isRecording && !currentState.isProcessing) {- audioManagerRef.current.startRecording();+ if (audioManagerRef.current.shouldUseStreaming()) {+ await audioManagerRef.current.startStreamingRecording();+ } else {+ await audioManagerRef.current.startRecording();+ }} else if (currentState.isRecording) {- audioManagerRef.current.stopRecording();+ if (currentState.isStreaming) {+ await audioManagerRef.current.stopStreamingRecording();+ } else {+ audioManagerRef.current.stopRecording();+ }}};- // Set up listener for push-to-talk start- const handleStart = () => {+ const handleStart = async () => {const currentState = audioManagerRef.current.getState();if (!currentState.isRecording && !currentState.isProcessing) {- audioManagerRef.current.startRecording();+ if (audioManagerRef.current.shouldUseStreaming()) {+ await audioManagerRef.current.startStreamingRecording();+ } else {+ await audioManagerRef.current.startRecording();+ }}};- // Set up listener for push-to-talk stop- const handleStop = () => {+ const handleStop = async () => {const currentState = audioManagerRef.current.getState();if (currentState.isRecording) {- audioManagerRef.current.stopRecording();+ if (currentState.isStreaming) {+ await audioManagerRef.current.stopStreamingRecording();+ } else {+ audioManagerRef.current.stopRecording();+ }}};@@ -108,20 +172,31 @@ export const useAudioRecording = (toast, options = {}) => {const startRecording = async () => {if (audioManagerRef.current) {+ if (audioManagerRef.current.shouldUseStreaming()) {+ return await audioManagerRef.current.startStreamingRecording();+ }return await audioManagerRef.current.startRecording();}return false;};- const stopRecording = () => {+ const stopRecording = async () => {if (audioManagerRef.current) {+ const state = audioManagerRef.current.getState();+ if (state.isStreaming) {+ return await audioManagerRef.current.stopStreamingRecording();+ }return audioManagerRef.current.stopRecording();}return false;};- const cancelRecording = () => {+ const cancelRecording = async () => {if (audioManagerRef.current) {+ const state = audioManagerRef.current.getState();+ if (state.isStreaming) {+ return await audioManagerRef.current.stopStreamingRecording();+ }return audioManagerRef.current.cancelRecording();}return false;@@ -134,22 +209,29 @@ export const useAudioRecording = (toast, options = {}) => {return false;};- const toggleListening = () => {+ const toggleListening = async () => {if (!isRecording && !isProcessing) {- startRecording();+ await startRecording();} else if (isRecording) {- stopRecording();+ await stopRecording();}};+ const warmupStreaming = () => {+ audioManagerRef.current?.warmupStreamingConnection();+ };+return {isRecording,isProcessing,+ isStreaming,transcript,+ partialTranscript,startRecording,stopRecording,cancelRecording,cancelProcessing,toggleListening,+ warmupStreaming,};};diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.tsnew file mode 100644index 000000000..801bcf775--- /dev/null+++ b/src/hooks/useAuth.ts@@ -0,0 +1,46 @@+import { useEffect, useRef } from "react";+import { authClient, isWithinGracePeriod } from "../lib/neonAuth";+import logger from "../utils/logger";++const useStaticSession = () => ({+ data: null,+ isPending: false,+ error: null,+ refetch: async () => null,+});++export function useAuth() {+ const useSession = authClient?.useSession ?? useStaticSession;+ const { data: session, isPending } = useSession();+ const user = session?.user ?? null;+ const rawIsSignedIn = Boolean(user);+ const gracePeriodActive = isWithinGracePeriod();++ // CRITICAL: During the grace period after OAuth, session cookies may not+ // be fully established yet. The Neon Auth SDK's useSession hook can return+ // null during this time, but we should NOT report signed out to the UI.+ // Instead, we keep reporting signed in and let withSessionRefresh handle retries.+ const isSignedIn = rawIsSignedIn || gracePeriodActive;++ // Track last synced state to prevent duplicate syncs+ const lastSyncedStateRef = useRef<boolean | null>(null);++ useEffect(() => {+ if (!isPending && lastSyncedStateRef.current !== isSignedIn) {+ logger.debug(+ "Auth state sync",+ { isSignedIn, rawIsSignedIn, gracePeriod: gracePeriodActive },+ "auth"+ );+ localStorage.setItem("isSignedIn", String(isSignedIn));+ lastSyncedStateRef.current = isSignedIn;+ }+ }, [isSignedIn, rawIsSignedIn, gracePeriodActive, isPending]);++ return {+ isSignedIn,+ isLoaded: !isPending,+ session,+ user,+ };+}diff --git a/src/hooks/useHotkey.js b/src/hooks/useHotkey.jsindex e2dd48b3b..b43c9e36a 100644--- a/src/hooks/useHotkey.js+++ b/src/hooks/useHotkey.js@@ -1,13 +1,16 @@import { useState, useEffect } from "react";+import { getDefaultHotkey } from "../utils/hotkeys";export const useHotkey = () => {- const [hotkey, setHotkey] = useState("`");+ const [hotkey, setHotkey] = useState(getDefaultHotkey());useEffect(() => {// Load hotkey from localStorage on mountconst savedHotkey = localStorage.getItem("dictationKey");if (savedHotkey) {setHotkey(savedHotkey);+ } else {+ setHotkey(getDefaultHotkey());}}, []);diff --git a/src/hooks/useHotkeyRegistration.ts b/src/hooks/useHotkeyRegistration.tsindex 34e6e0549..5afc4307a 100644--- a/src/hooks/useHotkeyRegistration.ts+++ b/src/hooks/useHotkeyRegistration.ts@@ -1,5 +1,7 @@import { useState, useCallback, useRef } from "react";import { formatHotkeyLabel } from "../utils/hotkeys";+import { validateHotkey } from "../utils/hotkeyValidator";+import { getPlatform } from "../utils/platform";export interface UseHotkeyRegistrationOptions {/**@@ -99,6 +101,21 @@ export function useHotkeyRegistration(return false;}+ const platform = getPlatform();+ const validation = validateHotkey(hotkey, platform);+ if (!validation.valid) {+ const errorMsg = validation.error || "That shortcut is not supported.";+ setLastError(errorMsg);+ if (showErrorToast && showAlert) {+ showAlert({+ title: "Invalid Hotkey",+ description: errorMsg,+ });+ }+ onError?.(errorMsg, hotkey);+ return false;+ }+// Check if Electron API is availableif (!window.electronAPI?.updateHotkey) {// In non-Electron environment, just succeed silentlydiff --git a/src/hooks/usePermissions.ts b/src/hooks/usePermissions.tsindex f698625da..4f8c9f81c 100644--- a/src/hooks/usePermissions.ts+++ b/src/hooks/usePermissions.ts@@ -1,5 +1,6 @@import { useState, useCallback, useEffect } from "react";import type { PasteToolsResult } from "../types/electron";+import { useLocalStorage } from "./useLocalStorage";export interface UsePermissionsReturn {// State@@ -99,9 +100,23 @@ const describeMicError = (error: unknown): string => {export const usePermissions = (showAlertDialog?: UsePermissionsProps["showAlertDialog"]): UsePermissionsReturn => {- const [micPermissionGranted, setMicPermissionGranted] = useState(false);+ const [micPermissionGranted, setMicPermissionGranted] = useLocalStorage(+ "micPermissionGranted",+ false,+ {+ serialize: String,+ deserialize: (value) => value === "true",+ }+ );const [micPermissionError, setMicPermissionError] = useState<string | null>(null);- const [accessibilityPermissionGranted, setAccessibilityPermissionGranted] = useState(false);+ const [accessibilityPermissionGranted, setAccessibilityPermissionGranted] = useLocalStorage(+ "accessibilityPermissionGranted",+ false,+ {+ serialize: String,+ deserialize: (value) => value === "true",+ }+ );const [pasteToolsInfo, setPasteToolsInfo] = useState<PasteToolsResult | null>(null);const [isCheckingPasteTools, setIsCheckingPasteTools] = useState(false);@@ -206,7 +221,7 @@ export const usePermissions = (} finally {setIsCheckingPasteTools(false);}- }, []);+ }, [setAccessibilityPermissionGranted]);// Check paste tools on mountuseEffect(() => {diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex efe8cb09b..7d3c1d9ca 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -3,6 +3,7 @@ import { useLocalStorage } from "./useLocalStorage";import { useDebouncedCallback } from "./useDebouncedCallback";import { API_ENDPOINTS } from "../config/constants";import ReasoningService from "../services/ReasoningService";+import logger from "../utils/logger";import type { LocalTranscriptionProvider } from "../types/electron";export interface TranscriptionSettings {@@ -17,7 +18,9 @@ export interface TranscriptionSettings {cloudTranscriptionProvider: string;cloudTranscriptionModel: string;cloudTranscriptionBaseUrl?: string;+ cloudTranscriptionMode: string;customDictionary: string[];+ assemblyAiStreaming: boolean;}export interface ReasoningSettings {@@ -46,6 +49,11 @@ export interface ApiKeySettings {customReasoningApiKey: string;}+export interface PrivacySettings {+ cloudBackupEnabled: boolean;+ telemetryEnabled: boolean;+}+export interface ThemeSettings {theme: "light" | "dark" | "auto";}@@ -95,7 +103,7 @@ export function useSettings() {});- const [preferredLanguage, setPreferredLanguage] = useLocalStorage("preferredLanguage", "en", {+ const [preferredLanguage, setPreferredLanguage] = useLocalStorage("preferredLanguage", "auto", {serialize: String,deserialize: String,});@@ -136,6 +144,16 @@ export function useSettings() {});+ // Cloud transcription mode: "openwhispr" (server-side) or "byok" (bring your own key)+ const [cloudTranscriptionMode, setCloudTranscriptionMode] = useLocalStorage(+ "cloudTranscriptionMode",+ "openwhispr",+ {+ serialize: String,+ deserialize: String,+ }+ );+// Custom dictionary for improving transcription of specific wordsconst [customDictionary, setCustomDictionaryRaw] = useLocalStorage<string[]>("customDictionary",@@ -153,12 +171,26 @@ export function useSettings() {});+ // Assembly AI real-time streaming (enabled by default for signed-in users)+ const [assemblyAiStreaming, setAssemblyAiStreaming] = useLocalStorage(+ "assemblyAiStreaming",+ true,+ {+ serialize: String,+ deserialize: (value) => value !== "false", // Default to true unless explicitly disabled+ }+ );+// Wrap setter to sync dictionary to SQLiteconst setCustomDictionary = useCallback((words: string[]) => {setCustomDictionaryRaw(words);- window.electronAPI?.setDictionary(words).catch(() => {- // Silently ignore SQLite sync errors+ window.electronAPI?.setDictionary(words).catch((err) => {+ logger.warn(+ "Failed to sync dictionary to SQLite",+ { error: (err as Error).message },+ "settings"+ );});},[setCustomDictionaryRaw]@@ -181,8 +213,12 @@ export function useSettings() {// Recover localStorage from SQLite (e.g. localStorage was cleared)setCustomDictionaryRaw(dbWords);}- } catch {- // Silently ignore sync errors+ } catch (err) {+ logger.warn(+ "Failed to sync dictionary on startup",+ { error: (err as Error).message },+ "settings"+ );}};@@ -236,6 +272,17 @@ export function useSettings() {},});+ // Privacy settings — both default to OFF+ const [cloudBackupEnabled, setCloudBackupEnabled] = useLocalStorage("cloudBackupEnabled", false, {+ serialize: String,+ deserialize: (value) => value === "true",+ });++ const [telemetryEnabled, setTelemetryEnabled] = useLocalStorage("telemetryEnabled", false, {+ serialize: String,+ deserialize: (value) => value === "true",+ });+// Custom endpoint API keys - synced to .env like other keysconst [customTranscriptionApiKey, setCustomTranscriptionApiKeyLocal] = useLocalStorage("customTranscriptionApiKey",@@ -291,16 +338,24 @@ export function useSettings() {}};- syncKeys().catch(() => {- // Silently ignore sync errors+ syncKeys().catch((err) => {+ logger.warn(+ "Failed to sync API keys on startup",+ { error: (err as Error).message },+ "settings"+ );});// eslint-disable-next-line react-hooks/exhaustive-deps}, []);const debouncedPersistToEnv = useDebouncedCallback(() => {if (typeof window !== "undefined" && window.electronAPI?.saveAllKeysToEnv) {- window.electronAPI.saveAllKeysToEnv().catch(() => {- // Silently ignore persistence errors+ window.electronAPI.saveAllKeysToEnv().catch((err) => {+ logger.warn(+ "Failed to persist API keys to .env",+ { error: (err as Error).message },+ "settings"+ );});}}, 1000);@@ -397,11 +452,9 @@ export function useSettings() {});- // Wrap setActivationMode to notify main process (for Windows Push-to-Talk)const setActivationMode = useCallback((mode: "tap" | "push") => {setActivationModeLocal(mode);- // Notify main process so Windows key listener can start/stopif (typeof window !== "undefined" && window.electronAPI?.notifyActivationModeChanged) {window.electronAPI.notifyActivationModeChanged(mode);}@@ -409,6 +462,23 @@ export function useSettings() {[setActivationModeLocal]);+ // Sync activation mode from main process on first mount (handles localStorage cleared)+ const hasRunActivationModeSync = useRef(false);+ useEffect(() => {+ if (hasRunActivationModeSync.current) return;+ hasRunActivationModeSync.current = true;++ const sync = async () => {+ if (!window.electronAPI?.getActivationMode) return;+ const envMode = await window.electronAPI.getActivationMode();+ if (envMode && envMode !== activationMode) {+ setActivationModeLocal(envMode);+ }+ };+ sync().catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// Microphone settingsconst [preferBuiltInMic, setPreferBuiltInMic] = useLocalStorage("preferBuiltInMic", true, {serialize: String,@@ -433,7 +503,13 @@ export function useSettings() {reasoningProvider,reasoningModel: reasoningProvider === "local" ? reasoningModel : undefined,})- .catch((err) => console.error("Failed to sync startup preferences:", err));+ .catch((err) =>+ logger.warn(+ "Failed to sync startup preferences",+ { error: (err as Error).message },+ "settings"+ )+ );}, [useLocalWhisper,localTranscriptionProvider,@@ -519,7 +595,10 @@ export function useSettings() {cloudTranscriptionModel,cloudTranscriptionBaseUrl,cloudReasoningBaseUrl,+ cloudTranscriptionMode,customDictionary,+ assemblyAiStreaming,+ setAssemblyAiStreaming,useReasoningModel,reasoningModel,reasoningProvider,@@ -541,6 +620,7 @@ export function useSettings() {setCloudTranscriptionModel,setCloudTranscriptionBaseUrl,setCloudReasoningBaseUrl,+ setCloudTranscriptionMode,setCustomDictionary,setUseReasoningModel,setReasoningModel,@@ -561,6 +641,10 @@ export function useSettings() {selectedMicDeviceId,setPreferBuiltInMic,setSelectedMicDeviceId,+ cloudBackupEnabled,+ setCloudBackupEnabled,+ telemetryEnabled,+ setTelemetryEnabled,updateTranscriptionSettings,updateReasoningSettings,updateApiKeys,diff --git a/src/hooks/useUsage.ts b/src/hooks/useUsage.tsnew file mode 100644index 000000000..4950b9b2b--- /dev/null+++ b/src/hooks/useUsage.ts@@ -0,0 +1,143 @@+import { useState, useEffect, useCallback, useRef } from "react";+import { useAuth } from "./useAuth";+import { CACHE_CONFIG } from "../config/constants";+import { withSessionRefresh } from "../lib/neonAuth";++interface UsageData {+ wordsUsed: number;+ wordsRemaining: number;+ limit: number;+ plan: string;+ isSubscribed: boolean;+ isTrial: boolean;+ trialDaysLeft: number | null;+ currentPeriodEnd: string | null;+ resetAt: string;+}++interface UseUsageResult {+ plan: string;+ wordsUsed: number;+ wordsRemaining: number;+ limit: number;+ isSubscribed: boolean;+ isTrial: boolean;+ trialDaysLeft: number | null;+ currentPeriodEnd: string | null;+ isOverLimit: boolean;+ isApproachingLimit: boolean;+ resetAt: string | null;+ isLoading: boolean;+ hasLoaded: boolean;+ error: string | null;+ refetch: () => Promise<void>;+ openCheckout: () => Promise<void>;+ openBillingPortal: () => Promise<void>;+}++const USAGE_CACHE_TTL = CACHE_CONFIG.API_KEY_TTL; // 1 hour++export function useUsage(): UseUsageResult | null {+ const { isSignedIn, isLoaded } = useAuth();+ const [data, setData] = useState<UsageData | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const [hasLoaded, setHasLoaded] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const lastFetchRef = useRef<number>(0);++ const fetchUsage = useCallback(async () => {+ if (!window.electronAPI?.cloudUsage) return;++ setIsLoading(true);+ setError(null);++ try {+ // Use withSessionRefresh to handle AUTH_EXPIRED automatically+ await withSessionRefresh(async () => {+ const result = await window.electronAPI.cloudUsage();+ if (result.success) {+ setData({+ wordsUsed: result.wordsUsed ?? 0,+ wordsRemaining: result.wordsRemaining ?? 0,+ limit: result.limit ?? 2000,+ plan: result.plan ?? "free",+ isSubscribed: result.isSubscribed ?? false,+ isTrial: result.isTrial ?? false,+ trialDaysLeft: result.trialDaysLeft ?? null,+ currentPeriodEnd: result.currentPeriodEnd ?? null,+ resetAt: result.resetAt ?? "rolling",+ });+ lastFetchRef.current = Date.now();+ } else {+ // Throw error to trigger withSessionRefresh retry logic if needed+ const error: any = new Error(result.error || "Failed to fetch usage");+ error.code = result.code;+ throw error;+ }+ });+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to fetch usage");+ } finally {+ setIsLoading(false);+ setHasLoaded(true);+ }+ }, []);++ // Fetch on mount when signed in, with TTL caching+ useEffect(() => {+ if (!isLoaded || !isSignedIn) return;++ const shouldFetch = Date.now() - lastFetchRef.current > USAGE_CACHE_TTL;+ if (shouldFetch) {+ fetchUsage();+ } else {+ setIsLoading(false);+ setHasLoaded(true);+ }+ }, [isLoaded, isSignedIn, fetchUsage]);++ const openCheckout = useCallback(async () => {+ if (!window.electronAPI?.cloudCheckout || !window.electronAPI?.openExternal) return;+ const result = await window.electronAPI.cloudCheckout();+ if (result.success && result.url) {+ await window.electronAPI.openExternal(result.url);+ }+ }, []);++ const openBillingPortal = useCallback(async () => {+ if (!window.electronAPI?.cloudBillingPortal || !window.electronAPI?.openExternal) return;+ const result = await window.electronAPI.cloudBillingPortal();+ if (result.success && result.url) {+ await window.electronAPI.openExternal(result.url);+ }+ }, []);++ // Return null when not signed in+ if (!isSignedIn) return null;++ const wordsUsed = data?.wordsUsed ?? 0;+ const limit = data?.limit ?? 2000;+ const isSubscribed = data?.isSubscribed ?? false;+ const isOverLimit = !isSubscribed && limit > 0 && wordsUsed >= limit;+ const isApproachingLimit = !isSubscribed && limit > 0 && wordsUsed >= limit * 0.8 && !isOverLimit;++ return {+ plan: data?.plan ?? "free",+ wordsUsed,+ wordsRemaining: data?.wordsRemaining ?? (limit > 0 ? limit - wordsUsed : -1),+ limit,+ isSubscribed,+ isTrial: data?.isTrial ?? false,+ trialDaysLeft: data?.trialDaysLeft ?? null,+ currentPeriodEnd: data?.currentPeriodEnd ?? null,+ isOverLimit,+ isApproachingLimit,+ resetAt: data?.resetAt ?? null,+ isLoading,+ hasLoaded,+ error,+ refetch: fetchUsage,+ openCheckout,+ openBillingPortal,+ };+}diff --git a/src/index.css b/src/index.cssindex a4faa2873..dc25ce3a0 100644--- a/src/index.css+++ b/src/index.css@@ -54,12 +54,12 @@--opacity-medium: 0.5;--opacity-high: 0.9;- /* Border Radius — generous Clerk-style rounding */- --radius: 0.625rem;- --radius-sm: 0.375rem;- --radius-md: 0.5rem;- --radius-lg: 0.625rem;- --radius-xl: 0.875rem;+ /* Border Radius — ultra-tight, premium macOS-style rounding */+ --radius: 0.375rem; /* 6px - default for buttons, inputs */+ --radius-sm: 0.25rem; /* 4px - minimal rounding */+ --radius-md: 0.375rem; /* 6px - standard */+ --radius-lg: 0.5rem; /* 8px - cards, panels */+ --radius-xl: 0.5rem; /* 8px - large cards (reduced from 10px) *//* Custom Light Mode Brand Colors (Parchment Theme) */--color-parchment-bg: #f9f6f1;@@ -71,6 +71,10 @@--color-brand-highlight: #c0a77d;--color-brand-link: #2e3659;--color-pattern: #e7e5e4;++ /* Model picker premium effects (light mode) */+ --shadow-metallic-light: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 1px 3px rgba(0, 0, 0, 0.08);+ --shadow-card-hover-subtle: 0 2px 8px -2px rgba(0, 0, 0, 0.1);}.dark {@@ -87,7 +91,7 @@--color-secondary-foreground: oklch(0.92 0 0);--color-muted: oklch(0.13 0.005 270);--color-muted-foreground: oklch(0.55 0 0);- --color-accent: oklch(0.68 0.20 285);+ --color-accent: oklch(0.68 0.2 285);--color-accent-foreground: oklch(0.99 0 0);--color-destructive: oklch(0.6 0.25 25);--color-destructive-foreground: oklch(0.99 0 0);@@ -112,12 +116,19 @@--color-border-subtle: oklch(0.2 0.004 270);--color-border-hover: oklch(0.28 0.01 270);--color-border-active: oklch(0.45 0.15 260);+ --color-link: oklch(0.64 0.09 250);/* Card depth shadows — no glow, clean depth only */--shadow-card: 0 1px 2px oklch(0 0 0 / 0.25);--shadow-card-hover: 0 2px 8px oklch(0 0 0 / 0.35);--shadow-elevated: 0 8px 24px oklch(0 0 0 / 0.4);--shadow-modal: 0 24px 48px -12px oklch(0 0 0 / 0.5);++ /* Model picker premium effects */+ --shadow-metallic-dark: inset 0 1px 0 rgba(255, 255, 255, 0.03), 0 2px 8px rgba(0, 0, 0, 0.3);+ --shadow-selected-glow:+ inset 0 0 0 1px oklch(0.62 0.22 260 / 0.15), 0 0 16px -4px oklch(0.62 0.22 260 / 0.25);+ --shadow-card-hover-subtle: 0 2px 8px -2px rgba(0, 0, 0, 0.15);}@layer base {@@ -212,13 +223,13 @@ svg:hover,cursor: pointer;}-/* Embossed paper-like input styling */+/* Premium input styling with subtle depth */input,textarea {- border-radius: 8px;+ border-radius: var(--radius);transition: all 0.2s ease;font-family: var(--font-family-sans);- box-shadow: inset 0 1px 3px rgba(43, 31, 20, var(--opacity-subtle));+ box-shadow: inset 0 1px 2px oklch(from var(--color-foreground) l c h / 0.06);}/* Light mode inputs - embossed parchment */@@ -243,31 +254,27 @@ textarea {.dark textarea {background-color: var(--color-input);border: 1px solid var(--color-border);- color: oklch(0.9 0 0);+ color: var(--color-foreground);box-shadow: none;}.dark input:focus,.dark textarea:focus {border-color: var(--color-border-active);- box-shadow: 0 0 0 2px oklch(0.62 0.22 260 / 0.15);+ box-shadow: 0 0 0 2px oklch(from var(--color-ring) l c h / 0.15);}/* Card styling - elevated parchment */.card {background-color: var(--color-card);- border: 1px solid var(--color-parchment-border);- border-radius: 12px;- box-shadow:- 0 4px 8px oklch(from var(--color-parchment-text) l c h / 0.08),- 0 1px 0 oklch(from var(--color-card) l c h / var(--opacity-medium)) inset;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ box-shadow: var(--shadow-card, 0 1px 3px oklch(from var(--color-foreground) l c h / 0.08));transition: all 0.2s ease;}.card:hover {- box-shadow:- 0 8px 16px oklch(from var(--color-parchment-text) l c h / var(--opacity-subtle)),- 0 1px 0 oklch(from var(--color-card) l c h / var(--opacity-medium)) inset;+ box-shadow: var(--shadow-card-hover, 0 4px 12px oklch(from var(--color-foreground) l c h / 0.1));transform: translateY(-1px);}@@ -285,15 +292,15 @@ textarea {/* Link styling */a {- color: var(--color-brand-link);+ color: var(--color-link);text-decoration: none;transition: color 0.2s ease;cursor: pointer;}a:hover {- color: var(--color-brand-accent);- text-decoration: underline;+ color: var(--color-link);+ opacity: 0.8;cursor: pointer;}@@ -370,6 +377,41 @@ a:hover {}}+/* Model picker LED pulse animation */+@keyframes pulse-glow {+ 0%,+ 100% {+ box-shadow: 0 0 6px oklch(0.62 0.22 260 / 0.4);+ opacity: 0.8;+ }+ 50% {+ box-shadow: 0 0 8px oklch(0.62 0.22 260 / 0.6);+ opacity: 1;+ }+}++/* Spinner rotation for downloading state */+@keyframes spinner-rotate {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+}++/* Scale-in animation for completion */+@keyframes scale-in {+ from {+ transform: scale(0.8);+ opacity: 0;+ }+ to {+ transform: scale(1);+ opacity: 1;+ }+}+/* Custom scrollbar styling for Windows/Linux (Chromium) */::-webkit-scrollbar {width: 8px;diff --git a/src/lib/neonAuth.ts b/src/lib/neonAuth.tsnew file mode 100644index 000000000..009247c12--- /dev/null+++ b/src/lib/neonAuth.ts@@ -0,0 +1,272 @@+import { createAuthClient } from "@neondatabase/auth";+import { BetterAuthReactAdapter } from "@neondatabase/auth/react";++export const NEON_AUTH_URL = import.meta.env.VITE_NEON_AUTH_URL || "";+export const authClient = NEON_AUTH_URL+ ? createAuthClient(NEON_AUTH_URL, { adapter: BetterAuthReactAdapter() })+ : null;++export type SocialProvider = "google";++const LAST_SIGN_IN_STORAGE_KEY = "openwhispr:lastSignInTime";+const GRACE_PERIOD_MS = 60_000;+const GRACE_RETRY_COUNT = 6;+const INITIAL_GRACE_RETRY_DELAY_MS = 500;++let lastSignInTime: number | null = null;++function getLocalStorageSafe(): Storage | null {+ if (typeof window === "undefined") return null;+ try {+ return window.localStorage;+ } catch {+ return null;+ }+}++function loadLastSignInTimeFromStorage(): number | null {+ const storage = getLocalStorageSafe();+ if (!storage) return null;++ const raw = storage.getItem(LAST_SIGN_IN_STORAGE_KEY);+ if (!raw) return null;++ const parsed = Number(raw);+ if (!Number.isFinite(parsed) || parsed <= 0) {+ storage.removeItem(LAST_SIGN_IN_STORAGE_KEY);+ return null;+ }++ return parsed;+}++function persistLastSignInTime(value: number | null): void {+ const storage = getLocalStorageSafe();+ if (!storage) return;++ if (value === null) {+ storage.removeItem(LAST_SIGN_IN_STORAGE_KEY);+ } else {+ storage.setItem(LAST_SIGN_IN_STORAGE_KEY, String(value));+ }+}++function getLastSignInTime(): number | null {+ const stored = loadLastSignInTimeFromStorage();+ if (stored !== null) {+ lastSignInTime = stored;+ }+ return lastSignInTime;+}++function createAuthExpiredError(originalError: unknown): Error {+ if (originalError instanceof Error) {+ (originalError as Error & { code?: string }).code = "AUTH_EXPIRED";+ return originalError;+ }++ const error = new Error("Session expired");+ (error as Error & { code?: string }).code = "AUTH_EXPIRED";+ return error;+}++export function clearLastSignInTime(): void {+ lastSignInTime = null;+ persistLastSignInTime(null);+}++function markSignedOutState(): void {+ const storage = getLocalStorageSafe();+ storage?.setItem("isSignedIn", "false");+ clearLastSignInTime();+}++/**+ * Updates the last sign-in timestamp. Call this after successful OAuth.+ */+export function updateLastSignInTime(): void {+ const now = Date.now();+ lastSignInTime = now;+ persistLastSignInTime(now);+}++/**+ * Check if we're within the grace period after sign-in.+ * Exported so useAuth can also suppress premature sign-outs.+ */+export function isWithinGracePeriod(): boolean {+ const startedAt = getLastSignInTime();+ if (!startedAt) return false;++ const elapsed = Math.max(0, Date.now() - startedAt);+ return elapsed < GRACE_PERIOD_MS;+}++/**+ * Attempts to refresh the current session by calling getSession().+ * The Neon Auth SDK automatically refreshes expired tokens when this is called.+ * Returns true if a valid session exists after refresh, false otherwise.+ */+export async function refreshSession(): Promise<boolean> {+ if (!authClient) {+ return false;+ }++ try {+ const result = await authClient.getSession();+ return Boolean(result.data?.session?.user);+ } catch {+ return false;+ }+}++/**+ * Signs out the user and clears all session cookies.+ * This is useful when session refresh fails and we need to fully clear the stale session.+ */+export async function signOut(): Promise<void> {+ try {+ // Clear session cookies via IPC+ if (window.electronAPI?.authClearSession) {+ await window.electronAPI.authClearSession();+ }++ // Sign out via auth client if available+ if (authClient) {+ await authClient.signOut();+ }++ // Clear local storage+ markSignedOutState();+ } catch {+ // Fallback: at minimum clear local storage+ markSignedOutState();+ }+}++/**+ * Utility to wrap API calls that may fail due to expired session.+ * Automatically retries AUTH_EXPIRED calls during OAuth grace, then attempts a+ * single session refresh before surfacing the auth error to the caller.+ *+ * During the grace period, retries the operation with exponential backoff to wait+ * for session cookies to establish.+ *+ * @param operation - The async operation to perform+ * @returns The result of the operation+ */+export async function withSessionRefresh<T>(operation: () => Promise<T>): Promise<T> {+ const startedInGracePeriod = isWithinGracePeriod();+ let graceRetriesUsed = 0;+ let refreshAttempted = false;++ while (true) {+ try {+ return await operation();+ } catch (error: any) {+ const isAuthExpired =+ error?.code === "AUTH_EXPIRED" ||+ error?.message?.toLowerCase().includes("session expired") ||+ error?.message?.toLowerCase().includes("auth expired");++ if (!isAuthExpired) {+ throw error;+ }++ if (startedInGracePeriod && graceRetriesUsed < GRACE_RETRY_COUNT) {+ const delayMs = INITIAL_GRACE_RETRY_DELAY_MS * Math.pow(2, graceRetriesUsed);+ graceRetriesUsed += 1;+ await new Promise((resolve) => setTimeout(resolve, delayMs));+ continue;+ }++ if (!refreshAttempted) {+ refreshAttempted = true;+ const refreshed = await refreshSession();+ if (refreshed) {+ continue;+ }+ }++ markSignedOutState();+ throw createAuthExpiredError(error);+ }+ }+}++export async function signInWithSocial(provider: SocialProvider): Promise<{ error?: Error }> {+ if (!authClient) {+ return { error: new Error("Auth not configured") };+ }++ try {+ // Build an absolute callback URL. Neon Auth redirects here after OAuth.+ // In the browser, this page detects it's outside Electron and redirects+ // to the app's custom protocol to hand the verifier back to Electron.+ const base = window.location.href.split("?")[0].split("#")[0];+ const callbackURL = `${base}?panel=true`;++ await authClient.signIn.social({+ provider,+ callbackURL,+ newUserCallbackURL: callbackURL,+ });++ return {};+ } catch (error) {+ return { error: error instanceof Error ? error : new Error("Social sign-in failed") };+ }+}++/**+ * Requests a password reset email to be sent to the specified email address.+ * The email contains a link that redirects to the app with a reset token.+ */+export async function requestPasswordReset(email: string): Promise<{ error?: Error }> {+ if (!authClient) {+ return { error: new Error("Auth not configured") };+ }++ try {+ // Build the redirect URL for the password reset link.+ // This will redirect back to the app with a token parameter.+ const base = window.location.href.split("?")[0].split("#")[0];+ const redirectTo = `${base}?panel=true&reset_password=true`;++ await authClient.requestPasswordReset({+ email: email.trim(),+ redirectTo,+ });++ return {};+ } catch (error) {+ return { error: error instanceof Error ? error : new Error("Failed to send reset email") };+ }+}++/**+ * Resets the user's password using the token from the reset email.+ * After successful reset, the user is automatically signed in.+ */+export async function resetPassword(+ newPassword: string,+ token: string+): Promise<{ error?: Error }> {+ if (!authClient) {+ return { error: new Error("Auth not configured") };+ }++ try {+ await authClient.resetPassword({+ newPassword,+ token,+ });++ // Mark sign-in time for grace period after password reset+ updateLastSignInTime();++ return {};+ } catch (error) {+ return { error: error instanceof Error ? error : new Error("Failed to reset password") };+ }+}diff --git a/src/main.jsx b/src/main.jsxindex 664e479ed..e6c35fa85 100644--- a/src/main.jsx+++ b/src/main.jsx@@ -3,10 +3,258 @@ import ReactDOM from "react-dom/client";import App from "./App.jsx";import ControlPanel from "./components/ControlPanel.tsx";import OnboardingFlow from "./components/OnboardingFlow.tsx";+import ErrorBoundary from "./components/ErrorBoundary.tsx";import { ToastProvider } from "./components/ui/Toast.tsx";import { useTheme } from "./hooks/useTheme";import "./index.css";+let root = null;++const VALID_CHANNELS = new Set(["development", "staging", "production"]);+const DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL = {+ development: "openwhispr-dev",+ staging: "openwhispr-staging",+ production: "openwhispr",+};+const inferredChannel = import.meta.env.DEV ? "development" : "production";+const configuredChannel = (import.meta.env.VITE_OPENWHISPR_CHANNEL || inferredChannel)+ .trim()+ .toLowerCase();+const APP_CHANNEL = VALID_CHANNELS.has(configuredChannel) ? configuredChannel : inferredChannel;+const defaultOAuthProtocol =+ DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL[APP_CHANNEL] || DEFAULT_OAUTH_PROTOCOL_BY_CHANNEL.production;+const OAUTH_PROTOCOL = (import.meta.env.VITE_OPENWHISPR_PROTOCOL || defaultOAuthProtocol)+ .trim()+ .toLowerCase();+const OAUTH_AUTH_BRIDGE_URL = (import.meta.env.VITE_OPENWHISPR_AUTH_BRIDGE_URL || "").trim();++// OAuth callback handler: when the browser redirects back from Google/Neon Auth+// with a session verifier, redirect to the configured custom protocol so Electron+// can capture it and complete authentication. This check runs before React+// mounts — if we detect we're in the system browser with a verifier, we+// redirect immediately and skip mounting the app entirely.+function isOAuthBrowserRedirect() {+ const params = new URLSearchParams(window.location.search);+ const verifier = params.get("neon_auth_session_verifier");+ const isInElectron = typeof window.electronAPI !== "undefined";++ if (verifier && !isInElectron) {+ if (OAUTH_AUTH_BRIDGE_URL) {+ try {+ const bridgeUrl = new URL(OAUTH_AUTH_BRIDGE_URL);+ bridgeUrl.searchParams.set("neon_auth_session_verifier", verifier);+ window.location.replace(bridgeUrl.toString());+ return true;+ } catch {+ // Fall back to protocol redirect below.+ }+ }++ setTimeout(() => {+ window.location.href = `${OAUTH_PROTOCOL}://auth/callback?neon_auth_session_verifier=${encodeURIComponent(verifier)}`;+ }, 2000);++ // Show an ultra-premium branded message while waiting+ document.body.innerHTML = `+ <style>+ /* Design tokens from index.css — single source of truth */+ :root {+ --bg: #ffffff;+ --surface-1: #fafafa;+ --surface-2: #ffffff;+ --border: #e5e5e5;+ --border-subtle: #e5e5e5;+ --text-primary: #171717;+ --text-muted: #737373;+ --primary: #2563eb;+ --shadow-card: 0 1px 3px rgba(0, 0, 0, 0.08);+ --shadow-elevated: 0 8px 24px rgba(0, 0, 0, 0.12);+ }++ @media (prefers-color-scheme: dark) {+ :root {+ --bg: oklch(0.1 0.005 270);+ --surface-1: oklch(0.13 0.006 270);+ --surface-2: oklch(0.155 0.008 270);+ --border: oklch(0.23 0.005 270);+ --border-subtle: oklch(0.2 0.004 270);+ --text-primary: oklch(0.95 0 0);+ --text-muted: oklch(0.55 0 0);+ --primary: oklch(0.62 0.22 260);+ --shadow-card: 0 1px 2px rgba(0, 0, 0, 0.25);+ --shadow-elevated: 0 8px 24px rgba(0, 0, 0, 0.4);+ }+ }++ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ background: var(--bg);+ color: var(--text-primary);+ font-family: "Noto Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ transition: background 150ms ease, color 150ms ease;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ }++ #oauth-container {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 100vh;+ padding: 20px;+ }++ /* Premium glass card — native macOS feel */+ .auth-card {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 16px;+ padding: 32px 40px;+ background: var(--surface-2);+ border: 1px solid var(--border);+ border-radius: 8px;+ box-shadow: var(--shadow-elevated);+ animation: fade-in 300ms ease-out;+ }++ @media (prefers-color-scheme: dark) {+ .auth-card {+ background: var(--surface-2);+ border: 1px solid var(--border);+ box-shadow: var(--shadow-elevated), 0 0 0 1px rgba(255, 255, 255, 0.03);+ }+ }++ /* Logo container with refined drop shadow */+ .logo-wrapper {+ position: relative;+ margin-bottom: 4px;+ }++ .logo {+ display: block;+ filter: drop-shadow(0 2px 8px rgba(37, 99, 235, 0.18));+ }++ @media (prefers-color-scheme: dark) {+ .logo {+ filter: drop-shadow(0 2px 12px rgba(100, 149, 237, 0.25));+ }+ }++ /* Premium spinner with metallic feel */+ .spinner-wrapper {+ position: relative;+ width: 28px;+ height: 28px;+ }++ .spinner {+ width: 28px;+ height: 28px;+ border: 2.5px solid transparent;+ border-top-color: var(--primary);+ border-radius: 50%;+ animation: spinner-rotate 0.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;+ }++ /* Tight, minimal text hierarchy */+ .content {+ text-align: center;+ line-height: 1.4;+ }++ h1 {+ font-size: 15px;+ font-weight: 600;+ letter-spacing: -0.01em;+ color: var(--text-primary);+ margin-bottom: 2px;+ }++ .subtitle {+ font-size: 13px;+ font-weight: 500;+ color: var(--text-muted);+ opacity: 0.8;+ }++ /* Smooth animations */+ @keyframes fade-in {+ from {+ opacity: 0;+ transform: translateY(4px) scale(0.98);+ }+ to {+ opacity: 1;+ transform: translateY(0) scale(1);+ }+ }++ @keyframes spinner-rotate {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+ }++ /* Accessibility — respect reduced motion */+ @media (prefers-reduced-motion: reduce) {+ .auth-card {+ animation: fade-in-simple 200ms ease-out;+ }+ @keyframes fade-in-simple {+ from { opacity: 0; }+ to { opacity: 1; }+ }+ .spinner {+ animation: none;+ border-top-color: var(--text-muted);+ opacity: 0.5;+ }+ }+ </style>++ <div id="oauth-container" role="status" aria-live="polite">+ <div class="auth-card">+ <div class="logo-wrapper">+ <svg class="logo" viewBox="0 0 1024 1024" width="64" height="64" aria-label="OpenWhispr">+ <rect width="1024" height="1024" rx="241" fill="#2056DF"/>+ <circle cx="512" cy="512" r="314" fill="#2056DF" stroke="white" stroke-width="74"/>+ <path d="M512 383V641" stroke="white" stroke-width="74" stroke-linecap="round"/>+ <path d="M627 457V568" stroke="white" stroke-width="74" stroke-linecap="round"/>+ <path d="M397 457V568" stroke="white" stroke-width="74" stroke-linecap="round"/>+ </svg>+ </div>++ <div class="spinner-wrapper">+ <div class="spinner"></div>+ </div>++ <div class="content">+ <h1>Redirecting to OpenWhispr</h1>+ <p class="subtitle">You can close this tab</p>+ </div>+ </div>+ </div>+ `;+ return true;+ }+ return false;+}++if (!isOAuthBrowserRedirect()) {+ mountApp();+}+function AppRouter() {// Initialize theme systemuseTheme();@@ -64,10 +312,21 @@ function AppRouter() {return isControlPanel ? <ControlPanel /> : <App />;}-ReactDOM.createRoot(document.getElementById("root")).render(- <React.StrictMode>- <ToastProvider>- <AppRouter />- </ToastProvider>- </React.StrictMode>-);+function mountApp() {+ if (!root) {+ root = ReactDOM.createRoot(document.getElementById("root"));+ }+ root.render(+ <React.StrictMode>+ <ErrorBoundary>+ <ToastProvider>+ <AppRouter />+ </ToastProvider>+ </ErrorBoundary>+ </React.StrictMode>+ );+}++if (import.meta.hot) {+ import.meta.hot.accept();+}diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.tsindex cf62d753d..eddfcf83c 100644--- a/src/models/ModelRegistry.ts+++ b/src/models/ModelRegistry.ts@@ -243,6 +243,15 @@ export function getReasoningModelLabel(modelId: string): string {}export function getModelProvider(modelId: string): string {+ // When in OpenWhispr cloud mode, route reasoning through the cloud API+ if (typeof localStorage !== "undefined") {+ const cloudMode = localStorage.getItem("cloudTranscriptionMode");+ const isSignedIn = localStorage.getItem("isSignedIn") === "true";+ if (cloudMode === "openwhispr" && isSignedIn) {+ return "openwhispr";+ }+ }+const model = getAllReasoningModels().find((m) => m.value === modelId);if (!model) {diff --git a/src/models/modelRegistryData.json b/src/models/modelRegistryData.jsonindex 4b74d0fa1..20443d3b8 100644--- a/src/models/modelRegistryData.json+++ b/src/models/modelRegistryData.json@@ -7,31 +7,31 @@"sizeMb": 680,"language": "multilingual","supportedLanguages": [+ "bg",+ "hr",+ "cs",+ "da",+ "nl","en",- "de",- "es",+ "et",+ "fi","fr",+ "de",+ "el",+ "hu","it",- "pt",- "nl",+ "lv",+ "lt",+ "mt","pl",- "ru",- "uk",- "zh",- "ja",- "ko",- "ar",- "hi",- "tr",- "vi",- "th",- "id",- "cs",+ "pt","ro",- "hu",- "el",- "he",- "sv"+ "sk",+ "sl",+ "es",+ "sv",+ "ru",+ "uk"],"recommended": true,"downloadUrl": "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2",@@ -471,5 +471,63 @@}]}- ]+ ],+ "openwhisprCloudModels": {+ "tiers": [+ {+ "id": "fast",+ "label": "Fast",+ "provider": "groq",+ "models": [+ {+ "id": "llama-3.3-70b-versatile",+ "name": "Llama 3.3 70B",+ "description": "Fast, high-quality reasoning",+ "recommended": true+ },+ {+ "id": "llama-3.1-8b-instant",+ "name": "Llama 3.1 8B",+ "description": "Ultra-fast, low latency"+ }+ ]+ },+ {+ "id": "balanced",+ "label": "Balanced",+ "provider": "openrouter",+ "models": [+ {+ "id": "anthropic/claude-sonnet-4",+ "name": "Claude Sonnet 4",+ "description": "Balanced performance and quality",+ "recommended": true+ },+ {+ "id": "google/gemini-2.5-flash",+ "name": "Gemini 2.5 Flash",+ "description": "Fast with strong reasoning"+ }+ ]+ },+ {+ "id": "quality",+ "label": "Quality",+ "provider": "openrouter",+ "models": [+ {+ "id": "anthropic/claude-opus-4",+ "name": "Claude Opus 4",+ "description": "Most capable, highest quality",+ "recommended": true+ },+ {+ "id": "openai/gpt-4.1",+ "name": "GPT-4.1",+ "description": "Strong general-purpose reasoning"+ }+ ]+ }+ ]+ }}diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.tsindex 7b726350e..781c80657 100644--- a/src/services/BaseReasoningService.ts+++ b/src/services/BaseReasoningService.ts@@ -21,8 +21,14 @@ export abstract class BaseReasoningService {}}+ protected getPreferredLanguage(): string {+ if (typeof window === "undefined" || !window.localStorage) return "auto";+ return window.localStorage.getItem("preferredLanguage") || "auto";+ }+protected getSystemPrompt(agentName: string | null): string {- return getSystemPrompt(agentName, this.getCustomDictionary());+ const language = this.getPreferredLanguage();+ return getSystemPrompt(agentName, this.getCustomDictionary(), language);}protected calculateMaxTokens(diff --git a/src/services/LocalReasoningService.ts b/src/services/LocalReasoningService.tsindex 5db5b869c..91cea5a1e 100644--- a/src/services/LocalReasoningService.ts+++ b/src/services/LocalReasoningService.ts@@ -85,7 +85,7 @@ class LocalReasoningService extends BaseReasoningService {stack: (error as Error).stack,});- console.error("LocalReasoningService error:", error);+ logger.error("LocalReasoningService error", { error: (error as Error).message }, "reasoning");throw error;} finally {this.isProcessing = false;@@ -98,7 +98,11 @@ class LocalReasoningService extends BaseReasoningService {await modelManager.ensureLlamaCpp();return true;} catch (error) {- console.warn("Local reasoning not available:", (error as Error).message);+ logger.warn(+ "Local reasoning not available",+ { error: (error as Error).message },+ "reasoning"+ );return false;}}@@ -109,7 +113,11 @@ class LocalReasoningService extends BaseReasoningService {const modelsWithStatus = await modelManager.getModelsWithStatus();return modelsWithStatus.filter((model) => model.isDownloaded);} catch (error) {- console.error("Failed to get downloaded models:", error);+ logger.error(+ "Failed to get downloaded models",+ { error: (error as Error).message },+ "reasoning"+ );return [];}}diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.tsindex 31da21ae3..5849e4956 100644--- a/src/services/ReasoningService.ts+++ b/src/services/ReasoningService.ts@@ -6,6 +6,7 @@ import { API_ENDPOINTS, TOKEN_LIMITS, buildApiUrl, normalizeBaseUrl } from "../cimport { UNIFIED_SYSTEM_PROMPT, LEGACY_PROMPTS } from "../config/prompts";import logger from "../utils/logger";import { isSecureEndpoint } from "../utils/urlUtils";+import { withSessionRefresh } from "../lib/neonAuth";/*** @deprecated Use UNIFIED_SYSTEM_PROMPT from ../config/prompts instead@@ -23,6 +24,10 @@ class ReasoningService extends BaseReasoningService {super();this.apiKeyCache = new SecureCache();this.cacheCleanupStop = this.apiKeyCache.startAutoCleanup();++ if (typeof window !== "undefined") {+ window.addEventListener("beforeunload", () => this.destroy());+ }}private getConfiguredOpenAIBase(): string {@@ -300,52 +305,64 @@ class ReasoningService extends BaseReasoningService {});const response = await withRetry(async () => {- const res = await fetch(endpoint, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${apiKey}`,- },- body: JSON.stringify(requestBody),- });+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30000);+ try {+ const res = await fetch(endpoint, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${apiKey}`,+ },+ body: JSON.stringify(requestBody),+ signal: controller.signal,+ });- if (!res.ok) {- const errorText = await res.text();- let errorData: any = { error: res.statusText };+ if (!res.ok) {+ const errorText = await res.text();+ let errorData: any = { error: res.statusText };- try {- errorData = JSON.parse(errorText);- } catch {- errorData = { error: errorText || res.statusText };- }+ try {+ errorData = JSON.parse(errorText);+ } catch {+ errorData = { error: errorText || res.statusText };+ }- logger.logReasoning(`${providerName.toUpperCase()}_API_ERROR_DETAIL`, {- status: res.status,- statusText: res.statusText,- error: errorData,- errorMessage: errorData.error?.message || errorData.message || errorData.error,- fullResponse: errorText.substring(0, 500),- });+ logger.logReasoning(`${providerName.toUpperCase()}_API_ERROR_DETAIL`, {+ status: res.status,+ statusText: res.statusText,+ error: errorData,+ errorMessage: errorData.error?.message || errorData.message || errorData.error,+ fullResponse: errorText.substring(0, 500),+ });- const errorMessage =- errorData.error?.message ||- errorData.message ||- errorData.error ||- `${providerName} API error: ${res.status}`;- throw new Error(errorMessage);- }+ const errorMessage =+ errorData.error?.message ||+ errorData.message ||+ errorData.error ||+ `${providerName} API error: ${res.status}`;+ throw new Error(errorMessage);+ }- const jsonResponse = await res.json();+ const jsonResponse = await res.json();- logger.logReasoning(`${providerName.toUpperCase()}_RAW_RESPONSE`, {- hasResponse: !!jsonResponse,- responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],- hasChoices: !!jsonResponse?.choices,- choicesLength: jsonResponse?.choices?.length || 0,- fullResponse: JSON.stringify(jsonResponse).substring(0, 500),- });+ logger.logReasoning(`${providerName.toUpperCase()}_RAW_RESPONSE`, {+ hasResponse: !!jsonResponse,+ responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],+ hasChoices: !!jsonResponse?.choices,+ choicesLength: jsonResponse?.choices?.length || 0,+ fullResponse: JSON.stringify(jsonResponse).substring(0, 500),+ });- return jsonResponse;+ return jsonResponse;+ } catch (error) {+ if ((error as Error).name === "AbortError") {+ throw new Error("Request timed out after 30s");+ }+ throw error;+ } finally {+ clearTimeout(timeoutId);+ }}, createApiRetryStrategy());if (!response.choices || !response.choices[0]) {@@ -427,6 +444,9 @@ class ReasoningService extends BaseReasoningService {case "groq":result = await this.processWithGroq(text, model, agentName, config);break;+ case "openwhispr":+ result = await this.processWithOpenWhispr(text, model, agentName, config);+ break;default:throw new Error(`Unsupported reasoning provider: ${provider}`);}@@ -518,6 +538,8 @@ class ReasoningService extends BaseReasoningService {let lastError: Error | null = null;for (const { url: endpoint, type } of endpointCandidates) {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30000);try {const requestBody: any = { model };@@ -538,6 +560,7 @@ class ReasoningService extends BaseReasoningService {Authorization: `Bearer ${apiKey}`,},body: JSON.stringify(requestBody),+ signal: controller.signal,});if (!res.ok) {@@ -564,6 +587,9 @@ class ReasoningService extends BaseReasoningService {this.rememberOpenAiPreference(openAiBase, type);return res.json();} catch (error) {+ if ((error as Error).name === "AbortError") {+ throw new Error("Request timed out after 30s");+ }lastError = error as Error;if (type === "responses") {logger.logReasoning("OPENAI_ENDPOINT_FALLBACK", {@@ -573,6 +599,8 @@ class ReasoningService extends BaseReasoningService {continue;}throw error;+ } finally {+ clearTimeout(timeoutId);}}@@ -691,12 +719,11 @@ class ReasoningService extends BaseReasoningService {textLength: text.length,});- const result = await window.electronAPI.processAnthropicReasoning(- text,- model,- agentName,- config- );+ const language = this.getPreferredLanguage();+ const result = await window.electronAPI.processAnthropicReasoning(text, model, agentName, {+ ...config,+ language,+ });const processingTime = Date.now() - startTime;@@ -743,7 +770,11 @@ class ReasoningService extends BaseReasoningService {textLength: text.length,});- const result = await window.electronAPI.processLocalReasoning(text, model, agentName, config);+ const language = this.getPreferredLanguage();+ const result = await window.electronAPI.processLocalReasoning(text, model, agentName, {+ ...config,+ language,+ });const processingTime = Date.now() - startTime;@@ -835,52 +866,64 @@ class ReasoningService extends BaseReasoningService {requestBody: JSON.stringify(requestBody).substring(0, 200),});- const res = await fetch(`${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`, {- method: "POST",- headers: {- "Content-Type": "application/json",- "x-goog-api-key": apiKey,- },- body: JSON.stringify(requestBody),- });+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30000);+ try {+ const res = await fetch(`${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "x-goog-api-key": apiKey,+ },+ body: JSON.stringify(requestBody),+ signal: controller.signal,+ });- if (!res.ok) {- const errorText = await res.text();- let errorData: any = { error: res.statusText };+ if (!res.ok) {+ const errorText = await res.text();+ let errorData: any = { error: res.statusText };- try {- errorData = JSON.parse(errorText);- } catch {- errorData = { error: errorText || res.statusText };- }+ try {+ errorData = JSON.parse(errorText);+ } catch {+ errorData = { error: errorText || res.statusText };+ }- logger.logReasoning("GEMINI_API_ERROR_DETAIL", {- status: res.status,- statusText: res.statusText,- error: errorData,- errorMessage: errorData.error?.message || errorData.message || errorData.error,- fullResponse: errorText.substring(0, 500),- });+ logger.logReasoning("GEMINI_API_ERROR_DETAIL", {+ status: res.status,+ statusText: res.statusText,+ error: errorData,+ errorMessage: errorData.error?.message || errorData.message || errorData.error,+ fullResponse: errorText.substring(0, 500),+ });- const errorMessage =- errorData.error?.message ||- errorData.message ||- errorData.error ||- `Gemini API error: ${res.status}`;- throw new Error(errorMessage);- }+ const errorMessage =+ errorData.error?.message ||+ errorData.message ||+ errorData.error ||+ `Gemini API error: ${res.status}`;+ throw new Error(errorMessage);+ }- const jsonResponse = await res.json();+ const jsonResponse = await res.json();- logger.logReasoning("GEMINI_RAW_RESPONSE", {- hasResponse: !!jsonResponse,- responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],- hasCandidates: !!jsonResponse?.candidates,- candidatesLength: jsonResponse?.candidates?.length || 0,- fullResponse: JSON.stringify(jsonResponse).substring(0, 500),- });+ logger.logReasoning("GEMINI_RAW_RESPONSE", {+ hasResponse: !!jsonResponse,+ responseKeys: jsonResponse ? Object.keys(jsonResponse) : [],+ hasCandidates: !!jsonResponse?.candidates,+ candidatesLength: jsonResponse?.candidates?.length || 0,+ fullResponse: JSON.stringify(jsonResponse).substring(0, 500),+ });- return jsonResponse;+ return jsonResponse;+ } catch (error) {+ if ((error as Error).name === "AbortError") {+ throw new Error("Request timed out after 30s");+ }+ throw error;+ } finally {+ clearTimeout(timeoutId);+ }}, createApiRetryStrategy());} catch (fetchError) {logger.logReasoning("GEMINI_FETCH_ERROR", {@@ -978,6 +1021,71 @@ class ReasoningService extends BaseReasoningService {}}+ private async processWithOpenWhispr(+ text: string,+ model: string,+ agentName: string | null = null,+ config: ReasoningConfig = {}+ ): Promise<string> {+ logger.logReasoning("OPENWHISPR_START", { model, agentName });++ if (this.isProcessing) {+ throw new Error("Already processing a request");+ }++ this.isProcessing = true;++ try {+ const customDictionary = this.getCustomDictionary();+ const language = this.getPreferredLanguage();++ // Use withSessionRefresh to handle AUTH_EXPIRED automatically+ const result = await withSessionRefresh(async () => {+ const res = await (window as any).electronAPI.cloudReason(text, {+ model,+ agentName,+ customDictionary,+ language,+ });++ if (!res.success) {+ const err: any = new Error(res.error || "OpenWhispr cloud reasoning failed");+ err.code = res.code;+ throw err;+ }++ return res;+ });++ logger.logReasoning("OPENWHISPR_SUCCESS", {+ model: result.model,+ provider: result.provider,+ resultLength: result.text.length,+ });++ return result.text;+ } catch (error) {+ logger.logReasoning("OPENWHISPR_ERROR", {+ model,+ error: (error as Error).message,+ });+ throw error;+ } finally {+ this.isProcessing = false;+ }+ }++ private getCustomDictionary(): string[] {+ try {+ const raw = localStorage.getItem("customDictionary");+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+ }+async isAvailable(): Promise<boolean> {try {const openaiKey = await window.electronAPI?.getOpenAIKey?.();diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.jsindex b7251ba27..1e8379208 100644--- a/src/services/localReasoningBridge.js+++ b/src/services/localReasoningBridge.js@@ -49,7 +49,7 @@ class LocalReasoningService {repeatPenalty: config.repeatPenalty || 1.1,contextSize: config.contextSize || 4096,threads: config.threads || 4,- systemPrompt: getSystemPrompt(agentName, config.customDictionary),+ systemPrompt: getSystemPrompt(agentName, config.customDictionary, config.language),};debugLogger.logReasoning("LOCAL_BRIDGE_INFERENCE", {diff --git a/src/types/electron.ts b/src/types/electron.tsindex 085f244f3..090e6e1d8 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -166,7 +166,7 @@ declare global {interface Window {electronAPI: {// Basic window operations- pasteText: (text: string) => Promise<void>;+ pasteText: (text: string, options?: { fromStreaming?: boolean }) => Promise<void>;hideWindow: () => Promise<void>;showDictationPanel: () => Promise<void>;onToggleDictation: (callback: () => void) => (() => void) | void;@@ -339,6 +339,7 @@ declare global {// Globe key listener for hotkey capture (macOS only)onGlobeKeyPressed?: (callback: () => void) => () => void;+ onGlobeKeyReleased?: (callback: () => void) => () => void;// Hotkey registration eventsonHotkeyFallbackUsed?: (@@ -366,6 +367,10 @@ declare global {getDictationKey?: () => Promise<string | null>;saveDictationKey?: (key: string) => Promise<void>;+ // Activation mode persistence (file-based for reliable startup)+ getActivationMode?: () => Promise<"tap" | "push">;+ saveActivationMode?: (mode: "tap" | "push") => Promise<void>;+// Debug logginggetLogLevel?: () => Promise<string>;log?: (entry: {@@ -405,6 +410,103 @@ declare global {// Auto-start at logingetAutoStartEnabled?: () => Promise<boolean>;setAutoStartEnabled?: (enabled: boolean) => Promise<{ success: boolean; error?: string }>;++ // Auth+ authClearSession?: () => Promise<void>;++ // OpenWhispr Cloud API+ cloudTranscribe?: (+ audioBuffer: ArrayBuffer,+ opts: { language?: string; prompt?: string }+ ) => Promise<{+ success: boolean;+ text?: string;+ wordsUsed?: number;+ wordsRemaining?: number;+ limitReached?: boolean;+ error?: string;+ code?: string;+ }>;+ cloudReason?: (+ text: string,+ opts: { model?: string; agentName?: string; customDictionary?: string[] }+ ) => Promise<{+ success: boolean;+ text?: string;+ model?: string;+ provider?: string;+ error?: string;+ code?: string;+ }>;+ cloudUsage?: () => Promise<{+ success: boolean;+ wordsUsed?: number;+ wordsRemaining?: number;+ limit?: number;+ plan?: string;+ isSubscribed?: boolean;+ isTrial?: boolean;+ trialDaysLeft?: number | null;+ currentPeriodEnd?: string | null;+ resetAt?: string;+ error?: string;+ code?: string;+ }>;+ cloudCheckout?: () => Promise<{+ success: boolean;+ url?: string;+ error?: string;+ code?: string;+ }>;+ cloudBillingPortal?: () => Promise<{+ success: boolean;+ url?: string;+ error?: string;+ code?: string;+ }>;++ // Usage limit events+ notifyLimitReached?: (data: { wordsUsed: number; limit: number }) => void;+ onLimitReached?: (+ callback: (data: { wordsUsed: number; limit: number }) => void+ ) => (() => void) | void;++ // AssemblyAI Streaming+ assemblyAiStreamingWarmup?: (options?: {+ sampleRate?: number;+ language?: string;+ }) => Promise<{+ success: boolean;+ alreadyWarm?: boolean;+ error?: string;+ code?: string;+ }>;+ assemblyAiStreamingStart?: (options?: { sampleRate?: number; language?: string }) => Promise<{+ success: boolean;+ usedWarmConnection?: boolean;+ error?: string;+ code?: string;+ }>;+ assemblyAiStreamingSend?: (audioBuffer: ArrayBuffer) => Promise<{+ success: boolean;+ error?: string;+ }>;+ assemblyAiStreamingForceEndpoint?: () => void;+ assemblyAiStreamingStop?: () => Promise<{+ success: boolean;+ text?: string;+ error?: string;+ }>;+ assemblyAiStreamingStatus?: () => Promise<{+ isConnected: boolean;+ sessionId: string | null;+ }>;+ onAssemblyAiPartialTranscript?: (callback: (text: string) => void) => () => void;+ onAssemblyAiFinalTranscript?: (callback: (text: string) => void) => () => void;+ onAssemblyAiError?: (callback: (error: string) => void) => () => void;+ onAssemblyAiSessionEnd?: (+ callback: (data: { audioDuration?: number; text?: string }) => void+ ) => () => void;};api?: {diff --git a/src/utils/hotkeyValidator.ts b/src/utils/hotkeyValidator.tsnew file mode 100644index 000000000..e02d19e80--- /dev/null+++ b/src/utils/hotkeyValidator.ts@@ -0,0 +1,625 @@+import { formatHotkeyLabelForPlatform } from "./hotkeys";++export type Platform = "darwin" | "win32" | "linux";++export type ValidationErrorCode =+ | "TOO_MANY_KEYS"+ | "NO_MODIFIER_OR_SPECIAL"+ | "LEFT_RIGHT_MIX"+ | "LEFT_MODIFIER_ONLY"+ | "DUPLICATE"+ | "RESERVED"+ | "INVALID_GLOBE";++export interface ValidationResult {+ valid: boolean;+ error?: string;+ errorCode?: ValidationErrorCode;+}++const MODIFIER_ORDER = ["Control", "Command", "Alt", "Shift", "Super", "Fn"];++const MODIFIERS = new Set(MODIFIER_ORDER);++const RIGHT_SIDE_MODIFIERS = new Set([+ "rightcontrol",+ "rightctrl",+ "rightalt",+ "rightoption",+ "rightshift",+ "rightcommand",+ "rightcmd",+ "rightsuper",+ "rightmeta",+ "rightwin",+]);++function isRightSideModifier(part: string): boolean {+ const normalized = part.replace(/[-_ ]/g, "").toLowerCase();+ return RIGHT_SIDE_MODIFIERS.has(normalized);+}++const SPECIAL_KEYS = new Set(+ [+ "GLOBE",+ "Fn",+ "Esc",+ "Tab",+ "Space",+ "Backspace",+ "Insert",+ "Delete",+ "Home",+ "End",+ "PageUp",+ "PageDown",+ "Left",+ "Right",+ "Up",+ "Down",+ "PrintScreen",+ "Pause",+ "ScrollLock",+ "NumLock",+ ].concat(Array.from({ length: 24 }, (_, i) => `F${i + 1}`))+);++const MAC_RESERVED_SHORTCUTS = [+ "Command+C",+ "Command+V",+ "Command+X",+ "Command+Z",+ "Command+Shift+Z",+ "Command+A",+ "Command+Q",+ "Command+W",+ "Command+R",+ "Command+T",+ "Command+S",+ "Command+P",+ "Command+N",+ "Command+M",+ "Command+H",+ "Command+F",+ "Command+G",+ "Command+Shift+G",+ "Command+,",+ "Command+Left",+ "Command+Right",+ "Command+Up",+ "Command+Down",+ "Command+Shift+Left",+ "Command+Shift+Right",+ "Command+Shift+Up",+ "Command+Shift+Down",+ "Command+Control+F",+ "Command+Space",+ "Command+Alt+Space",+ "Command+Shift+3",+ "Command+Shift+4",+ "Command+Shift+5",+ "Command+Alt+Esc",+ "Command+Alt+D",+ "Command+Delete",+ "Command+Shift+Delete",+ "Command+Shift+Q",+ "Command+B",+ "Command+I",+ "Command+U",+ "Command+Shift+T",+ "Command+=",+ "Command+-",+ "Command+Alt+F",+ "Command+Shift+F",+ "Fn+F11",+ "Fn+F12",+] as const;++const WINDOWS_RESERVED_SHORTCUTS = [+ "Control+C",+ "Control+V",+ "Control+X",+ "Control+Z",+ "Control+Y",+ "Control+R",+ "Control+A",+ "Control+F",+ "Control+G",+ "Control+O",+ "Control+S",+ "Control+P",+ "Control+N",+ "Control+T",+ "Control+W",+ "Control+Home",+ "Control+End",+ "Control+Alt+Delete",+ "Control+Shift+Esc",+ "Control+Backspace",+ "Control+Delete",+ "Control+K",+ "Control+Shift+T",+ "Control+=",+ "Control+-",+ "Alt+Tab",+ "Alt+F4",+ "Alt+Left",+ "Alt+Right",+ "Alt+PrintScreen",+ "F5",+ "F11",+ "Home",+ "End",+ "PrintScreen",+ "Super+E",+ "Super+R",+ "Super+L",+ "Super+D",+ "Super+Tab",+ "Super+I",+ "Super+S",+ "Super+X",+ "Super+P",+ "Super+Q",+ "Super+U",+ "Super+B",+ "Super+Up",+ "Super+Down",+] as const;++const LINUX_RESERVED_SHORTCUTS = [+ "Control+C",+ "Control+V",+ "Control+X",+ "Control+Z",+ "Control+Y",+ "Control+R",+ "Control+A",+ "Control+F",+ "Control+G",+ "Control+O",+ "Control+S",+ "Control+P",+ "Control+N",+ "Control+T",+ "Control+W",+ "Control+Q",+ "Control+H",+ "Control+L",+ "Control+Home",+ "Control+End",+ "Control+Backspace",+ "Control+Delete",+ "Control+Shift+T",+ "Control+Shift+Q",+ "Control+=",+ "Control+-",+ "Control+Alt+T",+ "Control+Alt+Delete",+ "Control+Alt+L",+ "Control+Alt+Esc",+ "Control+Alt+Left",+ "Control+Alt+Right",+ "Control+Alt+Up",+ "Control+Alt+Down",+ "Control+Alt+D",+ "Control+Alt+S",+ "Control+Alt+Tab",+ "Alt+Tab",+ "Alt+Shift+Tab",+ "Alt+F1",+ "Alt+F2",+ "Alt+F4",+ "Alt+F7",+ "Alt+F8",+ "Alt+F9",+ "Alt+F10",+ "Alt+Space",+ "Alt+Left",+ "Alt+Right",+ "Alt+PrintScreen",+ "Super",+ "Super+A",+ "Super+D",+ "Super+L",+ "Super+S",+ "Super+M",+ "Super+Tab",+ "Super+Space",+ "Super+Left",+ "Super+Right",+ "Super+Up",+ "Super+Down",+ "Super+Shift+Left",+ "Super+Shift+Right",+ "Super+Shift+Up",+ "Super+Shift+Down",+ "Super+PageUp",+ "Super+PageDown",+ "Super+Home",+ "Super+End",+ "F1",+ "F5",+ "F11",+ "PrintScreen",+ "Shift+PrintScreen",+ "Super+PrintScreen",+] as const;++const MAC_RECOMMENDED = [+ "Fn",+ "Ctrl + Option",+ "Option + Cmd",+ "Right Cmd or Right Option",+ "Modifier + unused key (e.g., Ctrl + Page Up)",+] as const;++const WINDOWS_RECOMMENDED = [+ "Ctrl + Win",+ "Ctrl + Alt",+ "Ctrl (right) or Alt (right)",+ "Modifier + rarely used key (e.g., Ctrl + Page Up)",+] as const;++const LINUX_RECOMMENDED = [+ "Ctrl + Super",+ "Ctrl + Shift + Super",+ "Super + Shift",+ "Ctrl (right) or Alt (right)",+ "Modifier + rarely used key (e.g., Ctrl + Page Up or Ctrl + Scroll Lock)",+] as const;++const MAC_EXAMPLES = [+ "Control+Shift+K",+ "Alt+F7",+ "Command+Shift+9",+ "Control+Space",+ "Control+Alt+M",+ "Shift+F9",+] as const;++const WINDOWS_EXAMPLES = [+ "Control+Shift+K",+ "Alt+F7",+ "Control+Space",+ "Control+Alt+M",+ "Shift+F9",+] as const;++const LINUX_EXAMPLES = [+ "Control+Super+K",+ "Control+Shift+K",+ "Super+Shift+R",+ "Control+Shift+Space",+ "Shift+F9",+ "Control+Super+M",+] as const;++export const VALIDATION_RULES = [+ "Uses three keys or fewer",+ "Includes at least one modifier or non-alphanumeric key",+ "Does not mix left and right versions of the same modifier",+ "Is not reserved by the system",+] as const;++function normalizeModifier(part: string, platform: Platform): string | null {+ const trimmed = part.replace(/\s+/g, "");+ const lowered = trimmed.toLowerCase();++ if (lowered === "commandorcontrol" || lowered === "cmdorctrl") {+ return platform === "darwin" ? "Command" : "Control";+ }++ if (lowered === "command" || lowered === "cmd") {+ return "Command";+ }++ if (lowered === "control" || lowered === "ctrl") {+ return "Control";+ }++ if (lowered === "alt" || lowered === "option") {+ return "Alt";+ }++ if (lowered === "shift") {+ return "Shift";+ }++ if (lowered === "super" || lowered === "win" || lowered === "meta") {+ return platform === "darwin" ? "Command" : "Super";+ }++ if (lowered === "fn") {+ return "Fn";+ }++ // Handle right-side modifiers (e.g., RightControl, RightOption)+ // These are valid modifiers but we preserve their "Right" prefix for single-modifier validation+ if (isRightSideModifier(part)) {+ // Return a normalized form but mark it as a modifier+ if (lowered.includes("control") || lowered.includes("ctrl")) return "RightControl";+ if (lowered.includes("alt") || lowered.includes("option"))+ return platform === "darwin" ? "RightOption" : "RightAlt";+ if (lowered.includes("shift")) return "RightShift";+ if (lowered.includes("command") || lowered.includes("cmd")) return "RightCommand";+ if (lowered.includes("super") || lowered.includes("meta") || lowered.includes("win")) {+ return platform === "darwin" ? "RightCommand" : "RightSuper";+ }+ }++ return null;+}++function normalizeKeyToken(part: string): string {+ const trimmed = part.replace(/\s+/g, "");+ const lowered = trimmed.toLowerCase();++ if (lowered === "arrowleft") return "Left";+ if (lowered === "arrowright") return "Right";+ if (lowered === "arrowup") return "Up";+ if (lowered === "arrowdown") return "Down";+ if (lowered === "escape" || lowered === "esc") return "Esc";+ if (lowered === "printscreen" || lowered === "print") return "PrintScreen";+ if (lowered === "pageup" || lowered === "pgup") return "PageUp";+ if (lowered === "pagedown" || lowered === "pgdown") return "PageDown";+ if (lowered === "scrolllock") return "ScrollLock";+ if (lowered === "numlock") return "NumLock";+ if (lowered === "delete" || lowered === "del") return "Delete";+ if (lowered === "insert" || lowered === "ins") return "Insert";+ if (lowered === "space") return "Space";+ if (lowered === "tab") return "Tab";+ if (lowered === "home") return "Home";+ if (lowered === "end") return "End";+ if (lowered === "backspace") return "Backspace";+ if (lowered === "globe") return "GLOBE";+ if (lowered === "fn") return "Fn";++ const functionMatch = lowered.match(/^f(\d{1,2})$/);+ if (functionMatch) {+ return `F${functionMatch[1]}`;+ }++ if (trimmed.length === 1) {+ return trimmed.toUpperCase();+ }++ return trimmed;+}++function isLeftRightMix(parts: string[]): boolean {+ const sidesByModifier = new Map<string, Set<string>>();++ const patterns = [+ /^(left|right)[-_ ]?(ctrl|control|alt|option|shift|command|cmd|super|meta)$/i,+ /^(ctrl|control|alt|option|shift|command|cmd|super|meta)[-_ ]?(left|right)$/i,+ ];++ for (const rawPart of parts) {+ const part = rawPart.replace(/\s+/g, "");+ for (const pattern of patterns) {+ const match = part.match(pattern);+ if (match) {+ const side = match[1].toLowerCase().includes("left") ? "left" : "right";+ const modifier = match[2]?.toLowerCase() || match[1]?.toLowerCase();+ if (!modifier) continue;+ const normalizedModifier =+ modifier === "ctrl"+ ? "control"+ : modifier === "cmd"+ ? "command"+ : modifier === "option"+ ? "alt"+ : modifier;+ const set = sidesByModifier.get(normalizedModifier) ?? new Set<string>();+ set.add(side);+ sidesByModifier.set(normalizedModifier, set);+ }+ }+ }++ for (const set of sidesByModifier.values()) {+ if (set.size > 1) {+ return true;+ }+ }++ return false;+}++export function normalizeHotkey(hotkey: string, platform: Platform): string {+ if (!hotkey) return "";++ const parts = hotkey+ .split("+")+ .map((part) => part.trim())+ .filter(Boolean);++ const modifiers: string[] = [];+ const keys: string[] = [];++ for (const part of parts) {+ const normalizedModifier = normalizeModifier(part, platform);+ if (normalizedModifier) {+ modifiers.push(normalizedModifier);+ continue;+ }++ keys.push(normalizeKeyToken(part));+ }++ modifiers.sort((a, b) => MODIFIER_ORDER.indexOf(a) - MODIFIER_ORDER.indexOf(b));++ return [...modifiers, ...keys].join("+");+}++export function getReservedShortcuts(platform: Platform): readonly string[] {+ switch (platform) {+ case "darwin":+ return MAC_RESERVED_SHORTCUTS;+ case "win32":+ return WINDOWS_RESERVED_SHORTCUTS;+ case "linux":+ return LINUX_RESERVED_SHORTCUTS;+ default:+ return [];+ }+}++export function getRecommendedPatterns(platform: Platform): readonly string[] {+ switch (platform) {+ case "darwin":+ return MAC_RECOMMENDED;+ case "win32":+ return WINDOWS_RECOMMENDED;+ case "linux":+ return LINUX_RECOMMENDED;+ default:+ return [];+ }+}++export function getValidExamples(platform: Platform): readonly string[] {+ switch (platform) {+ case "darwin":+ return MAC_EXAMPLES;+ case "win32":+ return WINDOWS_EXAMPLES;+ case "linux":+ return LINUX_EXAMPLES;+ default:+ return [];+ }+}++export function getValidationMessage(+ hotkey: string,+ platform: Platform,+ existingHotkeys: string[] = []+): string | null {+ const result = validateHotkey(hotkey, platform, existingHotkeys);+ if (result.valid) return null;++ if (result.errorCode === "RESERVED") {+ const label = formatHotkeyLabelForPlatform(hotkey, platform);+ return `${label} is reserved by the system`;+ }++ return result.error || "That shortcut is not supported";+}++export function validateHotkey(+ hotkey: string,+ platform: Platform,+ existingHotkeys: string[] = []+): ValidationResult {+ if (!hotkey || hotkey.trim() === "") {+ return { valid: false, error: "Please enter a valid shortcut." };+ }++ if (hotkey === "GLOBE" || hotkey === "Fn") {+ if (platform !== "darwin") {+ return {+ valid: false,+ error: "The Globe/Fn key is only available on macOS.",+ errorCode: "INVALID_GLOBE",+ };+ }+ return { valid: true };+ }++ const parts = hotkey+ .split("+")+ .map((part) => part.trim())+ .filter(Boolean);++ if (parts.length > 3) {+ return {+ valid: false,+ error: "Shortcuts are limited to three keys.",+ errorCode: "TOO_MANY_KEYS",+ };+ }++ if (isLeftRightMix(parts)) {+ return {+ valid: false,+ error: "Do not mix left and right versions of the same modifier in one shortcut.",+ errorCode: "LEFT_RIGHT_MIX",+ };+ }++ let hasModifier = false;+ let hasSpecialKey = false;++ for (const part of parts) {+ const normalizedModifier = normalizeModifier(part, platform);+ if (normalizedModifier) {+ hasModifier = true;+ continue;+ }++ const normalizedKey = normalizeKeyToken(part);+ if (SPECIAL_KEYS.has(normalizedKey)) {+ hasSpecialKey = true;+ }+ }++ if (!hasModifier && !hasSpecialKey) {+ return {+ valid: false,+ error:+ "Shortcuts must include a modifier or a non-alphanumeric key (like arrows, space, or function keys).",+ errorCode: "NO_MODIFIER_OR_SPECIAL",+ };+ }++ // Check for modifier-only hotkeys: require right-side for single modifier, or 2+ modifiers+ const modifierCount = parts.filter((part) => normalizeModifier(part, platform) !== null).length;+ const hasBaseKey = parts.length > modifierCount;++ if (!hasBaseKey && modifierCount === 1) {+ const singleMod = parts[0];+ if (!isRightSideModifier(singleMod)) {+ return {+ valid: false,+ error:+ "Single modifier hotkeys must use the right-side key (e.g., RightOption). Or use two modifiers (e.g., Control+Alt).",+ errorCode: "LEFT_MODIFIER_ONLY",+ };+ }+ // Right-side single modifiers require native listeners (not available on Linux)+ if (platform === "linux") {+ return {+ valid: false,+ error:+ "Right-side single modifier hotkeys are not supported on Linux. Use two modifiers (e.g., Control+Alt) instead.",+ errorCode: "LEFT_MODIFIER_ONLY",+ };+ }+ }++ const normalizedHotkey = normalizeHotkey(hotkey, platform);+ const normalizedExisting = existingHotkeys.map((existing) => normalizeHotkey(existing, platform));++ if (normalizedExisting.includes(normalizedHotkey)) {+ return {+ valid: false,+ error: "That shortcut is already in use.",+ errorCode: "DUPLICATE",+ };+ }++ const reserved = getReservedShortcuts(platform);+ const normalizedReserved = reserved.map((entry) => normalizeHotkey(entry, platform));++ if (normalizedReserved.includes(normalizedHotkey)) {+ return {+ valid: false,+ error: "That shortcut is reserved by your system.",+ errorCode: "RESERVED",+ };+ }++ return { valid: true };+}diff --git a/src/utils/hotkeys.ts b/src/utils/hotkeys.tsindex 0e03032c5..667f02c0d 100644--- a/src/utils/hotkeys.ts+++ b/src/utils/hotkeys.ts@@ -3,22 +3,16 @@* Supports both single keys and compound hotkeys (e.g., "CommandOrControl+Shift+K").*/-/**- * Detects if the current platform is macOS.- */-function isMacPlatform(): boolean {- if (typeof navigator === "undefined") return false;- return /Mac|Darwin/.test(navigator.platform);-}+import { getPlatform, type Platform } from "./platform";/*** Maps Electron accelerator parts to user-friendly labels.* Automatically adapts to the current platform (macOS vs Windows/Linux).*/-function formatModifierPart(part: string, isMac: boolean): string {+function formatModifierPart(part: string, platform: Platform): string {switch (part) {case "CommandOrControl":- return isMac ? "Cmd" : "Ctrl";+ return platform === "darwin" ? "Cmd" : "Ctrl";case "Command":case "Cmd":return "Cmd";@@ -26,14 +20,18 @@ function formatModifierPart(part: string, isMac: boolean): string {case "Ctrl":return "Ctrl";case "Alt":- return isMac ? "Option" : "Alt";+ return platform === "darwin" ? "Option" : "Alt";case "Option":return "Option";case "Shift":return "Shift";case "Super":case "Meta":- return isMac ? "Cmd" : "Win";+ return platform === "darwin" ? "Cmd" : platform === "win32" ? "Win" : "Super";+ case "Win":+ return platform === "win32" ? "Win" : "Super";+ case "Fn":+ return "Fn";default:return part;}@@ -49,30 +47,47 @@ function formatModifierPart(part: string, isMac: boolean): string {* formatHotkeyLabel("CommandOrControl+Shift+K") // "Cmd+Shift+K" on macOS, "Ctrl+Shift+K" on Windows* formatHotkeyLabel("GLOBE") // "Globe"* formatHotkeyLabel("`") // "`"- * formatHotkeyLabel(null) // "`"+ * formatHotkeyLabel(null) // platform default*/export function formatHotkeyLabel(hotkey?: string | null): string {- // Handle empty/null values - return default backtick+ const platform = getPlatform();+ const resolvedHotkey = hotkey && hotkey.trim() !== "" ? hotkey : getDefaultHotkey();+ return formatHotkeyLabelForPlatform(resolvedHotkey, platform);+}++export function formatHotkeyLabelForPlatform(hotkey: string, platform: Platform): string {if (!hotkey || hotkey.trim() === "") {- return "`";+ return "";}- // Handle special GLOBE key for macOSif (hotkey === "GLOBE") {return "Globe/Fn";}- // Handle compound hotkeys (contains "+")+ // Right-side single modifiers+ const rightSideMap: Record<string, string> = {+ RightOption: platform === "darwin" ? "Right Option" : "Right Alt",+ RightAlt: "Right Alt",+ RightCommand: "Right Cmd",+ RightCmd: "Right Cmd",+ RightControl: "Right Ctrl",+ RightCtrl: "Right Ctrl",+ RightShift: "Right Shift",+ RightSuper: platform === "win32" ? "Right Win" : "Right Super",+ RightMeta:+ platform === "darwin" ? "Right Cmd" : platform === "win32" ? "Right Win" : "Right Super",+ RightWin: "Right Win",+ };+ if (rightSideMap[hotkey]) {+ return rightSideMap[hotkey];+ }+if (hotkey.includes("+")) {- const isMac = isMacPlatform();const parts = hotkey.split("+");-- const formattedParts = parts.map((part) => formatModifierPart(part, isMac));-+ const formattedParts = parts.map((part) => formatModifierPart(part, platform));return formattedParts.join("+");}- // Single key - return as-isreturn hotkey;}@@ -114,11 +129,11 @@ export function isCompoundHotkey(hotkey: string): boolean {/*** Gets the default hotkey for the current platform.* - macOS: GLOBE key (Fn key on modern Macs)- * - Windows/Linux: Backtick (`)+ * - Windows/Linux: Control+Super (Ctrl+Win / Ctrl+Super)*/export function getDefaultHotkey(): string {- const isMac = isMacPlatform();- return isMac ? "GLOBE" : "`";+ const platform = getPlatform();+ return platform === "darwin" ? "GLOBE" : "Control+Super";}/**diff --git a/src/utils/languageSupport.ts b/src/utils/languageSupport.tsnew file mode 100644index 000000000..8ae1d5abe--- /dev/null+++ b/src/utils/languageSupport.ts@@ -0,0 +1,60 @@+import registry from "../config/languageRegistry.json";++function buildLanguageSet(key: "whisper" | "parakeet" | "assemblyai"): Set<string> {+ const set = new Set<string>();+ for (const lang of registry.languages) {+ if (lang[key]) {+ set.add(lang.code);+ const base = lang.code.split("-")[0];+ if (base !== lang.code) set.add(base);+ }+ }+ return set;+}++const WHISPER_LANGUAGES = buildLanguageSet("whisper");+const PARAKEET_LANGUAGES = buildLanguageSet("parakeet");+const ASSEMBLYAI_UNIVERSAL3_PRO_LANGUAGES = buildLanguageSet("assemblyai");++const MODEL_LANGUAGE_MAP: Record<string, Set<string>> = {+ "parakeet-tdt-0.6b-v3": PARAKEET_LANGUAGES,+};++const LANGUAGE_INSTRUCTIONS: Record<string, string> = Object.fromEntries(+ registry.languages+ .filter(+ (l): l is typeof l & { instruction: string } =>+ "instruction" in l && typeof l.instruction === "string"+ )+ .map((l) => [l.code, l.instruction])+);++export function getBaseLanguageCode(language: string | null | undefined): string | undefined {+ if (!language || language === "auto") return undefined;+ return language.split("-")[0];+}++export function validateLanguageForModel(+ language: string | null | undefined,+ modelId: string+): string | undefined {+ const baseCode = getBaseLanguageCode(language);+ if (!baseCode) return undefined;++ const supportedSet = MODEL_LANGUAGE_MAP[modelId];+ if (!supportedSet) return baseCode;++ return supportedSet.has(baseCode) ? baseCode : undefined;+}++export function getLanguageInstruction(language: string | undefined): string {+ if (!language) return "";+ return LANGUAGE_INSTRUCTIONS[language] || buildGenericInstruction(language);+}++function buildGenericInstruction(langCode: string): string {+ const template = registry._genericTemplate || "";+ return template.replace("{{code}}", langCode);+}++export { WHISPER_LANGUAGES, PARAKEET_LANGUAGES, ASSEMBLYAI_UNIVERSAL3_PRO_LANGUAGES };diff --git a/src/utils/languages.ts b/src/utils/languages.tsdeleted file mode 100644index bbcf6b8de..000000000--- a/src/utils/languages.ts+++ /dev/null@@ -1,65 +0,0 @@-export const LANGUAGE_OPTIONS = [- { value: "auto", label: "Auto-detect" },- { value: "af", label: "Afrikaans" },- { value: "ar", label: "Arabic" },- { value: "hy", label: "Armenian" },- { value: "az", label: "Azerbaijani" },- { value: "be", label: "Belarusian" },- { value: "bs", label: "Bosnian" },- { value: "bg", label: "Bulgarian" },- { value: "ca", label: "Catalan" },- { value: "zh", label: "Chinese" },- { value: "hr", label: "Croatian" },- { value: "cs", label: "Czech" },- { value: "da", label: "Danish" },- { value: "nl", label: "Dutch" },- { value: "en", label: "English" },- { value: "et", label: "Estonian" },- { value: "fi", label: "Finnish" },- { value: "fr", label: "French" },- { value: "gl", label: "Galician" },- { value: "de", label: "German" },- { value: "el", label: "Greek" },- { value: "he", label: "Hebrew" },- { value: "hi", label: "Hindi" },- { value: "hu", label: "Hungarian" },- { value: "is", label: "Icelandic" },- { value: "id", label: "Indonesian" },- { value: "it", label: "Italian" },- { value: "ja", label: "Japanese" },- { value: "kn", label: "Kannada" },- { value: "kk", label: "Kazakh" },- { value: "ko", label: "Korean" },- { value: "lv", label: "Latvian" },- { value: "lt", label: "Lithuanian" },- { value: "mk", label: "Macedonian" },- { value: "ms", label: "Malay" },- { value: "mr", label: "Marathi" },- { value: "mi", label: "Maori" },- { value: "ne", label: "Nepali" },- { value: "no", label: "Norwegian" },- { value: "fa", label: "Persian" },- { value: "pl", label: "Polish" },- { value: "pt", label: "Portuguese" },- { value: "ro", label: "Romanian" },- { value: "ru", label: "Russian" },- { value: "sr", label: "Serbian" },- { value: "sk", label: "Slovak" },- { value: "sl", label: "Slovenian" },- { value: "es", label: "Spanish" },- { value: "sw", label: "Swahili" },- { value: "sv", label: "Swedish" },- { value: "tl", label: "Tagalog" },- { value: "ta", label: "Tamil" },- { value: "th", label: "Thai" },- { value: "tr", label: "Turkish" },- { value: "uk", label: "Ukrainian" },- { value: "ur", label: "Urdu" },- { value: "vi", label: "Vietnamese" },- { value: "cy", label: "Welsh" },-];--export const getLanguageLabel = (code: string): string => {- const option = LANGUAGE_OPTIONS.find((lang) => lang.value === code);- return option?.label || code;-};diff --git a/src/utils/modelPickerStyles.ts b/src/utils/modelPickerStyles.tsindex 4e45c0d12..8e0a5beb1 100644--- a/src/utils/modelPickerStyles.ts+++ b/src/utils/modelPickerStyles.ts@@ -11,13 +11,13 @@ export interface ModelPickerStyles {export const MODEL_PICKER_COLORS: Record<ColorScheme, ModelPickerStyles> = {purple: {container:- "bg-card border border-border rounded-xl overflow-hidden dark:bg-surface-1 shadow-sm",+ "bg-surface-1/95 dark:bg-white/[0.03] rounded-lg overflow-hidden border border-border/60 dark:border-white/8 backdrop-blur-xl shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)",header: "font-medium text-foreground tracking-tight",modelCard: {selected:- "border-primary/30 bg-primary/8 dark:bg-primary/6 dark:border-primary/20 shadow-[0_0_0_1px_oklch(0.62_0.22_260/0.12),0_0_10px_-3px_oklch(0.62_0.22_260/0.18)]",+ "border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",default:- "border-border bg-surface-1 hover:border-border-hover hover:bg-muted dark:bg-card dark:border-border dark:hover:border-border-hover dark:hover:bg-surface-raised",+ "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",},badges: {selected:@@ -37,13 +37,13 @@ export const MODEL_PICKER_COLORS: Record<ColorScheme, ModelPickerStyles> = {},indigo: {container:- "bg-card border border-border rounded-xl overflow-hidden dark:bg-surface-1 shadow-sm",+ "bg-surface-1/95 dark:bg-white/[0.03] rounded-lg overflow-hidden border border-border/60 dark:border-white/8 backdrop-blur-xl shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)",header: "font-medium text-foreground tracking-tight",modelCard: {selected:- "border-primary/30 bg-primary/8 dark:bg-primary/6 dark:border-primary/20 shadow-[0_0_0_1px_oklch(0.62_0.22_260/0.12),0_0_10px_-3px_oklch(0.62_0.22_260/0.18)]",+ "border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",default:- "border-border bg-surface-1 hover:border-border-hover hover:bg-muted dark:bg-card dark:border-border dark:hover:border-border-hover dark:hover:bg-surface-raised",+ "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",},badges: {selected:@@ -63,13 +63,13 @@ export const MODEL_PICKER_COLORS: Record<ColorScheme, ModelPickerStyles> = {},blue: {container:- "bg-surface-1 dark:bg-white/3 rounded-xl overflow-hidden border border-border dark:border-white/5 backdrop-blur-md shadow-sm",+ "bg-surface-1/95 dark:bg-white/[0.03] rounded-lg overflow-hidden border border-border/60 dark:border-white/8 backdrop-blur-xl shadow-(--shadow-metallic-light) dark:shadow-(--shadow-metallic-dark)",header: "text-sm font-medium text-foreground tracking-tight",modelCard: {selected:- "border-primary/30 bg-primary/10 dark:bg-primary/6 shadow-[0_0_0_1px_oklch(0.62_0.22_260/0.15),0_0_12px_-3px_oklch(0.62_0.22_260/0.2)]",+ "border-primary/40 bg-primary/12 dark:bg-primary/8 shadow-(--shadow-selected-glow) relative before:absolute before:inset-0 before:bg-linear-to-b before:from-white/[0.03] before:to-transparent before:pointer-events-none",default:- "border-border bg-surface-1 hover:border-border-hover hover:bg-surface-raised dark:border-white/5 dark:bg-white/3 dark:hover:border-white/20 dark:hover:bg-white/8",+ "border-border/70 bg-surface-1/50 dark:bg-white/[0.02] hover:border-border-hover hover:bg-surface-raised/60 dark:hover:border-white/20 dark:hover:bg-white/[0.05] hover:-translate-y-[1px] hover:shadow-(--shadow-card-hover-subtle) transition-all duration-200 ease-out",},badges: {selected:diff --git a/src/utils/platform.ts b/src/utils/platform.tsnew file mode 100644index 000000000..22d5638b9--- /dev/null+++ b/src/utils/platform.ts@@ -0,0 +1,38 @@+export type Platform = "darwin" | "win32" | "linux";++/**+ * Detects the current platform using Electron when available,+ * falling back to user agent detection.+ */+export function getPlatform(): Platform {+ // Try Electron API first+ if (typeof window !== "undefined" && window.electronAPI?.getPlatform) {+ const platform = window.electronAPI.getPlatform();+ if (platform === "darwin" || platform === "win32" || platform === "linux") {+ return platform;+ }+ }++ // Fallback to user agent detection+ if (typeof navigator !== "undefined") {+ const ua = navigator.userAgent.toLowerCase();+ if (ua.includes("mac")) return "darwin";+ if (ua.includes("win")) return "win32";+ if (ua.includes("linux")) return "linux";+ }++ // Default to darwin+ return "darwin";+}++/**+ * Cached platform value for performance+ */+let cachedPlatform: Platform | null = null;++export function getCachedPlatform(): Platform {+ if (cachedPlatform === null) {+ cachedPlatform = getPlatform();+ }+ return cachedPlatform;+}diff --git a/src/vite.config.mjs b/src/vite.config.mjsindex 8aa51546a..1083236cb 100644--- a/src/vite.config.mjs+++ b/src/vite.config.mjs@@ -1,4 +1,4 @@-import { defineConfig } from 'vite'+import { defineConfig, loadEnv } from 'vite'import react from '@vitejs/plugin-react'import tailwindcss from '@tailwindcss/vite'import path from 'path'@@ -6,39 +6,61 @@ import { fileURLToPath } from 'url'const __filename = fileURLToPath(import.meta.url)const __dirname = path.dirname(__filename)+const DEFAULT_DEV_SERVER_PORT = 5183++const parseDevServerPort = (rawPort) => {+ const normalizedPort = rawPort || String(DEFAULT_DEV_SERVER_PORT)+ const parsedPort = Number(normalizedPort)++ if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {+ return DEFAULT_DEV_SERVER_PORT+ }++ return parsedPort+}// https://vite.dev/config/-export default defineConfig({- plugins: [react(), tailwindcss()],- base: './', // Use relative paths for file:// protocol in Electron- resolve: {- alias: {- "@": path.resolve(__dirname, "."),+export default defineConfig(({ mode }) => {+ const envDir = path.resolve(__dirname, '..')+ const env = loadEnv(mode, envDir, '')+ const rawPort = env.VITE_DEV_SERVER_PORT || env.OPENWHISPR_DEV_SERVER_PORT+ const devServerPort = parseDevServerPort(rawPort)++ return {+ plugins: [react(), tailwindcss()],+ base: './', // Use relative paths for file:// protocol in Electron+ envDir, // Load .env from project root+ resolve: {+ alias: {+ "@": path.resolve(__dirname, "."),+ },+ },+ server: {+ port: devServerPort,+ strictPort: true,+ host: '127.0.0.1', // Use IP address instead of localhost for Neon Auth CORS},- },- server: {- port: 5174,- },- build: {- outDir: 'dist',- assetsDir: 'assets',- rollupOptions: {- external: [- 'electron',- 'fs',- 'path',- 'child_process',- 'https',- 'http',- 'crypto',- 'os',- 'stream',- 'util',- 'zlib',- 'tar',- 'unzipper',- '@aws-sdk/client-s3'- ]+ build: {+ outDir: 'dist',+ assetsDir: 'assets',+ rollupOptions: {+ external: [+ 'electron',+ 'fs',+ 'path',+ 'child_process',+ 'https',+ 'http',+ 'crypto',+ 'os',+ 'stream',+ 'util',+ 'zlib',+ 'tar',+ 'unzipper',+ '@aws-sdk/client-s3'+ ]+ }}}})