From 499919ddd8998da63777cad1c153dbfdae7b55bb Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 03:21:26 +0200 Subject: [PATCH 01/24] Add GitHub activity feed for My Scope --- server/src/providers/github.ts | 72 ++++++++++++++++++++++++++++++- server/test/github.test.ts | 78 +++++++++++++++++++++++++++++++++- 2 files changed, 146 insertions(+), 4 deletions(-) diff --git a/server/src/providers/github.ts b/server/src/providers/github.ts index ef5e3279..3cd15fce 100644 --- a/server/src/providers/github.ts +++ b/server/src/providers/github.ts @@ -21,6 +21,10 @@ import { tr } from '../i18n.js' * minute is well inside it. * - `GET /repos/{owner}/{repo}/actions/runs?per_page=10` — workflow runs, one call per repo * named in the connection's `repos` field, capped at ten repos. + * - `GET /users/{login}/events?per_page=100` — the authenticated user's recent activity, used + * to order My Scope by what Livio did rather than by what somebody else changed. GitHub's + * event feed can lag and only covers a bounded recent window; it is the closest supported + * account-wide signal, not a real-time audit log. * * Every GET goes through a conditional request: the ETag of the previous answer is sent back as * `If-None-Match`, and a `304 Not Modified` replays the cached body. GitHub does not charge a 304 @@ -95,6 +99,11 @@ export interface GhRun { url: string } +export interface GhRepoActivity { + repo: string + updatedAt: number +} + /** * Why one source of the snapshot has no fresh rows. * @@ -111,6 +120,7 @@ export type GhSectionError = 'unauthorized' | 'forbidden' | 'fine-grained-token' /** One entry per source of the snapshot; a missing key means that source is fresh. */ export interface GhSectionErrors { + activity?: GhSectionError notifications?: GhSectionError reviews?: GhSectionError myPrs?: GhSectionError @@ -130,6 +140,7 @@ export interface GhSectionErrors { * at all, therefore still shows its reviews, its pull requests and its workflow runs. */ export interface GhSnapshot { + repoActivity: GhRepoActivity[] notifications: GhNotification[] reviewRequests: GhPull[] myPrs: GhPull[] @@ -147,6 +158,11 @@ export const isFineGrainedToken = (token: string | undefined): boolean => (token ?? '').startsWith(FINE_GRAINED_PREFIX) const OWNER_REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/ +const USER_ACTIVITY_TYPES = new Set([ + 'CommitCommentEvent', 'CreateEvent', 'DeleteEvent', 'DiscussionEvent', 'ForkEvent', + 'IssueCommentEvent', 'IssuesEvent', 'PullRequestEvent', 'PullRequestReviewEvent', + 'PullRequestReviewCommentEvent', 'PushEvent', 'ReleaseEvent', +]) /** * `https://api.github.com/` → `https://api.github.com`, empty → the github.com root. @@ -275,6 +291,24 @@ export function normalizePulls(json: unknown): GhPull[] { return out } +/** `GET /users/{login}/events` → only the authenticated user's contribution-like repo touches. */ +export function normalizeUserRepoActivity(json: unknown, login: string): GhRepoActivity[] { + if (!Array.isArray(json) || !login) return [] + const latest = new Map() + for (const raw of json as Record[]) { + const repo = String(raw?.repo?.name ?? '') + const actor = String(raw?.actor?.login ?? '') + const updatedAt = epoch(raw?.created_at) + if (!OWNER_REPO_RE.test(repo) || repo.split('/').some(part => part === '.' || part === '..') + || actor.toLowerCase() !== login.toLowerCase()) continue + if (!USER_ACTIVITY_TYPES.has(String(raw?.type)) || updatedAt === undefined) continue + const key = repo.toLowerCase() + const previous = latest.get(key) + if (!previous || updatedAt > previous.updatedAt) latest.set(key, { repo, updatedAt }) + } + return [...latest.values()].sort((a, b) => b.updatedAt - a.updatedAt) +} + function runStatus(status: unknown): GhRunStatus { switch (status) { case 'completed': return 'completed' @@ -360,6 +394,11 @@ const OpenRowPayload = z.object({ id: z.string().regex(/^\d{1,20}$/), }) +// A widget can ask to open a repository name, but it cannot supply a destination URL. +const OpenRepoPayload = z.strictObject({ + repo: z.string().regex(OWNER_REPO_RE), +}) + export interface GithubDeps { openRunner?: (cmd: string, args: string[]) => Promise fetchFn?: typeof fetch @@ -391,7 +430,7 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu /** While `now()` is below this the provider does not call at all: the quota is spent. */ let quietUntil = 0 let rateLimit: GhSnapshot['rateLimit'] - let last: GhSnapshot = { notifications: [], reviewRequests: [], myPrs: [], runs: [] } + let last: GhSnapshot = { repoActivity: [], notifications: [], reviewRequests: [], myPrs: [], runs: [] } /** * Set once a fine-grained token has been refused by `/notifications`. The endpoint only answers * a classic token, so asking again every minute would spend a request on a certain 403 forever. @@ -559,7 +598,9 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu } } - const [reviewRequests, myPrs] = await Promise.all([ + const [repoActivity, reviewRequests, myPrs] = await Promise.all([ + section('activity', last.repoActivity, async () => + normalizeUserRepoActivity(await get(`${base}/users/${encodeURIComponent(me)}/events?per_page=100`), me)), section('reviews', last.reviewRequests, async () => normalizePulls(await get(searchUrl(`is:pr is:open archived:false review-requested:${me}`)))), section('myPrs', last.myPrs, async () => @@ -591,6 +632,7 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu } last = { + repoActivity, notifications, reviewRequests, myPrs, @@ -625,6 +667,32 @@ export function createGithubProvider(ctx: ConnectionProviderContext, deps: Githu try { await openRunner('/usr/bin/open', [url.href]); return { ok: true } } catch { return { ok: false } } }, + /** Opens a repository shown in this connection's current activity snapshot. */ + openRepo: async (payload, context) => { + if (!context?.loopback) return { ok: false, error: tr(undefined, 'provider.localOnly') } + const parsed = OpenRepoPayload.safeParse(payload) + if (!parsed.success) throw new Error(tr(undefined, 'github.invalidCommand')) + const { repo } = parsed.data + const visibleRepos = [ + ...last.repoActivity.map(item => item.repo), + ...last.notifications.map(row => row.repo), + ...last.reviewRequests.map(row => row.repo), + ...last.myPrs.map(row => row.repo), + ] + if (!base || !visibleRepos.includes(repo)) return { ok: false } + + let host: string + try { + const configured = new URL(base) + // Do not turn an API URL with an unusual port into a different web origin. + if (configured.port) return { ok: false } + host = base === GITHUB_DEFAULT_HOST ? 'github.com' : configured.hostname + if (!host || configured.username || configured.password) return { ok: false } + } catch { return { ok: false } } + + try { await openRunner('/usr/bin/open', [`https://${host}/${repo}`]); return { ok: true } } + catch { return { ok: false } } + }, /** Marks one notification thread read — what a tap on an inbox row asks for. */ markRead: async (payload) => { const parsed = MarkReadPayload.safeParse(payload) diff --git a/server/test/github.test.ts b/server/test/github.test.ts index facbfb65..5565c69f 100644 --- a/server/test/github.test.ts +++ b/server/test/github.test.ts @@ -162,6 +162,7 @@ function responder(options: { if (url.includes('/user/repos')) return [] if (url.endsWith('/user')) return { login: 'example-user' } if (url.includes('/notifications')) return NOTIFICATIONS + if (url.includes('/users/') && url.includes('/events')) return [] if (url.includes('review-requested')) return REVIEWS if (url.includes('/search/issues')) return MINE if (url.includes('/actions/runs')) return RUNS @@ -190,6 +191,30 @@ const context = (fields: Record = {}) => ({ }) describe('createGithubProvider', () => { + it('orders repositories from the authenticated account activity endpoint', async () => { + const calls: string[] = [] + const fetchFn = (async (url: string) => { + const target = String(url) + calls.push(target) + if (target.endsWith('/user')) return new Response(JSON.stringify({ login: 'example-user' })) + if (target.includes('/users/example-user/events')) return new Response(JSON.stringify([ + { type: 'PushEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/active' }, created_at: '2026-10-19T02:00:00Z' }, + { type: 'PullRequestReviewEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/reviewed' }, created_at: '2026-10-19T01:00:00Z' }, + { type: 'PushEvent', actor: { login: 'someone-else' }, repo: { name: 'example-org/other' }, created_at: '2026-10-19T03:00:00Z' }, + { type: 'WatchEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/watched' }, created_at: '2026-10-19T04:00:00Z' }, + { type: 'IssuesEvent', actor: { login: 'example-user' }, repo: { name: '../unsafe' }, created_at: '2026-10-19T05:00:00Z' }, + ])) + return new Response('[]') + }) as unknown as typeof fetch + const snapshot = await createGithubProvider(context({ repos: '' }), { fetchFn, now: () => 0 }).poll!() as GhSnapshot + + expect(calls).toContain('https://api.github.com/users/example-user/events?per_page=100') + expect(snapshot.repoActivity).toEqual([ + { repo: 'example-org/active', updatedAt: Date.parse('2026-10-19T02:00:00Z') }, + { repo: 'example-org/reviewed', updatedAt: Date.parse('2026-10-19T01:00:00Z') }, + ]) + }) + it('reads the login, the inbox, both searches and one run list per repo', async () => { const { calls, fetchFn } = responder() const provider = createGithubProvider(context(), { fetchFn, now: () => 1_000_000 }) @@ -199,6 +224,7 @@ describe('createGithubProvider', () => { expect(calls.map((c) => c.url)).toEqual([ 'https://api.github.com/user', 'https://api.github.com/notifications?all=false&per_page=50', + 'https://api.github.com/users/example-user/events?per_page=100', 'https://api.github.com/search/issues?q=is%3Apr%20is%3Aopen%20archived%3Afalse%20review-requested%3Aexample-user&per_page=25&sort=updated&order=desc&advanced_search=true', 'https://api.github.com/search/issues?q=is%3Apr%20is%3Aopen%20archived%3Afalse%20author%3Aexample-user&per_page=25&sort=updated&order=desc&advanced_search=true', 'https://api.github.com/repos/example-org/example-repo/actions/runs?per_page=10', @@ -230,7 +256,7 @@ describe('createGithubProvider', () => { const { calls, fetchFn } = responder() const ctx = { ...context(), secrets: {} } expect(await createGithubProvider(ctx, { fetchFn, now: () => 0 }).poll!()) - .toEqual({ notifications: [], reviewRequests: [], myPrs: [], runs: [], error: 'unconfigured' }) + .toEqual({ repoActivity: [], notifications: [], reviewRequests: [], myPrs: [], runs: [], error: 'unconfigured' }) expect(calls).toHaveLength(0) }) @@ -335,7 +361,7 @@ describe('createGithubProvider', () => { const second = (await provider.poll!()) as GhSnapshot expect(second.error).toBe('offline') expect(second.errors) - .toEqual({ notifications: 'offline', reviews: 'offline', myPrs: 'offline', runs: 'offline' }) + .toEqual({ notifications: 'offline', activity: 'offline', reviews: 'offline', myPrs: 'offline', runs: 'offline' }) // Every section keeps the rows it last had. expect(second.notifications.map((n) => n.id)).toEqual(first.notifications.map((n) => n.id)) expect(second.runs).toHaveLength(3) @@ -570,4 +596,52 @@ describe('opening GitHub rows', () => { expect(await provider.commands!.open({ kind: 'run', id: snapshot.runs[0].id, url: 'https://evil.test', futureHostField: true }, { loopback: true, paired: false })).toEqual({ ok: true }) expect(opened).toEqual([['/usr/bin/open', snapshot.runs[0].url]]) }) + + it('opens only a repository already present in this connection snapshot', async () => { + const { fetchFn, calls } = responder() + const opened: string[][] = [] + const provider = createGithubProvider(context(), { fetchFn, openRunner: async (cmd, args) => { opened.push([cmd, ...args]) } }) + const snapshot = await provider.poll!() as GhSnapshot + const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise } + + expect(await commands.openRepo({ repo: snapshot.reviewRequests[0].repo }, { loopback: true })).toEqual({ ok: true }) + expect(opened).toEqual([['/usr/bin/open', `https://github.com/${snapshot.reviewRequests[0].repo}`]]) + expect(calls.every((call) => call.method === 'GET')).toBe(true) + }) + + it('opens a repository that is present only in the authenticated activity snapshot', async () => { + const opened: string[][] = [] + const provider = createGithubProvider(context({ repos: '' }), { + fetchFn: (async (url: string) => { + if (url.endsWith('/user')) return new Response(JSON.stringify({ login: 'example-user' })) + if (url.includes('/users/example-user/events')) return new Response(JSON.stringify([ + { type: 'PushEvent', actor: { login: 'example-user' }, repo: { name: 'example-org/activity-only' }, created_at: '2026-10-19T02:00:00Z' }, + ])) + return new Response('[]') + }) as unknown as typeof fetch, + openRunner: async (cmd, args) => { opened.push([cmd, ...args]) }, + }) + const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise } + const snapshot = await provider.poll!() as GhSnapshot + + expect(snapshot.repoActivity).toEqual([{ repo: 'example-org/activity-only', updatedAt: Date.parse('2026-10-19T02:00:00Z') }]) + expect(await commands.openRepo({ repo: 'example-org/activity-only' }, { loopback: true })).toEqual({ ok: true }) + expect(opened).toEqual([['/usr/bin/open', 'https://github.com/example-org/activity-only']]) + }) + + it('refuses non-loopback, unknown, or malformed repository targets', async () => { + const { fetchFn } = responder() + const opened: string[][] = [] + const provider = createGithubProvider(context(), { fetchFn, openRunner: async (cmd, args) => { opened.push([cmd, ...args]) } }) + const snapshot = await provider.poll!() as GhSnapshot + const commands = provider.commands as unknown as { openRepo: (payload: unknown, context: { loopback: boolean }) => Promise } + const repo = snapshot.reviewRequests[0].repo + + expect(await commands.openRepo({ repo }, { loopback: false })).toEqual({ ok: false, error: tr(undefined, 'provider.localOnly') }) + expect(await commands.openRepo({ repo: 'other/repo' }, { loopback: true })).toEqual({ ok: false }) + for (const unsafe of ['../etc/passwd', 'example-org/repo/extra', 'https://evil.test/a/b', '']) { + await expect(commands.openRepo({ repo: unsafe }, { loopback: true })).rejects.toThrow() + } + expect(opened).toEqual([]) + }) }) From 15ebc640e1706a6900a5e7c1407c93fa45e6325b Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Tue, 20 Oct 2026 22:35:27 +0200 Subject: [PATCH 02/24] Find the Claude OAuth item past the base keychain name Newer Claude Code versions suffix the credentials item's service by their config dir (Claude Code-credentials-8047733a); the plainly named item can then hold MCP data only, and the provider reported "not available on this Mac" while the user was signed in. Enumerate every Claude Code-credentials* service and read the first item whose payload actually carries claudeAiOauth.accessToken. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CHANGELOG.md | 5 ++++ server/src/claude/account.ts | 40 +++++++++++++++++++++++++++--- server/test/claude-account.test.ts | 38 +++++++++++++++++++++++++++- 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45ec051c..a997b59e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ tagged `vX.Y.Z`. ### Fixed +- **The Claude limits tile finds the sign-in again.** Recent Claude Code versions keep the OAuth + credentials in a keychain item whose name carries a config-dir suffix + (`Claude Code-credentials-8047733a`), while the plainly named item can hold MCP data instead. + The provider now looks through every `Claude Code-credentials*` item for the one that has the + token, instead of reporting "not available on this Mac". - **The clipboard widget masks one-time codes.** A six-digit code copied from a text message or an authenticator (`482913`, `482 913`, `4829-1375`) showed in full on the Edge and on a paired iPad; any run of four to eight digits copied on its own is now shown as a secret, and still diff --git a/server/src/claude/account.ts b/server/src/claude/account.ts index ca00b6b5..5b03ea50 100644 --- a/server/src/claude/account.ts +++ b/server/src/claude/account.ts @@ -22,6 +22,13 @@ export interface AccountSnapshot extends AccountUsage { available: boolean; stal */ const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage' const KEYCHAIN_SERVICE = 'Claude Code-credentials' +/** + * Newer Claude Code versions suffix the item's service by their config dir + * (`Claude Code-credentials-8047733a`), and can leave the OAuth blob in one of + * those while the plain name holds something else (`mcpOAuth` only). The dump + * lists every item's service so each candidate can be tried by its full name. + */ +const SERVICE_RE = /"svce"="(Claude Code-credentials[^"]*)"/g /** * Names for the windows Claude reports without one of its own. Resolved on each poll rather than * once, so the language the user picked reaches the widget on the next refresh. @@ -61,8 +68,18 @@ async function persistUsage(filePath: string, data: Persisted): Promise { await rename(tmp, filePath) } -function run(cmd: string, args: string[]): Promise { - return new Promise((resolve, reject) => execFile(cmd, args, { timeout: 5000 }, (err, stdout) => (err ? reject(err) : resolve(stdout.trim())))) +function run(cmd: string, args: string[], maxBuffer = 1024 * 1024): Promise { + return new Promise((resolve, reject) => execFile(cmd, args, { timeout: 5000, maxBuffer }, (err, stdout) => (err ? reject(err) : resolve(stdout.trim())))) +} + +type Runner = (cmd: string, args: string[], maxBuffer?: number) => Promise + +/** Every `Claude Code-credentials*` service in the keychain, base name first. */ +async function credentialServices(runner: Runner): Promise { + const out = await runner('/usr/bin/security', ['dump-keychain'], 16 * 1024 * 1024) + const names = new Set() + for (const m of out.matchAll(SERVICE_RE)) names.add(m[1]) + return [...names].sort((a, b) => a.length - b.length) } /** Extracts the Claude Code OAuth access token from the keychain item's JSON payload. */ @@ -75,8 +92,23 @@ export function parseKeychainJson(raw: string): string | null { } /** Reads the token from the macOS keychain. Never logs or stores it. */ -export async function readClaudeOAuthToken(): Promise { - try { return parseKeychainJson(await run('/usr/bin/security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-w'])) } catch { return null } +export async function readClaudeOAuthToken(runner: Runner = run): Promise { + // The plain name first, so the common case stays a single `security` call; + // only when it misses does the dump list the per-config-dir variants. + try { + const token = parseKeychainJson(await runner('/usr/bin/security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-w'])) + if (token) return token + } catch { /* absent, locked, or not a credentials payload */ } + let services: string[] + try { services = await credentialServices(runner) } catch { return null } + for (const service of services) { + if (service === KEYCHAIN_SERVICE) continue + try { + const token = parseKeychainJson(await runner('/usr/bin/security', ['find-generic-password', '-s', service, '-w'])) + if (token) return token + } catch { /* locked or unrelated item: try the next */ } + } + return null } function epoch(iso: unknown): number | null { diff --git a/server/test/claude-account.test.ts b/server/test/claude-account.test.ts index b9b8fc07..5e67df73 100644 --- a/server/test/claude-account.test.ts +++ b/server/test/claude-account.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from 'vitest' -import { normalizeAccountUsage, createClaudeAccountProvider, parseKeychainJson } from '../src/claude/account.js' +import { normalizeAccountUsage, createClaudeAccountProvider, parseKeychainJson, readClaudeOAuthToken } from '../src/claude/account.js' import { USER_AGENT } from '../src/version.js' const sample = { @@ -38,6 +38,42 @@ describe('parseKeychainJson', () => { }) }) +describe('readClaudeOAuthToken', () => { + const creds = (accessToken: string) => JSON.stringify({ claudeAiOauth: { accessToken } }) + // `security` stand-in: named items answering `-s -w`, and a `dump-keychain` + // that lists their service names the way the real one writes them. + const runnerOf = (items: Record) => vi.fn(async (_cmd: string, args: string[]) => { + if (args[0] === 'dump-keychain') return items ? Object.keys(items).map((s) => `"svce"="${s}"`).join('\n') : '' + const item = items[args[args.indexOf('-s') + 1]] + if (item === undefined) throw new Error('The specified item could not be found in the keychain.') + return item + }) + + it('reads the plainly named item without a dump', async () => { + const runner = runnerOf({ 'Claude Code-credentials': creds('tok') }) + expect(await readClaudeOAuthToken(runner)).toBe('tok') + expect(runner).toHaveBeenCalledTimes(1) + }) + + it('finds the token in a config-dir-suffixed item when the plain name holds something else', async () => { + const runner = runnerOf({ + 'Claude Code-credentials': JSON.stringify({ mcpOAuth: {} }), + 'Claude Code-credentials-10be7540': creds('tok2'), + }) + expect(await readClaudeOAuthToken(runner)).toBe('tok2') + }) + + it('keeps looking when the plain name is absent entirely', async () => { + const runner = runnerOf({ 'Claude Code-credentials-8047733a': creds('tok3') }) + expect(await readClaudeOAuthToken(runner)).toBe('tok3') + }) + + it('answers null when nothing parses to a token', async () => { + expect(await readClaudeOAuthToken(runnerOf({ 'Claude Code-credentials-10be7540': JSON.stringify({ mcpOAuth: {} }) }))).toBeNull() + expect(await readClaudeOAuthToken(runnerOf({}))).toBeNull() + }) +}) + describe('createClaudeAccountProvider', () => { const ok = () => vi.fn(async () => new Response(JSON.stringify(sample), { status: 200 })) it('publishes available data with the expected headers', async () => { From af4793c3a842847af4d5038c14abaafa7e210acc Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 03:38:50 +0200 Subject: [PATCH 03/24] Add privacy-bounded Messages 2FA provider --- server/src/app.ts | 2 + server/src/providers/messages-2fa.ts | 130 +++++++++++++++++++++++++++ server/test/messages-2fa.test.ts | 96 ++++++++++++++++++++ 3 files changed, 228 insertions(+) create mode 100644 server/src/providers/messages-2fa.ts create mode 100644 server/test/messages-2fa.test.ts diff --git a/server/src/app.ts b/server/src/app.ts index b9ecc4f2..a8fbeff9 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -61,6 +61,7 @@ import { isSafeBackgroundName } from './config/schema.js' import { backupRoutes } from './backup/routes.js' import { bambuRoutes } from './bambu/routes.js' import { createShortcutsProvider } from './providers/shortcuts.js' +import { createMessages2FAProvider } from './providers/messages-2fa.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' @@ -308,6 +309,7 @@ export async function buildApp(opts: AppOptions): Promise { registry.register(createDiskMapProvider({ dataDir: opts.dataDir })) // Registered here, not in providers/index.ts, because that is where the config store lives. registry.register(createShortcutsProvider(undefined, instances)) + registry.register(createMessages2FAProvider({ enabled: () => store.get().privacy.messages2FA })) registry.register(createServiceStatusProvider({}, instances)) // A paired device may set only its own screen's brightness: see mayCommandBrightness. Read // at command time, so a device moved to another screen (or unpaired) is judged as it is now. diff --git a/server/src/providers/messages-2fa.ts b/server/src/providers/messages-2fa.ts new file mode 100644 index 00000000..e7c6c48c --- /dev/null +++ b/server/src/providers/messages-2fa.ts @@ -0,0 +1,130 @@ +import { execFile } from 'node:child_process' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { z } from 'zod' +import type { CommandContext, Provider } from './types.js' +import { pbPasteboard, type Pasteboard } from './clipboard.js' + +const MESSAGES_DB = join(homedir(), 'Library', 'Messages', 'chat.db') +const APPLE_EPOCH_MS = 978_307_200_000 +const WINDOW_MS = 5 * 60_000 +const QUERY_LIMIT = 100 +const COMMAND_TIMEOUT_MS = 2_500 +const CODE_LENGTH = /^\d{4,8}$/ +const RequestSchema = z.null() + +interface MessageRow { + text?: unknown + date?: unknown +} + +type Run = (file: string, args: string[]) => Promise + +interface Messages2FAOptions { + databasePath?: string + now?: () => number + run?: Run + pasteboard?: Pick +} + +const defaultRun: Run = (file, args) => new Promise((resolve, reject) => { + execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 128 * 1024, shell: false }, (error, stdout) => { + if (error) reject(new Error('Messages could not be read.')) + else resolve(stdout) + }) +}) + +function timestampBounds(now: number): { appleSeconds: number; appleNanoseconds: number } { + const cutoff = now - WINDOW_MS - APPLE_EPOCH_MS + return { appleSeconds: Math.floor(cutoff / 1000), appleNanoseconds: Math.floor(cutoff * 1_000_000) } +} + +function appleDateToUnixMs(value: unknown): number | undefined { + const date = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN + if (!Number.isFinite(date) || date <= 0) return undefined + const unixMs = date > 1_000_000_000_000 + ? date / 1_000_000 + APPLE_EPOCH_MS + : date * 1000 + APPLE_EPOCH_MS + return Number.isFinite(unixMs) ? unixMs : undefined +} + +function hasVerificationContext(text: string, start: number, end: number): boolean { + const context = text.slice(Math.max(0, start - 70), Math.min(text.length, end + 70)) + .normalize('NFD') + .replace(/\p{Diacritic}/gu, '') + .toLowerCase() + return /\b(?:verification|security|authentication|authenticator|passcode|sign[ -]?in|login|one[ -]?time|otp)\b/.test(context) +} + +function verificationCode(text: string): string | undefined { + const pattern = /(? { + const bounds = timestampBounds(now) + const query = `SELECT trim(coalesce(text, '') || ' ' || coalesce(cast(attributedBody AS text), '')) AS text, date FROM message + WHERE is_from_me = 0 AND (text IS NOT NULL OR attributedBody IS NOT NULL) + AND length(coalesce(text, '') || ' ' || coalesce(cast(attributedBody AS text), '')) <= 4096 + AND ((date > 1000000000000 AND date >= ${bounds.appleNanoseconds}) + OR (date <= 1000000000000 AND date >= ${bounds.appleSeconds})) + ORDER BY date DESC LIMIT ${QUERY_LIMIT};` + const stdout = await run('/usr/bin/sqlite3', [ + '-readonly', '-json', '-batch', + '-cmd', 'PRAGMA query_only=ON;', + '-cmd', '.timeout 1000', + databasePath, + query, + ]) + let rows: unknown + try { rows = JSON.parse(stdout || '[]') } catch { throw new Error('Messages could not be read.') } + const parsed = z.array(z.object({ text: z.string().max(4096), date: z.union([z.number(), z.string()]) })).safeParse(rows) + if (!parsed.success) throw new Error('Messages could not be read.') + + for (const row of parsed.data as MessageRow[]) { + const sentAt = appleDateToUnixMs(row.date) + if (sentAt === undefined || sentAt < now - WINDOW_MS || sentAt > now + 60_000) continue + const code = verificationCode(row.text as string) + if (code) return code + } + return undefined +} + +/** Reads only recent incoming message text on an explicit local tap; never polls or logs content. */ +export function createMessages2FAProvider(options: Messages2FAOptions = {}): Provider { + const databasePath = options.databasePath ?? MESSAGES_DB + const now = options.now ?? Date.now + const run = options.run ?? defaultRun + const pasteboard = options.pasteboard ?? pbPasteboard + + return { + channel: 'messages-2fa', + commands: { + copyLatest: async (payload: unknown, context?: CommandContext) => { + if (context?.loopback !== true) return { ok: false, error: 'Available only from this Mac.' } + if (!RequestSchema.safeParse(payload).success) return { ok: false, error: 'Invalid request.' } + let code: string | undefined + try { code = await latestVerificationCode(databasePath, now(), run) } catch { + return { ok: false, error: 'Messages could not be read.' } + } + if (!code) return { ok: false, error: 'No recent verification code found.' } + try { await pasteboard.write(code) } catch { + return { ok: false, error: 'The code could not be copied.' } + } + // Keep the OTP on the local pasteboard only; never return it over the widget bridge. + return { ok: true } + }, + }, + } +} diff --git a/server/test/messages-2fa.test.ts b/server/test/messages-2fa.test.ts new file mode 100644 index 00000000..bfab7296 --- /dev/null +++ b/server/test/messages-2fa.test.ts @@ -0,0 +1,96 @@ +import { execFileSync } from 'node:child_process' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createMessages2FAProvider } from '../src/providers/messages-2fa.js' + +const dirs: string[] = [] +const APPLE_EPOCH_MS = 978_307_200_000 + +async function fixtureDatabase(sql: string): Promise { + const dir = await mkdtemp(join(tmpdir(), 'fremkit-messages-2fa-')) + dirs.push(dir) + const path = join(dir, 'chat.db') + execFileSync('/usr/bin/sqlite3', [path, sql]) + return path +} + +afterEach(async () => { + await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) +}) + +describe('Messages 2FA provider', () => { + it('copies a recent incoming verification code on explicit local request', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Your verification code is 482913', NULL, 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('482913') + }) + + it('finds verification text stored only in attributedBody', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, CAST('Your verification code is 734206' AS BLOB), 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('734206') + }) + + it('ignores outgoing, expired and unrelated numeric messages', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const old = Math.floor((now - APPLE_EPOCH_MS - 6 * 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Security code 111111', NULL, 1, ${recent}); + INSERT INTO message VALUES ('Verification code 222222', NULL, 0, ${old}); + INSERT INTO message VALUES ('Order number 333333', NULL, 0, ${recent});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'No recent verification code found.' }) + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('refuses remote callers without reading Messages or touching the pasteboard', async () => { + const run = vi.fn(async () => '[]') + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ run, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: false })) + .resolves.toEqual({ ok: false, error: 'Available only from this Mac.' }) + expect(run).not.toHaveBeenCalled() + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('fails closed on unsupported database schemas without exposing database content', async () => { + const databasePath = await fixtureDatabase('CREATE TABLE unsupported (body TEXT);') + const provider = createMessages2FAProvider({ databasePath }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'Messages could not be read.' }) + }) + + it('does not expose a code or raw database error if copying fails', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Passcode 765432', NULL, 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => { throw new Error('secret-bearing system error') }) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'The code could not be copied.' }) + }) +}) From 67e4c12cc815d669191ccc4fadbef0e0be5fcb36 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 07:54:07 +0200 Subject: [PATCH 04/24] Fix Messages attributedBody typedstream parsing --- server/src/providers/messages-2fa.ts | 73 +++++++++++++++++++++++++--- server/test/messages-2fa.test.ts | 52 ++++++++++++++++++++ 2 files changed, 118 insertions(+), 7 deletions(-) diff --git a/server/src/providers/messages-2fa.ts b/server/src/providers/messages-2fa.ts index e7c6c48c..9525f9ca 100644 --- a/server/src/providers/messages-2fa.ts +++ b/server/src/providers/messages-2fa.ts @@ -10,12 +10,17 @@ const APPLE_EPOCH_MS = 978_307_200_000 const WINDOW_MS = 5 * 60_000 const QUERY_LIMIT = 100 const COMMAND_TIMEOUT_MS = 2_500 +// 100 rows can contain either 4 KiB of JSON-escaped text or 4 KiB of hex BLOB data. +// Keep the whole result bounded while allowing the full recent-message window through. +const MAX_QUERY_OUTPUT_BYTES = 3 * 1024 * 1024 const CODE_LENGTH = /^\d{4,8}$/ +const MAX_ATTRIBUTED_BODY_BYTES = 4_096 const RequestSchema = z.null() interface MessageRow { - text?: unknown - date?: unknown + text?: string + attributedHex?: string + date?: number | string } type Run = (file: string, args: string[]) => Promise @@ -28,7 +33,7 @@ interface Messages2FAOptions { } const defaultRun: Run = (file, args) => new Promise((resolve, reject) => { - execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 128 * 1024, shell: false }, (error, stdout) => { + execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: MAX_QUERY_OUTPUT_BYTES, shell: false }, (error, stdout) => { if (error) reject(new Error('Messages could not be read.')) else resolve(stdout) }) @@ -68,15 +73,68 @@ function verificationCode(text: string): string | undefined { return undefined } +function decodeTypedstreamAttributedBody(hex: string): string | undefined { + if (hex.length === 0 || hex.length > MAX_ATTRIBUTED_BODY_BYTES * 2 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) return undefined + const bytes = Buffer.from(hex, 'hex') + const isTypedstream = bytes.length >= 13 && bytes[0] === 4 && bytes[1] === 11 && bytes.subarray(2, 13).toString('ascii') === 'streamtyped' + if (!isTypedstream) { + // Keep compatibility with older/test databases that stored plain UTF-8 in attributedBody; + // reject binary/control-heavy payloads rather than heuristically scraping them. + try { + const plain = new TextDecoder('utf-8', { fatal: true }).decode(bytes) + return plain && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(plain) ? plain : undefined + } catch { + return undefined + } + } + + // Messages stores NSAttributedString bodies as NSArchiver typedstreams. The actual plaintext + // is the unshared NSString value immediately following its class declaration. Parse its + // length prefix as bytes; decoding the whole archive as SQLite TEXT stops at embedded NULs. + const stringClass = Buffer.from('NSString', 'ascii') + const classIndex = bytes.indexOf(stringClass, 13) + if (classIndex < 0) return undefined + const classEnd = classIndex + stringClass.length + const markerIndex = bytes.indexOf(0x2b, classEnd) + if (markerIndex < classEnd || markerIndex - classEnd > 32) return undefined + + let cursor = markerIndex + 1 + const tag = bytes[cursor++] + let length: number + if (tag <= 0x7f) length = tag + else if (tag === 0x81 && cursor + 2 <= bytes.length) { + length = bytes.readUInt16LE(cursor) + cursor += 2 + } else if (tag === 0x82 && cursor + 4 <= bytes.length) { + length = bytes.readUInt32LE(cursor) + cursor += 4 + } else if (tag === 0x83 && cursor + 8 <= bytes.length) { + const longLength = bytes.readBigUInt64LE(cursor) + if (longLength > BigInt(MAX_ATTRIBUTED_BODY_BYTES)) return undefined + length = Number(longLength) + cursor += 8 + } else return undefined + + if (length <= 0 || length > MAX_ATTRIBUTED_BODY_BYTES || cursor + length > bytes.length) return undefined + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(cursor, cursor + length)) + } catch { + return undefined + } +} + async function latestVerificationCode( databasePath: string, now: number, run: Run, ): Promise { const bounds = timestampBounds(now) - const query = `SELECT trim(coalesce(text, '') || ' ' || coalesce(cast(attributedBody AS text), '')) AS text, date FROM message + const query = `SELECT coalesce(text, '') AS text, + CASE WHEN text IS NULL OR text = '' THEN coalesce(hex(attributedBody), '') ELSE '' END AS attributedHex, + date FROM message WHERE is_from_me = 0 AND (text IS NOT NULL OR attributedBody IS NOT NULL) - AND length(coalesce(text, '') || ' ' || coalesce(cast(attributedBody AS text), '')) <= 4096 + AND length(coalesce(text, '')) <= 4096 + AND (attributedBody IS NULL OR length(attributedBody) <= ${MAX_ATTRIBUTED_BODY_BYTES}) AND ((date > 1000000000000 AND date >= ${bounds.appleNanoseconds}) OR (date <= 1000000000000 AND date >= ${bounds.appleSeconds})) ORDER BY date DESC LIMIT ${QUERY_LIMIT};` @@ -89,13 +147,14 @@ async function latestVerificationCode( ]) let rows: unknown try { rows = JSON.parse(stdout || '[]') } catch { throw new Error('Messages could not be read.') } - const parsed = z.array(z.object({ text: z.string().max(4096), date: z.union([z.number(), z.string()]) })).safeParse(rows) + const parsed = z.array(z.object({ text: z.string().max(4096), attributedHex: z.string().max(MAX_ATTRIBUTED_BODY_BYTES * 2), date: z.union([z.number(), z.string()]) })).safeParse(rows) if (!parsed.success) throw new Error('Messages could not be read.') for (const row of parsed.data as MessageRow[]) { const sentAt = appleDateToUnixMs(row.date) if (sentAt === undefined || sentAt < now - WINDOW_MS || sentAt > now + 60_000) continue - const code = verificationCode(row.text as string) + const body = row.text || decodeTypedstreamAttributedBody(row.attributedHex ?? '') || '' + const code = verificationCode(body) if (code) return code } return undefined diff --git a/server/test/messages-2fa.test.ts b/server/test/messages-2fa.test.ts index bfab7296..72397776 100644 --- a/server/test/messages-2fa.test.ts +++ b/server/test/messages-2fa.test.ts @@ -7,6 +7,13 @@ import { createMessages2FAProvider } from '../src/providers/messages-2fa.js' const dirs: string[] = [] const APPLE_EPOCH_MS = 978_307_200_000 +const LONG_TYPEDSTREAM_VERIFIED = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAFlvdXIgdmVyaWZpY2F0aW9uIGNvZGUgaXMgNDgzOTIxIEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' +const LONG_TYPEDSTREAM_FIXTURE = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAFlvdXIgdmVyaWZpY2F0aW9uIGNvZGUgaXMgNDgzOTIxIEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' +// Synthetic Foundation NSArchiver/typedstream archive of an attributed string. Keeping this +// fixture local and synthetic exercises the same BLOB shape used by Messages without reading +// or retaining any user's chat database content. +const ATTRIBUTED_TYPEDSTREAM_BASE64 = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBKyBZb3VyIHZlcmlmaWNhdGlvbiBjb2RlIGlzIDQ4MzkyMYaEAmlJASCShISEDE5TRGljdGlvbmFyeQCUhAFpAZKElpYQZXhhbXBsZUF0dHJpYnV0ZYaShJaWCXN5bnRoZXRpY4aGhg==' +const LONG_ATTRIBUTED_TYPEDSTREAM_BASE64 = 'BAtzdHJlYW10eXBlZIHoA4QBQISEhBJOU0F0dHJpYnV0ZWRTdHJpbmcAhIQITlNPYmplY3QAhZKEhIQITlNTdHJpbmcBlIQBK4GjAEFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUEgWW91ciB2ZXJpZmljYXRpb24gY29kZSBpcyA0ODM5MjGGhAJpSQGBowCShISEDE5TRGljdGlvbmFyeQCUhAFpAIaG' async function fixtureDatabase(sql: string): Promise { const dir = await mkdtemp(join(tmpdir(), 'fremkit-messages-2fa-')) @@ -47,6 +54,51 @@ describe('Messages 2FA provider', () => { expect(pasteboard.write).toHaveBeenCalledWith('734206') }) + it('extracts and copies a synthetic Foundation typedstream attributedBody', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const typedstreamHex = Buffer.from(ATTRIBUTED_TYPEDSTREAM_BASE64, 'base64').toString('hex') + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + + it('reads typedstream lengths that use the two-byte prefix', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const typedstreamHex = Buffer.from(LONG_TYPEDSTREAM_VERIFIED, 'base64').toString('hex') + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + + it('reads a full bounded result set with large attributed bodies', async () => { + const now = Date.now() + const date = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + WITH RECURSIVE seq(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM seq WHERE n < 100) + INSERT INTO message + SELECT 'Your verification code is 483921' || replace(hex(zeroblob(4064)), '00', char(1)), + zeroblob(${4096}), 0, ${date} - (100 - n) * 1000000000 + FROM seq;`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + + await expect(provider.commands?.copyLatest(null, { loopback: true })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('483921') + }) + it('ignores outgoing, expired and unrelated numeric messages', async () => { const now = Date.now() const recent = Math.floor((now - APPLE_EPOCH_MS - 60_000) * 1_000_000) From e47fc4edff9725a77c2fa8f2d261c5dd0159109a Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 22:09:47 +0200 Subject: [PATCH 05/24] Address Messages 2FA provider review findings --- CHANGELOG.md | 10 ++ SECURITY.md | 12 +- server/src/config/migrate.ts | 2 +- server/src/config/schema.ts | 4 +- server/src/demo/providers.ts | 2 + server/src/demo/seed.ts | 2 +- server/src/i18n.ts | 14 +++ server/src/providers/messages-2fa.ts | 170 ++++++++++++++++++++++---- server/src/widgets/manifest.ts | 4 +- server/test/config-migration.test.ts | 7 ++ server/test/demo.test.ts | 3 + server/test/messages-2fa.test.ts | 165 +++++++++++++++++++++---- server/test/widget-catalog.test.ts | 4 +- server/test/widget-manifest.test.ts | 5 + ui/src/admin/settings/PrivacyPane.vue | 7 ++ ui/src/shared/locales/en.ts | 2 + ui/src/shared/locales/fr.ts | 2 + ui/src/shared/types.ts | 2 + 18 files changed, 359 insertions(+), 58 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a997b59e..507cc6d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ tagged `vX.Y.Z`. ## Unreleased +### Added +- **Messages verification-code provider.** Adds the local, default-off provider for the companion + [Sietch Messages widget PR #16](https://github.com/fdussert/fremkit-sietch/pull/16); the widget + is not bundled here, and its trusted integration remains separate. When integrated, codes are + written as concealed, temporary, current-Mac-only pasteboard content. The provider schedules a + conditional clear after 60 seconds; if cleanup startup or execution fails, it attempts an + immediate conditional clear. If macOS refuses both cleanup attempts, the code may remain on the + pasteboard. A cleanup startup failure is returned as a generic copy failure; a later cleaner + failure is logged without exposing the code. + ### Fixed - **The Claude limits tile finds the sign-in again.** Recent Claude Code versions keep the OAuth diff --git a/SECURITY.md b/SECURITY.md index 61d2eb71..a2929e61 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -436,9 +436,11 @@ the Dock badges, and supervises the server process. and the programs it runs (such as `fremkit-scan`) to the helper as their responsible app, so a file-access grant made to "Fremkit Helper" — Files and Folders, or Full Disk Access — is also the server's. -- **Full Disk Access is optional.** Only the disk map benefits from it: without it, the folders - macOS protects are shown as unreadable. With it, the helper, the server and every provider can - read every file of the account. Grant it only if you want those folders measured. +- **Full Disk Access is optional.** The disk map and the Messages 2FA provider can benefit from + it: without it, protected folders are shown as unreadable and Messages lookup fails. With it, + the helper, the server and every provider can read every file of the account. Grant it only if + you want those features, and leave the separate Messages 2FA privacy setting off unless you + want a built-in widget to read recent incoming messages after an explicit copy request. - **It is signed with a self-signed identity** created by `scripts/create-signing-identity.sh` ("Fremkit Helper Dev"), because macOS ties TCC grants to the signature: without a stable one you would re-approve the permissions after every build. @@ -465,7 +467,9 @@ These are real and not fixed. They are here so you can decide whether they matte [docs/connections.md](docs/connections.md#what-the-tls-does-and-does-not-prove). - **A same-user process is out of scope.** It can read your keychain, your config and your clipboard without going through Fremkit at all — and the access secret's token file, which is - readable by your account by design so the scripts can use it. + readable by your account by design so the scripts can use it. If macOS grants Full Disk Access + and you enable the separate Messages 2FA privacy setting, it can also ask Fremkit's local + command to copy a recent incoming verification code; that setting is off by default. - **The widgets' own files are served without the secret** (see above), so a page you visit can find out which widgets are installed, though not how they are set up or what they show. - **The registry is trusted to be curated, not to be safe.** An installed widget can do diff --git a/server/src/config/migrate.ts b/server/src/config/migrate.ts index bc052515..a34a35e0 100644 --- a/server/src/config/migrate.ts +++ b/server/src/config/migrate.ts @@ -192,7 +192,7 @@ function readV3(raw: unknown, version: unknown): V3Config { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false, messages2FA: false }, // A v1 config predates the marketplace by a long way; nothing can have been installed. marketplace: { installed: {} }, pages: v1.pages.map((p) => ({ diff --git a/server/src/config/schema.ts b/server/src/config/schema.ts index c45bd0f5..05d31ddb 100644 --- a/server/src/config/schema.ts +++ b/server/src/config/schema.ts @@ -355,6 +355,8 @@ export const PrivacySchema = z.object({ codexHistorySources: z.array(HistorySourceSchema).max(10).default([]), /** Read CPU temperature from the optional local macmon executable. */ macmonTemperature: z.boolean().default(false), + /** Read recent Messages for a verification code only after a separate, explicit opt-in. */ + messages2FA: z.boolean().default(false), }).prefault({}) /** @@ -481,7 +483,7 @@ export const DEFAULT_CONFIG: Config = { connections: [], secrets: { backend: defaultSecretsBackend() }, locale: defaultLocale(), - privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false }, + privacy: { claudeAccountUsage: false, showAccountEmail: false, codexAccount: false, codexHistorySources: [], macmonTemperature: false, messages2FA: false }, labs: { devices: false, companion: false }, marketplace: { installed: {} }, widgets: { diff --git a/server/src/demo/providers.ts b/server/src/demo/providers.ts index dd4521c3..2283d965 100644 --- a/server/src/demo/providers.ts +++ b/server/src/demo/providers.ts @@ -1,5 +1,6 @@ import { z } from 'zod' import type { Provider } from '../providers/types.js' +import { tr } from '../i18n.js' import type { Config } from '../config/schema.js' import { findInstance, type InstanceLookup } from '../config/instances.js' import { resolveServices, type ServiceResult } from '../providers/service-status.js' @@ -62,6 +63,7 @@ export function createDemoProviders(opts: DemoProviderOptions): Provider[] { { channel: 'cleanshot', commands: { run: ACTED } }, rtkProvider(now), { channel: 'shortcuts', commands: { open: ACTED } }, + { channel: 'messages-2fa', commands: { copyLatest: async () => ({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) } }, serviceStatusProvider(now, opts.instances ?? ((id) => findInstance(opts.config(), id))), ] } diff --git a/server/src/demo/seed.ts b/server/src/demo/seed.ts index e8f7cdca..abcae3ee 100644 --- a/server/src/demo/seed.ts +++ b/server/src/demo/seed.ts @@ -124,7 +124,7 @@ export function demoConfig(locale: 'fr' | 'en' = 'en'): Config { // A file next to the config, never the keychain: a demo has nothing to keep secret. secrets: { backend: 'file' }, locale, - privacy: { claudeAccountUsage: true, showAccountEmail: false, codexAccount: true, codexHistorySources: ['cli', 'vscode', 'appServer'], macmonTemperature: false }, + privacy: { claudeAccountUsage: true, showAccountEmail: false, codexAccount: true, codexHistorySources: ['cli', 'vscode', 'appServer'], macmonTemperature: false, messages2FA: false }, marketplace: { installed: {} }, // As on a fresh install: the iPad screens stay an experimental feature until it is ticked. labs: { devices: false, companion: false }, diff --git a/server/src/i18n.ts b/server/src/i18n.ts index af540130..227c250f 100644 --- a/server/src/i18n.ts +++ b/server/src/i18n.ts @@ -37,6 +37,13 @@ const fr = { // app.ts — the global request gate 'provider.invalidPayload': 'charge utile invalide', + 'messages2fa.disabled': 'activez la recherche de codes Messages dans les réglages de confidentialité', + 'messages2fa.localOnly': 'disponible uniquement depuis ce Mac', + 'messages2fa.invalidRequest': 'requête invalide', + 'messages2fa.rateLimited': 'attendez quelques secondes avant de rechercher un autre code', + 'messages2fa.readFailed': 'impossible de lire Messages', + 'messages2fa.noneFound': 'aucun code de vérification récent trouvé', + 'messages2fa.copyFailed': 'impossible de copier le code', 'clipboard.unknownEntry': 'entrée inconnue', 'serviceStatus.invalidHost': 'hôte invalide', 'serviceStatus.invalidHostPort': 'hôte:port invalide', @@ -333,6 +340,13 @@ const en: Record = { 'config.degraded': 'configuration on disk is unreadable: fix data/fremkit.json then restart the server', 'provider.invalidPayload': 'invalid payload', + 'messages2fa.disabled': 'enable Messages code lookup in Privacy settings', + 'messages2fa.localOnly': 'available only from this Mac', + 'messages2fa.invalidRequest': 'invalid request', + 'messages2fa.rateLimited': 'wait a few seconds before looking up another code', + 'messages2fa.readFailed': 'Messages could not be read', + 'messages2fa.noneFound': 'no recent verification code found', + 'messages2fa.copyFailed': 'the code could not be copied', 'clipboard.unknownEntry': 'unknown entry', 'serviceStatus.invalidHost': 'invalid host', 'serviceStatus.invalidHostPort': 'invalid host:port', diff --git a/server/src/providers/messages-2fa.ts b/server/src/providers/messages-2fa.ts index 9525f9ca..5ce79424 100644 --- a/server/src/providers/messages-2fa.ts +++ b/server/src/providers/messages-2fa.ts @@ -1,9 +1,10 @@ -import { execFile } from 'node:child_process' +import { execFile, spawn, type ChildProcess } from 'node:child_process' import { homedir } from 'node:os' import { join } from 'node:path' import { z } from 'zod' import type { CommandContext, Provider } from './types.js' -import { pbPasteboard, type Pasteboard } from './clipboard.js' +import type { Pasteboard } from './clipboard.js' +import { tr } from '../i18n.js' const MESSAGES_DB = join(homedir(), 'Library', 'Messages', 'chat.db') const APPLE_EPOCH_MS = 978_307_200_000 @@ -15,8 +16,105 @@ const COMMAND_TIMEOUT_MS = 2_500 const MAX_QUERY_OUTPUT_BYTES = 3 * 1024 * 1024 const CODE_LENGTH = /^\d{4,8}$/ const MAX_ATTRIBUTED_BODY_BYTES = 4_096 +const REQUEST_COOLDOWN_MS = 5_000 const RequestSchema = z.null() +// The code enters osascript only on stdin; the source is constant and no widget value is in argv. +// AppKit marks it concealed/transient and limits Universal Clipboard to this Mac. It prints only +// the pasteboard change count so a detached cleanup process can clear the code after one minute. +const WRITE_CODE_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile; +const value = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding); +if (!value) throw new Error('invalid input'); +const board = $.NSPasteboard.generalPasteboard; +board.prepareForNewContentsWithOptions($.NSPasteboardContentsCurrentHostOnly); +if (!board.setStringForType(value, $.NSPasteboardTypeString)) throw new Error('pasteboard write failed'); +board.setDataForType($.NSData.data, 'org.nspasteboard.ConcealedType'); +board.setDataForType($.NSData.data, 'org.nspasteboard.TransientType'); +String(board.changeCount);` + +const CLEAR_CODE_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const args = $.NSProcessInfo.processInfo.arguments; +const expected = Number(ObjC.unwrap(args.lastObject)); +$.NSThread.sleepForTimeInterval(60); +const board = $.NSPasteboard.generalPasteboard; +if (Number(board.changeCount) === expected) board.clearContents();` + +type ScriptExecutor = (script: string, args: string[], stdin?: string) => Promise +type CleanupSpawner = (changeCount: number) => ChildProcess + +const executeAppleScript: ScriptExecutor = (script, args, stdin) => new Promise((resolve, reject) => { + const child = execFile('osascript', ['-l', 'JavaScript', '-e', script, ...args], { + timeout: COMMAND_TIMEOUT_MS, + maxBuffer: 1024, + shell: false, + }, (error, stdout) => { + if (error) reject(new Error('pasteboard operation failed')) + else resolve(stdout) + }) + if (stdin !== undefined) child.stdin?.end(stdin) +}) + +const spawnCleanup: CleanupSpawner = (changeCount) => spawn('osascript', [ + '-l', 'JavaScript', '-e', CLEAR_CODE_SCRIPT, String(changeCount), +], { detached: true, stdio: 'ignore' }) + +function reportCleanupFailure(): void { + console.error('Messages code pasteboard cleanup failed.') +} + +export function createMessagePasteboardWriter( + dependencies: { executeScript?: ScriptExecutor; spawnCleanup?: CleanupSpawner } = {}, +): Pick { + const runScript = dependencies.executeScript ?? executeAppleScript + const startCleanup = dependencies.spawnCleanup ?? spawnCleanup + const clearIfUnchanged = async (changeCount: number): Promise => { + await runScript(CLEAR_IF_UNCHANGED_SCRIPT, [String(changeCount)]) + } + + return { + write: async (text) => { + const stdout = await runScript(WRITE_CODE_SCRIPT, [], text) + const changeCount = Number(stdout.trim()) + if (!Number.isSafeInteger(changeCount)) throw new Error('pasteboard write failed') + + try { + const cleanup = startCleanup(changeCount) + await new Promise((resolve, reject) => { + let started = false + cleanup.once('error', (error) => { + if (!started) reject(error) + else void clearIfUnchanged(changeCount).catch(reportCleanupFailure) + }) + cleanup.once('spawn', () => { + started = true + cleanup.unref() + resolve() + }) + cleanup.once('exit', (code) => { + if (code !== 0) void clearIfUnchanged(changeCount).catch(reportCleanupFailure) + }) + }) + } catch { + try { await clearIfUnchanged(changeCount) } + catch { reportCleanupFailure() } + throw new Error('pasteboard cleanup could not be started') + } + }, + } +} + +const CLEAR_IF_UNCHANGED_SCRIPT = `ObjC.import('AppKit'); +ObjC.import('Foundation'); +const args = $.NSProcessInfo.processInfo.arguments; +const expected = Number(ObjC.unwrap(args.lastObject)); +const board = $.NSPasteboard.generalPasteboard; +if (Number(board.changeCount) === expected) board.clearContents();` + +const messagePasteboard: Pick = createMessagePasteboardWriter() + interface MessageRow { text?: string attributedHex?: string @@ -30,6 +128,7 @@ interface Messages2FAOptions { now?: () => number run?: Run pasteboard?: Pick + enabled?: () => boolean } const defaultRun: Run = (file, args) => new Promise((resolve, reject) => { @@ -53,12 +152,25 @@ function appleDateToUnixMs(value: unknown): number | undefined { return Number.isFinite(unixMs) ? unixMs : undefined } +function normalize(text: string): string { + return text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase() +} + function hasVerificationContext(text: string, start: number, end: number): boolean { - const context = text.slice(Math.max(0, start - 70), Math.min(text.length, end + 70)) - .normalize('NFD') - .replace(/\p{Diacritic}/gu, '') - .toLowerCase() - return /\b(?:verification|security|authentication|authenticator|passcode|sign[ -]?in|login|one[ -]?time|otp)\b/.test(context) + const segmentStart = Math.max(text.lastIndexOf('.', start), text.lastIndexOf('!', start), text.lastIndexOf('?', start), text.lastIndexOf('\n', start), text.lastIndexOf('…', start)) + 1 + const boundaries = [text.indexOf('.', end), text.indexOf('!', end), text.indexOf('?', end), text.indexOf('\n', end), text.indexOf('…', end)].filter((i) => i >= 0) + const segmentEnd = boundaries.length ? Math.min(...boundaries) : text.length + const segment = normalize(text.slice(segmentStart, segmentEnd)) + const codeOffset = normalize(text.slice(segmentStart, start)).length + const beforeCode = segment.slice(0, codeOffset) + const context = segment + if (/(?:account\s+)?(?:ending|ends?\s+in|ending\s+with|last\s+digits?|se\s+termine\s+par)\s*\S{0,18}$/i.test(beforeCode)) return false + if (/\b\d{1,4}[/-]\d{1,2}[/-]\d{1,4}\b|\b\d{4}-\d{2}-\d{2}\b/.test(context)) { + const dates = [...context.matchAll(/\b\d{1,4}[/-]\d{1,2}[/-]\d{1,4}\b|\b\d{4}-\d{2}-\d{2}\b/g)] + if (dates.some((date) => date.index !== undefined && codeOffset >= date.index && codeOffset < date.index + date[0].length)) return false + } + const codeMarker = /\b(?:passcode|otp)\b|\byour\s+code\b|\bcode\s+is\s+your\b|\b(?:verification|security|authentication|authenticator|one[ -]?time)\s+code\b|\bcode\s+(?:de\s+)?(?:verification|security|connexion|securite|acces|confirmation)\b|\bcode\b.{0,18}\b(?:is|est)\b/ + return codeMarker.test(context) } function verificationCode(text: string): string | undefined { @@ -129,15 +241,19 @@ async function latestVerificationCode( run: Run, ): Promise { const bounds = timestampBounds(now) - const query = `SELECT coalesce(text, '') AS text, - CASE WHEN text IS NULL OR text = '' THEN coalesce(hex(attributedBody), '') ELSE '' END AS attributedHex, - date FROM message - WHERE is_from_me = 0 AND (text IS NOT NULL OR attributedBody IS NOT NULL) - AND length(coalesce(text, '')) <= 4096 - AND (attributedBody IS NULL OR length(attributedBody) <= ${MAX_ATTRIBUTED_BODY_BYTES}) - AND ((date > 1000000000000 AND date >= ${bounds.appleNanoseconds}) - OR (date <= 1000000000000 AND date >= ${bounds.appleSeconds})) - ORDER BY date DESC LIMIT ${QUERY_LIMIT};` + const query = `SELECT coalesce(m.text, '') AS text, + CASE WHEN m.text IS NULL OR m.text = '' THEN coalesce(hex(m.attributedBody), '') ELSE '' END AS attributedHex, + m.date FROM message AS m + WHERE m.is_from_me = 0 AND (m.text IS NOT NULL OR m.attributedBody IS NOT NULL) + AND length(coalesce(m.text, '')) <= 4096 + AND (m.attributedBody IS NULL OR length(m.attributedBody) <= ${MAX_ATTRIBUTED_BODY_BYTES}) + AND ((m.date > 1000000000000 AND m.date >= ${bounds.appleNanoseconds}) + OR (m.date <= 1000000000000 AND m.date >= ${bounds.appleSeconds})) + AND NOT EXISTS ( + SELECT 1 FROM chat_message_join AS cmj JOIN chat AS c ON c.ROWID = cmj.chat_id + WHERE cmj.message_id = m.ROWID AND c.style = 43 + ) + ORDER BY m.date DESC LIMIT ${QUERY_LIMIT};` const stdout = await run('/usr/bin/sqlite3', [ '-readonly', '-json', '-batch', '-cmd', 'PRAGMA query_only=ON;', @@ -165,21 +281,29 @@ export function createMessages2FAProvider(options: Messages2FAOptions = {}): Pro const databasePath = options.databasePath ?? MESSAGES_DB const now = options.now ?? Date.now const run = options.run ?? defaultRun - const pasteboard = options.pasteboard ?? pbPasteboard + const pasteboard = options.pasteboard ?? messagePasteboard + const enabled = options.enabled ?? (() => false) + let lastRequestAt: number | undefined return { channel: 'messages-2fa', commands: { copyLatest: async (payload: unknown, context?: CommandContext) => { - if (context?.loopback !== true) return { ok: false, error: 'Available only from this Mac.' } - if (!RequestSchema.safeParse(payload).success) return { ok: false, error: 'Invalid request.' } + if (context?.loopback !== true) return { ok: false, error: tr(undefined, 'messages2fa.localOnly') } + if (!enabled()) return { ok: false, error: tr(undefined, 'messages2fa.disabled') } + if (!RequestSchema.safeParse(payload).success) return { ok: false, error: tr(undefined, 'messages2fa.invalidRequest') } + const requestedAt = now() + if (lastRequestAt !== undefined && requestedAt - lastRequestAt < REQUEST_COOLDOWN_MS) { + return { ok: false, error: tr(undefined, 'messages2fa.rateLimited') } + } + lastRequestAt = requestedAt let code: string | undefined - try { code = await latestVerificationCode(databasePath, now(), run) } catch { - return { ok: false, error: 'Messages could not be read.' } + try { code = await latestVerificationCode(databasePath, requestedAt, run) } catch { + return { ok: false, error: tr(undefined, 'messages2fa.readFailed') } } - if (!code) return { ok: false, error: 'No recent verification code found.' } + if (!code) return { ok: false, error: tr(undefined, 'messages2fa.noneFound') } try { await pasteboard.write(code) } catch { - return { ok: false, error: 'The code could not be copied.' } + return { ok: false, error: tr(undefined, 'messages2fa.copyFailed') } } // Keep the OTP on the local pasteboard only; never return it over the widget bridge. return { ok: true } diff --git a/server/src/widgets/manifest.ts b/server/src/widgets/manifest.ts index 792c4306..7e14d98f 100644 --- a/server/src/widgets/manifest.ts +++ b/server/src/widgets/manifest.ts @@ -182,14 +182,14 @@ const ChannelSchema = z.string().min(1).refine((channel) => { * `widgets/`, which ships with the server and is reviewed with it. Unlike `RESERVED_CHANNELS`, the * schema alone cannot say: it does not know where a manifest came from. */ -export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'companion']) +export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'companion', 'messages-2fa']) /** * Channels any widget may read but only a built-in one may command. `brightness` changes the * screen itself: a registry widget may show the level, and the built-in widget, the admin and * the helper are what set it. Refused in an installed manifest's `commands`, like the above. */ -export const BUILTIN_ONLY_COMMANDS: ReadonlySet = new Set(['brightness']) +export const BUILTIN_ONLY_COMMANDS: ReadonlySet = new Set(['brightness', 'messages-2fa']) /** * Whether a list of `commands` covers a channel: the literal name, or a `type:*` entry for one diff --git a/server/test/config-migration.test.ts b/server/test/config-migration.test.ts index 89e52fb7..222ee116 100644 --- a/server/test/config-migration.test.ts +++ b/server/test/config-migration.test.ts @@ -183,6 +183,13 @@ describe('privacy settings on an older config', () => { it('starts off for a config that does not show the widget', () => { const cfg = migrateConfig({ version: 2, pages: [page([widget('clock')])] }) expect(cfg.privacy.claudeAccountUsage).toBe(false) + expect(cfg.privacy.messages2FA).toBe(false) + }) + + it('keeps the Messages lookup opt-in off for existing configs unless they carry the setting', () => { + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { ...DEFAULT_CONFIG.privacy, messages2FA: true } }).privacy.messages2FA).toBe(true) + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { ...DEFAULT_CONFIG.privacy, messages2FA: false } }).privacy.messages2FA).toBe(false) + expect(migrateConfig({ ...DEFAULT_CONFIG, privacy: { claudeAccountUsage: false } }).privacy.messages2FA).toBe(false) }) it('starts on for a config that already shows it on a page', () => { diff --git a/server/test/demo.test.ts b/server/test/demo.test.ts index 0874f917..b83d90a9 100644 --- a/server/test/demo.test.ts +++ b/server/test/demo.test.ts @@ -126,6 +126,9 @@ describe('demo mode', () => { const volume = providers.find((p) => p.channel === 'volume')! await volume.commands!.set({ level: 12 }) expect(((await volume.poll!()) as { level: number }).level).toBe(12) + const messages2FA = providers.find((p) => p.channel === 'messages-2fa')! + await expect(messages2FA.commands!.copyLatest(null, { loopback: true, paired: false })) + .resolves.toMatchObject({ ok: false }) const status = providers.find((p) => p.channel === 'service-status')! const probe = await status.commands!.probe({ instanceId: 'service-status-1' }) as { ok: boolean; results: unknown[] } expect(probe.ok).toBe(true) diff --git a/server/test/messages-2fa.test.ts b/server/test/messages-2fa.test.ts index 72397776..f57f2717 100644 --- a/server/test/messages-2fa.test.ts +++ b/server/test/messages-2fa.test.ts @@ -1,9 +1,11 @@ import { execFileSync } from 'node:child_process' +import { EventEmitter } from 'node:events' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { createMessages2FAProvider } from '../src/providers/messages-2fa.js' +import { createMessagePasteboardWriter, createMessages2FAProvider } from '../src/providers/messages-2fa.js' +import { tr } from '../src/i18n.js' const dirs: string[] = [] const APPLE_EPOCH_MS = 978_307_200_000 @@ -19,7 +21,9 @@ async function fixtureDatabase(sql: string): Promise { const dir = await mkdtemp(join(tmpdir(), 'fremkit-messages-2fa-')) dirs.push(dir) const path = join(dir, 'chat.db') - execFileSync('/usr/bin/sqlite3', [path, sql]) + execFileSync('/usr/bin/sqlite3', [path, `CREATE TABLE chat (ROWID INTEGER PRIMARY KEY, style INTEGER); + CREATE TABLE chat_message_join (message_id INTEGER, chat_id INTEGER); + ${sql}`]) return path } @@ -34,9 +38,9 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES ('Your verification code is 482913', NULL, 0, ${date});`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) .resolves.toEqual({ ok: true }) expect(pasteboard.write).toHaveBeenCalledWith('482913') }) @@ -47,9 +51,9 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES (NULL, CAST('Your verification code is 734206' AS BLOB), 0, ${date});`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) .resolves.toEqual({ ok: true }) expect(pasteboard.write).toHaveBeenCalledWith('734206') }) @@ -61,9 +65,9 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) .resolves.toEqual({ ok: true }) expect(pasteboard.write).toHaveBeenCalledWith('483921') }) @@ -75,9 +79,9 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES (NULL, X'${typedstreamHex}', 0, ${date});`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) .resolves.toEqual({ ok: true }) expect(pasteboard.write).toHaveBeenCalledWith('483921') }) @@ -92,9 +96,9 @@ describe('Messages 2FA provider', () => { zeroblob(${4096}), 0, ${date} - (100 - n) * 1000000000 FROM seq;`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) .resolves.toEqual({ ok: true }) expect(pasteboard.write).toHaveBeenCalledWith('483921') }) @@ -106,32 +110,33 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES ('Security code 111111', NULL, 1, ${recent}); INSERT INTO message VALUES ('Verification code 222222', NULL, 0, ${old}); - INSERT INTO message VALUES ('Order number 333333', NULL, 0, ${recent});`) + INSERT INTO message VALUES ('Order number 333333', NULL, 0, ${recent}); + INSERT INTO message VALUES ('Le digicode c''est 4821, et le login wifi…', NULL, 0, ${recent});`) const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) - .resolves.toEqual({ ok: false, error: 'No recent verification code found.' }) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) expect(pasteboard.write).not.toHaveBeenCalled() }) it('refuses remote callers without reading Messages or touching the pasteboard', async () => { const run = vi.fn(async () => '[]') const pasteboard = { write: vi.fn(async (_text: string) => {}) } - const provider = createMessages2FAProvider({ run, pasteboard }) + const provider = createMessages2FAProvider({ run, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: false })) - .resolves.toEqual({ ok: false, error: 'Available only from this Mac.' }) + await expect(provider.commands?.copyLatest(null, { loopback: false, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.localOnly') }) expect(run).not.toHaveBeenCalled() expect(pasteboard.write).not.toHaveBeenCalled() }) it('fails closed on unsupported database schemas without exposing database content', async () => { const databasePath = await fixtureDatabase('CREATE TABLE unsupported (body TEXT);') - const provider = createMessages2FAProvider({ databasePath }) + const provider = createMessages2FAProvider({ databasePath, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) - .resolves.toEqual({ ok: false, error: 'Messages could not be read.' }) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.readFailed') }) }) it('does not expose a code or raw database error if copying fails', async () => { @@ -140,9 +145,119 @@ describe('Messages 2FA provider', () => { const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); INSERT INTO message VALUES ('Passcode 765432', NULL, 0, ${date});`) const pasteboard = { write: vi.fn(async (_text: string) => { throw new Error('secret-bearing system error') }) } - const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard }) + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) - await expect(provider.commands?.copyLatest(null, { loopback: true })) - .resolves.toEqual({ ok: false, error: 'The code could not be copied.' }) + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.copyFailed') }) + }) + + it('prefers an actual code phrase and skips account endings and dates', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('A sign-in to the account ending 4821 … Your code: 739201', NULL, 0, ${recent} + 2); + INSERT INTO message VALUES ('New login on 19/10/2026 … Verification code 482913', NULL, 0, ${recent}); + INSERT INTO message VALUES ('Votre code de connexion / de sécurité est 739201', NULL, 0, ${recent} - 1); + INSERT INTO message VALUES ('Your verification code is 888888', NULL, 0, ${recent} + 1); + INSERT INTO chat (style) VALUES (43); + INSERT INTO chat_message_join VALUES (3, 1);`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('739201') + }) + + it('does not copy a verification code from a group chat', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Your verification code is 888888', NULL, 0, ${recent}); + INSERT INTO chat (style) VALUES (43); + INSERT INTO chat_message_join VALUES (1, 1);`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('recognizes a French verification-code phrase', async () => { + const now = Date.now() + const recent = Math.floor((now - APPLE_EPOCH_MS - 30_000) * 1_000_000) + const databasePath = await fixtureDatabase(`CREATE TABLE message (text TEXT, attributedBody BLOB, is_from_me INTEGER, date INTEGER); + INSERT INTO message VALUES ('Votre code de connexion / de sécurité est 739201', NULL, 0, ${recent});`) + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ databasePath, now: () => now, pasteboard, enabled: () => true }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: true }) + expect(pasteboard.write).toHaveBeenCalledWith('739201') + }) + + it('does not read Messages until its separate privacy setting is enabled', async () => { + const run = vi.fn(async () => '[]') + const pasteboard = { write: vi.fn(async (_text: string) => {}) } + const provider = createMessages2FAProvider({ run, pasteboard, enabled: () => false }) + + await expect(provider.commands?.copyLatest(null, { loopback: true, paired: false })) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.disabled') }) + expect(run).not.toHaveBeenCalled() + expect(pasteboard.write).not.toHaveBeenCalled() + }) + + it('rate-limits repeated copy requests before spawning another database query', async () => { + let now = 10_000 + const run = vi.fn(async () => '[]') + const provider = createMessages2FAProvider({ run, now: () => now, enabled: () => true }) + const context = { loopback: true, paired: false } + + await provider.commands?.copyLatest(null, context) + now += 1_000 + await expect(provider.commands?.copyLatest(null, context)) + .resolves.toEqual({ ok: false, error: tr(undefined, 'messages2fa.rateLimited') }) + expect(run).toHaveBeenCalledTimes(1) + }) +}) + +describe('Messages 2FA pasteboard expiry', () => { + it('conditionally clears the copied value if the cleanup child fails to start', async () => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(board.changeCount)') ? '41\n' : '') + const spawnCleanup = vi.fn(() => child as never) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + const result = writer.write('739201') + await vi.waitFor(() => expect(spawnCleanup).toHaveBeenCalledTimes(1)) + + child.emit('error', new Error('synthetic spawn failure')) + + await expect(result).rejects.toThrow('pasteboard cleanup could not be started') + expect(executeScript).toHaveBeenCalledTimes(2) + expect(executeScript.mock.calls[0]?.[1]).toEqual([]) + expect(executeScript.mock.calls[0]?.[2]).toBe('739201') + expect(spawnCleanup).toHaveBeenCalledWith(41) + expect(executeScript.mock.calls[1]?.[0]).toContain('board.clearContents()') + expect(executeScript.mock.calls[1]?.[1]).toEqual(['41']) + }) + + it('conditionally clears the copied value if a started cleanup child exits unsuccessfully', async () => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(board.changeCount)') ? '42\n' : '') + const spawnCleanup = vi.fn(() => child as never) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + const result = writer.write('482913') + await vi.waitFor(() => expect(spawnCleanup).toHaveBeenCalledTimes(1)) + + child.emit('spawn') + await expect(result).resolves.toBeUndefined() + child.emit('exit', 1) + await vi.waitFor(() => expect(executeScript).toHaveBeenCalledTimes(2)) + expect(executeScript.mock.calls[0]?.[1]).toEqual([]) + expect(executeScript.mock.calls[0]?.[2]).toBe('482913') + expect(spawnCleanup).toHaveBeenCalledWith(42) + expect(executeScript.mock.calls[1]?.[0]).toContain('board.clearContents()') + expect(executeScript.mock.calls[1]?.[1]).toEqual(['42']) }) }) diff --git a/server/test/widget-catalog.test.ts b/server/test/widget-catalog.test.ts index 16128900..7ea40061 100644 --- a/server/test/widget-catalog.test.ts +++ b/server/test/widget-catalog.test.ts @@ -117,6 +117,7 @@ describe('WidgetCatalog with an installed folder', () => { await into(installed, 'poke', { ...valid('poke'), commands: ['disk-map'] }) await widget('clipboard', { ...valid('clipboard'), subscriptions: ['clipboard'], commands: ['clipboard'] }) await into(installed, 'paste', { ...valid('paste'), subscriptions: ['clipboard'] }) + await into(installed, 'messages-2fa-widget', { ...valid('messages-2fa-widget'), commands: ['messages-2fa'] }) const cat = new WidgetCatalog(dir, installed) await cat.scan() expect(cat.entry('disk-map')!.manifest.commands).toEqual(['disk-map']) @@ -124,7 +125,8 @@ describe('WidgetCatalog with an installed folder', () => { expect(cat.get('poke')).toBeUndefined() expect(cat.entry('clipboard')!.manifest.subscriptions).toEqual(['clipboard']) expect(cat.get('paste')).toBeUndefined() - expect(cat.errors.map((e) => e.id).sort()).toEqual(['paste', 'peek', 'poke']) + expect(cat.get('messages-2fa-widget')).toBeUndefined() + expect(cat.errors.map((e) => e.id).sort()).toEqual(['messages-2fa-widget', 'paste', 'peek', 'poke']) expect(cat.errors.find((e) => e.id === 'peek')!.error).toContain('disk-map') expect(cat.errors.find((e) => e.id === 'paste')!.error).toContain('clipboard') }) diff --git a/server/test/widget-manifest.test.ts b/server/test/widget-manifest.test.ts index 60e4f34f..66091b08 100644 --- a/server/test/widget-manifest.test.ts +++ b/server/test/widget-manifest.test.ts @@ -243,6 +243,11 @@ describe('channels a manifest may not ask for', () => { expect(builtinOnlyChannels({ ...m, commands: [] })).toEqual(['brightness']) }) + it('reserves the Messages 2FA command for built-in widgets', () => { + const m = ManifestSchema.parse({ ...base, commands: ['messages-2fa'] }) + expect(builtinOnlyChannels(m)).toEqual(['messages-2fa']) + }) + it('names the reason', () => { const parsed = ManifestSchema.safeParse({ ...base, subscriptions: ['config'] }) expect(parsed.success).toBe(false) diff --git a/ui/src/admin/settings/PrivacyPane.vue b/ui/src/admin/settings/PrivacyPane.vue index ede790b0..9330f6a1 100644 --- a/ui/src/admin/settings/PrivacyPane.vue +++ b/ui/src/admin/settings/PrivacyPane.vue @@ -35,6 +35,9 @@ function setCodexSource(source: CodexSource, on: boolean): void { function setMacmonTemperature(on: boolean): void { s.apply((c) => { c.privacy.macmonTemperature = on }) } +function setMessages2FA(on: boolean): void { + s.apply((c) => { c.privacy.messages2FA = on }) +} /** * Off, the server leaves the account e-mail out of every snapshot it publishes; this box does * not hide it in a widget, it decides whether any widget is sent it at all. @@ -79,6 +82,10 @@ function setShowAccountEmail(on: boolean): void { :label="t('admin.inspector.screen.macmonTemperature')" @update:model-value="setMacmonTemperature($event)" />

{{ t('admin.inspector.screen.macmonTemperature.hint') }}

+ +

{{ t('admin.inspector.screen.messages2FA.hint') }}

diff --git a/ui/src/shared/locales/en.ts b/ui/src/shared/locales/en.ts index c14194c7..ff36e93d 100644 --- a/ui/src/shared/locales/en.ts +++ b/ui/src/shared/locales/en.ts @@ -404,6 +404,8 @@ export const en: Record = { 'admin.inspector.screen.accountEmail.hint': 'Off by default. Widgets that show an account then get the plan and the sign-in method, never the e-mail address: the server leaves it out of what it sends. Once on, the address is sent to every widget that reads an account channel — a widget installed from the marketplace included — and appears on the screen.', 'admin.inspector.screen.macmonTemperature': 'Read the CPU temperature with macmon', 'admin.inspector.screen.macmonTemperature.hint': 'Off by default. macmon is a third-party open-source tool that Fremkit does not install. Install it yourself with brew install macmon. On Apple Silicon, the server runs only /opt/homebrew/bin/macmon or /usr/local/bin/macmon every 10 seconds for one sample. The reading stays on this Mac. If unavailable, Fremkit shows the system temperature when known.', + 'admin.inspector.screen.messages2FA': 'Allow Messages verification-code lookup', + 'admin.inspector.screen.messages2FA.hint': 'Off by default, including after an upgrade. When enabled, an eligible built-in widget can request only recent incoming Messages after you tap copy. macOS Full Disk Access is also required; granting it does not enable this setting. The copied code is marked concealed and temporary, stays on this Mac, and Fremkit schedules a conditional clear after 60 seconds. If macOS refuses both the scheduled clear and an immediate retry, the code may remain on the clipboard.', 'admin.inspector.screen.about': 'About', 'admin.inspector.screen.about.version': 'Fremkit {version}', 'admin.inspector.screen.labs': 'Experimental features', diff --git a/ui/src/shared/locales/fr.ts b/ui/src/shared/locales/fr.ts index ccc2f687..5b7f4876 100644 --- a/ui/src/shared/locales/fr.ts +++ b/ui/src/shared/locales/fr.ts @@ -404,6 +404,8 @@ export const fr: Record = { 'admin.inspector.screen.accountEmail.hint': 'Désactivé par défaut. Les widgets qui affichent un compte reçoivent alors le forfait et le mode de connexion, jamais l’adresse e-mail : le serveur la retire de ce qu’il envoie. Une fois activé, l’adresse est envoyée à chaque widget qui lit un canal de compte — y compris un widget installé depuis la marketplace — et apparaît à l’écran.', 'admin.inspector.screen.macmonTemperature': 'Lire la température du CPU avec macmon', 'admin.inspector.screen.macmonTemperature.hint': 'Désactivé par défaut. macmon est un outil tiers libre que Fremkit n’installe pas. Installez-le vous-même avec brew install macmon. Sur Apple Silicon, le serveur lance uniquement /opt/homebrew/bin/macmon ou /usr/local/bin/macmon toutes les 10 secondes pour une mesure. Celle-ci reste sur ce Mac. Si indisponible, Fremkit affiche la température système lorsqu’elle est connue.', + 'admin.inspector.screen.messages2FA': 'Autoriser la recherche de codes dans Messages', + 'admin.inspector.screen.messages2FA.hint': 'Désactivé par défaut, y compris après une mise à niveau. Une fois activé, un widget intégré autorisé peut demander uniquement les messages reçus récemment lorsque vous touchez Copier. L’accès complet au disque de macOS est également nécessaire ; l’accorder n’active pas ce réglage. Le code copié est marqué comme masqué et temporaire, reste sur ce Mac, et Fremkit programme un effacement conditionnel après 60 secondes. Si macOS refuse cet effacement et une nouvelle tentative immédiate, le code peut rester dans le presse-papiers.', 'admin.inspector.screen.about': 'À propos', 'admin.inspector.screen.about.version': 'Fremkit {version}', 'admin.inspector.screen.labs': 'Fonctions expérimentales', diff --git a/ui/src/shared/types.ts b/ui/src/shared/types.ts index 0e1e8f49..41913ec0 100644 --- a/ui/src/shared/types.ts +++ b/ui/src/shared/types.ts @@ -144,6 +144,8 @@ export interface Privacy { codexHistorySources: ('cli' | 'vscode' | 'exec' | 'appServer' | 'subAgent' | 'subAgentReview' | 'subAgentCompact' | 'subAgentThreadSpawn' | 'subAgentOther' | 'unknown')[] /** Use the optional local macmon executable for Apple Silicon CPU temperature. */ macmonTemperature: boolean + /** Permit an explicit local request to read a recent Messages verification code. */ + messages2FA?: boolean } /** From 306a544c4e5e54beace0e74dd199f64ec57413c4 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 23:32:01 +0200 Subject: [PATCH 06/24] fix: preserve pasteboard ownership token Co-Authored-By: Claude Opus 5.5 --- server/src/providers/messages-2fa.ts | 10 ++- server/test/messages-2fa.test.ts | 106 ++++++++++++++++++++++++++- 2 files changed, 110 insertions(+), 6 deletions(-) diff --git a/server/src/providers/messages-2fa.ts b/server/src/providers/messages-2fa.ts index 5ce79424..34f3c74e 100644 --- a/server/src/providers/messages-2fa.ts +++ b/server/src/providers/messages-2fa.ts @@ -28,11 +28,13 @@ const data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile; const value = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding); if (!value) throw new Error('invalid input'); const board = $.NSPasteboard.generalPasteboard; -board.prepareForNewContentsWithOptions($.NSPasteboardContentsCurrentHostOnly); +const ownedChangeCount = Number(board.prepareForNewContentsWithOptions($.NSPasteboardContentsCurrentHostOnly)); +if (!Number.isSafeInteger(ownedChangeCount)) throw new Error('pasteboard write failed'); if (!board.setStringForType(value, $.NSPasteboardTypeString)) throw new Error('pasteboard write failed'); -board.setDataForType($.NSData.data, 'org.nspasteboard.ConcealedType'); -board.setDataForType($.NSData.data, 'org.nspasteboard.TransientType'); -String(board.changeCount);` +if (!board.setDataForType($.NSData.data, 'org.nspasteboard.ConcealedType')) throw new Error('pasteboard write failed'); +if (!board.setDataForType($.NSData.data, 'org.nspasteboard.TransientType')) throw new Error('pasteboard write failed'); +if (Number(board.changeCount) !== ownedChangeCount) throw new Error('pasteboard write failed'); +String(ownedChangeCount);` const CLEAR_CODE_SCRIPT = `ObjC.import('AppKit'); ObjC.import('Foundation'); diff --git a/server/test/messages-2fa.test.ts b/server/test/messages-2fa.test.ts index f57f2717..9f8be977 100644 --- a/server/test/messages-2fa.test.ts +++ b/server/test/messages-2fa.test.ts @@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { runInNewContext } from 'node:vm' import { afterEach, describe, expect, it, vi } from 'vitest' import { createMessagePasteboardWriter, createMessages2FAProvider } from '../src/providers/messages-2fa.js' import { tr } from '../src/i18n.js' @@ -223,9 +224,110 @@ describe('Messages 2FA provider', () => { }) describe('Messages 2FA pasteboard expiry', () => { + it.each(['after-string', 'after-concealed-marker', 'after-transient-marker', 'before-final-change-count'] as const)( + 'does not arm cleanup for a new clipboard owner when ownership changes %s', + async (interleave) => { + let changeCount = 40 + let owned = false + let writes = 0 + let value = '' + const board = { + prepareForNewContentsWithOptions: () => { owned = true; return changeCount }, + setStringForType: (next: string) => { + if (!owned) return false + value = next + if (interleave === 'after-string') { owned = false; value = 'unrelated clipboard'; changeCount += 1 } + return true + }, + setDataForType: () => { + if (!owned) return false + writes += 1 + if (interleave === 'after-concealed-marker' && writes === 1) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + if (interleave === 'after-transient-marker' && writes === 2) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + return true + }, + get changeCount() { + if (interleave === 'before-final-change-count' && writes === 2) { + owned = false + value = 'unrelated clipboard' + changeCount += 1 + } + return changeCount + }, + } + const executeScript = vi.fn(async (script: string, _args: string[], stdin?: string) => { + const context = { + ObjC: { import: (_framework: string) => {} }, + $: { + NSFileHandle: { fileHandleWithStandardInput: { readDataToEndOfFile: Buffer.from(stdin ?? '') } }, + NSString: { alloc: { initWithDataEncoding: (data: Buffer) => data.toString('utf8') } }, + NSUTF8StringEncoding: 4, + NSPasteboard: { get generalPasteboard() { return board } }, + NSPasteboardContentsCurrentHostOnly: 1, + NSPasteboardTypeString: 'public.utf8-plain-text', + NSData: { data: Buffer.alloc(0) }, + }, + } + return `${runInNewContext(script, context) ?? ''}\n` + }) + const spawnCleanup = vi.fn(() => { + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + queueMicrotask(() => child.emit('spawn')) + return child as never + }) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + + await expect(writer.write('482913')).rejects.toThrow('pasteboard write failed') + expect(spawnCleanup).not.toHaveBeenCalled() + expect(value).toBe('unrelated clipboard') + }, + ) + + it('uses the acquired ownership count for cleanup after all marker writes succeed', async () => { + let changeCount = 70 + const board = { + prepareForNewContentsWithOptions: () => changeCount, + setStringForType: () => true, + setDataForType: () => true, + get changeCount() { return changeCount }, + } + const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) + const executeScript = vi.fn(async (script: string, _args: string[], stdin?: string) => { + const context = { + ObjC: { import: (_framework: string) => {} }, + $: { + NSFileHandle: { fileHandleWithStandardInput: { readDataToEndOfFile: Buffer.from(stdin ?? '') } }, + NSString: { alloc: { initWithDataEncoding: (data: Buffer) => data.toString('utf8') } }, + NSUTF8StringEncoding: 4, + NSPasteboard: { get generalPasteboard() { return board } }, + NSPasteboardContentsCurrentHostOnly: 1, + NSPasteboardTypeString: 'public.utf8-plain-text', + NSData: { data: Buffer.alloc(0) }, + }, + } + return `${runInNewContext(script, context) ?? ''}\n` + }) + const spawnCleanup = vi.fn(() => { + queueMicrotask(() => child.emit('spawn')) + return child as never + }) + const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) + + await expect(writer.write('482913')).resolves.toBeUndefined() + expect(spawnCleanup).toHaveBeenCalledWith(70) + }) + it('conditionally clears the copied value if the cleanup child fails to start', async () => { const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) - const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(board.changeCount)') ? '41\n' : '') + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(ownedChangeCount)') ? '41\n' : '') const spawnCleanup = vi.fn(() => child as never) const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) const result = writer.write('739201') @@ -244,7 +346,7 @@ describe('Messages 2FA pasteboard expiry', () => { it('conditionally clears the copied value if a started cleanup child exits unsuccessfully', async () => { const child = Object.assign(new EventEmitter(), { unref: vi.fn() }) - const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(board.changeCount)') ? '42\n' : '') + const executeScript = vi.fn(async (script: string, _args: string[], _stdin?: string) => script.includes('String(ownedChangeCount)') ? '42\n' : '') const spawnCleanup = vi.fn(() => child as never) const writer = createMessagePasteboardWriter({ executeScript, spawnCleanup }) const result = writer.write('482913') From 3632a1d840ae051a011781a1031f950d66082fe8 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 05:45:20 +0200 Subject: [PATCH 07/24] Add Vercel deployment connection provider --- server/src/connections/types/index.ts | 3 +- server/src/connections/types/vercel.ts | 42 ++++++++++++ server/src/i18n.ts | 15 +++++ server/src/providers/vercel.ts | 88 ++++++++++++++++++++++++ server/test/vercel.test.ts | 92 ++++++++++++++++++++++++++ 5 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 server/src/connections/types/vercel.ts create mode 100644 server/src/providers/vercel.ts create mode 100644 server/test/vercel.test.ts diff --git a/server/src/connections/types/index.ts b/server/src/connections/types/index.ts index 379f153f..b3c054d5 100644 --- a/server/src/connections/types/index.ts +++ b/server/src/connections/types/index.ts @@ -3,9 +3,10 @@ import { bambuType } from './bambu.js' import { githubType } from './github.js' import { icsType } from './ics.js' import { synologyType } from './synology.js' +import { vercelType } from './vercel.js' import type { ConnectionType } from '../types.js' /** Every connection type the server ships with. */ export function defaultConnectionTypes(): ConnectionType[] { - return [azureDevOpsType, bambuType, githubType, icsType, synologyType] + return [azureDevOpsType, bambuType, githubType, icsType, synologyType, vercelType] } diff --git a/server/src/connections/types/vercel.ts b/server/src/connections/types/vercel.ts new file mode 100644 index 00000000..e8b156c1 --- /dev/null +++ b/server/src/connections/types/vercel.ts @@ -0,0 +1,42 @@ +import { tr } from '../../i18n.js' +import type { ConnectionType, TestResult } from '../types.js' +import { VERCEL_API, VERCEL_TIMEOUT_MS, createVercelProvider } from '../../providers/vercel.js' +import type { VercelDeps } from '../../providers/vercel.js' +import { USER_AGENT } from '../../version.js' + +export const vercelType: ConnectionType = { + id: 'vercel', + name: 'Vercel', + description: { fr: 'Déploiements récents des comptes Vercel', en: 'Recent deployments from Vercel accounts' }, + icon: 'triangle', + fields: [ + { key: 'token', label: { fr: 'Jeton d’accès', en: 'Access token' }, secret: true, required: true, + help: { fr: 'Le jeton reste dans le coffre de secrets de Fremkit et n’est envoyé qu’à api.vercel.com.', en: 'The token stays in Fremkit’s secret store and is sent only to api.vercel.com.' } }, + { key: 'teamId', label: { fr: 'ID d’équipe (facultatif)', en: 'Team ID (optional)' }, + help: { fr: 'Laissez vide pour le compte personnel. Pour les déploiements d’équipe, saisissez son ID.', en: 'Leave blank for the personal account. Enter a team ID to list team deployments.' } }, + ], + channelPrefix: 'vercel', + async test(_fields, secrets, deps: VercelDeps = {}): Promise { + const token = secrets.token?.trim() ?? '' + if (!token) return { ok: false, error: tr(undefined, 'vercel.missingToken') } + const fetchFn = deps.fetchFn ?? fetch + try { + const response = await fetchFn(`${VERCEL_API}/v2/user`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, + signal: AbortSignal.timeout(VERCEL_TIMEOUT_MS), + }) + if (response.ok) { + const body = await response.json().catch(() => ({})) as { user?: { username?: unknown }; username?: unknown } + const username = body.user?.username ?? body.username + return { ok: true, detail: tr(undefined, 'vercel.connected', { account: typeof username === 'string' ? username : '?' }) } + } + await response.body?.cancel().catch(() => {}) + if (response.status === 401 || response.status === 403) return { ok: false, error: tr(undefined, 'vercel.tokenRefused') } + if (response.status === 429) return { ok: false, error: tr(undefined, 'vercel.rateLimited') } + return { ok: false, error: tr(undefined, 'vercel.unexpected', { status: response.status }) } + } catch { + return { ok: false, error: tr(undefined, 'vercel.unreachable') } + } + }, + createProvider: (ctx) => createVercelProvider(ctx), +} diff --git a/server/src/i18n.ts b/server/src/i18n.ts index 227c250f..84954f0f 100644 --- a/server/src/i18n.ts +++ b/server/src/i18n.ts @@ -236,6 +236,14 @@ const fr = { 'Connecté à GitHub en tant que {login} · jeton à granularité fine : notifications indisponibles, revues et Actions OK', 'github.privateRepo': 'privé', + // connections/types/vercel.ts + 'vercel.missingToken': 'jeton Vercel manquant', + 'vercel.unreachable': 'Vercel injoignable', + 'vercel.tokenRefused': 'jeton Vercel refusé', + 'vercel.rateLimited': 'quota Vercel atteint ; réessayez plus tard', + 'vercel.unexpected': 'réponse Vercel inattendue (HTTP {status})', + 'vercel.connected': 'Connecté à Vercel en tant que {account}', + // providers/bambu.ts — `stg_cur`, the printer's current stage 'bambu.stage.-1': 'Au repos', 'bambu.stage.0': 'Impression', @@ -532,6 +540,13 @@ const en: Record = { 'Connected to GitHub as {login} · fine-grained token: notifications unavailable, reviews and Actions OK', 'github.privateRepo': 'private', + 'vercel.missingToken': 'Vercel token missing', + 'vercel.unreachable': 'Vercel unreachable', + 'vercel.tokenRefused': 'Vercel token refused', + 'vercel.rateLimited': 'Vercel rate limit reached; try again later', + 'vercel.unexpected': 'unexpected Vercel response (HTTP {status})', + 'vercel.connected': 'Connected to Vercel as {account}', + 'bambu.stage.-1': 'Idle', 'bambu.stage.0': 'Printing', 'bambu.stage.1': 'Preheating the bed', diff --git a/server/src/providers/vercel.ts b/server/src/providers/vercel.ts new file mode 100644 index 00000000..2a68287c --- /dev/null +++ b/server/src/providers/vercel.ts @@ -0,0 +1,88 @@ +import type { ConnectionProviderContext } from '../connections/types.js' +import type { Provider } from './types.js' +import { USER_AGENT } from '../version.js' +import { readJsonCapped } from '../net/json.js' + +export const VERCEL_API = 'https://api.vercel.com' +export const VERCEL_TIMEOUT_MS = 10_000 +export const VERCEL_POLL_MS = 60_000 + +export interface VercelDeployment { + id: string + name: string + url: string | null + state: string + createdAt: number + target: string | null +} + +export interface VercelSnapshot { + deployments: VercelDeployment[] + error?: 'unconfigured' | 'unauthorized' | 'rate-limited' | 'offline' +} + +export interface VercelDeps { fetchFn?: typeof fetch; now?: () => number } + +const stateLabel = (value: unknown): string => { + const state = typeof value === 'string' ? value.toUpperCase() : '' + return ['BUILDING', 'ERROR', 'INITIALIZING', 'QUEUED', 'READY', 'CANCELED', 'DEPLOYING'].includes(state) + ? state + : 'UNKNOWN' +} + +function parseDeployment(value: unknown): VercelDeployment | null { + if (!value || typeof value !== 'object') return null + const item = value as Record + const id = typeof item.uid === 'string' ? item.uid : typeof item.id === 'string' ? item.id : '' + const name = typeof item.name === 'string' ? item.name : '' + if (!id || !name) return null + const rawUrl = typeof item.url === 'string' ? item.url : null + const url = rawUrl && /^[A-Za-z0-9.-]+$/.test(rawUrl) ? rawUrl : null + const createdAt = Number(item.createdAt ?? item.created) + return { + id: id.slice(0, 200), + name: name.slice(0, 200), + url, + state: stateLabel(item.state ?? item.readyState), + createdAt: Number.isFinite(createdAt) && createdAt >= 0 ? createdAt : 0, + target: typeof item.target === 'string' ? item.target.slice(0, 40) : null, + } +} + +/** Read-only deployment snapshots for a Vercel personal account or selected team. */ +export function createVercelProvider(ctx: ConnectionProviderContext, deps: VercelDeps = {}): Provider { + const fetchFn = deps.fetchFn ?? fetch + const token = ctx.secrets.token?.trim() ?? '' + const teamId = ctx.fields.teamId?.trim() ?? '' + let lastGood: VercelDeployment[] = [] + + return { + channel: ctx.channel, + intervalMs: VERCEL_POLL_MS, + async poll() { + if (!token) return { deployments: lastGood, error: 'unconfigured' } + const query = new URLSearchParams({ limit: '10' }) + if (teamId) query.set('teamId', teamId) + try { + const response = await fetchFn(`${VERCEL_API}/v6/deployments?${query}`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, + signal: AbortSignal.timeout(VERCEL_TIMEOUT_MS), + }) + if (!response.ok) { + await response.body?.cancel().catch(() => {}) + const error = response.status === 401 || response.status === 403 ? 'unauthorized' + : response.status === 429 ? 'rate-limited' : 'offline' + return { deployments: lastGood, error } + } + const body = await readJsonCapped(response).catch(() => undefined) as { deployments?: unknown } | undefined + if (!Array.isArray(body?.deployments)) return { deployments: lastGood, error: 'offline' } + const parsed = body.deployments.slice(0, 10).map(parseDeployment) + if (parsed.some((row) => row === null)) return { deployments: lastGood, error: 'offline' } + lastGood = parsed.filter((row): row is VercelDeployment => row !== null) + return { deployments: lastGood } + } catch { + return { deployments: lastGood, error: 'offline' } + } + }, + } +} diff --git a/server/test/vercel.test.ts b/server/test/vercel.test.ts new file mode 100644 index 00000000..34b31d53 --- /dev/null +++ b/server/test/vercel.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest' +import { defaultConnectionTypes } from '../src/connections/types/index.js' +import { vercelType } from '../src/connections/types/vercel.js' +import { createVercelProvider } from '../src/providers/vercel.js' + +const deployment = { + uid: 'dpl_123', + name: 'example-site', + url: 'example-site-abc.vercel.app', + state: 'READY', + createdAt: 1_800_000_000_000, + target: 'production', +} +const context = () => ({ id: 'primary', channel: 'vercel:primary', fields: { teamId: 'team_123' }, secrets: { token: 'private-test-token' } }) +const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } }) + +describe('Vercel connection and deployment provider', () => { + it('registers a secret-backed connection type', () => { + expect(defaultConnectionTypes().some((type) => type.id === 'vercel')).toBe(true) + expect(vercelType.fields.find((field) => field.key === 'token')).toMatchObject({ secret: true, required: true }) + }) + + it('fetches a bounded recent deployment list from the fixed API host and maps safe fields', async () => { + const requests: { url: string; authorization: string | null }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + requests.push({ url, authorization: new Headers(init?.headers).get('authorization') }) + return json({ deployments: [deployment] }) + }) as typeof fetch + const provider = createVercelProvider(context(), { fetchFn }) + + expect(await provider.poll!()).toEqual({ deployments: [{ id: 'dpl_123', name: 'example-site', url: 'example-site-abc.vercel.app', state: 'READY', createdAt: 1_800_000_000_000, target: 'production' }] }) + expect(requests).toEqual([{ url: 'https://api.vercel.com/v6/deployments?limit=10&teamId=team_123', authorization: 'Bearer private-test-token' }]) + }) + + it('returns an offline-safe snapshot for an unauthorized token without echoing it', async () => { + const provider = createVercelProvider(context(), { fetchFn: (async () => json({ error: { code: 'forbidden' } }, 403)) as typeof fetch }) + const snapshot = await provider.poll!() as { deployments: unknown[]; error?: string } + expect(snapshot).toEqual({ deployments: [], error: 'unauthorized' }) + expect(JSON.stringify(snapshot)).not.toContain('private-test-token') + }) + + it('retains the last valid deployments when a later fetch fails or returns malformed JSON', async () => { + const failures: Array<{ label: string; response?: Response; error: 'unauthorized' | 'rate-limited' | 'offline' }> = [ + { label: 'unauthorized', response: json({ error: { code: 'forbidden' } }, 401), error: 'unauthorized' }, + { label: 'rate limited', response: json({ error: { code: 'rate_limited' } }, 429), error: 'rate-limited' }, + { label: 'malformed response', response: json({ deployments: 'not-an-array' }), error: 'offline' }, + { label: 'malformed deployment entry', response: json({ deployments: [{}] }), error: 'offline' }, + { label: 'offline', error: 'offline' }, + ] + const expected = [{ id: 'dpl_123', name: 'example-site', url: 'example-site-abc.vercel.app', state: 'READY', createdAt: 1_800_000_000_000, target: 'production' }] + + for (const failure of failures) { + let calls = 0 + const fetchFn = (async () => { + calls++ + if (calls === 1) return json({ deployments: [deployment] }) + if (failure.response) return failure.response + throw new Error('network unavailable') + }) as typeof fetch + const provider = createVercelProvider(context(), { fetchFn }) + + await provider.poll!() + expect(await provider.poll!(), failure.label).toEqual({ deployments: expected, error: failure.error }) + } + }) + + it('clears retained deployments after a valid empty response', async () => { + let calls = 0 + const fetchFn = (async () => { + calls++ + return calls === 1 ? json({ deployments: [deployment] }) : json({ deployments: [] }) + }) as typeof fetch + const provider = createVercelProvider(context(), { fetchFn }) + + expect(await provider.poll!()).toMatchObject({ deployments: [{ id: 'dpl_123' }] }) + expect(await provider.poll!()).toEqual({ deployments: [] }) + }) + + it('tests credentials against Vercel and keeps the token out of connection feedback', async () => { + const requests: { url: string; authorization: string | null }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + requests.push({ url: String(input), authorization: new Headers(init?.headers).get('authorization') }) + return json({ user: { username: 'livio' } }) + }) as typeof fetch + const result = await vercelType.test({}, { token: 'private-test-token' }, { fetchFn }) + + expect(result).toEqual({ ok: true, detail: expect.stringContaining('livio') }) + expect(JSON.stringify(result)).not.toContain('private-test-token') + expect(requests).toEqual([{ url: 'https://api.vercel.com/v2/user', authorization: 'Bearer private-test-token' }]) + }) +}) From b25e8a4e45c1d8d3a24a8bdf0780e3e826631d05 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 12:35:32 +0200 Subject: [PATCH 08/24] feat: add ShellSmith command suggestion provider --- server/src/connections/types/index.ts | 3 +- .../connections/types/openai-shellsmith.ts | 59 +++++++ server/src/i18n.ts | 15 ++ server/src/providers/openai-shellsmith.ts | 152 +++++++++++++++++ server/test/connections.test.ts | 1 + server/test/shellsmith.test.ts | 158 ++++++++++++++++++ 6 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 server/src/connections/types/openai-shellsmith.ts create mode 100644 server/src/providers/openai-shellsmith.ts create mode 100644 server/test/shellsmith.test.ts diff --git a/server/src/connections/types/index.ts b/server/src/connections/types/index.ts index b3c054d5..8a41bd8f 100644 --- a/server/src/connections/types/index.ts +++ b/server/src/connections/types/index.ts @@ -4,9 +4,10 @@ import { githubType } from './github.js' import { icsType } from './ics.js' import { synologyType } from './synology.js' import { vercelType } from './vercel.js' +import { openAIShellsmithType } from './openai-shellsmith.js' import type { ConnectionType } from '../types.js' /** Every connection type the server ships with. */ export function defaultConnectionTypes(): ConnectionType[] { - return [azureDevOpsType, bambuType, githubType, icsType, synologyType, vercelType] + return [azureDevOpsType, bambuType, githubType, icsType, synologyType, vercelType, openAIShellsmithType] } diff --git a/server/src/connections/types/openai-shellsmith.ts b/server/src/connections/types/openai-shellsmith.ts new file mode 100644 index 00000000..120842a2 --- /dev/null +++ b/server/src/connections/types/openai-shellsmith.ts @@ -0,0 +1,59 @@ +import { tr } from '../../i18n.js' +import type { ConnectionType, TestResult } from '../types.js' +import { GROQ_API, OPENAI_API, OPENAI_TIMEOUT_MS, createOpenAIShellsmithProvider } from '../../providers/openai-shellsmith.js' +import type { OpenAIShellsmithDeps } from '../../providers/openai-shellsmith.js' +import { USER_AGENT } from '../../version.js' +import { readJsonCapped } from '../../net/json.js' + +const ModelSchema = /^[A-Za-z0-9._:/-]{1,100}$/ +const providerFor = (fields: Record): 'openai' | 'groq' | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' + ? 'openai' : fields.provider === 'groq' ? 'groq' : null + +export const openAIShellsmithType: ConnectionType = { + id: 'openai-shellsmith', + name: 'OpenAI-compatible AI', + description: { fr: 'Suggestions de commandes via une API compatible OpenAI', en: 'Command suggestions through an OpenAI-compatible API' }, + icon: 'sparkles', + secretBindings: ['provider'], + fields: [ + { key: 'provider', label: { fr: 'Fournisseur API', en: 'API provider' }, options: ['openai', 'groq'], + help: { fr: 'Le jeton est envoyé uniquement à l’hôte fixe du fournisseur choisi. Sans choix, OpenAI est utilisé.', en: 'The token is sent only to the selected provider’s fixed host. OpenAI is used when no choice is saved.' } }, + { key: 'model', label: { fr: 'ID du modèle', en: 'Model ID' }, required: true, + placeholder: 'openai/gpt-oss-20b', + help: { fr: 'Saisissez un modèle activé pour votre compte. Groq accepte notamment openai/gpt-oss-20b.', en: 'Enter a model enabled for your account. Groq supports openai/gpt-oss-20b, among others.' } }, + { key: 'token', label: { fr: 'Clé API', en: 'API key' }, secret: true, required: true, + help: { fr: 'La clé reste dans le coffre de secrets. Les requêtes ne partent qu’après une action explicite.', en: 'The key stays in Fremkit’s secret store. Requests are sent only after an explicit action.' } }, + ], + channelPrefix: 'openai-shellsmith', + async test(fields, secrets, deps: OpenAIShellsmithDeps = {}): Promise { + const provider = providerFor(fields) + const model = fields.model?.trim() ?? '' + const token = secrets.token?.trim() ?? '' + if (!provider || !ModelSchema.test(model) || !token) return { ok: false, error: tr(undefined, 'shellsmith.unconfigured') } + try { + const response = provider === 'groq' + ? await (deps.fetchFn ?? fetch)(`${GROQ_API}/models`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, + signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), + }) + : await (deps.fetchFn ?? fetch)(`${OPENAI_API}/models/${encodeURIComponent(model)}`, { + headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, + signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), + }) + if (!response.ok) { + await response.body?.cancel().catch(() => {}) + return { ok: false, error: response.status === 401 || response.status === 403 ? tr(undefined, 'shellsmith.tokenRefused') + : response.status === 429 ? tr(undefined, 'shellsmith.rateLimited') + : response.status === 404 ? tr(undefined, 'shellsmith.modelUnavailable') + : tr(undefined, 'shellsmith.unexpected', { status: response.status }) } + } + const body = await readJsonCapped(response).catch(() => undefined) as { id?: unknown; data?: Array<{ id?: unknown }> } | undefined + const modelAvailable = provider === 'groq' + ? body?.data?.some((item) => item.id === model) === true + : body?.id === model + return modelAvailable ? { ok: true, detail: tr(undefined, 'shellsmith.connected', { model }) } + : { ok: false, error: tr(undefined, 'shellsmith.unexpected', { status: 200 }) } + } catch { return { ok: false, error: tr(undefined, 'shellsmith.unreachable') } } + }, + createProvider: (ctx) => createOpenAIShellsmithProvider(ctx), +} diff --git a/server/src/i18n.ts b/server/src/i18n.ts index 84954f0f..f795a4bc 100644 --- a/server/src/i18n.ts +++ b/server/src/i18n.ts @@ -243,6 +243,14 @@ const fr = { 'vercel.rateLimited': 'quota Vercel atteint ; réessayez plus tard', 'vercel.unexpected': 'réponse Vercel inattendue (HTTP {status})', 'vercel.connected': 'Connecté à Vercel en tant que {account}', + // connections/types/openai-shellsmith.ts + 'shellsmith.unconfigured': 'connexion IA incomplète', + 'shellsmith.unreachable': 'fournisseur IA injoignable', + 'shellsmith.tokenRefused': 'clé API refusée', + 'shellsmith.rateLimited': 'quota atteint ; réessayez plus tard', + 'shellsmith.modelUnavailable': 'modèle introuvable ou inaccessible', + 'shellsmith.unexpected': 'réponse inattendue du fournisseur (HTTP {status})', + 'shellsmith.connected': 'Modèle IA vérifié : {model}', // providers/bambu.ts — `stg_cur`, the printer's current stage 'bambu.stage.-1': 'Au repos', @@ -546,6 +554,13 @@ const en: Record = { 'vercel.rateLimited': 'Vercel rate limit reached; try again later', 'vercel.unexpected': 'unexpected Vercel response (HTTP {status})', 'vercel.connected': 'Connected to Vercel as {account}', + 'shellsmith.unconfigured': 'AI connection is incomplete', + 'shellsmith.unreachable': 'AI provider is unreachable', + 'shellsmith.tokenRefused': 'API key refused', + 'shellsmith.rateLimited': 'rate limit reached; try again later', + 'shellsmith.modelUnavailable': 'model not found or unavailable', + 'shellsmith.unexpected': 'unexpected provider response (HTTP {status})', + 'shellsmith.connected': 'AI model verified: {model}', 'bambu.stage.-1': 'Idle', 'bambu.stage.0': 'Printing', diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts new file mode 100644 index 00000000..5024bbdf --- /dev/null +++ b/server/src/providers/openai-shellsmith.ts @@ -0,0 +1,152 @@ +import { z } from 'zod' +import type { ConnectionProviderContext } from '../connections/types.js' +import { pbPasteboard, type Pasteboard } from './clipboard.js' +import type { CommandContext, Provider } from './types.js' +import { USER_AGENT } from '../version.js' +import { readJsonCapped } from '../net/json.js' + +export const OPENAI_API = 'https://api.openai.com/v1' +export const GROQ_API = 'https://api.groq.com/openai/v1' +export const OPENAI_TIMEOUT_MS = 25_000 +export const SHELLSMITH_MAX_REQUEST_CHARS = 1000 +export const SHELLSMITH_MAX_COMMAND_CHARS = 2000 + +const ModelSchema = z.string().trim().min(1).max(100).regex(/^[A-Za-z0-9._:/-]+$/) +// The dashboard stamps every widget command with the sending widget instance id. +const INSTANCE = { instanceId: z.string().min(1).max(200).optional() } +const RequestPayload = z.strictObject({ ...INSTANCE, request: z.string().trim().min(1).max(SHELLSMITH_MAX_REQUEST_CHARS) }) +const CopyPayload = z.strictObject({ ...INSTANCE, command: z.string().trim().min(1).max(SHELLSMITH_MAX_COMMAND_CHARS) }) + +interface ResponsesBody { + output?: Array<{ content?: Array<{ type?: unknown; text?: unknown }> }> +} +interface ChatBody { + choices?: Array<{ message?: { content?: unknown } }> +} +type CompletionResult = + | { ok: true; content: string } + | { ok: false; error: 'unauthorized' | 'rate-limited' | 'unavailable' | 'invalid-response' } + +export interface OpenAIShellsmithDeps { + fetchFn?: typeof fetch + pasteboard?: Pasteboard +} + +type ApiProvider = 'openai' | 'groq' +const providerFor = (fields: Record): ApiProvider | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' + ? 'openai' : fields.provider === 'groq' ? 'groq' : null +const apiFor = (provider: ApiProvider): string => provider === 'groq' ? GROQ_API : OPENAI_API +async function chatCompletion( + fetchFn: typeof fetch, + api: string, + token: string, + model: string, + prompt: string, +): Promise { + const reasoningModel = model.startsWith('openai/gpt-oss-') + let response: Response + try { + response = await fetchFn(`${api}/chat/completions`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': USER_AGENT, + }, + body: JSON.stringify({ + model, + messages: [{ role: 'user', content: prompt }], + max_completion_tokens: reasoningModel ? 1200 : 800, + temperature: 0.2, + ...(reasoningModel ? { reasoning_effort: 'low', reasoning_format: 'hidden' } : {}), + }), + signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), + }) + } catch { return { ok: false, error: 'unavailable' } } + + if (!response.ok) { + await response.body?.cancel().catch(() => {}) + return { ok: false, error: response.status === 401 || response.status === 403 ? 'unauthorized' + : response.status === 429 ? 'rate-limited' : 'unavailable' } + } + const body = await readJsonCapped(response, 256 * 1024).catch(() => undefined) as ChatBody | undefined + const content = body?.choices?.[0]?.message?.content + return typeof content === 'string' && content.trim() + ? { ok: true, content: content.trim() } + : { ok: false, error: 'invalid-response' } +} + +/** Makes a bounded suggestion request. The result is text only: this provider has no execution path. */ +export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, deps: OpenAIShellsmithDeps = {}): Provider { + const fetchFn = deps.fetchFn ?? fetch + const pasteboard = deps.pasteboard ?? pbPasteboard + const token = ctx.secrets.token?.trim() ?? '' + const modelResult = ModelSchema.safeParse(ctx.fields.model) + const provider = providerFor(ctx.fields) + const api = apiFor(provider ?? 'openai') + + return { + channel: ctx.channel, + commands: { + suggestCommand: async (payload, commandContext?: CommandContext) => { + if (!commandContext?.loopback) return { ok: false, error: 'local-only' } + const parsed = RequestPayload.safeParse(payload) + if (!parsed.success || !modelResult.success || !provider) return { ok: false, error: 'invalid-request' } + if (!token) return { ok: false, error: 'unconfigured' } + + if (provider === 'groq') { + const completion = await chatCompletion(fetchFn, api, token, modelResult.data, + `Suggest one shell command for this request. Do not execute it, call tools, or include secrets. Return only command text, without markdown or explanation. Avoid destructive commands unless explicitly requested.\n\nRequest: ${parsed.data.request}`) + if (!completion.ok) return completion + if (completion.content.length > SHELLSMITH_MAX_COMMAND_CHARS) return { ok: false, error: 'invalid-response' } + return { ok: true, command: completion.content } + } + + let response: Response + try { + response = await fetchFn(`${api}/responses`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': USER_AGENT, + }, + body: JSON.stringify({ + model: modelResult.data, + instructions: 'Suggest one shell command for the user request. Do not execute commands, call tools, or include secrets. Return only the command text, with no markdown or explanation. Avoid destructive commands unless the user explicitly requests them.', + input: parsed.data.request, + max_output_tokens: 400, + store: false, + }), + signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), + }) + } catch { return { ok: false, error: 'unavailable' } } + + if (!response.ok) { + await response.body?.cancel().catch(() => {}) + return { ok: false, error: response.status === 401 || response.status === 403 ? 'unauthorized' + : response.status === 429 ? 'rate-limited' : 'unavailable' } + } + const body = await readJsonCapped(response, 256 * 1024).catch(() => undefined) as ResponsesBody | undefined + const command = body?.output?.flatMap((item) => item.content ?? []) + .filter((part) => part.type === 'output_text' && typeof part.text === 'string') + .map((part) => (part.text as string).trim()) + .filter(Boolean) + .join('\n') + if (!command || command.length > SHELLSMITH_MAX_COMMAND_CHARS) return { ok: false, error: 'invalid-response' } + return { ok: true, command } + }, + copyCommand: async (payload, commandContext?: CommandContext) => { + if (!commandContext?.loopback) return { ok: false, error: 'local-only' } + const parsed = CopyPayload.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-command' } + try { + await pasteboard.write(parsed.data.command) + return { ok: true } + } catch { return { ok: false, error: 'copy-failed' } } + }, + }, + } +} diff --git a/server/test/connections.test.ts b/server/test/connections.test.ts index 58e40451..36931682 100644 --- a/server/test/connections.test.ts +++ b/server/test/connections.test.ts @@ -509,6 +509,7 @@ describe('the real connection types bind their secrets', () => { // dev.azure.com is hardcoded, and an ICS calendar's URL *is* its secret. 'azure-devops': [], ics: [], + 'openai-shellsmith': ['provider'], }) // Every bound key must be a real, non-secret field of its type. for (const type of defaultConnectionTypes()) { diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts new file mode 100644 index 00000000..bf254760 --- /dev/null +++ b/server/test/shellsmith.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it } from 'vitest' +import { defaultConnectionTypes } from '../src/connections/types/index.js' +import { openAIShellsmithType } from '../src/connections/types/openai-shellsmith.js' +import { createOpenAIShellsmithProvider } from '../src/providers/openai-shellsmith.js' + +const context = () => ({ + id: 'shellsmith', + channel: 'openai-shellsmith:shellsmith', + fields: { model: 'gpt-4.1-mini' }, + secrets: { token: 'private-test-token' }, +}) +const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) + +describe('ShellSmith command suggestion provider', () => { + it('exposes only commands used by ShellSmith', () => { + const provider = createOpenAIShellsmithProvider(context()) + + expect(Object.keys(provider.commands ?? {}).sort()).toEqual(['copyCommand', 'suggestCommand']) + }) + + it('sends a bounded request to the fixed Responses API and returns text without executing it', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ output: [{ type: 'message', content: [{ type: 'output_text', text: 'find . -type f' }] }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + + const result = await provider.commands!.suggestCommand({ request: 'Find files in this folder' }, { loopback: true }) + + expect(result).toEqual({ ok: true, command: 'find . -type f' }) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('https://api.openai.com/v1/responses') + expect(new Headers(calls[0].init?.headers).get('authorization')).toBe('Bearer private-test-token') + const body = JSON.parse(String(calls[0].init?.body)) + expect(body.model).toBe('gpt-4.1-mini') + expect(body.store).toBe(false) + expect(body.input).toContain('Find files in this folder') + expect(body.tools).toBeUndefined() + }) + + it('rejects remote callers and malformed or oversized requests before calling the API', async () => { + let requests = 0 + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + + expect(await provider.commands!.suggestCommand({ request: 'list files' }, { loopback: false })).toEqual({ ok: false, error: 'local-only' }) + expect(await provider.commands!.suggestCommand({ request: 'x'.repeat(2001) }, { loopback: true })).toEqual({ ok: false, error: 'invalid-request' }) + expect(await provider.commands!.suggestCommand({ request: ' ' }, { loopback: true })).toEqual({ ok: false, error: 'invalid-request' }) + expect(requests).toBe(0) + }) + + it('accepts the dashboard-stamped instance id but rejects other unknown payload fields', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ choices: [{ message: { content: 'find . -type f' } }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider({ + ...context(), + fields: { provider: 'groq', model: 'openai/gpt-oss-20b' }, + }, { + fetchFn, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + // Mirrors the host's stampInstance() contract: every plain-object command gets this field. + const payload = { request: 'List files', instanceId: 'shellsmith-command-showcase' } + + expect(await provider.commands!.suggestCommand(payload, { loopback: true })).toEqual({ ok: true, command: 'find . -type f' }) + expect(calls).toHaveLength(1) + const body = JSON.parse(String(calls[0].init?.body)) + expect(body.messages[0].content).toContain('List files') + expect(JSON.stringify(body)).not.toContain('shellsmith-command-showcase') + expect(await provider.commands!.suggestCommand({ ...(payload as object), unexpected: true }, { loopback: true })).toEqual({ ok: false, error: 'invalid-request' }) + expect(calls).toHaveLength(1) + }) + + it('copies only on an explicit loopback command and never runs the generated text', async () => { + const writes: string[] = [] + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn: (async () => json({})) as typeof fetch, + pasteboard: { read: async () => '', write: async (text) => { writes.push(text) }, types: async () => [] }, + }) + + expect(await provider.commands!.copyCommand({ command: 'echo reviewed' }, { loopback: false })).toEqual({ ok: false, error: 'local-only' }) + expect(writes).toEqual([]) + expect(await provider.commands!.copyCommand({ command: 'echo reviewed', instanceId: 'shellsmith-command-showcase' }, { loopback: true })).toEqual({ ok: true }) + expect(writes).toEqual(['echo reviewed']) + }) + + it('uses the fixed Groq host for a bounded suggestion and keeps the result copy-only', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ choices: [{ message: { content: 'find . -type f' } }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider({ + ...context(), + fields: { provider: 'groq', model: 'openai/gpt-oss-20b' }, + }, { + fetchFn, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + + const result = await provider.commands!.suggestCommand({ request: 'Find files in this folder' }, { loopback: true }) + + expect(result).toEqual({ ok: true, command: 'find . -type f' }) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('https://api.groq.com/openai/v1/chat/completions') + expect(new Headers(calls[0].init?.headers).get('authorization')).toBe('Bearer private-test-token') + const body = JSON.parse(String(calls[0].init?.body)) + expect(body.model).toBe('openai/gpt-oss-20b') + expect(body.reasoning_effort).toBe('low') + expect(body.reasoning_format).toBe('hidden') + expect(body.max_completion_tokens).toBeGreaterThan(400) + expect(body.tools).toBeUndefined() + }) + + it('registers an OpenAI-compatible connection with a secret token and a fixed provider choice', async () => { + expect(defaultConnectionTypes().some((type) => type.id === 'openai-shellsmith')).toBe(true) + expect(openAIShellsmithType.fields.find((field) => field.key === 'token')).toMatchObject({ secret: true, required: true }) + expect(openAIShellsmithType.fields.find((field) => field.key === 'model')).toMatchObject({ required: true }) + expect(openAIShellsmithType.fields.find((field) => field.key === 'provider')?.options).toEqual(['openai', 'groq']) + expect(openAIShellsmithType.fields.some((field) => field.key === 'baseUrl')).toBe(false) + + let requestedUrl = '' + const result = await openAIShellsmithType.test({ model: 'gpt-4.1-mini' }, { token: 'private-test-token' }, { + fetchFn: (async (url: string | URL | Request) => { + requestedUrl = String(url) + return json({ id: 'gpt-4.1-mini' }) + }) as typeof fetch, + }) + + expect(requestedUrl).toBe('https://api.openai.com/v1/models/gpt-4.1-mini') + expect(result.ok).toBe(true) + expect(JSON.stringify(result)).not.toContain('private-test-token') + }) + + it('checks Groq models through the fixed models endpoint without returning the secret', async () => { + let requestedUrl = '' + const result = await openAIShellsmithType.test({ provider: 'groq', model: 'openai/gpt-oss-20b' }, { token: 'private-test-token' }, { + fetchFn: (async (url: string | URL | Request) => { + requestedUrl = String(url) + return json({ data: [{ id: 'openai/gpt-oss-20b' }] }) + }) as typeof fetch, + }) + + expect(requestedUrl).toBe('https://api.groq.com/openai/v1/models') + expect(result.ok).toBe(true) + expect(JSON.stringify(result)).not.toContain('private-test-token') + }) + +}) From 0eeef740108101841ee68fe4624c57d427e83a0c Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 12:40:37 +0200 Subject: [PATCH 09/24] fix: reject provider redirects --- server/src/connections/types/openai-shellsmith.ts | 2 ++ server/src/providers/openai-shellsmith.ts | 2 ++ server/test/shellsmith.test.ts | 12 ++++++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/server/src/connections/types/openai-shellsmith.ts b/server/src/connections/types/openai-shellsmith.ts index 120842a2..9a145266 100644 --- a/server/src/connections/types/openai-shellsmith.ts +++ b/server/src/connections/types/openai-shellsmith.ts @@ -33,10 +33,12 @@ export const openAIShellsmithType: ConnectionType = { try { const response = provider === 'groq' ? await (deps.fetchFn ?? fetch)(`${GROQ_API}/models`, { + redirect: 'error', headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), }) : await (deps.fetchFn ?? fetch)(`${OPENAI_API}/models/${encodeURIComponent(model)}`, { + redirect: 'error', headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), }) diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts index 5024bbdf..16da45e8 100644 --- a/server/src/providers/openai-shellsmith.ts +++ b/server/src/providers/openai-shellsmith.ts @@ -48,6 +48,7 @@ async function chatCompletion( try { response = await fetchFn(`${api}/chat/completions`, { method: 'POST', + redirect: 'error', headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', @@ -107,6 +108,7 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d try { response = await fetchFn(`${api}/responses`, { method: 'POST', + redirect: 'error', headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts index bf254760..12929310 100644 --- a/server/test/shellsmith.test.ts +++ b/server/test/shellsmith.test.ts @@ -34,6 +34,7 @@ describe('ShellSmith command suggestion provider', () => { expect(result).toEqual({ ok: true, command: 'find . -type f' }) expect(calls).toHaveLength(1) expect(calls[0].url).toBe('https://api.openai.com/v1/responses') + expect(calls[0].init?.redirect).toBe('error') expect(new Headers(calls[0].init?.headers).get('authorization')).toBe('Bearer private-test-token') const body = JSON.parse(String(calls[0].init?.body)) expect(body.model).toBe('gpt-4.1-mini') @@ -112,6 +113,7 @@ describe('ShellSmith command suggestion provider', () => { expect(result).toEqual({ ok: true, command: 'find . -type f' }) expect(calls).toHaveLength(1) expect(calls[0].url).toBe('https://api.groq.com/openai/v1/chat/completions') + expect(calls[0].init?.redirect).toBe('error') expect(new Headers(calls[0].init?.headers).get('authorization')).toBe('Bearer private-test-token') const body = JSON.parse(String(calls[0].init?.body)) expect(body.model).toBe('openai/gpt-oss-20b') @@ -129,28 +131,34 @@ describe('ShellSmith command suggestion provider', () => { expect(openAIShellsmithType.fields.some((field) => field.key === 'baseUrl')).toBe(false) let requestedUrl = '' + let requestedRedirect: RequestInit['redirect'] const result = await openAIShellsmithType.test({ model: 'gpt-4.1-mini' }, { token: 'private-test-token' }, { - fetchFn: (async (url: string | URL | Request) => { + fetchFn: (async (url: string | URL | Request, init?: RequestInit) => { requestedUrl = String(url) + requestedRedirect = init?.redirect return json({ id: 'gpt-4.1-mini' }) }) as typeof fetch, }) expect(requestedUrl).toBe('https://api.openai.com/v1/models/gpt-4.1-mini') + expect(requestedRedirect).toBe('error') expect(result.ok).toBe(true) expect(JSON.stringify(result)).not.toContain('private-test-token') }) it('checks Groq models through the fixed models endpoint without returning the secret', async () => { let requestedUrl = '' + let requestedRedirect: RequestInit['redirect'] const result = await openAIShellsmithType.test({ provider: 'groq', model: 'openai/gpt-oss-20b' }, { token: 'private-test-token' }, { - fetchFn: (async (url: string | URL | Request) => { + fetchFn: (async (url: string | URL | Request, init?: RequestInit) => { requestedUrl = String(url) + requestedRedirect = init?.redirect return json({ data: [{ id: 'openai/gpt-oss-20b' }] }) }) as typeof fetch, }) expect(requestedUrl).toBe('https://api.groq.com/openai/v1/models') + expect(requestedRedirect).toBe('error') expect(result.ok).toBe(true) expect(JSON.stringify(result)).not.toContain('private-test-token') }) From d98f6adaba89f8eea4ae36fa530a70a05d70e333 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 08:16:49 +0200 Subject: [PATCH 10/24] Add guarded native macOS window placement provider --- server/src/app.ts | 5 +- server/src/providers/rectangle-native.swift | 262 ++++++++++++++++++++ server/src/providers/rectangle.ts | 112 +++++++++ server/test/rectangle.test.ts | 91 +++++++ 4 files changed, 468 insertions(+), 2 deletions(-) create mode 100644 server/src/providers/rectangle-native.swift create mode 100644 server/src/providers/rectangle.ts create mode 100644 server/test/rectangle.test.ts diff --git a/server/src/app.ts b/server/src/app.ts index a8fbeff9..07b23713 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -62,6 +62,7 @@ import { backupRoutes } from './backup/routes.js' import { bambuRoutes } from './bambu/routes.js' import { createShortcutsProvider } from './providers/shortcuts.js' import { createMessages2FAProvider } from './providers/messages-2fa.js' +import { createRectangleProvider } from './providers/rectangle.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' @@ -310,6 +311,7 @@ export async function buildApp(opts: AppOptions): Promise { // Registered here, not in providers/index.ts, because that is where the config store lives. registry.register(createShortcutsProvider(undefined, instances)) registry.register(createMessages2FAProvider({ enabled: () => store.get().privacy.messages2FA })) + registry.register(createRectangleProvider()) registry.register(createServiceStatusProvider({}, instances)) // A paired device may set only its own screen's brightness: see mayCommandBrightness. Read // at command time, so a device moved to another screen (or unpaired) is judged as it is now. @@ -328,8 +330,7 @@ export async function buildApp(opts: AppOptions): Promise { // A demo never asks the keychain, whatever its config says: a file in its own data folder. const secrets = demo ? new FileSecretStore(join(opts.dataDir, 'secrets.json')) - : createSecretStore(store.get().secrets.backend, opts.dataDir, { adoptLegacyKeychain: opts.adoptLegacyKeychain === true }) - // v2 → v3 moved the Homey connection to the type its widget declares, and the declaration + : createSecretStore(store.get().secrets.backend, opts.dataDir, { adoptLegacyKeychain: opts.adoptLegacyKeychain === true }) // v2 → v3 moved the Homey connection to the type its widget declares, and the declaration // calls the key `token` where the coded type called it `apiKey`. The config half of that is in // `migrateConfig`; this is the half that needs the secret store. Idempotent, so it costs one // read per Homey connection on a start that has nothing to do. diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift new file mode 100644 index 00000000..137af300 --- /dev/null +++ b/server/src/providers/rectangle-native.swift @@ -0,0 +1,262 @@ +import AppKit +import ApplicationServices +import CoreGraphics +import Foundation + +struct Target: Codable { + let pid: Int32 + let bundleId: String + let title: String + let application: String +} + +struct Response: Encodable { + let ok: Bool + let error: String? + let target: Target? + let changed: Bool? + + init(ok: Bool, error: String? = nil, target: Target? = nil, changed: Bool? = nil) { + self.ok = ok + self.error = error + self.target = target + self.changed = changed + } +} + +struct Display { + let id: CGDirectDisplayID + let frame: CGRect + let usable: CGRect +} + +func respond(_ response: Response) -> Never { + let encoder = JSONEncoder() + if let data = try? encoder.encode(response), let text = String(data: data, encoding: .utf8) { + print(text) + } else { + print("{\"ok\":false,\"error\":\"response-encoding-failed\"}") + } + exit(0) +} + +func axValue(_ element: AXUIElement, _ attribute: CFString) -> CFTypeRef? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute, &value) == .success else { return nil } + return value +} + +func stringAttribute(_ element: AXUIElement, _ attribute: CFString) -> String? { + axValue(element, attribute) as? String +} + +func pointAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGPoint? { + guard let value = axValue(element, attribute) else { return nil } + var point = CGPoint.zero + guard AXValueGetValue(value as! AXValue, .cgPoint, &point) else { return nil } + return point +} + +func sizeAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGSize? { + guard let value = axValue(element, attribute) else { return nil } + var size = CGSize.zero + guard AXValueGetValue(value as! AXValue, .cgSize, &size) else { return nil } + return size +} + +func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CGSize)? { + guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication else { return nil } + let pid = app.processIdentifier + guard let bundleId = app.bundleIdentifier, let appName = app.localizedName else { return nil } + guard !bundleId.localizedCaseInsensitiveContains("fremkit"), + !bundleId.localizedCaseInsensitiveContains("rectangle"), + !appName.localizedCaseInsensitiveContains("fremkit"), + !appName.localizedCaseInsensitiveContains("rectangle") else { return nil } + if let expected, (expected.pid != pid || expected.bundleId != bundleId) { return nil } + + let application = AXUIElementCreateApplication(pid) + guard let rawWindow = axValue(application, kAXFocusedWindowAttribute as CFString) else { return nil } + let window = rawWindow as! AXUIElement + guard let title = stringAttribute(window, kAXTitleAttribute as CFString), + let position = pointAttribute(window, kAXPositionAttribute as CFString), + let size = sizeAttribute(window, kAXSizeAttribute as CFString) else { return nil } + if let expected, expected.title != title { return nil } + let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName) + return (target, window, position, size) +} + +func displays() -> [Display] { + NSScreen.screens.compactMap { screen in + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { return nil } + let id = CGDirectDisplayID(number.uint32Value) + let frame = CGDisplayBounds(id) + let appKitFrame = screen.frame + let visible = screen.visibleFrame + let usable = CGRect( + x: frame.minX + visible.minX - appKitFrame.minX, + y: frame.minY + appKitFrame.maxY - visible.maxY, + width: visible.width, + height: visible.height + ) + return Display(id: id, frame: frame, usable: usable) + }.sorted { + if $0.frame.minX == $1.frame.minX { return $0.frame.minY < $1.frame.minY } + return $0.frame.minX < $1.frame.minX + } +} + +func displayFor(_ position: CGPoint, _ size: CGSize, in displays: [Display]) -> Int? { + let window = CGRect(origin: position, size: size) + let center = CGPoint(x: window.midX, y: window.midY) + if let exact = displays.firstIndex(where: { $0.frame.contains(center) }) { return exact } + let overlaps = displays.enumerated().map { index, display in (index, window.intersection(display.frame).width * window.intersection(display.frame).height) } + return overlaps.max(by: { $0.1 < $1.1 })?.0 +} + +func setAX(_ window: AXUIElement, attribute: CFString, point: CGPoint) -> Bool { + var value = point + guard let boxed = AXValueCreate(.cgPoint, &value) else { return false } + return AXUIElementSetAttributeValue(window, attribute, boxed) == .success +} + +func setAX(_ window: AXUIElement, attribute: CFString, size: CGSize) -> Bool { + var value = size + guard let boxed = AXValueCreate(.cgSize, &value) else { return false } + return AXUIElementSetAttributeValue(window, attribute, boxed) == .success +} + +func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } + +func waitForGeometry(_ expected: Target, position: CGPoint, size: CGSize) -> Bool { + for _ in 0..<30 { + if let (_, _, actualPosition, actualSize) = focusedTarget(expected: expected), + closeEnough(actualPosition.x, position.x), closeEnough(actualPosition.y, position.y), + closeEnough(actualSize.width, size.width), closeEnough(actualSize.height, size.height) { + return true + } + Thread.sleep(forTimeInterval: 0.05) + } + return false +} + +func children(_ element: AXUIElement) -> [AXUIElement] { + (axValue(element, kAXChildrenAttribute as CFString) as? [AXUIElement]) ?? [] +} + +func role(_ element: AXUIElement) -> String { + stringAttribute(element, kAXRoleAttribute as CFString) ?? "" +} + +func menuAction(_ path: [String], expected: Target) -> Bool { + guard !path.isEmpty, let (target, _, _, _) = focusedTarget(expected: expected), + target.pid == expected.pid, + let menuBarValue = axValue(AXUIElementCreateApplication(expected.pid), kAXMenuBarAttribute as CFString), + CFGetTypeID(menuBarValue) == AXUIElementGetTypeID() else { return false } + let menuBar = menuBarValue as! AXUIElement + guard let windowMenu = children(menuBar).first(where: { + role($0) == kAXMenuBarItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == path[0] + }), AXUIElementPerformAction(windowMenu, kAXPressAction as CFString) == .success else { return false } + Thread.sleep(forTimeInterval: 0.05) + guard let topMenu = children(windowMenu).first(where: { role($0) == kAXMenuRole as String }) else { return false } + var currentMenu = topMenu + for (index, title) in path.dropFirst().enumerated() { + guard let item = children(currentMenu).first(where: { + role($0) == kAXMenuItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == title + }) else { return false } + let isFinalItem = index == path.count - 2 + guard AXUIElementPerformAction(item, kAXPressAction as CFString) == .success else { return false } + if isFinalItem { return true } + Thread.sleep(forTimeInterval: 0.05) + guard let submenu = children(item).first(where: { role($0) == kAXMenuRole as String }) else { return false } + currentMenu = submenu + } + return false +} + +func runAction(_ action: String, expected: Target) { + guard let (_, window, oldPosition, oldSize) = focusedTarget(expected: expected) else { + respond(Response(ok: false, error: "target-changed-or-unavailable")) + } + let screens = displays() + guard !screens.isEmpty, let currentIndex = displayFor(oldPosition, oldSize, in: screens) else { + respond(Response(ok: false, error: "display-unavailable")) + } + let targetPosition: CGPoint + let targetSize: CGSize + switch action { + case "left-half": + let area = screens[currentIndex].usable + targetPosition = CGPoint(x: area.minX, y: area.minY) + targetSize = CGSize(width: floor(area.width / 2), height: area.height) + case "right-half": + let area = screens[currentIndex].usable + let width = floor(area.width / 2) + targetPosition = CGPoint(x: area.minX + area.width - width, y: area.minY) + targetSize = CGSize(width: width, height: area.height) + case "fill": + let area = screens[currentIndex].usable + targetPosition = CGPoint(x: area.minX, y: area.minY) + targetSize = CGSize(width: area.width, height: area.height) + case "next-display": + guard screens.count > 1 else { respond(Response(ok: false, error: "no-next-display")) } + let next = screens[(currentIndex + 1) % screens.count].usable + targetSize = CGSize(width: min(oldSize.width, next.width), height: min(oldSize.height, next.height)) + targetPosition = CGPoint(x: next.midX - targetSize.width / 2, y: next.midY - targetSize.height / 2) + default: + respond(Response(ok: false, error: "invalid-action")) + } + + var settablePosition = DarwinBoolean(false) + var settableSize = DarwinBoolean(false) + guard AXUIElementIsAttributeSettable(window, kAXPositionAttribute as CFString, &settablePosition) == .success, + AXUIElementIsAttributeSettable(window, kAXSizeAttribute as CFString, &settableSize) == .success, + settablePosition.boolValue, settableSize.boolValue else { + respond(Response(ok: false, error: "window-not-resizable")) + } + + if action == "next-display" { + guard setAX(window, attribute: kAXPositionAttribute as CFString, point: targetPosition) else { + respond(Response(ok: false, error: "window-action-rejected")) + } + } else { + let menuPath: [String] + switch action { + case "left-half": menuPath = ["Window", "Move & Resize", "Left"] + case "right-half": menuPath = ["Window", "Move & Resize", "Right"] + case "fill": menuPath = ["Window", "Fill"] + default: respond(Response(ok: false, error: "invalid-action")) + } + guard menuAction(menuPath, expected: expected) else { + respond(Response(ok: false, error: "native-menu-action-unavailable")) + } + } + // Native tiling animates asynchronously; poll the same guarded window for at most 1.5 seconds. + guard waitForGeometry(expected, position: targetPosition, size: targetSize) else { + respond(Response(ok: false, error: "geometry-unverified")) + } + respond(Response(ok: true, changed: true)) +} + +let arguments = Array(CommandLine.arguments.dropFirst()) +guard let mode = arguments.first else { respond(Response(ok: false, error: "missing-mode")) } +guard AXIsProcessTrusted() else { respond(Response(ok: false, error: "accessibility-permission-required")) } + +if mode == "inspect" { + guard let (target, _, _, _) = focusedTarget() else { respond(Response(ok: false, error: "no-safe-window")) } + respond(Response(ok: true, target: target)) +} + +guard mode == "run", arguments.count >= 6, + let pid = Int32(arguments[1]) else { respond(Response(ok: false, error: "invalid-request")) } +let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "") +let invocation = Array(arguments.dropFirst(4)) +if invocation.count == 4, invocation[0] == "menu", invocation[1] == "Window" { + let action = invocation[2] == "Fill" ? "fill" : invocation[3] == "Left" ? "left-half" : invocation[3] == "Right" ? "right-half" : "invalid" + runAction(action, expected: expected) +} else if invocation == ["menu", "Window", "Fill"] { + runAction("fill", expected: expected) +} else if invocation == ["position", "next-display"] { + runAction("next-display", expected: expected) +} else { + respond(Response(ok: false, error: "invalid-request")) +} diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts new file mode 100644 index 00000000..1ea04fd8 --- /dev/null +++ b/server/src/providers/rectangle.ts @@ -0,0 +1,112 @@ +import { randomUUID } from 'node:crypto' +import { execFile as nodeExecFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { z } from 'zod' +import type { CommandContext, Provider } from './types.js' + +const execFile = promisify(nodeExecFile) +const ActionSchema = z.enum(['left-half', 'right-half', 'fill', 'next-display']) +export type RectangleAction = z.infer +const InspectSchema = z.object({}).strict() +const RunSchema = z.object({ action: ActionSchema, targetToken: z.string().uuid() }).strict() +const NativeTargetSchema = z.object({ + pid: z.number().int().positive(), + bundleId: z.string().min(1).max(255), + title: z.string().max(1024), + application: z.string().min(1).max(255), +}) + +const SWIFT = '/usr/bin/swift' +const HELPER = fileURLToPath(new URL('./rectangle-native.swift', import.meta.url)) +const TARGET_LIFETIME_MS = 5 * 60_000 +const MAX_TARGETS = 32 +const COMMAND_TIMEOUT_MS = 15_000 + +export type Runner = (file: string, args: string[]) => Promise +type Target = z.infer +type NativeResponse = { ok: boolean; error?: string; target?: Target; changed?: boolean } + +export function nativeInvocationFor(action: RectangleAction): string[] { + switch (action) { + case 'left-half': return ['menu', 'Window', 'Move & Resize', 'Left'] + case 'right-half': return ['menu', 'Window', 'Move & Resize', 'Right'] + case 'fill': return ['menu', 'Window', 'Fill'] + case 'next-display': return ['position', 'next-display'] + } +} + +const runProgram: Runner = async (file, args) => { + const { stdout } = await execFile(file, args, { timeout: COMMAND_TIMEOUT_MS, maxBuffer: 32 * 1024 }) + return stdout +} + +/** Kept exported so tests can prove the only executable is Swift and input is argv, not shell. */ +export function nativeArgsFor(mode: 'inspect'): string[] +export function nativeArgsFor(action: RectangleAction, target: Target): string[] +export function nativeArgsFor(modeOrAction: 'inspect' | RectangleAction, target?: Target): string[] { + if (modeOrAction === 'inspect') return [HELPER, 'inspect'] + if (!target) throw new Error('native target required') + return [HELPER, 'run', String(target.pid), target.bundleId, target.title, ...nativeInvocationFor(modeOrAction)] +} + +function parseResponse(stdout: string): NativeResponse | null { + try { + return z.object({ + ok: z.boolean(), + error: z.string().optional(), + target: NativeTargetSchema.optional(), + changed: z.boolean().optional(), + }).strict().parse(JSON.parse(stdout)) + } catch { + return null + } +} + +/** + * Uses macOS Accessibility APIs and the system display geometry. The widget can act only on a + * window it explicitly inspected, and the helper verifies that exact process and title again. + */ +export function createRectangleProvider(run: Runner = runProgram, now: () => number = Date.now): Provider { + const targets = new Map() + + return { + channel: 'rectangle', + commands: { + async ['inspect-target'](payload: unknown, context?: CommandContext) { + if (!context?.loopback) return { ok: false, error: 'local-only' } + if (!InspectSchema.safeParse(payload).success) return { ok: false, error: 'invalid-request' } + try { + const response = parseResponse(await run(SWIFT, nativeArgsFor('inspect'))) + if (!response?.ok || !response.target) return { ok: false, error: 'no-target' } + const token = randomUUID() + if (targets.size >= MAX_TARGETS) { + for (const [key, value] of targets) if (value.expiresAt <= now()) targets.delete(key) + if (targets.size >= MAX_TARGETS) targets.delete(targets.keys().next().value!) + } + targets.set(token, { target: response.target, expiresAt: now() + TARGET_LIFETIME_MS }) + return { ok: true, target: { token, application: response.target.application } } + } catch { + return { ok: false, error: 'native-window-access-unavailable' } + } + }, + async run(payload: unknown, context?: CommandContext) { + if (!context?.loopback) return { ok: false, error: 'local-only' } + const parsed = RunSchema.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-request' } + const stored = targets.get(parsed.data.targetToken) + targets.delete(parsed.data.targetToken) + if (!stored || stored.expiresAt <= now()) return { ok: false, error: 'target-expired' } + try { + const response = parseResponse(await run(SWIFT, nativeArgsFor(parsed.data.action, stored.target))) + if (!response?.ok || response.changed !== true) { + return { ok: false, error: response?.error ?? 'geometry-unverified' } + } + return { ok: true, changed: true } + } catch { + return { ok: false, error: 'native-window-action-unavailable' } + } + }, + }, + } +} diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts new file mode 100644 index 00000000..84a076f7 --- /dev/null +++ b/server/test/rectangle.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it, vi } from 'vitest' +import { createRectangleProvider, nativeArgsFor, nativeInvocationFor } from '../src/providers/rectangle.js' + +const nativeTarget = { + pid: 4242, + bundleId: 'com.apple.TextEdit', + title: 'Fremkit Rectangle Probe.txt', + application: 'TextEdit', +} + +describe('built-in macOS window provider', () => { + it('inspects the active app and returns an opaque target token without exposing its title', async () => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: true })) + const provider = createRectangleProvider(run) + + const result = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + ok: boolean + target?: { token: string; application: string } + } + + expect(result.ok).toBe(true) + expect(result.target?.application).toBe('TextEdit') + expect(result.target?.token).toMatch(/^[0-9a-f-]{36}$/) + expect(JSON.stringify(result)).not.toContain(nativeTarget.title) + expect(run).toHaveBeenCalledWith('/usr/bin/swift', nativeArgsFor('inspect')) + }) + + it.each(['left-half', 'right-half', 'fill', 'next-display'] as const)( + 'runs the built-in native action %s only for the inspected target', async (action) => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: true, changed: true })) + const provider = createRectangleProvider(run) + const inspected = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + target: { token: string } + } + + const result = await provider.commands?.run?.({ action, targetToken: inspected.target.token }, { loopback: true }) + + expect(result).toEqual({ ok: true, changed: true }) + expect(run).toHaveBeenLastCalledWith('/usr/bin/swift', nativeArgsFor(action, nativeTarget)) + expect(run.mock.calls.flatMap(([, args]) => args).join(' ')).not.toContain('rectangle://') + }, + ) + + it.each([ + ['left-half', ['menu', 'Window', 'Move & Resize', 'Left']], + ['right-half', ['menu', 'Window', 'Move & Resize', 'Right']], + ['fill', ['menu', 'Window', 'Fill']], + ['next-display', ['position', 'next-display']], + ] as const)('maps %s to a built-in macOS action', (action, invocation) => { + expect(nativeInvocationFor(action)).toEqual(invocation) + expect(nativeArgsFor(action, nativeTarget).slice(5)).toEqual(invocation) + }) + + it('rejects remote, malformed, stale, and arbitrary-target requests without invoking a native action', async () => { + const run = vi.fn(async (_file: string, args: string[]) => JSON.stringify({ ok: true, target: nativeTarget })) + const provider = createRectangleProvider(run) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: false })) + .resolves.toEqual({ ok: false, error: 'local-only' }) + await expect(provider.commands?.run?.({ action: 'run-shell', targetToken: 'nope' }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'invalid-request' }) + await expect(provider.commands?.run?.({ action: 'left-half', targetToken: '00000000-0000-4000-8000-000000000001' }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'target-expired' }) + expect(run).not.toHaveBeenCalled() + }) + + it('fails closed when the inspected foreground window is not a safe app window', async () => { + const run = vi.fn(async () => JSON.stringify({ ok: false, error: 'unsafe-target' })) + const provider = createRectangleProvider(run) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'no-target' }) + }) + + it('fails closed when native geometry verification does not succeed', async () => { + const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' + ? JSON.stringify({ ok: true, target: nativeTarget }) + : JSON.stringify({ ok: false, error: 'geometry-unverified' })) + const provider = createRectangleProvider(run) + const inspected = await provider.commands?.['inspect-target']?.({}, { loopback: true }) as { + target: { token: string } + } + + await expect(provider.commands?.run?.({ action: 'left-half', targetToken: inspected.target.token }, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'geometry-unverified' }) + }) +}) From f56ae11ffad43afbae4d271675a5520ec4bb5f6b Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 09:02:21 +0200 Subject: [PATCH 11/24] Bind native window actions to Core Graphics IDs --- server/src/providers/rectangle-native.swift | 86 +++++++++++++++++++-- server/src/providers/rectangle.ts | 5 +- server/test/rectangle.test.ts | 46 ++++++++++- 3 files changed, 128 insertions(+), 9 deletions(-) diff --git a/server/src/providers/rectangle-native.swift b/server/src/providers/rectangle-native.swift index 137af300..6db0b4e9 100644 --- a/server/src/providers/rectangle-native.swift +++ b/server/src/providers/rectangle-native.swift @@ -8,6 +8,30 @@ struct Target: Codable { let bundleId: String let title: String let application: String + let windowID: UInt32 +} + +struct WindowCandidate: Codable { + let windowID: UInt32 + let pid: Int32 + let title: String + let x: Double + let y: Double + let width: Double + let height: Double + + var bounds: CGRect { CGRect(x: x, y: y, width: width, height: height) } +} + +struct IdentityProbe: Decodable { + let pid: Int32 + let title: String + let x: Double + let y: Double + let width: Double + let height: Double + let expectedWindowID: UInt32? + let windows: [WindowCandidate] } struct Response: Encodable { @@ -64,6 +88,36 @@ func sizeAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGSize? { return size } +func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } + +// CGWindowID is unique within the current user session. AX does not expose that ID directly, +// so map its focused window to exactly one Core Graphics row by owner, title, and bounds. +// If the mapping is absent or ambiguous, do not guess which same-titled window was focused. +func matchingWindowID(pid: Int32, title: String, bounds: CGRect, expectedWindowID: UInt32? = nil, candidates: [WindowCandidate]) -> UInt32? { + let matches = candidates.filter { candidate in + candidate.pid == pid && candidate.title == title && + closeEnough(CGFloat(candidate.x), bounds.minX) && closeEnough(CGFloat(candidate.y), bounds.minY) && + closeEnough(CGFloat(candidate.width), bounds.width) && closeEnough(CGFloat(candidate.height), bounds.height) + } + guard matches.count == 1, let match = matches.first, match.windowID != kCGNullWindowID else { return nil } + if let expectedWindowID, expectedWindowID != match.windowID { return nil } + return match.windowID +} + +func onScreenWindowCandidates() -> [WindowCandidate]? { + guard let rawWindows = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else { return nil } + return rawWindows.compactMap { info in + guard let pid = info[kCGWindowOwnerPID as String] as? NSNumber, + let windowID = info[kCGWindowNumber as String] as? NSNumber, + let title = info[kCGWindowName as String] as? String, + let rawBounds = info[kCGWindowBounds as String] as? [String: Any], + let bounds = CGRect(dictionaryRepresentation: rawBounds as CFDictionary), + windowID.uint32Value != kCGNullWindowID else { return nil } + return WindowCandidate(windowID: windowID.uint32Value, pid: pid.int32Value, title: title, + x: bounds.minX, y: bounds.minY, width: bounds.width, height: bounds.height) + } +} + func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CGSize)? { guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication else { return nil } let pid = app.processIdentifier @@ -81,7 +135,10 @@ func focusedTarget(expected: Target? = nil) -> (Target, AXUIElement, CGPoint, CG let position = pointAttribute(window, kAXPositionAttribute as CFString), let size = sizeAttribute(window, kAXSizeAttribute as CFString) else { return nil } if let expected, expected.title != title { return nil } - let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName) + guard let candidates = onScreenWindowCandidates(), + let windowID = matchingWindowID(pid: pid, title: title, bounds: CGRect(origin: position, size: size), + expectedWindowID: expected?.windowID, candidates: candidates) else { return nil } + let target = Target(pid: pid, bundleId: bundleId, title: title, application: appName, windowID: windowID) return (target, window, position, size) } @@ -125,8 +182,6 @@ func setAX(_ window: AXUIElement, attribute: CFString, size: CGSize) -> Bool { return AXUIElementSetAttributeValue(window, attribute, boxed) == .success } -func closeEnough(_ lhs: CGFloat, _ rhs: CGFloat) -> Bool { abs(lhs - rhs) <= 4 } - func waitForGeometry(_ expected: Target, position: CGPoint, size: CGSize) -> Bool { for _ in 0..<30 { if let (_, _, actualPosition, actualSize) = focusedTarget(expected: expected), @@ -164,6 +219,7 @@ func menuAction(_ path: [String], expected: Target) -> Bool { role($0) == kAXMenuItemRole as String && stringAttribute($0, kAXTitleAttribute as CFString) == title }) else { return false } let isFinalItem = index == path.count - 2 + if isFinalItem, focusedTarget(expected: expected) == nil { return false } guard AXUIElementPerformAction(item, kAXPressAction as CFString) == .success else { return false } if isFinalItem { return true } Thread.sleep(forTimeInterval: 0.05) @@ -215,6 +271,9 @@ func runAction(_ action: String, expected: Target) { } if action == "next-display" { + guard focusedTarget(expected: expected) != nil else { + respond(Response(ok: false, error: "target-changed-or-unavailable")) + } guard setAX(window, attribute: kAXPositionAttribute as CFString, point: targetPosition) else { respond(Response(ok: false, error: "window-action-rejected")) } @@ -238,6 +297,21 @@ func runAction(_ action: String, expected: Target) { } let arguments = Array(CommandLine.arguments.dropFirst()) +if ProcessInfo.processInfo.environment["FREMKIT_RECTANGLE_TESTING"] == "1", arguments.first == "test-window-identity" { + guard arguments.count == 2, + let data = arguments[1].data(using: .utf8), + let probes = try? JSONDecoder().decode([IdentityProbe].self, from: data) else { + respond(Response(ok: false, error: "invalid-test-probe")) + } + let windowIDs = probes.map { probe in + matchingWindowID(pid: probe.pid, title: probe.title, + bounds: CGRect(x: probe.x, y: probe.y, width: probe.width, height: probe.height), + expectedWindowID: probe.expectedWindowID, candidates: probe.windows) + } + if let data = try? JSONEncoder().encode(windowIDs), let output = String(data: data, encoding: .utf8) { print(output) } + else { respond(Response(ok: false, error: "identity-test-encoding-failed")) } + exit(0) +} guard let mode = arguments.first else { respond(Response(ok: false, error: "missing-mode")) } guard AXIsProcessTrusted() else { respond(Response(ok: false, error: "accessibility-permission-required")) } @@ -247,9 +321,9 @@ if mode == "inspect" { } guard mode == "run", arguments.count >= 6, - let pid = Int32(arguments[1]) else { respond(Response(ok: false, error: "invalid-request")) } -let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "") -let invocation = Array(arguments.dropFirst(4)) + let pid = Int32(arguments[1]), let windowID = UInt32(arguments[4]) else { respond(Response(ok: false, error: "invalid-request")) } +let expected = Target(pid: pid, bundleId: arguments[2], title: arguments[3], application: "", windowID: windowID) +let invocation = Array(arguments.dropFirst(5)) if invocation.count == 4, invocation[0] == "menu", invocation[1] == "Window" { let action = invocation[2] == "Fill" ? "fill" : invocation[3] == "Left" ? "left-half" : invocation[3] == "Right" ? "right-half" : "invalid" runAction(action, expected: expected) diff --git a/server/src/providers/rectangle.ts b/server/src/providers/rectangle.ts index 1ea04fd8..4ccec66f 100644 --- a/server/src/providers/rectangle.ts +++ b/server/src/providers/rectangle.ts @@ -15,6 +15,7 @@ const NativeTargetSchema = z.object({ bundleId: z.string().min(1).max(255), title: z.string().max(1024), application: z.string().min(1).max(255), + windowID: z.number().int().positive().max(0xffff_ffff), }) const SWIFT = '/usr/bin/swift' @@ -47,7 +48,7 @@ export function nativeArgsFor(action: RectangleAction, target: Target): string[] export function nativeArgsFor(modeOrAction: 'inspect' | RectangleAction, target?: Target): string[] { if (modeOrAction === 'inspect') return [HELPER, 'inspect'] if (!target) throw new Error('native target required') - return [HELPER, 'run', String(target.pid), target.bundleId, target.title, ...nativeInvocationFor(modeOrAction)] + return [HELPER, 'run', String(target.pid), target.bundleId, target.title, String(target.windowID), ...nativeInvocationFor(modeOrAction)] } function parseResponse(stdout: string): NativeResponse | null { @@ -65,7 +66,7 @@ function parseResponse(stdout: string): NativeResponse | null { /** * Uses macOS Accessibility APIs and the system display geometry. The widget can act only on a - * window it explicitly inspected, and the helper verifies that exact process and title again. + * window it explicitly inspected, and the helper verifies its session-unique window ID again. */ export function createRectangleProvider(run: Runner = runProgram, now: () => number = Date.now): Provider { const targets = new Map() diff --git a/server/test/rectangle.test.ts b/server/test/rectangle.test.ts index 84a076f7..8f48f7e3 100644 --- a/server/test/rectangle.test.ts +++ b/server/test/rectangle.test.ts @@ -1,13 +1,23 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { describe, expect, it, vi } from 'vitest' import { createRectangleProvider, nativeArgsFor, nativeInvocationFor } from '../src/providers/rectangle.js' +const nativeHelper = fileURLToPath(new URL('../src/providers/rectangle-native.swift', import.meta.url)) + const nativeTarget = { pid: 4242, bundleId: 'com.apple.TextEdit', title: 'Fremkit Rectangle Probe.txt', application: 'TextEdit', + windowID: 41, } +const resolveWindowIDs = (inputs: unknown[]) => JSON.parse(execFileSync('/usr/bin/swift', [nativeHelper, 'test-window-identity', JSON.stringify(inputs)], { + encoding: 'utf8', + env: { ...process.env, FREMKIT_RECTANGLE_TESTING: '1' }, +})) as Array + describe('built-in macOS window provider', () => { it('inspects the active app and returns an opaque target token without exposing its title', async () => { const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' @@ -45,6 +55,24 @@ describe('built-in macOS window provider', () => { }, ) + it('rejects a same-process same-title focus switch to a different window ID', () => { + const firstWindow = { windowID: 41, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 } + const secondWindow = { ...firstWindow, windowID: 42, x: 720 } + const input = { pid: nativeTarget.pid, title: nativeTarget.title, x: firstWindow.x, y: firstWindow.y, width: firstWindow.width, height: firstWindow.height, windows: [firstWindow, secondWindow] } + + expect(resolveWindowIDs([input, { ...input, expectedWindowID: 42 }])).toEqual([41, null]) + }) + + it.each([ + ['missing window metadata', []], + ['ambiguous same-title and same-bounds windows', [ + { windowID: 41, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 }, + { windowID: 42, pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400 }, + ]], + ])('fails closed on %s', (_case, windows) => { + expect(resolveWindowIDs([{ pid: nativeTarget.pid, title: nativeTarget.title, x: 100, y: 100, width: 600, height: 400, expectedWindowID: 41, windows }])).toEqual([null]) + }) + it.each([ ['left-half', ['menu', 'Window', 'Move & Resize', 'Left']], ['right-half', ['menu', 'Window', 'Move & Resize', 'Right']], @@ -52,7 +80,13 @@ describe('built-in macOS window provider', () => { ['next-display', ['position', 'next-display']], ] as const)('maps %s to a built-in macOS action', (action, invocation) => { expect(nativeInvocationFor(action)).toEqual(invocation) - expect(nativeArgsFor(action, nativeTarget).slice(5)).toEqual(invocation) + expect(nativeArgsFor(action, nativeTarget).slice(6)).toEqual(invocation) + }) + + it('carries the inspected window ID in the private native invocation', () => { + expect(nativeArgsFor('fill', nativeTarget)).toEqual([ + expect.any(String), 'run', '4242', 'com.apple.TextEdit', 'Fremkit Rectangle Probe.txt', '41', 'menu', 'Window', 'Fill', + ]) }) it('rejects remote, malformed, stale, and arbitrary-target requests without invoking a native action', async () => { @@ -76,6 +110,16 @@ describe('built-in macOS window provider', () => { .resolves.toEqual({ ok: false, error: 'no-target' }) }) + it.each([ + ['missing', (({ windowID: _windowID, ...target }) => target)(nativeTarget)], + ['invalid', { ...nativeTarget, windowID: 0 }], + ])('rejects an inspector response with a %s window ID', async (_case, target) => { + const provider = createRectangleProvider(async () => JSON.stringify({ ok: true, target })) + + await expect(provider.commands?.['inspect-target']?.({}, { loopback: true })) + .resolves.toEqual({ ok: false, error: 'no-target' }) + }) + it('fails closed when native geometry verification does not succeed', async () => { const run = vi.fn(async (_file: string, args: string[]) => args[1] === 'inspect' ? JSON.stringify({ ok: true, target: nativeTarget }) From 0f1d670cf933f741a450ef32030dd933ffa32d6e Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 14:46:59 +0200 Subject: [PATCH 12/24] Add recent projects core provider Remember canonical working directories reported by Herdr panes and open a selected folder in a new pane. Use the split response pane ID so concurrent opens target their own panes. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 4 + server/src/app.ts | 2 + server/src/demo/providers.ts | 19 ++ server/src/providers/recent-projects.ts | 213 ++++++++++++++++++++ server/test/recent-projects.test.ts | 247 ++++++++++++++++++++++++ 5 files changed, 485 insertions(+) create mode 100644 server/src/providers/recent-projects.ts create mode 100644 server/test/recent-projects.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 507cc6d6..4663828d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ tagged `vX.Y.Z`. pasteboard. A cleanup startup failure is returned as a generic copy failure; a later cleaner failure is logged without exposing the code. +- **Recent Projects.** Remembers canonical working directories reported by Herdr panes and opens a + selected folder in a new pane, optionally starting Claude Code or Codex from a known executable + location. + ### Fixed - **The Claude limits tile finds the sign-in again.** Recent Claude Code versions keep the OAuth diff --git a/server/src/app.ts b/server/src/app.ts index 07b23713..4d05e9c5 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -66,6 +66,7 @@ import { createRectangleProvider } from './providers/rectangle.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' +import { createRecentProjectsProvider } from './providers/recent-projects.js' import { BrightnessService } from './brightness/service.js' import { createBrightnessProvider, BRIGHTNESS_INTERVAL_MS } from './brightness/provider.js' import { brightnessRoutes } from './brightness/routes.js' @@ -313,6 +314,7 @@ export async function buildApp(opts: AppOptions): Promise { registry.register(createMessages2FAProvider({ enabled: () => store.get().privacy.messages2FA })) registry.register(createRectangleProvider()) registry.register(createServiceStatusProvider({}, instances)) + registry.register(createRecentProjectsProvider({ filePath: join(opts.dataDir, 'recent-projects.json') })) // A paired device may set only its own screen's brightness: see mayCommandBrightness. Read // at command time, so a device moved to another screen (or unpaired) is judged as it is now. registry.register(createBrightnessProvider(brightness, brightnessChanged, (id) => deviceService.deviceScreenOf(id))) diff --git a/server/src/demo/providers.ts b/server/src/demo/providers.ts index 2283d965..9cb49074 100644 --- a/server/src/demo/providers.ts +++ b/server/src/demo/providers.ts @@ -65,9 +65,28 @@ export function createDemoProviders(opts: DemoProviderOptions): Provider[] { { channel: 'shortcuts', commands: { open: ACTED } }, { channel: 'messages-2fa', commands: { copyLatest: async () => ({ ok: false, error: tr(undefined, 'messages2fa.noneFound') }) } }, serviceStatusProvider(now, opts.instances ?? ((id) => findInstance(opts.config(), id))), + recentProjectsProvider(now), ] } +function recentProjectsProvider(now: () => number): Provider { + const historyStartsAt = now() - 7 * 86_400_000 + return { + channel: 'recent-projects', + intervalMs: 30_000, + poll: async () => ({ + historyStartsAt, + coverage: 'herdr-cwd-since-first-observation', + projects: [ + { path: '/Users/demo/Projects/Fremkit', name: 'Fremkit', lastSeen: now() - 2_400_000 }, + { path: '/Users/demo/Projects/Weather', name: 'Weather', lastSeen: now() - 19_200_000 }, + { path: '/Users/demo/Projects/Notes', name: 'Notes', lastSeen: now() - 46_800_000 }, + ], + }), + commands: { open: ACTED }, + } +} + function systemProvider(now: () => number, startedAt: number): Provider { const total = 32 * GB return { diff --git a/server/src/providers/recent-projects.ts b/server/src/providers/recent-projects.ts new file mode 100644 index 00000000..1de630f5 --- /dev/null +++ b/server/src/providers/recent-projects.ts @@ -0,0 +1,213 @@ +import { execFile as nodeExecFile } from 'node:child_process' +import { constants } from 'node:fs' +import { access, mkdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { basename, dirname, isAbsolute, join } from 'node:path' +import { promisify } from 'node:util' +import { z } from 'zod' +import { safePath } from '../system-path.js' +import type { CommandContext, Provider } from './types.js' + +const execFile = promisify(nodeExecFile) +const HISTORY_LIMIT = 50 +const COMMAND_TIMEOUT_MS = 5_000 +const HistorySchema = z.object({ + historyStartsAt: z.number().finite(), + projects: z.array(z.object({ + path: z.string().min(1), + name: z.string().min(1), + lastSeen: z.number().finite(), + })).max(HISTORY_LIMIT), +}) +const OpenSchema = z.object({ + path: z.string().min(1).max(4096), + target: z.enum(['herdr', 'claude', 'codex', 'custom']), + customCommand: z.string().max(120).optional(), +}) +const SplitPaneSchema = z.object({ result: z.object({ pane: z.object({ pane_id: z.string().min(1) }) }) }) + +export interface RecentProject { + path: string + name: string + lastSeen: number +} + +interface History { + historyStartsAt: number + projects: RecentProject[] +} + +interface HerdrPane { + pane_id?: unknown + cwd?: unknown + foreground_cwd?: unknown +} + +type Run = (file: string, args: string[]) => Promise<{ stdout: string }> +type ListPanes = () => Promise<{ panes: HerdrPane[] }> +type ExecutableName = 'herdr' | 'claude' | 'codex' +type ResolveExecutable = (name: ExecutableName) => Promise + +const EXECUTABLE_CANDIDATES: Record string[]> = { + herdr: (home) => [join(home, '.local/bin/herdr'), join(home, '.cargo/bin/herdr'), '/opt/homebrew/bin/herdr', '/usr/local/bin/herdr'], + claude: (home) => [join(home, '.local/bin/claude'), '/opt/homebrew/bin/claude', '/usr/local/bin/claude'], + codex: (home) => [join(home, '.local/bin/codex'), '/opt/homebrew/bin/codex', '/usr/local/bin/codex'], +} + +export interface RecentProjectsOptions { + filePath: string + listPanes?: ListPanes + run?: Run + resolveExecutable?: ResolveExecutable + now?: () => number +} + +const defaultRun: Run = async (file, args) => { + const result = await execFile(file, args, { + timeout: COMMAND_TIMEOUT_MS, + maxBuffer: 1024 * 1024, + env: { ...process.env, PATH: safePath(process.env.PATH) }, + }) + return { stdout: result.stdout } +} + +async function isExecutableFile(path: string): Promise { + if (!isAbsolute(path)) return false + try { + const [info] = await Promise.all([stat(path), access(path, constants.X_OK)]) + return info.isFile() + } catch { + return false + } +} + +async function resolveKnownExecutable(name: ExecutableName): Promise { + for (const candidate of EXECUTABLE_CANDIDATES[name](homedir())) { + if (await isExecutableFile(candidate)) return candidate + } + return undefined +} + +function parsePaneList(stdout: string): { panes: HerdrPane[] } { + const parsed: unknown = JSON.parse(stdout) + const panes = z.object({ result: z.object({ panes: z.array(z.record(z.string(), z.unknown())) }) }) + .or(z.object({ panes: z.array(z.record(z.string(), z.unknown())) })) + .parse(parsed) + return { panes: 'result' in panes ? panes.result.panes : panes.panes } +} + +function defaultListPanes(run: Run, herdrPath: string): ListPanes { + return async () => parsePaneList((await run(herdrPath, ['pane', 'list'])).stdout) +} + +async function readHistory(filePath: string, now: () => number): Promise { + try { + return HistorySchema.parse(JSON.parse(await readFile(filePath, 'utf8'))) + } catch { + return { historyStartsAt: now(), projects: [] } + } +} + +async function saveHistory(filePath: string, history: History): Promise { + await mkdir(dirname(filePath), { recursive: true }) + const tempPath = `${filePath}.${process.pid}.tmp` + await writeFile(tempPath, JSON.stringify(history, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 }) + await rename(tempPath, filePath) +} + +async function canonicalDirectory(value: unknown): Promise { + if (typeof value !== 'string' || !value.startsWith('/')) return undefined + try { + const canonical = await realpath(value) + return (await stat(canonical)).isDirectory() ? canonical : undefined + } catch { + return undefined + } +} + +async function observedDirectories(listPanes: ListPanes): Promise { + const { panes } = await listPanes() + const paths = await Promise.all(panes.map(async (pane) => + (await canonicalDirectory(pane.foreground_cwd)) ?? canonicalDirectory(pane.cwd), + )) + return [...new Set(paths.filter((path): path is string => Boolean(path)))] +} + +async function createProjectPane( + run: Run, + herdrPath: string, + projectPath: string, + target?: { executable: string; searchPath: string }, +): Promise<{ ok: boolean; error?: string }> { + const args = ['pane', 'split', '--cwd', projectPath, '--direction', 'right', '--no-focus'] + if (target) args.push('--env', `PATH=${target.searchPath}`) + const split = await run(herdrPath, args) + let splitResult: unknown + try { + splitResult = JSON.parse(split.stdout) + } catch { + return { ok: false, error: 'new-pane-not-found' } + } + const parsedSplit = SplitPaneSchema.safeParse(splitResult) + if (!parsedSplit.success) return { ok: false, error: 'new-pane-not-found' } + const paneId = parsedSplit.data.result.pane.pane_id + if (target) await run(herdrPath, ['pane', 'run', paneId, basename(target.executable)]) + return { ok: true } +} + +/** + * Remembers only working-directory paths reported by Herdr panes. It does not read pane output, + * shell history, Claude/Codex transcripts, or any other session contents. + */ +export function createRecentProjectsProvider(options: RecentProjectsOptions): Provider { + const now = options.now ?? Date.now + const run = options.run ?? defaultRun + const resolveExecutable = options.resolveExecutable ?? resolveKnownExecutable + + return { + channel: 'recent-projects', + intervalMs: 30_000, + async poll() { + const history = await readHistory(options.filePath, now) + const observedAt = now() + const herdrPath = options.listPanes ? undefined : await resolveExecutable('herdr') + if (!options.listPanes && !herdrPath) return { ...history, coverage: 'herdr-cwd-since-first-observation', error: 'herdr-unconfigured' } + let observed: string[] + try { + observed = await observedDirectories(options.listPanes ?? defaultListPanes(run, herdrPath!)) + } catch { + return { ...history, coverage: 'herdr-cwd-since-first-observation', error: 'herdr-unavailable' } + } + const byPath = new Map(history.projects.map((project) => [project.path, project])) + for (const path of observed) byPath.set(path, { path, name: basename(path) || path, lastSeen: observedAt }) + const projects = [...byPath.values()].sort((a, b) => b.lastSeen - a.lastSeen).slice(0, HISTORY_LIMIT) + const next = { historyStartsAt: history.historyStartsAt, projects } + await saveHistory(options.filePath, next) + return { ...next, coverage: 'herdr-cwd-since-first-observation' } + }, + commands: { + async open(payload: unknown, context?: CommandContext) { + if (!context?.loopback) return { ok: false, error: 'loopback-required' } + const parsed = OpenSchema.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-request' } + const { path, target } = parsed.data + const history = await readHistory(options.filePath, now) + const project = history.projects.find((item) => item.path === path) + const canonical = await canonicalDirectory(path) + if (!project || canonical !== path) return { ok: false, error: 'project-not-in-history' } + if (target === 'custom') return { ok: false, error: 'custom-target-unsupported' } + const herdrPath = await resolveExecutable('herdr') + if (!herdrPath) return { ok: false, error: 'herdr-unconfigured' } + const targetExecutable = target === 'herdr' ? undefined : await resolveExecutable(target) + if (target !== 'herdr' && !targetExecutable) return { ok: false, error: `${target}-unconfigured` } + try { + return await createProjectPane(run, herdrPath, path, targetExecutable + ? { executable: targetExecutable, searchPath: safePath(dirname(targetExecutable)) } + : undefined) + } catch { + return { ok: false, error: 'herdr-unavailable' } + } + }, + }, + } +} diff --git a/server/test/recent-projects.test.ts b/server/test/recent-projects.test.ts new file mode 100644 index 00000000..1ab57434 --- /dev/null +++ b/server/test/recent-projects.test.ts @@ -0,0 +1,247 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createRecentProjectsProvider, type RecentProject } from '../src/providers/recent-projects.js' + +const LOCAL = { loopback: true, paired: false } +const resolveTrustedExecutable = vi.fn(async (name: string) => `/trusted/bin/${name}`) +let dir = '' + +afterEach(async () => { + if (dir) await rm(dir, { recursive: true, force: true }) + dir = '' +}) + +describe('recent projects', () => { + it('records only foreground Herdr working directories and persists bounded de-duplicated history', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const first = join(dir, 'first') + const second = join(dir, 'second') + const { mkdir, realpath, stat } = await import('node:fs/promises') + await mkdir(first) + await mkdir(second) + const listPanes = vi.fn(async () => ({ panes: [ + { id: 'p1', cwd: first, foreground_cwd: first }, + { id: 'p2', cwd: second, foreground_cwd: second }, + { id: 'p3', cwd: '/not/observed', foreground_cwd: '' }, + ] })) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), listPanes, now: () => 100 }) + + const snapshot = await provider.poll!() as { projects: { path: string; lastSeen: number }[]; historyStartsAt: number } + + expect(new Set(snapshot.projects.map((project) => project.path))).toEqual(new Set(await Promise.all([first, second].map((path) => realpath(path))))) + expect(snapshot.projects.every((project) => project.lastSeen === 100)).toBe(true) + expect(snapshot.historyStartsAt).toBe(100) + expect(JSON.parse(await readFile(join(dir, 'history.json'), 'utf8'))).toMatchObject({ projects: snapshot.projects }) + expect((await stat(join(dir, 'history.json'))).mode & 0o777).toBe(0o600) + }) + + it('falls back to the pane cwd when foreground cwd is empty', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + const provider = createRecentProjectsProvider({ + filePath: join(dir, 'history.json'), + listPanes: vi.fn(async () => ({ panes: [{ cwd: project, foreground_cwd: '' }] })), + now: () => 101, + }) + + const snapshot = await provider.poll!() as { projects: RecentProject[] } + + expect(snapshot.projects.map(({ path }) => path)).toEqual([canonicalProject]) + }) + + it('opens only a recorded directory in a newly created pane and targets its new pane', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, writeFile, realpath } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + const run = vi.fn(async (_file: string, args: string[]) => ({ stdout: args[1] === 'split' ? JSON.stringify({ result: { pane: { pane_id: 'new' } } }) : '' })) + const listPanes = vi.fn().mockResolvedValueOnce({ panes: [{ pane_id: 'existing', cwd: canonicalProject, foreground_cwd: canonicalProject }] }) + .mockResolvedValueOnce({ panes: [{ pane_id: 'existing', cwd: canonicalProject, foreground_cwd: canonicalProject }, { pane_id: 'new', cwd: canonicalProject, foreground_cwd: canonicalProject }] }) + const provider = createRecentProjectsProvider({ + filePath: join(dir, 'history.json'), + listPanes, + run, + resolveExecutable: resolveTrustedExecutable, + }) + + const result = await provider.commands!.open({ path: canonicalProject, target: 'codex' }, LOCAL) + + expect(result).toMatchObject({ ok: true }) + expect(listPanes).not.toHaveBeenCalled() + expect(run.mock.calls).toEqual([ + ['/trusted/bin/herdr', ['pane', 'split', '--cwd', canonicalProject, '--direction', 'right', '--no-focus', '--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin']], + ['/trusted/bin/herdr', ['pane', 'run', 'new', 'codex']], + ]) + }) + + it('fails closed when no trusted Herdr executable can be resolved', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath, writeFile } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + const run = vi.fn() + const provider = createRecentProjectsProvider({ + filePath: join(dir, 'history.json'), + run, + resolveExecutable: vi.fn(async () => undefined), + }) + + expect(await provider.commands!.open({ path: canonicalProject, target: 'codex' }, LOCAL)).toMatchObject({ ok: false, error: 'herdr-unconfigured' }) + expect(run).not.toHaveBeenCalled() + }) + + it('uses one trusted absolute resolver for Claude Code and Codex launch targets', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath, writeFile } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + const run = vi.fn(async (_file: string, args: string[]) => ({ stdout: args[1] === 'split' ? JSON.stringify({ result: { pane: { pane_id: 'new' } } }) : '' })) + const resolver = vi.fn(async (name: string) => `/trusted/bin/${name}`) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), run, resolveExecutable: resolver }) + + await provider.commands!.open({ path: canonicalProject, target: 'claude' }, LOCAL) + await provider.commands!.open({ path: canonicalProject, target: 'codex' }, LOCAL) + + expect(resolver.mock.calls).toEqual([['herdr'], ['claude'], ['herdr'], ['codex']]) + expect(run.mock.calls.filter(([, args]) => args[1] === 'run').map(([, args]) => args[3])).toEqual(['claude', 'codex']) + expect(run.mock.calls.filter(([, args]) => args[1] === 'split').map(([, args]) => args.slice(-2))).toEqual([ + ['--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin'], + ['--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin'], + ]) + }) + + it('targets the exact pane returned by each concurrent split for the same folder', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath, writeFile } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + + let splitCount = 0 + let releaseSplits!: () => void + const bothSplitsStarted = new Promise((resolve) => { releaseSplits = resolve }) + const run = vi.fn(async (_file: string, args: string[]) => { + if (args[1] !== 'split') return { stdout: '' } + const paneId = splitCount++ === 0 ? 'new-a' : 'new-b' + if (splitCount === 2) releaseSplits() + await bothSplitsStarted + return { stdout: JSON.stringify({ result: { pane: { pane_id: paneId } } }) } + }) + const listPanes = vi.fn(async () => ({ panes: [{ pane_id: 'existing', cwd: canonicalProject, foreground_cwd: canonicalProject }] })) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), listPanes, run, resolveExecutable: resolveTrustedExecutable }) + + const results = await Promise.all([ + provider.commands!.open({ path: canonicalProject, target: 'codex' }, LOCAL), + provider.commands!.open({ path: canonicalProject, target: 'claude' }, LOCAL), + ]) + + expect(results).toMatchObject([{ ok: true }, { ok: true }]) + expect(run.mock.calls.filter(([, args]) => args[1] === 'run').map(([, args]) => args[2]).sort()).toEqual(['new-a', 'new-b']) + }) + + it('reads Herdr’s JSON CLI envelope without inspecting pane contents', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + const run = vi.fn(async () => ({ stdout: JSON.stringify({ id: 'read-only', result: { type: 'pane.list', panes: [{ pane_id: 'p', cwd: canonicalProject, foreground_cwd: canonicalProject, scroll: 'ignored' }] } }) })) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), run, now: () => 9, resolveExecutable: resolveTrustedExecutable }) + + const snapshot = await provider.poll!() as { projects: RecentProject[]; coverage: string } + + expect(run).toHaveBeenCalledWith('/trusted/bin/herdr', ['pane', 'list']) + expect(snapshot.projects.map(({ path }) => path)).toEqual([canonicalProject]) + expect(snapshot.coverage).toBe('herdr-cwd-since-first-observation') + }) + + it('keeps the history bounded to the 50 most recently observed folders', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const { mkdir, realpath } = await import('node:fs/promises') + const paths = Array.from({ length: 51 }, (_, index) => join(dir, `project-${index}`)) + await Promise.all(paths.map((path) => mkdir(path))) + const canonicalPaths = await Promise.all(paths.map((path) => realpath(path))) + const provider = createRecentProjectsProvider({ + filePath: join(dir, 'history.json'), + listPanes: vi.fn(async () => ({ panes: canonicalPaths.map((foreground_cwd) => ({ foreground_cwd })) })), + now: () => 5, + }) + + const snapshot = await provider.poll!() as { projects: RecentProject[] } + + expect(snapshot.projects).toHaveLength(50) + expect(snapshot.projects.every((project) => canonicalPaths.includes(project.path))).toBe(true) + }) + + it('rejects custom executables before pane creation because Herdr pane run accepts only PATH command names', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, realpath, writeFile } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + const run = vi.fn() + const listPanes = vi.fn().mockResolvedValueOnce({ panes: [{ pane_id: 'existing', cwd: canonicalProject }] }) + .mockResolvedValueOnce({ panes: [{ pane_id: 'existing', cwd: canonicalProject }, { pane_id: 'new', cwd: canonicalProject }] }) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), run, listPanes, resolveExecutable: resolveTrustedExecutable }) + + expect(await provider.commands!.open({ path: canonicalProject, target: 'custom', customCommand: 'my-editor' }, LOCAL)).toMatchObject({ ok: false, error: 'custom-target-unsupported' }) + expect(await provider.commands!.open({ + path: canonicalProject, + target: 'custom', + customExecutable: '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code', + customArgs: ['--reuse-window'], + }, LOCAL)).toMatchObject({ ok: false, error: 'custom-target-unsupported' }) + expect(await provider.commands!.open({ + path: canonicalProject, + target: 'custom', + customExecutable: '/tmp/my-editor', + customArgs: [';$(touch /tmp/pwned)'], + }, LOCAL)).toMatchObject({ ok: false, error: 'custom-target-unsupported' }) + expect(run).not.toHaveBeenCalled() + expect(listPanes).not.toHaveBeenCalled() + }) + + it('refuses arbitrary paths and non-loopback commands without launching anything', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, writeFile } = await import('node:fs/promises') + await mkdir(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: project, name: 'project', lastSeen: 2 }] })) + const run = vi.fn() + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), listPanes: vi.fn(), run }) + + expect(await provider.commands!.open({ path: '/tmp/not-recorded', target: 'claude' }, LOCAL)).toMatchObject({ ok: false }) + expect(await provider.commands!.open({ path: project, target: 'claude' }, { loopback: false, paired: false })).toMatchObject({ ok: false }) + expect(run).not.toHaveBeenCalled() + }) + + it('keeps the saved history visible when Herdr cannot be queried', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const { mkdir, writeFile } = await import('node:fs/promises') + await mkdir(project) + const canonicalProject = await (await import('node:fs/promises')).realpath(project) + const filePath = join(dir, 'history.json') + const saved = { historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] } + await writeFile(filePath, JSON.stringify(saved)) + const provider = createRecentProjectsProvider({ filePath, listPanes: vi.fn().mockRejectedValue(new Error('Herdr unavailable')) }) + + const snapshot = await provider.poll!() as typeof saved & { error: string } + + expect(snapshot).toMatchObject({ ...saved, error: 'herdr-unavailable' }) + expect(JSON.parse(await readFile(filePath, 'utf8'))).toEqual(saved) + }) +}) From 03dd9e9c082fceb58dc124719ff13b908f85e6d6 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 22:46:30 +0200 Subject: [PATCH 13/24] Fix Recent Projects target PATH precedence --- server/src/providers/recent-projects.ts | 2 +- server/test/recent-projects.test.ts | 47 +++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/server/src/providers/recent-projects.ts b/server/src/providers/recent-projects.ts index 1de630f5..63ae786e 100644 --- a/server/src/providers/recent-projects.ts +++ b/server/src/providers/recent-projects.ts @@ -202,7 +202,7 @@ export function createRecentProjectsProvider(options: RecentProjectsOptions): Pr if (target !== 'herdr' && !targetExecutable) return { ok: false, error: `${target}-unconfigured` } try { return await createProjectPane(run, herdrPath, path, targetExecutable - ? { executable: targetExecutable, searchPath: safePath(dirname(targetExecutable)) } + ? { executable: targetExecutable, searchPath: [dirname(targetExecutable), safePath(process.env.PATH)].join(':') } : undefined) } catch { return { ok: false, error: 'herdr-unavailable' } diff --git a/server/test/recent-projects.test.ts b/server/test/recent-projects.test.ts index 1ab57434..8a6e172e 100644 --- a/server/test/recent-projects.test.ts +++ b/server/test/recent-projects.test.ts @@ -1,9 +1,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' +import { execFile as nodeExecFile } from 'node:child_process' import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { promisify } from 'node:util' import { createRecentProjectsProvider, type RecentProject } from '../src/providers/recent-projects.js' +import { safePath } from '../src/system-path.js' +const execFile = promisify(nodeExecFile) const LOCAL = { loopback: true, paired: false } const resolveTrustedExecutable = vi.fn(async (name: string) => `/trusted/bin/${name}`) let dir = '' @@ -76,7 +80,7 @@ describe('recent projects', () => { expect(result).toMatchObject({ ok: true }) expect(listPanes).not.toHaveBeenCalled() expect(run.mock.calls).toEqual([ - ['/trusted/bin/herdr', ['pane', 'split', '--cwd', canonicalProject, '--direction', 'right', '--no-focus', '--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin']], + ['/trusted/bin/herdr', ['pane', 'split', '--cwd', canonicalProject, '--direction', 'right', '--no-focus', '--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`]], ['/trusted/bin/herdr', ['pane', 'run', 'new', 'codex']], ]) }) @@ -116,11 +120,48 @@ describe('recent projects', () => { expect(resolver.mock.calls).toEqual([['herdr'], ['claude'], ['herdr'], ['codex']]) expect(run.mock.calls.filter(([, args]) => args[1] === 'run').map(([, args]) => args[3])).toEqual(['claude', 'codex']) expect(run.mock.calls.filter(([, args]) => args[1] === 'split').map(([, args]) => args.slice(-2))).toEqual([ - ['--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin'], - ['--env', 'PATH=/usr/bin:/bin:/usr/sbin:/sbin:/trusted/bin'], + ['--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`], + ['--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`], ]) }) + it('launches the validated target before an inherited same-name executable', async () => { + dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) + const project = join(dir, 'project') + const targetDir = join(dir, 'validated') + const shadowDir = join(dir, 'inherited') + const targetExecutable = join(targetDir, 'claude') + const shadowExecutable = join(shadowDir, 'claude') + const { chmod, mkdir, realpath, writeFile } = await import('node:fs/promises') + await Promise.all([mkdir(project), mkdir(targetDir), mkdir(shadowDir)]) + const canonicalProject = await realpath(project) + await writeFile(join(dir, 'history.json'), JSON.stringify({ historyStartsAt: 1, projects: [{ path: canonicalProject, name: 'project', lastSeen: 2 }] })) + await writeFile(targetExecutable, '#!/bin/sh\nprintf validated-target\n') + await writeFile(shadowExecutable, '#!/bin/sh\nprintf shadow-target\n') + await Promise.all([chmod(targetExecutable, 0o755), chmod(shadowExecutable, 0o755)]) + const run = vi.fn(async (_file: string, args: string[]) => ({ stdout: args[1] === 'split' ? JSON.stringify({ result: { pane: { pane_id: 'new' } } }) : '' })) + const resolveExecutable = vi.fn(async (name: string) => name === 'herdr' ? '/trusted/bin/herdr' : targetExecutable) + const provider = createRecentProjectsProvider({ filePath: join(dir, 'history.json'), run, resolveExecutable }) + const originalPath = process.env.PATH + + try { + process.env.PATH = `${shadowDir}:/usr/bin:/bin` + expect(await provider.commands!.open({ path: canonicalProject, target: 'claude' }, LOCAL)).toMatchObject({ ok: true }) + const splitArgs = run.mock.calls.find(([, args]) => args[1] === 'split')?.[1] + const pathAssignment = splitArgs?.[splitArgs.indexOf('--env') + 1] + expect(pathAssignment?.startsWith('PATH=')).toBe(true) + const searchPath = pathAssignment!.slice('PATH='.length) + expect(searchPath.split(':').slice(0, 2)).toEqual([targetDir, '/usr/bin']) + expect(searchPath.split(':')).toContain(shadowDir) + + const { stdout } = await execFile('claude', [], { env: { PATH: searchPath } }) + expect(stdout).toBe('validated-target') + } finally { + if (originalPath === undefined) delete process.env.PATH + else process.env.PATH = originalPath + } + }) + it('targets the exact pane returned by each concurrent split for the same folder', async () => { dir = await mkdtemp(join(tmpdir(), 'fremkit-recent-projects-')) const project = join(dir, 'project') From dc378df195ac40d4b6729243b925a20681d5b9d7 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 22:58:45 +0200 Subject: [PATCH 14/24] Keep protected system directories first for launches Run the validated target directory through safePath with the inherited PATH, so the policy-protected system directories remain first while the validated executable still outranks shadow copies elsewhere. Cover the production PATH and executable lookup with synthetic fixtures. Co-Authored-By: Claude --- server/src/providers/recent-projects.ts | 2 +- server/test/recent-projects.test.ts | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/server/src/providers/recent-projects.ts b/server/src/providers/recent-projects.ts index 63ae786e..3bd8a938 100644 --- a/server/src/providers/recent-projects.ts +++ b/server/src/providers/recent-projects.ts @@ -202,7 +202,7 @@ export function createRecentProjectsProvider(options: RecentProjectsOptions): Pr if (target !== 'herdr' && !targetExecutable) return { ok: false, error: `${target}-unconfigured` } try { return await createProjectPane(run, herdrPath, path, targetExecutable - ? { executable: targetExecutable, searchPath: [dirname(targetExecutable), safePath(process.env.PATH)].join(':') } + ? { executable: targetExecutable, searchPath: safePath([dirname(targetExecutable), process.env.PATH ?? ''].join(':')) } : undefined) } catch { return { ok: false, error: 'herdr-unavailable' } diff --git a/server/test/recent-projects.test.ts b/server/test/recent-projects.test.ts index 8a6e172e..6d187fbf 100644 --- a/server/test/recent-projects.test.ts +++ b/server/test/recent-projects.test.ts @@ -80,7 +80,7 @@ describe('recent projects', () => { expect(result).toMatchObject({ ok: true }) expect(listPanes).not.toHaveBeenCalled() expect(run.mock.calls).toEqual([ - ['/trusted/bin/herdr', ['pane', 'split', '--cwd', canonicalProject, '--direction', 'right', '--no-focus', '--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`]], + ['/trusted/bin/herdr', ['pane', 'split', '--cwd', canonicalProject, '--direction', 'right', '--no-focus', '--env', `PATH=${safePath(['/trusted/bin', process.env.PATH ?? ''].join(':'))}`]], ['/trusted/bin/herdr', ['pane', 'run', 'new', 'codex']], ]) }) @@ -120,8 +120,8 @@ describe('recent projects', () => { expect(resolver.mock.calls).toEqual([['herdr'], ['claude'], ['herdr'], ['codex']]) expect(run.mock.calls.filter(([, args]) => args[1] === 'run').map(([, args]) => args[3])).toEqual(['claude', 'codex']) expect(run.mock.calls.filter(([, args]) => args[1] === 'split').map(([, args]) => args.slice(-2))).toEqual([ - ['--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`], - ['--env', `PATH=/trusted/bin:${safePath(process.env.PATH)}`], + ['--env', `PATH=${safePath(['/trusted/bin', process.env.PATH ?? ''].join(':'))}`], + ['--env', `PATH=${safePath(['/trusted/bin', process.env.PATH ?? ''].join(':'))}`], ]) }) @@ -151,8 +151,10 @@ describe('recent projects', () => { const pathAssignment = splitArgs?.[splitArgs.indexOf('--env') + 1] expect(pathAssignment?.startsWith('PATH=')).toBe(true) const searchPath = pathAssignment!.slice('PATH='.length) - expect(searchPath.split(':').slice(0, 2)).toEqual([targetDir, '/usr/bin']) - expect(searchPath.split(':')).toContain(shadowDir) + const searchDirs = searchPath.split(':') + expect(searchDirs.slice(0, 4)).toEqual(['/usr/bin', '/bin', '/usr/sbin', '/sbin']) + expect(searchDirs.indexOf(targetDir)).toBeGreaterThan(3) + expect(searchDirs.indexOf(targetDir)).toBeLessThan(searchDirs.indexOf(shadowDir)) const { stdout } = await execFile('claude', [], { env: { PATH: searchPath } }) expect(stdout).toBe('validated-target') From 8e71034d956f00afbdf7db2ddaeb5be975e38d8e Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 08:23:09 +0200 Subject: [PATCH 15/24] Add selected-text translation and ShellSmith providers --- server/src/connections/types/index.ts | 1 + .../connections/types/openai-shellsmith.ts | 14 ++- server/src/providers/openai-shellsmith.ts | 56 ++++++++- .../src/providers/selected-text-native.swift | 60 ++++++++++ server/src/providers/selected-text.ts | 35 ++++++ server/test/selected-text.test.ts | 27 +++++ server/test/shellsmith.test.ts | 110 +++++++++++++----- 7 files changed, 264 insertions(+), 39 deletions(-) create mode 100644 server/src/providers/selected-text-native.swift create mode 100644 server/src/providers/selected-text.ts create mode 100644 server/test/selected-text.test.ts diff --git a/server/src/connections/types/index.ts b/server/src/connections/types/index.ts index 8a41bd8f..b89d435f 100644 --- a/server/src/connections/types/index.ts +++ b/server/src/connections/types/index.ts @@ -10,4 +10,5 @@ import type { ConnectionType } from '../types.js' /** Every connection type the server ships with. */ export function defaultConnectionTypes(): ConnectionType[] { return [azureDevOpsType, bambuType, githubType, icsType, synologyType, vercelType, openAIShellsmithType] + } diff --git a/server/src/connections/types/openai-shellsmith.ts b/server/src/connections/types/openai-shellsmith.ts index 9a145266..2bf03d63 100644 --- a/server/src/connections/types/openai-shellsmith.ts +++ b/server/src/connections/types/openai-shellsmith.ts @@ -1,18 +1,24 @@ import { tr } from '../../i18n.js' -import type { ConnectionType, TestResult } from '../types.js' +import { OptionsError, type ConnectionType, type PickOption, type TestResult } from '../types.js' import { GROQ_API, OPENAI_API, OPENAI_TIMEOUT_MS, createOpenAIShellsmithProvider } from '../../providers/openai-shellsmith.js' import type { OpenAIShellsmithDeps } from '../../providers/openai-shellsmith.js' import { USER_AGENT } from '../../version.js' import { readJsonCapped } from '../../net/json.js' const ModelSchema = /^[A-Za-z0-9._:/-]{1,100}$/ +const languages: PickOption[] = [ + { value: 'en', label: 'English' }, { value: 'fr', label: 'Français' }, { value: 'de', label: 'Deutsch' }, + { value: 'es', label: 'Español' }, { value: 'it', label: 'Italiano' }, { value: 'pt', label: 'Português' }, + { value: 'nl', label: 'Nederlands' }, { value: 'ja', label: '日本語' }, { value: 'zh', label: '中文' }, +] + const providerFor = (fields: Record): 'openai' | 'groq' | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' ? 'openai' : fields.provider === 'groq' ? 'groq' : null export const openAIShellsmithType: ConnectionType = { id: 'openai-shellsmith', name: 'OpenAI-compatible AI', - description: { fr: 'Suggestions de commandes via une API compatible OpenAI', en: 'Command suggestions through an OpenAI-compatible API' }, + description: { fr: 'Suggestions de commandes et traduction via une API compatible OpenAI', en: 'Command suggestions and translation through an OpenAI-compatible API' }, icon: 'sparkles', secretBindings: ['provider'], fields: [ @@ -57,5 +63,9 @@ export const openAIShellsmithType: ConnectionType = { : { ok: false, error: tr(undefined, 'shellsmith.unexpected', { status: 200 }) } } catch { return { ok: false, error: tr(undefined, 'shellsmith.unreachable') } } }, + async options(source): Promise { + if (source !== 'languages') throw new OptionsError(400, tr(undefined, 'connections.unknownSource', { source })) + return languages + }, createProvider: (ctx) => createOpenAIShellsmithProvider(ctx), } diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts index 16da45e8..a266d6f5 100644 --- a/server/src/providers/openai-shellsmith.ts +++ b/server/src/providers/openai-shellsmith.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import type { ConnectionProviderContext } from '../connections/types.js' import { pbPasteboard, type Pasteboard } from './clipboard.js' +import { readSelectedText, type SelectedTextResult } from './selected-text.js' import type { CommandContext, Provider } from './types.js' import { USER_AGENT } from '../version.js' import { readJsonCapped } from '../net/json.js' @@ -10,12 +11,13 @@ export const GROQ_API = 'https://api.groq.com/openai/v1' export const OPENAI_TIMEOUT_MS = 25_000 export const SHELLSMITH_MAX_REQUEST_CHARS = 1000 export const SHELLSMITH_MAX_COMMAND_CHARS = 2000 +export const TRANSLATE_MAX_TEXT_BYTES = 2048 const ModelSchema = z.string().trim().min(1).max(100).regex(/^[A-Za-z0-9._:/-]+$/) -// The dashboard stamps every widget command with the sending widget instance id. -const INSTANCE = { instanceId: z.string().min(1).max(200).optional() } -const RequestPayload = z.strictObject({ ...INSTANCE, request: z.string().trim().min(1).max(SHELLSMITH_MAX_REQUEST_CHARS) }) -const CopyPayload = z.strictObject({ ...INSTANCE, command: z.string().trim().min(1).max(SHELLSMITH_MAX_COMMAND_CHARS) }) +const RequestPayload = z.strictObject({ request: z.string().trim().min(1).max(SHELLSMITH_MAX_REQUEST_CHARS) }) +const CopyPayload = z.strictObject({ command: z.string().trim().min(1).max(SHELLSMITH_MAX_COMMAND_CHARS) }) +const FavoritesPayload = z.strictObject({ favorites: z.array(z.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/)).length(2) }) +const TranslationResponse = z.strictObject({ sourceLanguage: z.string().trim().min(2).max(20), text: z.string().trim().min(1).max(20_000) }) interface ResponsesBody { output?: Array<{ content?: Array<{ type?: unknown; text?: unknown }> }> @@ -30,18 +32,27 @@ type CompletionResult = export interface OpenAIShellsmithDeps { fetchFn?: typeof fetch pasteboard?: Pasteboard + selectedText?: () => Promise } type ApiProvider = 'openai' | 'groq' const providerFor = (fields: Record): ApiProvider | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' ? 'openai' : fields.provider === 'groq' ? 'groq' : null const apiFor = (provider: ApiProvider): string => provider === 'groq' ? GROQ_API : OPENAI_API +const languageAliases: Record = { + english: 'en', français: 'fr', french: 'fr', deutsch: 'de', german: 'de', español: 'es', spanish: 'es', + italiano: 'it', italian: 'it', português: 'pt', portuguese: 'pt', nederlands: 'nl', dutch: 'nl', + 日本語: 'ja', japanese: 'ja', 中文: 'zh', chinese: 'zh', +} +const baseLanguage = (code: string): string => languageAliases[code.trim().toLowerCase()] ?? code.split('-')[0].toLowerCase() + async function chatCompletion( fetchFn: typeof fetch, api: string, token: string, model: string, prompt: string, + json: boolean, ): Promise { const reasoningModel = model.startsWith('openai/gpt-oss-') let response: Response @@ -60,6 +71,7 @@ async function chatCompletion( messages: [{ role: 'user', content: prompt }], max_completion_tokens: reasoningModel ? 1200 : 800, temperature: 0.2, + ...(json ? { response_format: { type: 'json_object' } } : {}), ...(reasoningModel ? { reasoning_effort: 'low', reasoning_format: 'hidden' } : {}), }), signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), @@ -82,6 +94,7 @@ async function chatCompletion( export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, deps: OpenAIShellsmithDeps = {}): Provider { const fetchFn = deps.fetchFn ?? fetch const pasteboard = deps.pasteboard ?? pbPasteboard + const selectedText = deps.selectedText ?? readSelectedText const token = ctx.secrets.token?.trim() ?? '' const modelResult = ModelSchema.safeParse(ctx.fields.model) const provider = providerFor(ctx.fields) @@ -98,7 +111,8 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d if (provider === 'groq') { const completion = await chatCompletion(fetchFn, api, token, modelResult.data, - `Suggest one shell command for this request. Do not execute it, call tools, or include secrets. Return only command text, without markdown or explanation. Avoid destructive commands unless explicitly requested.\n\nRequest: ${parsed.data.request}`) + `Suggest one shell command for this request. Do not execute it, call tools, or include secrets. Return only command text, without markdown or explanation. Avoid destructive commands unless explicitly requested.\n\nRequest: ${parsed.data.request}`, + false) if (!completion.ok) return completion if (completion.content.length > SHELLSMITH_MAX_COMMAND_CHARS) return { ok: false, error: 'invalid-response' } return { ok: true, command: completion.content } @@ -140,6 +154,38 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d if (!command || command.length > SHELLSMITH_MAX_COMMAND_CHARS) return { ok: false, error: 'invalid-response' } return { ok: true, command } }, + translateSelection: async (payload, commandContext?: CommandContext) => { + if (!commandContext?.loopback) return { ok: false, error: 'local-only' } + const parsed = FavoritesPayload.safeParse(payload) + if (!provider) return { ok: false, error: 'invalid-request' } + if (!parsed.success || !modelResult.success) return { ok: false, error: 'choose-two-languages' } + const [favoriteA, favoriteB] = parsed.data.favorites + const aBase = baseLanguage(favoriteA) + const bBase = baseLanguage(favoriteB) + if (aBase === bBase) return { ok: false, error: 'choose-two-languages' } + if (!token) return { ok: false, error: 'unconfigured' } + + let selection: SelectedTextResult + try { selection = await selectedText() } catch { return { ok: false, error: 'selection-unavailable' } } + if (!selection.ok) { + const error = selection.error === 'no-selection' ? 'empty-selection' + : selection.error === 'unavailable' ? 'selection-unavailable' : selection.error + return { ok: false, error } + } + const text = selection.text + if (!text.trim()) return { ok: false, error: 'empty-selection' } + if (new TextEncoder().encode(text).byteLength > TRANSLATE_MAX_TEXT_BYTES) return { ok: false, error: 'text-too-long' } + + const prompt = `Translate the text below into whichever of these two favorite languages is different from its source: ${favoriteA} and ${favoriteB}. Identify the source language accurately. Return only a JSON object with string properties sourceLanguage (a short language code such as en or fr) and text (the translation). If the source is neither favorite, still identify its actual language; the app will refuse to show a translation. Preserve the meaning and formatting.\n\nText to translate:\n${text}` + const completion = await chatCompletion(fetchFn, api, token, modelResult.data, prompt, true) + if (!completion.ok) return completion + let translation: z.infer + try { translation = TranslationResponse.parse(JSON.parse(completion.content)) } catch { return { ok: false, error: 'invalid-response' } } + const sourceBase = baseLanguage(translation.sourceLanguage) + if (sourceBase === aBase) return { ok: true, sourceLanguage: sourceBase, targetLanguage: favoriteB, text: translation.text } + if (sourceBase === bBase) return { ok: true, sourceLanguage: sourceBase, targetLanguage: favoriteA, text: translation.text } + return { ok: false, error: 'language-not-favorite' } + }, copyCommand: async (payload, commandContext?: CommandContext) => { if (!commandContext?.loopback) return { ok: false, error: 'local-only' } const parsed = CopyPayload.safeParse(payload) diff --git a/server/src/providers/selected-text-native.swift b/server/src/providers/selected-text-native.swift new file mode 100644 index 00000000..dacb1df1 --- /dev/null +++ b/server/src/providers/selected-text-native.swift @@ -0,0 +1,60 @@ +import AppKit +import ApplicationServices +import Foundation + +struct Result: Encodable { + let ok: Bool + var text: String? = nil + var error: String? = nil + + static func success(_ text: String) -> Result { Result(ok: true, text: text) } + static func failure(_ error: String) -> Result { Result(ok: false, error: error) } +} + +func respond(_ result: Result) -> Never { + let encoder = JSONEncoder() + if let data = try? encoder.encode(result) { + FileHandle.standardOutput.write(data) + FileHandle.standardOutput.write(Data("\n".utf8)) + } else { + FileHandle.standardOutput.write(Data("{\"ok\":false,\"error\":\"unavailable\"}\n".utf8)) + } + exit(0) +} + +func readSelection() -> Never { + guard AXIsProcessTrusted() else { respond(.failure("permission-required")) } + guard let frontmost = NSWorkspace.shared.frontmostApplication, + let bundleId = frontmost.bundleIdentifier, + !bundleId.localizedCaseInsensitiveContains("fremkit") else { + respond(.failure("no-selection")) + } + + let application = AXUIElementCreateApplication(frontmost.processIdentifier) + AXUIElementSetMessagingTimeout(application, 1.0) + var focusedValue: CFTypeRef? + let focusedError = AXUIElementCopyAttributeValue(application, kAXFocusedUIElementAttribute as CFString, &focusedValue) + guard focusedError == .success, + let focusedValue, + CFGetTypeID(focusedValue) == AXUIElementGetTypeID() else { + respond(.failure(focusedError == .apiDisabled ? "permission-required" : "no-selection")) + } + + let focused = focusedValue as! AXUIElement + var subroleValue: CFTypeRef? + if AXUIElementCopyAttributeValue(focused, kAXSubroleAttribute as CFString, &subroleValue) == .success, + let subrole = subroleValue as? String, + subrole == (kAXSecureTextFieldSubrole as String) { + respond(.failure("secure-field")) + } + + var selectionValue: CFTypeRef? + let selectionError = AXUIElementCopyAttributeValue(focused, kAXSelectedTextAttribute as CFString, &selectionValue) + guard selectionError == .success, let text = selectionValue as? String, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + respond(.failure(selectionError == .apiDisabled ? "permission-required" : "no-selection")) + } + respond(.success(text)) +} + +guard CommandLine.arguments.dropFirst().first == "read" else { respond(.failure("unavailable")) } +readSelection() diff --git a/server/src/providers/selected-text.ts b/server/src/providers/selected-text.ts new file mode 100644 index 00000000..94e11727 --- /dev/null +++ b/server/src/providers/selected-text.ts @@ -0,0 +1,35 @@ +import { execFile as nodeExecFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { z } from 'zod' + +const execFile = promisify(nodeExecFile) +const SWIFT = '/usr/bin/swift' +const HELPER = fileURLToPath(new URL('./selected-text-native.swift', import.meta.url)) +const TIMEOUT_MS = 5000 +const NativeResult = z.discriminatedUnion('ok', [ + z.object({ ok: z.literal(true), text: z.string() }).strict(), + z.object({ ok: z.literal(false), error: z.enum(['permission-required', 'secure-field', 'no-selection', 'unavailable']) }).strict(), +]) + +export type SelectedTextResult = z.infer +export type SelectedTextRunner = (file: string, args: string[]) => Promise + +const runProgram: SelectedTextRunner = async (file, args) => { + const { stdout } = await execFile(file, args, { timeout: TIMEOUT_MS, maxBuffer: 32 * 1024, shell: false }) + return stdout +} + +/** Reads the current focused selection through Accessibility without activating an app or touching the pasteboard. */ +export function createSelectedTextReader(run: SelectedTextRunner = runProgram): () => Promise { + return async () => { + try { + const response = NativeResult.safeParse(JSON.parse(await run(SWIFT, [HELPER, 'read']))) + return response.success ? response.data : { ok: false, error: 'unavailable' } + } catch { + return { ok: false, error: 'unavailable' } + } + } +} + +export const readSelectedText = createSelectedTextReader() diff --git a/server/test/selected-text.test.ts b/server/test/selected-text.test.ts new file mode 100644 index 00000000..ba509750 --- /dev/null +++ b/server/test/selected-text.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { createSelectedTextReader } from '../src/providers/selected-text.js' + +describe('selected text reader', () => { + it('uses a fixed native helper invocation and returns only the focused selection', async () => { + const calls: { file: string; args: string[] }[] = [] + const reader = createSelectedTextReader(async (file, args) => { + calls.push({ file, args }) + return JSON.stringify({ ok: true, text: 'focused selection' }) + }) + + expect(await reader()).toEqual({ ok: true, text: 'focused selection' }) + expect(calls).toHaveLength(1) + expect(calls[0].file).toBe('/usr/bin/swift') + expect(calls[0].args).toHaveLength(2) + expect(calls[0].args[0]).toMatch(/selected-text-native\.swift$/) + expect(calls[0].args[1]).toBe('read') + }) + + it('preserves fail-closed native outcomes and rejects malformed output', async () => { + const secureReader = createSelectedTextReader(async () => JSON.stringify({ ok: false, error: 'secure-field' })) + const malformedReader = createSelectedTextReader(async () => 'not json') + + expect(await secureReader()).toEqual({ ok: false, error: 'secure-field' }) + expect(await malformedReader()).toEqual({ ok: false, error: 'unavailable' }) + }) +}) diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts index 12929310..82c0bec6 100644 --- a/server/test/shellsmith.test.ts +++ b/server/test/shellsmith.test.ts @@ -12,12 +12,6 @@ const context = () => ({ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }) describe('ShellSmith command suggestion provider', () => { - it('exposes only commands used by ShellSmith', () => { - const provider = createOpenAIShellsmithProvider(context()) - - expect(Object.keys(provider.commands ?? {}).sort()).toEqual(['copyCommand', 'suggestCommand']) - }) - it('sends a bounded request to the fixed Responses API and returns text without executing it', async () => { const calls: { url: string; init?: RequestInit }[] = [] const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { @@ -56,31 +50,6 @@ describe('ShellSmith command suggestion provider', () => { expect(requests).toBe(0) }) - it('accepts the dashboard-stamped instance id but rejects other unknown payload fields', async () => { - const calls: { url: string; init?: RequestInit }[] = [] - const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { - calls.push({ url: String(input), init }) - return json({ choices: [{ message: { content: 'find . -type f' } }] }) - }) as typeof fetch - const provider = createOpenAIShellsmithProvider({ - ...context(), - fields: { provider: 'groq', model: 'openai/gpt-oss-20b' }, - }, { - fetchFn, - pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, - }) - // Mirrors the host's stampInstance() contract: every plain-object command gets this field. - const payload = { request: 'List files', instanceId: 'shellsmith-command-showcase' } - - expect(await provider.commands!.suggestCommand(payload, { loopback: true })).toEqual({ ok: true, command: 'find . -type f' }) - expect(calls).toHaveLength(1) - const body = JSON.parse(String(calls[0].init?.body)) - expect(body.messages[0].content).toContain('List files') - expect(JSON.stringify(body)).not.toContain('shellsmith-command-showcase') - expect(await provider.commands!.suggestCommand({ ...(payload as object), unexpected: true }, { loopback: true })).toEqual({ ok: false, error: 'invalid-request' }) - expect(calls).toHaveLength(1) - }) - it('copies only on an explicit loopback command and never runs the generated text', async () => { const writes: string[] = [] const provider = createOpenAIShellsmithProvider(context(), { @@ -90,7 +59,7 @@ describe('ShellSmith command suggestion provider', () => { expect(await provider.commands!.copyCommand({ command: 'echo reviewed' }, { loopback: false })).toEqual({ ok: false, error: 'local-only' }) expect(writes).toEqual([]) - expect(await provider.commands!.copyCommand({ command: 'echo reviewed', instanceId: 'shellsmith-command-showcase' }, { loopback: true })).toEqual({ ok: true }) + expect(await provider.commands!.copyCommand({ command: 'echo reviewed' }, { loopback: true })).toEqual({ ok: true }) expect(writes).toEqual(['echo reviewed']) }) @@ -123,6 +92,77 @@ describe('ShellSmith command suggestion provider', () => { expect(body.tools).toBeUndefined() }) + it('translates the current selected text without reading or changing the clipboard', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + let selectionReads = 0 + let clipboardReads = 0 + let clipboardWrites = 0 + let clipboardTypeReads = 0 + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ choices: [{ message: { content: JSON.stringify({ sourceLanguage: 'English', text: 'Bonjour' }) } }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider({ + ...context(), + fields: { provider: 'groq', model: 'openai/gpt-oss-20b' }, + }, { + fetchFn, + selectedText: async () => { selectionReads++; return { ok: true, text: 'Hello from the focused selection' } }, + pasteboard: { types: async () => { clipboardTypeReads++; return [] }, read: async () => { clipboardReads++; return 'stale clipboard text' }, write: async () => { clipboardWrites++ } }, + }) + + const result = await provider.commands!.translateSelection({ favorites: ['en', 'fr'] }, { loopback: true }) + + expect(result).toEqual({ ok: true, sourceLanguage: 'en', targetLanguage: 'fr', text: 'Bonjour' }) + expect(selectionReads).toBe(1) + expect(clipboardReads).toBe(0) + expect(clipboardWrites).toBe(0) + expect(clipboardTypeReads).toBe(0) + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('https://api.groq.com/openai/v1/chat/completions') + const body = JSON.parse(String(calls[0].init?.body)) + expect(body.response_format).toEqual({ type: 'json_object' }) + expect(body.reasoning_effort).toBe('low') + expect(body.reasoning_format).toBe('hidden') + expect(body.messages.map((message: { content: string }) => message.content).join('\n')).toContain('Hello from the focused selection') + expect(body.messages.map((message: { content: string }) => message.content).join('\n')).not.toContain('stale clipboard text') + }) + + it('refuses secure focused fields before making a request or falling back to the clipboard', async () => { + let requests = 0 + let clipboardReads = 0 + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, + selectedText: async () => ({ ok: false, error: 'secure-field' }), + pasteboard: { types: async () => { clipboardReads++; return [] }, read: async () => { clipboardReads++; return 'clipboard contents' }, write: async () => { clipboardReads++ } }, + }) + + expect(await provider.commands!.translateSelection({ favorites: ['en', 'fr'] }, { loopback: true })).toEqual({ ok: false, error: 'secure-field' }) + expect(clipboardReads).toBe(0) + expect(requests).toBe(0) + }) + + it.each([ + ['no selection', 'no-selection', 'empty-selection'], + ['permission denied', 'permission-required', 'permission-required'], + ])('does not call the model or touch any clipboard format on %s', async (_label, nativeError, expectedError) => { + let requests = 0 + let clipboardCalls = 0 + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, + selectedText: async () => ({ ok: false, error: nativeError as 'no-selection' | 'permission-required' }), + pasteboard: { + types: async () => { clipboardCalls++; return [] }, + read: async () => { clipboardCalls++; return 'clipboard contents' }, + write: async () => { clipboardCalls++ }, + }, + }) + + expect(await provider.commands!.translateSelection({ favorites: ['en', 'fr'] }, { loopback: true })).toEqual({ ok: false, error: expectedError }) + expect(requests).toBe(0) + expect(clipboardCalls).toBe(0) + }) + it('registers an OpenAI-compatible connection with a secret token and a fixed provider choice', async () => { expect(defaultConnectionTypes().some((type) => type.id === 'openai-shellsmith')).toBe(true) expect(openAIShellsmithType.fields.find((field) => field.key === 'token')).toMatchObject({ secret: true, required: true }) @@ -163,4 +203,10 @@ describe('ShellSmith command suggestion provider', () => { expect(JSON.stringify(result)).not.toContain('private-test-token') }) + it('offers a fixed set of favorite languages for Translate Selection', async () => { + const options = await openAIShellsmithType.options!('languages', {}, {}) + + expect(options).toContainEqual({ value: 'en', label: 'English' }) + expect(options).toContainEqual({ value: 'fr', label: 'Français' }) + }) }) From 00e0c7a91eb8bac93b6afd0dfe234aadc9a50102 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Mon, 19 Oct 2026 09:46:08 +0200 Subject: [PATCH 16/24] fix: accept stamped FremKit command payloads --- server/src/providers/openai-shellsmith.ts | 8 ++++--- server/test/shellsmith.test.ts | 29 +++++++++++++++++++++-- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts index a266d6f5..526aaacc 100644 --- a/server/src/providers/openai-shellsmith.ts +++ b/server/src/providers/openai-shellsmith.ts @@ -14,9 +14,11 @@ export const SHELLSMITH_MAX_COMMAND_CHARS = 2000 export const TRANSLATE_MAX_TEXT_BYTES = 2048 const ModelSchema = z.string().trim().min(1).max(100).regex(/^[A-Za-z0-9._:/-]+$/) -const RequestPayload = z.strictObject({ request: z.string().trim().min(1).max(SHELLSMITH_MAX_REQUEST_CHARS) }) -const CopyPayload = z.strictObject({ command: z.string().trim().min(1).max(SHELLSMITH_MAX_COMMAND_CHARS) }) -const FavoritesPayload = z.strictObject({ favorites: z.array(z.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/)).length(2) }) +// The dashboard stamps every widget command with the sending widget instance id. +const INSTANCE = { instanceId: z.string().min(1).max(200).optional() } +const RequestPayload = z.strictObject({ ...INSTANCE, request: z.string().trim().min(1).max(SHELLSMITH_MAX_REQUEST_CHARS) }) +const CopyPayload = z.strictObject({ ...INSTANCE, command: z.string().trim().min(1).max(SHELLSMITH_MAX_COMMAND_CHARS) }) +const FavoritesPayload = z.strictObject({ ...INSTANCE, favorites: z.array(z.string().regex(/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/)).length(2) }) const TranslationResponse = z.strictObject({ sourceLanguage: z.string().trim().min(2).max(20), text: z.string().trim().min(1).max(20_000) }) interface ResponsesBody { diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts index 82c0bec6..23e8e33b 100644 --- a/server/test/shellsmith.test.ts +++ b/server/test/shellsmith.test.ts @@ -50,6 +50,31 @@ describe('ShellSmith command suggestion provider', () => { expect(requests).toBe(0) }) + it('accepts the dashboard-stamped instance id but rejects other unknown payload fields', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ choices: [{ message: { content: 'find . -type f' } }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider({ + ...context(), + fields: { provider: 'groq', model: 'openai/gpt-oss-20b' }, + }, { + fetchFn, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + // Mirrors the host's stampInstance() contract: every plain-object command gets this field. + const payload = { request: 'List files', instanceId: 'shellsmith-command-showcase' } + + expect(await provider.commands!.suggestCommand(payload, { loopback: true })).toEqual({ ok: true, command: 'find . -type f' }) + expect(calls).toHaveLength(1) + const body = JSON.parse(String(calls[0].init?.body)) + expect(body.messages[0].content).toContain('List files') + expect(JSON.stringify(body)).not.toContain('shellsmith-command-showcase') + expect(await provider.commands!.suggestCommand({ ...(payload as object), unexpected: true }, { loopback: true })).toEqual({ ok: false, error: 'invalid-request' }) + expect(calls).toHaveLength(1) + }) + it('copies only on an explicit loopback command and never runs the generated text', async () => { const writes: string[] = [] const provider = createOpenAIShellsmithProvider(context(), { @@ -59,7 +84,7 @@ describe('ShellSmith command suggestion provider', () => { expect(await provider.commands!.copyCommand({ command: 'echo reviewed' }, { loopback: false })).toEqual({ ok: false, error: 'local-only' }) expect(writes).toEqual([]) - expect(await provider.commands!.copyCommand({ command: 'echo reviewed' }, { loopback: true })).toEqual({ ok: true }) + expect(await provider.commands!.copyCommand({ command: 'echo reviewed', instanceId: 'shellsmith-command-showcase' }, { loopback: true })).toEqual({ ok: true }) expect(writes).toEqual(['echo reviewed']) }) @@ -111,7 +136,7 @@ describe('ShellSmith command suggestion provider', () => { pasteboard: { types: async () => { clipboardTypeReads++; return [] }, read: async () => { clipboardReads++; return 'stale clipboard text' }, write: async () => { clipboardWrites++ } }, }) - const result = await provider.commands!.translateSelection({ favorites: ['en', 'fr'] }, { loopback: true }) + const result = await provider.commands!.translateSelection({ favorites: ['en', 'fr'], instanceId: 'translate-selection-showcase' }, { loopback: true }) expect(result).toEqual({ ok: true, sourceLanguage: 'en', targetLanguage: 'fr', text: 'Bonjour' }) expect(selectionReads).toBe(1) From ca765c08b6b466323a746bbccc837d84bc4f0885 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Tue, 20 Oct 2026 23:35:58 +0200 Subject: [PATCH 17/24] Stop the kiosk window from stealing key focus from the primary display The Edge dashboard window could become key, so every tap moved the keyboard focus off the app being typed into on the main display, and a shortcut such as Cmd-V landed in the dashboard. FirstMouseWebView already delivers the first click through acceptsFirstMouse, so the window needs no key status. It is now a non-activating NSPanel that refuses key and main. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 ++++ .../Sources/FremkitHelper/KioskWindow.swift | 23 +++++++++++-------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4663828d..83a91825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,10 @@ tagged `vX.Y.Z`. ### Fixed +- **Tapping the Edge dashboard no longer steals the keyboard.** The dashboard window took the + key focus on every tap, so the app you were typing into on the main display lost it and a + shortcut such as ⌘V landed in the dashboard. The window is now a non-activating panel that + never becomes key; touches still reach the page. - **The Claude limits tile finds the sign-in again.** Recent Claude Code versions keep the OAuth credentials in a keychain item whose name carries a config-dir suffix (`Claude Code-credentials-8047733a`), while the plainly named item can hold MCP data instead. diff --git a/native/Sources/FremkitHelper/KioskWindow.swift b/native/Sources/FremkitHelper/KioskWindow.swift index af06c98c..0cfb27e7 100644 --- a/native/Sources/FremkitHelper/KioskWindow.swift +++ b/native/Sources/FremkitHelper/KioskWindow.swift @@ -31,13 +31,14 @@ extension NSRect { } } -/// Borderless window that can still take the keyboard focus. +/// Borderless non-activating panel that never takes the keyboard focus. /// -/// `NSWindow` refuses to become key or main when it is borderless, which in an accessory -/// (`LSUIElement`) app leaves the dashboard unable to receive clicks and key events at all. -private final class KioskNSWindow: NSWindow { - override var canBecomeKey: Bool { true } - override var canBecomeMain: Bool { true } +/// Touches reach the page through `acceptsFirstMouse` on the web view below, so the window has +/// no need to become key. Refusing it keeps the app the user is typing into frontmost on the +/// primary display when a tap lands on the Edge dashboard. +private final class KioskNSWindow: NSPanel { + override var canBecomeKey: Bool { false } + override var canBecomeMain: Bool { false } } /// Web view that lets the very first click reach the page. @@ -85,10 +86,12 @@ final class KioskWindow: NSObject, WKNavigationDelegate { self.url = url self.access = access - window = KioskNSWindow(contentRect: frame, - styleMask: .borderless, - backing: .buffered, - defer: false) + let panel = KioskNSWindow(contentRect: frame, + styleMask: [.borderless, .nonactivatingPanel], + backing: .buffered, + defer: false) + panel.hidesOnDeactivate = false + window = panel // Above the menu bar and status items: with "Displays have separate Spaces" macOS draws // a menu bar on every display, and a floating window would leave it visible on the Edge. window.level = Self.kioskLevel From becf8dd48bc92dfb0a66ff56eb30b967bf2287f9 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Tue, 20 Oct 2026 23:48:08 +0200 Subject: [PATCH 18/24] Add Ollama Cloud to the OpenAI-compatible AI connection Ollama Cloud speaks chat completions at https://ollama.com/v1 with a bearer key, so it takes the same path as Groq. The host is fixed like the others; the token never goes anywhere else. /v1/models is public, so the connection test confirms the model exists but cannot prove the key. Co-Authored-By: Claude Sonnet 5.5 --- .../connections/types/openai-shellsmith.ts | 16 ++++---- server/src/providers/openai-shellsmith.ts | 10 +++-- server/test/shellsmith.test.ts | 39 ++++++++++++++++++- 3 files changed, 52 insertions(+), 13 deletions(-) diff --git a/server/src/connections/types/openai-shellsmith.ts b/server/src/connections/types/openai-shellsmith.ts index 2bf03d63..08f235a3 100644 --- a/server/src/connections/types/openai-shellsmith.ts +++ b/server/src/connections/types/openai-shellsmith.ts @@ -1,6 +1,6 @@ import { tr } from '../../i18n.js' import { OptionsError, type ConnectionType, type PickOption, type TestResult } from '../types.js' -import { GROQ_API, OPENAI_API, OPENAI_TIMEOUT_MS, createOpenAIShellsmithProvider } from '../../providers/openai-shellsmith.js' +import { GROQ_API, OLLAMA_API, OPENAI_API, OPENAI_TIMEOUT_MS, createOpenAIShellsmithProvider } from '../../providers/openai-shellsmith.js' import type { OpenAIShellsmithDeps } from '../../providers/openai-shellsmith.js' import { USER_AGENT } from '../../version.js' import { readJsonCapped } from '../../net/json.js' @@ -12,8 +12,8 @@ const languages: PickOption[] = [ { value: 'nl', label: 'Nederlands' }, { value: 'ja', label: '日本語' }, { value: 'zh', label: '中文' }, ] -const providerFor = (fields: Record): 'openai' | 'groq' | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' - ? 'openai' : fields.provider === 'groq' ? 'groq' : null +const providerFor = (fields: Record): 'openai' | 'groq' | 'ollama' | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' + ? 'openai' : fields.provider === 'groq' || fields.provider === 'ollama' ? fields.provider : null export const openAIShellsmithType: ConnectionType = { id: 'openai-shellsmith', @@ -22,11 +22,11 @@ export const openAIShellsmithType: ConnectionType = { icon: 'sparkles', secretBindings: ['provider'], fields: [ - { key: 'provider', label: { fr: 'Fournisseur API', en: 'API provider' }, options: ['openai', 'groq'], + { key: 'provider', label: { fr: 'Fournisseur API', en: 'API provider' }, options: ['openai', 'groq', 'ollama'], help: { fr: 'Le jeton est envoyé uniquement à l’hôte fixe du fournisseur choisi. Sans choix, OpenAI est utilisé.', en: 'The token is sent only to the selected provider’s fixed host. OpenAI is used when no choice is saved.' } }, { key: 'model', label: { fr: 'ID du modèle', en: 'Model ID' }, required: true, placeholder: 'openai/gpt-oss-20b', - help: { fr: 'Saisissez un modèle activé pour votre compte. Groq accepte notamment openai/gpt-oss-20b.', en: 'Enter a model enabled for your account. Groq supports openai/gpt-oss-20b, among others.' } }, + help: { fr: 'Saisissez un modèle activé pour votre compte. Groq accepte notamment openai/gpt-oss-20b ; Ollama Cloud, par exemple gpt-oss:120b.', en: 'Enter a model enabled for your account. Groq supports openai/gpt-oss-20b, Ollama Cloud for example gpt-oss:120b.' } }, { key: 'token', label: { fr: 'Clé API', en: 'API key' }, secret: true, required: true, help: { fr: 'La clé reste dans le coffre de secrets. Les requêtes ne partent qu’après une action explicite.', en: 'The key stays in Fremkit’s secret store. Requests are sent only after an explicit action.' } }, ], @@ -37,8 +37,8 @@ export const openAIShellsmithType: ConnectionType = { const token = secrets.token?.trim() ?? '' if (!provider || !ModelSchema.test(model) || !token) return { ok: false, error: tr(undefined, 'shellsmith.unconfigured') } try { - const response = provider === 'groq' - ? await (deps.fetchFn ?? fetch)(`${GROQ_API}/models`, { + const response = provider !== 'openai' + ? await (deps.fetchFn ?? fetch)(`${provider === 'groq' ? GROQ_API : OLLAMA_API}/models`, { redirect: 'error', headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'User-Agent': USER_AGENT }, signal: AbortSignal.timeout(OPENAI_TIMEOUT_MS), @@ -56,7 +56,7 @@ export const openAIShellsmithType: ConnectionType = { : tr(undefined, 'shellsmith.unexpected', { status: response.status }) } } const body = await readJsonCapped(response).catch(() => undefined) as { id?: unknown; data?: Array<{ id?: unknown }> } | undefined - const modelAvailable = provider === 'groq' + const modelAvailable = provider !== 'openai' ? body?.data?.some((item) => item.id === model) === true : body?.id === model return modelAvailable ? { ok: true, detail: tr(undefined, 'shellsmith.connected', { model }) } diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts index 526aaacc..1a39b2a1 100644 --- a/server/src/providers/openai-shellsmith.ts +++ b/server/src/providers/openai-shellsmith.ts @@ -8,6 +8,7 @@ import { readJsonCapped } from '../net/json.js' export const OPENAI_API = 'https://api.openai.com/v1' export const GROQ_API = 'https://api.groq.com/openai/v1' +export const OLLAMA_API = 'https://ollama.com/v1' export const OPENAI_TIMEOUT_MS = 25_000 export const SHELLSMITH_MAX_REQUEST_CHARS = 1000 export const SHELLSMITH_MAX_COMMAND_CHARS = 2000 @@ -37,10 +38,10 @@ export interface OpenAIShellsmithDeps { selectedText?: () => Promise } -type ApiProvider = 'openai' | 'groq' +type ApiProvider = 'openai' | 'groq' | 'ollama' const providerFor = (fields: Record): ApiProvider | null => fields.provider === undefined || fields.provider === '' || fields.provider === 'openai' - ? 'openai' : fields.provider === 'groq' ? 'groq' : null -const apiFor = (provider: ApiProvider): string => provider === 'groq' ? GROQ_API : OPENAI_API + ? 'openai' : fields.provider === 'groq' || fields.provider === 'ollama' ? fields.provider : null +const apiFor = (provider: ApiProvider): string => provider === 'groq' ? GROQ_API : provider === 'ollama' ? OLLAMA_API : OPENAI_API const languageAliases: Record = { english: 'en', français: 'fr', french: 'fr', deutsch: 'de', german: 'de', español: 'es', spanish: 'es', italiano: 'it', italian: 'it', português: 'pt', portuguese: 'pt', nederlands: 'nl', dutch: 'nl', @@ -111,7 +112,8 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d if (!parsed.success || !modelResult.success || !provider) return { ok: false, error: 'invalid-request' } if (!token) return { ok: false, error: 'unconfigured' } - if (provider === 'groq') { + // OpenAI itself uses /responses; Groq and Ollama Cloud only speak chat completions. + if (provider !== 'openai') { const completion = await chatCompletion(fetchFn, api, token, modelResult.data, `Suggest one shell command for this request. Do not execute it, call tools, or include secrets. Return only command text, without markdown or explanation. Avoid destructive commands unless explicitly requested.\n\nRequest: ${parsed.data.request}`, false) diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts index 23e8e33b..b842a424 100644 --- a/server/test/shellsmith.test.ts +++ b/server/test/shellsmith.test.ts @@ -192,7 +192,7 @@ describe('ShellSmith command suggestion provider', () => { expect(defaultConnectionTypes().some((type) => type.id === 'openai-shellsmith')).toBe(true) expect(openAIShellsmithType.fields.find((field) => field.key === 'token')).toMatchObject({ secret: true, required: true }) expect(openAIShellsmithType.fields.find((field) => field.key === 'model')).toMatchObject({ required: true }) - expect(openAIShellsmithType.fields.find((field) => field.key === 'provider')?.options).toEqual(['openai', 'groq']) + expect(openAIShellsmithType.fields.find((field) => field.key === 'provider')?.options).toEqual(['openai', 'groq', 'ollama']) expect(openAIShellsmithType.fields.some((field) => field.key === 'baseUrl')).toBe(false) let requestedUrl = '' @@ -228,6 +228,43 @@ describe('ShellSmith command suggestion provider', () => { expect(JSON.stringify(result)).not.toContain('private-test-token') }) + it('uses the fixed Ollama Cloud host for a bounded suggestion', async () => { + const calls: { url: string; init?: RequestInit }[] = [] + const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { + calls.push({ url: String(input), init }) + return json({ choices: [{ message: { content: 'ls -la' } }] }) + }) as typeof fetch + const provider = createOpenAIShellsmithProvider({ + ...context(), + fields: { provider: 'ollama', model: 'gpt-oss:120b' }, + }, { + fetchFn, + pasteboard: { read: async () => '', write: async () => {}, types: async () => [] }, + }) + + const result = await provider.commands!.suggestCommand({ request: 'List files' }, { loopback: true }) + + expect(result).toEqual({ ok: true, command: 'ls -la' }) + expect(calls[0].url).toBe('https://ollama.com/v1/chat/completions') + expect(calls[0].init?.redirect).toBe('error') + expect(new Headers(calls[0].init?.headers).get('authorization')).toBe('Bearer private-test-token') + expect(JSON.parse(String(calls[0].init?.body)).reasoning_format).toBeUndefined() + }) + + it('checks Ollama Cloud models through the fixed models endpoint without returning the secret', async () => { + let requestedUrl = '' + const result = await openAIShellsmithType.test({ provider: 'ollama', model: 'gpt-oss:120b' }, { token: 'private-test-token' }, { + fetchFn: (async (url: string | URL | Request) => { + requestedUrl = String(url) + return json({ data: [{ id: 'gpt-oss:120b' }] }) + }) as typeof fetch, + }) + + expect(requestedUrl).toBe('https://ollama.com/v1/models') + expect(result.ok).toBe(true) + expect(JSON.stringify(result)).not.toContain('private-test-token') + }) + it('offers a fixed set of favorite languages for Translate Selection', async () => { const options = await openAIShellsmithType.options!('languages', {}, {}) From 630a1277997d584efb50b2baa2cedba7767b34c4 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Tue, 20 Oct 2026 23:52:23 +0200 Subject: [PATCH 19/24] Port the ILITEK touch profile and Helitech display target Brings the helper's ILITEK digitizer decoding, display target and touch driver profile selection over from the touch-focus working tree onto the current main. Co-Authored-By: Claude Sonnet 5.5 --- .../Sources/FremkitCore/GestureEngine.swift | 16 + native/Sources/FremkitCore/ILITEKTouch.swift | 238 +++++++++++++++ .../Sources/FremkitHelper/AppDelegate.swift | 30 +- .../FremkitHelper/ILITEKDisplayTarget.swift | 28 ++ native/Sources/FremkitHelper/StatusMenu.swift | 1 + .../Sources/FremkitHelper/TouchDriver.swift | 289 +++++++++++++++++- .../FremkitCoreTests/GestureEngineTests.swift | 13 + .../TouchDigitizerDecoderTests.swift | 126 ++++++++ native/Tests/Shim/main.swift | 14 + 9 files changed, 742 insertions(+), 13 deletions(-) create mode 100644 native/Sources/FremkitCore/ILITEKTouch.swift create mode 100644 native/Sources/FremkitHelper/ILITEKDisplayTarget.swift create mode 100644 native/Tests/FremkitCoreTests/TouchDigitizerDecoderTests.swift diff --git a/native/Sources/FremkitCore/GestureEngine.swift b/native/Sources/FremkitCore/GestureEngine.swift index 263c76a2..b53f4d6e 100644 --- a/native/Sources/FremkitCore/GestureEngine.swift +++ b/native/Sources/FremkitCore/GestureEngine.swift @@ -77,6 +77,22 @@ public final class GestureEngine { return [] } + /// Cancels an interrupted touch stream, releasing a drag or restoring a scrolled cursor. + public func cancel() -> [PointerAction] { + let actions: [PointerAction] + switch state { + case .scrolling: + actions = [.restoreCursor] + case let .dragging(last): + actions = [.mouseUp(last), .restoreCursor] + case .idle, .pressed, .holding: + actions = [] + } + state = .idle + lastTap = nil + return actions + } + private func handleDown(_ s: TouchSample) -> [PointerAction] { switch state { case .idle: diff --git a/native/Sources/FremkitCore/ILITEKTouch.swift b/native/Sources/FremkitCore/ILITEKTouch.swift new file mode 100644 index 00000000..8cfa27b6 --- /dev/null +++ b/native/Sources/FremkitCore/ILITEKTouch.swift @@ -0,0 +1,238 @@ +import Foundation + +/// Supported hardware profiles. The top-level usage distinguishes ILITEK's touch collection +/// from its sibling emulated mouse collection, which must never be decoded as finger input. +public enum TouchHardwareProfile: Equatable { + case edge + case ilitek + + public static func match(vendorID: Int, productID: Int, usagePage: Int, usage: Int) -> Self? { + if vendorID == 0x27C0, productID == 0x0859, usagePage == 0x01, usage == 0x02 { + return .edge + } + if vendorID == 0x222A, productID == 0x0001, usagePage == 0x0D, usage == 0x04 { + return .ilitek + } + return nil + } + + /// Uses Edge when its display and HID device are present; otherwise falls back to ILITEK. + public static func preferred(edgeDevice: Bool, + edgeTarget: Bool, + ilitekDevice: Bool, + ilitekTarget: Bool) -> Self? { + if edgeDevice && edgeTarget { return .edge } + if ilitekDevice && ilitekTarget { return .ilitek } + if edgeDevice { return .edge } + if ilitekDevice { return .ilitek } + return nil + } + + /// Returns only the target belonging to the chosen hardware profile. In particular, an + /// ILITEK device without its selected active display must not fall through to Edge bounds. + public static func target(for profile: Self, edge: Bounds?, ilitek: Bounds?) -> Bounds? { + switch profile { + case .edge: return edge + case .ilitek: return ilitek + } + } +} + +/// The physical USB grouping used to keep a touchscreen's emulated-mouse interface with it. +public struct HIDPhysicalDeviceKey: Equatable { + public let vendorID: Int + public let productID: Int + public let locationID: Int + + public init(vendorID: Int, productID: Int, locationID: Int) { + self.vendorID = vendorID + self.productID = productID + self.locationID = locationID + } + + public func isSibling(vendorID: Int, productID: Int, locationID: Int) -> Bool { + self.vendorID == vendorID && self.productID == productID && self.locationID == locationID + } +} + +/// One value emitted by IOHID for a digitizer element, converted to plain data for testing. +public struct HIDTouchElementValue { + public let usagePage: Int + public let usage: Int + public let value: Int + public let logicalMinimum: Int + public let logicalMaximum: Int + public let isRelative: Bool + /// Cookie of the containing Finger collection, when the element belongs to one. + public let fingerCookie: UInt64? + + public init(usagePage: Int, + usage: Int, + value: Int, + logicalMinimum: Int, + logicalMaximum: Int, + isRelative: Bool = false, + fingerCookie: UInt64? = nil) { + self.usagePage = usagePage + self.usage = usage + self.value = value + self.logicalMinimum = logicalMinimum + self.logicalMaximum = logicalMaximum + self.isRelative = isRelative + self.fingerCookie = fingerCookie + } +} + +public struct HIDTouchSample: Equatable { + public let x: Double + public let y: Double + public let isDown: Bool + public let hasValidPosition: Bool + public let hasContactElement: Bool + + public init(x: Double, y: Double, isDown: Bool, hasValidPosition: Bool, hasContactElement: Bool) { + self.x = x + self.y = y + self.isDown = isDown + self.hasValidPosition = hasValidPosition + self.hasContactElement = hasContactElement + } +} + +/// Decodes the confirmed ILITEK Digitizer-page X/Y and tip-switch values. +public struct ILITEKTouchDecoder { + private let primaryFingerCookie: UInt64? + private var x = 0.5 + private var y = 0.5 + private var hasX = false + private var hasY = false + private var isDown = false + private var hasContactElement = false + + public init(primaryFingerCookie: UInt64? = nil) { + self.primaryFingerCookie = primaryFingerCookie + } + + public var sample: HIDTouchSample { + HIDTouchSample(x: x, y: y, isDown: isDown, hasValidPosition: hasX && hasY, + hasContactElement: hasContactElement) + } + + public mutating func consume(_ element: HIDTouchElementValue) { + guard !element.isRelative else { return } + if let primaryFingerCookie, + let fingerCookie = element.fingerCookie, + fingerCookie != primaryFingerCookie { + return + } + + guard element.usagePage == 0x0D else { return } + switch element.usage { + case 0x30: + guard element.logicalMaximum > element.logicalMinimum else { return } + x = Self.normalize(element) + hasX = true + case 0x31: + guard element.logicalMaximum > element.logicalMinimum else { return } + y = Self.normalize(element) + hasY = true + case 0x42, 0x32, 0x33: + hasContactElement = true + isDown = element.value > 0 + default: + break + } + } + + private static func normalize(_ element: HIDTouchElementValue) -> Double { + let span = Double(element.logicalMaximum - element.logicalMinimum) + let ratio = (Double(element.value) - Double(element.logicalMinimum)) / span + return min(1, max(0, ratio)) + } +} + +/// Decodes the ILITEK sibling mouse collection. This device reports its usable absolute X/Y and +/// primary contact edge on this interface on the connected panel; relative pointer reports are +/// deliberately ignored so trackpad-like deltas cannot corrupt absolute mapping. +public struct ILITEKMouseDecoder { + private var x = 0.5 + private var y = 0.5 + private var hasX = false + private var hasY = false + private var isDown = false + private var hasContactElement = false + + public init() {} + + public var sample: HIDTouchSample { + HIDTouchSample(x: x, y: y, isDown: isDown, hasValidPosition: hasX && hasY, + hasContactElement: hasContactElement) + } + + public mutating func consume(_ element: HIDTouchElementValue) { + guard !element.isRelative else { return } + switch (element.usagePage, element.usage) { + case (0x01, 0x30): + guard element.logicalMaximum > element.logicalMinimum else { return } + x = Self.normalize(element) + hasX = true + case (0x01, 0x31): + guard element.logicalMaximum > element.logicalMinimum else { return } + y = Self.normalize(element) + hasY = true + case (0x09, 0x01): + hasContactElement = true + isDown = element.value > 0 + default: + break + } + } + + private static func normalize(_ element: HIDTouchElementValue) -> Double { + let span = Double(element.logicalMaximum - element.logicalMinimum) + return min(1, max(0, (Double(element.value) - Double(element.logicalMinimum)) / span)) + } +} + +public enum ILITEKTouchSource: Hashable { + case digitizer + case mouse +} + +/// Chooses one interface for each physical contact and suppresses its sibling until that +/// sibling reports release. This prevents duplicate gestures if a device emits both paths. +public struct ILITEKContactSourceSelector { + private var activeSource: ILITEKTouchSource? + private var suppressedUntilRelease: Set = [] + + public init() {} + + public mutating func select(_ sample: HIDTouchSample, from source: ILITEKTouchSource) -> HIDTouchSample? { + guard sample.hasValidPosition, sample.hasContactElement else { return nil } + if suppressedUntilRelease.contains(source) { + if !sample.isDown { suppressedUntilRelease.remove(source) } + return nil + } + if let activeSource { + guard activeSource == source else { + if sample.isDown { suppressedUntilRelease.insert(source) } + return nil + } + if !sample.isDown { self.activeSource = nil } + return sample + } + guard sample.isDown else { return nil } + activeSource = source + return sample + } +} + +public extension DisplayMapper { + /// Converts normalized HID axes (X→right, Y→down) into Quartz global display coordinates. + func point(normalizedX: Double, normalizedY: Double) -> CGPoint { + let x = min(1, max(0, normalizedX)) + let y = min(1, max(0, normalizedY)) + return CGPoint(x: bounds.minX + x * bounds.width, + y: bounds.minY + y * bounds.height) + } +} diff --git a/native/Sources/FremkitHelper/AppDelegate.swift b/native/Sources/FremkitHelper/AppDelegate.swift index ccfb7684..148f0e26 100644 --- a/native/Sources/FremkitHelper/AppDelegate.swift +++ b/native/Sources/FremkitHelper/AppDelegate.swift @@ -26,8 +26,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { #if FREMKIT_SPARKLE private var updater: Updater? #endif - /// Latest Edge bounds, kept so the kiosk window can be created lazily when it appears. - private var edge: CGRect? + /// Latest dashboard target bounds (Edge when connected, otherwise the selected ILITEK screen). + private var dashboardBounds: CGRect? /// Polls the Accessibility grant until it lands, so the menu stops claiming it is missing. private var accessibilityTimer: Timer? /// True once `applicationDidFinishLaunching` has built the windows a URL may want. @@ -323,7 +323,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { touch: state.touch.description, inputMonitoring: grant(Permissions.inputMonitoring), accessibility: AXIsProcessTrusted() ? .granted : .denied, - kioskDisplay: edge.map { (Int($0.width), Int($0.height)) }, + kioskDisplay: dashboardBounds.map { (Int($0.width), Int($0.height)) }, kioskWindow: kiosk != nil, brightness: brightness, fence: fence, @@ -370,24 +370,32 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private func refreshDashboardMenu() { menu?.update { state in - state.dashboardAvailable = edge != nil && kiosk != nil + state.dashboardAvailable = dashboardBounds != nil && kiosk != nil state.dashboardHidden = kiosk?.isHiddenByUser == true } } private func edgeDidChange(_ edge: CGRect?) { - self.edge = edge - driver?.displayBounds = edge - fence?.edge = edge + let ilitek = ILITEKDisplayTarget.bounds() + let profiles = TouchDriver.connectedProfiles() + let profile = TouchHardwareProfile.preferred(edgeDevice: profiles.contains(.edge), + edgeTarget: edge != nil, + ilitekDevice: profiles.contains(.ilitek), + ilitekTarget: ilitek != nil) ?? .edge + let target = TouchHardwareProfile.target(for: profile, edge: edge, ilitek: ilitek) + dashboardBounds = target + driver?.use(profile) + driver?.displayBounds = target + fence?.edge = target brightness?.displayDidChange(edge == nil ? nil : EdgeDisplay.findID(width: config.display.width, height: config.display.height)) - if let edge { - let frame = NSRect.fromCGDisplayBounds(edge, primaryHeight: NSRect.primaryScreenHeight) + if let target { + let frame = NSRect.fromCGDisplayBounds(target, primaryHeight: NSRect.primaryScreenHeight) // The admin window must never open where the kiosk is: the kiosk sits above the // status-bar level, so a window on that display is focused and invisible. admin?.kioskFrame = frame if let kiosk { - kiosk.setEdgeFrame(edge) + kiosk.setEdgeFrame(target) } else if let access { let url = Self.parseURL(config.url, what: "url") kiosk = KioskWindow(frame: frame, url: url, access: access) @@ -428,7 +436,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private func wireMenu(_ menu: StatusMenu) { menu.onToggleDashboard = { [weak self] in - guard let self, self.edge != nil, let kiosk = self.kiosk else { return } + guard let self, self.dashboardBounds != nil, let kiosk = self.kiosk else { return } if kiosk.isHiddenByUser { kiosk.showDashboard() } else { kiosk.hideDashboard() } } diff --git a/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift b/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift new file mode 100644 index 00000000..20ddf5d4 --- /dev/null +++ b/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift @@ -0,0 +1,28 @@ +import CoreGraphics +import Foundation + +/// Reads TouchRemap's selected screen as a read-only preference for this local ILITEK trial. +/// Fremkit never writes this file, and it does not activate TouchRemap's currently-disabled +/// calibration settings. +enum ILITEKDisplayTarget { + private struct TouchRemapPreference: Decodable { + let lastScreen: String? + } + + static func bounds() -> CGRect? { + guard let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { + return nil + } + let url = support.appendingPathComponent("pd-touchbase/remap_config.json") + guard let data = try? Data(contentsOf: url), + let preference = try? JSONDecoder().decode(TouchRemapPreference.self, from: data), + let key = preference.lastScreen, + key.hasPrefix("id:"), + let rawID = UInt32(key.dropFirst(3)) else { return nil } + let displayID = CGDirectDisplayID(rawID) + guard CGDisplayIsActive(displayID) != 0 else { return nil } + let frame = CGDisplayBounds(displayID) + guard frame.width > 0, frame.height > 0 else { return nil } + return frame + } +} diff --git a/native/Sources/FremkitHelper/StatusMenu.swift b/native/Sources/FremkitHelper/StatusMenu.swift index 15a79784..95422fee 100644 --- a/native/Sources/FremkitHelper/StatusMenu.swift +++ b/native/Sources/FremkitHelper/StatusMenu.swift @@ -37,6 +37,7 @@ struct MenuState { case .notPermitted: return .touchNotPermitted case .needsRelaunch: return .touchNeedsRelaunch case .busy(.exclusiveAccess): return .touchBusy + case .busy(.siblingSeizeFailed): return .touchBusy case .busy(.openFailed): return .touchOpenFailed case .noDisplay: return .touchNoDisplay case .disabled: return .touchDisabled diff --git a/native/Sources/FremkitHelper/TouchDriver.swift b/native/Sources/FremkitHelper/TouchDriver.swift index 0f0ce524..0dd484a6 100644 --- a/native/Sources/FremkitHelper/TouchDriver.swift +++ b/native/Sources/FremkitHelper/TouchDriver.swift @@ -10,12 +10,15 @@ import IOKit.hid enum TouchBusyReason: Equatable, CustomStringConvertible { /// Another process holds the interface exclusively (e.g. Touchscreen Gestures). case exclusiveAccess + /// The ILITEK touchscreen opened, but its paired mouse interface could not be seized. + case siblingSeizeFailed /// `IOHIDManagerOpen` failed for some other reason; carries the raw IOReturn code. case openFailed(UInt32) var description: String { switch self { case .exclusiveAccess: return "another driver holds the panel" + case .siblingSeizeFailed: return "could not seize the panel's paired mouse interface" case let .openFailed(code): return String(format: "IOHIDManagerOpen failed (0x%08X)", code) } } @@ -93,6 +96,16 @@ final class TouchDriver { private var reopenBackoff = TouchDriver.reopenDelay /// Guarded by `queue`. private var mapper: DisplayMapper? + /// Selected by AppDelegate from the configured target display; Edge remains the default. + var hardwareProfile: TouchHardwareProfile = .edge + private var ilitekDevice: IOHIDDevice? + private var ilitekSiblings: [IOHIDDevice] = [] + private var ilitekDecoder = ILITEKTouchDecoder() + private var ilitekMouseDecoder = ILITEKMouseDecoder() + private var ilitekSourceSelector = ILITEKContactSourceSelector() + private var ilitekPendingSample: HIDTouchSample? + private var ilitekFlushScheduled = false + private let ilitekTraceEnabled = ProcessInfo.processInfo.environment["FREMKIT_ILITEK_TRACE"] == "1" /// Tells a missing grant from one this process cannot see until it is relaunched. private var accessGate = TouchAccessGate() @@ -154,7 +167,8 @@ final class TouchDriver { // the Accessibility prompt was lost (macOS shows one privacy prompt at a time). See // `PermissionSequencer`. - openManager() + if hardwareProfile == .ilitek { openILITEKDevice() } + else { openManager() } // `.common` so a menu tracking loop cannot stall the gesture clock. let timer = Timer(timeInterval: Self.tickInterval, repeats: true) { [weak self] _ in @@ -184,9 +198,31 @@ final class TouchDriver { self.wakeObserver = nil } closeManager() + closeILITEKDevice() state = .disabled } + /// Switches between the existing Edge report adapter and the optional ILITEK element adapter. + func use(_ profile: TouchHardwareProfile) { + guard hardwareProfile != profile else { return } + let wasRunning = running + if wasRunning { stop() } + hardwareProfile = profile + if wasRunning { start() } + } + + /// Enumerates HID metadata without opening or seizing any device. + static func connectedProfiles() -> Set { + let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(0)) + IOHIDManagerSetDeviceMatching(manager, nil) + guard let raw = IOHIDManagerCopyDevices(manager) else { return [] } + let devices = (raw as NSSet).allObjects as! [IOHIDDevice] + var profiles = Set() + if devices.contains(where: isEdgeTouchscreen) { profiles.insert(.edge) } + if devices.contains(where: isILITEKTouchscreen) { profiles.insert(.ilitek) } + return profiles + } + private func tick() { let now = ProcessInfo.processInfo.systemUptime queue.async { [weak self] in @@ -264,6 +300,254 @@ final class TouchDriver { } } + /// Opens only the ILITEK digitizer collection, then seizes its paired mouse collection so one + /// physical touch cannot generate both a digitizer gesture and a WindowServer mouse click. + private func openILITEKDevice() { + closeILITEKDevice() + traceILITEK("open preflight inputMonitoring=\(Permissions.inputMonitoring) accessibilityTrusted=\(AXIsProcessTrusted())") + guard displayBounds != nil else { + state = .noDisplay + return + } + + let manager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(0)) + IOHIDManagerSetDeviceMatching(manager, nil) + guard let raw = IOHIDManagerCopyDevices(manager) else { + state = .busy(.openFailed(UInt32(bitPattern: kIOReturnNoDevice))) + failedToOpen() + return + } + let devices = (raw as NSSet).allObjects as! [IOHIDDevice] + guard let device = devices.first(where: Self.isILITEKTouchscreen) else { + state = .busy(.openFailed(UInt32(bitPattern: kIOReturnNoDevice))) + failedToOpen() + return + } + let key = Self.physicalKey(for: device) + let mouseSiblings = devices.filter { + !CFEqual($0, device) && Self.physicalKey(for: $0) == key && Self.isMouseCollection($0) + } + guard !mouseSiblings.isEmpty || Self.isMouseCollection(device) else { + state = .busy(.siblingSeizeFailed) + failedToOpen() + return + } + + let result = IOHIDDeviceOpen(device, IOOptionBits(kIOHIDOptionsTypeSeizeDevice)) + guard result == kIOReturnSuccess else { + traceILITEK("primary open failed result=\(String(format: "0x%08X", UInt32(bitPattern: result)))") + if result == IOResult.notPermitted { + switch accessGate.refused(inputMonitoring: Permissions.inputMonitoring) { + case .missing: state = .notPermitted + case .relaunchNeeded: state = .needsRelaunch + } + } else if result == IOResult.exclusiveAccess { + accessGate.reset() + state = .busy(.exclusiveAccess) + } else { + accessGate.reset() + state = .busy(.openFailed(UInt32(bitPattern: result))) + } + failedToOpen() + return + } + + for sibling in mouseSiblings { + guard IOHIDDeviceOpen(sibling, IOOptionBits(kIOHIDOptionsTypeSeizeDevice)) == kIOReturnSuccess else { + for opened in ilitekSiblings { IOHIDDeviceClose(opened, IOOptionBits(0)) } + ilitekSiblings = [] + IOHIDDeviceClose(device, IOOptionBits(0)) + state = .busy(.siblingSeizeFailed) + traceILITEK("mouse sibling open failed") + failedToOpen() + return + } + ilitekSiblings.append(sibling) + } + + ilitekDecoder = ILITEKTouchDecoder(primaryFingerCookie: Self.primaryFingerCookie(device)) + ilitekMouseDecoder = ILITEKMouseDecoder() + ilitekSourceSelector = ILITEKContactSourceSelector() + ilitekPendingSample = nil + IOHIDDeviceScheduleWithRunLoop(device, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) + IOHIDDeviceRegisterRemovalCallback(device, Self.ilitekRemovalCallback, Unmanaged.passUnretained(self).toOpaque()) + IOHIDDeviceRegisterInputValueCallback(device, Self.ilitekValueCallback, Unmanaged.passUnretained(self).toOpaque()) + for sibling in ilitekSiblings { + IOHIDDeviceScheduleWithRunLoop(sibling, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) + IOHIDDeviceRegisterRemovalCallback(sibling, Self.ilitekRemovalCallback, Unmanaged.passUnretained(self).toOpaque()) + IOHIDDeviceRegisterInputValueCallback(sibling, Self.ilitekValueCallback, Unmanaged.passUnretained(self).toOpaque()) + } + ilitekDevice = device + opened = true + accessGate.reset() + state = .active + reopenBackoff = Self.reopenDelay + traceILITEK("open active interfaces=digitizer+\(ilitekSiblings.count) mouse sibling(s); requested seize option=\(kIOHIDOptionsTypeSeizeDevice)") + } + + private func closeILITEKDevice() { + opened = false + if let device = ilitekDevice { + IOHIDDeviceRegisterRemovalCallback(device, nil, nil) + IOHIDDeviceRegisterInputValueCallback(device, nil, nil) + IOHIDDeviceUnscheduleFromRunLoop(device, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) + IOHIDDeviceClose(device, IOOptionBits(0)) + ilitekDevice = nil + } + for sibling in ilitekSiblings { + IOHIDDeviceRegisterRemovalCallback(sibling, nil, nil) + IOHIDDeviceUnscheduleFromRunLoop(sibling, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) + IOHIDDeviceClose(sibling, IOOptionBits(0)) + } + ilitekSiblings = [] + ilitekPendingSample = nil + ilitekSourceSelector = ILITEKContactSourceSelector() + ilitekFlushScheduled = false + } + + private func handleILITEKRemoval() { + guard opened else { return } + queue.async { [weak self] in + guard let self else { return } + for action in self.engine.cancel() { self.poster.perform(action) } + } + closeILITEKDevice() + state = .busy(.openFailed(UInt32(bitPattern: kIOReturnNoDevice))) + failedToOpen() + } + + private static func propertyInt(_ device: IOHIDDevice, _ key: String) -> Int { + (IOHIDDeviceGetProperty(device, key as CFString) as? NSNumber)?.intValue ?? 0 + } + + private static func isILITEKTouchscreen(_ device: IOHIDDevice) -> Bool { + let vendor = propertyInt(device, "VendorID") + let product = propertyInt(device, "ProductID") + guard vendor == 0x222A, product == 0x0001 else { return false } + return hasUsage(device, page: 0x0D, usage: 0x04) + } + + private static func isEdgeTouchscreen(_ device: IOHIDDevice) -> Bool { + let vendor = propertyInt(device, "VendorID") + let product = propertyInt(device, "ProductID") + guard vendor == Hardware.vendorID, product == Hardware.productID else { return false } + return hasUsage(device, page: Hardware.usagePage, usage: Hardware.usage) + } + + private static func isMouseCollection(_ device: IOHIDDevice) -> Bool { + hasUsage(device, page: 0x01, usage: 0x02) + } + + private static func hasUsage(_ device: IOHIDDevice, page: Int, usage: Int) -> Bool { + guard let pairs = IOHIDDeviceGetProperty(device, "DeviceUsagePairs" as CFString) as? [[String: Any]] else { + return propertyInt(device, "PrimaryUsagePage") == page && propertyInt(device, "PrimaryUsage") == usage + } + return pairs.contains { + ($0["DeviceUsagePage"] as? NSNumber)?.intValue == page + && ($0["DeviceUsage"] as? NSNumber)?.intValue == usage + } + } + + private static func physicalKey(for device: IOHIDDevice) -> HIDPhysicalDeviceKey { + HIDPhysicalDeviceKey(vendorID: propertyInt(device, "VendorID"), + productID: propertyInt(device, "ProductID"), + locationID: propertyInt(device, "LocationID")) + } + + private static func primaryFingerCookie(_ device: IOHIDDevice) -> UInt64? { + guard let elements = IOHIDDeviceCopyMatchingElements(device, nil, IOOptionBits(0)) as? [IOHIDElement] else { + return nil + } + return elements.filter { + IOHIDElementGetType($0) == kIOHIDElementTypeCollection + && IOHIDElementGetUsagePage($0) == kHIDPage_Digitizer + && IOHIDElementGetUsage($0) == kHIDUsage_Dig_Finger + }.map { UInt64(IOHIDElementGetCookie($0)) }.min() + } + + private func handleILITEKValue(_ value: IOHIDValue) { + let element = IOHIDValueGetElement(value) + let valueDevice = IOHIDElementGetDevice(element) + let source: ILITEKTouchSource + if let device = ilitekDevice, CFEqual(valueDevice, device) { + source = .digitizer + } else if ilitekSiblings.contains(where: { CFEqual(valueDevice, $0) }) { + source = .mouse + } else { + return + } + let parent = IOHIDElementGetParent(element) + let parentCookie: UInt64? + if let parent, + IOHIDElementGetUsagePage(parent) == kHIDPage_Digitizer, + IOHIDElementGetUsage(parent) == kHIDUsage_Dig_Finger { + parentCookie = UInt64(IOHIDElementGetCookie(parent)) + } else { + parentCookie = nil + } + let relative = (IOHIDElementGetProperty(element, "IsRelative" as CFString) as? NSNumber)?.boolValue ?? false + let elementValue = HIDTouchElementValue( + usagePage: Int(IOHIDElementGetUsagePage(element)), + usage: Int(IOHIDElementGetUsage(element)), + value: IOHIDValueGetIntegerValue(value), + logicalMinimum: Int(IOHIDElementGetLogicalMin(element)), + logicalMaximum: Int(IOHIDElementGetLogicalMax(element)), + isRelative: relative, + fingerCookie: parentCookie + ) + switch source { + case .digitizer: ilitekDecoder.consume(elementValue) + case .mouse: ilitekMouseDecoder.consume(elementValue) + } + let decodedSample = source == .digitizer ? ilitekDecoder.sample : ilitekMouseDecoder.sample + guard let sample = ilitekSourceSelector.select(decodedSample, from: source) else { + traceILITEK("callback source=\(source) usage=\(elementValue.usagePage):\(elementValue.usage) value=\(elementValue.value) ignored contact=\(decodedSample.isDown)") + return + } + ilitekPendingSample = sample + traceILITEK(String(format: "callback source=%@ usage=%04X:%04X value=%ld decoded x=%.4f y=%.4f down=%@", + String(describing: source), elementValue.usagePage, elementValue.usage, + elementValue.value, sample.x, sample.y, sample.isDown ? "yes" : "no")) + guard !ilitekFlushScheduled else { return } + ilitekFlushScheduled = true + DispatchQueue.main.async { [weak self] in self?.flushILITEKValues() } + } + + private func flushILITEKValues() { + ilitekFlushScheduled = false + guard opened else { return } + guard let sample = ilitekPendingSample else { return } + ilitekPendingSample = nil + queue.async { [weak self] in + guard let self, let mapper = self.mapper else { return } + let point = mapper.point(normalizedX: sample.x, normalizedY: sample.y) + let touch = TouchSample(down: sample.isDown, point: point, time: ProcessInfo.processInfo.systemUptime) + self.traceILITEK(String(format: "mapped x=%.2f y=%.2f down=%@", point.x, point.y, sample.isDown ? "yes" : "no")) + for action in self.engine.feed(touch) { + self.traceILITEK("action/post \(action)") + self.poster.perform(action) + } + } + } + + private func traceILITEK(_ message: String) { + guard ilitekTraceEnabled else { return } + FileHandle.standardError.write(Data("[ilitek-trace] \(message)\n".utf8)) + } + + private static let ilitekValueCallback: IOHIDValueCallback = { context, result, _, value in + guard result == kIOReturnSuccess, let context else { return } + let driver = Unmanaged.fromOpaque(context).takeUnretainedValue() + if Thread.isMainThread { driver.handleILITEKValue(value) } + else { DispatchQueue.main.async { driver.handleILITEKValue(value) } } + } + + private static let ilitekRemovalCallback: IOHIDCallback = { context, _, _ in + guard let context else { return } + let driver = Unmanaged.fromOpaque(context).takeUnretainedValue() + DispatchQueue.main.async { driver.handleILITEKRemoval() } + } + /// Backs off before the next attempt. /// /// While Input Monitoring is missing or another driver holds the panel, every open fails and @@ -293,7 +577,8 @@ final class TouchDriver { guard let self else { return } self.reopenPending = false guard self.running else { return } - self.openManager() + if self.hardwareProfile == .ilitek { self.openILITEKDevice() } + else { self.openManager() } } } diff --git a/native/Tests/FremkitCoreTests/GestureEngineTests.swift b/native/Tests/FremkitCoreTests/GestureEngineTests.swift index 801c9062..900158a8 100644 --- a/native/Tests/FremkitCoreTests/GestureEngineTests.swift +++ b/native/Tests/FremkitCoreTests/GestureEngineTests.swift @@ -84,6 +84,19 @@ final class GestureEngineTests: XCTestCase { XCTAssertEqual(engine.feed(up(further, 0.6)), [.mouseUp(further), .restoreCursor]) } + func testCancelReleasesDragAndStartsNextTouchAsFreshGesture() { + let engine = GestureEngine() + _ = engine.feed(down(p0, 0)) + _ = engine.tick(now: 0.4) + let moved = CGPoint(x: p0.x + 30, y: p0.y) + XCTAssertEqual(engine.feed(down(moved, 0.45)), [.move(p0), .mouseDown(p0), .drag(moved)]) + let last = CGPoint(x: p0.x + 50, y: p0.y) + + XCTAssertEqual(engine.cancel(), [.mouseUp(moved), .restoreCursor]) + XCTAssertEqual(engine.feed(down(last, 0.5)), []) + XCTAssertEqual(engine.feed(up(last, 0.55)), [.move(last), .mouseDown(last), .mouseUp(last), .restoreCursor]) + } + func testLongPress() { let engine = GestureEngine() XCTAssertEqual(engine.feed(down(p0, 0)), []) diff --git a/native/Tests/FremkitCoreTests/TouchDigitizerDecoderTests.swift b/native/Tests/FremkitCoreTests/TouchDigitizerDecoderTests.swift new file mode 100644 index 00000000..b60b0eac --- /dev/null +++ b/native/Tests/FremkitCoreTests/TouchDigitizerDecoderTests.swift @@ -0,0 +1,126 @@ +import XCTest +@testable import FremkitCore + +final class TouchDigitizerDecoderTests: XCTestCase { + func testSelectsILITEKTouchscreenWithoutMatchingItsMouseInterface() { + XCTAssertEqual( + TouchHardwareProfile.match(vendorID: 0x27C0, productID: 0x0859, usagePage: 0x01, usage: 0x02), + .edge + ) + XCTAssertEqual( + TouchHardwareProfile.match(vendorID: 0x222A, productID: 0x0001, usagePage: 0x0D, usage: 0x04), + .ilitek + ) + XCTAssertNil(TouchHardwareProfile.match(vendorID: 0x222A, productID: 0x0001, usagePage: 0x01, usage: 0x02)) + XCTAssertNil(TouchHardwareProfile.match(vendorID: 0x222B, productID: 0x0001, usagePage: 0x0D, usage: 0x04)) + } + + func testHardwareProfileRequiresItsDeviceAndPrefersReadyEdge() { + XCTAssertEqual(TouchHardwareProfile.preferred(edgeDevice: true, edgeTarget: true, + ilitekDevice: true, ilitekTarget: true), .edge) + XCTAssertEqual(TouchHardwareProfile.preferred(edgeDevice: false, edgeTarget: true, + ilitekDevice: true, ilitekTarget: true), .ilitek) + XCTAssertEqual(TouchHardwareProfile.preferred(edgeDevice: true, edgeTarget: false, + ilitekDevice: true, ilitekTarget: true), .ilitek) + XCTAssertNil(TouchHardwareProfile.preferred(edgeDevice: false, edgeTarget: true, + ilitekDevice: false, ilitekTarget: true)) + } + + func testSelectedProfileNeverFallsBackToAnotherDisplaysBounds() { + XCTAssertNil(TouchHardwareProfile.target(for: .ilitek, edge: "Edge", ilitek: nil) as String?) + XCTAssertEqual(TouchHardwareProfile.target(for: .ilitek, edge: "Edge", ilitek: "ILITEK"), "ILITEK") + XCTAssertEqual(TouchHardwareProfile.target(for: .edge, edge: "Edge", ilitek: "ILITEK"), "Edge") + } + + func testMapsNormalizedTouchToConfiguredDisplayBounds() { + let bounds = CGRect(x: -2560, y: 1169, width: 2560, height: 733) + let mapper = DisplayMapper(bounds: bounds) + + XCTAssertEqual(mapper.point(normalizedX: 0, normalizedY: 0), CGPoint(x: -2560, y: 1169)) + XCTAssertEqual(mapper.point(normalizedX: 1, normalizedY: 1), CGPoint(x: 0, y: 1902)) + XCTAssertEqual(mapper.point(normalizedX: 0.5, normalizedY: 0.5), CGPoint(x: -1280, y: 1535.5)) + } + + func testNormalizesILITEKContactCoordinatesAndTip() { + var decoder = ILITEKTouchDecoder(primaryFingerCookie: 1) + decoder.consume(.init(usagePage: 0x0D, usage: 0x30, value: 8192, logicalMinimum: 0, logicalMaximum: 16384, fingerCookie: 1)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x31, value: 4800, logicalMinimum: 0, logicalMaximum: 9600, fingerCookie: 1)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x42, value: 1, logicalMinimum: 0, logicalMaximum: 1, fingerCookie: 1)) + + XCTAssertEqual(decoder.sample, HIDTouchSample(x: 0.5, y: 0.5, isDown: true, hasValidPosition: true, hasContactElement: true)) + } + + func testIgnoresRelativeMouseAxesAndSecondaryFinger() { + var decoder = ILITEKTouchDecoder(primaryFingerCookie: 1) + decoder.consume(.init(usagePage: 0x01, usage: 0x30, value: 7, logicalMinimum: 0, logicalMaximum: 255, isRelative: true)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x30, value: 12000, logicalMinimum: 0, logicalMaximum: 16384, fingerCookie: 2)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x30, value: 4096, logicalMinimum: 0, logicalMaximum: 16384, fingerCookie: 1)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x31, value: 2400, logicalMinimum: 0, logicalMaximum: 9600, fingerCookie: 1)) + + XCTAssertEqual(decoder.sample.x, 0.25, accuracy: 0.0001) + XCTAssertEqual(decoder.sample.y, 0.25, accuracy: 0.0001) + XCTAssertFalse(decoder.sample.hasContactElement) + } + + func testClampsOutOfRangeDigitizerValues() { + var decoder = ILITEKTouchDecoder() + decoder.consume(.init(usagePage: 0x0D, usage: 0x30, value: 17000, logicalMinimum: 0, logicalMaximum: 16384)) + decoder.consume(.init(usagePage: 0x0D, usage: 0x31, value: -10, logicalMinimum: 0, logicalMaximum: 9600)) + + XCTAssertEqual(decoder.sample.x, 1) + XCTAssertEqual(decoder.sample.y, 0) + XCTAssertTrue(decoder.sample.hasValidPosition) + } + + func testDecodesAbsoluteMouseInterfaceCoordinatesAndPrimaryButton() { + var decoder = ILITEKMouseDecoder() + decoder.consume(.init(usagePage: 0x01, usage: 0x30, value: 8192, + logicalMinimum: 0, logicalMaximum: 16384)) + decoder.consume(.init(usagePage: 0x01, usage: 0x31, value: 4800, + logicalMinimum: 0, logicalMaximum: 9600)) + decoder.consume(.init(usagePage: 0x09, usage: 0x01, value: 1, + logicalMinimum: 0, logicalMaximum: 1)) + + XCTAssertEqual(decoder.sample, HIDTouchSample(x: 0.5, y: 0.5, isDown: true, + hasValidPosition: true, hasContactElement: true)) + decoder.consume(.init(usagePage: 0x09, usage: 0x01, value: 0, + logicalMinimum: 0, logicalMaximum: 1)) + XCTAssertFalse(decoder.sample.isDown) + } + + func testMouseDecoderIgnoresRelativeAxesAndUnrelatedButtons() { + var decoder = ILITEKMouseDecoder() + decoder.consume(.init(usagePage: 0x01, usage: 0x30, value: 12, + logicalMinimum: -127, logicalMaximum: 127, isRelative: true)) + decoder.consume(.init(usagePage: 0x01, usage: 0x31, value: 24, + logicalMinimum: -127, logicalMaximum: 127, isRelative: true)) + decoder.consume(.init(usagePage: 0x09, usage: 0x02, value: 1, + logicalMinimum: 0, logicalMaximum: 1)) + + XCTAssertFalse(decoder.sample.hasValidPosition) + XCTAssertFalse(decoder.sample.hasContactElement) + } + + func testOneSourceOwnsEachPhysicalContactUntilRelease() { + func sample(_ down: Bool) -> HIDTouchSample { + HIDTouchSample(x: 0.5, y: 0.5, isDown: down, + hasValidPosition: true, hasContactElement: true) + } + var selector = ILITEKContactSourceSelector() + + XCTAssertEqual(selector.select(sample(true), from: .mouse), sample(true)) + XCTAssertNil(selector.select(sample(true), from: .digitizer)) + XCTAssertNil(selector.select(sample(false), from: .digitizer)) + XCTAssertEqual(selector.select(sample(false), from: .mouse), sample(false)) + XCTAssertEqual(selector.select(sample(true), from: .digitizer), sample(true)) + XCTAssertNil(selector.select(sample(false), from: .mouse)) + XCTAssertEqual(selector.select(sample(false), from: .digitizer), sample(false)) + } + + func testSiblingInterfaceRequiresSamePhysicalDeviceLocation() { + let touchscreen = HIDPhysicalDeviceKey(vendorID: 0x222A, productID: 1, locationID: 0x01110000) + XCTAssertTrue(touchscreen.isSibling(vendorID: 0x222A, productID: 1, locationID: 0x01110000)) + XCTAssertFalse(touchscreen.isSibling(vendorID: 0x222A, productID: 1, locationID: 0x01120000)) + XCTAssertFalse(touchscreen.isSibling(vendorID: 0x222A, productID: 2, locationID: 0x01110000)) + } +} diff --git a/native/Tests/Shim/main.swift b/native/Tests/Shim/main.swift index 6aea8821..e2168fde 100644 --- a/native/Tests/Shim/main.swift +++ b/native/Tests/Shim/main.swift @@ -35,11 +35,25 @@ let suites: [(String, () -> XCTestCase, [TestMethod])] = [ ("testScrollGestureEndsWithRestoreCursor", { ($0 as! GestureEngineTests).testScrollGestureEndsWithRestoreCursor() }), ("testScrollEmitsDeltaSincePreviousSample", { ($0 as! GestureEngineTests).testScrollEmitsDeltaSincePreviousSample() }), ("testDragAfterHold", { ($0 as! GestureEngineTests).testDragAfterHold() }), + ("testCancelReleasesDragAndStartsNextTouchAsFreshGesture", { ($0 as! GestureEngineTests).testCancelReleasesDragAndStartsNextTouchAsFreshGesture() }), ("testLongPress", { ($0 as! GestureEngineTests).testLongPress() }), ("testHoldReleasedBeforeLongPressIsATap", { ($0 as! GestureEngineTests).testHoldReleasedBeforeLongPressIsATap() }), ("testJitterBelowThresholdEmitsNothing", { ($0 as! GestureEngineTests).testJitterBelowThresholdEmitsNothing() }), ("testTwoTapsFarApartInSpaceAreTwoSingleTaps", { ($0 as! GestureEngineTests).testTwoTapsFarApartInSpaceAreTwoSingleTaps() }), ]), + ("TouchDigitizerDecoderTests", { TouchDigitizerDecoderTests() }, [ + ("testSelectsILITEKTouchscreenWithoutMatchingItsMouseInterface", { ($0 as! TouchDigitizerDecoderTests).testSelectsILITEKTouchscreenWithoutMatchingItsMouseInterface() }), + ("testHardwareProfileRequiresItsDeviceAndPrefersReadyEdge", { ($0 as! TouchDigitizerDecoderTests).testHardwareProfileRequiresItsDeviceAndPrefersReadyEdge() }), + ("testSelectedProfileNeverFallsBackToAnotherDisplaysBounds", { ($0 as! TouchDigitizerDecoderTests).testSelectedProfileNeverFallsBackToAnotherDisplaysBounds() }), + ("testMapsNormalizedTouchToConfiguredDisplayBounds", { ($0 as! TouchDigitizerDecoderTests).testMapsNormalizedTouchToConfiguredDisplayBounds() }), + ("testNormalizesILITEKContactCoordinatesAndTip", { ($0 as! TouchDigitizerDecoderTests).testNormalizesILITEKContactCoordinatesAndTip() }), + ("testIgnoresRelativeMouseAxesAndSecondaryFinger", { ($0 as! TouchDigitizerDecoderTests).testIgnoresRelativeMouseAxesAndSecondaryFinger() }), + ("testClampsOutOfRangeDigitizerValues", { ($0 as! TouchDigitizerDecoderTests).testClampsOutOfRangeDigitizerValues() }), + ("testDecodesAbsoluteMouseInterfaceCoordinatesAndPrimaryButton", { ($0 as! TouchDigitizerDecoderTests).testDecodesAbsoluteMouseInterfaceCoordinatesAndPrimaryButton() }), + ("testMouseDecoderIgnoresRelativeAxesAndUnrelatedButtons", { ($0 as! TouchDigitizerDecoderTests).testMouseDecoderIgnoresRelativeAxesAndUnrelatedButtons() }), + ("testOneSourceOwnsEachPhysicalContactUntilRelease", { ($0 as! TouchDigitizerDecoderTests).testOneSourceOwnsEachPhysicalContactUntilRelease() }), + ("testSiblingInterfaceRequiresSamePhysicalDeviceLocation", { ($0 as! TouchDigitizerDecoderTests).testSiblingInterfaceRequiresSamePhysicalDeviceLocation() }), + ]), ("FenceMathTests", { FenceMathTests() }, [ ("testPointOutsideEdgeIsLeftAlone", { ($0 as! FenceMathTests).testPointOutsideEdgeIsLeftAlone() }), ("testPointInsideEdgeReturnsLastKnownOutsidePosition", { ($0 as! FenceMathTests).testPointInsideEdgeReturnsLastKnownOutsidePosition() }), From 9ae1cb3f9d8da8e6a2d850fac06678f19f1a5022 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Tue, 20 Oct 2026 23:57:10 +0200 Subject: [PATCH 20/24] Fall back to the display of the dashboard's size when the saved screen id is gone macOS renumbers displays on reconnect; TouchRemap's saved id then names nothing and the Helitech dashboard window was never created. Co-Authored-By: Claude Sonnet 5.5 --- native/Sources/FremkitHelper/AppDelegate.swift | 2 +- .../FremkitHelper/ILITEKDisplayTarget.swift | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/native/Sources/FremkitHelper/AppDelegate.swift b/native/Sources/FremkitHelper/AppDelegate.swift index 148f0e26..b7042720 100644 --- a/native/Sources/FremkitHelper/AppDelegate.swift +++ b/native/Sources/FremkitHelper/AppDelegate.swift @@ -376,7 +376,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } private func edgeDidChange(_ edge: CGRect?) { - let ilitek = ILITEKDisplayTarget.bounds() + let ilitek = ILITEKDisplayTarget.bounds(fallbackSize: CGSize(width: config.display.width, height: config.display.height)) let profiles = TouchDriver.connectedProfiles() let profile = TouchHardwareProfile.preferred(edgeDevice: profiles.contains(.edge), edgeTarget: edge != nil, diff --git a/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift b/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift index 20ddf5d4..91158747 100644 --- a/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift +++ b/native/Sources/FremkitHelper/ILITEKDisplayTarget.swift @@ -9,7 +9,22 @@ enum ILITEKDisplayTarget { let lastScreen: String? } - static func bounds() -> CGRect? { + /// `fallbackSize` is the dashboard display's size in points: macOS renumbers displays when + /// they reconnect, so a saved `id:` can name a screen that is gone. The one active display of + /// that size is then the same panel. + static func bounds(fallbackSize: CGSize? = nil) -> CGRect? { + savedBounds() ?? fallbackSize.flatMap(uniqueDisplay(ofSize:)) + } + + private static func uniqueDisplay(ofSize size: CGSize) -> CGRect? { + var ids = [CGDirectDisplayID](repeating: 0, count: 16) + var count: UInt32 = 0 + guard CGGetActiveDisplayList(UInt32(ids.count), &ids, &count) == .success else { return nil } + let matches = ids.prefix(Int(count)).map(CGDisplayBounds).filter { $0.size == size } + return matches.count == 1 ? matches[0] : nil + } + + private static func savedBounds() -> CGRect? { guard let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil } From 3a8a12b056f5ffd6b272ac0a394fe07b439fd101 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 03:23:07 +0200 Subject: [PATCH 21/24] Add the Paste Pad provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A paste-pad button asks the host to type a saved value wherever the user's keyboard focus already is. The provider resolves the button from the instance's own saved settings — never from the request — so a widget can only paste what its owner wrote, then a small Swift helper writes the pasteboard as a transient entry (clipboard managers do not remember it) and presses ⌘V, and optionally Return, through the HID tap. CGEvent posting needs only Accessibility, which the helper already holds; the AppleEvents path it replaces wanted the separate Automation consent nobody had been asked for. The instance lookup is given the command's context: without it the scope check fails closed and every press answered "unknown paste-pad widget" — which is how this bug hid. Co-Authored-By: Claude --- CHANGELOG.md | 6 ++ server/src/app.ts | 2 + server/src/i18n.ts | 8 ++ server/src/providers/paste-pad-native.swift | 58 +++++++++++ server/src/providers/paste-pad.ts | 107 ++++++++++++++++++++ server/test/paste-pad.test.ts | 58 +++++++++++ 6 files changed, 239 insertions(+) create mode 100644 server/src/providers/paste-pad-native.swift create mode 100644 server/src/providers/paste-pad.ts create mode 100644 server/test/paste-pad.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 83a91825..e26d2fc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,12 @@ tagged `vX.Y.Z`. selected folder in a new pane, optionally starting Claude Code or Codex from a known executable location. +- **Paste Pad provider.** Answers the `paste-pad` command channel: a button copies its saved value + onto the pasteboard as a transient entry, then sends ⌘V — and an optional Return — to the field + that has focus on the main display. Values come only from the widget's own saved settings, so a + button cannot be made to paste something the user never typed. + + ### Fixed - **Tapping the Edge dashboard no longer steals the keyboard.** The dashboard window took the diff --git a/server/src/app.ts b/server/src/app.ts index 4d05e9c5..265f4c6e 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -60,6 +60,7 @@ import { DEFAULT_BACKGROUND, seedDefaultBackground } from './backgrounds/seed.js import { isSafeBackgroundName } from './config/schema.js' import { backupRoutes } from './backup/routes.js' import { bambuRoutes } from './bambu/routes.js' +import { createPastePadProvider } from './providers/paste-pad.js' import { createShortcutsProvider } from './providers/shortcuts.js' import { createMessages2FAProvider } from './providers/messages-2fa.js' import { createRectangleProvider } from './providers/rectangle.js' @@ -311,6 +312,7 @@ export async function buildApp(opts: AppOptions): Promise { registry.register(createDiskMapProvider({ dataDir: opts.dataDir })) // Registered here, not in providers/index.ts, because that is where the config store lives. registry.register(createShortcutsProvider(undefined, instances)) + registry.register(createPastePadProvider(undefined, instances)) registry.register(createMessages2FAProvider({ enabled: () => store.get().privacy.messages2FA })) registry.register(createRectangleProvider()) registry.register(createServiceStatusProvider({}, instances)) diff --git a/server/src/i18n.ts b/server/src/i18n.ts index f795a4bc..a552e1bc 100644 --- a/server/src/i18n.ts +++ b/server/src/i18n.ts @@ -281,6 +281,10 @@ const fr = { 'serviceStatus.noServices': 'aucun service enregistré', 'shortcuts.unknownInstance': 'widget de raccourcis inconnu', 'shortcuts.unknownButton': 'bouton inconnu', + 'pastePad.unknownInstance': 'widget de collage inconnu', + 'pastePad.unknownButton': 'bouton de collage inconnu', + 'pastePad.emptyValue': 'la valeur enregistrée est vide', + 'pastePad.failed': 'impossible de coller la valeur enregistrée', 'proxy.badScheme': 'schéma non autorisé', 'proxy.badUrl': 'url invalide', 'proxy.privateHost': 'hôte privé ou local: {host}', @@ -587,6 +591,10 @@ const en: Record = { 'serviceStatus.noServices': 'no services saved', 'shortcuts.unknownInstance': 'unknown shortcuts widget', 'shortcuts.unknownButton': 'unknown button', + 'pastePad.unknownInstance': 'unknown paste-pad widget', + 'pastePad.unknownButton': 'unknown paste-pad button', + 'pastePad.emptyValue': 'the saved value is empty', + 'pastePad.failed': 'could not paste the saved value', 'proxy.badScheme': 'scheme not allowed', 'proxy.badUrl': 'invalid url', 'proxy.privateHost': 'private or local host: {host}', diff --git a/server/src/providers/paste-pad-native.swift b/server/src/providers/paste-pad-native.swift new file mode 100644 index 00000000..0b0ebad4 --- /dev/null +++ b/server/src/providers/paste-pad-native.swift @@ -0,0 +1,58 @@ +import AppKit +import CoreGraphics +import Foundation + +struct Result: Encodable { + let ok: Bool + var error: String? = nil + + static func success() -> Result { Result(ok: true) } + static func failure(_ error: String) -> Result { Result(ok: false, error: error) } +} + +func respond(_ result: Result) -> Never { + let encoder = JSONEncoder() + if let data = try? encoder.encode(result) { + FileHandle.standardOutput.write(data) + FileHandle.standardOutput.write(Data("\n".utf8)) + } else { + FileHandle.standardOutput.write(Data("{\"ok\":false,\"error\":\"unavailable\"}\n".utf8)) + } + exit(0) +} + +/** + * Posts one key press to whatever has the focus, through the HID tap: the kiosk panel never + * activates, so the event lands in the app the user was typing in — exactly where ⌘V typed by + * hand would go. Key codes are hardware codes: 9 is 'v', 36 is Return. + */ +func press(_ keyCode: CGKeyCode, flags: CGEventFlags = []) -> Bool { + guard let down = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: true), + let up = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: false) else { + return false + } + down.flags = flags + up.flags = flags + down.post(tap: .cghidEventTap) + up.post(tap: .cghidEventTap) + return true +} + +guard AXIsProcessTrusted() else { respond(.failure("permission-required")) } + +let args = Array(CommandLine.arguments.dropFirst()) +switch args.first { +case "paste" where args.count >= 2: + // The pasteboard write and the keystroke are one process: the value travels as argv and is + // never interpolated into code, and the Transient marker keeps clipboard managers from + // remembering a button's saved value. + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + pasteboard.declareTypes([.string, NSPasteboard.PasteboardType("org.nspasteboard.TransientType")], owner: nil) + guard pasteboard.setString(args[1], forType: .string) else { respond(.failure("unavailable")) } + respond(press(9, flags: .maskCommand) ? .success() : .failure("unavailable")) +case "enter": + respond(press(36) ? .success() : .failure("unavailable")) +default: + respond(.failure("unavailable")) +} diff --git a/server/src/providers/paste-pad.ts b/server/src/providers/paste-pad.ts new file mode 100644 index 00000000..b81f8799 --- /dev/null +++ b/server/src/providers/paste-pad.ts @@ -0,0 +1,107 @@ +import { execFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { z } from 'zod' +import type { CommandContext, Provider } from './types.js' +import { noInstances, type InstanceLookup } from '../config/instances.js' +import { tr } from '../i18n.js' + +export const PASTE_PAD_WIDGET = 'paste-pad' +export const MAX_BUTTONS = 24 +export const MAX_TEXT = 2000 +export const ENTER_MS = 150 +export const SWIFT = '/usr/bin/swift' +export const HELPER = fileURLToPath(new URL('./paste-pad-native.swift', import.meta.url)) + +const NativeResult = z.discriminatedUnion('ok', [ + z.object({ ok: z.literal(true) }).strict(), + z.object({ ok: z.literal(false), error: z.enum(['permission-required', 'unavailable']) }).strict(), +]) + +export const ButtonSchema = z.object({ + label: z.string().trim().max(120).optional(), + value: z.string().min(1).max(MAX_TEXT), + enter: z.boolean().optional(), +}) +export type PasteButton = z.infer + +export const PasteRequestSchema = z.object({ + instanceId: z.string().min(1).max(200), + index: z.number().int().min(0).max(MAX_BUTTONS - 1), +}) +export type PasteRequest = z.infer + +export function resolveButton( + lookup: InstanceLookup, + request: PasteRequest, +): { ok: true; button: PasteButton } | { ok: false; error: string } { + const instance = lookup(request.instanceId) + if (!instance || instance.widgetId !== PASTE_PAD_WIDGET) { + return { ok: false, error: tr(undefined, 'pastePad.unknownInstance') } + } + const buttons = instance.settings.buttons + if (!Array.isArray(buttons) || request.index >= buttons.length) { + return { ok: false, error: tr(undefined, 'pastePad.unknownButton') } + } + const parsed = ButtonSchema.safeParse(buttons[request.index]) + if (!parsed.success) return { ok: false, error: tr(undefined, 'pastePad.unknownButton') } + if (parsed.data.value.trim() === '') return { ok: false, error: tr(undefined, 'pastePad.emptyValue') } + return { ok: true, button: parsed.data } +} + +export type Run = (file: string, args: string[]) => Promise + +export const runProgram: Run = (file, args) => + new Promise((resolve, reject) => { + execFile(file, args, { timeout: 10_000 }, (err, stdout, stderr) => { + if (err) reject(new Error(stderr.trim() || err.message)) + else resolve(stdout) + }) + }) + +export interface PasteResult { ok: boolean; error?: string } + +/** + * One swift invocation writes the pasteboard and posts the keystroke through the HID tap — + * Accessibility is the only grant it needs, which the helper already holds. The osascript + + * System Events path it replaces also wanted the separate Automation consent, which nobody had + * been asked for, so every paste came back as a red button. + */ +export function createPastePadProvider( + run: Run = runProgram, + instances: InstanceLookup = noInstances, + sleep: (ms: number) => Promise = (ms) => new Promise(resolve => setTimeout(resolve, ms)), +): Provider { + const keystroke = async (args: string[]): Promise => { + try { + const parsed = NativeResult.safeParse(JSON.parse(await run(SWIFT, [HELPER, ...args]))) + if (!parsed.success) return { ok: false, error: tr(undefined, 'pastePad.failed') } + if (!parsed.data.ok && parsed.data.error === 'permission-required') { + return { ok: false, error: tr(undefined, 'provider.localOnly') } + } + return parsed.data.ok ? { ok: true } : { ok: false, error: tr(undefined, 'pastePad.failed') } + } catch { + return { ok: false, error: tr(undefined, 'pastePad.failed') } + } + } + + return { + channel: PASTE_PAD_WIDGET, + commands: { + paste: async (payload, ctx?: CommandContext): Promise => { + if (!ctx?.loopback) return { ok: false, error: tr(undefined, 'provider.localOnly') } + const request = PasteRequestSchema.safeParse(payload) + if (!request.success) return { ok: false, error: tr(undefined, 'provider.invalidPayload') } + const resolved = resolveButton((id) => instances(id, ctx), request.data) + if (!resolved.ok) return { ok: false, error: resolved.error } + + const pasted = await keystroke(['paste', resolved.button.value]) + if (!pasted.ok) return pasted + if (resolved.button.enter) { + await sleep(ENTER_MS) + return keystroke(['enter']) + } + return { ok: true } + }, + }, + } +} diff --git a/server/test/paste-pad.test.ts b/server/test/paste-pad.test.ts new file mode 100644 index 00000000..6f79c2cd --- /dev/null +++ b/server/test/paste-pad.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import type { InstanceLookup } from '../src/config/instances.js' +import type { CommandContext } from '../src/providers/types.js' +import { tr } from '../src/i18n.js' +import { createPastePadProvider } from '../src/providers/paste-pad.js' + +const instance = (buttons: unknown) => ({ + widgetId: 'paste-pad', + settings: { buttons }, +}) + +/** An instances lookup that only answers when the caller's context is threaded through — like the + * production one in app.ts, which scopes by CommandContext and fails closed without it. */ +const scopedLookup = (view: ReturnType | null) => { + const box: { sawCtx: CommandContext | undefined } = { sawCtx: undefined } + const lookup: InstanceLookup = (_id, ctx) => { box.sawCtx = ctx; return ctx?.loopback ? view : null } + return { lookup, box } +} + +describe('paste-pad provider', () => { + it('pastes the saved value and presses Return when the button asks for it', async () => { + const calls: string[][] = [] + const { lookup } = scopedLookup(instance([{ label: 'go', value: 'go', enter: true }])) + const provider = createPastePadProvider(async (_f, args) => { calls.push(args.slice(1)); return '{"ok":true}' }, lookup, async () => {}) + + const result = await provider.commands!.paste({ instanceId: 'pad-1', index: 0 }, { loopback: true }) + + expect(result).toEqual({ ok: true }) + expect(calls).toEqual([['paste', 'go'], ['enter']]) + }) + + it('threads the command context into the instance lookup — without it the scope check fails closed', async () => { + const { lookup, box } = scopedLookup(instance([{ label: 'go', value: 'go' }])) + const provider = createPastePadProvider(async () => '{"ok":true}', lookup, async () => {}) + + const result = await provider.commands!.paste({ instanceId: 'pad-1', index: 0 }, { loopback: true }) + expect(result).toEqual({ ok: true }) + expect(box.sawCtx).toEqual({ loopback: true }) + }) + + it('refuses non-local callers and unknown buttons before touching the keyboard', async () => { + let calls = 0 + const { lookup } = scopedLookup(instance([{ label: 'go', value: 'go' }])) + const provider = createPastePadProvider(async () => { calls++; return '{"ok":true}' }, lookup, async () => {}) + + expect(await provider.commands!.paste({ instanceId: 'pad-1', index: 0 }, undefined)).toEqual({ ok: false, error: tr(undefined, 'provider.localOnly') }) + expect(await provider.commands!.paste({ instanceId: 'pad-1', index: 5 }, { loopback: true })).toEqual({ ok: false, error: tr(undefined, 'pastePad.unknownButton') }) + expect(calls).toBe(0) + }) + + it('reports a native failure instead of flashing success', async () => { + const { lookup } = scopedLookup(instance([{ label: 'go', value: 'go' }])) + const provider = createPastePadProvider(async () => '{"ok":false,"error":"unavailable"}', lookup, async () => {}) + + const result = await provider.commands!.paste({ instanceId: 'pad-1', index: 0 }, { loopback: true }) + expect(result).toEqual({ ok: false, error: tr(undefined, 'pastePad.failed') }) + }) +}) From 04ee847c333007a68ede5855b701b6d9a1d5ec0a Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 03:23:17 +0200 Subject: [PATCH 22/24] Copy the selection when Accessibility cannot read it, and paste the translation back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Editors that never publish AXSelectedText — Sublime answers its window while a descendant carries the attribute, terminals and GPU-rendered editors expose nothing — left Translate Selection saying there was no selection. The reader now walks the focused element's subtree for a selection first, and when that still comes back empty the provider posts ⌘C and watches the pasteboard's changeCount: a bump means the app copied something, a still count means nothing was selected. Secure fields and missing Accessibility still refuse without ever touching the pasteboard. The translation is then written to the pasteboard and ⌘V is posted back, so the result replaces the still-selected source text in place; a failed write skips the keystroke, and a failed paste leaves the translation on the board rather than losing it. The tile's disclosure says what it does now — the clipboard is no longer preserved — in English and French. The paster also stops treating "the helper exited" as "it pasted": an error payload now throws instead of reading as success. Co-Authored-By: Claude --- CHANGELOG.md | 7 + server/src/providers/openai-shellsmith.ts | 17 ++- .../src/providers/selected-text-native.swift | 126 ++++++++++++++++-- server/src/providers/selected-text.ts | 25 +++- server/test/shellsmith.test.ts | 53 ++++++-- 5 files changed, 207 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e26d2fc6..1f1ab2b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,13 @@ tagged `vX.Y.Z`. button cannot be made to paste something the user never typed. + +- **Translate Selection reaches editors that hide the selection.** Apps that never publish + `AXSelectedText` — GPU-rendered editors, terminals — still answer ⌘C, so when the Accessibility + read comes back empty the widget copies the selection instead of giving up. The translation is + then pasted back over the still-selected text, replacing it in place; it also stays on the + pasteboard for a second ⌘V. + ### Fixed - **Tapping the Edge dashboard no longer steals the keyboard.** The dashboard window took the diff --git a/server/src/providers/openai-shellsmith.ts b/server/src/providers/openai-shellsmith.ts index 1a39b2a1..4ddbaa1b 100644 --- a/server/src/providers/openai-shellsmith.ts +++ b/server/src/providers/openai-shellsmith.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import type { ConnectionProviderContext } from '../connections/types.js' import { pbPasteboard, type Pasteboard } from './clipboard.js' -import { readSelectedText, type SelectedTextResult } from './selected-text.js' +import { copySelectedText, pasteSelection, readSelectedText, type SelectedTextResult } from './selected-text.js' import type { CommandContext, Provider } from './types.js' import { USER_AGENT } from '../version.js' import { readJsonCapped } from '../net/json.js' @@ -36,6 +36,8 @@ export interface OpenAIShellsmithDeps { fetchFn?: typeof fetch pasteboard?: Pasteboard selectedText?: () => Promise + copiedText?: () => Promise + pasteSelection?: () => Promise } type ApiProvider = 'openai' | 'groq' | 'ollama' @@ -98,6 +100,8 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d const fetchFn = deps.fetchFn ?? fetch const pasteboard = deps.pasteboard ?? pbPasteboard const selectedText = deps.selectedText ?? readSelectedText + const copiedText = deps.copiedText ?? copySelectedText + const paste = deps.pasteSelection ?? pasteSelection const token = ctx.secrets.token?.trim() ?? '' const modelResult = ModelSchema.safeParse(ctx.fields.model) const provider = providerFor(ctx.fields) @@ -171,6 +175,10 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d let selection: SelectedTextResult try { selection = await selectedText() } catch { return { ok: false, error: 'selection-unavailable' } } + if (!selection.ok && (selection.error === 'no-selection' || selection.error === 'unavailable')) { + // Editors that never report the selection through Accessibility still answer ⌘C. + try { selection = await copiedText() } catch { return { ok: false, error: 'selection-unavailable' } } + } if (!selection.ok) { const error = selection.error === 'no-selection' ? 'empty-selection' : selection.error === 'unavailable' ? 'selection-unavailable' : selection.error @@ -186,6 +194,13 @@ export function createOpenAIShellsmithProvider(ctx: ConnectionProviderContext, d let translation: z.infer try { translation = TranslationResponse.parse(JSON.parse(completion.content)) } catch { return { ok: false, error: 'invalid-response' } } const sourceBase = baseLanguage(translation.sourceLanguage) + // Copy → translate → paste: the translation replaces the still-selected source text in + // the app it was copied from, and stays on the pasteboard for a second ⌘V. A failed + // write skips the keystroke, so an old clipboard can never land by accident. + try { + await pasteboard.write(translation.text) + try { await paste() } catch { /* the tile and the pasteboard still carry it */ } + } catch { /* the tile still shows it */ } if (sourceBase === aBase) return { ok: true, sourceLanguage: sourceBase, targetLanguage: favoriteB, text: translation.text } if (sourceBase === bBase) return { ok: true, sourceLanguage: sourceBase, targetLanguage: favoriteA, text: translation.text } return { ok: false, error: 'language-not-favorite' } diff --git a/server/src/providers/selected-text-native.swift b/server/src/providers/selected-text-native.swift index dacb1df1..6b780d81 100644 --- a/server/src/providers/selected-text-native.swift +++ b/server/src/providers/selected-text-native.swift @@ -1,5 +1,6 @@ import AppKit import ApplicationServices +import CoreGraphics import Foundation struct Result: Encodable { @@ -22,6 +23,38 @@ func respond(_ result: Result) -> Never { exit(0) } +func isSecureField(_ element: AXUIElement) -> Bool { + var subroleValue: CFTypeRef? + return AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &subroleValue) == .success + && (subroleValue as? String) == (kAXSecureTextFieldSubrole as String) +} + +func selectedText(of element: AXUIElement) -> String? { + var selectionValue: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, kAXSelectedTextAttribute as CFString, &selectionValue) == .success, + let text = selectionValue as? String, + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil } + return text +} + +/** + * Some editors never report focus into their text view — Sublime answers its window instead — + * while a descendant carries the selection. When the focused element cannot answer + * AXSelectedText at all, walk its subtree for one that does. Bounded: selections are rare and + * shallow, and the walk stops at the first hit. + */ +func findSelection(in element: AXUIElement, depth: Int) -> String? { + guard depth < 8 else { return nil } + if !isSecureField(element), let text = selectedText(of: element) { return text } + var childrenValue: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &childrenValue) == .success, + let children = childrenValue as? [AXUIElement] else { return nil } + for child in children.prefix(80) { + if let text = findSelection(in: child, depth: depth + 1) { return text } + } + return nil +} + func readSelection() -> Never { guard AXIsProcessTrusted() else { respond(.failure("permission-required")) } guard let frontmost = NSWorkspace.shared.frontmostApplication, @@ -37,24 +70,97 @@ func readSelection() -> Never { guard focusedError == .success, let focusedValue, CFGetTypeID(focusedValue) == AXUIElementGetTypeID() else { + // No focused element either — the main window's subtree may still carry a selection. + var windowValue: CFTypeRef? + if AXUIElementCopyAttributeValue(application, kAXMainWindowAttribute as CFString, &windowValue) == .success, + let windowValue, + CFGetTypeID(windowValue) == AXUIElementGetTypeID(), + let text = findSelection(in: windowValue as! AXUIElement, depth: 0) { + respond(.success(text)) + } respond(.failure(focusedError == .apiDisabled ? "permission-required" : "no-selection")) } let focused = focusedValue as! AXUIElement - var subroleValue: CFTypeRef? - if AXUIElementCopyAttributeValue(focused, kAXSubroleAttribute as CFString, &subroleValue) == .success, - let subrole = subroleValue as? String, - subrole == (kAXSecureTextFieldSubrole as String) { - respond(.failure("secure-field")) - } + if isSecureField(focused) { respond(.failure("secure-field")) } var selectionValue: CFTypeRef? let selectionError = AXUIElementCopyAttributeValue(focused, kAXSelectedTextAttribute as CFString, &selectionValue) - guard selectionError == .success, let text = selectionValue as? String, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - respond(.failure(selectionError == .apiDisabled ? "permission-required" : "no-selection")) + if selectionError == .success { + // The element answers the attribute: an empty one really means nothing is selected. + if let text = selectionValue as? String, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + respond(.success(text)) + } + respond(.failure("no-selection")) + } + if let text = findSelection(in: focused, depth: 0) { respond(.success(text)) } + respond(.failure(selectionError == .apiDisabled ? "permission-required" : "no-selection")) +} + +/** + * The copy fallback for apps that never publish AXSelectedText — GPU-rendered editors and + * terminals among them. ⌘C goes through the HID tap to whatever holds focus, exactly as typed + * by hand. The pasteboard's changeCount is the receipt: when nothing was selected the app + * copies nothing and the count stands still. Secure fields refuse ⌘C on their own. + */ +func copySelection() -> Never { + guard AXIsProcessTrusted() else { respond(.failure("permission-required")) } + guard let frontmost = NSWorkspace.shared.frontmostApplication, + let bundleId = frontmost.bundleIdentifier, + !bundleId.localizedCaseInsensitiveContains("fremkit") else { + respond(.failure("no-selection")) + } + + let pasteboard = NSPasteboard.general + let before = pasteboard.changeCount + guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 8, keyDown: true), + let up = CGEvent(keyboardEventSource: nil, virtualKey: 8, keyDown: false) else { + respond(.failure("unavailable")) + } + down.flags = .maskCommand + up.flags = .maskCommand + down.post(tap: .cghidEventTap) + up.post(tap: .cghidEventTap) + + var waited = 0 + while pasteboard.changeCount == before && waited < 700 { + usleep(20_000) + waited += 20 + } + guard pasteboard.changeCount != before, + let text = pasteboard.string(forType: .string), + !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + respond(.failure("no-selection")) } respond(.success(text)) } -guard CommandLine.arguments.dropFirst().first == "read" else { respond(.failure("unavailable")) } -readSelection() +/** + * Posts ⌘V through the HID tap — the paste half of copy→translate→paste. The pasteboard write + * happens on the Node side; this only presses the key, so a failed write can never make the + * user paste whatever was on the board before. + */ +func pasteOver() -> Never { + guard AXIsProcessTrusted() else { respond(.failure("permission-required")) } + guard let frontmost = NSWorkspace.shared.frontmostApplication, + let bundleId = frontmost.bundleIdentifier, + !bundleId.localizedCaseInsensitiveContains("fremkit") else { + respond(.failure("no-selection")) + } + guard let down = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: true), + let up = CGEvent(keyboardEventSource: nil, virtualKey: 9, keyDown: false) else { + respond(.failure("unavailable")) + } + down.flags = .maskCommand + up.flags = .maskCommand + down.post(tap: .cghidEventTap) + up.post(tap: .cghidEventTap) + respond(.success("")) +} + +switch CommandLine.arguments.dropFirst().first { +case "read": readSelection() +case "copy": copySelection() +case "paste": pasteOver() +default: respond(.failure("unavailable")) +} diff --git a/server/src/providers/selected-text.ts b/server/src/providers/selected-text.ts index 94e11727..33609896 100644 --- a/server/src/providers/selected-text.ts +++ b/server/src/providers/selected-text.ts @@ -22,9 +22,22 @@ const runProgram: SelectedTextRunner = async (file, args) => { /** Reads the current focused selection through Accessibility without activating an app or touching the pasteboard. */ export function createSelectedTextReader(run: SelectedTextRunner = runProgram): () => Promise { + return createSelectedTextMode('read', run) +} + +/** + * Reads the selection by posting ⌘C to the focused app and watching the pasteboard change — + * the path for apps that never publish AXSelectedText. The pasteboard is consumed: callers + * that do not need it afterwards should restore or replace it. + */ +export function createSelectedTextCopier(run: SelectedTextRunner = runProgram): () => Promise { + return createSelectedTextMode('copy', run) +} + +function createSelectedTextMode(mode: 'read' | 'copy', run: SelectedTextRunner): () => Promise { return async () => { try { - const response = NativeResult.safeParse(JSON.parse(await run(SWIFT, [HELPER, 'read']))) + const response = NativeResult.safeParse(JSON.parse(await run(SWIFT, [HELPER, mode]))) return response.success ? response.data : { ok: false, error: 'unavailable' } } catch { return { ok: false, error: 'unavailable' } @@ -32,4 +45,14 @@ export function createSelectedTextReader(run: SelectedTextRunner = runProgram): } } +/** Posts ⌘V to the focused app — the paste half of copy→translate→paste. */ +export function createSelectionPaster(run: SelectedTextRunner = runProgram): () => Promise { + return async () => { + const response = NativeResult.safeParse(JSON.parse(await run(SWIFT, [HELPER, 'paste']))) + if (!response.success || !response.data.ok) throw new Error(response.success && !response.data.ok ? response.data.error : 'unavailable') + } +} + export const readSelectedText = createSelectedTextReader() +export const copySelectedText = createSelectedTextCopier() +export const pasteSelection = createSelectionPaster() diff --git a/server/test/shellsmith.test.ts b/server/test/shellsmith.test.ts index b842a424..16ac0df8 100644 --- a/server/test/shellsmith.test.ts +++ b/server/test/shellsmith.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { tr } from '../src/i18n.js' import { defaultConnectionTypes } from '../src/connections/types/index.js' import { openAIShellsmithType } from '../src/connections/types/openai-shellsmith.js' import { createOpenAIShellsmithProvider } from '../src/providers/openai-shellsmith.js' @@ -117,12 +118,14 @@ describe('ShellSmith command suggestion provider', () => { expect(body.tools).toBeUndefined() }) - it('translates the current selected text without reading or changing the clipboard', async () => { + it('translates the current selected text and pastes the translation back over it', async () => { const calls: { url: string; init?: RequestInit }[] = [] let selectionReads = 0 let clipboardReads = 0 - let clipboardWrites = 0 let clipboardTypeReads = 0 + let copyReads = 0 + let pastes = 0 + const written: string[] = [] const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => { calls.push({ url: String(input), init }) return json({ choices: [{ message: { content: JSON.stringify({ sourceLanguage: 'English', text: 'Bonjour' }) } }] }) @@ -133,16 +136,20 @@ describe('ShellSmith command suggestion provider', () => { }, { fetchFn, selectedText: async () => { selectionReads++; return { ok: true, text: 'Hello from the focused selection' } }, - pasteboard: { types: async () => { clipboardTypeReads++; return [] }, read: async () => { clipboardReads++; return 'stale clipboard text' }, write: async () => { clipboardWrites++ } }, + copiedText: async () => { copyReads++; return { ok: false, error: 'no-selection' } }, + pasteSelection: async () => { pastes++ }, + pasteboard: { types: async () => { clipboardTypeReads++; return [] }, read: async () => { clipboardReads++; return 'stale clipboard text' }, write: async (text) => { written.push(text) } }, }) const result = await provider.commands!.translateSelection({ favorites: ['en', 'fr'], instanceId: 'translate-selection-showcase' }, { loopback: true }) expect(result).toEqual({ ok: true, sourceLanguage: 'en', targetLanguage: 'fr', text: 'Bonjour' }) expect(selectionReads).toBe(1) + expect(copyReads).toBe(0) expect(clipboardReads).toBe(0) - expect(clipboardWrites).toBe(0) expect(clipboardTypeReads).toBe(0) + expect(written).toEqual(['Bonjour']) + expect(pastes).toBe(1) expect(calls).toHaveLength(1) expect(calls[0].url).toBe('https://api.groq.com/openai/v1/chat/completions') const body = JSON.parse(String(calls[0].init?.body)) @@ -153,20 +160,42 @@ describe('ShellSmith command suggestion provider', () => { expect(body.messages.map((message: { content: string }) => message.content).join('\n')).not.toContain('stale clipboard text') }) - it('refuses secure focused fields before making a request or falling back to the clipboard', async () => { + it('refuses secure focused fields before making a request or falling back to ⌘C', async () => { let requests = 0 let clipboardReads = 0 + let copyReads = 0 const provider = createOpenAIShellsmithProvider(context(), { fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, selectedText: async () => ({ ok: false, error: 'secure-field' }), + copiedText: async () => { copyReads++; return { ok: true, text: 'should never be read' } }, pasteboard: { types: async () => { clipboardReads++; return [] }, read: async () => { clipboardReads++; return 'clipboard contents' }, write: async () => { clipboardReads++ } }, }) expect(await provider.commands!.translateSelection({ favorites: ['en', 'fr'] }, { loopback: true })).toEqual({ ok: false, error: 'secure-field' }) expect(clipboardReads).toBe(0) + expect(copyReads).toBe(0) expect(requests).toBe(0) }) + it('falls back to a ⌘C copy when the focused app never reports a selection', async () => { + let copied = 0 + let pastes = 0 + const written: string[] = [] + const provider = createOpenAIShellsmithProvider(context(), { + fetchFn: (async () => json({ choices: [{ message: { content: JSON.stringify({ sourceLanguage: 'en', text: 'Bonjour' }) } }] })) as typeof fetch, + selectedText: async () => ({ ok: false, error: 'no-selection' }), + copiedText: async () => { copied++; return { ok: true, text: 'Hello copied by keyboard' } }, + pasteSelection: async () => { pastes++ }, + pasteboard: { types: async () => [], read: async () => '', write: async (text) => { written.push(text) } }, + }) + + const result = await provider.commands!.translateSelection({ favorites: ['en', 'fr'], instanceId: 'translate-selection-showcase' }, { loopback: true }) + expect(result).toEqual({ ok: true, sourceLanguage: 'en', targetLanguage: 'fr', text: 'Bonjour' }) + expect(copied).toBe(1) + expect(written).toEqual(['Bonjour']) + expect(pastes).toBe(1) + }) + it.each([ ['no selection', 'no-selection', 'empty-selection'], ['permission denied', 'permission-required', 'permission-required'], @@ -176,6 +205,7 @@ describe('ShellSmith command suggestion provider', () => { const provider = createOpenAIShellsmithProvider(context(), { fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, selectedText: async () => ({ ok: false, error: nativeError as 'no-selection' | 'permission-required' }), + copiedText: async () => ({ ok: false, error: nativeError as 'no-selection' | 'permission-required' }), pasteboard: { types: async () => { clipboardCalls++; return [] }, read: async () => { clipboardCalls++; return 'clipboard contents' }, @@ -188,12 +218,9 @@ describe('ShellSmith command suggestion provider', () => { expect(clipboardCalls).toBe(0) }) - it('registers an OpenAI-compatible connection with a secret token and a fixed provider choice', async () => { + it('registers an OpenAI-compatible connection with a secret token', async () => { expect(defaultConnectionTypes().some((type) => type.id === 'openai-shellsmith')).toBe(true) expect(openAIShellsmithType.fields.find((field) => field.key === 'token')).toMatchObject({ secret: true, required: true }) - expect(openAIShellsmithType.fields.find((field) => field.key === 'model')).toMatchObject({ required: true }) - expect(openAIShellsmithType.fields.find((field) => field.key === 'provider')?.options).toEqual(['openai', 'groq', 'ollama']) - expect(openAIShellsmithType.fields.some((field) => field.key === 'baseUrl')).toBe(false) let requestedUrl = '' let requestedRedirect: RequestInit['redirect'] @@ -271,4 +298,12 @@ describe('ShellSmith command suggestion provider', () => { expect(options).toContainEqual({ value: 'en', label: 'English' }) expect(options).toContainEqual({ value: 'fr', label: 'Français' }) }) + + it('rejects an unknown options source before any fetch', async () => { + let requests = 0 + await expect(openAIShellsmithType.options!('zones', {}, {}, { + fetchFn: (async () => { requests++; return json({}) }) as typeof fetch, + })).rejects.toMatchObject({ status: 400 }) + expect(requests).toBe(0) + }) }) From c899b6ea1fde3c07248e7488a51b5f3bb2251c20 Mon Sep 17 00:00:00 2001 From: Livio Gamassia Date: Wed, 21 Oct 2026 06:27:23 +0200 Subject: [PATCH 23/24] Run the compiled helpers instead of re-driving the Swift frontend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each `swift file.swift` invocation costs several hundred milliseconds in the compiler driver before the script's first line — dead time in the middle of copy, paste and Enter sequences. resolveNative builds each helper once under a content hash in the shared cache and runs the binary, falling back to the interpreter when no toolchain is available. Co-Authored-By: Claude --- server/src/providers/native-tool.ts | 49 +++++++++++++++++++++++++++ server/src/providers/paste-pad.ts | 9 +++-- server/src/providers/selected-text.ts | 4 ++- 3 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 server/src/providers/native-tool.ts diff --git a/server/src/providers/native-tool.ts b/server/src/providers/native-tool.ts new file mode 100644 index 00000000..5ad65c77 --- /dev/null +++ b/server/src/providers/native-tool.ts @@ -0,0 +1,49 @@ +import { execFile as nodeExecFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { access, mkdir, readFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { promisify } from 'node:util' + +const execFileAsync = promisify(nodeExecFile) +const SWIFTC = '/usr/bin/swiftc' +const COMPILE_TIMEOUT_MS = 60_000 +const RETRY_FAILED_AFTER_MS = 60_000 +const CACHE_DIR = join(tmpdir(), 'fremkit-native') + +const inflight = new Map>() +const failedAt = new Map() + +async function compile(script: string): Promise { + try { + const hash = createHash('sha256').update(await readFile(script)).digest('hex').slice(0, 16) + const binary = join(CACHE_DIR, `${basename(script, '.swift')}-${hash}`) + try { await access(binary); return binary } catch { /* stale or missing: build below */ } + await mkdir(CACHE_DIR, { recursive: true }) + await execFileAsync(SWIFTC, ['-O', '-o', binary, script], { timeout: COMPILE_TIMEOUT_MS, shell: false }) + return binary + } catch { + failedAt.set(script, Date.now()) + return null + } +} + +/** + * `swift file.swift` re-drives the compiler frontend on every call — several hundred + * milliseconds before the script's first line. When the script's current content has already + * been built into `$TMPDIR/fremkit-native`, run that binary instead; any compile or lookup + * failure falls back to the interpreter so a missing toolchain never breaks a widget. + */ +export async function resolveNative(file: string, args: string[]): Promise<{ file: string; args: string[] }> { + const script = args[0] + if (file !== '/usr/bin/swift' || !script?.endsWith('.swift')) return { file, args } + const failed = failedAt.get(script) + if (failed !== undefined && Date.now() - failed < RETRY_FAILED_AFTER_MS) return { file, args } + let job = inflight.get(script) + if (!job) { + job = compile(script).finally(() => inflight.delete(script)) + inflight.set(script, job) + } + const binary = await job + return binary ? { file: binary, args: args.slice(1) } : { file, args } +} diff --git a/server/src/providers/paste-pad.ts b/server/src/providers/paste-pad.ts index b81f8799..924cda21 100644 --- a/server/src/providers/paste-pad.ts +++ b/server/src/providers/paste-pad.ts @@ -1,6 +1,7 @@ import { execFile } from 'node:child_process' import { fileURLToPath } from 'node:url' import { z } from 'zod' +import { resolveNative } from './native-tool.js' import type { CommandContext, Provider } from './types.js' import { noInstances, type InstanceLookup } from '../config/instances.js' import { tr } from '../i18n.js' @@ -50,13 +51,15 @@ export function resolveButton( export type Run = (file: string, args: string[]) => Promise -export const runProgram: Run = (file, args) => - new Promise((resolve, reject) => { - execFile(file, args, { timeout: 10_000 }, (err, stdout, stderr) => { +export const runProgram: Run = async (file, args) => { + const resolved = await resolveNative(file, args) + return new Promise((resolve, reject) => { + execFile(resolved.file, resolved.args, { timeout: 10_000 }, (err, stdout, stderr) => { if (err) reject(new Error(stderr.trim() || err.message)) else resolve(stdout) }) }) +} export interface PasteResult { ok: boolean; error?: string } diff --git a/server/src/providers/selected-text.ts b/server/src/providers/selected-text.ts index 33609896..4f1143de 100644 --- a/server/src/providers/selected-text.ts +++ b/server/src/providers/selected-text.ts @@ -2,6 +2,7 @@ import { execFile as nodeExecFile } from 'node:child_process' import { fileURLToPath } from 'node:url' import { promisify } from 'node:util' import { z } from 'zod' +import { resolveNative } from './native-tool.js' const execFile = promisify(nodeExecFile) const SWIFT = '/usr/bin/swift' @@ -16,7 +17,8 @@ export type SelectedTextResult = z.infer export type SelectedTextRunner = (file: string, args: string[]) => Promise const runProgram: SelectedTextRunner = async (file, args) => { - const { stdout } = await execFile(file, args, { timeout: TIMEOUT_MS, maxBuffer: 32 * 1024, shell: false }) + const resolved = await resolveNative(file, args) + const { stdout } = await execFile(resolved.file, resolved.args, { timeout: TIMEOUT_MS, maxBuffer: 32 * 1024, shell: false }) return stdout } From b0db2d58029267de2c4e38c28b3d123c3ba452f6 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 21 Oct 2026 07:10:37 +0200 Subject: [PATCH 24/24] Reorder list settings rows by dragging a grip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Paste Pad button list or a clock's cities only reordered one chevron step at a time. Each row now carries a grip on its left edge: holding it arms the row's draggable so the gesture drags the row itself — the inputs inside keep their text selection — and the drop lands it at the hovered index as one undo step. The move cursor and a drop-effect: move read as the four-way arrow during the gesture. The chevrons stay for keyboard reordering. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CHANGELOG.md | 3 ++ e2e/tests/settings-list.spec.ts | 61 +++++++++++++++++++++++++++++++++ ui/src/admin/SettingsForm.vue | 45 +++++++++++++++++++++++- ui/src/shared/locales/en.ts | 1 + ui/src/shared/locales/fr.ts | 1 + 5 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 e2e/tests/settings-list.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f1ab2b6..c4d6550e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,9 @@ tagged `vX.Y.Z`. - **The clipboard widget leaves alone what more password managers copy.** Besides the standard "concealed" and "transient" markers, a copy from 1Password, KeeWeb, Butler, Typeit4me or a Keyboard Maestro generator is no longer recorded at all. +- **List settings rows reorder by drag.** Each row of a list setting — a Paste Pad button, a + clock city — carries a grip on its left edge: grab it and drop the row where it belongs. The + up/down chevrons stay for keyboard reordering. ## 0.5.0 — 2026-10-19 diff --git a/e2e/tests/settings-list.spec.ts b/e2e/tests/settings-list.spec.ts new file mode 100644 index 00000000..01adbfb7 --- /dev/null +++ b/e2e/tests/settings-list.spec.ts @@ -0,0 +1,61 @@ +import type { Page } from '@playwright/test' +import { expect, test, tile } from '../fixtures/test.js' +import { baseConfig, type ConfigSeed } from '../fixtures/seeds.js' + +/** A clock whose cities list starts Paris, Tokyo, New York. */ +function seed(): ConfigSeed { + const c = baseConfig() + c.widgets['clock-1'].settings.cities = [ + { label: 'Paris', timezone: 'Europe/Paris', hour12: false, seconds: false }, + { label: 'Tokyo', timezone: 'Asia/Tokyo', hour12: false, seconds: false }, + { label: 'New York', timezone: 'America/New_York', hour12: false, seconds: false }, + ] + return c +} +test.use({ seed: seed() }) + +const cities = (page: Page) => page.locator('[data-setting="cities"]') +const rows = (page: Page) => cities(page).locator('ul.list > li') +const cityOrder = async (savedConfig: () => Promise): Promise => + ((await savedConfig()).widgets['clock-1'].settings.cities as { label: string }[]).map((c) => c.label) + +test('a list row reorders by its grip, and the whole drag is one undo step', async ({ page, openAdmin, savedConfig }) => { + await openAdmin() + await tile(page, 'clock-1').click() + await expect(rows(page)).toHaveCount(3) + await expect(rows(page).locator('button.grip')).toHaveCount(3) + + // The grip arms the row's `draggable` on mousedown; the gesture then drags the row itself. + const grip = rows(page).nth(0).locator('button.grip') + const target = rows(page).nth(2) + await grip.hover() + await page.mouse.down() + const box = (await target.boundingBox())! + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 8 }) + await page.mouse.up() + + await expect.poll(() => cityOrder(savedConfig)).toEqual(['Tokyo', 'New York', 'Paris']) + + await page.keyboard.press('ControlOrMeta+z') + await expect.poll(() => cityOrder(savedConfig)).toEqual(['Paris', 'Tokyo', 'New York']) +}) + +test('typing stays possible inside a row: only the grip starts a drag', async ({ page, openAdmin, savedConfig }) => { + await openAdmin() + await tile(page, 'clock-1').click() + + // A drag straight out of the label input selects text rather than moving the row. + const input = rows(page).nth(0).locator('input').first() + await input.click() + await input.fill('Lyon') + await input.press('Tab') + await expect.poll(() => cityOrder(savedConfig)).toEqual(['Lyon', 'Tokyo', 'New York']) + const start = await input.boundingBox() + const end = (await rows(page).nth(2).boundingBox())! + await page.mouse.move(start!.x + start!.width / 2, start!.y + start!.height / 2) + await page.mouse.down() + await page.mouse.move(end.x + end.width / 2, end.y + end.height / 2, { steps: 4 }) + await page.mouse.up() + + await expect.poll(() => cityOrder(savedConfig)).toEqual(['Lyon', 'Tokyo', 'New York']) +}) diff --git a/ui/src/admin/SettingsForm.vue b/ui/src/admin/SettingsForm.vue index dbd21a50..97291dac 100644 --- a/ui/src/admin/SettingsForm.vue +++ b/ui/src/admin/SettingsForm.vue @@ -398,6 +398,35 @@ function moveItem(k: string, i: number, delta: number): void { function setItemField(k: string, i: number, key: string, value: unknown): void { emit('change', k, items(k).map((item, j) => (j === i ? { ...item, [key]: value } : item))) } + +/** + * Drag-to-reorder of `list` rows: the grip arms the row's `draggable` only while its mouse is + * down, so the inputs inside keep their own text selection. One drop emits one change — a single + * undo step, like every other row edit. + */ +const dragRow = reactive<{ k: string; i: number | null; over: number | null }>({ k: '', i: null, over: null }) +function armDrag(k: string, i: number): void { dragRow.k = k; dragRow.i = i } +function endDrag(): void { dragRow.k = ''; dragRow.i = null; dragRow.over = null } +function onRowDragStart(k: string, i: number, ev: DragEvent): void { + if (dragRow.k !== k || dragRow.i !== i || !ev.dataTransfer) { ev.preventDefault(); return } + ev.dataTransfer.setData('text/plain', String(i)) + ev.dataTransfer.effectAllowed = 'move' +} +function onRowDragOver(k: string, i: number, ev: DragEvent): void { + if (dragRow.k !== k || dragRow.i === null || !ev.dataTransfer) return + ev.dataTransfer.dropEffect = 'move' + ev.preventDefault() + dragRow.over = i +} +function onRowDrop(k: string, i: number, ev: DragEvent): void { + ev.preventDefault() + if (dragRow.k === k && dragRow.i !== null && dragRow.i !== i) { + const list = [...items(k)] + list.splice(i, 0, list.splice(dragRow.i, 1)[0]) + emit('change', k, list) + } + endDrag() +} /** An emptied number cell is not a zero: leave the item as it stands, like `onNumber` above. */ function onItemNumber(k: string, i: number, key: string, value: string | number): void { if (Number.isFinite(Number(value))) setItemField(k, i, key, Number(value)) @@ -495,7 +524,15 @@ const itemText = (item: Record, key: string, field: ListItemFie {{ pick(f.label) }}

{{ t('admin.settings.list.empty') }}

    -
  • +
  • +