diff --git a/apps/server/src/assets/NativeAppIconResolver.ts b/apps/server/src/assets/NativeAppIconResolver.ts index e31d7a1d8c30d..5f6dd053474e5 100644 --- a/apps/server/src/assets/NativeAppIconResolver.ts +++ b/apps/server/src/assets/NativeAppIconResolver.ts @@ -1,34 +1,32 @@ -import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import type { NativeAppIconReference } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; -import * as Cause from "effect/Cause"; -import * as Digest from "effect/crypto/Digest"; -import * as SecureRandom from "effect/crypto/SecureRandom"; -import * as Effect from "effect/Effect"; -import * as Clock from "effect/Clock"; +import type * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; +import type * as PlatformError from "effect/PlatformError"; import * as Semaphore from "effect/Semaphore"; -import * as Hex from "effect/encoding/Hex"; -import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as ServerConfig from "../config.ts"; +import { darwinSource } from "./nativeAppIcons/darwin.ts"; +import { linuxSource } from "./nativeAppIcons/linux.ts"; +import { win32Source } from "./nativeAppIcons/win32.ts"; +import type { NativeAppIconSource } from "./nativeAppIcons/source.ts"; -const ICON_SIZE = 128; -const COMMAND_TIMEOUT = "5 seconds"; const RESOLUTION_CACHE_TTL = Duration.hours(1); const RESOLUTION_CACHE_MAX_ENTRIES = 256; +/** One source per platform; a platform without one resolves nothing. */ +const SOURCES: ReadonlyArray = [darwinSource, linuxSource, win32Source]; + +/** Resolves and caches host application icons without exposing host paths to clients. */ export class NativeAppIconResolver extends Context.Service< NativeAppIconResolver, { + /** Returns a cached image path for the application, or `null` when no icon is available. */ readonly resolve: (app: NativeAppIconReference) => Effect.Effect; } >()("t3/assets/NativeAppIconResolver") {} @@ -41,49 +39,6 @@ function appFromCacheKey(key: string): NativeAppIconReference { return JSON.parse(key) as NativeAppIconReference; } -const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) { - const fileSystem = yield* FileSystem.FileSystem; - const info = yield* fileSystem.stat(filePath).pipe( - Effect.asSome, - Effect.catchTags({ - PlatformError: (error) => - error.reason._tag === "NotFound" ? Effect.succeedNone : Effect.fail(error), - }), - ); - return Option.isSome(info) && info.value.type === "File" ? filePath : null; -}); - -const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* ( - command: string, - args: ReadonlyArray, -) { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - return yield* spawner - .string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" })) - .pipe(Effect.timeout(COMMAND_TIMEOUT)); -}); - -const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* ( - infoPlistPath: string, - key: string, -) { - return yield* commandOutput("/usr/bin/plutil", [ - "-extract", - key, - "raw", - "-o", - "-", - infoPlistPath, - ]).pipe( - Effect.map((value) => value.trim()), - Effect.orElseSucceed(() => ""), - ); -}); - -function escapeSpotlightString(value: string): string { - return value.replace(/([\\'*?])/gu, "\\$1"); -} - function containsControlCharacter(value: string): boolean { return [...value].some((character) => { const codePoint = character.codePointAt(0) ?? 0; @@ -91,135 +46,11 @@ function containsControlCharacter(value: string): boolean { }); } -const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* ( - app: NativeAppIconReference, -) { - const path = yield* Path.Path; - if (app._tag === "app-path") { - const appPath = expandHomePath(app.path, yield* HostProcess.HomeDirectory); - return path.isAbsolute(appPath) && appPath.endsWith(".app") ? appPath : null; - } - const query = - app._tag === "app-id" - ? `kMDItemCFBundleIdentifier == '${app.appId}'` - : `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`; - const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]); - const candidates = spotlightOutput - .split(/\r?\n/u) - .map((value) => value.trim()) - .filter((value) => value.endsWith(".app")); - const matchingCandidates = - app._tag === "app-id" - ? candidates - : candidates.filter( - (value) => - path.basename(value, ".app").toLocaleLowerCase() === - app.displayName.toLocaleLowerCase(), - ); - const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates; - let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null; - for (const candidate of rankedCandidates) { - const lastUsed = yield* commandOutput("/usr/bin/mdls", [ - "-raw", - "-name", - "kMDItemLastUsedDate", - candidate, - ]).pipe( - Effect.map((value) => value.trim()), - Effect.orElseSucceed(() => ""), - ); - if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) { - mostRecentlyUsed = { path: candidate, lastUsed }; - } - } - return mostRecentlyUsed?.path ?? null; -}); - -const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* ( - app: NativeAppIconReference, -) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const config = yield* ServerConfig.ServerConfig; - const appPath = yield* resolveApplicationPath(app); - if (!appPath) return null; - - const canonicalAppPath = yield* fileSystem.realPath(appPath); - const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist"); - const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources"); - const iconName = - (yield* plistValue(infoPlistPath, "CFBundleIconFile")) || - (yield* plistValue(infoPlistPath, "CFBundleIconName")); - if (iconName && path.basename(iconName) !== iconName) return null; - const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null; - const resourceEntries = yield* fileSystem - .readDirectory(resourcesDirectory) - .pipe(Effect.orElseSucceed(() => [])); - const sourceIconCandidate = - (iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ?? - (yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ?? - (resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns")) - ? yield* existingFile( - path.join( - resourcesDirectory, - resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!, - ), - ) - : null); - if (!sourceIconCandidate) return null; - const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate); - const relativeSource = path.relative(resourcesDirectory, sourceIconPath); - if ( - relativeSource === ".." || - relativeSource.startsWith(`..${path.sep}`) || - path.isAbsolute(relativeSource) - ) { - return null; - } - - const appVersion = - (yield* plistValue(infoPlistPath, "CFBundleVersion")) || - (yield* plistValue(infoPlistPath, "CFBundleShortVersionString")); - const random = yield* SecureRandom.SecureRandom; - const digest = yield* Digest.Digest; - const cacheKey = yield* digest - .digest( - Digest.sha256, - new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`), - ) - .pipe(Effect.map(Hex.encode), Effect.orDie); - const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons"); - const cachePath = path.join(cacheDirectory, `${cacheKey}-${ICON_SIZE}.png`); - if (yield* existingFile(cachePath)) return cachePath; - - yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true }); - const temporaryPath = path.join( - cacheDirectory, - `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* random.uuidV4()}.png`, - ); - yield* commandOutput("/usr/bin/sips", [ - "-z", - String(ICON_SIZE), - String(ICON_SIZE), - "-s", - "format", - "png", - sourceIconPath, - "--out", - temporaryPath, - ]).pipe( - Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)), - Effect.ensuring( - fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })), - ), - ); - return yield* existingFile(cachePath); -}); - /** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const hostPlatform = yield* HostProcess.Platform; + const source = SOURCES.find((candidate) => candidate.platform === hostPlatform); const resolutionSemaphore = yield* Semaphore.make(2); const resolutionCache: Cache.Cache< string, @@ -227,7 +58,9 @@ export const make = Effect.gen(function* () { PlatformError.PlatformError | Cause.TimeoutError > = yield* Cache.makeWith( (key: string) => - resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))), + source + ? resolutionSemaphore.withPermits(1)(source.resolve(appFromCacheKey(key))) + : Effect.succeed(null), { capacity: RESOLUTION_CACHE_MAX_ENTRIES, timeToLive: Exit.match({ @@ -249,10 +82,7 @@ export const make = Effect.gen(function* () { const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* ( app: NativeAppIconReference, ) { - if ( - hostPlatform !== "darwin" || - (app._tag === "display-name" && containsControlCharacter(app.displayName)) - ) { + if (!source || (app._tag === "display-name" && containsControlCharacter(app.displayName))) { return null; } diff --git a/apps/server/src/assets/nativeAppIcons/darwin.ts b/apps/server/src/assets/nativeAppIcons/darwin.ts new file mode 100644 index 0000000000000..cb44ec366c89d --- /dev/null +++ b/apps/server/src/assets/nativeAppIcons/darwin.ts @@ -0,0 +1,183 @@ +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import type { NativeAppIconReference } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import * as ServerConfig from "../../config.ts"; +import { existingFile, type NativeAppIconSource } from "./source.ts"; + +const ICON_SIZE = 128; +const COMMAND_TIMEOUT = "5 seconds"; + +const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* ( + command: string, + args: ReadonlyArray, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return yield* spawner + .string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" })) + .pipe(Effect.timeout(COMMAND_TIMEOUT)); +}); + +const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* ( + infoPlistPath: string, + key: string, +) { + return yield* commandOutput("/usr/bin/plutil", [ + "-extract", + key, + "raw", + "-o", + "-", + infoPlistPath, + ]).pipe( + Effect.map((value) => value.trim()), + Effect.orElseSucceed(() => ""), + ); +}); + +function escapeSpotlightString(value: string): string { + return value.replace(/([\\'*?])/gu, "\\$1"); +} + +const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* ( + app: NativeAppIconReference, +) { + const path = yield* Path.Path; + if (app._tag === "app-path") { + const appPath = expandHomePath(app.path, yield* HostProcess.HomeDirectory); + return path.isAbsolute(appPath) && appPath.endsWith(".app") ? appPath : null; + } + const query = + app._tag === "app-id" + ? `kMDItemCFBundleIdentifier == '${app.appId}'` + : `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`; + const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]); + const candidates = spotlightOutput + .split(/\r?\n/u) + .map((value) => value.trim()) + .filter((value) => value.endsWith(".app")); + const matchingCandidates = + app._tag === "app-id" + ? candidates + : candidates.filter( + (value) => + path.basename(value, ".app").toLocaleLowerCase() === + app.displayName.toLocaleLowerCase(), + ); + const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates; + let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null; + for (const candidate of rankedCandidates) { + const lastUsed = yield* commandOutput("/usr/bin/mdls", [ + "-raw", + "-name", + "kMDItemLastUsedDate", + candidate, + ]).pipe( + Effect.map((value) => value.trim()), + Effect.orElseSucceed(() => ""), + ); + if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) { + mostRecentlyUsed = { path: candidate, lastUsed }; + } + } + return mostRecentlyUsed?.path ?? null; +}); + +const resolveIcon = Effect.fn("NativeAppIconResolver.darwin.resolve")(function* ( + app: NativeAppIconReference, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + const appPath = yield* resolveApplicationPath(app); + if (!appPath) return null; + + const canonicalAppPath = yield* fileSystem.realPath(appPath); + const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist"); + const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources"); + const iconName = + (yield* plistValue(infoPlistPath, "CFBundleIconFile")) || + (yield* plistValue(infoPlistPath, "CFBundleIconName")); + if (iconName && path.basename(iconName) !== iconName) return null; + const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null; + const resourceEntries = yield* fileSystem + .readDirectory(resourcesDirectory) + .pipe(Effect.orElseSucceed(() => [])); + const sourceIconCandidate = + (iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ?? + (yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ?? + (resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns")) + ? yield* existingFile( + path.join( + resourcesDirectory, + resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!, + ), + ) + : null); + if (!sourceIconCandidate) return null; + const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate); + const relativeSource = path.relative(resourcesDirectory, sourceIconPath); + if ( + relativeSource === ".." || + relativeSource.startsWith(`..${path.sep}`) || + path.isAbsolute(relativeSource) + ) { + return null; + } + + const appVersion = + (yield* plistValue(infoPlistPath, "CFBundleVersion")) || + (yield* plistValue(infoPlistPath, "CFBundleShortVersionString")); + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const cacheKey = yield* digest + .digest( + Digest.sha256, + new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`), + ) + .pipe(Effect.map(Hex.encode), Effect.orDie); + const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons"); + const cachePath = path.join(cacheDirectory, `${cacheKey}-${ICON_SIZE}.png`); + if (yield* existingFile(cachePath)) return cachePath; + + yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true }); + const temporaryPath = path.join( + cacheDirectory, + `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* random.uuidV4()}.png`, + ); + yield* commandOutput("/usr/bin/sips", [ + "-z", + String(ICON_SIZE), + String(ICON_SIZE), + "-s", + "format", + "png", + sourceIconPath, + "--out", + temporaryPath, + ]).pipe( + Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)), + Effect.ensuring( + fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })), + ), + ); + return yield* existingFile(cachePath); +}); + +/** + * Spotlight finds the bundle for a bundle id or display name; the bundle's + * `.icns` is rendered to a cached PNG with `sips`. Every path stays on the + * server, so a display name cannot be used to walk the filesystem. + */ +export const darwinSource: NativeAppIconSource = { + platform: "darwin", + resolve: resolveIcon, +}; diff --git a/apps/server/src/assets/nativeAppIcons/linux.test.ts b/apps/server/src/assets/nativeAppIcons/linux.test.ts new file mode 100644 index 0000000000000..859beae0edaa9 --- /dev/null +++ b/apps/server/src/assets/nativeAppIcons/linux.test.ts @@ -0,0 +1,149 @@ +// @effect-diagnostics nodeBuiltinImport:off - fixtures are written before the layer exists. +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { afterAll } from "vite-plus/test"; + +import * as ServerConfig from "../../config.ts"; +import * as NativeAppIconResolver from "../NativeAppIconResolver.ts"; +import { parseDesktopEntry, rankDesktopEntry } from "./linux.ts"; + +const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-linux-app-icons-")); +afterAll(() => NodeFS.rmSync(root, { recursive: true, force: true })); + +function write(relative: string, contents: string) { + const filePath = NodePath.join(root, relative); + NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true }); + NodeFS.writeFileSync(filePath, contents); + return filePath; +} + +const CHROMIUM_DESKTOP = `[Desktop Entry] +Version=1.0 +Name=Chromium +Name[de]=Chromium Webbrowser +Comment=Access the Internet +Exec=/usr/bin/chromium %U +Icon=chromium +Type=Application +StartupWMClass=Chromium-browser +Categories=Network;WebBrowser; + +[Desktop Action new-window] +Name=New Window +Exec=/usr/bin/chromium +`; + +describe("parseDesktopEntry", () => { + it("keeps only the Desktop Entry group and skips hidden launchers", () => { + expect(parseDesktopEntry(CHROMIUM_DESKTOP, "chromium")).toEqual({ + name: "Chromium", + icon: "chromium", + wmClass: "Chromium-browser", + fileStem: "chromium", + }); + expect( + parseDesktopEntry("[Desktop Entry]\nName=Helper\nIcon=helper\nNoDisplay=true\n", "helper"), + ).toBeUndefined(); + expect(parseDesktopEntry("[Desktop Entry]\nName=NoIcon\n", "noicon")).toBeUndefined(); + }); +}); + +describe("rankDesktopEntry", () => { + const chromium = parseDesktopEntry(CHROMIUM_DESKTOP, "chromium")!; + it("prefers the window class over name prefixes", () => { + expect( + rankDesktopEntry(chromium, { _tag: "display-name", displayName: "Chromium-browser" }), + ).toBe(5); + expect(rankDesktopEntry(chromium, { _tag: "display-name", displayName: "chromium" })).toBe(3); + expect( + rankDesktopEntry(chromium, { _tag: "display-name", displayName: "Chromium-nightly" }), + ).toBe(2); + expect(rankDesktopEntry(chromium, { _tag: "display-name", displayName: "Firefox" })).toBe(0); + expect(rankDesktopEntry(chromium, { _tag: "app-id", appId: "chromium" })).toBe(4); + }); +}); + +// XDG_DATA_DIRS is colon-separated, so its fixture paths cannot carry a Windows drive letter. +describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("linux native app icons", () => { + const dataDir = NodePath.join(root, "share"); + const homeDir = NodePath.join(root, "home"); + write("share/applications/chromium.desktop", CHROMIUM_DESKTOP); + write("share/applications/broken.desktop", "not an ini"); + const png = write("share/icons/hicolor/64x64/apps/chromium.png", "png"); + write("share/icons/hicolor/16x16/apps/chromium.png", "tiny"); + const sketchSvg = write("opt/sketch/icon.svg", ""); + write( + "home/.local/share/applications/sketch.desktop", + `[Desktop Entry]\nName=Sketch\nIcon=${sketchSvg}\nStartupWMClass=sketch\n`, + ); + write( + "home/.local/share/applications/escape.desktop", + "[Desktop Entry]\nName=Escape\nIcon=../../../etc/passwd\nStartupWMClass=escape\n", + ); + write( + "share/applications/svgonly.desktop", + "[Desktop Entry]\nName=Vector\nIcon=vector\nStartupWMClass=vector\n", + ); + const svg = write("share/icons/hicolor/scalable/apps/vector.svg", ""); + + const dependencies = Layer.mergeAll( + ServerConfig.ServerConfig.layerTest(root, { prefix: "t3-linux-app-icon-" }), + Layer.succeed(HostProcess.Platform, "linux"), + Layer.succeed(HostProcess.Environment, { + HOME: homeDir, + XDG_DATA_DIRS: `${dataDir}:/nonexistent`, + }), + ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + const testLayer = NativeAppIconResolver.layer.pipe(Layer.provide(dependencies)); + + it.effect("resolves a window class through its launcher to the best hicolor size", () => + Effect.gen(function* () { + const resolver = yield* NativeAppIconResolver.NativeAppIconResolver; + expect( + yield* resolver.resolve({ _tag: "display-name", displayName: "Chromium-browser" }), + ).toBe(png); + expect(yield* resolver.resolve({ _tag: "display-name", displayName: "Chromium" })).toBe(png); + expect(yield* resolver.resolve({ _tag: "display-name", displayName: "Firefox" })).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("serves absolute and scalable icons but refuses relative escapes", () => + Effect.gen(function* () { + const resolver = yield* NativeAppIconResolver.NativeAppIconResolver; + expect(yield* resolver.resolve({ _tag: "display-name", displayName: "sketch" })).toBe( + sketchSvg, + ); + expect(yield* resolver.resolve({ _tag: "display-name", displayName: "vector" })).toBe(svg); + expect(yield* resolver.resolve({ _tag: "display-name", displayName: "escape" })).toBeNull(); + }).pipe(Effect.provide(testLayer)), + ); + + it.effect("resolves nothing on a platform without a source", () => + Effect.gen(function* () { + const resolver = yield* NativeAppIconResolver.NativeAppIconResolver; + expect( + yield* resolver.resolve({ _tag: "display-name", displayName: "Chromium-browser" }), + ).toBeNull(); + }).pipe( + Effect.provide( + NativeAppIconResolver.layer.pipe( + Layer.provide( + Layer.mergeAll( + ServerConfig.ServerConfig.layerTest(root, { prefix: "t3-aix-app-icon-" }), + Layer.succeed(HostProcess.Platform, "aix"), + Layer.succeed(HostProcess.Environment, { HOME: homeDir, XDG_DATA_DIRS: dataDir }), + ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ), + ), + ), + ), + ); +}); diff --git a/apps/server/src/assets/nativeAppIcons/linux.ts b/apps/server/src/assets/nativeAppIcons/linux.ts new file mode 100644 index 0000000000000..604993ccd1def --- /dev/null +++ b/apps/server/src/assets/nativeAppIcons/linux.ts @@ -0,0 +1,179 @@ +import type { NativeAppIconReference, ToolActivityNativeAppReference } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + +import { existingFile, type NativeAppIconSource } from "./source.ts"; + +/** Sizes worth serving for a 64px icon, best first; the client scales down. */ +const PREFERRED_SIZES = [64, 128, 96, 72, 256, 48, 512, 32] as const; +const ICON_EXTENSIONS = [".png", ".svg"] as const; +const MAX_DESKTOP_FILE_BYTES = 64 * 1024; + +export interface DesktopEntry { + readonly name: string; + readonly icon: string; + readonly wmClass: string | undefined; + readonly fileStem: string; +} + +/** + * Reads the `[Desktop Entry]` group of a freedesktop launcher. Only the keys + * the icon lookup needs are kept; localized `Name[xx]` variants are ignored + * because agents see the unlocalized window class. + */ +export function parseDesktopEntry(contents: string, fileStem: string): DesktopEntry | undefined { + let inEntry = false; + let name: string | undefined; + let icon: string | undefined; + let wmClass: string | undefined; + let hidden = false; + for (const rawLine of contents.split(/\r?\n/u)) { + const line = rawLine.trim(); + if (line.startsWith("[")) { + inEntry = line === "[Desktop Entry]"; + continue; + } + if (!inEntry || line.startsWith("#")) continue; + const separator = line.indexOf("="); + if (separator === -1) continue; + const key = line.slice(0, separator).trim(); + const value = line.slice(separator + 1).trim(); + if (key === "Name") name = value; + else if (key === "Icon") icon = value; + else if (key === "StartupWMClass") wmClass = value; + else if ((key === "NoDisplay" || key === "Hidden") && value === "true") hidden = true; + } + if (hidden || !name || !icon) return undefined; + return { name, icon, wmClass, fileStem }; +} + +const normalize = (value: string) => value.trim().toLocaleLowerCase(); + +/** + * Window classes rarely match launcher names (Chromium reports `Chromium-browser` for + * `chromium.desktop`), so the strictest match ranks first and `StartupWMClass` wins. + */ +export function rankDesktopEntry(entry: DesktopEntry, app: ToolActivityNativeAppReference): number { + const wanted = normalize(app._tag === "app-id" ? app.appId : app.displayName); + const wmClass = entry.wmClass ? normalize(entry.wmClass) : undefined; + const name = normalize(entry.name); + const stem = normalize(entry.fileStem); + if (wmClass === wanted) return 5; + if (app._tag === "app-id" && stem === wanted) return 4; + if (name === wanted || stem === wanted) return 3; + if (wanted.startsWith(`${stem}-`) || wanted.startsWith(`${name}-`)) return 2; + if (name.length >= 3 && wanted.startsWith(name)) return 1; + return 0; +} + +const applicationDirectories = Effect.fn("NativeAppIconResolver.linux.applicationDirectories")( + function* () { + const path = yield* Path.Path; + const environment = yield* HostProcess.Environment; + const dataHome = + environment.XDG_DATA_HOME?.trim() || + (environment.HOME ? path.join(environment.HOME, ".local", "share") : undefined); + const dataDirs = (environment.XDG_DATA_DIRS?.trim() || "/usr/local/share:/usr/share") + .split(":") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0 && path.isAbsolute(entry)); + const roots = [...(dataHome ? [dataHome] : []), ...dataDirs]; + return { + applications: roots.map((root) => path.join(root, "applications")), + icons: roots.flatMap((root) => [ + path.join(root, "icons", "hicolor"), + path.join(root, "pixmaps"), + ]), + }; + }, +); + +const readDesktopEntries = Effect.fn("NativeAppIconResolver.linux.readDesktopEntries")(function* ( + directories: ReadonlyArray, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const entries: DesktopEntry[] = []; + for (const directory of directories) { + const fileNames = yield* fileSystem + .readDirectory(directory) + .pipe(Effect.orElseSucceed((): string[] => [])); + for (const fileName of fileNames) { + if (!fileName.endsWith(".desktop")) continue; + const filePath = path.join(directory, fileName); + const info = yield* fileSystem.stat(filePath).pipe(Effect.option); + if (info._tag === "None" || info.value.type !== "File") continue; + if (info.value.size > MAX_DESKTOP_FILE_BYTES) continue; + const contents = yield* fileSystem.readFileString(filePath).pipe(Effect.option); + if (contents._tag === "None") continue; + const entry = parseDesktopEntry(contents.value, path.basename(fileName, ".desktop")); + if (entry) entries.push(entry); + } + } + return entries; +}); + +/** + * `Icon=` is either an absolute path or a theme name looked up in hicolor by + * size, then in pixmaps. A relative path with separators is rejected rather + * than joined, since the entry could point anywhere. + */ +const resolveIconFile = Effect.fn("NativeAppIconResolver.linux.resolveIconFile")(function* ( + icon: string, + iconDirectories: ReadonlyArray, +) { + const path = yield* Path.Path; + if (path.isAbsolute(icon)) { + const extension = path.extname(icon).toLowerCase(); + return (ICON_EXTENSIONS as ReadonlyArray).includes(extension) + ? yield* existingFile(icon) + : null; + } + if (icon.includes("/") || icon.includes("\\") || icon.includes("..")) return null; + const baseName = path.extname(icon) ? icon.slice(0, -path.extname(icon).length) : icon; + for (const directory of iconDirectories) { + const candidates = directory.endsWith("hicolor") + ? [ + ...PREFERRED_SIZES.flatMap((size) => + ICON_EXTENSIONS.map((extension) => + path.join(directory, `${size}x${size}`, "apps", `${baseName}${extension}`), + ), + ), + path.join(directory, "scalable", "apps", `${baseName}.svg`), + ] + : ICON_EXTENSIONS.map((extension) => path.join(directory, `${baseName}${extension}`)); + for (const candidate of candidates) { + const found = yield* existingFile(candidate); + if (found) return found; + } + } + return null; +}); + +const resolveIcon = Effect.fn("NativeAppIconResolver.linux.resolve")(function* ( + app: NativeAppIconReference, +) { + if (app._tag === "app-path") return null; + const directories = yield* applicationDirectories(); + const entries = yield* readDesktopEntries(directories.applications); + let best: { readonly entry: DesktopEntry; readonly rank: number } | undefined; + for (const entry of entries) { + const rank = rankDesktopEntry(entry, app); + if (rank > 0 && (!best || rank > best.rank)) best = { entry, rank }; + } + if (!best) return null; + return yield* resolveIconFile(best.entry.icon, directories.icons); +}); + +/** + * Cua reports a Linux app by its X11 window class, with no bundle id. The + * launcher database is the only place that maps a class back to an icon, so + * `.desktop` entries are matched by class, name, or file name and their + * `Icon=` resolved through the hicolor theme. PNG and SVG both serve as-is. + */ +export const linuxSource: NativeAppIconSource = { + platform: "linux", + resolve: resolveIcon, +}; diff --git a/apps/server/src/assets/nativeAppIcons/source.ts b/apps/server/src/assets/nativeAppIcons/source.ts new file mode 100644 index 0000000000000..0a9122677eebc --- /dev/null +++ b/apps/server/src/assets/nativeAppIcons/source.ts @@ -0,0 +1,48 @@ +import type { NativeAppIconReference } from "@t3tools/contracts"; +import type * as Cause from "effect/Cause"; +import type * as Digest from "effect/crypto/Digest"; +import type * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import type * as Path from "effect/Path"; +import type * as PlatformError from "effect/PlatformError"; +import type { ChildProcessSpawner } from "effect/process"; + +import type * as ServerConfig from "../../config.ts"; + +/** + * One platform's way of turning an app reference into an icon file on disk. + * The resolver picks the source for the host platform and owns caching and + * error handling, so a source only has to find (or render) the file. + */ +export interface NativeAppIconSource { + readonly platform: NodeJS.Platform; + /** An image file the asset route can serve, or `null` when the app has no icon. */ + readonly resolve: ( + app: NativeAppIconReference, + ) => Effect.Effect< + string | null, + PlatformError.PlatformError | Cause.TimeoutError, + | FileSystem.FileSystem + | Path.Path + | ServerConfig.ServerConfig + | ChildProcessSpawner.ChildProcessSpawner + | Digest.Digest + | SecureRandom.SecureRandom + >; +} + +export const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* ( + filePath: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const info = yield* fileSystem.stat(filePath).pipe( + Effect.asSome, + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" ? Effect.succeedNone : Effect.fail(error), + }), + ); + return Option.isSome(info) && info.value.type === "File" ? filePath : null; +}); diff --git a/apps/server/src/assets/nativeAppIcons/win32.ts b/apps/server/src/assets/nativeAppIcons/win32.ts new file mode 100644 index 0000000000000..96c5feaebbb37 --- /dev/null +++ b/apps/server/src/assets/nativeAppIcons/win32.ts @@ -0,0 +1,104 @@ +import type { NativeAppIconReference } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Digest from "effect/crypto/Digest"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import * as ServerConfig from "../../config.ts"; +import { existingFile, type NativeAppIconSource } from "./source.ts"; + +const COMMAND_TIMEOUT = "10 seconds"; + +/** + * Writes the app's icon as a PNG. Windows has no bundle ids, so the script tries a running process + * with Cua's app name, then a Start Menu shortcut. Arguments arrive as environment variables so + * the name is never spliced into the script. + */ +const EXTRACT_SCRIPT = ` +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Drawing +$name = $env:T3_APP_NAME +$exe = $null +$process = Get-Process -ErrorAction SilentlyContinue | + Where-Object { $_.Path -and ($_.ProcessName -ieq $name -or $_.MainWindowTitle -ieq $name -or $_.Product -ieq $name) } | + Select-Object -First 1 +if ($process) { $exe = $process.Path } +if (-not $exe) { + $shell = New-Object -ComObject WScript.Shell + $roots = @("$env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs", "$env:AppData\\Microsoft\\Windows\\Start Menu\\Programs") + $link = Get-ChildItem -Path $roots -Filter '*.lnk' -Recurse -ErrorAction SilentlyContinue | + Where-Object { $_.BaseName -ieq $name } | Select-Object -First 1 + if ($link) { $exe = $shell.CreateShortcut($link.FullName).TargetPath } +} +if (-not $exe -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { exit 3 } +Write-Output $exe +if ($env:T3_ICON_OUT) { + $icon = [System.Drawing.Icon]::ExtractAssociatedIcon($exe) + $bitmap = $icon.ToBitmap() + $bitmap.Save($env:T3_ICON_OUT, [System.Drawing.Imaging.ImageFormat]::Png) +} +`; + +const runScript = Effect.fn("NativeAppIconResolver.win32.runScript")(function* ( + env: Record, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return yield* spawner + .string( + ChildProcess.make( + "powershell.exe", + ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", EXTRACT_SCRIPT], + { stdin: "ignore", stderr: "ignore", env, extendEnv: true }, + ), + ) + .pipe(Effect.timeout(COMMAND_TIMEOUT)); +}); + +const resolveIcon = Effect.fn("NativeAppIconResolver.win32.resolve")(function* ( + app: NativeAppIconReference, +) { + if (app._tag === "app-path") return null; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const config = yield* ServerConfig.ServerConfig; + const name = (app._tag === "display-name" ? app.displayName : app.appId).trim(); + if (name.length === 0 || /[\\/:*?"<>|]/u.test(name)) return null; + + // The first run only locates the executable; its path and size key the cache. + const executable = (yield* runScript({ T3_APP_NAME: name })).trim(); + if (!executable) return null; + const info = yield* fileSystem.stat(executable); + const digest = yield* Digest.Digest; + const cacheKey = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(`${executable}\0${info.size}`)) + .pipe(Effect.map(Hex.encode), Effect.orDie); + const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons"); + const cachePath = path.join(cacheDirectory, `${cacheKey}.png`); + if (yield* existingFile(cachePath)) return cachePath; + + yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true }); + const temporaryPath = path.join( + cacheDirectory, + `.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}.png`, + ); + yield* runScript({ T3_APP_NAME: name, T3_ICON_OUT: temporaryPath }).pipe( + Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)), + Effect.ensuring( + fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })), + ), + ); + return yield* existingFile(cachePath); +}); + +/** + * Cua reports a Windows app by its name. PowerShell finds the executable + * (a running process first, then a Start Menu shortcut) and System.Drawing + * renders its associated icon to a cached PNG. + */ +export const win32Source: NativeAppIconSource = { + platform: "win32", + resolve: resolveIcon, +}; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c13cd9e5a48e1..354fd40ca9260 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -223,6 +223,10 @@ import { normalizeMcpText, } from "@t3tools/provider-core/server/mcpToolPresentation"; import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; +import { + parseCuaToolName, + rememberCuaToolResult, +} from "@t3tools/provider-core/server/cuaToolPresentation"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { @@ -7091,6 +7095,31 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly toolNonExecutionKind?: string; }) => { const completedAt = input.status === "running" ? null : input.updatedAt; + // Cua Driver titles follow the call's final input and status, and a + // finished call teaches the thread which app each pid is. + const cuaTool = parseCuaToolName(input.toolName); + if (cuaTool !== undefined && input.status === "completed") { + rememberCuaToolResult( + input.threadId, + cuaTool, + claudeNativeToolInputValue(input.toolInput), + claudeNativeToolOutputValue(input.output), + ); + } + const presentation = + cuaTool === undefined + ? input.presentation + : mcpToolPresentation({ + toolName: input.toolName, + threadId: input.threadId, + args: claudeNativeToolInputValue(input.toolInput), + status: + input.status === "running" + ? "inProgress" + : input.status === "completed" + ? "completed" + : "failed", + }); const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CLAUDE_PROVIDER, nativeItemId: input.nativeItemId, @@ -7156,7 +7185,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? formatReadToolLabel(readPath) : (searchTitle ?? dynamicToolTitle(input.toolName, nativeToolInput) ?? - input.presentation?.title ?? + presentation?.title ?? null), startedAt: input.startedAt, completedAt, @@ -7238,12 +7267,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( : { ...itemBase, type: "dynamic_tool", - ...(input.presentation?.toolIcon === undefined + ...(presentation?.toolSurface === undefined + ? {} + : { toolSurface: presentation.toolSurface }), + ...(presentation?.toolIcon === undefined ? {} - : { toolIcon: input.presentation.toolIcon }), - ...(input.presentation?.toolSource === undefined + : { toolIcon: presentation.toolIcon }), + ...(presentation?.toolSource === undefined ? {} - : { toolSource: input.presentation.toolSource }), + : { toolSource: presentation.toolSource }), toolName: input.toolName, ...(viewedImagePath === undefined ? {} : { viewedImagePath }), input: claudeNativeToolInputValue(input.toolInput), diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 830f33ef9a0c0..e2d94e4190a38 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -7,6 +7,11 @@ import { mcpToolPresentation, type McpToolPresentation, } from "../../provider/CodexToolPresentation.ts"; +import { + cuaCallContext, + mcpToolPresentation as sharedMcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; +import { isCuaServerName } from "@t3tools/provider-core/server/cuaToolPresentation"; import { makeCodexTurnTokenUsageState, getCodexTurnAccumulator, @@ -559,6 +564,8 @@ export function codexDynamicToolOutput( const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicToolItem")(function* ( item: CodexDynamicToolItem, + /** The app thread; Cua Driver calls resolve their app through it. */ + threadId: ThreadId | null = null, ): Effect.fn.Return { const output = item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item); @@ -566,8 +573,24 @@ const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicTool item.type === "mcpToolCall" ? `${item.server}.${item.tool}` : [trimText(item.namespace), item.tool].filter(Boolean).join("."); + const status = codexItemStatus(item.status).turnItem; const presentation: McpToolPresentation = - item.type === "mcpToolCall" ? yield* mcpToolPresentation(item) : {}; + item.type !== "mcpToolCall" + ? {} + : isCuaServerName(item.server) + ? sharedMcpToolPresentation({ + serverName: item.server, + toolName: item.tool, + ...cuaCallContext({ + serverName: item.server, + toolName: item.tool, + threadId, + status, + args: item.arguments, + result: item.result, + }), + }) + : yield* mcpToolPresentation(item); const title = dynamicToolTitle(toolName, item.arguments, presentation.title) ?? presentation.title; const toolSurface = presentation.toolSurface ?? dynamicToolSurface(toolName, item.arguments); @@ -582,7 +605,7 @@ const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicTool toolName, ...(title ? { title } : {}), input: item.arguments, - status: codexItemStatus(item.status).turnItem, + status, }; return output === undefined ? projection : { ...projection, output }; }); @@ -4270,9 +4293,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: item.id, }); const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id); - const projection = yield* projectCodexDynamicToolItem(item).pipe( - Effect.provideService(Digest.Digest, digest), - ); + const projection = yield* projectCodexDynamicToolItem( + item, + context.projectionThreadId, + ).pipe(Effect.provideService(Digest.Digest, digest)); const node: OrchestrationV2ExecutionNode = { id: nodeId, threadId: context.projectionThreadId, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 0cdd5933c3d26..40236c0c309ff 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -72,7 +72,10 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { makeAcpMcpOverAcpBridge, type AcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts"; -import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; +import { + cuaCallContext, + mcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { @@ -4442,6 +4445,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( source: unknownRecord( (unknownRecord(rawOutputRecord?.result) ?? rawOutputRecord)?._meta, )?.source, + ...cuaCallContext({ + serverName: mcpIdentity.server, + toolName: mcpIdentity.tool, + threadId: base.threadId, + status: base.status, + args: mcpIdentity.input ?? unknownRecord(rawInputRecord?.arguments), + result: rawOutput, + }), }), type: "dynamic_tool", toolName, diff --git a/packages/provider-core/package.json b/packages/provider-core/package.json index 3ff646eaa135d..b7958b5e4a50f 100644 --- a/packages/provider-core/package.json +++ b/packages/provider-core/package.json @@ -27,6 +27,10 @@ "types": "./src/server/collectStreamText.ts", "import": "./src/server/collectStreamText.ts" }, + "./server/cuaToolPresentation": { + "types": "./src/server/cuaToolPresentation.ts", + "import": "./src/server/cuaToolPresentation.ts" + }, "./server/driver": { "types": "./src/server/driver.ts", "import": "./src/server/driver.ts" diff --git a/packages/provider-core/src/server/cuaToolPresentation.test.ts b/packages/provider-core/src/server/cuaToolPresentation.test.ts new file mode 100644 index 0000000000000..f91110bb01ca7 --- /dev/null +++ b/packages/provider-core/src/server/cuaToolPresentation.test.ts @@ -0,0 +1,341 @@ +import * as NodeAssert from "node:assert/strict"; + +import { ThreadId } from "@t3tools/contracts"; +import { describe, it } from "vite-plus/test"; + +import { + CUA_TOOL_TITLES, + clearCuaToolContext, + cuaToolPresentation, + isCuaServerName, + parseCuaToolName, + readCuaWindowTarget, + rememberCuaToolResult, +} from "./cuaToolPresentation.ts"; + +const threadId = ThreadId.make("thread-cua-presentation"); + +describe("parseCuaToolName", () => { + it.each([ + ["mcp__cua-driver__click", "click"], + ["cua-driver_type_text", "type_text"], + ["cua-driver/get_window_state", "get_window_state"], + ["cua-driver: list_apps", "list_apps"], + ["Run cua_driver.scroll", "scroll"], + ])("reads %s as %s", (raw, expected) => { + NodeAssert.equal(parseCuaToolName(raw), expected); + }); + + it("ignores other servers and unrelated titles", () => { + NodeAssert.equal(parseCuaToolName("mcp__linear__create_issue"), undefined); + NodeAssert.equal(parseCuaToolName("Bash"), undefined); + NodeAssert.equal(parseCuaToolName(undefined), undefined); + NodeAssert.equal(isCuaServerName("cua-driver"), true); + NodeAssert.equal(isCuaServerName("cua_driver"), true); + NodeAssert.equal(isCuaServerName("node_repl"), false); + }); +}); + +describe("cuaToolPresentation", () => { + it("resolves apps by pid from earlier discovery results", () => { + clearCuaToolContext(threadId); + rememberCuaToolResult( + threadId, + "list_apps", + {}, + JSON.stringify({ + apps: [{ pid: 1246, name: "Helium", bundle_id: "net.imput.helium", running: true }], + }), + ); + const clicked = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__click", + args: { pid: 1246, window_id: 59, x: 10, y: 20 }, + status: "completed", + }); + NodeAssert.deepEqual(clicked, { + title: "Clicked in Helium", + toolSurface: "computer", + toolIcon: { _tag: "native-app", app: { _tag: "app-id", appId: "net.imput.helium" } }, + toolSource: { + key: "native-app:net.imput.helium", + name: "Helium", + kind: "computer", + icon: { _tag: "native-app", app: { _tag: "app-id", appId: "net.imput.helium" } }, + }, + }); + NodeAssert.equal( + cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__hotkey", + args: { pid: 1246, keys: ["cmd", "t"] }, + status: "inProgress", + })?.title, + "Pressing ⌘T in Helium", + ); + NodeAssert.equal( + cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__scroll", + args: { pid: 1246, direction: "down" }, + status: "completed", + })?.title, + "Scrolled down in Helium", + ); + }); + + it("learns names from window listings and MCP content arrays", () => { + clearCuaToolContext(threadId); + rememberCuaToolResult( + threadId, + "list_windows", + {}, + { + content: [ + { + type: "text", + text: JSON.stringify({ windows: [{ window_id: 59, pid: 1246, app_name: "Helium" }] }), + }, + ], + }, + ); + const looked = cuaToolPresentation({ + threadId, + rawToolName: "cua-driver_get_window_state", + args: { pid: 1246, window_id: 59 }, + status: "completed", + }); + NodeAssert.equal(looked?.title, "Looked at Helium"); + NodeAssert.deepEqual(looked?.toolIcon, { + _tag: "native-app", + app: { _tag: "display-name", displayName: "Helium" }, + }); + NodeAssert.equal(looked?.toolSource.key, "native-app-name:helium"); + }); + + it("falls back to a generic computer-use source without an app", () => { + clearCuaToolContext(threadId); + const listing = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__list_apps", + args: {}, + status: "inProgress", + }); + NodeAssert.equal(listing?.title, "Listing apps"); + NodeAssert.equal(listing?.toolIcon, undefined); + NodeAssert.deepEqual(listing?.toolSource, { + key: "computer-use", + name: "Computer Use", + kind: "computer", + }); + const unknownPid = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__click", + args: { pid: 999 }, + status: "completed", + }); + NodeAssert.equal(unknownPid?.title, "Clicked"); + }); + + it("uses the requested bundle for launch_app before any listing", () => { + clearCuaToolContext(threadId); + const launching = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__launch_app", + args: { bundle_id: "com.apple.Safari" }, + status: "inProgress", + }); + NodeAssert.equal(launching?.title, "Launching Safari"); + NodeAssert.deepEqual(launching?.toolIcon, { + _tag: "native-app", + app: { _tag: "app-id", appId: "com.apple.Safari" }, + }); + rememberCuaToolResult( + threadId, + "launch_app", + { bundle_id: "com.apple.Safari" }, + JSON.stringify({ pid: 4321, name: "Safari" }), + ); + NodeAssert.equal( + cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__type_text", + args: { pid: 4321, text: "hello" }, + status: "completed", + })?.title, + "Typed text in Safari", + ); + }); + + it("returns nothing for tools outside Cua", () => { + NodeAssert.equal( + cuaToolPresentation({ + threadId, + rawToolName: "mcp__linear__create_issue", + args: {}, + status: "completed", + }), + undefined, + ); + }); +}); + +/** Tools advertised by Cua Driver 0.38 (`cua-driver mcp`) on any platform. */ +const CUA_DRIVER_TOOLS = [ + "bring_to_front", + "browser_click", + "browser_dialog", + "browser_download", + "browser_navigate", + "browser_pointer", + "browser_prepare", + "browser_select", + "browser_set_input_files", + "browser_type", + "check_for_update", + "check_permissions", + "click", + "clipboard_read", + "clipboard_write", + "debug_window_info", + "double_click", + "drag", + "end_session", + "escalate_session", + "get_accessibility_tree", + "get_agent_cursor_state", + "get_browser_state", + "get_config", + "get_cursor_position", + "get_desktop_state", + "get_guide", + "get_recording_state", + "get_screen_size", + "get_session", + "get_session_state", + "get_window_state", + "health_report", + "hotkey", + "install_extension", + "install_ffmpeg", + "invoke_menu", + "kill_app", + "launch_app", + "list_apps", + "list_sessions", + "list_windows", + "mouse_button_down", + "mouse_button_up", + "mouse_drag", + "move_cursor", + "page", + "parallel_mouse_drag", + "parse_visual_regions", + "press_key", + "replay_trajectory", + "right_click", + "run_script", + "run_steps", + "scroll", + "set_agent_cursor_enabled", + "set_agent_cursor_motion", + "set_agent_cursor_theme", + "set_config", + "set_value", + "set_window_frame", + "start_recording", + "start_session", + "stop_recording", + "type_text", + "verify_state", + "zoom", +]; + +describe("readCuaWindowTarget", () => { + it("remembers the last pid and window id a tool call addressed", () => { + clearCuaToolContext(threadId); + NodeAssert.equal(readCuaWindowTarget(threadId), undefined); + cuaToolPresentation({ + threadId, + rawToolName: "cua-driver/get_window_state", + args: { pid: 42, window_id: "7" }, + status: "completed", + }); + NodeAssert.deepEqual(readCuaWindowTarget(threadId), { pid: 42, windowId: 7n }); + cuaToolPresentation({ + threadId, + rawToolName: "cua-driver/click", + args: { pid: 42, element_token: "e1" }, + status: "completed", + }); + NodeAssert.deepEqual(readCuaWindowTarget(threadId), { pid: 42, windowId: 7n }); + cuaToolPresentation({ + threadId, + rawToolName: "cua-driver/click", + args: { pid: 9, window_id: 0, x: 1, y: 1 }, + status: "completed", + }); + NodeAssert.deepEqual(readCuaWindowTarget(threadId), { pid: 42, windowId: 7n }); + clearCuaToolContext(threadId); + NodeAssert.equal(readCuaWindowTarget(threadId), undefined); + }); +}); + +describe("CUA_TOOL_TITLES", () => { + it("names every tool the driver exposes", () => { + const missing = CUA_DRIVER_TOOLS.filter((tool) => !(tool in CUA_TOOL_TITLES)); + NodeAssert.deepEqual(missing, []); + for (const tool of CUA_DRIVER_TOOLS) { + const title = CUA_TOOL_TITLES[tool]!({ args: {}, appName: undefined, inProgress: false }); + NodeAssert.ok(title.length > 0 && !title.includes("_"), `${tool}: ${title}`); + } + }); + + it("names the app a run_steps batch targets through its last step", () => { + clearCuaToolContext(threadId); + rememberCuaToolResult( + threadId, + "list_apps", + {}, + { + apps: [{ pid: 512, name: "Safari", bundle_id: "com.apple.Safari" }], + }, + ); + const presentation = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__run_steps", + args: { + steps: [ + { action: "click", pid: 99 }, + { action: "type_text", pid: 512, window_id: 3 }, + ], + }, + status: "completed", + }); + NodeAssert.equal(presentation?.title, "Ran steps in Safari"); + }); + + it("targets the last app in the thread when a call only carries an element token", () => { + clearCuaToolContext(threadId); + rememberCuaToolResult( + threadId, + "list_apps", + {}, + '{"apps":[{"pid":1252,"name":"Calendar","bundle_id":"com.apple.iCal"}]}', + ); + cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__get_window_state", + args: { pid: 1252, window_id: 61 }, + status: "completed", + }); + const clicked = cuaToolPresentation({ + threadId, + rawToolName: "mcp__cua-driver__click", + args: { element_token: "s00000001:119", session: "cal" }, + status: "failed", + }); + NodeAssert.equal(clicked?.title, "Clicked in Calendar"); + NodeAssert.equal(clicked?.toolSource.key, "native-app:com.apple.ical"); + }); +}); diff --git a/packages/provider-core/src/server/cuaToolPresentation.ts b/packages/provider-core/src/server/cuaToolPresentation.ts new file mode 100644 index 0000000000000..22530ef0f47d1 --- /dev/null +++ b/packages/provider-core/src/server/cuaToolPresentation.ts @@ -0,0 +1,487 @@ +import type { + ThreadId, + ToolActivityIcon, + ToolActivityNativeAppReference, + ToolActivitySource, +} from "@t3tools/contracts"; + +import { CUA_MCP_SERVER_NAME } from "./mcpSession.ts"; + +/** + * Shared presentation for Cua Driver tool calls, so every provider renders + * them like Codex computer use: a "computer" surface, the target app's icon, + * and a human title. Cua addresses apps by pid, so the directory learns + * pid-to-app mappings from discovery results and resolves later calls. + */ +export interface CuaToolPresentation { + readonly title: string; + readonly toolSurface: "computer"; + readonly toolIcon?: ToolActivityIcon; + readonly toolSource: ToolActivitySource; +} + +export interface CuaApp { + readonly name?: string; + readonly bundleId?: string; +} + +const SERVER_PATTERN = CUA_MCP_SERVER_NAME.replace(/-/gu, "[-_]"); +// Claude: mcp__cua-driver__click. OpenCode: cua-driver_click. ACP titles vary: +// "cua-driver/click", "cua-driver: click", "cua-driver.click". +const TOOL_NAME_PATTERN = new RegExp( + `(?:^|[\\s(\`"'])(?:mcp__)?${SERVER_PATTERN}\\s*(?:__|_|/|:|\\.|\\s)\\s*([A-Za-z][A-Za-z0-9_]*)`, + "u", +); + +/** The Cua tool a provider-formatted tool name or title refers to, if any. */ +export function parseCuaToolName(value: string | undefined): string | undefined { + if (!value) return undefined; + const tool = TOOL_NAME_PATTERN.exec(value)?.[1]; + return tool ? tool.toLowerCase() : undefined; +} + +export function isCuaServerName(server: string | undefined): boolean { + return server?.trim().toLowerCase().replace(/_/gu, "-") === CUA_MCP_SERVER_NAME; +} + +const MAX_THREADS = 256; +const MAX_APPS_PER_THREAD = 128; + +/** The window the agent addressed most recently, for the live preview. */ +export interface CuaWindowTarget { + readonly pid: number; + readonly windowId: bigint; +} + +interface ThreadDirectory { + readonly byPid: Map; + lastApp: CuaApp | undefined; + lastWindow: CuaWindowTarget | undefined; +} + +const directories = new Map(); + +function directoryFor(threadId: ThreadId): ThreadDirectory { + const existing = directories.get(threadId); + if (existing) { + // Refresh insertion order so the busiest threads survive eviction. + directories.delete(threadId); + directories.set(threadId, existing); + return existing; + } + while (directories.size >= MAX_THREADS) { + const oldest = directories.keys().next().value; + if (oldest === undefined) break; + directories.delete(oldest); + } + const created: ThreadDirectory = { byPid: new Map(), lastApp: undefined, lastWindow: undefined }; + directories.set(threadId, created); + return created; +} + +export function clearCuaToolContext(threadId: ThreadId): void { + directories.delete(threadId); +} + +/** Last window the agent targeted in this thread, if any tool call named one. */ +export function readCuaWindowTarget(threadId: ThreadId): CuaWindowTarget | undefined { + return directories.get(threadId)?.lastWindow; +} + +function asWindowId(value: unknown): bigint | undefined { + if (typeof value === "bigint") return value > 0n ? value : undefined; + if (typeof value === "number" && Number.isInteger(value) && value > 0) return BigInt(value); + if (typeof value === "string" && /^[0-9]+$/u.test(value)) { + const id = BigInt(value); + return id > 0n ? id : undefined; + } + return undefined; +} + +function asRecord(value: unknown): Record | undefined { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function asPid(value: unknown): number | undefined { + const pid = typeof value === "string" ? Number(value) : value; + return typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : undefined; +} + +function asText(value: unknown, maxLength: number): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= maxLength ? trimmed : undefined; +} + +const asAppName = (value: unknown) => asText(value, 160); +const asBundleId = (value: unknown) => { + const id = asText(value, 512); + return id && /^[A-Za-z0-9._-]+$/u.test(id) ? id : undefined; +}; + +/** Accepts tool result text, MCP content arrays, or already-parsed objects. */ +function parseResult(result: unknown): unknown { + if (typeof result === "string") { + try { + return JSON.parse(result) as unknown; + } catch { + return undefined; + } + } + const record = asRecord(result); + if (record?.structuredContent !== undefined) return record.structuredContent; + const content = Array.isArray(record?.content) ? record.content : undefined; + if (content) { + for (const entry of content) { + const item = asRecord(entry); + if (item?.type === "text" && typeof item.text === "string") { + const parsed = parseResult(item.text); + if (parsed !== undefined) return parsed; + } + } + return undefined; + } + return result; +} + +function rememberApp(directory: ThreadDirectory, pid: number | undefined, app: CuaApp): CuaApp { + if (pid === undefined) return app; + const merged = { ...directory.byPid.get(pid), ...app }; + if (!directory.byPid.has(pid)) { + while (directory.byPid.size >= MAX_APPS_PER_THREAD) { + const oldest = directory.byPid.keys().next().value; + if (oldest === undefined) break; + directory.byPid.delete(oldest); + } + } + directory.byPid.set(pid, merged); + return merged; +} + +function learnFromRecord(directory: ThreadDirectory, record: Record): void { + const name = asAppName(record.app_name) ?? asAppName(record.name); + const bundleId = asBundleId(record.bundle_id); + if (!name && !bundleId) return; + rememberApp(directory, asPid(record.pid), { + ...(name ? { name } : {}), + ...(bundleId ? { bundleId } : {}), + }); +} + +/** + * Records app identities found in a tool result. `list_apps` and + * `list_windows` return arrays; `launch_app` and window-state results + * describe one app at the top level. + */ +export function rememberCuaToolResult( + threadId: ThreadId, + toolName: string, + args: unknown, + result: unknown, +): void { + const parsed = asRecord(parseResult(result)); + if (!parsed) return; + const directory = directoryFor(threadId); + for (const value of Object.values(parsed)) { + if (!Array.isArray(value)) continue; + for (const entry of value.slice(0, MAX_APPS_PER_THREAD)) { + const record = asRecord(entry); + if (record) learnFromRecord(directory, record); + } + } + learnFromRecord(directory, parsed); + const nested = asRecord(parsed.app) ?? asRecord(parsed.window); + if (nested) learnFromRecord(directory, nested); + // launch_app answers for the bundle it was asked to start. + const requestedBundleId = asBundleId(asRecord(args)?.bundle_id); + const pid = asPid(parsed.pid); + if (requestedBundleId && pid !== undefined && toolName === "launch_app") { + rememberApp(directory, pid, { bundleId: requestedBundleId }); + } +} + +function humanizeBundleId(bundleId: string): string | undefined { + const tail = bundleId.split(".").at(-1); + return tail && /^[A-Za-z]/u.test(tail) ? tail.replace(/[-_]/gu, " ") : undefined; +} + +function resolveApp( + threadId: ThreadId, + args: Record | undefined, +): CuaApp | undefined { + const directory = directories.get(threadId); + const pid = asPid(args?.pid); + const bundleId = asBundleId(args?.bundle_id); + const name = asAppName(args?.app_name) ?? asAppName(args?.app); + const known = pid !== undefined ? directory?.byPid.get(pid) : undefined; + const windowId = asWindowId(args?.window_id); + if (pid !== undefined && windowId !== undefined) { + directoryFor(threadId).lastWindow = { pid, windowId }; + } + const app: CuaApp = { + ...known, + ...(bundleId ? { bundleId } : {}), + ...(name ? { name } : {}), + }; + if (app.name || app.bundleId) { + if (directory) { + if (pid !== undefined) rememberApp(directory, pid, app); + directory.lastApp = app; + } + return app; + } + // Element tokens and session labels address a window the agent already + // resolved, so the app it last touched in this thread is the target. + return pid === undefined ? directory?.lastApp : undefined; +} + +const TOOLS_WITHOUT_APP = new Set([ + "list_apps", + "get_desktop_state", + "get_screen_size", + "get_cursor_position", + "check_permissions", + "health_report", + "check_for_update", + "install_ffmpeg", + "install_extension", + "start_session", + "end_session", + "get_session", + "get_session_state", + "list_sessions", + "escalate_session", + "get_config", + "set_config", + "get_agent_cursor_state", + "set_agent_cursor_enabled", + "set_agent_cursor_motion", + "set_agent_cursor_theme", + "clipboard_read", + "clipboard_write", + "start_recording", + "stop_recording", + "get_recording_state", + "replay_trajectory", + "get_guide", +]); + +function humanizeTool(tool: string, inProgress: boolean): string { + const words = tool.split("_").filter((word) => word.length > 0); + const verb = words[0] ?? tool; + const rest = words.slice(1).join(" "); + const progressive = inProgress + ? verb.endsWith("e") + ? `${verb.slice(0, -1)}ing` + : `${verb}ing` + : verb.endsWith("e") + ? `${verb}d` + : `${verb}ed`; + const label = `${progressive}${rest ? ` ${rest}` : ""}`; + return label.charAt(0).toUpperCase() + label.slice(1); +} + +function keyLabel(keys: unknown): string | undefined { + const list = Array.isArray(keys) ? keys : typeof keys === "string" ? [keys] : []; + const labels = list + .map((key) => (typeof key === "string" ? key.trim() : "")) + .filter((key) => key.length > 0 && key.length <= 24) + .map((key) => { + const lower = key.toLowerCase(); + if (lower === "cmd" || lower === "command" || lower === "meta") return "⌘"; + if (lower === "shift") return "⇧"; + if (lower === "alt" || lower === "option") return "⌥"; + if (lower === "ctrl" || lower === "control") return "⌃"; + if (lower === "enter" || lower === "return") return "Return"; + if (lower === "esc" || lower === "escape") return "Esc"; + return key.length === 1 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1); + }); + if (labels.length === 0 || labels.length > 4) return undefined; + return labels.join(labels.every((label) => label.length === 1) ? "" : "+"); +} + +interface TitleInput { + readonly args: Record | undefined; + readonly appName: string | undefined; + readonly inProgress: boolean; +} + +const verb = (inProgress: boolean, doing: string, done: string) => (inProgress ? doing : done); + +/** Every tool Cua Driver 0.38 exposes; the test pins this list against the server's catalogue. */ +export const CUA_TOOL_TITLES: Readonly string>> = (() => { + const withApp = (label: string, appName: string | undefined) => + appName ? `${label} in ${appName}` : label; + const inApp = (doing: string, done: string) => (input: TitleInput) => + withApp(verb(input.inProgress, doing, done), input.appName); + const onApp = (doing: string, done: string, fallback: string) => (input: TitleInput) => + input.appName + ? `${verb(input.inProgress, doing, done)} ${input.appName}` + : `${verb(input.inProgress, doing, done)} ${fallback}`; + const plain = (doing: string, done: string) => (input: TitleInput) => + verb(input.inProgress, doing, done); + const looked = (input: TitleInput) => + input.appName + ? `${verb(input.inProgress, "Looking at", "Looked at")} ${input.appName}` + : verb(input.inProgress, "Looking at the screen", "Looked at the screen"); + const configured = plain("Configuring computer use", "Configured computer use"); + return { + list_apps: plain("Listing apps", "Listed apps"), + list_windows: inApp("Listing windows", "Listed windows"), + launch_app: onApp("Launching", "Launched", "app"), + kill_app: onApp("Quitting", "Quit", "app"), + bring_to_front: onApp("Focusing", "Focused", "window"), + get_window_state: looked, + get_desktop_state: looked, + get_accessibility_tree: looked, + get_browser_state: looked, + verify_state: looked, + get_screen_size: looked, + get_cursor_position: looked, + debug_window_info: looked, + click: inApp("Clicking", "Clicked"), + double_click: inApp("Double-clicking", "Double-clicked"), + right_click: inApp("Right-clicking", "Right-clicked"), + drag: inApp("Dragging", "Dragged"), + mouse_drag: inApp("Dragging", "Dragged"), + parallel_mouse_drag: inApp("Dragging", "Dragged"), + mouse_button_down: inApp("Pressing mouse button", "Pressed mouse button"), + mouse_button_up: inApp("Releasing mouse button", "Released mouse button"), + move_cursor: inApp("Moving cursor", "Moved cursor"), + scroll: (input) => { + const direction = asText(input.args?.direction, 16)?.toLowerCase(); + return withApp( + `${verb(input.inProgress, "Scrolling", "Scrolled")}${direction ? ` ${direction}` : ""}`, + input.appName, + ); + }, + type_text: inApp("Typing text", "Typed text"), + browser_type: inApp("Typing text", "Typed text"), + set_value: inApp("Setting value", "Set value"), + press_key: (input) => + withApp( + `${verb(input.inProgress, "Pressing", "Pressed")} ${keyLabel(input.args?.keys ?? input.args?.key) ?? "key"}`, + input.appName, + ), + hotkey: (input) => + withApp( + `${verb(input.inProgress, "Pressing", "Pressed")} ${keyLabel(input.args?.keys ?? input.args?.key) ?? "shortcut"}`, + input.appName, + ), + invoke_menu: inApp("Choosing menu item", "Chose menu item"), + set_window_frame: inApp("Resizing window", "Resized window"), + zoom: inApp("Zooming", "Zoomed"), + page: inApp("Reading page", "Read page"), + browser_navigate: (input) => + withApp( + `${verb(input.inProgress, "Opening", "Opened")} ${asText(input.args?.url, 200) ?? "page"}`, + input.appName, + ), + browser_click: inApp("Clicking", "Clicked"), + browser_pointer: inApp("Clicking", "Clicked"), + browser_prepare: inApp("Preparing browser", "Prepared browser"), + browser_dialog: inApp("Answering dialog", "Answered dialog"), + browser_download: inApp("Downloading file", "Downloaded file"), + browser_set_input_files: inApp("Attaching files", "Attached files"), + browser_select: inApp("Choosing option", "Chose option"), + clipboard_read: plain("Reading clipboard", "Read clipboard"), + clipboard_write: plain("Writing clipboard", "Wrote clipboard"), + start_recording: plain("Starting recording", "Started recording"), + stop_recording: plain("Stopping recording", "Stopped recording"), + get_recording_state: plain("Checking recording", "Checked recording"), + replay_trajectory: plain("Replaying actions", "Replayed actions"), + run_steps: inApp("Running steps", "Ran steps"), + run_script: inApp("Running script", "Ran script"), + get_guide: plain("Reading guide", "Read guide"), + check_permissions: plain("Checking permissions", "Checked permissions"), + parse_visual_regions: looked, + install_extension: configured, + start_session: plain("Starting computer use session", "Started computer use session"), + end_session: plain("Ending computer use session", "Ended computer use session"), + escalate_session: plain("Escalating computer use session", "Escalated computer use session"), + get_session: configured, + get_session_state: configured, + list_sessions: configured, + get_config: configured, + set_config: configured, + get_agent_cursor_state: configured, + set_agent_cursor_enabled: configured, + set_agent_cursor_motion: configured, + set_agent_cursor_theme: configured, + health_report: configured, + check_for_update: configured, + install_ffmpeg: configured, + }; +})(); + +function cuaToolTitle( + tool: string, + args: Record | undefined, + appName: string | undefined, + inProgress: boolean, +): string { + const known = CUA_TOOL_TITLES[tool]; + if (known) return known({ args, appName, inProgress }); + const label = humanizeTool(tool, inProgress); + return appName ? `${label} in ${appName}` : label; +} + +// run_steps names its window at the top level or on each step; the last step that names one wins. +function runStepsTarget( + args: Record | undefined, +): Record | undefined { + if (!args || args.pid !== undefined || !Array.isArray(args.steps)) return args; + for (const step of args.steps.toReversed()) { + const record = asRecord(step); + if (record?.pid === undefined) continue; + return { + ...args, + pid: record.pid, + ...(record.window_id === undefined ? {} : { window_id: record.window_id }), + }; + } + return args; +} + +function nativeApp(app: CuaApp): ToolActivityNativeAppReference | undefined { + if (app.bundleId) return { _tag: "app-id", appId: app.bundleId }; + if (app.name) return { _tag: "display-name", displayName: app.name }; + return undefined; +} + +/** + * Presentation for one Cua tool call. `rawToolName` may be a provider tool + * name or an ACP title; returns undefined for anything that is not Cua. + */ +export function cuaToolPresentation(input: { + readonly threadId: ThreadId; + readonly rawToolName: string | undefined; + readonly args: unknown; + readonly status: "inProgress" | "completed" | "failed"; +}): CuaToolPresentation | undefined { + const tool = parseCuaToolName(input.rawToolName); + if (!tool) return undefined; + const args = asRecord(input.args); + const targetArgs = tool === "run_steps" ? runStepsTarget(args) : args; + const app = TOOLS_WITHOUT_APP.has(tool) ? undefined : resolveApp(input.threadId, targetArgs); + const appName = app?.name ?? (app?.bundleId ? humanizeBundleId(app.bundleId) : undefined); + const reference = app ? nativeApp(app) : undefined; + const icon = reference ? ({ _tag: "native-app", app: reference } as const) : undefined; + return { + title: cuaToolTitle(tool, args, appName, input.status === "inProgress"), + toolSurface: "computer", + ...(icon ? { toolIcon: icon } : {}), + toolSource: { + key: app?.bundleId + ? `native-app:${app.bundleId.toLowerCase()}` + : appName + ? `native-app-name:${appName.toLowerCase().replace(/[^a-z0-9]+/gu, "-")}` + : "computer-use", + name: appName ?? "Computer Use", + kind: "computer", + ...(icon ? { icon } : {}), + }, + }; +} diff --git a/packages/provider-core/src/server/mcpToolPresentation.test.ts b/packages/provider-core/src/server/mcpToolPresentation.test.ts index 832d66f0a055f..edb6310fca4cf 100644 --- a/packages/provider-core/src/server/mcpToolPresentation.test.ts +++ b/packages/provider-core/src/server/mcpToolPresentation.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from "@effect/vitest"; -import { mcpToolPresentation } from "./mcpToolPresentation.ts"; +import { ThreadId } from "@t3tools/contracts"; + +import { clearCuaToolContext } from "./cuaToolPresentation.ts"; +import { cuaCallContext, mcpToolPresentation } from "./mcpToolPresentation.ts"; describe("mcpToolPresentation", () => { it.each([ @@ -20,4 +23,40 @@ describe("mcpToolPresentation", () => { toolSource: { key: "mcp:weather", name: "weather", kind: "integration" }, }); }); + + it("presents Cua Driver calls from any provider as computer use in the app they drive", () => { + const threadId = ThreadId.make("thread-mcp-cua"); + clearCuaToolContext(threadId); + // An earlier list_apps result teaches the thread which app owns pid 512. + cuaCallContext({ + serverName: "cua-driver", + toolName: "list_apps", + threadId, + status: "completed", + args: {}, + result: { apps: [{ pid: 512, name: "Safari", bundle_id: "com.apple.Safari" }] }, + }); + for (const [serverName, toolName] of [ + ["cua-driver", "click"], + ["cua_driver", "click"], + [undefined, "mcp__cua-driver__click"], + ] as const) { + const presentation = mcpToolPresentation({ + serverName, + toolName, + ...cuaCallContext({ + serverName: serverName ?? "cua-driver", + toolName: "click", + threadId, + status: "running", + args: { pid: 512, window_id: 3 }, + }), + }); + expect(presentation).toMatchObject({ + title: "Clicking in Safari", + toolSurface: "computer", + toolSource: { key: "native-app:com.apple.safari", kind: "computer" }, + }); + } + }); }); diff --git a/packages/provider-core/src/server/mcpToolPresentation.ts b/packages/provider-core/src/server/mcpToolPresentation.ts index c8f4dbc0eb11f..494480e1a3ee3 100644 --- a/packages/provider-core/src/server/mcpToolPresentation.ts +++ b/packages/provider-core/src/server/mcpToolPresentation.ts @@ -1,6 +1,17 @@ -import type { ToolActivityIcon, ToolActivitySource } from "@t3tools/contracts"; +import type { + ThreadId, + ToolActivityIcon, + ToolActivitySource, + ToolActivitySurface, +} from "@t3tools/contracts"; import { resolveT3McpToolDefinition } from "@t3tools/shared/t3McpToolPresentation"; +import { + cuaToolPresentation, + isCuaServerName, + rememberCuaToolResult, +} from "./cuaToolPresentation.ts"; + export function normalizeMcpText(value: unknown, maxLength = 160): string | undefined { if (typeof value !== "string") return undefined; const text = value.trim().replace(/\s+/gu, " "); @@ -27,8 +38,17 @@ export function mcpToolPresentation(input: { readonly iconUrl?: unknown; readonly iconUrlDark?: unknown; readonly source?: unknown; + /** + * The app thread, so Cua Driver calls can name the app the agent drives: + * Cua addresses apps by pid, which earlier calls in the thread resolved. + */ + readonly threadId?: ThreadId | null; + /** The call's arguments, which carry that pid or app. */ + readonly args?: unknown; + readonly status?: "inProgress" | "completed" | "failed"; }): { readonly title?: string; + readonly toolSurface?: ToolActivitySurface; readonly toolIcon?: ToolActivityIcon; readonly toolSource?: ToolActivitySource; } { @@ -39,6 +59,16 @@ export function mcpToolPresentation(input: { const server = normalizeMcpText(input.serverName ?? qualified?.[1] ?? input.serverDisplayName); const tool = normalizeMcpText(qualified?.[2] ?? input.toolName); if (server && tool && resolveT3McpToolDefinition(`${server}.${tool}`)) return {}; + // Cua Driver calls read as computer use in every provider, like Codex's own. + if (server && tool && isCuaServerName(server) && input.threadId) { + const cua = cuaToolPresentation({ + threadId: input.threadId, + rawToolName: `mcp__cua-driver__${tool}`, + args: input.args, + status: input.status ?? "completed", + }); + if (cua) return cua; + } const title = normalizeMcpText(input.title) ?? (server && tool ? normalizeMcpText(tool.replace(/[_-]+/gu, " ")) : undefined); @@ -68,3 +98,33 @@ export function mcpToolPresentation(input: { }, }; } + +/** + * The Cua Driver context for an MCP item: its thread, input, and status. A + * completed call also teaches the thread which app each pid is, so later + * calls can name it. + */ +export function cuaCallContext(input: { + readonly serverName: string | undefined; + readonly toolName: string | undefined; + readonly threadId: ThreadId | null; + readonly status: string; + readonly args: unknown; + readonly result?: unknown; +}): { + readonly threadId?: ThreadId; + readonly args?: unknown; + readonly status?: "inProgress" | "completed" | "failed"; +} { + if (!isCuaServerName(input.serverName) || !input.toolName || input.threadId === null) return {}; + const status = + input.status === "completed" + ? ("completed" as const) + : input.status === "running" || input.status === "pending" + ? ("inProgress" as const) + : ("failed" as const); + if (status === "completed" && input.result !== undefined) { + rememberCuaToolResult(input.threadId, input.toolName, input.args, input.result); + } + return { threadId: input.threadId, args: input.args, status }; +} diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 6b27e63ed514f..272f0ba0552dc 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -44,7 +44,10 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; -import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; +import { + cuaCallContext, + mcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { CursorTransportFailure } from "./transportFailure.ts"; @@ -1490,6 +1493,14 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ? mcpToolPresentation({ serverName: toolCall.args.providerIdentifier, toolName: toolCall.args.toolName, + ...cuaCallContext({ + serverName: toolCall.args.providerIdentifier, + toolName: toolCall.args.toolName, + threadId: base.threadId, + status: base.status, + args: toolCall.args.args, + result: cursorToolOutput(toolCall), + }), }) : {}), toolName: cursorToolName(toolCall), diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 7a80788657d6b..0e30cdc969e97 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -55,7 +55,10 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; -import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; +import { + cuaCallContext, + mcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; @@ -1823,6 +1826,16 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function serverName, toolName: part.tool.slice(serverName.replace(/[^a-zA-Z0-9_-]/g, "_").length + 1), title: toolTitle(part) === part.tool ? undefined : toolTitle(part), + ...cuaCallContext({ + serverName, + toolName: part.tool.slice( + serverName.replace(/[^a-zA-Z0-9_-]/g, "_").length + 1, + ), + threadId: base.threadId, + status: base.status, + args: input, + result: output, + }), }); const files = part.state.status === "completed" diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 98451922bfae4..30336cafb3b66 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -71,6 +71,10 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; +import { + cuaCallContext, + mcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; @@ -1445,7 +1449,34 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr : undefined, }, ); - yield* emit({ type: "turn_item.updated", driver, turnItem }); + // OpenCode names the thread's Cua tools `cua-driver-_`. + const cuaPrefix = state.cua === undefined ? undefined : `${state.cua.name}_`; + const cuaTool = + cuaPrefix !== undefined && tool.name.startsWith(cuaPrefix) + ? tool.name.slice(cuaPrefix.length) + : undefined; + yield* emit({ + type: "turn_item.updated", + driver, + turnItem: + cuaTool === undefined || turnItem.type !== "dynamic_tool" + ? turnItem + : { + ...turnItem, + ...mcpToolPresentation({ + serverName: McpProviderSession.CUA_MCP_SERVER_NAME, + toolName: cuaTool, + ...cuaCallContext({ + serverName: McpProviderSession.CUA_MCP_SERVER_NAME, + toolName: cuaTool, + threadId: turnItem.threadId, + status: turnItem.status, + args: tool.input, + result: result?.output, + }), + }), + }, + }); if (status === "running") return; // A script that returns the reference already renders through its own item. const returnedPage = diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 313b7f030cd45..3738b1d75e9f9 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -46,7 +46,10 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt"; -import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; +import { + cuaCallContext, + mcpToolPresentation, +} from "@t3tools/provider-core/server/mcpToolPresentation"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { parsePiCompactCommand, type PiCompactCommand } from "./commands.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; @@ -1458,7 +1461,17 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...shared, title: toolName, type: "dynamic_tool", - ...mcpToolPresentation({ toolName }), + ...mcpToolPresentation({ + toolName, + ...cuaCallContext({ + serverName: /^mcp__(.+?)__/u.exec(toolName)?.[1], + toolName: /^mcp__.+?__(.+)$/u.exec(toolName)?.[1], + threadId: shared.threadId, + status: shared.status, + args: args ?? {}, + result: resultRecord, + }), + }), toolName, input: args ?? {}, ...(output === undefined ? {} : { output }),