From 9545456ee00ce4f83acb956b92a9f9caca4bbd20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Hadry=C5=9B?= Date: Fri, 16 Oct 2026 05:40:48 +0200 Subject: [PATCH 01/12] feat(helper): list installed apps and their icons for the Style page The Style page cannot show which installed apps a style applies to, because nothing lists installed apps. Electron's app.getFileIcon cannot supply the icons either: on macOS 27 it returns one generic placeholder for every .app, and size "large" crashes Electron. Protocol 12 adds apps.list and icons.render. The helper scans /Applications, /System/Applications and ~/Applications, plus one level of plain subfolders, reads each Info.plist directly, and draws NSWorkspace icons into 64x64 PNGs, all on a utility queue. Main asks for the list only when the hub calls getInstalledApps, lowercases and dedupes bundle ids, and asks for icons only for catalog apps it has not rendered yet. Icons stay in memory for the life of main. A malformed list entry is dropped and the rest kept. If the helper does not answer within five seconds, the list rejects and the next call starts over. BROWSER_BUNDLE_IDS mirrors the helper's browser list for the coming app picker, and a test keeps the two equal. --- apps/desktop/src/main/helper.test.ts | 6 +- apps/desktop/src/main/index.ts | 5 + apps/desktop/src/main/installed-apps.test.ts | 145 ++++++++++++++++++ apps/desktop/src/main/installed-apps.ts | 87 +++++++++++ apps/desktop/src/main/protocol.test.ts | 47 +++++- apps/desktop/src/main/protocol.ts | 25 ++- apps/desktop/src/main/testing/fake-helper.ts | 2 +- apps/desktop/src/preload/hub.test.ts | 1 + apps/desktop/src/preload/hub.ts | 1 + apps/desktop/src/renderer/preview.tsx | 18 +++ apps/desktop/src/shared/api.ts | 7 + .../desktop/src/shared/app-categories.test.ts | 19 +++ apps/desktop/src/shared/app-categories.ts | 17 ++ .../Sources/VoiceHelper/InstalledApps.swift | 77 ++++++++++ .../Sources/VoiceHelper/main.swift | 8 +- .../VoiceHelperCore/InstalledApp.swift | 43 ++++++ .../Sources/VoiceHelperCore/Protocol.swift | 30 ++++ .../InstalledAppTests.swift | 45 ++++++ .../VoiceHelperCoreTests/ProtocolTests.swift | 14 +- native/voice-helper/scripts/helper.mjs | 2 +- 20 files changed, 589 insertions(+), 10 deletions(-) create mode 100644 apps/desktop/src/main/installed-apps.test.ts create mode 100644 apps/desktop/src/main/installed-apps.ts create mode 100644 apps/desktop/src/shared/app-categories.test.ts create mode 100644 native/voice-helper/Sources/VoiceHelper/InstalledApps.swift create mode 100644 native/voice-helper/Sources/VoiceHelperCore/InstalledApp.swift create mode 100644 native/voice-helper/Tests/VoiceHelperCoreTests/InstalledAppTests.swift diff --git a/apps/desktop/src/main/helper.test.ts b/apps/desktop/src/main/helper.test.ts index 7d2eaec3..8db3e8a5 100644 --- a/apps/desktop/src/main/helper.test.ts +++ b/apps/desktop/src/main/helper.test.ts @@ -100,7 +100,7 @@ describe("startHelper", () => { const h = boot({ transcript: "call ada tomorrow", startMs: 20 }); helper = h.helper; await h.waitFor((e) => e.type === "asr.status"); - expect(h.of("ready")[0]?.event).toEqual({ type: "ready", version: 11 }); + expect(h.of("ready")[0]?.event).toEqual({ type: "ready", version: 12 }); expect(h.of("log").map((e) => e.event.message)).toContain("hotkey configured: fn"); expect(h.of("permissions")[0]?.event).toEqual({ type: "permissions", @@ -203,12 +203,12 @@ describe("startHelper", () => { helper = h.helper; await expect .poll(() => h.logs.join("\n")) - .toMatch(/helper: speaks protocol v2 but this build expects v11; refusing/); + .toMatch(/helper: speaks protocol v2 but this build expects v12; refusing/); expect(h.entries).toEqual([ { message: "helper protocol mismatch", level: "fatal", - attributes: { "helper.protocol_version": 2, "helper.expected_version": 11 }, + attributes: { "helper.protocol_version": 2, "helper.expected_version": 12 }, }, ]); await sleep(RESTART_MIN_MS + 150); diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 03f3b8b7..7f126395 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -56,6 +56,7 @@ import { startHelper, type Helper } from "./helper.ts"; import { hubMinimumSize, hubWindowSize } from "./hub-window.ts"; import { createHistory } from "./history.ts"; import { createInsights } from "./insights.ts"; +import { createInstalledApps } from "./installed-apps.ts"; import type { Commands } from "./ipc.ts"; import { denyPermissions, lockNavigation, pageUrl, type Page } from "./lockdown.ts"; import { createApplicationMenu } from "./menu.ts"; @@ -345,6 +346,7 @@ async function main() { if (lifecycle !== "running") return; dictation.onHelperEvent(event); microphoneTest.onHelperEvent(event); + installedApps.onHelperEvent(event); }, onExit: (exit) => { if (lifecycle === "running") { @@ -423,6 +425,8 @@ async function main() { }, }); + const installedApps = createInstalledApps({ send: helper.send }); + const updates = createUpdates({ loadEngine: store.state.updates.status.kind === "disabled" @@ -800,6 +804,7 @@ async function main() { hubCommands.handle(Channel.cancelAccountDeletion, () => account.cancelDeletion()); hubCommands.handle(Channel.retryAccountDeletion, () => account.retryDeletion()); hubCommands.handle(Channel.getInsights, () => insights.get()); + hubCommands.handle(Channel.getInstalledApps, () => installedApps.list()); hubCommands.handle(Channel.clearInsights, async () => { try { await insights.clear(); diff --git a/apps/desktop/src/main/installed-apps.test.ts b/apps/desktop/src/main/installed-apps.test.ts new file mode 100644 index 00000000..4e2c63d5 --- /dev/null +++ b/apps/desktop/src/main/installed-apps.test.ts @@ -0,0 +1,145 @@ +import { afterEach, describe, expect, test, vi } from "vite-plus/test"; + +import { createInstalledApps } from "./installed-apps.ts"; +import type { HelperCommand } from "./protocol.ts"; + +type Listed = { bundleId: string; name: string; path: string }; + +const MAIL = { bundleId: "com.apple.mail", name: "Mail", path: "/System/Applications/Mail.app" }; +const SLACK = { + bundleId: "com.tinyspeck.slackmacgap", + name: "Slack", + path: "/Applications/Slack.app", +}; +const XCODE = { bundleId: "com.apple.dt.Xcode", name: "Xcode", path: "/Applications/Xcode.app" }; + +const png = (path: string) => `png-of-${path}`; +const dataUrl = (path: string) => `data:image/png;base64,${png(path)}`; + +function setup(options: { apps: Listed[]; answer?: boolean }) { + const sent: HelperCommand[] = []; + const state = { apps: options.apps, answer: options.answer ?? true }; + const installed = createInstalledApps({ + timeoutMs: 1000, + send: (command) => { + sent.push(command); + if (!state.answer) return; + queueMicrotask(() => { + if (command.type === "apps.list") { + installed.onHelperEvent({ type: "apps.listed", apps: state.apps }); + } else if (command.type === "icons.render") { + const icons = command.paths.map((path) => ({ path, png: png(path) })); + installed.onHelperEvent({ type: "icons.rendered", icons }); + } + }); + }, + }); + const renders = () => + sent.flatMap((command) => (command.type === "icons.render" ? [command.paths] : [])); + return { installed, sent, state, renders }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("installed apps", () => { + test("renders icons only for catalog apps", async () => { + const { installed, renders } = setup({ apps: [MAIL, XCODE, SLACK] }); + expect(await installed.list()).toEqual([ + { bundleId: "com.apple.mail", name: "Mail", icon: dataUrl(MAIL.path) }, + { bundleId: "com.apple.dt.xcode", name: "Xcode", icon: null }, + { bundleId: "com.tinyspeck.slackmacgap", name: "Slack", icon: dataUrl(SLACK.path) }, + ]); + expect(renders()).toEqual([[MAIL.path, SLACK.path]]); + }); + + test("serves icons it already has from memory", async () => { + const { installed, renders } = setup({ apps: [MAIL, SLACK] }); + const first = await installed.list(); + expect(await installed.list()).toEqual(first); + expect(renders()).toHaveLength(1); + }); + + test("renders only a moved or newly installed catalog app on the next list", async () => { + const { installed, state, renders } = setup({ apps: [MAIL, SLACK] }); + await installed.list(); + const movedSlack = { ...SLACK, path: "/Users/test/Applications/Slack.app" }; + const whatsapp = { + bundleId: "net.whatsapp.WhatsApp", + name: "WhatsApp", + path: "/Applications/WhatsApp.app", + }; + state.apps = [MAIL, movedSlack, whatsapp]; + expect(await installed.list()).toEqual([ + { bundleId: "com.apple.mail", name: "Mail", icon: dataUrl(MAIL.path) }, + { bundleId: "com.tinyspeck.slackmacgap", name: "Slack", icon: dataUrl(movedSlack.path) }, + { bundleId: "net.whatsapp.whatsapp", name: "WhatsApp", icon: dataUrl(whatsapp.path) }, + ]); + expect(renders()).toEqual([ + [MAIL.path, SLACK.path], + [movedSlack.path, whatsapp.path], + ]); + }); + + test("lowercases ids, keeps the first of a duplicate, and drops an invalid id", async () => { + const { installed } = setup({ + apps: [ + { + bundleId: "com.apple.MobileSMS", + name: "Messages", + path: "/System/Applications/Messages.app", + }, + { + bundleId: "COM.APPLE.MOBILESMS", + name: "Old Messages", + path: "/Applications/Messages.app", + }, + { bundleId: "com.apple/mail", name: "Bad", path: "/Applications/Bad.app" }, + ], + }); + expect(await installed.list()).toEqual([ + { + bundleId: "com.apple.mobilesms", + name: "Messages", + icon: dataUrl("/System/Applications/Messages.app"), + }, + ]); + }); + + test("asks the helper once while a list is in flight", async () => { + const { installed, sent } = setup({ apps: [XCODE] }); + const [a, b] = await Promise.all([installed.list(), installed.list()]); + expect(a).toBe(b); + expect(sent.filter((command) => command.type === "apps.list")).toHaveLength(1); + }); + + test("rejects when the helper never lists apps, and a later list starts fresh", async () => { + vi.useFakeTimers(); + const { installed, state } = setup({ apps: [MAIL], answer: false }); + const first = expect(installed.list()).rejects.toThrow(); + await vi.advanceTimersByTimeAsync(1000); + await first; + state.answer = true; + expect(await installed.list()).toEqual([ + { bundleId: "com.apple.mail", name: "Mail", icon: dataUrl(MAIL.path) }, + ]); + }); + + test("returns the list without icons when the helper never renders them", async () => { + vi.useFakeTimers(); + const sent: HelperCommand[] = []; + const installed = createInstalledApps({ + timeoutMs: 1000, + send: (command) => { + sent.push(command); + if (command.type === "apps.list") { + queueMicrotask(() => installed.onHelperEvent({ type: "apps.listed", apps: [MAIL] })); + } + }, + }); + const listed = installed.list(); + await vi.advanceTimersByTimeAsync(1000); + expect(await listed).toEqual([{ bundleId: "com.apple.mail", name: "Mail", icon: null }]); + }); +}); diff --git a/apps/desktop/src/main/installed-apps.ts b/apps/desktop/src/main/installed-apps.ts new file mode 100644 index 00000000..32f32070 --- /dev/null +++ b/apps/desktop/src/main/installed-apps.ts @@ -0,0 +1,87 @@ +import { APP_CATEGORIES, parseBundleId, type BundleId } from "../shared/app-categories.ts"; +import type { InstalledApp } from "../shared/api.ts"; +import type { HelperCommand, HelperEvent } from "./protocol.ts"; + +type Listed = Extract["apps"]; + +export type InstalledApps = { + list(): Promise; + onHelperEvent(event: HelperEvent): void; +}; + +export function createInstalledApps(options: { + send: (command: HelperCommand) => void; + timeoutMs?: number; +}): InstalledApps { + const { send, timeoutMs = 5000 } = options; + const iconsByPath = new Map(); + let onListed: ((apps: Listed) => void) | null = null; + let onRendered: (() => void) | null = null; + let inFlight: Promise | null = null; + + function replyBeforeDeadline( + wait: (resolve: (value: T) => void) => void, + command: HelperCommand, + ) { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(null), timeoutMs); + wait((value) => { + clearTimeout(timer); + resolve(value); + }); + send(command); + }); + } + + async function load(): Promise { + try { + const listed = await replyBeforeDeadline((resolve) => (onListed = resolve), { + type: "apps.list", + }); + if (listed === null) throw new Error("The helper did not list installed apps in time."); + const apps = new Map(); + for (const { bundleId: raw, name, path } of listed) { + const bundleId = parseBundleId(raw); + if (bundleId !== null && !apps.has(bundleId)) apps.set(bundleId, { name, path }); + } + const paths = [...apps] + .filter(([bundleId, { path }]) => APP_CATEGORIES.has(bundleId) && !iconsByPath.has(path)) + .map(([, { path }]) => path); + if (paths.length > 0) { + await replyBeforeDeadline((resolve) => (onRendered = resolve), { + type: "icons.render", + paths, + }); + } + return [...apps].map(([bundleId, { name, path }]) => ({ + bundleId, + name, + icon: iconsByPath.get(path) ?? null, + })); + } finally { + onListed = null; + onRendered = null; + } + } + + return { + list() { + inFlight ??= load().finally(() => { + inFlight = null; + }); + return inFlight; + }, + onHelperEvent(event) { + switch (event.type) { + case "apps.listed": + onListed?.(event.apps); + return; + case "icons.rendered": + for (const { path, png } of event.icons) + iconsByPath.set(path, `data:image/png;base64,${png}`); + onRendered?.(); + return; + } + }, + }; +} diff --git a/apps/desktop/src/main/protocol.test.ts b/apps/desktop/src/main/protocol.test.ts index 880e4593..9a9448c1 100644 --- a/apps/desktop/src/main/protocol.test.ts +++ b/apps/desktop/src/main/protocol.test.ts @@ -7,7 +7,7 @@ const line = (value: unknown) => JSON.stringify(value); describe("parseHelperEvent", () => { test("accepts every event variant with exactly the typed fields", () => { const events = [ - { type: "ready", version: 11 }, + { type: "ready", version: 12 }, { type: "hotkey", action: "down" }, { type: "hotkey", action: "up" }, { type: "hotkey", action: "chord" }, @@ -56,6 +56,11 @@ describe("parseHelperEvent", () => { { type: "permissions", microphone: "granted", accessibility: "denied" }, { type: "asr.status", state: "ready", message: null }, { type: "log", level: "info", message: "hello" }, + { + type: "apps.listed", + apps: [{ bundleId: "com.apple.mail", name: "Mail", path: "/System/Applications/Mail.app" }], + }, + { type: "icons.rendered", icons: [{ path: "/Applications/Slack.app", png: "iVBORw0KGgo=" }] }, ]; for (const event of events) expect(parseHelperEvent(line(event))).toEqual(event); }); @@ -196,6 +201,45 @@ describe("parseHelperEvent", () => { }); }); + test("keeps the rest of an app list when one entry is malformed", () => { + const mail = { + bundleId: "com.apple.mail", + name: "Mail", + path: "/System/Applications/Mail.app", + }; + const slack = { + bundleId: "com.tinyspeck.slackmacgap", + name: "Slack", + path: "/Applications/Slack.app", + }; + expect( + parseHelperEvent( + line({ + type: "apps.listed", + apps: [ + mail, + { bundleId: 7, name: "Seven", path: "/Applications/Seven.app" }, + { bundleId: "a.b", name: "B" }, + null, + slack, + ], + }), + ), + ).toEqual({ type: "apps.listed", apps: [mail, slack] }); + }); + + test("keeps the rest of the icons when one entry is malformed", () => { + const slack = { path: "/Applications/Slack.app", png: "iVBORw0KGgo=" }; + expect( + parseHelperEvent( + line({ + type: "icons.rendered", + icons: [{ path: "/Applications/Mail.app" }, slack, { path: 3, png: "x" }], + }), + ), + ).toEqual({ type: "icons.rendered", icons: [slack] }); + }); + test.each([ '{"type":"ready","version":1e400}', '{"type":"capture.started","id":"a","startMs":1e400}', @@ -215,6 +259,7 @@ describe("parseHelperEvent", () => { ["a wrong field type", line({ type: "transcript", id: "a", text: 5, audioMs: 1, asrMs: 1 })], ["an unknown enum value", line({ type: "hotkey", action: "sideways" })], ["a NaN number", '{"type":"capture.level","id":"a","level":NaN}'], + ["an app list that is not a list", line({ type: "apps.listed", apps: "Mail" })], [ "an unknown permission state", line({ type: "permissions", microphone: "maybe", accessibility: "granted" }), diff --git a/apps/desktop/src/main/protocol.ts b/apps/desktop/src/main/protocol.ts index a4a14f56..6a851d36 100644 --- a/apps/desktop/src/main/protocol.ts +++ b/apps/desktop/src/main/protocol.ts @@ -13,7 +13,7 @@ import type { DictationLanguage } from "../shared/dictation-language.ts"; import type { Target } from "../shared/style.ts"; // Bump together with the helper's `ready` version whenever a line's shape changes. -export const HELPER_PROTOCOL_VERSION = 11; +export const HELPER_PROTOCOL_VERSION = 12; export type HelperCommand = | { type: "hotkey.configure"; key: Hotkey; toggleKey: Hotkey | null } @@ -36,7 +36,9 @@ export type HelperCommand = | { type: "permissions.request"; kind: PermissionKind } | { type: "asr.prepare"; download: boolean } | { type: "asr.remove" } - | { type: "test.target"; target: Target | null }; + | { type: "test.target"; target: Target | null } + | { type: "apps.list" } + | { type: "icons.render"; paths: string[] }; const permissionState = Schema.Literals(["granted", "denied", "notDetermined"]); // The default covers a missing key and catchDecoding a malformed value; neither covers both. @@ -74,6 +76,15 @@ const TargetSchema = Schema.NullOr( ); export const decodeTarget = Schema.decodeUnknownOption(TargetSchema); const target = nullOnInvalid(TargetSchema); +const validEntries = (entry: S) => + Schema.Array( + Schema.NullOr(entry).pipe(Schema.catchDecoding(() => Effect.succeedSome(null))), + ).pipe( + Schema.decodeTo(Schema.Array(Schema.toType(entry)), { + decode: SchemaGetter.transform((entries) => entries.filter((e) => e !== null)), + encode: SchemaGetter.transform((entries) => entries), + }), + ); const level = Schema.Finite.pipe( Schema.decode({ decode: SchemaGetter.transform(clamp({ minimum: 0, maximum: 1 })), @@ -157,6 +168,16 @@ const HelperEventSchema = Schema.Union([ state: Schema.Literals(["missing", "downloading", "loading", "ready", "failed"]), message: statusMessage, }), + Schema.Struct({ + type: Schema.Literal("apps.listed"), + apps: validEntries( + Schema.Struct({ bundleId: Schema.String, name: Schema.String, path: Schema.String }), + ), + }), + Schema.Struct({ + type: Schema.Literal("icons.rendered"), + icons: validEntries(Schema.Struct({ path: Schema.String, png: Schema.String })), + }), Schema.Struct({ type: Schema.Literal("log"), level: Schema.Literals(["info", "error"]), diff --git a/apps/desktop/src/main/testing/fake-helper.ts b/apps/desktop/src/main/testing/fake-helper.ts index 360c9740..69e1bf3f 100755 --- a/apps/desktop/src/main/testing/fake-helper.ts +++ b/apps/desktop/src/main/testing/fake-helper.ts @@ -99,7 +99,7 @@ for (const { at, action } of config.script ?? []) { setTimeout(() => act(action), Math.max(0, startedAt + at - Date.now())); } -const ready = () => emit({ type: "ready", version: config.version ?? 11 }); +const ready = () => emit({ type: "ready", version: config.version ?? 12 }); if (config.control) { const path = config.control; diff --git a/apps/desktop/src/preload/hub.test.ts b/apps/desktop/src/preload/hub.test.ts index 8b6d7fa2..9ca6b83b 100644 --- a/apps/desktop/src/preload/hub.test.ts +++ b/apps/desktop/src/preload/hub.test.ts @@ -48,6 +48,7 @@ describe("hub preload", () => { "downloadUpdate", "getHistory", "getInsights", + "getInstalledApps", "getSnapshot", "installModel", "onHistory", diff --git a/apps/desktop/src/preload/hub.ts b/apps/desktop/src/preload/hub.ts index e5e29078..f7f054d8 100644 --- a/apps/desktop/src/preload/hub.ts +++ b/apps/desktop/src/preload/hub.ts @@ -58,6 +58,7 @@ const voice: HubApi = { getInsights: () => ipcRenderer.invoke(Channel.getInsights), onInsights: (listener) => subscribe(Channel.insights, listener), clearInsights: () => ipcRenderer.invoke(Channel.clearInsights), + getInstalledApps: () => ipcRenderer.invoke(Channel.getInstalledApps), }; contextBridge.exposeInMainWorld("voice", voice); diff --git a/apps/desktop/src/renderer/preview.tsx b/apps/desktop/src/renderer/preview.tsx index e07373e9..f24cb934 100644 --- a/apps/desktop/src/renderer/preview.tsx +++ b/apps/desktop/src/renderer/preview.tsx @@ -12,6 +12,7 @@ import { type PillApi, type UpdateStatus, } from "../shared/api.ts"; +import { parseBundleId } from "../shared/app-categories.ts"; import type { HistoryEntry, HistoryRetention, @@ -610,6 +611,23 @@ function fakeVoice( insights = EMPTY_INSIGHTS; for (const listener of insightsListeners) listener(insights); }, + getInstalledApps: async () => + ( + [ + ["com.apple.MobileSMS", "Messages"], + ["net.whatsapp.WhatsApp", "WhatsApp"], + ["ru.keepcoder.Telegram", "Telegram"], + ["org.whispersystems.signal-desktop", "Signal"], + ["com.hnc.Discord", "Discord"], + ["com.tencent.xinWeChat", "WeChat"], + ["com.tinyspeck.slackmacgap", "Slack"], + ["com.apple.mail", "Mail"], + ["com.apple.dt.Xcode", "Xcode"], + ] satisfies [string, string][] + ).flatMap(([id, name]) => { + const bundleId = parseBundleId(id); + return bundleId ? [{ bundleId, name, icon: null }] : []; + }), }; } diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.ts index 5e4eb3f0..8fd0f329 100644 --- a/apps/desktop/src/shared/api.ts +++ b/apps/desktop/src/shared/api.ts @@ -1,3 +1,4 @@ +import type { BundleId } from "./app-categories.ts"; import type { Microphone } from "./microphone.ts"; import type { DictationLanguage } from "./dictation-language.ts"; import type { ModelId } from "./models.ts"; @@ -230,6 +231,9 @@ export type PillApi = WindowApi & { onPillSnapshot(listener: (snapshot: PillSnapshot) => void): () => void; }; +/** An app found in the standard application folders. `icon` is a PNG data URL, for built-in catalog apps only. */ +export type InstalledApp = { bundleId: BundleId; name: string; icon: string | null }; + export type HubApi = WindowApi & { checkForUpdates(): Promise; downloadUpdate(): Promise; @@ -272,6 +276,8 @@ export type HubApi = WindowApi & { onInsights(listener: (insights: Insights) => void): () => void; /** Rejects with a message for the user when the file could not be removed. */ clearInsights(): Promise; + /** Rejects when the helper does not answer in time. */ + getInstalledApps(): Promise; }; export type VoiceApi = PillApi | HubApi; @@ -313,4 +319,5 @@ export const Channel = { getInsights: "voice:getInsights", insights: "voice:insights", clearInsights: "voice:clearInsights", + getInstalledApps: "voice:getInstalledApps", } as const; diff --git a/apps/desktop/src/shared/app-categories.test.ts b/apps/desktop/src/shared/app-categories.test.ts new file mode 100644 index 00000000..597c1b50 --- /dev/null +++ b/apps/desktop/src/shared/app-categories.test.ts @@ -0,0 +1,19 @@ +import { readFileSync } from "node:fs"; +import * as NodePath from "node:path"; + +import { expect, test } from "vite-plus/test"; + +import { BROWSER_BUNDLE_IDS, parseBundleId } from "./app-categories.ts"; + +const SWIFT = "native/voice-helper/Sources/VoiceHelper/TargetHost.swift"; + +test("the browser list matches the helper's", () => { + const source = readFileSync(NodePath.join(import.meta.dirname, "../../../..", SWIFT), "utf8"); + const literal = /browserBundleIds: Set = \[([^\]]*)\]/.exec(source)?.[1]; + expect(literal, `browserBundleIds not found in ${SWIFT}`).toBeDefined(); + const swift = [...(literal ?? "").matchAll(/"([^"]+)"/g)].map(([, id = ""]) => parseBundleId(id)); + expect( + new Set(swift), + `BROWSER_BUNDLE_IDS in apps/desktop/src/shared/app-categories.ts must equal browserBundleIds in ${SWIFT}`, + ).toEqual(BROWSER_BUNDLE_IDS); +}); diff --git a/apps/desktop/src/shared/app-categories.ts b/apps/desktop/src/shared/app-categories.ts index 108392d4..04078e10 100644 --- a/apps/desktop/src/shared/app-categories.ts +++ b/apps/desktop/src/shared/app-categories.ts @@ -152,3 +152,20 @@ export const APP_CATEGORIES: ReadonlyMap = new Map( export const SITE_CATEGORIES: ReadonlyMap = new Map( BUILT_IN_SITES.map(({ host, category }) => [host, category]), ); + +export const BROWSER_BUNDLE_IDS: ReadonlySet = new Set( + [ + "com.apple.Safari", + "com.apple.SafariTechnologyPreview", + "com.google.Chrome", + "com.google.Chrome.canary", + "org.chromium.Chromium", + "net.imput.helium", + "company.thebrowser.Browser", + "com.brave.Browser", + "com.microsoft.edgemac", + "org.mozilla.firefox", + "com.operasoftware.Opera", + "com.vivaldi.Vivaldi", + ].map((key) => parsed(parseBundleId, key)), +); diff --git a/native/voice-helper/Sources/VoiceHelper/InstalledApps.swift b/native/voice-helper/Sources/VoiceHelper/InstalledApps.swift new file mode 100644 index 00000000..29f6d74a --- /dev/null +++ b/native/voice-helper/Sources/VoiceHelper/InstalledApps.swift @@ -0,0 +1,77 @@ +import AppKit +import Foundation +import VoiceHelperCore + +final class InstalledApps { + private let output: Output + private let queue = DispatchQueue(label: "voice.installed-apps", qos: .utility) + + init(output: Output) { + self.output = output + } + + func list() { + queue.async { [output] in + output.emit(.appsListed(apps: scanInstalledApps())) + } + } + + func renderIcons(paths: [String]) { + queue.async { [output] in + let icons = paths.compactMap { path in + autoreleasepool { renderIcon(path: path).map { RenderedIcon(path: path, png: $0) } } + } + output.emit(.iconsRendered(icons: icons)) + } + } +} + +private func scanInstalledApps() -> [InstalledApp] { + let roots = ["/Applications", "/System/Applications", FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications").path] + return roots.flatMap { root in + sortedEntries(root).flatMap { path -> [String] in + if path.hasSuffix(".app") { return [path] } + return isDirectory(path) ? sortedEntries(path).filter { $0.hasSuffix(".app") } : [] + } + .compactMap(readInstalledApp) + } +} + +private func sortedEntries(_ directory: String) -> [String] { + let names = (try? FileManager.default.contentsOfDirectory(atPath: directory)) ?? [] + return names.filter { !$0.hasPrefix(".") }.sorted().map { (directory as NSString).appendingPathComponent($0) } +} + +private func isDirectory(_ path: String) -> Bool { + var directory: ObjCBool = false + return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue +} + +// Bundle(url:) caches each bundle for the life of the process, so an app updated or replaced +// after launch would keep its old name; reading the plist directly stays fresh. +private func readInstalledApp(path: String) -> InstalledApp? { + let plist = URL(fileURLWithPath: path).appendingPathComponent("Contents/Info.plist") + guard let data = try? Data(contentsOf: plist), + let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { + return nil + } + return installedApp(info: info, path: path) +} + +private let iconPixels = 64 + +private func renderIcon(path: String) -> Data? { + guard FileManager.default.fileExists(atPath: path), + let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: iconPixels, pixelsHigh: iconPixels, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0), + let context = NSGraphicsContext(bitmapImageRep: rep) else { + return nil + } + let icon = NSWorkspace.shared.icon(forFile: path) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = context + icon.draw(in: NSRect(x: 0, y: 0, width: iconPixels, height: iconPixels)) + NSGraphicsContext.restoreGraphicsState() + return rep.representation(using: .png, properties: [:]) +} diff --git a/native/voice-helper/Sources/VoiceHelper/main.swift b/native/voice-helper/Sources/VoiceHelper/main.swift index 601acc7b..c7ad6ba2 100644 --- a/native/voice-helper/Sources/VoiceHelper/main.swift +++ b/native/voice-helper/Sources/VoiceHelper/main.swift @@ -12,6 +12,7 @@ final class Helper { private let insertion: Insertion private let hotkeyTap: HotkeyTap private let permissions: Permissions + private let installedApps: InstalledApps private var testTarget: TranscriptTarget? @MainActor @@ -33,6 +34,7 @@ final class Helper { let hotkeyTap = HotkeyTap(output: output) { capture.isActive } self.hotkeyTap = hotkeyTap permissions = Permissions(output: output) { hotkeyTap.install() } + installedApps = InstalledApps(output: output) } func installHotkeyTap() { @@ -91,6 +93,10 @@ final class Helper { case .testTarget(let target): guard testMode else { return output.log(.error, "test hooks disabled") } testTarget = target + case .appsList: + installedApps.list() + case .iconsRender(let paths): + installedApps.renderIcons(paths: paths) } } @@ -116,7 +122,7 @@ guard let modelsDir = directoryArgument("--models-dir"), let stateDir = director // A vanished parent must end the helper via stdin EOF, not a SIGPIPE mid-write. signal(SIGPIPE, SIG_IGN) let output = Output() -output.emit(.ready(version: 11)) +output.emit(.ready(version: 12)) let helper = MainActor.assumeIsolated { Helper(output: output, modelsDir: modelsDir, stateDir: stateDir, environment: ProcessInfo.processInfo.environment) diff --git a/native/voice-helper/Sources/VoiceHelperCore/InstalledApp.swift b/native/voice-helper/Sources/VoiceHelperCore/InstalledApp.swift new file mode 100644 index 00000000..d9921432 --- /dev/null +++ b/native/voice-helper/Sources/VoiceHelperCore/InstalledApp.swift @@ -0,0 +1,43 @@ +import Foundation + +public struct InstalledApp: Equatable, Sendable { + public let bundleId: String + public let name: String + public let path: String + + public init(bundleId: String, name: String, path: String) { + self.bundleId = bundleId + self.name = name + self.path = path + } +} + +public struct RenderedIcon: Equatable, Sendable { + public let path: String + public let png: Data + + public init(path: String, png: Data) { + self.path = path + self.png = png + } +} + +public func installedApp(info: [String: Any], path: String) -> InstalledApp? { + guard let bundleId = nonBlank(info["CFBundleIdentifier"]) else { return nil } + let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension + guard let name = nonBlank(info["CFBundleDisplayName"]) ?? nonBlank(info["CFBundleName"]) ?? nonBlank(fileName) else { + return nil + } + return InstalledApp(bundleId: bundleId, name: name, path: path) +} + +// Some bundles pad their names with invisible format characters; WhatsApp's display name +// starts with a left-to-right mark (U+200E). +private let padding = CharacterSet.whitespacesAndNewlines.union(.controlCharacters) + +private func nonBlank(_ value: Any?) -> String? { + guard let trimmed = (value as? String)?.trimmingCharacters(in: padding), !trimmed.isEmpty else { + return nil + } + return trimmed +} diff --git a/native/voice-helper/Sources/VoiceHelperCore/Protocol.swift b/native/voice-helper/Sources/VoiceHelperCore/Protocol.swift index 012b73e3..64fe7e5c 100644 --- a/native/voice-helper/Sources/VoiceHelperCore/Protocol.swift +++ b/native/voice-helper/Sources/VoiceHelperCore/Protocol.swift @@ -55,6 +55,8 @@ public enum HelperCommand: Equatable, Sendable { case testAudioFile(path: String?) /// The next capture reports this target instead of the frontmost app; nil clears a pending one. case testTarget(TranscriptTarget?) + case appsList + case iconsRender(paths: [String]) } /// What the user was dictating into: the frontmost app and, for a browser page, the page host. @@ -90,6 +92,8 @@ public enum HelperEvent: Equatable, Sendable { case permissions(microphone: PermissionState, accessibility: PermissionState) case asrStatus(state: AsrState, message: String?) case log(level: LogLevel, message: String) + case appsListed(apps: [InstalledApp]) + case iconsRendered(icons: [RenderedIcon]) } public struct ProtocolError: Error, Equatable, CustomStringConvertible, Sendable { @@ -101,6 +105,7 @@ private enum Key: String, CodingKey { case type, key, id, text, kind, download, path, action, muteWhileDictating, language case version, startMs, level, reason, message, audioMs, asrMs, speechMs, method, html case microphone, accessibility, state, devices, defaultUid, toggleKey, target, bundleId, host, detectHost + case paths, apps, name, icons, png } extension HelperCommand: Decodable { @@ -136,6 +141,8 @@ extension HelperCommand: Decodable { case "asr.remove": self = .asrRemove case "test.audioFile": self = .testAudioFile(path: try c.decodeIfPresent(String.self, forKey: .path)) case "test.target": self = .testTarget(try c.decode(TranscriptTarget?.self, forKey: .target)) + case "apps.list": self = .appsList + case "icons.render": self = .iconsRender(paths: try c.decode([String].self, forKey: .paths)) default: throw DecodingError.dataCorruptedError(forKey: .type, in: c, debugDescription: "unknown command type \"\(type)\"") } @@ -248,6 +255,12 @@ extension HelperEvent: Encodable { try c.encode("log", forKey: .type) try c.encode(level, forKey: .level) try c.encode(message, forKey: .message) + case .appsListed(let apps): + try c.encode("apps.listed", forKey: .type) + try c.encode(apps, forKey: .apps) + case .iconsRendered(let icons): + try c.encode("icons.rendered", forKey: .type) + try c.encode(icons, forKey: .icons) } } @@ -276,6 +289,23 @@ extension TranscriptTarget: Codable { } } +extension InstalledApp: Encodable { + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: Key.self) + try c.encode(bundleId, forKey: .bundleId) + try c.encode(name, forKey: .name) + try c.encode(path, forKey: .path) + } +} + +extension RenderedIcon: Encodable { + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: Key.self) + try c.encode(path, forKey: .path) + try c.encode(png.base64EncodedString(), forKey: .png) + } +} + // JSONEncoder refuses NaN and infinity; a bad audio buffer must not break the stream. private func finite(_ value: Double) -> Double { value.isFinite ? value : 0 diff --git a/native/voice-helper/Tests/VoiceHelperCoreTests/InstalledAppTests.swift b/native/voice-helper/Tests/VoiceHelperCoreTests/InstalledAppTests.swift new file mode 100644 index 00000000..a688a9b3 --- /dev/null +++ b/native/voice-helper/Tests/VoiceHelperCoreTests/InstalledAppTests.swift @@ -0,0 +1,45 @@ +import Testing +@testable import VoiceHelperCore + +@Suite struct InstalledAppTests { + private let path = "/Applications/Slack.app" + + @Test func usesTheDisplayNameWhenPresent() { + let info: [String: Any] = ["CFBundleIdentifier": "com.tinyspeck.slackmacgap", "CFBundleDisplayName": " Slack ", "CFBundleName": "SlackName"] + #expect(installedApp(info: info, path: path) == InstalledApp(bundleId: "com.tinyspeck.slackmacgap", name: "Slack", path: path)) + } + + @Test func stripsInvisibleFormatCharactersFromTheName() { + let info: [String: Any] = ["CFBundleIdentifier": "net.whatsapp.WhatsApp", "CFBundleDisplayName": "\u{200E}WhatsApp", "CFBundleName": "WhatsApp"] + #expect(installedApp(info: info, path: "/Applications/WhatsApp.app")?.name == "WhatsApp") + } + + @Test func fallsBackToTheBundleName() { + let info: [String: Any] = ["CFBundleIdentifier": "com.tinyspeck.slackmacgap", "CFBundleName": "SlackName"] + #expect(installedApp(info: info, path: path)?.name == "SlackName") + } + + @Test func skipsABlankOrNonStringDisplayName() { + for displayName: Any in [" ", "", "\n", "\u{200E}", 42] { + let info: [String: Any] = ["CFBundleIdentifier": "com.tinyspeck.slackmacgap", "CFBundleDisplayName": displayName, "CFBundleName": "SlackName"] + #expect(installedApp(info: info, path: path)?.name == "SlackName") + } + } + + @Test func fallsBackToTheFileNameWithoutTheAppExtension() { + let info: [String: Any] = ["CFBundleIdentifier": "com.microsoft.teams2", "CFBundleDisplayName": "", "CFBundleName": " "] + #expect(installedApp(info: info, path: "/Applications/Microsoft Teams.app")?.name == "Microsoft Teams") + } + + @Test func keepsTheBundleIdCase() { + let info: [String: Any] = ["CFBundleIdentifier": "net.WhatsApp.WhatsApp", "CFBundleName": "WhatsApp"] + #expect(installedApp(info: info, path: "/Applications/WhatsApp.app")?.bundleId == "net.WhatsApp.WhatsApp") + } + + @Test func skipsABundleWithoutAUsableId() { + #expect(installedApp(info: ["CFBundleName": "Slack"], path: path) == nil) + for bundleId: Any in ["", " ", 7] { + #expect(installedApp(info: ["CFBundleIdentifier": bundleId, "CFBundleName": "Slack"], path: path) == nil) + } + } +} diff --git a/native/voice-helper/Tests/VoiceHelperCoreTests/ProtocolTests.swift b/native/voice-helper/Tests/VoiceHelperCoreTests/ProtocolTests.swift index cdf3c2c5..7405939b 100644 --- a/native/voice-helper/Tests/VoiceHelperCoreTests/ProtocolTests.swift +++ b/native/voice-helper/Tests/VoiceHelperCoreTests/ProtocolTests.swift @@ -36,6 +36,10 @@ private func json(_ line: String) throws -> [String: Any] { (#"{"type":"test.target","target":{"bundleId":"com.apple.TextEdit","host":null}}"#, .testTarget(TranscriptTarget(bundleId: "com.apple.TextEdit", host: nil))), (#"{"type":"test.target","target":null}"#, .testTarget(nil)), + (#"{"type":"apps.list"}"#, .appsList), + (#"{"type":"icons.render","paths":["/Applications/Slack.app","/System/Applications/Mail.app"]}"#, + .iconsRender(paths: ["/Applications/Slack.app", "/System/Applications/Mail.app"])), + (#"{"type":"icons.render","paths":[]}"#, .iconsRender(paths: [])), ] for (line, expected) in cases { #expect(HelperCommand.decode(line: line) == .success(expected), Comment(rawValue: line)) @@ -64,6 +68,8 @@ private func json(_ line: String) throws -> [String: Any] { let appless = HelperCommand.decode(line: #"{"type":"test.target","target":{"bundleId":null,"host":null}}"#) #expect(try unknownDescription(appless).contains("field \"bundleId\" has the wrong type")) + let pathless = HelperCommand.decode(line: #"{"type":"icons.render"}"#) + #expect(try unknownDescription(pathless).contains("missing field \"paths\"")) } private func unknownDescription(_ result: Result) throws -> String { @@ -75,7 +81,7 @@ private func unknownDescription(_ result: Result) @Test func encodesEveryEventWithContractTypeStrings() throws { let cases: [(HelperEvent, [String: Any])] = [ - (.ready(version: 11), ["type": "ready", "version": 11]), + (.ready(version: 12), ["type": "ready", "version": 12]), (.hotkey(action: .down), ["type": "hotkey", "action": "down"]), (.hotkey(action: .chord), ["type": "hotkey", "action": "chord"]), (.hotkey(action: .cancel), ["type": "hotkey", "action": "cancel"]), @@ -113,6 +119,12 @@ private func unknownDescription(_ result: Result) ["type": "permissions", "microphone": "granted", "accessibility": "notDetermined"]), (.asrStatus(state: .failed, message: "boom"), ["type": "asr.status", "state": "failed", "message": "boom"]), (.log(level: .error, message: "bad"), ["type": "log", "level": "error", "message": "bad"]), + (.appsListed(apps: [InstalledApp(bundleId: "com.tinyspeck.slackmacgap", name: "Slack", path: "/Applications/Slack.app")]), + ["type": "apps.listed", "apps": [["bundleId": "com.tinyspeck.slackmacgap", "name": "Slack", "path": "/Applications/Slack.app"]]]), + (.appsListed(apps: []), ["type": "apps.listed", "apps": [Any]()]), + (.iconsRendered(icons: [RenderedIcon(path: "/Applications/Slack.app", png: Data([0x89, 0x50, 0x4E, 0x47, 0xFF]))]), + ["type": "icons.rendered", "icons": [["path": "/Applications/Slack.app", "png": "iVBOR/8="]]]), + (.iconsRendered(icons: []), ["type": "icons.rendered", "icons": [Any]()]), ] for (event, expected) in cases { let line = event.encodeLine() diff --git a/native/voice-helper/scripts/helper.mjs b/native/voice-helper/scripts/helper.mjs index 9c0a7a65..c95dc5b1 100644 --- a/native/voice-helper/scripts/helper.mjs +++ b/native/voice-helper/scripts/helper.mjs @@ -158,7 +158,7 @@ export async function withHelper(options, body) { const helper = new Helper(options); try { const ready = await helper.waitForType("ready"); - assert(ready.version === 11, `ready.version is ${ready.version}`); + assert(ready.version === 12, `ready.version is ${ready.version}`); return await body(helper); } finally { await helper.close(); From 427c55b1bc2329b1352b0ef46871d9083c74104a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Hadry=C5=9B?= Date: Fri, 16 Oct 2026 05:40:11 +0200 Subject: [PATCH 02/12] feat(desktop): show the installed apps each style applies to Each Style tab described its category in a fixed caption that named example apps whether or not they were installed. Each tab now reads "This style applies in personal messengers" (workplace messengers, all major email apps, all other apps) followed by the icons of the matching installed apps, in catalog order. Up to four show, and "+N" names the rest in its tooltip and accessible label. An app without an icon, or whose icon fails to load, shows its first letter. The list is fetched once each time the page opens, and a failure shows no icons. --- apps/desktop/src/renderer/Style.tsx | 131 +++++++++++++++--- apps/desktop/src/renderer/styleView.test.ts | 80 +++++++++++ apps/desktop/src/renderer/styleView.ts | 21 +++ apps/desktop/src/renderer/useInstalledApps.ts | 21 +++ 4 files changed, 237 insertions(+), 16 deletions(-) create mode 100644 apps/desktop/src/renderer/styleView.test.ts create mode 100644 apps/desktop/src/renderer/styleView.ts create mode 100644 apps/desktop/src/renderer/useInstalledApps.ts diff --git a/apps/desktop/src/renderer/Style.tsx b/apps/desktop/src/renderer/Style.tsx index eb9cf728..1f4e53b4 100644 --- a/apps/desktop/src/renderer/Style.tsx +++ b/apps/desktop/src/renderer/Style.tsx @@ -1,19 +1,23 @@ import { Radio } from "@base-ui/react/radio"; import { RadioGroup } from "@base-ui/react/radio-group"; import { Tabs } from "@base-ui/react/tabs"; +import { Tooltip } from "@base-ui/react/tooltip"; import * as stylex from "@stylexjs/stylex"; import { CheckIcon } from "lucide-react"; import { useId, useState } from "react"; import { finishText, type WritingStyle } from "@voice/cleanup/style"; -import type { Settings as SettingsValue, SettingsPatch } from "../shared/api.ts"; +import type { InstalledApp, Settings as SettingsValue, SettingsPatch } from "../shared/api.ts"; import { CATEGORIES, type Category } from "../shared/app-categories.ts"; import { supportsCleanup, wantsCleanup } from "../shared/dictation-language.ts"; import { pageStyles } from "./pageStyles.ts"; +import { bannerApps, type BannerApp } from "./styleView.ts"; import { Switch } from "./Switch.tsx"; import { color, font, radius, space } from "./tokens.stylex.ts"; +import { tooltipPopupClass, tooltipPositionerClass } from "./tooltip.ts"; import { useAction } from "./useAction.ts"; +import { useInstalledApps } from "./useInstalledApps.ts"; import { hubApi } from "./voice.ts"; const SEMI_FORMAL_EXAMPLES: Record = { @@ -23,20 +27,11 @@ const SEMI_FORMAL_EXAMPLES: Record = { other: "The quarterly numbers look good, and churn is down.", }; -const CATEGORY_TABS: Record = { - personal: { - label: "Personal messages", - caption: "Used in personal messengers like Messages and WhatsApp.", - }, - work: { label: "Work messages", caption: "Used in workplace messengers like Slack and Teams." }, - email: { - label: "Email", - caption: "Used in email apps like Mail and Outlook, and in webmail like Gmail.", - }, - other: { - label: "Other", - caption: "Used everywhere else, including editors, terminals, and notes.", - }, +const CATEGORY_TABS: Record = { + personal: { label: "Personal messages", appliesIn: "personal messengers" }, + work: { label: "Work messages", appliesIn: "workplace messengers" }, + email: { label: "Email", appliesIn: "all major email apps" }, + other: { label: "Other", appliesIn: "all other apps" }, }; const writingStyles: { value: WritingStyle; label: string; rule: string }[] = [ @@ -99,6 +94,30 @@ const styles = stylex.create({ outline: { default: "none", ":focus-visible": `2px solid ${color["--ring"]}` }, outlineOffset: 3, }, + banner: { + display: "flex", + flexWrap: "wrap", + alignItems: "center", + columnGap: space.sm, + rowGap: 4, + minHeight: 24, + }, + apps: { display: "flex", alignItems: "center", gap: 4 }, + appCell: { display: "grid", placeItems: "center", width: 24, height: 24 }, + appImage: { display: "block", width: 24, height: 24 }, + // macOS icons leave a margin inside their canvas, so a letter tile is drawn smaller to match. + monogram: { + display: "grid", + placeItems: "center", + width: 20, + height: 20, + borderRadius: 5, + backgroundColor: color.segmentTrack, + color: color.mutedForeground, + fontSize: 11, + fontWeight: 600, + }, + more: { paddingInline: 2, color: color.mutedForeground, fontSize: 12, fontWeight: 500 }, title: { display: "block", fontWeight: 500 }, detail: { margin: 0, color: color.mutedForeground, fontSize: 12.5 }, fieldset: { minWidth: 0, margin: 0, padding: 0, borderWidth: 0 }, @@ -173,6 +192,7 @@ export function Style({ settings }: { settings: SettingsValue }) { const cleanupSupported = supportsCleanup(settings.dictationLanguage); const cleanupEnabled = wantsCleanup(settings); const [category, setCategory] = useState("personal"); + const installed = useInstalledApps(); const changeCleanup = (cleanup: NonNullable) => run(() => hubApi().updateSettings({ cleanup }), "Could not save your style settings."); @@ -222,7 +242,7 @@ export function Style({ settings }: { settings: SettingsValue }) { {CATEGORIES.map((value) => ( -

{CATEGORY_TABS[value].caption}

+