The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Desktop and mobile apps: full UI test of the desktop app, smoother install (move to Applications, open at login, dmg window, one-click Windows), native code in clear folders, docs/apps.md (PR 2073)
Tim Gutberletb550bd5896a0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9549ee6b..ffa1dada 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -37,6 +37,7 @@ TypeScript everywhere. pnpm + Turborepo. Hono + Zod (+ `@hono/zod-openapi`) for- `apps/api`: Hono server. Better Auth at `/api/auth/*`, `POST /v1/actions/<name>` (the one write path), `GET /v1/shape/<table>` (read sync via Electric, workspace-filtered), handlers in `src/handlers.ts`.- `apps/web`: Vite React SPA (local store + outbox). `apps/agent`: LiveKit voice agent and the call simulator; talks to the API only through `src/api-client.ts`.+- `apps/mobile` (Capacitor, iOS and Android) and `apps/desktop` (Electron, macOS and Windows): thin shells that open the server's web app; the web app's side of them is `apps/web/src/native/` (`mobile/`, `desktop/`, `sign-in/`). Which code goes where: [docs/apps.md](docs/apps.md).- `packages/db`: Drizzle schema + migrations; row types in `src/types.ts`, shared with the browser. Columns are snake_case in TS too.- `packages/actions`: the registry. Most actions are a declarative `patch` (optimistic in the browser, a workspace-scoped UPDATE on the server); the rest get a handler in `apps/api`.- `packages/sync`: local store, IndexedDB outbox, `ReadSyncAdapter` (Electric). `packages/telephony`: `TelephonyProvider` + adapters (Telnyx, the default; Twilio; `dev`), selected by `TELEPHONY_PROVIDER`.diff --git a/apps/api/src/app-sign-in.test.ts b/apps/api/src/app-sign-in.test.tsindex b0baf844..f918e135 100644--- a/apps/api/src/app-sign-in.test.ts+++ b/apps/api/src/app-sign-in.test.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto'import { describe, expect, it } from 'vitest'-// The PKCE check of the app's sign-in hand-back (app-sign-in.ts): the same S256 the web app computes (native/appSignIn.ts).+// The PKCE check of the app's sign-in hand-back (app-sign-in.ts): the same S256 the web app computes (native/sign-in/appSignIn.ts).const s256 = (verifier: string) => createHash('sha256').update(verifier).digest('base64url')import { START_TTL_S, sessionFitsStart, verifierFits } from './app-sign-in-pkce.ts'diff --git a/apps/desktop/README.md b/apps/desktop/README.mdindex f131a89e..c61e902f 100644--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@ -1,9 +1,11 @@# Linedesk app for macOS and Windows+How the web, mobile and desktop apps fit together: [docs/apps.md](../../docs/apps.md).+A native shell around the web app (Electron), like the mobile app (`apps/mobile`). The window opens the server's ownpages (Linedesk Cloud by default), so the session, sync and every update of the web app come from the server as on theweb. The web app finds the shell by `window.linedeskDesktop` (`src/preload.ts`, only on the server's own pages) and-uses it for what a browser tab cannot do (`apps/web/src/native/desktop.ts`):+uses it for what a browser tab cannot do (`apps/web/src/native/desktop/bridge.ts`):- **Sign-in with a provider** (Google, Apple, Microsoft, GitHub, single sign-on) runs in the system's browser. Thesession comes back with the same one-use code and PKCE as in the mobile app (`apps/api/src/app-sign-in.ts`), but on a@@ -15,7 +17,7 @@ uses it for what a browser tab cannot do (`apps/web/src/native/desktop.ts`):while the app is not running.- **Links**: the app opens `linedesk://open/#call/…` (the start page with its page, like links in emails). A browseron a Mac or a PC hands links from emails to the app when "Open links in the desktop app" is on in that browser- (User settings › Profile; `apps/web/src/native/openInDesktop.ts`).+ (User settings › Profile; `apps/web/src/native/desktop/openInDesktop.ts`).- **Menus**: the macOS menu bar (Settings ⌘,, Back ⌘[, Forward ⌘], Reload ⌘R, Edit, Window), the Windows tray. Theirwords come from the web app in the person's language. No menu key takes one the web app uses.- **Window**: only the server's pages and a fixed list of sites the web app sends it to and that lead back (Stripe@@ -24,6 +26,10 @@ uses it for what a browser tab cannot do (`apps/web/src/native/desktop.ts`):(notifications, microphone for test calls), Electron's fuses set for a shipped app. A shipped app refuses a debuggingport and ignores `LINEDESK_DESKTOP_SERVER`; both work only in development and in CI's test build(`LINEDESK_DESKTOP_E2E=1` at build time, never shipped).+- **Install**: macOS: drag the app from the .dmg to Applications; started from anywhere else it offers once to move+ itself there. Windows: one click, no admin rights; the installer adds Start menu and desktop shortcuts and opens the+ app. From its first start the app opens at login, in the background, so calls keep notifying ("Open at login" in User+ settings › Profile turns it off; `src/install.ts`).- **Updates**: built in (`electron-updater`, `src/updates.ts`) and off until Linedesk publishes desktop releases.Buying works in the desktop app as on the web (it is no store app).@@ -49,8 +55,8 @@ and tests it with screenshots; the installers are kept as artifacts. Nothing is## Tests- `pnpm test`: the link and sign-in rules (`src/*.test.ts`).-- `e2e/flow.spec.ts`, against a local dev stack with the demo data and a GitHub app set (`GITHUB_CLIENT_ID` and+- `e2e/ui.spec.ts`, against a local dev stack with the demo data and a GitHub app set (`GITHUB_CLIENT_ID` and`GITHUB_CLIENT_SECRET`, any values: GitHub itself is never reached): the whole provider sign-in through the browserand the loopback port, the inbox, and an urgent call's notification with the window closed.- `E2E_SERVER=<web origin> pnpm e2e e2e/flow.spec.ts` (Linux without a screen: `xvfb-run -a`, `ELECTRON_DISABLE_SANDBOX=1`).+ `E2E_SERVER=<web origin> pnpm e2e e2e/ui.spec.ts` (Linux without a screen: `xvfb-run -a`, `ELECTRON_DISABLE_SANDBOX=1`).- `e2e/smoke.spec.ts`: an installed test build (`LINEDESK_DESKTOP_E2E=1`; `E2E_APP=<its executable>`), as CI runs it.diff --git a/apps/desktop/e2e/flow.spec.ts b/apps/desktop/e2e/flow.spec.tsdeleted file mode 100644index a2f1205d..00000000--- a/apps/desktop/e2e/flow.spec.ts+++ /dev/null@@ -1,98 +0,0 @@-// Against a local dev stack (E2E_SERVER, its demo data seeded, a GitHub app configured with any id: GitHub itself is-// never reached): the app shows the sign-in page; "Continue with GitHub" opens the server's sign-in page in "the-// system browser" (here a second Chromium the test drives); that browser signs in (by password, after the start, in-// place of GitHub), confirms, and hands the one-use code to the app's loopback port; the app redeems it and shows the-// inbox. Then a running call becomes urgent and the app shows its notification. Screenshots in E2E_SHOTS.-import { mkdirSync } from 'node:fs'-import { join } from 'node:path'-import { _electron as electron, chromium, expect, test } from '@playwright/test'--const server = process.env.E2E_SERVER ?? 'http://localhost:5173'-const email = process.env.E2E_EMAIL ?? '[email protected]'-const password = process.env.E2E_PASSWORD ?? 'brightwater-demo'-const shots = process.env.E2E_SHOTS ?? join(import.meta.dirname, 'shots')-mkdirSync(shots, { recursive: true })--test('sign-in through the browser, inbox, urgent call notification', async () => {- const app = await electron.launch({- args: [join(import.meta.dirname, '..')],- env: { ...process.env, LINEDESK_DESKTOP_SERVER: server },- })- // "The system browser": every address the app hands to the system lands here.- await app.evaluate(({ shell }) => {- const g = globalThis as { opened?: string[] }- g.opened = []- shell.openExternal = async (url: string) => {- g.opened!.push(url)- }- })- await app.evaluate(({ Notification }) => {- const g = globalThis as { shown?: { title: string; body: string }[] }- g.shown = []- const show = Notification.prototype.show- Notification.prototype.show = function (this: Electron.Notification) {- g.shown!.push({ title: this.title, body: this.body })- return show.call(this)- }- })- const win = await app.firstWindow()- // Signed out, as a new install: an earlier run's session and data go.- await app.evaluate(({ session }) => session.defaultSession.clearStorageData())- await win.reload()- await win.setViewportSize({ width: 1280, height: 800 })- await expect(win.getByRole('heading', { name: /Sign in to/ })).toBeVisible({ timeout: 30_000 })- expect(await win.evaluate(() => typeof (window as { linedeskDesktop?: unknown }).linedeskDesktop)).toBe('object')- await win.screenshot({ path: join(shots, '1-sign-in.png') })-- await win.getByRole('button', { name: /GitHub/ }).click()- const start = await expect- .poll(() => app.evaluate(() => (globalThis as { opened?: string[] }).opened?.[0]), { timeout: 15_000 })- .toMatch(/\/app-sign-in\?provider=github&challenge=[\w-]{43}&port=\d+$/)- .then(() => app.evaluate(() => (globalThis as { opened?: string[] }).opened![0]!))-- const browser = await chromium.launch()- const page = await browser.newPage()- // The page posts the challenge (a cookie of this browser), then leaves for GitHub: stopped here.- await page.route('https://github.com/**', route => route.abort())- const started = page.waitForResponse(r => r.url().endsWith('/api/auth/app-sign-in/start'))- await page.goto(start).catch(() => {})- expect((await started).ok()).toBe(true)- // In place of GitHub: a sign-in of this browser after the start.- const signedIn = await page.request.post(`${server}/api/auth/sign-in/email`, {- data: { email, password },- headers: { origin: server },- })- expect(signedIn.ok()).toBe(true)- const port = new URL(start).searchParams.get('port')- await page.goto(`${server}/app-sign-in?done=1&port=${port}`)- await expect(page.getByText(`on this computer. The app is then signed in as ${email}`)).toBeVisible()- await page.screenshot({ path: join(shots, '2-browser-confirm.png') })- await page.getByRole('button', { name: 'Continue' }).click()- await page.waitForURL(/\/app-sign-in\/back\?desktop=1$/)- await expect(page.getByText('Go back to the Linedesk app. You can close this tab.')).toBeVisible()- await page.screenshot({ path: join(shots, '3-browser-done.png') })- // The browser's own session ended with the hand-back.- expect(await (await page.request.get(`${server}/api/auth/get-session`)).json()).toBeNull()- await browser.close()-- await expect(win.getByRole('navigation').first()).toBeVisible({ timeout: 30_000 })- await expect(win.locator('[data-call-id]').first()).toBeVisible({ timeout: 30_000 })- await win.screenshot({ path: join(shots, '4-inbox.png') })-- // A call becomes urgent while the window is closed (the app keeps running): the app shows it. E2E_URGENT is a- // command that sets a running call of the demo workspace urgent (E2E_URGENT_RESET, run first, sets it back).- if (process.env.E2E_URGENT) {- const { execSync } = await import('node:child_process')- if (process.env.E2E_URGENT_RESET) execSync(process.env.E2E_URGENT_RESET, { stdio: 'inherit' })- await win.waitForTimeout(3000)- await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.close())- expect(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())).toBe(false)- execSync(process.env.E2E_URGENT, { stdio: 'inherit' })- await expect- .poll(() => app.evaluate(() => (globalThis as { shown?: { title: string }[] }).shown?.map(s => s.title)), {- timeout: 30_000,- })- .toContainEqual(expect.stringMatching(/^Urgent: /))- }- await app.close()-})diff --git a/apps/desktop/e2e/playwright.config.ts b/apps/desktop/e2e/playwright.config.tsindex 92ee61fc..9091f37b 100644--- a/apps/desktop/e2e/playwright.config.ts+++ b/apps/desktop/e2e/playwright.config.ts@@ -1,5 +1,4 @@-// The desktop app's own tests in a running app (LIN-903). `flow.spec.ts`: the whole sign-in hand-back, the inbox and-// a call's notification against a local dev stack (apps/desktop/README.md). `smoke.spec.ts`: an installed build on+// The desktop app's own tests in a running app (LIN-903). `ui.spec.ts`: the whole app against a local dev stack (sign-in through the browser, inbox, keyboard, menus, links, notifications, offline). `smoke.spec.ts`: an installed build on// macOS or Windows (CI), its window, a password sign-in and a notification, with screenshots.import { defineConfig } from '@playwright/test'diff --git a/apps/desktop/e2e/smoke.spec.ts b/apps/desktop/e2e/smoke.spec.tsindex 7c884977..703a175a 100644--- a/apps/desktop/e2e/smoke.spec.ts+++ b/apps/desktop/e2e/smoke.spec.ts@@ -84,6 +84,19 @@ test('installed app: sign-in page, inbox, notification', async () => {await page.waitForTimeout(2000)await page.screenshot({ path: join(shots, '2-inbox.png') })screen('2-inbox')+ // The install set itself up: the app opens at login from its first start, and says so in User settings.+ const atLogin = await page.evaluate(() =>+ (window as { linedeskDesktop?: { getOpenAtLogin(): Promise<boolean | null> } }).linedeskDesktop?.getOpenAtLogin(),+ )+ console.log(`open at login: ${atLogin}`)+ if (process.platform === 'win32') expect(atLogin).toBe(true)+ await page.evaluate(() => {+ window.location.hash = '#account/profile'+ })+ await expect(page.getByText('Notifications on this device')).toBeVisible({ timeout: 30_000 })+ await page.waitForTimeout(1500)+ await page.screenshot({ path: join(shots, '3-settings.png') })+ screen('3-settings')}console.log('step: inbox')@@ -99,6 +112,6 @@ test('installed app: sign-in page, inbox, notification', async () => {)console.log('step: notified')await page.waitForTimeout(4000)- screen('3-notification')+ screen('4-notification')await browser.close()})diff --git a/apps/desktop/e2e/ui.spec.ts b/apps/desktop/e2e/ui.spec.tsnew file mode 100644index 00000000..666a5cf7--- /dev/null+++ b/apps/desktop/e2e/ui.spec.ts@@ -0,0 +1,205 @@+// The desktop app end to end, against a local dev stack (E2E_SERVER, demo data seeded, a GitHub app set with any id:+// GitHub itself is never reached). One app, the steps in order, a screenshot after each (E2E_SHOTS):+// 1. a new install shows the sign-in page, with the bridge, and the menus get the web app's words;+// 2. "Continue with GitHub" opens the server's page in "the system browser" (a second Chromium the test drives),+// which signs in, confirms and hands the one-use code to the app's loopback port; the app shows the inbox;+// 3. the inbox by keyboard: J/K, Enter opens a call, Escape back, the command menu (Ctrl/⌘ K);+// 4. Settings from the menu: User settings with the desktop app's rows (no "Open links in the desktop app" there);+// 5. links: another site opens in the browser, never in the window; `linedesk://open/#call/…` opens that call;+// 6. closing the window keeps the app running; a running call that becomes urgent notifies; a click on the+// notification brings the window back on that call;+// 7. a server that cannot be reached shows the offline page.+// E2E_DB: a command that runs SQL on the stack's database (argument: the statement).+import { execFileSync } from 'node:child_process'+import { mkdirSync } from 'node:fs'+import { join } from 'node:path'+import { _electron as electron, chromium, type ElectronApplication, expect, type Page, test } from '@playwright/test'++const server = process.env.E2E_SERVER ?? 'http://localhost:5173'+const email = process.env.E2E_EMAIL ?? '[email protected]'+const password = process.env.E2E_PASSWORD ?? 'brightwater-demo'+const shots = process.env.E2E_SHOTS ?? join(import.meta.dirname, 'shots')+const appDir = join(import.meta.dirname, '..')+const mod = process.platform === 'darwin' ? 'Meta' : 'Control'+mkdirSync(shots, { recursive: true })++const sql = (statement: string) => {+ const db = process.env.E2E_DB+ if (!db) throw new Error('E2E_DB is not set')+ execFileSync('sh', ['-c', `${db} "$1"`, 'sh', statement], { stdio: 'inherit' })+}++type Spy = { opened: string[]; shown: { title: string; body: string }[] }+const spy = (app: ElectronApplication) => app.evaluate(() => (globalThis as unknown as { spy: Spy }).spy)++async function launch(serverUrl: string) {+ const app = await electron.launch({ args: [appDir], env: { ...process.env, LINEDESK_DESKTOP_SERVER: serverUrl } })+ // "The system browser" and the system's notifications, seen by the test.+ await app.evaluate(({ shell, Notification }) => {+ const g = globalThis as unknown as { spy: Spy; notices: Electron.Notification[] }+ g.spy = { opened: [], shown: [] }+ g.notices = []+ shell.openExternal = async (url: string) => {+ g.spy.opened.push(url)+ }+ const show = Notification.prototype.show+ Notification.prototype.show = function (this: Electron.Notification) {+ g.spy.shown.push({ title: this.title, body: this.body })+ g.notices.push(this)+ return show.call(this)+ }+ })+ return app+}++test.describe.configure({ mode: 'serial' })+let app: ElectronApplication+let win: Page+const shot = (name: string) => win.screenshot({ path: join(shots, `${name}.png`) })++test.beforeAll(async () => {+ sql("update calls set status='completed', urgency='normal', ended_at=now() where id='call_demo_01'")+ app = await launch(server)+ win = await app.firstWindow()+ // A new install: no session or data of an earlier run.+ await app.evaluate(({ session }) => session.defaultSession.clearStorageData())+ await win.reload()+ await win.setViewportSize({ width: 1280, height: 800 })+})+test.afterAll(async () => {+ await app?.close()+})++test('1. sign-in page, bridge, menus in the web app’s words', async () => {+ await expect(win.getByRole('heading', { name: /Sign in to/ })).toBeVisible({ timeout: 30_000 })+ expect(await win.evaluate(() => typeof (window as { linedeskDesktop?: unknown }).linedeskDesktop)).toBe('object')+ await expect+ .poll(() => app.evaluate(({ Menu }) => Menu.getApplicationMenu()?.items.map(i => i.label) ?? []))+ .toEqual(expect.arrayContaining(['Edit', 'View', 'Window', 'Help']))+ await shot('01-sign-in')+})++test('2. provider sign-in through the system browser, back on the loopback port', async () => {+ await win.getByRole('button', { name: /GitHub/ }).click()+ await expect.poll(async () => (await spy(app)).opened[0] ?? '', { timeout: 15_000 }).toMatch(/\/app-sign-in\?/)+ const start = (await spy(app)).opened[0]!+ expect(start).toMatch(/provider=github&challenge=[\w-]{43}&port=\d+$/)++ const browser = await chromium.launch()+ const page = await browser.newPage()+ await page.route('https://github.com/**', route => route.abort())+ const started = page.waitForResponse(r => r.url().endsWith('/api/auth/app-sign-in/start'))+ await page.goto(start).catch(() => {})+ expect((await started).ok()).toBe(true)+ // In place of GitHub: this browser signs in after the start.+ const signedIn = await page.request.post(`${server}/api/auth/sign-in/email`, {+ data: { email, password },+ headers: { origin: server },+ })+ expect(signedIn.ok()).toBe(true)+ const port = new URL(start).searchParams.get('port')+ await page.goto(`${server}/app-sign-in?done=1&port=${port}`)+ await expect(page.getByText(`on this computer. The app is then signed in as ${email}`)).toBeVisible()+ await page.screenshot({ path: join(shots, '02-browser-confirm.png') })+ await page.getByRole('button', { name: 'Continue' }).click()+ await page.waitForURL(/\/app-sign-in\/back\?desktop=1$/)+ await expect(page.getByText('Go back to the Linedesk app. You can close this tab.')).toBeVisible()+ await page.screenshot({ path: join(shots, '03-browser-done.png') })+ expect(await (await page.request.get(`${server}/api/auth/get-session`)).json()).toBeNull()+ await browser.close()++ await expect(win.locator('[data-call-id]').first()).toBeVisible({ timeout: 30_000 })+ await shot('04-inbox')+ // The web app's "Add a passkey" offer after a sign-in (not in the macOS app): not now.+ const passkey = win.getByRole('dialog', { name: 'Add a passkey' })+ if (await passkey.isVisible().catch(() => false)) await passkey.getByRole('button', { name: 'Not now' }).click()+})++test('3. the inbox by keyboard', async () => {+ const rows = win.locator('[data-call-id]')+ await win.locator('body').click({ position: { x: 640, y: 780 } })+ await win.keyboard.press('j')+ await expect(win.locator('[data-call-id].is-cursor')).toHaveCount(1)+ const second = await win.locator('[data-call-id].is-cursor').getAttribute('data-call-id')+ await win.keyboard.press('k')+ await expect(win.locator('[data-call-id].is-cursor')).not.toHaveAttribute('data-call-id', second ?? '')+ await win.keyboard.press('Enter')+ await expect(win).toHaveURL(/#call\//)+ await shot('05-call')+ await win.keyboard.press('Escape')+ await expect(rows.first()).toBeVisible()+ await win.keyboard.press(`${mod}+k`)+ await expect(win.getByRole('dialog')).toBeVisible()+ await shot('06-command-menu')+ await win.keyboard.press('Escape')+ await expect(win.getByRole('dialog')).toHaveCount(0)+})++test('4. Settings from the menu', async () => {+ await app.evaluate(({ Menu }) => {+ const find = (items: Electron.MenuItem[]): Electron.MenuItem | undefined => {+ for (const item of items) {+ if (/^Settings/.test(item.label)) return item+ const inner = item.submenu && find(item.submenu.items)+ if (inner) return inner+ }+ }+ find(Menu.getApplicationMenu()?.items ?? [])?.click()+ })+ await expect(win).toHaveURL(/#account\/profile/)+ await expect(win.getByText('Notifications on this device')).toBeVisible({ timeout: 15_000 })+ await expect(win.getByText(/New calls while the Linedesk app runs/)).toBeVisible()+ // In the app itself the browser's switch has no place.+ await expect(win.getByRole('switch', { name: 'Open links in the desktop app' })).toHaveCount(0)+ await shot('07-settings')+})++test('5. links: other sites in the browser, linedesk:// in the app', async () => {+ const before = win.url()+ await win.evaluate(() => {+ window.location.href = 'https://example.com/looks-like-linedesk'+ })+ await expect.poll(async () => (await spy(app)).opened).toContain('https://example.com/looks-like-linedesk')+ expect(win.url()).toBe(before)+ await win.evaluate(() => window.open('https://linedesk.ai/docs', '_blank'))+ await expect.poll(async () => (await spy(app)).opened).toContain('https://linedesk.ai/docs')+ expect(app.windows()).toHaveLength(1)+ await app.evaluate(({ app: a }) => a.emit('second-instance', {}, ['Linedesk', 'linedesk://open/#call/call_demo_02']))+ await expect(win).toHaveURL(/#call\/call_demo_02$/, { timeout: 15_000 })+ await expect(win.getByText('Quote for bathroom remodel').first()).toBeVisible({ timeout: 15_000 })+ await shot('08-deep-link-call')+})++test('6. window closed: an urgent call notifies, its click opens the call', async () => {+ // Back to the inbox, as a person would leave the call.+ await win.keyboard.press('Escape')+ await expect(win).not.toHaveURL(/#call\//)+ await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.close())+ expect(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())).toBe(false)+ sql("update calls set status='live', urgency='urgent', started_at=now(), ended_at=null where id='call_demo_01'")+ await expect+ .poll(async () => (await spy(app)).shown.map(s => s.title), { timeout: 30_000 })+ .toContainEqual(expect.stringMatching(/^Urgent: /))+ const notice = (await spy(app)).shown.find(s => s.title.startsWith('Urgent: '))!+ console.log(`notification: ${notice.title} / ${notice.body}`)+ await app.evaluate(() => {+ const g = globalThis as unknown as { notices: Electron.Notification[] }+ g.notices.find(n => n.title.startsWith('Urgent: '))?.emit('click')+ })+ await expect.poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible())).toBe(true)+ await expect(win).toHaveURL(/#call\/call_demo_01$/)+ await expect(win.getByText('That page does not exist.')).toHaveCount(0)+ await shot('09-notification-opened-call')+ sql("update calls set status='completed', urgency='normal', ended_at=now() where id='call_demo_01'")+})++test('7. no server: the offline page', async () => {+ // One app at a time: the first one ends before another starts.+ await app.close()+ const offline = await launch('https://127.0.0.1:9')+ const page = await offline.firstWindow()+ await expect(page.getByRole('heading', { name: 'No connection' })).toBeVisible({ timeout: 30_000 })+ await expect(page.getByRole('button', { name: 'Try again' })).toBeVisible()+ await page.screenshot({ path: join(shots, '10-offline.png') })+ await offline.close()+})diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.ymlindex 02039e5c..d419d047 100644--- a/apps/desktop/electron-builder.yml+++ b/apps/desktop/electron-builder.yml@@ -46,17 +46,36 @@ mac:extendInfo:NSMicrophoneUsageDescription: Linedesk uses the microphone for test calls with your assistant.notarize: true+# The .dmg window: the app, an arrow's distance from Applications, nothing else to read.dmg:title: LinedeskwriteUpdateInfo: false+ iconSize: 100+ window:+ width: 540+ height: 380+ contents:+ - x: 140+ y: 180+ type: file+ - x: 400+ y: 180+ type: link+ path: /Applicationswin:icon: build/icon.icotarget:- target: nsisarch: [x64, arm64]+# One click, no admin rights, no questions: installs for this person, adds Start menu and desktop shortcuts and opens+# the app (which then opens at login: src/install.ts).nsis:oneClick: trueperMachine: false+ runAfterFinish: true+ createDesktopShortcut: always+ createStartMenuShortcut: true+ shortcutName: LinedeskdeleteAppDataOnUninstall: falsedifferentialPackage: falseartifactName: Linedesk-${version}-win-setup.${ext}diff --git a/apps/desktop/src/bridge.ts b/apps/desktop/src/bridge.tsindex 74df2416..0b410c38 100644--- a/apps/desktop/src/bridge.ts+++ b/apps/desktop/src/bridge.ts@@ -1,5 +1,5 @@// What the web app and this shell say to each other (the preload's `window.linedeskDesktop`, the IPC channels). The-// web app's side of it: apps/web/src/native/desktop.ts.+// web app's side of it: apps/web/src/native/desktop/bridge.ts.export const CHANNEL = {signIn: 'linedesk:sign-in',@@ -8,6 +8,8 @@ export const CHANNEL = {badge: 'linedesk:badge',/** Main to page: open this call (a notification was clicked). */openCall: 'linedesk:open-call',+ getOpenAtLogin: 'linedesk:get-open-at-login',+ setOpenAtLogin: 'linedesk:set-open-at-login',} as const/** A notification about a call; one per call (`id`): a newer one replaces it. */@@ -30,8 +32,32 @@ export type Labels = {window: stringhelp: stringdocs: string+ /** macOS, first start outside Applications (install.ts). */+ moveTitle: string+ moveText: string+ moveButton: string+ notNow: string}+const LABEL_KEYS = [+ 'open',+ 'settings',+ 'quit',+ 'back',+ 'forward',+ 'reload',+ 'file',+ 'edit',+ 'view',+ 'window',+ 'help',+ 'docs',+ 'moveTitle',+ 'moveText',+ 'moveButton',+ 'notNow',+] as const+export const isCallNotice = (v: unknown): v is CallNotice => {const n = v as CallNoticereturn (@@ -49,7 +75,5 @@ export const isCallNotice = (v: unknown): v is CallNotice => {export const isLabels = (v: unknown): v is Labels =>!!v &&typeof v === 'object' &&- Object.values(v as object).every(s => typeof s === 'string' && s.length <= 80) &&- ['open', 'settings', 'quit', 'back', 'forward', 'reload', 'file', 'edit', 'view', 'window', 'help', 'docs'].every(- k => k in (v as object),- )+ Object.values(v as object).every(s => typeof s === 'string' && s.length <= 300) &&+ LABEL_KEYS.every(k => k in (v as object))diff --git a/apps/desktop/src/install.ts b/apps/desktop/src/install.tsnew file mode 100644index 00000000..25725c32--- /dev/null+++ b/apps/desktop/src/install.ts@@ -0,0 +1,77 @@+// The first start after installing, so nothing more is to set up by hand:+// - macOS: an app started from the .dmg or Downloads offers to move itself to Applications (and starts again there),+// so it stays, updates and opens links. Asked once, with the web app's words (bridge.ts Labels).+// - Open at login, on by default from the first start (the app notifies about calls only while it runs); the person+// turns it off in User settings › Profile. Started at login, the app stays in the Dock or tray without a window.+import { readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { app, dialog } from 'electron'+import type { Labels } from './bridge.ts'++const HIDDEN_ARG = '--hidden'+const stateFile = () => join(app.getPath('userData'), 'install-state.json')++type State = { loginItemSet?: boolean; moveAsked?: boolean }++function readState(): State {+ try {+ return JSON.parse(readFileSync(stateFile(), 'utf8')) as State+ } catch {+ return {}+ }+}++function writeState(next: State) {+ try {+ writeFileSync(stateFile(), JSON.stringify({ ...readState(), ...next }))+ } catch {+ // A read-only data folder: asked again next time.+ }+}++/** Login items only make sense for an installed app (not `electron .` in development). */+const installed = () => app.isPackaged && (process.platform === 'darwin' || process.platform === 'win32')++export function openAtLogin(): boolean {+ if (!installed()) return false+ return app.getLoginItemSettings(process.platform === 'win32' ? { args: [HIDDEN_ARG] } : undefined).openAtLogin+}++export function setOpenAtLogin(on: boolean) {+ if (!installed()) return+ app.setLoginItemSettings({ openAtLogin: on, args: [HIDDEN_ARG] })+ writeState({ loginItemSet: true })+}++/** On the first start of an installed app: open at login. */+export function firstStart() {+ if (!installed() || readState().loginItemSet) return+ setOpenAtLogin(true)+}++/** Started by the system at login: no window, the app waits in the Dock or tray for calls. */+export function startedAtLogin(): boolean {+ if (process.argv.includes(HIDDEN_ARG)) return true+ return process.platform === 'darwin' && app.isPackaged && app.getLoginItemSettings().wasOpenedAtLogin === true+}++/** macOS: once, an app outside Applications offers to move there (it quits and starts again from there). */+export async function offerMoveToApplications(labels: Labels) {+ if (process.platform !== 'darwin' || !app.isPackaged || app.isInApplicationsFolder() || readState().moveAsked) return+ writeState({ moveAsked: true })+ const { response } = await dialog.showMessageBox({+ type: 'question',+ message: labels.moveTitle,+ detail: labels.moveText,+ buttons: [labels.moveButton, labels.notNow],+ defaultId: 0,+ cancelId: 1,+ })+ if (response === 0) {+ try {+ app.moveToApplicationsFolder()+ } catch {+ // Not allowed (another copy is open there, or no rights): it keeps running from here.+ }+ }+}diff --git a/apps/desktop/src/links.ts b/apps/desktop/src/links.tsindex 6d8b176f..cfc0de05 100644--- a/apps/desktop/src/links.ts+++ b/apps/desktop/src/links.ts@@ -82,7 +82,7 @@ export function newWindowTarget(address: string, server: string): 'app' | 'exter/*** The server page a link opens in the app: `linedesk://open/#call/…` (from the web app's "Open in the desktop app")* and the server's own `https://…/#call/…` (a link given to the app on the command line). Only the start page with- * its page in the hash, like the links in emails, and like the mobile app (apps/web/src/native/init.ts pageToOpen).+ * its page in the hash, like the links in emails, and like the mobile app (apps/web/src/native/mobile/init.ts pageToOpen).* Null for anything else.*/export function pageForLink(link: string, server: string): string | null {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 626a0275..7080a4cd 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -23,6 +23,7 @@ import { APP_ID, E2E_BUILD, SERVER } from './config.ts'import { linkInArgs, navigationTarget, newWindowTarget, PROTOCOL, pageForLink } from './links.ts'import { appMenu, type MenuActions, makeTray, trayMenu } from './menu.ts'import { isStartPage, type Waiting, waitForSignIn } from './signIn.ts'+import { firstStart, offerMoveToApplications, openAtLogin, setOpenAtLogin, startedAtLogin } from './install.ts'import { startUpdates } from './updates.ts'import { keepWindowState, readWindowState } from './windowState.ts'@@ -169,7 +170,9 @@ function createMain() {main = new BrowserWindow({ ...windowOptions(), ...state, show: false })if (state.maximized) main.maximize()keepWindowState(main)- main.once('ready-to-show', () => main?.show())+ // Started at login: the app waits for calls without a window (the Dock icon or the tray opens it).+ const hidden = startedAtLogin()+ main.once('ready-to-show', () => !hidden && main?.show())// Closing the window keeps the app running (Dock on macOS, tray on Windows), so calls still notify; Quit ends it.main.on('close', e => {if (quitting) return@@ -234,8 +237,18 @@ ipcMain.on(CHANNEL.notify, (e, notice: unknown) => {})ipcMain.on(CHANNEL.labels, (e, next: unknown) => {if (!fromServer(e) || !isLabels(next)) return+ const first = !labelslabels = nextsetMenus()+ if (first) void offerMoveToApplications(next)+})+ipcMain.handle(CHANNEL.getOpenAtLogin, e => {+ if (!fromServer(e)) throw new Error('refused')+ return app.isPackaged ? openAtLogin() : null+})+ipcMain.handle(CHANNEL.setOpenAtLogin, (e, on: unknown) => {+ if (!fromServer(e) || typeof on !== 'boolean') throw new Error('refused')+ setOpenAtLogin(on)})ipcMain.on(CHANNEL.badge, (e, count: unknown) => {if (!fromServer(e) || typeof count !== 'number' || !Number.isInteger(count) || count < 0) return@@ -261,6 +274,7 @@ app.whenReady().then(() => {(_contents, permission, origin) => allowed.has(permission) && ownPage(origin),)app.on('web-contents-created', (_e, contents) => guard(contents))+ firstStart()createMain()if (!isMac) {tray = makeTray(staticFile('tray.png'), actions)diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 20e9556b..244e3808 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,4 +1,4 @@-// The bridge the web app sees as `window.linedeskDesktop` (apps/web/src/native/desktop.ts), only on the app's own+// The bridge the web app sees as `window.linedeskDesktop` (apps/web/src/native/desktop/bridge.ts), only on the app's own// server: a provider sign-in or Stripe page in this window gets nothing. The main process checks the sender's origin// again for every message.import { contextBridge, ipcRenderer } from 'electron'@@ -18,6 +18,9 @@ if (server && window.location.origin === server) {notify: (notice: CallNotice) => ipcRenderer.send(CHANNEL.notify, notice),setLabels: (labels: Labels) => ipcRenderer.send(CHANNEL.labels, labels),setBadge: (count: number) => ipcRenderer.send(CHANNEL.badge, count),+ /** Whether the app opens when the person signs in to the computer (null where it cannot: development). */+ getOpenAtLogin: (): Promise<boolean | null> => ipcRenderer.invoke(CHANNEL.getOpenAtLogin),+ setOpenAtLogin: (on: boolean): Promise<void> => ipcRenderer.invoke(CHANNEL.setOpenAtLogin, on),onOpenCall: (fn: (id: string) => void) => {const listener = (_: unknown, id: unknown) => typeof id === 'string' && fn(id)ipcRenderer.on(CHANNEL.openCall, listener)diff --git a/apps/desktop/static/offline.html b/apps/desktop/static/offline.htmlindex 4bddbf8c..7e6d9f89 100644--- a/apps/desktop/static/offline.html+++ b/apps/desktop/static/offline.html@@ -5,7 +5,7 @@<title>Linedesk</title><style>- html, body { height: 100%; margin: 0; }+ html, body { height: 100%; margin: 0; box-sizing: border-box; }body {display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px;padding: 24px;diff --git a/apps/mobile/README.md b/apps/mobile/README.mdindex f12a255c..12c562ec 100644--- a/apps/mobile/README.md+++ b/apps/mobile/README.md@@ -1,8 +1,10 @@# Linedesk app for iOS and Android+How the web, mobile and desktop apps fit together: [docs/apps.md](../../docs/apps.md).+A native shell around the web app (Capacitor). The app opens the server's own pages (`server.url` in`capacitor.config.ts`, default Linedesk Cloud), so the session, sync and every update come from the server as on the-web. The native parts are called by the web app when it runs in here (`apps/web/src/native`):+web. The native parts are called by the web app when it runs in here (`apps/web/src/native/mobile` and `sign-in`):- Sign-in with a provider (Google, Apple, Microsoft, GitHub, single sign-on) runs in the system's sign-in browser(iOS `ASWebAuthenticationSession`, Android Custom Tabs: `LinedeskAuthPlugin`) and the session comes back to the appdiff --git a/apps/mobile/android/app/src/main/java/ai/linedesk/app/LinedeskAuthPlugin.java b/apps/mobile/android/app/src/main/java/ai/linedesk/app/LinedeskAuthPlugin.javaindex 2c4cbc84..7838bdeb 100644--- a/apps/mobile/android/app/src/main/java/ai/linedesk/app/LinedeskAuthPlugin.java+++ b/apps/mobile/android/app/src/main/java/ai/linedesk/app/LinedeskAuthPlugin.java@@ -10,7 +10,7 @@ import com.getcapacitor.PluginMethod;import com.getcapacitor.annotation.CapacitorPlugin;/**- * A provider sign-in in the system browser (Chrome Custom Tabs), for the web app's native/appSignIn.ts: Google refuses+ * A provider sign-in in the system browser (Chrome Custom Tabs), for the web app's native/sign-in/appSignIn.ts: Google refuses* sign-ins inside an app's web view. `start` opens the server's sign-in page and resolves with the address the page* ends on: the server's own https address at `callbackPath`, a verified app link (assetlinks.json), so it comes back* to this activity and to no other app. Closing the tab without finishing rejects with "cancelled".diff --git a/apps/mobile/ios/App/App/AppDelegate.swift b/apps/mobile/ios/App/App/AppDelegate.swiftindex b2c45939..076d0d65 100644--- a/apps/mobile/ios/App/App/AppDelegate.swift+++ b/apps/mobile/ios/App/App/AppDelegate.swift@@ -11,7 +11,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {return true}- // Push notifications (@capacitor/push-notifications; the web app registers the token, apps/web/src/native/push.ts).+ // Push notifications (@capacitor/push-notifications; the web app registers the token, apps/web/src/native/mobile/push.ts).func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)}diff --git a/apps/mobile/ios/App/App/LinedeskBridge.swift b/apps/mobile/ios/App/App/LinedeskBridge.swiftindex 3fe731c3..97c34d14 100644--- a/apps/mobile/ios/App/App/LinedeskBridge.swift+++ b/apps/mobile/ios/App/App/LinedeskBridge.swift@@ -10,7 +10,7 @@ class LinedeskViewController: CAPBridgeViewController {}/// A provider sign-in in the system's sign-in browser (ASWebAuthenticationSession), for the web app's-/// native/appSignIn.ts: Google refuses sign-ins inside an app's web view, and this sheet is the one Apple expects.+/// native/sign-in/appSignIn.ts: Google refuses sign-ins inside an app's web view, and this sheet is the one Apple expects./// `start` opens the server's sign-in page and resolves with the address it ends on: the server's own https address at/// `callbackPath` (`.https` callback, iOS 17.4: only an app with the server's associated domain gets it, no custom/// scheme another app could also claim). Closing the sheet rejects with "cancelled".diff --git a/apps/web/src/Login.tsx b/apps/web/src/Login.tsxindex 0c98a568..662a0421 100644--- a/apps/web/src/Login.tsx+++ b/apps/web/src/Login.tsx@@ -52,7 +52,7 @@ import { emailFieldPasskey } from './passkey-autofill.ts'import { useQuery } from './cachedQuery.ts'import { LastUsed, ProviderButton, SignInMark } from './ui/brand-logos.tsx'import { AuthError } from './ui/AuthError.tsx'-import { isNativeApp } from './native/platform.ts'+import { isNativeApp } from './native/mobile/platform.ts'import { WaitLine } from './shell/SignedInAuthPage.tsx'import { HelpTip, type HelpTipContent } from './ui/HelpTip.tsx'import { Input } from './ui/form.tsx'diff --git a/apps/web/src/NoWorkspace.tsx b/apps/web/src/NoWorkspace.tsxindex fc1db172..51e85ca8 100644--- a/apps/web/src/NoWorkspace.tsx+++ b/apps/web/src/NoWorkspace.tsx@@ -17,7 +17,7 @@ import { AdminMode } from './admin/AdminMode.tsx'import { SecondFactorPrompt } from './admin/SecondFactorPrompt.tsx'import { auth, isInstanceAdmin, type Me } from './auth.ts'import { i18n } from './i18n/index.tsx'-import { isNativeApp } from './native/platform.ts'+import { isNativeApp } from './native/mobile/platform.ts'import { signOutAndForget } from './localData.ts'import { AdminStart } from './onboarding/AdminStart.tsx'import { AgentSetup, choseManualSetup, isAgentSetupHash, rememberManual } from './onboarding/AgentSetup.tsx'diff --git a/apps/web/src/Signup.tsx b/apps/web/src/Signup.tsxindex d131bb47..9e37f2d4 100644--- a/apps/web/src/Signup.tsx+++ b/apps/web/src/Signup.tsx@@ -14,7 +14,7 @@ import { ProviderButton } from './ui/brand-logos.tsx'import { CardFooter, CodeWait, HaveAccount, useAuthMethods } from './Login.tsx'import { browserPlace } from './countryHint.ts'import { signOutAndForget } from './localData.ts'-import { isNativeApp } from './native/platform.ts'+import { isNativeApp } from './native/mobile/platform.ts'import {CODE_LENGTH,codeErrorMessage,diff --git a/apps/web/src/Workspace.tsx b/apps/web/src/Workspace.tsxindex 4d287f6b..78071a9f 100644--- a/apps/web/src/Workspace.tsx+++ b/apps/web/src/Workspace.tsx@@ -7,7 +7,7 @@ import { AdminMode } from './admin/AdminMode.tsx'import { PasskeyStepUpHost } from './admin/PasskeyStepUp.tsx'import { SecondFactorPrompt } from './admin/SecondFactorPrompt.tsx'import { isInstanceAdmin, type Me, passkeySupported } from './auth.ts'-import { isNativeApp } from './native/platform.ts'+import { isNativeApp } from './native/mobile/platform.ts'import { workspaceBillingView } from './settings/billingModel.ts'import { PasskeyCard } from './AddPasskey.tsx'import { passkeyAsk, pausedAt } from './passkey-ask.ts'diff --git a/apps/web/src/auth.ts b/apps/web/src/auth.tsindex e37f2ea3..8c518fdc 100644--- a/apps/web/src/auth.ts+++ b/apps/web/src/auth.ts@@ -13,8 +13,8 @@ import { readLastUsedMethod } from './sign-in-methods.ts'import { announceSwitch } from './tabWorkspace.ts'import { brandName } from './brand.ts'import { i18n } from './i18n/index.tsx'-import { desktopApp, isDesktopApp } from './native/desktop.ts'-import { isNativeApp } from './native/platform.ts'+import { desktopApp, isDesktopApp } from './native/desktop/bridge.ts'+import { isNativeApp } from './native/mobile/platform.ts'export type { AuthMethods, LegalLinks, SsoMethod }@@ -348,7 +348,7 @@ export function signInWithPasskey() {/*** Leaves the page for the provider; the session exists when the browser comes back. In the Linedesk app (phone or- * desktop) the provider page opens in the system's sign-in browser instead and the session comes back by a one-use code (native/appSignIn.ts):+ * desktop) the provider page opens in the system's sign-in browser instead and the session comes back by a one-use code (native/sign-in/appSignIn.ts):* Google refuses sign-ins inside an app's web view. `cancelled`: the person closed that browser, nothing to say.*/export async function startSso(@@ -358,7 +358,7 @@ export async function startSso(const res = await auth.signIn.social({ provider: method.id, ...back() })return { error: res.error }}- const { nativeProviderSignIn } = await import('./native/appSignIn.ts')+ const { nativeProviderSignIn } = await import('./native/sign-in/appSignIn.ts')const { error } = await nativeProviderSignIn(method.id)if (error === 'cancelled' || error === 'user_cancelled_authorize' || error === 'access_denied')return { error: null, cancelled: true }diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 6acdc0bd..8f253ce4 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -1,12 +1,12 @@import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { App } from './App.tsx'-import { AppSignInPage } from './native/AppSignInPage.tsx'-import { readAppSignInPage } from './native/appSignIn.ts'-import { desktopAppReady, startDesktopApp } from './native/desktop.ts'-import { nativeAppReady, startNativeApp } from './native/init.ts'-import { OpenedInDesktopPage } from './native/OpenedInDesktopPage.tsx'-import { desktopLinkHere } from './native/openInDesktop.ts'+import { AppSignInPage } from './native/sign-in/AppSignInPage.tsx'+import { readAppSignInPage } from './native/sign-in/appSignIn.ts'+import { desktopAppReady, startDesktopApp } from './native/desktop/bridge.ts'+import { nativeAppReady, startNativeApp } from './native/mobile/init.ts'+import { OpenedInDesktopPage } from './native/desktop/OpenedInDesktopPage.tsx'+import { desktopLinkHere } from './native/desktop/openInDesktop.ts'// Fonts ship with the app: no request to a font CDN when a self-hosted install opens.import '@fontsource/geist/400.css'import '@fontsource/geist/500.css'@@ -28,9 +28,9 @@ import { registerServiceWorker } from './serviceWorker.ts'import { watchUnauthorized } from './signedOutWatch.ts'import { installTooltips } from './ui/tooltips.ts'-// Inside the iOS or Android app: status bar, back button, links (native/init.ts). Nothing in a browser.+// Inside the iOS or Android app: status bar, back button, links (native/mobile/init.ts). Nothing in a browser.startNativeApp()-// Inside the desktop app: notifications' clicks, its CSS class (native/desktop.ts). Nothing in a browser.+// Inside the desktop app: notifications' clicks, its CSS class (native/desktop/bridge.ts). Nothing in a browser.startDesktopApp()// Signed out on any screen: the app goes to the sign-in page (signedOutWatch.ts, App.tsx).watchUnauthorized()@@ -48,9 +48,9 @@ registerServiceWorker()const openRouterBack = captureOpenRouterReturn(window.location.search)if (openRouterBack) window.history.replaceState(null, '', `${window.location.pathname}${openRouterBack}`)-// The Linedesk app's provider sign-in, in the system browser (native/appSignIn.ts): only its own page, not the app.+// The Linedesk app's provider sign-in, in the system browser (native/sign-in/appSignIn.ts): only its own page, not the app.const appSignIn = readAppSignInPage()-// A link from an email that this browser hands to the desktop app (native/openInDesktop.ts): only a note stays here.+// A link from an email that this browser hands to the desktop app (native/desktop/openInDesktop.ts): only a note stays here.const toDesktop = appSignIn ? null : desktopLinkHere()if (toDesktop) window.location.href = toDesktopdiff --git a/apps/web/src/native/README.md b/apps/web/src/native/README.mdnew file mode 100644index 00000000..1c0cbfe0--- /dev/null+++ b/apps/web/src/native/README.md@@ -0,0 +1,21 @@+# Native shells: the web app's side++Linedesk has three ways to run the same web app: in a browser, in the mobile app (`apps/mobile`, Capacitor, iOS and+Android) and in the desktop app (`apps/desktop`, Electron, macOS and Windows). Both apps load the server's own pages;+there is no second client. This folder is everything the web app does differently inside them. Overview of all three:+[docs/apps.md](../../../../docs/apps.md).++| Folder | Runs in | What |+|---|---|---|+| `mobile/` | the mobile app | `platform.ts`: `isNativeApp()`, `nativePlatform()` (Capacitor). `plugins.ts`: the native plugins' interfaces (the plugins live in `apps/mobile`). `init.ts`: status bar, Android back button, links from emails, splash. `push.ts`: APNs/FCM device tokens. |+| `desktop/` | the desktop app, and browsers on a Mac or PC | `bridge.ts`: `desktopApp()`, `isDesktopApp()`, the menus' words, a clicked notification (the shell's preload gives `window.linedeskDesktop`). `openInDesktop.ts` and `OpenedInDesktopPage.tsx`: in a browser, hand links from emails to the desktop app when the person turned that on. |+| `sign-in/` | both apps, and the system browser they open | `appSignIn.ts`: a provider sign-in for an app: a one-use code with PKCE, back to the phone app on its verified https address or to the desktop app on a loopback port. `AppSignInPage.tsx`: the page in the system browser. The server side: `apps/api/src/app-sign-in.ts`. |++Rules:++- **Which shell am I in?** `isNativeApp()` is only the mobile app (store rules: no buying inside it). `isDesktopApp()`+ is only the desktop app (buying works there as on the web). In a browser both are false.+- Call native code only through these files; the rest of the web app imports from here and never from Capacitor or+ Electron directly.+- Text the user sees comes from i18n keys like everywhere else; the shells carry none of their own (the desktop menus+ get their words from `desktop/bridge.ts`).diff --git a/apps/web/src/native/OpenedInDesktopPage.tsx b/apps/web/src/native/desktop/OpenedInDesktopPage.tsxsimilarity index 84%rename from apps/web/src/native/OpenedInDesktopPage.tsxrename to apps/web/src/native/desktop/OpenedInDesktopPage.tsxindex b3624450..9fb5aa00 100644--- a/apps/web/src/native/OpenedInDesktopPage.tsx+++ b/apps/web/src/native/desktop/OpenedInDesktopPage.tsx@@ -1,8 +1,8 @@-// Shown in the browser tab whose page went on to the desktop app (native/openInDesktop.ts): where it went, the link+// Shown in the browser tab whose page went on to the desktop app (native/desktop/openInDesktop.ts): where it went, the link// again, and the way to stay here.import { useT } from '@linedesk/i18n/react'-import { brandName } from '../brand.ts'-import { AuthPage, Button } from '../ui/kit.tsx'+import { brandName } from '../../brand.ts'+import { AuthPage, Button } from '../../ui/kit.tsx'import { stayInBrowser } from './openInDesktop.ts'export function OpenedInDesktopPage({ link }: { link: string }) {diff --git a/apps/web/src/native/desktop.ts b/apps/web/src/native/desktop/bridge.tssimilarity index 79%rename from apps/web/src/native/desktop.tsrename to apps/web/src/native/desktop/bridge.tsindex 7f43dc89..d29f462e 100644--- a/apps/web/src/native/desktop.ts+++ b/apps/web/src/native/desktop/bridge.ts@@ -1,10 +1,10 @@// The Linedesk desktop app for macOS and Windows (apps/desktop, Electron around these same pages). Its preload gives// the server's own pages `window.linedeskDesktop`; in a browser and in the mobile app it is missing and everything-// here says "no". Unlike the mobile app (native/platform.ts isNativeApp), the desktop app is no store app: buying+// here says "no". Unlike the mobile app (native/mobile/platform.ts isNativeApp), the desktop app is no store app: buying// works in it as on the web.-import { brandName } from '../brand.ts'-import { i18n, onLocaleChange } from '../i18n/index.tsx'-import { callHash } from '../shell/useRoute.ts'+import { brandName } from '../../brand.ts'+import { i18n, onLocaleChange } from '../../i18n/index.tsx'+import { callHash } from '../../shell/useRoute.ts'/** A notification about a call (one per call id; a newer one replaces it). */export type DesktopNotice = { id: string; title: string; body: string; urgent: boolean }@@ -18,6 +18,9 @@ export interface DesktopBridge {notify(notice: DesktopNotice): voidsetLabels(labels: Record<string, string>): voidsetBadge(count: number): void+ /** Whether the app opens when the person signs in to the computer; null where it cannot (a development build). */+ getOpenAtLogin(): Promise<boolean | null>+ setOpenAtLogin(on: boolean): Promise<void>onOpenCall(fn: (id: string) => void): () => void}@@ -45,6 +48,10 @@ function menuLabels(): Record<string, string> {window: t('shell.desktop.window'),help: t('shell.desktop.help'),docs: t('shell.desktop.docs', { brand }),+ moveTitle: t('shell.desktop.moveTitle', { brand }),+ moveText: t('shell.desktop.moveText', { brand }),+ moveButton: t('shell.desktop.moveButton'),+ notNow: t('shell.desktop.notNow'),}}diff --git a/apps/web/src/native/openInDesktop.test.ts b/apps/web/src/native/desktop/openInDesktop.test.tssimilarity index 100%rename from apps/web/src/native/openInDesktop.test.tsrename to apps/web/src/native/desktop/openInDesktop.test.tsdiff --git a/apps/web/src/native/openInDesktop.ts b/apps/web/src/native/desktop/openInDesktop.tssimilarity index 97%rename from apps/web/src/native/openInDesktop.tsrename to apps/web/src/native/desktop/openInDesktop.tsindex 2cbeb97a..87609bc8 100644--- a/apps/web/src/native/openInDesktop.ts+++ b/apps/web/src/native/desktop/openInDesktop.ts@@ -3,8 +3,8 @@// Profile, Preferences), and from then on a page that came from outside (a link in an email or another app, not a// click inside Linedesk) goes on to the app as `linedesk://open/<the same page>`, while this tab says so and offers to// stay. The app opens only the start page with its page in the hash (apps/desktop/src/links.ts pageForLink).-import { isDesktopApp } from './desktop.ts'-import { isNativeApp } from './platform.ts'+import { isDesktopApp } from './bridge.ts'+import { isNativeApp } from '../mobile/platform.ts'const SETTING_KEY = 'linedesk.openLinksInDesktop'/** This tab stays in the browser (the person chose "Open here instead"). */diff --git a/apps/web/src/native/init.test.ts b/apps/web/src/native/mobile/init.test.tssimilarity index 100%rename from apps/web/src/native/init.test.tsrename to apps/web/src/native/mobile/init.test.tsdiff --git a/apps/web/src/native/init.ts b/apps/web/src/native/mobile/init.tssimilarity index 93%rename from apps/web/src/native/init.tsrename to apps/web/src/native/mobile/init.tsindex 1374099f..5da05fe6 100644--- a/apps/web/src/native/init.ts+++ b/apps/web/src/native/mobile/init.ts@@ -1,7 +1,7 @@// What the web app does once at start inside the Linedesk app (apps/mobile): the status bar, the splash screen, the// Android back button, links from emails (universal links / app links) and the page's edges around the notch.// Nothing here runs in a browser.-import { i18n } from '../i18n/index.tsx'+import { i18n } from '../../i18n/index.tsx'import { App, Keyboard, SplashScreen, StatusBar } from './plugins.ts'import { prepareNativePush } from './push.ts'import { nativePlatform } from './platform.ts'@@ -9,7 +9,7 @@ import { nativePlatform } from './platform.ts'/*** A link to the app's own server that should show here: only its start page (`/`, with the page in the hash, as links* in emails are), the one path besides the sign-in hand-back that the app claims (apps/api/src/app-links.ts, the- * Android intent filter). The hand-back belongs to the sign-in that waits for it (native/appSignIn.ts); any other path+ * Android intent filter). The hand-back belongs to the sign-in that waits for it (native/sign-in/appSignIn.ts); any other path* (the API, a download) never loads in the app's web view. Links elsewhere open in the system browser (Capacitor's* default).*/@@ -62,7 +62,7 @@ export function startNativeApp() {/*** After the first paint of the app (its language is loaded): the splash screen goes, and when the phone already allows- * notifications, Android's calls channel is made (native/push.ts prepareNativePush), signed in or not.+ * notifications, Android's calls channel is made (native/mobile/push.ts prepareNativePush), signed in or not.*/export function nativeAppReady() {if (!nativePlatform()) returndiff --git a/apps/web/src/native/platform.ts b/apps/web/src/native/mobile/platform.tssimilarity index 100%rename from apps/web/src/native/platform.tsrename to apps/web/src/native/mobile/platform.tsdiff --git a/apps/web/src/native/plugins.ts b/apps/web/src/native/mobile/plugins.tssimilarity index 100%rename from apps/web/src/native/plugins.tsrename to apps/web/src/native/mobile/plugins.tsdiff --git a/apps/web/src/native/push.ts b/apps/web/src/native/mobile/push.tssimilarity index 98%rename from apps/web/src/native/push.tsrename to apps/web/src/native/mobile/push.tsindex ec56949c..804ce6dc 100644--- a/apps/web/src/native/push.ts+++ b/apps/web/src/native/mobile/push.ts@@ -2,7 +2,7 @@// permission, its device token (registered with push.registerDevice, endpoint `apns:<token>` / `fcm:<token>`), and a// tap on a notification opening its call. The web push of browsers (../push.ts) does the same with a service worker.import { ANDROID_CALLS_CHANNEL, ANDROID_OLD_CALLS_CHANNEL, nativePushEndpoint } from '@linedesk/actions'-import { readStored, writeStored } from '../safeStorage.ts'+import { readStored, writeStored } from '../../safeStorage.ts'import { nativePlatform, type NativePlatform } from './platform.ts'import { PushNotifications } from './plugins.ts'diff --git a/apps/web/src/native/AppSignInPage.tsx b/apps/web/src/native/sign-in/AppSignInPage.tsxsimilarity index 93%rename from apps/web/src/native/AppSignInPage.tsxrename to apps/web/src/native/sign-in/AppSignInPage.tsxindex 0f8f8749..01938315 100644--- a/apps/web/src/native/AppSignInPage.tsx+++ b/apps/web/src/native/sign-in/AppSignInPage.tsx@@ -1,12 +1,12 @@-// The page the Linedesk app opens in the system's sign-in browser (native/appSignIn.ts): straight on to the provider;+// The page the Linedesk app opens in the system's sign-in browser (native/sign-in/appSignIn.ts): straight on to the provider;// back from it, who signed in and the person's OK; then the hand-back to the app. Shown in place of the whole web app.// The OK is a tap on purpose: no code ever leaves without it, and on Android a tap lets the verified link open the app.// For the desktop app (`port` in the address) the code goes to its loopback port, and the browser ends on a note.import { useT } from '@linedesk/i18n/react'import { useEffect, useState } from 'react'-import { WaitLine } from '../shell/SignedInAuthPage.tsx'-import { AuthError } from '../ui/AuthError.tsx'-import { AuthPage, Button } from '../ui/kit.tsx'+import { WaitLine } from '../../shell/SignedInAuthPage.tsx'+import { AuthError } from '../../ui/AuthError.tsx'+import { AuthPage, Button } from '../../ui/kit.tsx'import {type AppSignInPage as Page,appReturnUrl,diff --git a/apps/web/src/native/appSignIn.test.ts b/apps/web/src/native/sign-in/appSignIn.test.tssimilarity index 100%rename from apps/web/src/native/appSignIn.test.tsrename to apps/web/src/native/sign-in/appSignIn.test.tsdiff --git a/apps/web/src/native/appSignIn.ts b/apps/web/src/native/sign-in/appSignIn.tssimilarity index 98%rename from apps/web/src/native/appSignIn.tsrename to apps/web/src/native/sign-in/appSignIn.tsindex 066f094b..0f56ac0e 100644--- a/apps/web/src/native/appSignIn.ts+++ b/apps/web/src/native/sign-in/appSignIn.ts@@ -4,9 +4,9 @@// server's own https address (a universal link / verified app link only the real app receives). The desktop app// (apps/desktop) does the same, but its code comes back on a loopback address only it listens on (RFC 8252, 7.3):// `http://127.0.0.1:<port>/app-sign-in/back?code=…`, the port in the page's address (`port`).-import { auth } from '../auth.ts'-import { desktopApp } from './desktop.ts'-import { LinedeskAuth } from './plugins.ts'+import { auth } from '../../auth.ts'+import { desktopApp } from '../desktop/bridge.ts'+import { LinedeskAuth } from '../mobile/plugins.ts'/*** The browser page's own path (served like every path, the web app's index.html), and its parameters: the provider to@@ -21,7 +21,6 @@ const DONE_PARAM = 'done'/** The desktop app's loopback port (its sign-in) and the note it sends the browser to afterwards. */const PORT_PARAM = 'port'const DESKTOP_PARAM = 'desktop'-const CHALLENGE_KEY = 'linedesk.appSignInChallenge'const base64url = (bytes: Uint8Array) =>btoa(String.fromCharCode(...bytes))diff --git a/apps/web/src/nativePurchases.test.tsx b/apps/web/src/nativePurchases.test.tsxindex f37d2f03..860b76a0 100644--- a/apps/web/src/nativePurchases.test.tsx+++ b/apps/web/src/nativePurchases.test.tsx@@ -6,7 +6,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest'import type { Activation, Me } from './auth.ts'const native = vi.hoisted(() => ({ on: false }))-vi.mock('./native/platform.ts', () => ({+vi.mock('./native/mobile/platform.ts', () => ({isNativeApp: () => native.on,nativePlatform: () => (native.on ? 'ios' : null),}))diff --git a/apps/web/src/onboarding/ActivateStep.tsx b/apps/web/src/onboarding/ActivateStep.tsxindex 8a89bc7e..c2e83c87 100644--- a/apps/web/src/onboarding/ActivateStep.tsx+++ b/apps/web/src/onboarding/ActivateStep.tsx@@ -9,7 +9,7 @@ import { useFormat, useT } from '@linedesk/i18n/react'import { useState } from 'react'import type { Activation, Me } from '../auth.ts'import { goToCheckout } from '../checkout.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { askTermsAgain } from '../shell/TermsUpdate.tsx'import { useAssistantName } from '../store.tsx'import { IntervalSwitch } from '../ui/IntervalSwitch.tsx'diff --git a/apps/web/src/onboarding/AgentSetup.tsx b/apps/web/src/onboarding/AgentSetup.tsxindex 9d349ea7..56f980ad 100644--- a/apps/web/src/onboarding/AgentSetup.tsx+++ b/apps/web/src/onboarding/AgentSetup.tsx@@ -45,7 +45,7 @@ import { brandName, installBrandName, useBrand } from '../brand.ts'import { useQuery } from '../cachedQuery.ts'import { microphoneAllowed } from '../call/microphone.ts'import { i18n } from '../i18n/index.tsx'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { SETUP_LINK_KEY, signInAgain as signOutAndSignIn } from '../localData.ts'import { NewClientDialog } from '../partner/PartnerArea.tsx'import { loadPartner, PARTNER_QUERY } from '../partner/partner-api.ts'diff --git a/apps/web/src/onboarding/Frame.tsx b/apps/web/src/onboarding/Frame.tsxindex 43060378..2d59ae52 100644--- a/apps/web/src/onboarding/Frame.tsx+++ b/apps/web/src/onboarding/Frame.tsx@@ -4,7 +4,7 @@import { useT } from '@linedesk/i18n/react'import { type ReactNode, useEffect, useState } from 'react'import { brandName, installBrandName } from '../brand.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { Button } from '../ui/kit.tsx'import { Loading, SkeletonFields } from '../ui/LoadStates.tsx'import { useClientWord } from './clientWords.tsx'diff --git a/apps/web/src/onboarding/PhoneStep.tsx b/apps/web/src/onboarding/PhoneStep.tsxindex b7307695..a39e87ce 100644--- a/apps/web/src/onboarding/PhoneStep.tsx+++ b/apps/web/src/onboarding/PhoneStep.tsx@@ -6,7 +6,7 @@ import type { PhoneNumber } from '@linedesk/db/types'import { T, useT } from '@linedesk/i18n/react'import { useEffect, useState } from 'react'import type { PhoneSetupStatus } from '../auth.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { useDefaultPhoneCountry } from '../phoneCountry.ts'import { AreaCodeInput } from '../settings/AreaCodeInput.tsx'import { CarrierNumberInput } from '../settings/CarrierNumberInput.tsx'diff --git a/apps/web/src/onboarding/TrialLink.tsx b/apps/web/src/onboarding/TrialLink.tsxindex d8342031..d07d28b1 100644--- a/apps/web/src/onboarding/TrialLink.tsx+++ b/apps/web/src/onboarding/TrialLink.tsx@@ -6,7 +6,7 @@import { useFormat, useT } from '@linedesk/i18n/react'import { useEffect, useRef, useState } from 'react'import type { Me } from '../auth.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { useMembers } from '../team/members.ts'import { markAlreadyRunning, readTrialLink, takeTrialLink } from '../trialLink.ts'import { Dialog } from '../ui/form.tsx'diff --git a/apps/web/src/partner/PartnerArea.tsx b/apps/web/src/partner/PartnerArea.tsxindex 213821ed..f87a248d 100644--- a/apps/web/src/partner/PartnerArea.tsx+++ b/apps/web/src/partner/PartnerArea.tsx@@ -11,7 +11,7 @@ import {} from '@linedesk/actions'import { type MessageKey, msg } from '@linedesk/i18n'import { useT } from '@linedesk/i18n/react'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { type FormEvent, useEffect, useMemo, useState } from 'react'import { day } from '../admin/parts.tsx'import { setQueryData, useQuery } from '../cachedQuery.ts'diff --git a/apps/web/src/partner/PartnerSetup.tsx b/apps/web/src/partner/PartnerSetup.tsxindex 44e95ed6..cee2de14 100644--- a/apps/web/src/partner/PartnerSetup.tsx+++ b/apps/web/src/partner/PartnerSetup.tsx@@ -15,7 +15,7 @@ import { useEffect, useState } from 'react'import { ColorField, nameProblem, parsedColor } from '../admin/Branding.tsx'import { setQueryData, useQuery } from '../cachedQuery.ts'import { goToCheckout } from '../checkout.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { rememberDraftOpenedFrom } from '../onboarding/flow.ts'import { SetupFoot } from '../onboarding/SetupFoot.tsx'diff --git a/apps/web/src/push.ts b/apps/web/src/push.tsindex 2bac924d..a3a1cc01 100644--- a/apps/web/src/push.ts+++ b/apps/web/src/push.ts@@ -2,9 +2,14 @@// whether it gets pushes in the open workspace, and ending its subscription on sign-out. The// subscription (endpoint and keys) only goes to the API (push.subscribe); it is never stored here.import { type NotificationSettingsData, pushDeviceId } from '@linedesk/actions'-import { isDesktopApp } from './native/desktop.ts'-import { isNativeApp, nativePlatform } from './native/platform.ts'-import { nativeEndpointHere, onNativePushOpensCall, registerNativePush, unregisterNativePush } from './native/push.ts'+import { isDesktopApp } from './native/desktop/bridge.ts'+import { isNativeApp, nativePlatform } from './native/mobile/platform.ts'+import {+ nativeEndpointHere,+ onNativePushOpensCall,+ registerNativePush,+ unregisterNativePush,+} from './native/mobile/push.ts'import { serviceWorkerSupported } from './serviceWorker.ts'import { workspaceHeaders } from './tabWorkspace.ts'@@ -17,7 +22,7 @@ const isInstalled = () =>(navigator as { standalone?: boolean }).standalone === true/**- * iOS and iPadOS only offer push to an app added to the Home Screen. The Linedesk app has its own (native/push.ts).+ * iOS and iPadOS only offer push to an app added to the Home Screen. The Linedesk app has its own (native/mobile/push.ts).* The desktop app has no push service (Electron has none): it notifies from its own sync while it runs, also with its* window closed (shell/useCallNotifications.ts).*/diff --git a/apps/web/src/settings/Notifications.tsx b/apps/web/src/settings/Notifications.tsxindex b16c935f..705f37ba 100644--- a/apps/web/src/settings/Notifications.tsx+++ b/apps/web/src/settings/Notifications.tsx@@ -7,9 +7,9 @@ import { T, useT } from '@linedesk/i18n/react'import { type ReactNode, useEffect, useState } from 'react'import { brandName } from '../brand.ts'import { i18n } from '../i18n/index.tsx'-import { isDesktopApp } from '../native/desktop.ts'-import { nativePlatform } from '../native/platform.ts'-import { registerNativePush } from '../native/push.ts'+import { isDesktopApp } from '../native/desktop/bridge.ts'+import { nativePlatform } from '../native/mobile/platform.ts'+import { registerNativePush } from '../native/mobile/push.ts'import { currentEndpoint, pushSupport, subscribeThisBrowser, thisDeviceId } from '../push.ts'import {browserNotificationsSupported,@@ -76,7 +76,7 @@ export async function turnOnPush(if (blocked) return { id: null, note: blocked }try {if (nativePlatform()) {- // The app: Apple's or Google's device token (native/push.ts), registered like a browser's subscription.+ // The app: Apple's or Google's device token (native/mobile/push.ts), registered like a browser's subscription.const device = await registerNativePush(i18n().t('account.notify.callsChannel'))if (device === 'denied') return { id: null, note: blockedText() }const id = await thisDeviceId()diff --git a/apps/web/src/settings/PhoneNumbers.tsx b/apps/web/src/settings/PhoneNumbers.tsxindex f30dc01f..672aee9b 100644--- a/apps/web/src/settings/PhoneNumbers.tsx+++ b/apps/web/src/settings/PhoneNumbers.tsx@@ -49,7 +49,7 @@ import {offerHasAreaCode,phoneFromValue,} from '@linedesk/actions'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { useDefaultPhoneCountry } from '../phoneCountry.ts'import { providerAudience } from '../providerAudience.ts'import { notAnsweringWhy } from '../inbox/goLive.ts'diff --git a/apps/web/src/settings/account/Preferences.tsx b/apps/web/src/settings/account/Preferences.tsxindex bb54357a..719293ba 100644--- a/apps/web/src/settings/account/Preferences.tsx+++ b/apps/web/src/settings/account/Preferences.tsx@@ -7,7 +7,7 @@*/import { PSEUDO_LOCALE } from '@linedesk/i18n'import { useT } from '@linedesk/i18n/react'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { brandName } from '../../brand.ts'import { activate } from '../../i18n/index.tsx'import {@@ -19,7 +19,8 @@ import {} from '../../i18n/LanguageSelect.tsx'import { browserLanguages, missingBrowserLanguage } from '../../i18n/locale.ts'import { chooseLocale } from '../../i18n/user.ts'-import { canOpenInDesktop, opensLinksInDesktop, setOpensLinksInDesktop } from '../../native/openInDesktop.ts'+import { desktopApp } from '../../native/desktop/bridge.ts'+import { canOpenInDesktop, opensLinksInDesktop, setOpensLinksInDesktop } from '../../native/desktop/openInDesktop.ts'import { Switch } from '../../ui/controls.tsx'import { FeatureLine, LineGroup } from '../../ui/FeatureLine.tsx'import { Button, Note } from '../../ui/kit.tsx'@@ -82,7 +83,7 @@ function MissingLanguageNote() {}/**- * In a browser on a Mac or a Windows PC: links from emails open in the desktop app (native/openInDesktop.ts). Kept in+ * In a browser on a Mac or a Windows PC: links from emails open in the desktop app (native/desktop/openInDesktop.ts). Kept in* this browser, not on the account: another computer may not have the app.*/function DesktopLinks() {@@ -104,6 +105,36 @@ function DesktopLinks() {)}+/**+ * In the desktop app: whether it opens when the person signs in to the computer (on from the first start, so calls+ * notify; apps/desktop/src/install.ts). Hidden where the app cannot say (a development build).+ */+function OpenAtLogin() {+ const t = useT()+ const desktop = desktopApp()+ const [on, setOn] = useState<boolean | null>(null)+ useEffect(() => {+ void desktop+ ?.getOpenAtLogin()+ .then(setOn)+ .catch(() => setOn(null))+ }, [desktop])+ if (!desktop || on === null) return null+ const change = (next: boolean) => {+ setOn(next)+ void desktop.setOpenAtLogin(next).catch(() => setOn(!next))+ }+ return (+ <section className="k-card ac-desktop-links" aria-label={t('account.desktopApp.openAtLogin')}>+ <SettingRow+ title={t('account.desktopApp.openAtLogin')}+ description={t('account.desktopApp.openAtLoginDescription', { brand: brandName() })}+ control={<Switch label={t('account.desktopApp.openAtLogin')} on={on} onChange={change} />}+ />+ </section>+ )+}+/*** `saved`: reloads the account, so the choice shows when the page opens again. `hasWorkspace`: false on the screen* without a workspace (NoWorkspace.tsx), which has no notifications to set. `languageOpen`: a link to the language@@ -165,6 +196,7 @@ export function Preferences({{error && <Note tone="danger">{error}</Note>}</FeatureLine><DesktopLinks />+ <OpenAtLogin />{hasWorkspace && (<><LineGroup>{t('account.nav.notifications.label')}</LineGroup>diff --git a/apps/web/src/settings/billingModel.ts b/apps/web/src/settings/billingModel.tsindex fc930733..46aa8a0d 100644--- a/apps/web/src/settings/billingModel.ts+++ b/apps/web/src/settings/billingModel.ts@@ -11,7 +11,7 @@ import type {} from '@linedesk/actions'import { type Formatters, inTimeZone, knownTimeZone, type MessageKey, msg } from '@linedesk/i18n'import type { Me } from '../auth.ts'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'import { browserTimeZone, gmtOffset } from './timeZones.ts'/** Settings › Billing opens the add-calls dialog (`?addCalls=1`; the busy-line email and banner link there, LIN-450). */diff --git a/apps/web/src/settings/levelModel.ts b/apps/web/src/settings/levelModel.tsindex b885c26a..ed107e78 100644--- a/apps/web/src/settings/levelModel.ts+++ b/apps/web/src/settings/levelModel.ts@@ -2,7 +2,7 @@// packages/actions/src/usage-level.ts): their names and, where there are prices, the price a minute.import { CALL_QUALITY_LABELS, type CallQuality, type CallQualityLevelOption } from '@linedesk/actions'import { i18n } from '../i18n/index.tsx'-import { isNativeApp } from '../native/platform.ts'+import { isNativeApp } from '../native/mobile/platform.ts'/** The value of the "Default" option (the server's model for the level). */export const DEFAULT_CHOICE = ''diff --git a/apps/web/src/settings/notificationPermission.ts b/apps/web/src/settings/notificationPermission.tsindex 6403ecee..ae6e2fcc 100644--- a/apps/web/src/settings/notificationPermission.ts+++ b/apps/web/src/settings/notificationPermission.ts@@ -2,8 +2,8 @@// Notifications and the onboarding notify step, which ask for it when turned on.import { useEffect, useState } from 'react'import { brandName } from '../brand.ts'-import { isNativeApp } from '../native/platform.ts'-import { askNativePermission, nativePermission, readNativePermission } from '../native/push.ts'+import { isNativeApp } from '../native/mobile/platform.ts'+import { askNativePermission, nativePermission, readNativePermission } from '../native/mobile/push.ts'import { pushSupport } from '../push.ts'import { browserNotificationsSupported } from '../shell/useCallNotifications.ts'import { i18n } from '../i18n/index.tsx'@@ -11,7 +11,7 @@ import { i18n } from '../i18n/index.tsx'export type NotificationPermissionState = 'granted' | 'default' | 'denied' | 'unsupported' | 'ios-needs-install'const read = (): NotificationPermissionState => {- // The app: the phone's own permission (native/push.ts), read again on focus and after asking.+ // The app: the phone's own permission (native/mobile/push.ts), read again on focus and after asking.if (isNativeApp()) return nativePermission()if (pushSupport() === 'ios-needs-install') return 'ios-needs-install'return browserNotificationsSupported() ? Notification.permission : 'unsupported'diff --git a/apps/web/src/shell/setup-account-menu-routes.test.ts b/apps/web/src/shell/setup-account-menu-routes.test.tsindex 5f530ce2..19e02d2a 100644--- a/apps/web/src/shell/setup-account-menu-routes.test.ts+++ b/apps/web/src/shell/setup-account-menu-routes.test.ts@@ -45,14 +45,14 @@ const SETUP_SCREENS: Record<string, string> = {const MENU_HOSTS = ['onboarding/SetupTopBar.tsx', 'shell/SignedInAuthPage.tsx']/** Pages before signing in: the bare card page, no account to show. */-// native/AppSignInPage.tsx: the app's sign-in hand-back in the system browser, which signs that browser out again.-// native/OpenedInDesktopPage.tsx: a browser tab that handed its link to the desktop app; shown before the app starts.+// native/sign-in/AppSignInPage.tsx: the app's sign-in hand-back in the system browser, which signs that browser out again.+// native/desktop/OpenedInDesktopPage.tsx: a browser tab that handed its link to the desktop app; shown before the app starts.const SIGNED_OUT_ONLY = new Set(['Login.tsx','SignInLink.tsx','shell/SignedInAuthPage.tsx',- 'native/AppSignInPage.tsx',- 'native/OpenedInDesktopPage.tsx',+ 'native/sign-in/AppSignInPage.tsx',+ 'native/desktop/OpenedInDesktopPage.tsx',])function files(dir: string): string[] {diff --git a/apps/web/src/shell/useCallNotifications.ts b/apps/web/src/shell/useCallNotifications.tsindex 4b318194..0536c86e 100644--- a/apps/web/src/shell/useCallNotifications.ts+++ b/apps/web/src/shell/useCallNotifications.ts@@ -4,7 +4,7 @@// `browser` setting. Only when the tab is in the background, only for calls that finished after the app// opened, never for test calls or spam; an urgent call already while it runs, when the assistant flags it (like the// push of kind `urgent`; the same tag, so its end replaces it). Clicking one opens the call. In the desktop app-// (native/desktop.ts) the app shows them, also with its window closed.+// (native/desktop/bridge.ts) the app shows them, also with its window closed.import type { NotificationSettingsData } from '@linedesk/actions'import type { Call } from '@linedesk/db/types'import { useEffect, useRef } from 'react'@@ -15,7 +15,7 @@ import { readAction } from '../settings/settings-api.ts'import { useRows } from '../store.tsx'import { callHash } from './useRoute.ts'import { i18n } from '../i18n/index.tsx'-import { desktopApp } from '../native/desktop.ts'+import { desktopApp } from '../native/desktop/bridge.ts'// The member's settings, shared by this hook and Account settings, Notifications (which updates them on// change): the last known at once (also across page loads), checked again in the background.@@ -76,7 +76,7 @@ function notificationTitle(call: Call): string {function show(call: Call, callerName: (call: Call) => string) {const title = notificationTitle(call)const body = [callerName(call), call.summary].filter(Boolean).join(' · ')- // The desktop app shows it itself: urgent ones stay, a click brings its window back (native/desktop.ts).+ // The desktop app shows it itself: urgent ones stay, a click brings its window back (native/desktop/bridge.ts).const desktop = desktopApp()if (desktop) return desktop.notify({ id: call.id, title, body, urgent: call.urgency === 'urgent' })const notification = new Notification(title, {diff --git a/docs/apps.md b/docs/apps.mdnew file mode 100644index 00000000..9105084e--- /dev/null+++ b/docs/apps.md@@ -0,0 +1,40 @@+# Apps: web, mobile, desktop++Linedesk is one web app (`apps/web`). The mobile and desktop apps are thin native shells that open the server's own+pages, so sessions, sync, the outbox and every update work and ship as on the web. Nothing is built twice: a feature+in the web app is in every app. The details of each shell are in [architecture.md](architecture.md), section 19.++| | Web | Mobile (iOS, Android) | Desktop (macOS, Windows) |+|---|---|---|---|+| Code | `apps/web` | `apps/mobile` (Capacitor) | `apps/desktop` (Electron) |+| Web app's side | — | `apps/web/src/native/mobile/` | `apps/web/src/native/desktop/` |+| How the web app knows | — | `isNativeApp()` | `isDesktopApp()` |+| Provider sign-in (Google, Apple, Microsoft, GitHub, SSO) | in the page | system browser, code back on the verified https address | system browser, code back on a loopback port |+| Sign-in code (both apps) | — | `apps/web/src/native/sign-in/`, `apps/api/src/app-sign-in.ts` | same |+| Links from emails | the page | universal links / app links (`apps/api/src/app-links.ts`) | `linedesk://open/…`; a browser hands them over when "Open links in the desktop app" is on |+| Notifications | Web Push (service worker) and while the tab is open | APNs / FCM (`apps/api/src/native-push.ts`) | from the app's own sync while it runs (also with its window closed) |+| Buying | yes | no (store rules: every purchase step hidden) | yes |+| Builds | `ci.yml` (Docker images) | `mobile.yml` | `desktop.yml` |+| Server it opens | — | `LINEDESK_APP_URL` at build time (default Linedesk Cloud) | the same |++## Where to change what++- A screen, a setting, an action: in `apps/web` and `packages/*` as always. It reaches both apps with the next deploy of+ the server; the apps need no new build.+- Something only a native shell can do (a system sheet, a native notification, a menu): the shell's code in+ `apps/mobile` or `apps/desktop`, and its call from the web app in `apps/web/src/native/` (see its+ [README](../apps/web/src/native/README.md)). Never import Capacitor or Electron anywhere else in the web app.+- Sign-in for the apps: `apps/web/src/native/sign-in/` and `apps/api/src/app-sign-in.ts`. A change there needs a security+ review.++## Build and test++Mobile: [apps/mobile/README.md](../apps/mobile/README.md). Desktop: [apps/desktop/README.md](../apps/desktop/README.md).+Both build in CI on every pull request that changes them; the desktop workflow installs each build on a macOS and a+Windows runner and tests it with screenshots, and keeps the installers as artifacts.++## Your own server++The apps open Linedesk Cloud. For your own server, build them with `LINEDESK_APP_URL=https://your.server`, and your own+bundle IDs, signing and keys (each app's README says which). The server needs nothing extra for the desktop app; for the+mobile app it names the app in `.env` (`MOBILE_IOS_APP_IDS`, `MOBILE_ANDROID_APP`) so that links open it.diff --git a/docs/architecture.md b/docs/architecture.mdindex c22e31fd..77e7c9b2 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -543,13 +543,13 @@ Design: [white-label.md](white-label.md) (decided 2026-11-17). A partner (`partn## 19. Mobile apps (iOS, Android)-`apps/mobile` is a Capacitor shell around the web app (decision of 2026-11-28), not a second client: the app opens the server's own pages (`server.url`, Linedesk Cloud by default; `LINEDESK_APP_URL` at `cap sync` for another server), so sessions, sync, the outbox and every update work and ship as on the web. The web app finds out it runs inside the app with `isNativeApp()` (`apps/web/src/native/platform.ts`) and calls the native plugins only through `apps/web/src/native/plugins.ts` (Capacitor's `registerPlugin`; the plugin code lives in `apps/mobile`).+`apps/mobile` is a Capacitor shell around the web app (decision of 2026-11-28), not a second client: the app opens the server's own pages (`server.url`, Linedesk Cloud by default; `LINEDESK_APP_URL` at `cap sync` for another server), so sessions, sync, the outbox and every update work and ship as on the web. The web app finds out it runs inside the app with `isNativeApp()` (`apps/web/src/native/mobile/platform.ts`) and calls the native plugins only through `apps/web/src/native/mobile/plugins.ts` (Capacitor's `registerPlugin`; the plugin code lives in `apps/mobile`).- **Provider sign-in.** Google refuses OAuth inside an app's web view, so in the app every provider sign-in (Google, Apple, Microsoft, GitHub, OIDC) runs in the system's sign-in browser: iOS `ASWebAuthenticationSession` (iOS 17.4, `.https` callback), Android Chrome Custom Tabs (`LinedeskAuthPlugin`, our own plugin in both projects; it opens only the app's own server). The session comes back like an OAuth code with PKCE, tied to a provider sign-in of that same flow (`apps/api/src/app-sign-in.ts`, a Better Auth plugin; security review of #1997): the app keeps a random verifier and opens `/app-sign-in?provider=…&challenge=<SHA-256 of it>`. That page posts the challenge to `POST /api/auth/app-sign-in/start` (kept with the time in a signed httpOnly cookie of that browser, 15 minutes) and signs in with the provider. Back from it, the page shows who signed in and asks for the person's OK; only then `POST /api/auth/app-sign-in/code` gives a one-use code (32 random bytes, stored hashed in `verification` with the user, the challenge and the browser's session; 2 minutes, one per start), and only for a session made after the start: a session the browser had before never counts, and an impersonation never. The code goes to the app on the server's own https address `/app-sign-in/back?code=…`, a universal link / verified app link that only the real app receives (no custom scheme another app could claim). The app's web view redeems it with the verifier (`POST /api/auth/app-sign-in/redeem`): the row is deleted in the same statement that reads it, a wrong verifier spends it, the browser's session must still exist (a password reset or "sign out everywhere" in between ends the hand-back) and is ended, the web view's own older session too, and the new session is made by Better Auth's adapter, so the session hooks run (disabled accounts, the host, the audit log with method `app`). All three endpoints check the origin like Better Auth's own sign-in endpoints (`formCsrfMiddleware`), so another site's form can neither start nor redeem. Everything the provider sign-in itself checks (address proof, sign-up gate, admin alerts) ran in the browser. Email codes, passwords and passkeys work inside the app's web view as on the web (passkeys through the app's associated domain).-- **Links.** `GET /.well-known/apple-app-site-association` and `/.well-known/assetlinks.json` (`apps/api/src/app-links.ts`, from `MOBILE_IOS_APP_IDS` and `MOBILE_ANDROID_APP`; 404 without them) let links to the start page `/` (every email link: `/#call/…`, `/?invite=…`) and the sign-in hand-back `/app-sign-in/back` open the app; the app then shows that address (`appUrlOpen`, `native/init.ts`; the hand-back belongs to the waiting sign-in). Other paths (`/app-sign-in`, the API, Stripe's return) stay in the browser.+- **Links.** `GET /.well-known/apple-app-site-association` and `/.well-known/assetlinks.json` (`apps/api/src/app-links.ts`, from `MOBILE_IOS_APP_IDS` and `MOBILE_ANDROID_APP`; 404 without them) let links to the start page `/` (every email link: `/#call/…`, `/?invite=…`) and the sign-in hand-back `/app-sign-in/back` open the app; the app then shows that address (`appUrlOpen`, `native/mobile/init.ts`; the hand-back belongs to the waiting sign-in). Other paths (`/app-sign-in`, the API, Stripe's return) stay in the browser.- **Push.** The app gets its pushes from Apple (APNs, token-based with the `.p8` key, `apps/api/src/native-push.ts`, over HTTP/2; production first, the sandbox for a build from Xcode) and Google (FCM HTTP v1, an access token from the service account), next to the browsers' Web Push and with the same payload and job (`push.ts`): who called and, for members who opted in, one line on what about; one notification per call (APNs `apns-collapse-id`, FCM `collapse_key` and tag), time-sensitive on iOS and the high-importance "Calls" channel on Android for urgent calls (channel `calls-v2`, private on the lock screen: only that a notification came, not who called or why). Turning on notifications in the app asks the phone, registers it with Apple or Google and stores its token with `push.registerDevice` in `push_subscriptions` as the endpoint `apns:<token>` or `fcm:<token>` (no keys; the same row rules as a browser: per member and workspace, at most 10, a token of someone else's row is taken over, gone tokens are deleted when APNs or FCM say so (FCM: only `UNREGISTERED`), sign-out removes it, and the row ends with the session that registered it: `push_subscriptions.session_id`, ON DELETE CASCADE, so a sign-out in Settings › Sessions, a password change or reset that ends the other sessions, or expiry stops its pushes too). The keys are Server admin › Providers › Mobile app push (Apple Push Notifications: `.p8` key, key ID, team ID, bundle ID; Firebase Cloud Messaging: the service account JSON), read at each push; Test connection sends to a made-up device. Unlike Web Push (encrypted end to end, RFC 8291), Apple and Google can read the app's notifications: the caller's name or number and, for members who opted in, the summary line.- **Phone.** Status bar, splash screen, the Android back button (closes what is open, then goes back, then puts the app in the background), the keyboard, safe areas (`viewport-fit=cover` inside the app).- **No buying in the apps.** The store rules (App Store 3.1.1 and 3.1.3(b), Google Play payments) allow a multiplatform service whose plans are bought elsewhere, without calls to action. Inside the app every purchase step is hidden: Settings › Billing, the billing banner, the trial link, the plan step of onboarding (a neutral "Your plan is managed on the web" step that waits for the plan), extra paid phone numbers, the partner's activation and billing, prices of call quality levels, and trial wording on the sign-up and sign-in pages.- **Account deletion** (App Store 5.1.1(v)): Account › Profile › Delete account opens Workspace settings › Danger zone, where leaving the last workspace or deleting an owned one deletes the account.- **Builds.** CI builds both apps on a pull request that changes `apps/mobile`; on the trunk the iOS build goes to TestFlight (App Store Connect API key, signed in the cloud) and the signed Android bundle (upload key) is kept for Google Play.-- **Desktop (macOS, Windows).** `apps/desktop` is an Electron shell around the same pages (decision of 2026-12-03; Electron over Tauri: TypeScript like the rest, the same Chromium on both systems, and its packaging signs, notarizes and makes the Windows installer). The web app finds it by `window.linedeskDesktop` (`apps/web/src/native/desktop.ts`; the preload gives it only to the server's own pages, and the main process checks every message's origin), not by `isNativeApp()`: it is no store app, so buying works as on the web. A provider sign-in runs in the system browser with the hand-back above, except that the code comes back on a loopback address only the app listens on (RFC 8252, 7.3): the app's start page carries `port`, the browser page sends the code to `http://127.0.0.1:<port>/app-sign-in/back` (never another host) and then shows `/app-sign-in/back?desktop=1` ("go back to the app"); the server is unchanged. No push service in Electron: while the app runs (its window closed too) it notifies from its own sync (`useCallNotifications.ts`: an urgent call as soon as it is flagged, every call when it ends; the main process shows them when its window is not in front). `linedesk://open/<search><hash>` opens the start page with that page; a browser on a Mac or PC hands links from emails to the app when "Open links in the desktop app" is on there (`native/openInDesktop.ts`, kept in that browser). Only the server's pages and a fixed list of consent and checkout sites that lead back to it stay in the window (`IN_WINDOW_SITES`); other links open in the browser. The browser page takes `port` only in a computer's browser: on a phone another app could listen on a loopback port, so there the code goes only to the verified https address. A shipped app refuses a debugging port. Automatic updates are built in and off. CI builds a .dmg and a Windows installer, installs and tests them, and keeps them as artifacts; nothing is published.+- **Desktop (macOS, Windows).** `apps/desktop` is an Electron shell around the same pages (decision of 2026-12-03; Electron over Tauri: TypeScript like the rest, the same Chromium on both systems, and its packaging signs, notarizes and makes the Windows installer). The web app finds it by `window.linedeskDesktop` (`apps/web/src/native/desktop/bridge.ts`; the preload gives it only to the server's own pages, and the main process checks every message's origin), not by `isNativeApp()`: it is no store app, so buying works as on the web. A provider sign-in runs in the system browser with the hand-back above, except that the code comes back on a loopback address only the app listens on (RFC 8252, 7.3): the app's start page carries `port`, the browser page sends the code to `http://127.0.0.1:<port>/app-sign-in/back` (never another host) and then shows `/app-sign-in/back?desktop=1` ("go back to the app"); the server is unchanged. No push service in Electron: while the app runs (its window closed too) it notifies from its own sync (`useCallNotifications.ts`: an urgent call as soon as it is flagged, every call when it ends; the main process shows them when its window is not in front). `linedesk://open/<search><hash>` opens the start page with that page; a browser on a Mac or PC hands links from emails to the app when "Open links in the desktop app" is on there (`native/desktop/openInDesktop.ts`, kept in that browser). Only the server's pages and a fixed list of consent and checkout sites that lead back to it stay in the window (`IN_WINDOW_SITES`); other links open in the browser. The browser page takes `port` only in a computer's browser: on a phone another app could listen on a loopback port, so there the code goes only to the verified https address. A shipped app refuses a debugging port. Automatic updates are built in and off. CI builds a .dmg and a Windows installer, installs and tests them, and keeps them as artifacts; nothing is published.diff --git a/packages/i18n/locales/en/account.json b/packages/i18n/locales/en/account.jsonindex 0cb74bd8..b0fdadc5 100644--- a/packages/i18n/locales/en/account.json+++ b/packages/i18n/locales/en/account.json@@ -94,6 +94,8 @@"delete.buttonTitle": "Opens Workspace settings › Danger zone","delete.text": "Deletes your account and your sign-in for good. Your account goes with your last workspace: leave it, or delete it if you own it. Both are under <link>Workspace settings › Danger zone</link>.","delete.title": "Delete account",+ "desktopApp.openAtLogin": "Open at login",+ "desktopApp.openAtLoginDescription": "{brand} starts in the background when you sign in to this computer, so new calls reach you.","desktopLinks.description": "Links from emails open in the {brand} app for Mac or Windows on this computer, not in this browser.","desktopLinks.title": "Open links in the desktop app","device.apiClient": "API client",diff --git a/packages/i18n/locales/en/shell.json b/packages/i18n/locales/en/shell.jsonindex 578d3af9..0b821ed6 100644--- a/packages/i18n/locales/en/shell.json+++ b/packages/i18n/locales/en/shell.json@@ -70,6 +70,10 @@"desktop.file": "File","desktop.forward": "Forward","desktop.help": "Help",+ "desktop.moveButton": "Move to Applications",+ "desktop.moveText": "{brand} runs from here now. In Applications it stays after a restart and opens links from emails.",+ "desktop.moveTitle": "Move {brand} to Applications?",+ "desktop.notNow": "Not now","desktop.open": "Open {brand}","desktop.openAgain": "Open in the {brand} app again","desktop.openHere": "Open here instead",